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.
 
 

589 lines
22 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\SsdbKeys;
use App\Exception\ErrorCodeException;
use App\Model\v3\Coupon;
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\ShoppingCart;
use App\Model\v3\Store;
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\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\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;
/**
* 下单
* @param $marketId
* @param $userId
* @param $userAddrId
* @param $storeList
* @param $totalMoney
* @param string $deliveryTimeNote
* @param int $serviceMoney
* @param null $receiveCouponIds
* @param string $plat
* @return array[]
*/
public function do($marketId, $userId, $userAddrId, $storeList, $totalMoney, $deliveryTimeNote='尽快送达', $serviceMoney=0, $receiveCouponIds=null, $plat=''){
Db::beginTransaction();
try {
$currentTime = time();
bcscale(6);
// 用户收货地址
// 获取配送费用
$userAddrAndDPrice = $this->userAddressService->getAddressAndDistributionPrice($userAddrId, $marketId);
$userAddr = $userAddrAndDPrice['address']['address'];
$deliveryAmount = $userAddrAndDPrice['distribution_price'];
$deliveryDistance = $userAddrAndDPrice['delivery_distance'];
// 优惠券数据,当前订单可用个优惠券
$couponRecs = $this->couponRecService->allForOnlineOrderAvailable($userId, $marketId);
$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);
}
// 处理购物车数据,计算订单金额、子订单数据处理等
$totalAmount = 0; # 实付金额
$orderAmount = 0; # 订单金额
$dataMain = []; # 主订单
$dataChildren = []; # 子订单
$dataOrderGoods = []; # 订单商品
$storeTypeIds = []; # 订单中的商户类型,用于校验红包
foreach ($storeList as $key => &$storeItem) {
$storeId = $storeItem->store_id;
// 子订单金额
$subAmount = 0;
// 店铺分类
$storeType = Store::query()->where(['id' => $storeId])->value('category_id');
$storeTypeIds[] = (string)$storeType;
// 店铺今天的订单数
$count = Order::query()
->join('lanzu_order_main as main', 'main.id', '=', 'lanzu_order.order_main_id')
->where(['lanzu_order.store_id' => $storeId, 'main.type' => OrderType::ONLINE])
->whereBetween('lanzu_order.created_at', [strtotime(date('Y-m-d 00:00:00')), strtotime(date('Y-m-d 23:59:59'))])
->count();
// 用户购物车数据
$cartIds = explode(',', $storeItem->cart_ids);
$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.'/'.$goods->goods_unit.']');
}
} 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.']');
}
$check = $this->goodsActivityService->check($goods, $cart->num, $userId);
if (true !== $check) {
throw new ErrorCodeException($check, '['.$goods->name.'/'.$goods->goods_unit.']');
}
}
// 算金额
$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);
}
// 优惠券的使用
$couponMoney = 0;
if (!empty($receiveCouponIds)) {
// 计算红包折扣金额
foreach ($canRealUseCoupons as $key => &$coupon) {
if (!in_array($coupon['id'], $receiveCouponIds)) {
unset($coupon);
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);
$discountRate = bcsub(1,$discountRate);
$discountMoney = bcmul($orderAmount, $discountRate);
$couponMoney = bcadd($couponMoney, $discountMoney, 2);
}
}
}
// 获取分布式全局ID
$generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
$globalOrderId = $generator->generate();
$orderAmount = bcadd((string)$orderAmount, '0', 2);
$totalAmount = bcadd((string)$totalAmount, (string)$orderAmount);
$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);
}
// 校验订单总金额是否满足起送
$initDeliveryAmount = $this->initialDeliveryService->get();
if ($orderAmount < $initDeliveryAmount) {
throw new ErrorCodeException(ErrorCode::ORDER_NOT_ENOUGH_INITIAL_DELIVERY, "[{$initDeliveryAmount}]");
}
$dataMain = [
'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($dataOrderGoods);
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);
}
}
// 优惠券红包使用记录
$this->couponService->orderUseCoupons($globalOrderId, $canRealUseCoupons);
Db::commit();
// 清除购物车
$this->shopCartUpdateService->doClear($userId, $marketId);
// 记录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();
$this->log->event(LogLabel::ORDER_ONLINE_LOG, ['msg' => $e->getMessage()]);
throw new ErrorCodeException(ErrorCode::ORDER_ONLINE_FAIL, $e->getMessage());
}
}
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();
foreach ($orderGoods as $key => &$goods) {
$this->goodsActivityService->clearCacheRecord($goods->goods_id, $goods->number, $orderMain->user_id);
}
Db::commit();
// 记录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();
return ['order_main' => $orderMain, 'orders' => $orders];
}
/**
* @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();
// 月销流水
$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;
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);
// 微信退款
if ($orderMain->pay_type == Payment::WECHAT) {
return $this->paymentService->undo($orderMain->global_order_id, $userId);
}
}
}