|
|
<?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\Market;use App\Model\v3\Order;use App\Model\v3\OrderGoods;use App\Model\v3\OrderMain;use App\Model\v3\OrderSalesStatistic;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\PaymentServiceInterface;use App\Service\v3\Interfaces\ShopCartUpdateServiceInterface;use App\Service\v3\Interfaces\UserAddressServiceInterface;use App\TaskWorker\SSDBTask;use Exception;use Hyperf\Database\Model\Model;use Hyperf\DbConnection\Db;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;
/** * 下单 * @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) { // 用户收货地址
// 获取配送费用
$userAddrAndDPrice = $this->userAddressService->getAddressAndDistributionPrice($userAddrId, $marketId); $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), ]; }
// 子订单数据
$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){ $this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => '同一订单中有活动商品不可同时购买多款', 'data' => json_encode($dataOrderGoods)]); throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_RESTRICT_LIMIT); }
// 订单成功,做一些处理
// 活动商品购买记录
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();
// 释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; } }
/** * @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(); if (!$orderMain->save()) { throw new ErrorCodeException(ErrorCode::ORDER_COMPLETE_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::COMPLETED);
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; }}
|