You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
985 lines
40 KiB
985 lines
40 KiB
<?php
|
|
|
|
namespace App\Service\v3\Implementations;
|
|
|
|
use App\Commons\Log;
|
|
use App\Constants\v3\ErrorCode;
|
|
use App\Constants\v3\LogLabel;
|
|
use App\Constants\v3\OrderState;
|
|
use App\Constants\v3\OrderType;
|
|
use App\Constants\v3\Payment;
|
|
use App\Constants\v3\Shipping;
|
|
use App\Constants\v3\SsdbKeys;
|
|
use App\Exception\ErrorCodeException;
|
|
use App\Model\v3\Coupon;
|
|
use App\Model\v3\Employees;
|
|
use App\Model\v3\Goods;
|
|
use App\Model\v3\GoodsActivity;
|
|
use App\Model\v3\Order;
|
|
use App\Model\v3\OrderGoods;
|
|
use App\Model\v3\OrderMain;
|
|
use App\Model\v3\OrderSalesStatistic;
|
|
use App\Model\v3\SfExpressOrder;
|
|
use App\Model\v3\ShoppingCart;
|
|
use App\Model\v3\Store;
|
|
use App\Model\v3\User;
|
|
use App\Model\v3\UserAddress;
|
|
use App\Service\v3\Interfaces\BadgeServiceInterface;
|
|
use App\Service\v3\Interfaces\CouponRecServiceInterface;
|
|
use App\Service\v3\Interfaces\CouponServiceInterface;
|
|
use App\Service\v3\Interfaces\GoodsActivityServiceInterface;
|
|
use App\Service\v3\Interfaces\GoodsInventoryServiceInterface;
|
|
use App\Service\v3\Interfaces\GoodsServiceInterface;
|
|
use App\Service\v3\Interfaces\InitialDeliveryServiceInterface;
|
|
use App\Service\v3\Interfaces\MiniprogramServiceInterface;
|
|
use App\Service\v3\Interfaces\PaymentServiceInterface;
|
|
use App\Service\v3\Interfaces\ShopCartUpdateServiceInterface;
|
|
use App\Service\v3\Interfaces\UserAddressServiceInterface;
|
|
use App\Service\v3\SfExpress;
|
|
use App\TaskWorker\SSDBTask;
|
|
use Exception;
|
|
use Hyperf\Database\Model\Model;
|
|
use Hyperf\DbConnection\Db;
|
|
/** @var Inject 注解使用 */
|
|
use Hyperf\Di\Annotation\Inject;
|
|
use App\Service\v3\Interfaces\OrderOnlineServiceInterface;
|
|
use Hyperf\Redis\Redis;
|
|
use Hyperf\Snowflake\IdGeneratorInterface;
|
|
use Hyperf\Utils\ApplicationContext;
|
|
|
|
class OrderOnlineService implements OrderOnlineServiceInterface
|
|
{
|
|
|
|
/**
|
|
* @Inject
|
|
* @var Log
|
|
*/
|
|
protected $log;
|
|
|
|
/**
|
|
* @Inject
|
|
* @var UserAddressServiceInterface
|
|
*/
|
|
protected $userAddressService;
|
|
|
|
/**
|
|
* @Inject
|
|
* @var CouponRecServiceInterface
|
|
*/
|
|
protected $couponRecService;
|
|
|
|
/**
|
|
* @Inject
|
|
* @var CouponServiceInterface
|
|
*/
|
|
protected $couponService;
|
|
|
|
/**
|
|
* @Inject
|
|
* @var GoodsActivityServiceInterface
|
|
*/
|
|
protected $goodsActivityService;
|
|
|
|
/**
|
|
* @Inject
|
|
* @var GoodsServiceInterface
|
|
*/
|
|
protected $goodsService;
|
|
|
|
/**
|
|
* @Inject
|
|
* @var PaymentServiceInterface
|
|
*/
|
|
protected $paymentService;
|
|
|
|
/**
|
|
* @Inject
|
|
* @var ShopCartUpdateServiceInterface
|
|
*/
|
|
protected $shopCartUpdateService;
|
|
|
|
/**
|
|
* @Inject
|
|
* @var BadgeServiceInterface
|
|
*/
|
|
protected $badgeService;
|
|
|
|
/**
|
|
* @Inject
|
|
* @var InitialDeliveryServiceInterface
|
|
*/
|
|
protected $initialDeliveryService;
|
|
|
|
/**
|
|
* @Inject
|
|
* @var GoodsInventoryServiceInterface
|
|
*/
|
|
protected $goodsInventoryService;
|
|
|
|
/**
|
|
* @Inject
|
|
* @var MiniprogramServiceInterface
|
|
*/
|
|
protected $miniprogramService;
|
|
|
|
/**
|
|
* 下单
|
|
* @param $marketId
|
|
* @param $userId
|
|
* @param $userAddrId
|
|
* @param $storeList
|
|
* @param $totalMoney
|
|
* @param string $deliveryTimeNote
|
|
* @param int $serviceMoney
|
|
* @param null $receiveCouponIds
|
|
* @param string $plat
|
|
* @param int $selfTake
|
|
* @return array[]
|
|
*/
|
|
public function do($marketId, $userId, $userAddrId, $storeList, $totalMoney, $deliveryTimeNote='尽快送达', $serviceMoney=0, $receiveCouponIds=null, $plat='', $selfTake=0){
|
|
// $redis = ApplicationContext::getContainer()->get(Redis::class);
|
|
$isCacheInventory = false;
|
|
$carts = [];
|
|
Db::beginTransaction();
|
|
try {
|
|
|
|
// 获取分布式全局ID
|
|
$generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
|
|
$globalOrderId = $generator->generate();
|
|
|
|
$mainTable = ApplicationContext::getContainer()->get(OrderMain::class)->getTable();
|
|
$childTable = ApplicationContext::getContainer()->get(Order::class)->getTable();
|
|
|
|
$currentTime = time();
|
|
bcscale(6);
|
|
|
|
$userAddr = (object)[];
|
|
$deliveryAmount = 0;
|
|
$deliveryDistance = 0;
|
|
$shippingType = Shipping::TYPE_SELF_TAKE;
|
|
|
|
// 如果非自提,则通过用户地址计算相关数据和费用
|
|
if ($selfTake != 1) {
|
|
// 用户收货地址
|
|
// 获取配送费用
|
|
$shopCartIds = join(',', array_column($storeList, 'cart_ids'));
|
|
$userAddrAndDPrice = $this->userAddressService->getAddressAndDistributionPrice($userAddrId, $marketId, $shopCartIds, $deliveryTimeNote);
|
|
$userAddr = $userAddrAndDPrice['address']['address'];
|
|
$deliveryAmount = $userAddrAndDPrice['distribution_price'];
|
|
$deliveryDistance = $userAddrAndDPrice['delivery_distance'];
|
|
$shippingType = Shipping::TYPE_LANZU;
|
|
} else {
|
|
|
|
$user = User::query()->find($userId);
|
|
$userDefaultAddr = UserAddress::query()->where(['user_id' => $userId])->orderBy('is_default', 'desc')->first();
|
|
$userAddr->tel = $user->tel ?? '';
|
|
$userAddr->address = $userDefaultAddr->address ?? '';
|
|
$userAddr->user_name = $user->nick_name ?? $userDefaultAddr->user_name;
|
|
$userAddr->lat = $userDefaultAddr->lat ?? '';
|
|
$userAddr->lng = $userDefaultAddr->lng ?? '';
|
|
|
|
// $market = Market::query()->find($marketId);
|
|
// $userAddr->tel = $market->tel;
|
|
// $userAddr->address = $market->address ;
|
|
// $userAddr->user_name = $market->name;
|
|
// $userAddr->lat = $market->lat;
|
|
// $userAddr->lng = $market->lng;
|
|
}
|
|
|
|
// 处理购物车数据,计算订单金额、子订单数据处理等
|
|
$totalAmount = 0; # 实付金额
|
|
$orderAmount = 0; # 订单金额
|
|
$dataMain = []; # 主订单
|
|
$dataChildren = []; # 子订单
|
|
$dataOrderGoods = []; # 订单商品
|
|
$storeTypeIds = []; # 订单中的商户类型,用于校验红包
|
|
$activityGoodsIds = []; # 活动商品IDs
|
|
$shopcartIds = [];
|
|
|
|
// 获取当前用户的商户信息,主要用于限制当前商户购买自己或本市场的活动商品
|
|
$userStore = Store::query()
|
|
->withoutGlobalScope('normal')
|
|
->withTrashed()
|
|
->where(['user_id' => $userId])->orWhere(['admin_id' => $userId])
|
|
->first();
|
|
|
|
foreach ($storeList as $key => &$storeItem) {
|
|
|
|
$storeId = $storeItem->store_id;
|
|
|
|
// 子订单金额
|
|
$subAmount = 0;
|
|
|
|
// 店铺信息
|
|
$store = Store::query()->where(['id' => $storeId])->first();
|
|
|
|
// 禁止店铺自己下自己的单
|
|
// if (in_array($userId, [$store->user_id, $store->admin_id])) {
|
|
// throw new ErrorCodeException(ErrorCode::ORDER_ONLINE_LIMIT_STORE_BUY_SELF, '', ['store' => json_encode($store), 'user_id' => $userId, 'store_item' => $storeItem]);
|
|
// }
|
|
|
|
// 店铺分类
|
|
$storeType = $store->category_id;
|
|
$storeTypeIds[] = (string)$storeType;
|
|
// 店铺今天的订单数
|
|
$count = Order::query()
|
|
->join($mainTable, ''.$mainTable.'.global_order_id', '=', ''.$childTable.'.order_main_id')
|
|
->where([''.$childTable.'.store_id' => $storeId, ''.$mainTable.'.type' => OrderType::ONLINE])
|
|
->whereBetween(''.$childTable.'.created_at', [strtotime(date('Y-m-d 00:00:00')), strtotime(date('Y-m-d 23:59:59'))])
|
|
->count();
|
|
|
|
// 用户购物车数据
|
|
$cartIds = explode(',', $storeItem->cart_ids);
|
|
$shopcartIds = array_merge($shopcartIds, $cartIds);
|
|
$carts = ShoppingCart::query()->whereIn('id', $cartIds)->where(['market_id' => $marketId, 'user_id' => $userId])->get();
|
|
foreach ($carts as $k => &$cart) {
|
|
// 查个商品,做商品有效的判断检查
|
|
$goods = [];
|
|
if ($cart->activity_type == 1) {
|
|
$goods = Goods::query()->lockForUpdate()->with('store')->find($cart->goods_id);
|
|
if (empty($goods)) {
|
|
throw new ErrorCodeException(ErrorCode::GOODS_NOT_EXISTS, '['.$cart->goods_id.']');
|
|
}
|
|
$check = $this->goodsService->check($goods, $cart->num);
|
|
if (true !== $check) {
|
|
throw new ErrorCodeException($check, '['.$goods->name.']');
|
|
}
|
|
} elseif ($cart->activity_type == 2) {
|
|
|
|
$goods = GoodsActivity::query()->lockForUpdate()->with('store')->find($cart->goods_id);
|
|
if (empty($goods)) {
|
|
throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_NOT_EXISTS, '['.$cart->goods_id.']');
|
|
}
|
|
|
|
// 商户不能购买自己市场或自己店铺的活动商品
|
|
if (!is_null($userStore)) { // 当前用户是商户
|
|
if (in_array($userStore->market_id, json_decode($goods->market_ids, true)) || $userStore->id == $goods->store_id) { // 如果活动商品是当前市场或者自己店铺的,滚粗不让买
|
|
throw new ErrorCodeException(ErrorCode::ORDER_ONLINE_LIMIT_STORE_BUY_SELF, '', [
|
|
'user_store' => json_encode($userStore),
|
|
'store' => json_encode($store),
|
|
'user_id' => $userId,
|
|
'store_item' => $storeItem,
|
|
'ac_goods' => json_encode($goods)
|
|
]);
|
|
}
|
|
}
|
|
|
|
// TODO 校验当前用户今天是否超过了购买活动秒杀商品的(特定价格)的订单笔数
|
|
if (!$this->checkIfBuyFlashGoodsToday($userId)) {
|
|
throw new ErrorCodeException(
|
|
ErrorCode::ORDER_ONLINE_LIMIT_BUY_COUNT,
|
|
'['.env('LIMIT_BUY_COUNT').']',
|
|
['params' => $userId, 'limit_prices' => env('LIMIT_BUY_COUNT_GOODS_PRICES')]
|
|
);
|
|
}
|
|
|
|
$check = $this->goodsActivityService->check($goods, $cart->num, $userId);
|
|
if (true !== $check) {
|
|
throw new ErrorCodeException($check, '['.$goods->name.']');
|
|
}
|
|
|
|
}
|
|
|
|
// 压redis库存
|
|
// redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
|
|
// $inventoryKey = 'goods_inventory_sold_'.$cart->activity_type.'_'.$cart->goods_id; // 拼接activity_type和goods_id
|
|
// if (!$redis->exists($inventoryKey)) {
|
|
// $redis->set($inventoryKey, $cart->num);
|
|
// } else {
|
|
// $redis->incrBy($inventoryKey, intval($cart->num));
|
|
// }
|
|
$this->goodsInventoryService->doSold($cart->activity_type, $cart->goods_id, $cart->num);
|
|
$isCacheInventory = true;
|
|
|
|
if ($cart->activity_type == 2) {
|
|
$activityGoodsIds[] = $cart->goods_id;
|
|
}
|
|
|
|
// 算金额
|
|
$goodsAmount = bcmul((string)$goods->price, (string)$cart->num); # 当前商品的金额
|
|
$subAmount = bcadd((string)$subAmount, (string)$goodsAmount); # 当前店铺子订单的金额
|
|
|
|
// 订单商品数据
|
|
$dataOrderGoods[$storeId][] = [
|
|
'order_id' => 0,
|
|
'goods_id' => $cart->goods_id,
|
|
'activity_type' => $cart->activity_type,
|
|
'number' => $cart->num,
|
|
'price' => $goods->price,
|
|
'original_price' => $goods->original_price,
|
|
'vip_price' => $goods->vip_price,
|
|
'name' => $goods->name ?: '',
|
|
'goods_unit' => $goods->goods_unit ?: '',
|
|
'cover_img' => $goods->cover_img ?: '',
|
|
'spec' => json_encode($goods->spec),
|
|
'weight' => $goods->weight ?: 0, // add:2022-04-17 增加商品重量
|
|
];
|
|
}
|
|
|
|
// 子订单数据
|
|
$dataChildren[] = [
|
|
'order_main_id' => 0,
|
|
'user_id' => $userId,
|
|
'store_id' => $storeId,
|
|
'money' => bcadd((string)$subAmount, '0', 2),
|
|
'oid' => $count + 1,
|
|
'order_num' => date('YmdHis').mt_rand(1000, 9999),
|
|
'note' => $storeItem->note
|
|
];
|
|
|
|
// 订单金额
|
|
$orderAmount = bcadd((string)$orderAmount, (string)$subAmount);
|
|
}
|
|
|
|
// 优惠券数据,当前订单可用个优惠券
|
|
$couponRecs = $this->couponRecService->allForOnlineOrderAvailable($userId, $marketId ,$shopcartIds);
|
|
$canRealUseCoupons = $couponRecs['available'];
|
|
$canRealUseCouponRecIds = array_values(array_column($canRealUseCoupons, 'id'));
|
|
if (!empty(array_diff($receiveCouponIds, $canRealUseCouponRecIds))) {
|
|
$this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => '订单中有不能使用优惠券的商品', 'data' => json_encode([
|
|
'all_user_coupons_rec' => json_encode($couponRecs),
|
|
'can_real_user_coupons' => json_encode($canRealUseCoupons),
|
|
'receive_coupon_ids' => json_encode($canRealUseCouponRecIds),
|
|
])]);
|
|
throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_CANNOT_USE_COUPON);
|
|
}
|
|
|
|
// 优惠券的使用
|
|
$couponMoney = 0;
|
|
if (!empty($receiveCouponIds)) {
|
|
|
|
// 计算红包折扣金额
|
|
foreach ($canRealUseCoupons as $key => &$coupon) {
|
|
|
|
if (!in_array($coupon->id, $receiveCouponIds)) {
|
|
unset($canRealUseCoupons[$key]);
|
|
continue;
|
|
}
|
|
|
|
if ($coupon->coupon->discount_type == Coupon::DISCOUNT_TYPE_CASH) {
|
|
$couponMoney = bcadd($couponMoney, $coupon->coupon->discounts, 2);
|
|
} elseif ($coupon->coupon->discount_type == Coupon::DISCOUNT_TYPE_RATE) {
|
|
$discountRate = bcdiv($coupon->coupon->discounts,10);
|
|
$discountMoney = bcmul($orderAmount, $discountRate, 2);
|
|
$couponMoney = bcsub($orderAmount, $discountMoney, 2);
|
|
// $discountRate = bcdiv($coupon->coupon->discounts,10);
|
|
// $discountRate = bcsub(1,$discountRate);
|
|
// $discountMoney = bcmul($orderAmount, $discountRate);
|
|
// $couponMoney = bcadd($couponMoney, $discountMoney, 2);
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
$orderAmount = bcadd((string)$orderAmount, '0', 2);
|
|
$totalAmount = bcadd((string)$totalAmount, (string)$orderAmount);
|
|
|
|
if ($shippingType != Shipping::TYPE_SELF_TAKE) {
|
|
$totalAmount = bcadd((string)$totalAmount, (string)$deliveryAmount);
|
|
}
|
|
|
|
$totalAmount = bcadd((string)$totalAmount, (string)$serviceMoney);
|
|
$totalAmount = bcsub((string)$totalAmount, (string)$couponMoney, 2);
|
|
|
|
// 校验订单总金额
|
|
if ($totalAmount != $totalMoney) {
|
|
throw new ErrorCodeException(
|
|
ErrorCode::ORDER_TOTAL_AMOUNT_ERROR,
|
|
'',
|
|
[
|
|
'total_amount' => $totalAmount,
|
|
'total_money' => $totalMoney,
|
|
'deliveryAmount' => $deliveryAmount,
|
|
'$orderAmount' => $orderAmount,
|
|
'serviceMoney' => $serviceMoney,
|
|
'couponMoney' => $couponMoney,
|
|
]
|
|
);
|
|
}
|
|
|
|
// 校验订单总金额是否满足起送
|
|
$initDeliveryAmount = $this->initialDeliveryService->get();
|
|
if ($orderAmount < $initDeliveryAmount) {
|
|
throw new ErrorCodeException(ErrorCode::ORDER_NOT_ENOUGH_INITIAL_DELIVERY, "[{$initDeliveryAmount}]");
|
|
}
|
|
|
|
$dataMain = [
|
|
'shipping_type' => $shippingType,
|
|
'market_id' => $marketId,
|
|
'order_num' => $globalOrderId,
|
|
'global_order_id' => $globalOrderId,
|
|
'user_id' => $userId,
|
|
'type' => OrderType::ONLINE,
|
|
'money' => $totalAmount,
|
|
'total_money' => $orderAmount,
|
|
'services_money' => $serviceMoney,
|
|
'coupon_money' => $couponMoney,
|
|
'delivery_money' => $deliveryAmount,
|
|
'delivery_distance' => $deliveryDistance,
|
|
'state' => OrderState::UNPAID,
|
|
'tel' => $userAddr->tel ?? '',
|
|
'address' => ($userAddr->address ?? '').($userAddr->doorplate ?? ''),
|
|
'lat' => $userAddr->lat ?? '',
|
|
'lng' => $userAddr->lng ?? '',
|
|
'name' => $userAddr->user_name ?? '',
|
|
'plat' => $plat,
|
|
'delivery_time_note' => $deliveryTimeNote
|
|
];
|
|
|
|
// 生成主订单
|
|
$orderMain = OrderMain::query()->create($dataMain);
|
|
|
|
// 处理子订单
|
|
foreach ($dataChildren as $key => &$child) {
|
|
$child['order_main_id'] = $globalOrderId;
|
|
$orderChild = Order::query()->create($child);
|
|
$orderChildId = $orderChild->id;
|
|
|
|
foreach ($dataOrderGoods[$child['store_id']] as $k => &$orderGoods) {
|
|
$orderGoods['order_id'] = $orderChildId;
|
|
$orderGoods['created_at'] = $currentTime;
|
|
$orderGoods['updated_at'] = $currentTime;
|
|
}
|
|
OrderGoods::query()->insert($dataOrderGoods[$child['store_id']]);
|
|
}
|
|
|
|
// 判断是否有购买多个特价商品
|
|
$check = $this->goodsActivityService->checkOrderActivityCount($activityGoodsIds);
|
|
if($check !== true){
|
|
$this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => '同一订单中有活动商品不可同时购买多款', 'data' => json_encode($dataOrderGoods)]);
|
|
throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_RESTRICT_LIMIT, '[商品:' . $check . ']');
|
|
}
|
|
|
|
// 订单成功,做一些处理
|
|
// 活动商品购买记录
|
|
foreach ($dataOrderGoods as $key => &$goods) {
|
|
foreach ($goods as $k => &$goodsItem) {
|
|
if ($goodsItem['activity_type'] == 2) {
|
|
$this->goodsActivityService->cacheRecord($goodsItem['goods_id'], $goodsItem['number'], $userId);
|
|
}
|
|
}
|
|
}
|
|
|
|
Db::commit();
|
|
|
|
if (!empty($receiveCouponIds)) {
|
|
$this->couponService->orderUseCoupons($globalOrderId, $canRealUseCoupons);
|
|
}
|
|
|
|
// 清除购物车
|
|
$this->shopCartUpdateService->doClear($userId, $marketId, $shopcartIds);
|
|
|
|
// 记录badge
|
|
$this->badgeService->doByOrder($userId, array_values(array_column($dataChildren, 'store_id')), $orderMain->global_order_id, OrderState::UNPAID);
|
|
|
|
// 支付
|
|
return $this->paymentService->do($globalOrderId, $totalAmount, $userId, config('wechat.notify_url.online'));
|
|
} catch (Exception $e) {
|
|
Db::rollBack();
|
|
|
|
if ($isCacheInventory) {
|
|
// 释redis库存
|
|
foreach ($carts as $k => &$cart) {
|
|
// // 拼接activity_type和goods_id
|
|
// $inventoryKey = 'goods_inventory_sold_'.$cart->activity_type.'_'.$cart->goods_id;
|
|
// // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
|
|
// if (!$redis->exists($inventoryKey)) {
|
|
// $redis->set($inventoryKey, 0);
|
|
// } else {
|
|
// $redis->decrBy($inventoryKey, intval($cart->num));
|
|
// }
|
|
$this->goodsInventoryService->undoSold($cart->activity_type, $cart->goods_id, $cart->num);
|
|
}
|
|
}
|
|
$this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => $e->getMessage()]);
|
|
|
|
$message = '';
|
|
if ($e instanceof ErrorCodeException) {
|
|
$message = $e->getMessage();
|
|
}
|
|
throw new ErrorCodeException(ErrorCode::ORDER_ONLINE_FAIL, $message);
|
|
}
|
|
}
|
|
|
|
public function check($globalOrderId, $userId, $state): Model
|
|
{
|
|
$builder = OrderMain::query()
|
|
->where(['global_order_id' => $globalOrderId, 'user_id' => $userId]);
|
|
|
|
if (is_array($state)) {
|
|
$builder = $builder->whereIn('state', $state);
|
|
} else {
|
|
$builder = $builder->where(['state' => $state]);
|
|
}
|
|
$orderMain = $builder->first();
|
|
if (empty($orderMain)) {
|
|
throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
|
|
}
|
|
|
|
return $orderMain;
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function undo($globalOrderId, $userId)
|
|
{
|
|
Db::beginTransaction();
|
|
try {
|
|
// 订单待支付
|
|
$orderMain = $this->check($globalOrderId, $userId, OrderState::UNPAID);
|
|
$orderMain->state = OrderState::CANCELED;
|
|
if (!$orderMain->save()) {
|
|
throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
|
|
}
|
|
|
|
// 退还优惠券
|
|
$this->couponService->orderRefundCoupons($globalOrderId);
|
|
|
|
// 撤销活动商品购买记录
|
|
$orders = Order::query()->where(['order_main_id' => $globalOrderId])->get()->toArray();
|
|
$orderGoods = OrderGoods::query()
|
|
// ->where('activity_type', 2)
|
|
->whereIn('order_id', array_values(array_column($orders, 'id')))
|
|
->get()
|
|
->toArray();
|
|
foreach ($orderGoods as $key => &$goods) {
|
|
if ($goods['activity_type'] == 2) {
|
|
$this->goodsActivityService->clearCacheRecord($goods['goods_id'], $goods['number'], $orderMain['user_id']);
|
|
}
|
|
}
|
|
|
|
Db::commit();
|
|
|
|
// 释redis库存
|
|
$redis = ApplicationContext::getContainer()->get(Redis::class);
|
|
foreach ($orderGoods as $k => &$goodsItem) {
|
|
// // 拼接activity_type和goods_id
|
|
// $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
|
|
// // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
|
|
// if (!$redis->exists($inventoryKey)) {
|
|
// $redis->set($inventoryKey, 0);
|
|
// } else {
|
|
// $redis->decrBy($inventoryKey, intval($goodsItem['number']));
|
|
// }
|
|
$this->goodsInventoryService->undoSold($goodsItem['activity_type'], $goodsItem['goods_id'], $goodsItem['number']);
|
|
}
|
|
|
|
// 记录badge
|
|
$orderChildIds = array_values(array_column($orders, 'store_id'));
|
|
$this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::CANCELED);
|
|
|
|
return true;
|
|
} catch (Exception $e) {
|
|
Db::rollBack();
|
|
throw new ErrorCodeException(ErrorCode::ORDER_CANCEL_FAIL, $e->getMessage());
|
|
}
|
|
}
|
|
|
|
public function detailByUser($globalOrderId, $userId)
|
|
{
|
|
//主订单
|
|
$orderMain = OrderMain::with(['market'])->where(['global_order_id' => $globalOrderId])->first();
|
|
//子订单
|
|
$orders = Order::query()
|
|
->where(['order_main_id' => $globalOrderId, 'user_id' => $userId])
|
|
->with([
|
|
'orderGoods',
|
|
'store'
|
|
])
|
|
->get()->toArray();
|
|
//配送人员信息
|
|
if($orderMain->horseman_id > 0) {
|
|
$employees = Employees::query()->where('id', $orderMain->horseman_id)->first();
|
|
}else{
|
|
$employees = null;
|
|
}
|
|
return ['order_main' => $orderMain, 'orders' => $orders,'employees' => $employees];
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function doByPaid($globalOrderId)
|
|
{
|
|
Db::beginTransaction();
|
|
try {
|
|
|
|
$ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
|
|
|
|
// 查询订单
|
|
$orderMain = OrderMain::query()
|
|
->where(['global_order_id' => $globalOrderId,'type' => OrderType::ONLINE])
|
|
->first();
|
|
|
|
// 修改订单、子订单状态
|
|
$currentTime = time();
|
|
$orderMain->state = OrderState::PAID;
|
|
$orderMain->pay_time = $currentTime;
|
|
$orderMain->save();;
|
|
|
|
// 更新商品库存和销量
|
|
$orders = Order::query()
|
|
->where(['order_main_id' => $globalOrderId])
|
|
->get()
|
|
->toArray();
|
|
|
|
// 更新商户销量
|
|
$upStoreScore = Store::query()
|
|
->whereIn('id', array_values(array_column($orders, 'store_id')))
|
|
->update(['sales' => Db::raw('sales+1')]);
|
|
|
|
$orderGoods = OrderGoods::query()
|
|
->whereIn('order_id', array_values(array_column($orders, 'id')))
|
|
->get()
|
|
->toArray();
|
|
foreach ($orderGoods as $key => &$goodsItem) {
|
|
if ($goodsItem['activity_type'] == 2) { # 活动商品
|
|
$goods = GoodsActivity::find($goodsItem['goods_id']);
|
|
} else {
|
|
$goods = Goods::find($goodsItem['goods_id']);
|
|
}
|
|
$goods->inventory = $goods->inventory - $goodsItem['number'];
|
|
$goods->sales = $goods->sales + $goodsItem['number'];
|
|
$goods->save();
|
|
|
|
// 商品月销
|
|
if (!$ssdb->exec('exists', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_'.$goods->id)) {
|
|
$ssdb->exec('set', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
|
|
} else {
|
|
$ssdb->exec('incr', SsdbKeys::GOODS_MONTH_SALES . date('Ym') . '_' . $goodsItem['activity_type'] . '_' . $goods->id, $goodsItem['number']);
|
|
}
|
|
}
|
|
|
|
Db::commit();
|
|
|
|
# 创建顺丰订单
|
|
$this->createSfExpressOrder($globalOrderId);
|
|
|
|
// 释redis库存
|
|
$redis = ApplicationContext::getContainer()->get(Redis::class);
|
|
foreach ($orderGoods as $k => &$goodsItem) {
|
|
// // 拼接activity_type和goods_id
|
|
// $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
|
|
// // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
|
|
// if (!$redis->exists($inventoryKey)) {
|
|
// $redis->set($inventoryKey, 0);
|
|
// } else {
|
|
// $redis->decrBy($inventoryKey, intval($goodsItem['number']));
|
|
// }
|
|
$this->goodsInventoryService->undoSold($goodsItem['activity_type'], $goodsItem['goods_id'], $goodsItem['number']);
|
|
}
|
|
|
|
// 月销流水
|
|
$statistics = [];
|
|
foreach ($orders as $key => &$order) {
|
|
$statistics[] = [
|
|
'money' => $order['money'],
|
|
'user_id' => $order['user_id'],
|
|
'store_id' => $order['store_id'],
|
|
'market_id' => $orderMain->market_id,
|
|
'order_id' => $order['id'],
|
|
];
|
|
|
|
// 商户月销
|
|
if (!$ssdb->exec('exists', SsdbKeys::STORE_MONTH_SALES . date('Ym').'_' . $order['store_id'])) {
|
|
$ssdb->exec('set', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
|
|
} else {
|
|
$ssdb->exec('incr', SsdbKeys::STORE_MONTH_SALES . date('Ym') . '_' . $order['store_id'], 1);
|
|
}
|
|
}
|
|
|
|
if (is_array($statistics) && !empty($statistics)) {
|
|
$inSalesStatistics = OrderSalesStatistic::query()->insert($statistics);
|
|
}
|
|
|
|
return true;
|
|
} catch (Exception $e) {
|
|
|
|
$this->log->event(LogLabel::ORDER_ONLINE_PAID_LOG, ['exception' => $e->getMessage()]);
|
|
Db::rollBack();
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 支付回调之后,协程创建顺丰订单
|
|
*/
|
|
private function createSfExpressOrder($globalOrderId)
|
|
{
|
|
co(function () use ($globalOrderId) {
|
|
try {
|
|
# 主订单
|
|
$orderMain = OrderMain::where('global_order_id', $globalOrderId)->first();
|
|
|
|
$weight = 0;
|
|
$product_detail = [];
|
|
|
|
# 子订单
|
|
$subOrderIds = Order::where('order_main_id', $globalOrderId)->pluck('id')->toArray();
|
|
$orderGoods = OrderGoods::whereIn('order_id', $subOrderIds)->get();
|
|
foreach ($orderGoods as $goods) {
|
|
$weight += $goods->number * $goods->weight;
|
|
$product_detail[] = ['product_name' => $goods->name, 'product_num' => $goods->number];
|
|
}
|
|
|
|
# 创建顺丰订单
|
|
$sfOrder = SfExpress::getInstance()->createOrder([
|
|
'shop_order_id' => $globalOrderId,
|
|
'order_time' => time(),
|
|
'receive' => [
|
|
'user_name' => $orderMain->name, //必填,用户姓名
|
|
'user_phone' => $orderMain->tel, //必填,用户电话
|
|
'user_address' => $orderMain->address, //必填,用户详细地址
|
|
'user_lng' => $orderMain->lng, //必填,用户地址经度
|
|
'user_lat' => $orderMain->lat, //必填,用户地址纬度
|
|
],
|
|
'order_detail' => [ // 必填,订单详情
|
|
'total_price' => 0, //用户订单商品总金额(单位:分) 100 表示1元(最大值为100万, 超过此值则按100万计算)
|
|
'product_type' => 6, //必填,物品类型。1:快餐,2:药品,3:百货,4:脏衣服收,5:干净衣服派,6:生鲜,其它详见文档
|
|
// 'user_money' => 0, // 用户实付商家金额(单位:分) 100 表示1元
|
|
// 'shop_money' => 0, // 商家实收用户金额(单位:分) 100 表示1元
|
|
'weight_gram' => $weight, // 必填,物品重量(单位:克) 100 表示100g
|
|
// 'volume_litre' => 0, // 物品体积(单位:升) 1 表示1升
|
|
// 'delivery_money' => 0, // 商家收取用户的配送费(单位:分) 100 表示1元
|
|
'product_num' => $orderGoods->sum('number'), // 必填,物品个数
|
|
'product_type_num' => $orderGoods->count(), // 必填,物品种类个数
|
|
'product_detail' => $product_detail, /*[ // 必填,物品种类个数
|
|
[
|
|
'product_name' => '', // 必填,物品名称
|
|
// 'product_id' => 1, // 物品ID
|
|
'product_num' => 1, // 必填,物品数量
|
|
// 'product_price' => 0, // 物品价格
|
|
// 'product_unit' => 0, // 物品单位
|
|
// 'product_remark' => 0, // 备注
|
|
// 'item_detail' => 0, // 详情
|
|
],
|
|
],*/
|
|
],
|
|
]);
|
|
|
|
# 保存到顺丰订单表
|
|
SfExpressOrder::unguard();
|
|
SfExpressOrder::updateOrCreate(['shop_order_id' => $globalOrderId], [
|
|
'shop_order_id' => $globalOrderId,
|
|
'sf_order_id' => $sfOrder['result']['sf_order_id'],
|
|
'sf_bill_id' => $sfOrder['result']['sf_bill_id'],
|
|
'total_price' => $sfOrder['result']['total_price'] ?? 0,
|
|
'delivery_distance_meter' => $sfOrder['result']['delivery_distance_meter'] ?? 0,
|
|
'weight_gram' => $sfOrder['result']['weight_gram'] ?? 0,
|
|
'start_time' => $sfOrder['result']['start_time'] ?? 0,
|
|
'expect_time' => $sfOrder['result']['expect_time'] ?? 0,
|
|
'total_pay_money' => $sfOrder['result']['total_pay_money'] ?? 0,
|
|
'real_pay_money' => $sfOrder['result']['real_pay_money'] ?? 0,
|
|
]);
|
|
echo '创建顺丰订单成功了!', PHP_EOL;
|
|
} catch (Exception $exception) {
|
|
$this->log->event('SfExpress', ['exception' => $exception->getMessage()]);
|
|
|
|
# 取消顺丰订单,如果失败,重试 3 次
|
|
co(function () use ($globalOrderId) {
|
|
for ($i = 0; $i < 3; $i++) {
|
|
try {
|
|
$res = SfExpress::getInstance()->cancelOrder(['order_id' => $globalOrderId]);
|
|
if ($res['error_code'] == 0) {
|
|
echo "取消顺丰订单 $globalOrderId 成功!", PHP_EOL;
|
|
break;
|
|
}
|
|
} catch (Exception $exception) {
|
|
echo $exception->getMessage(), PHP_EOL;
|
|
}
|
|
sleep(1);
|
|
}
|
|
});
|
|
}
|
|
});
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function doPay($globalOrderId, $userId)
|
|
{
|
|
// 订单待支付
|
|
$orderMain = $this->check($globalOrderId, $userId, OrderState::UNPAID);
|
|
return $this->paymentService->do(
|
|
$orderMain->global_order_id,
|
|
$orderMain->money,
|
|
$orderMain->user_id,
|
|
config('wechat.notify_url.online')
|
|
);
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
* @throws Exception
|
|
*/
|
|
public function doDel($globalOrderId, $userId)
|
|
{
|
|
// 订单完成
|
|
$orderMain = $this->check($globalOrderId, $userId, OrderState::CAN_DEL);
|
|
if (!$orderMain->delete()) {
|
|
throw new ErrorCodeException(ErrorCode::ORDER_DELETE_FAIL);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function doApplyRefund($globalOrderId, $userId)
|
|
{
|
|
// 未接单
|
|
$orderMain = $this->check($globalOrderId, $userId, OrderState::PAID);
|
|
$orderMain->state = OrderState::REFUNDING;
|
|
if (!$orderMain->save()) {
|
|
throw new ErrorCodeException(ErrorCode::ORDER_APPLY_REFUND_FAIL);
|
|
}
|
|
|
|
// 记录badge
|
|
$orderChildIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('store_id');
|
|
$this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::REFUNDING);
|
|
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function doComplete($globalOrderId, $userId)
|
|
{
|
|
$orderMain = $this->check($globalOrderId, $userId, OrderState::RECEIVING);
|
|
$orderMain->state = OrderState::COMPLETED;
|
|
$orderMain->complete_time = time();
|
|
$orderMain->delivery_time = time();
|
|
if (!$orderMain->save()) {
|
|
throw new ErrorCodeException(ErrorCode::ORDER_COMPLETE_FAIL);
|
|
}
|
|
|
|
co(function () use ($orderMain) {
|
|
// 记录badge
|
|
$orderChildIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('store_id');
|
|
$this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::COMPLETED);
|
|
|
|
// 发送订阅消息
|
|
$this->miniprogramService->subscribeMsgForOrderComplete($orderMain);
|
|
});
|
|
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function doRefund($globalOrderId, $userId)
|
|
{
|
|
|
|
$orderMain = $this->check($globalOrderId, $userId, OrderState::REFUNDING);
|
|
|
|
$orderIds = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->pluck('id');
|
|
$orderGoods = OrderGoods::query()->whereIn('order_id', $orderIds)->get()->toArray();
|
|
|
|
// 微信退款
|
|
if ($orderMain->pay_type == Payment::WECHAT) {
|
|
return $this->paymentService->undo($orderMain->global_order_id, $userId);
|
|
}
|
|
}
|
|
|
|
public function autoCancel()
|
|
{
|
|
|
|
try {
|
|
|
|
$orderMains = OrderMain::query()
|
|
->where(['state' => OrderState::UNPAID, 'type' => OrderType::ONLINE])
|
|
->where('created_at', '<', time()-600)
|
|
->orderBy('created_at', 'asc')
|
|
->limit(100)
|
|
->get();
|
|
|
|
foreach ($orderMains as $key => &$orderMain) {
|
|
|
|
// 订单取消
|
|
OrderMain::query()->where(['id' => $orderMain->id])->update(['state' => OrderState::CANCELED]);
|
|
|
|
// 退还优惠券
|
|
$this->couponService->orderRefundCoupons($orderMain->global_order_id);
|
|
|
|
// 撤销活动商品购买记录
|
|
$orders = Order::query()->where(['order_main_id' => $orderMain->global_order_id])->get()->toArray();
|
|
$orderGoods = OrderGoods::query()
|
|
->whereIn('order_id', array_values(array_column($orders, 'id')))
|
|
->get()
|
|
->toArray();
|
|
foreach ($orderGoods as $key => &$goods) {
|
|
if ($goods['activity_type'] == 2) {
|
|
$this->goodsActivityService->clearCacheRecord($goods['goods_id'], $goods['number'], $orderMain->user_id);
|
|
}
|
|
}
|
|
|
|
// 释redis库存
|
|
$redis = ApplicationContext::getContainer()->get(Redis::class);
|
|
foreach ($orderGoods as $k => &$goodsItem) {
|
|
// // 拼接activity_type和goods_id
|
|
// $inventoryKey = 'goods_inventory_sold_'.$goodsItem['activity_type'].'_'.$goodsItem['goods_id'];
|
|
// // redis记录当前商品的购买数量,压库存,下单失败、下单成功扣库存成功、订单取消的时候释放
|
|
// if (!$redis->exists($inventoryKey)) {
|
|
// $redis->set($inventoryKey, 0);
|
|
// } else {
|
|
// $redis->decrBy($inventoryKey, intval($goodsItem['number']));
|
|
// }
|
|
$this->goodsInventoryService->undoSold($goodsItem['activity_type'], $goodsItem['goods_id'], $goodsItem['number']);
|
|
}
|
|
|
|
// 记录badge
|
|
$orderChildIds = array_values(array_column($orders, 'store_id'));
|
|
$this->badgeService->doByOrder($orderMain->user_id, $orderChildIds, $orderMain->global_order_id, OrderState::CANCELED);
|
|
}
|
|
|
|
} catch (Exception $e) {
|
|
$this->log->event(LogLabel::ORDER_AUTO_CANCEL_FAIL_LOG, ['message' => $e->getMessage()]);
|
|
}
|
|
|
|
}
|
|
|
|
/**
|
|
* 校验用户今天是否买过x单[y,z]分钱的活动商品
|
|
* @param $userId
|
|
*/
|
|
public function checkIfBuyFlashGoodsToday($userId)
|
|
{
|
|
$mainTable = ApplicationContext::getContainer()->get(OrderMain::class)->getTable();
|
|
$orderTable = ApplicationContext::getContainer()->get(Order::class)->getTable();
|
|
$goodsTable = ApplicationContext::getContainer()->get(OrderGoods::class)->getTable();
|
|
|
|
$limitPrices = explode(',', env('LIMIT_BUY_COUNT_GOODS_PRICES'));
|
|
$limitCount = intval(env('LIMIT_BUY_COUNT'));
|
|
|
|
$countToday = OrderMain::query()
|
|
->join($orderTable, $orderTable.'.order_main_id', '=', $mainTable.'.global_order_id')
|
|
->join($goodsTable, $goodsTable.'.order_id', '=', $orderTable.'.id')
|
|
->where($mainTable.'.updated_at', '>=', strtotime(date('Y-m-d 00:00:00')))
|
|
->where($mainTable.'.updated_at', '<=', strtotime(date('Y-m-d 23:59:59')))
|
|
->where([$goodsTable.'.activity_type' => 2])
|
|
->whereIn($mainTable.'.state', OrderState::LIMIT_BUY_COUNT)
|
|
->where([$mainTable.'.user_id' => $userId])
|
|
->whereIn($goodsTable.'.price', $limitPrices)
|
|
->count();
|
|
|
|
if ($countToday >= $limitCount) {
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
public function getOrderInfo($globalOrderId)
|
|
{
|
|
return OrderMain::query()->where('global_order_id',$globalOrderId)->with('market','orderGoods')->first();
|
|
}
|
|
|
|
public function completeForHorseman($globalOrderId)
|
|
{
|
|
return true;
|
|
}
|
|
}
|