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.
553 lines
21 KiB
553 lines
21 KiB
<?php
|
|
|
|
namespace App\Service\v3\Implementations;
|
|
|
|
use App\Commons\Log;
|
|
use App\Constants\v3\ActivityType;
|
|
use App\Constants\v3\ErrorCode;
|
|
use App\Constants\v3\LogLabel;
|
|
use App\Constants\v3\OrderState;
|
|
use App\Constants\v3\OrderType;
|
|
use App\Constants\v3\SsdbKeys;
|
|
use App\Exception\ErrorCodeException;
|
|
use App\Model\v3\Coupon;
|
|
use App\Model\v3\CouponRec;
|
|
use App\Model\v3\CouponUse;
|
|
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\Model\v3\UserAddress;
|
|
use App\Service\v3\Interfaces\CouponRecServiceInterface;
|
|
use App\Service\v3\Interfaces\CouponServiceInterface;
|
|
use App\Service\v3\Interfaces\DeliveryMoneyServiceInterface;
|
|
use App\Service\v3\Interfaces\GoodsActivityServiceInterface;
|
|
use App\Service\v3\Interfaces\GoodsServiceInterface;
|
|
use App\Service\v3\Interfaces\PaymentServiceInterface;
|
|
use App\Service\v3\Interfaces\ShopCartUpdateServiceInterface;
|
|
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 DeliveryMoneyServiceInterface
|
|
*/
|
|
protected $deliveryService;
|
|
|
|
/**
|
|
* @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;
|
|
|
|
/**
|
|
* 下单
|
|
* @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);
|
|
// 用户收货地址
|
|
$userAddr = UserAddress::query()->find($userAddrId);
|
|
// 获取配送费用
|
|
$deliveryAmount = $this->deliveryService->do($userAddr->lat, $userAddr->lng);
|
|
// 优惠券数据
|
|
$couponRec = CouponRec::query()->lockForUpdate()->whereIn('id', $receiveCouponIds)->get()->toArray();
|
|
|
|
// 处理购物车数据,计算订单金额、子订单数据处理等
|
|
$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()
|
|
->where(['store_id' => $storeId, 'type' => OrderType::ONLINE])
|
|
->whereBetween('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()->find($cart->goods_id);
|
|
$check = $this->goodsService->check($goods->id, $cart->num);
|
|
if (true !== $check) {
|
|
throw new ErrorCodeException($check, '[商品失效1]'.$cart->goods_id);
|
|
}
|
|
} elseif ($cart->activity_type == 2) {
|
|
$goods = GoodsActivity::query()->lockForUpdate()->find($cart->goods_id);
|
|
$check = $this->goodsActivityService->check($goods->id, $cart->num, $userId);
|
|
if (true !== $check) {
|
|
throw new ErrorCodeException($check, '[商品失效2]'.$cart->goods_id);
|
|
}
|
|
|
|
// 活动商品不可用优惠券
|
|
if ($goods->can_use_coupon!=1 && $receiveCouponIds) {
|
|
throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_CANNOT_USE_COUPON, '[商品失效]'.$cart->goods_id);
|
|
}
|
|
|
|
// 活动商品可用优惠券,再校验这些优惠券是不是可以在当前活动类型可用
|
|
// receiveCouponIds中是不是有当前活动不可用的优惠券
|
|
$couponIds = array_values(array_column($couponRec, 'coupon_id'));
|
|
$couponsActivityAvailable = Coupon::query()
|
|
->select(['id'])
|
|
->whereJsonContains('activity_available', [(string)$goods->type])
|
|
->whereIn('id', $couponIds)
|
|
->get()->toArray();
|
|
$couponsActivityAvailableIds = array_values(array_column($couponsActivityAvailable, 'id'));
|
|
if (!empty(array_diff($couponIds, $couponsActivityAvailableIds))) {
|
|
throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_CANNOT_USE_COUPON, '[商品失效]'.json_encode($couponsActivityAvailableIds));
|
|
}
|
|
|
|
}
|
|
|
|
if (empty($goods)) {
|
|
throw new ErrorCodeException(ErrorCode::ORDER_GOODS_NOT_AVAILABLE);
|
|
}
|
|
|
|
// 库存判断
|
|
if ($goods->is_infinite !=1 && $goods->inventory < $cart->num) {
|
|
throw new ErrorCodeException(ErrorCode::ORDER_GOODS_INVENTORY_LIMIT);
|
|
}
|
|
|
|
// 算金额
|
|
$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' => $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($couponRec)) {
|
|
$couponsCanUse = $this->couponRecService->allForOrderOlAvailable($totalAmount, $userId, $marketId, 2, $storeTypeIds);
|
|
$couponCanUseIds = array_column($couponsCanUse, 'id');
|
|
$couponCanUseIds = array_intersect($couponCanUseIds, $receiveCouponIds);
|
|
$couponCannotUseIds = array_diff($receiveCouponIds, $couponCanUseIds);
|
|
|
|
if (empty($couponCanUseIds)||!empty($couponCannotUseIds)) {
|
|
throw new ErrorCodeException(ErrorCode::COUPON_NOT_AVAILABLE);
|
|
}
|
|
|
|
// 计算红包折扣金额
|
|
foreach ($couponsCanUse as $key => $coupon) {
|
|
if (!in_array($coupon->id, $receiveCouponIds)) {
|
|
continue;
|
|
}
|
|
|
|
if ($coupon->discount_type == Coupon::DISCOUNT_TYPE_CASH) {
|
|
$couponMoney = bcadd($couponMoney, $coupon->discounts, 2);
|
|
} elseif ($coupon->discount_type == Coupon::DISCOUNT_TYPE_RATE) {
|
|
$discountRate = bcdiv($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);
|
|
}
|
|
|
|
$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,
|
|
'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);
|
|
$orderMainId = $orderMain->id;
|
|
|
|
// 处理子订单
|
|
foreach ($dataChildren as $key => &$child) {
|
|
$child['order_main_id'] = $orderMainId;
|
|
$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){
|
|
throw new ErrorCodeException(ErrorCode::GOODS_ACTIVITY_RESTRICT_LIMIT, '[同一订单同种类型活动商品]'.json_encode($dataOrderGoods));
|
|
}
|
|
|
|
// 订单成功,做一些处理
|
|
// 活动商品购买记录
|
|
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($orderMainId, $couponRec);
|
|
|
|
Db::commit();
|
|
|
|
// 清除购物车
|
|
$this->shopCartUpdateService->doClear($userId, $marketId);
|
|
|
|
// 支付
|
|
return $this->paymentService->do($globalOrderId, $totalAmount, $userId, config('wechat.notify_url.online'));
|
|
} catch (Exception $e) {
|
|
Db::rollBack();
|
|
$this->log->event(LogLabel::ORDER_ONLINE_LOG, ['exception_msg' => $e->getMessage()]);
|
|
throw new ErrorCodeException(ErrorCode::ORDER_ONLINE_FAIL, $e->getMessage());
|
|
}
|
|
}
|
|
|
|
public function check($orderMainId, $userId, $state): Model
|
|
{
|
|
$builder = OrderMain::query()
|
|
->where(['id' => $orderMainId, '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($orderMainId, $userId)
|
|
{
|
|
Db::beginTransaction();
|
|
try {
|
|
// 订单待支付
|
|
$orderMain = $this->check($orderMainId, $userId, OrderState::UNPAID);
|
|
$orderMain->state = OrderState::CANCELED;
|
|
if (!$orderMain->save()) {
|
|
throw new ErrorCodeException(ErrorCode::ORDER_NOT_AVAILABLE);
|
|
}
|
|
|
|
// 退还优惠券
|
|
$this->couponService->orderRefundCoupons($orderMainId);
|
|
|
|
// 撤销活动商品购买记录
|
|
$orders = Order::query()->where(['order_main_id' => $orderMainId])->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();
|
|
return true;
|
|
} catch (Exception $e) {
|
|
Db::rollBack();
|
|
throw new ErrorCodeException(ErrorCode::ORDER_CANCEL_FAIL, $e->getMessage());
|
|
}
|
|
}
|
|
|
|
public function detailByUser($orderMainId, $userId)
|
|
{
|
|
|
|
$orderMain = OrderMain::with(['market'])->find($orderMainId);
|
|
$orders = Order::query()
|
|
->where(['order_main_id' => $orderMainId, 'user_id' => $userId])
|
|
->with([
|
|
'orderGoods',
|
|
'store'
|
|
])
|
|
->get()->toArray();
|
|
|
|
return ['order_main' => $orderMain, 'orders' => $orders];
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function doByPaid($orderMainId)
|
|
{
|
|
Db::beginTransaction();
|
|
try {
|
|
|
|
$ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
|
|
|
|
// 查询订单
|
|
$orderMain = OrderMain::query()
|
|
->where(['id' => $orderMainId,'type' => OrderType::ONLINE])
|
|
->first();
|
|
|
|
// 修改订单、子订单状态
|
|
$currentTime = time();
|
|
$orderMain->state = OrderState::PAID;
|
|
$orderMain->pay_time = $currentTime;
|
|
$orderMain->save();;
|
|
|
|
// 更新商品库存和销量
|
|
$orders = Order::query()
|
|
->where(['order_main_id' => $orderMain->id])
|
|
->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']);
|
|
}
|
|
}
|
|
|
|
// 月销流水
|
|
$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'],
|
|
'createtime' => $orderMain->pay_time,
|
|
];
|
|
|
|
// 商户月销
|
|
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);
|
|
}
|
|
|
|
Db::commit();
|
|
return true;
|
|
} catch (Exception $e) {
|
|
|
|
$this->log->event(LogLabel::ORDER_ONLINE_PAID_LOG, ['exception' => $e->getMessage()]);
|
|
Db::rollBack();
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function doPay($orderMainId, $userId)
|
|
{
|
|
// 订单待支付
|
|
$orderMain = $this->check($orderMainId, $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($orderMainId, $userId)
|
|
{
|
|
// 订单完成
|
|
$orderMain = $this->check($orderMainId, $userId, OrderState::CAN_DEL);
|
|
if (!$orderMain->delete()) {
|
|
throw new ErrorCodeException(ErrorCode::ORDER_DELETE_FAIL);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function doApplyRefund($orderMainId, $userId)
|
|
{
|
|
// 未接单
|
|
$orderMain = $this->check($orderMainId, $userId, OrderState::PAID);
|
|
$orderMain->state = OrderState::REFUNDING;
|
|
if (!$orderMain->save()) {
|
|
throw new ErrorCodeException(ErrorCode::ORDER_APPLY_REFUND_FAIL);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* @inheritDoc
|
|
*/
|
|
public function doComplete($orderMainId, $userId)
|
|
{
|
|
$orderMain = $this->check($orderMainId, $userId, OrderState::RECEIVING);
|
|
$orderMain->state = OrderState::COMPLETED;
|
|
if (!$orderMain->save()) {
|
|
throw new ErrorCodeException(ErrorCode::ORDER_COMPLETE_FAIL);
|
|
}
|
|
return true;
|
|
}
|
|
}
|