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.
456 lines
18 KiB
456 lines
18 KiB
<?php
|
|
|
|
namespace App\Service\v3\Implementations;
|
|
|
|
use App\Constants\LogLabel;
|
|
use App\Constants\v3\OrderType;
|
|
use App\Model\CouponRec;
|
|
use App\Model\CouponUserUse;
|
|
use App\Model\Goods;
|
|
use App\Model\OrderGoods;
|
|
use App\Model\SpecCombination;
|
|
use App\Model\v3\Order;
|
|
use App\Model\v3\OrderMain;
|
|
use App\Model\v3\ShoppingCart;
|
|
use App\Model\v3\UserAddress;
|
|
use App\Service\v3\Interfaces\DeliveryMoneyServiceInterface;
|
|
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 DeliveryMoneyServiceInterface
|
|
*/
|
|
protected $deliveryService;
|
|
|
|
/**
|
|
* 下单
|
|
* @param $marketId
|
|
* @param $userId
|
|
* @param $userAddrId
|
|
* @param $cartIds
|
|
* @param $totalMoney
|
|
* @param string $deliveryTimeNote
|
|
* @param null $receiveCouponIds
|
|
* @return string
|
|
*/
|
|
public function do($marketId, $userId, $userAddrId, $cartIds, $totalMoney, $deliveryTimeNote='尽快送达', $receiveCouponIds=null){
|
|
|
|
bcscale(6);
|
|
|
|
// 用户收货地址
|
|
$userAddr = UserAddress::query()->find($userAddrId);
|
|
// 用户购物车数据
|
|
$carts = ShoppingCart::query()->whereIn('id', $cartIds)->where(['market_id' => $marketId])->get();
|
|
// 优惠券数据
|
|
$couponRec = CouponRec::query()->whereIn('id', $receiveCouponIds);
|
|
|
|
// 获取配送费用
|
|
$deliveryAmount = $this->deliveryService->do($userAddr->lat, $userAddr->lng);
|
|
|
|
// 处理购物车数据,计算订单金额、子订单数据处理等
|
|
$totalAmount = bcadd((string)$deliveryAmount, 0);
|
|
$orderAmount = 0;
|
|
$orderChildren = [];
|
|
foreach ($carts as $key => $cart) {
|
|
// 查个商品
|
|
$goods = Goods::query()->select('price')->find($cart->goods_id);
|
|
$goodsAmount = bcmul((string)$goods->price, (string)$cart->num);
|
|
|
|
// 子订单
|
|
$orderChildren[$cart->store_id]['user_id'] = $cart->user_id;
|
|
if (!isset($orderChildren[$cart->store_id]['money'])) {
|
|
$orderChildren[$cart->store_id]['money'] = 0;
|
|
}
|
|
$orderChildren[$cart->store_id]['money'] = bcadd((string)$orderChildren[$cart->store_id]['money'], (string)$goodsAmount);
|
|
$totalAmount = bcadd((string)$totalAmount, (string)$goodsAmount);
|
|
}
|
|
|
|
// 获取分布式全局ID
|
|
$generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
|
|
$global_order_id = $generator->generate();
|
|
|
|
$dataMain = [
|
|
'market_id' => $marketId,
|
|
'order_num' => $global_order_id,
|
|
'global_order_id' => $global_order_id,
|
|
'user_id' => $userId,
|
|
'type' => OrderType::ONLINE,
|
|
'money' => $totalAmount,
|
|
'total_money' => '',
|
|
'services_money' => '',
|
|
'coupon_money' => '',
|
|
'delivery_money' => '',
|
|
'state' => '',
|
|
'pay_time' => '',
|
|
'receive_time' => '',
|
|
'delivery_time' => '',
|
|
'complete_time' => '',
|
|
'cancel_time' => '',
|
|
'refund_time' => '',
|
|
'tel' => '',
|
|
'address' => '',
|
|
'area' => '',
|
|
'lat' => '',
|
|
'lng' => '',
|
|
'name' => '',
|
|
'print_num' => '',
|
|
'plat' => '',
|
|
'refuse_refund_note' => '',
|
|
'delivery_time_note' => '',
|
|
'total_refund_note' => '',
|
|
'note' => '',
|
|
'created_at' => '',
|
|
'updated_at' => '',
|
|
'deleted_at' => '',
|
|
];
|
|
|
|
return ['data_main' => $dataMain];
|
|
$dataMain = $data;
|
|
|
|
Db::beginTransaction();
|
|
try {
|
|
|
|
// TODO 这个字段后续可能不用了,之前由达达订单号从前端传上来
|
|
$dataMain['order_num'] = 'o'.date('YmdHis').mt_rand(1000,9999);
|
|
|
|
// 计算当前订单可用红包优惠金额
|
|
$couponMoney = 0;
|
|
$receiveCouponIds = [];
|
|
if (isset($data['receive_coupon_ids'])&&$data['receive_coupon_ids']) {
|
|
$receiveCouponIds = explode(',', str_replace(',',',',$data['receive_coupon_ids']));
|
|
$couponMoney = $this->getCouponAmount($receiveCouponIds, $data['money'], $data['user_id'], $data['market_id']);
|
|
}
|
|
$dataMain['yhq_money2'] = $couponMoney;
|
|
|
|
// 获取分布式全局ID
|
|
$generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
|
|
$dataMain['global_order_id'] = $generator->generate();
|
|
|
|
// 店铺IDs
|
|
$dataMain['store_ids'] = '';
|
|
$storeList = json_decode(html_entity_decode($data['store_list']), true);
|
|
if (!is_array($storeList)||empty($storeList)) {
|
|
Db::rollBack();
|
|
return '订单中商品不存在或已失效';
|
|
}
|
|
|
|
// 获取商户IDs
|
|
foreach ($storeList as &$item) {
|
|
$dataMain['store_ids'] .= empty($dataMain['store_ids']) ? $item['store_id'] : ','.$item['store_id'];
|
|
}
|
|
|
|
// 主订单插入数据
|
|
$currentTime = time();
|
|
$dataMain['time'] = date('Y-m-d H:i:s', $currentTime);
|
|
$dataMain['time_add'] = $currentTime;
|
|
$dataMain['pay_time'] = '';
|
|
$dataMain['state'] = \App\Model\OrderMain::ORDER_STATE_UNPAY;
|
|
$dataMain['code'] = $dataMain['global_order_id'];
|
|
$dataMain['jj_note'] = '';
|
|
|
|
// 主订单模型保存
|
|
$orderMain = OrderMain::create($dataMain);
|
|
$orderMainId = $orderMain->id;
|
|
|
|
// 统计订单中所有店铺当日订单数,做店铺订单序号
|
|
$countsArr = \App\Model\Order::query()
|
|
->selectRaw('store_id, COUNT(*) AS count')
|
|
->whereIn('store_id', explode(',', $dataMain['store_ids']))
|
|
->where(['type' => OrderMain::ORDER_TYPE_ONLINE])
|
|
->whereBetween('time', [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')])
|
|
->groupBy('store_id')
|
|
->get()
|
|
->toArray();
|
|
|
|
$storeOrderCounts = [];
|
|
foreach ($countsArr as $key => &$row) {
|
|
$storeOrderCounts[$row['store_id']] = $row['count'];
|
|
}
|
|
|
|
// 循环处理订单总额、子订单总额、商品、商户订单等信息
|
|
$orderAmountTotal = 0; # 总订单金额
|
|
$orderGoods = [];
|
|
foreach ($storeList as $key => &$item) {
|
|
|
|
// 子订单数据处理
|
|
$dataChild = [
|
|
'uniacid' => $data['uniacid'],
|
|
'order_num' => 's'.date('YmdHis', time()) . rand(1111, 9999),
|
|
'user_id' => $orderMain->user_id,
|
|
'store_id' => $item['store_id'],
|
|
'order_main_id' => $orderMainId,
|
|
'state' => OrderMain::ORDER_STATE_UNPAY,
|
|
'tel' => $orderMain->tel,
|
|
'name' => $orderMain->name,
|
|
'address' => $orderMain->address,
|
|
'area' => $orderMain->area,
|
|
'time' => date("Y-m-d H:i:s"),
|
|
'note' => $item['note'] ?? '',
|
|
'delivery_time' => $orderMain->delivery_time,
|
|
'type' => $orderMain->type,
|
|
'lat' => $orderMain->lat,
|
|
'lng' => $orderMain->lng,
|
|
'pay_type' => $orderMain->pay_type,
|
|
'order_type' => $orderMain->order_type,
|
|
'money' => floatval($item['subtotal']),
|
|
'box_money' => floatval($item['box_money']),
|
|
'mj_money' => floatval($item['mj_money']),
|
|
'yhq_money' => floatval($item['yhq_money']),
|
|
'yhq_money2' => floatval($item['yhq_money2']),
|
|
'zk_money' => floatval($item['zk_money']),
|
|
'coupon_id' => $item['coupon_id'],
|
|
'coupon_id2' => $item['coupon_id2'],
|
|
'xyh_money' => floatval($item['xyh_money']),
|
|
'oid' => (isset($storeOrderCounts[$item['store_id']]) ? $item['store_id'] : 0) + 1,
|
|
'time_add' => date("Y-m-d H:i:s"),
|
|
'jj_note' => '',
|
|
'form_id' => '',
|
|
'form_id2' => '',
|
|
'code' => '',
|
|
];
|
|
|
|
$orderChildId = Order::query()->insertGetId($dataChild);
|
|
|
|
// 子订单内商品处理
|
|
$goodsAmountTotal = 0;
|
|
|
|
if (!is_array($item['good_list'])||empty($item['good_list'])) {
|
|
Db::rollBack();
|
|
return '订单商品异常';
|
|
}
|
|
foreach ($item['good_list'] as &$goods) {
|
|
$goodsAmount = bcadd(floatval($goods['money']), floatval($goods['box_money']));
|
|
$goodsAmount = bcmul($goodsAmount, $goods['num']);
|
|
$goodsAmountTotal = bcadd($goodsAmountTotal, $goodsAmount);
|
|
|
|
$orderGoods[$goods['id']] = $goods;
|
|
$orderGoods[$goods['id']]['uniacid'] = $data['uniacid'];
|
|
$orderGoods[$goods['id']]['order_id'] = $orderChildId;
|
|
$orderGoods[$goods['id']]['user_id'] = $dataMain['user_id'];
|
|
$orderGoods[$goods['id']]['store_id'] = $item['store_id'];
|
|
}
|
|
|
|
// 子订单优惠总额
|
|
$discountAmountTotal = bcadd($dataChild['mj_money'], $dataChild['yhq_money']);
|
|
$discountAmountTotal = bcadd($discountAmountTotal, $dataChild['yhq_money2']);
|
|
$discountAmountTotal = bcadd($discountAmountTotal, $dataChild['zk_money']);
|
|
$discountAmountTotal = bcadd($discountAmountTotal, $dataChild['xyh_money']);
|
|
|
|
$goodsAmountTotal = bcsub($goodsAmountTotal, $discountAmountTotal, 2);
|
|
$orderAmountTotal = bcadd($orderAmountTotal, $goodsAmountTotal, 2);
|
|
|
|
// 校验子订单金额
|
|
if ($goodsAmountTotal != $dataChild['money']) {
|
|
Db::rollBack();
|
|
return '店铺订单总金额错误';
|
|
}
|
|
|
|
}
|
|
|
|
// 校验库存
|
|
foreach ($orderGoods as $Key => &$goodsItem) {
|
|
|
|
$goodsItem['combination_id'] = intval($goodsItem['combination_id']);
|
|
|
|
// 存在规格,则去规格处查库存
|
|
$goods = [];
|
|
if ($goodsItem['combination_id'] > 0) {
|
|
|
|
$combination = SpecCombination::query()
|
|
->select(['good_id AS id', 'number AS inventory'])
|
|
->where(['id' => $goodsItem['combination_id']])
|
|
->first()
|
|
->toArray();
|
|
|
|
$goods = Goods::query()
|
|
->select(['id', 'name', 'is_max'])
|
|
->where(['id' => $combination['id']])
|
|
->first()
|
|
->toArray();
|
|
$goods['inventory'] = $combination['inventory'];
|
|
|
|
} else {
|
|
|
|
$goods = Goods::query()
|
|
->select(['id', 'name', 'is_max', 'inventory'])
|
|
->where(['id' => $goodsItem['good_id']])
|
|
->first()
|
|
->toArray();
|
|
|
|
}
|
|
|
|
if (!$goods) {
|
|
Db::rollBack();
|
|
return '缺少商品';
|
|
}
|
|
|
|
if($goodsItem['num'] > $goods['inventory'] && $goods['is_max'] != Goods::INVENTORY_NOLIMIT){
|
|
Db::rollBack();
|
|
return '商品 '.$goods->name.' 库存不足!';
|
|
}
|
|
|
|
}
|
|
|
|
// 校验总订单金额
|
|
$deliveryAmount = 0; # 配送费用
|
|
if($dataMain['order_type'] == OrderMain::ORDER_TYPE_ONLINE){
|
|
$deliveryAmount = $dataMain['dada_fee'];
|
|
}
|
|
|
|
$orderAmountTotal = bcadd($orderAmountTotal, $deliveryAmount);
|
|
# 总订单优惠总额
|
|
$discountAmountTotal = bcadd($dataMain['mj_money'], $dataMain['yhq_money']);
|
|
$discountAmountTotal = bcadd($discountAmountTotal, $dataMain['yhq_money2']);
|
|
$discountAmountTotal = bcadd($discountAmountTotal, $dataMain['zk_money']);
|
|
$discountAmountTotal = bcadd($discountAmountTotal, $dataMain['xyh_money']);
|
|
$orderAmountTotal = bcsub($orderAmountTotal, $discountAmountTotal, 2);
|
|
|
|
if ($orderAmountTotal != bcsub(bcadd($dataMain['money'], $deliveryAmount), $discountAmountTotal, 2)) {
|
|
Db::rollBack();
|
|
return '订单总金额错误';
|
|
}
|
|
|
|
// 添加订单商品
|
|
$tempGoods = $orderGoods;
|
|
$orderGoods = [];
|
|
foreach ($tempGoods as $key => &$value) {
|
|
$goodsTemp['good_id'] = $value['good_id'];
|
|
$goodsTemp['img'] = $value['logo'];
|
|
$goodsTemp['number'] = $value['num'];
|
|
$goodsTemp['order_id'] = $value['order_id'];
|
|
$goodsTemp['name'] = $value['name'];
|
|
$goodsTemp['money'] = $value['money'];
|
|
$goodsTemp['dishes_id'] = $value['dishes_id'];
|
|
$goodsTemp['spec'] = $value['spec'];
|
|
$goodsTemp['is_qg'] = $value['is_qg'];
|
|
$goodsTemp['good_unit'] = $value['good_unit'];
|
|
$goodsTemp['uniacid'] = $value['uniacid'];
|
|
$goodsTemp['combination_id'] = $value['combination_id'];
|
|
$orderGoods[] = $goodsTemp;
|
|
}
|
|
|
|
$addOrderGoods = OrderGoods::query()->insert($orderGoods);
|
|
if (!$addOrderGoods) {
|
|
Db::rollBack();
|
|
return '订单商品异常';
|
|
}
|
|
//判断是否有购买多个特价商品
|
|
$result = $this->purchaseLimitService->PurchaseLimit($orderGoods);
|
|
if(!$result){
|
|
Db::rollBack();
|
|
return '同一个订单不能购买多个特价商品';
|
|
}
|
|
|
|
//判断是否有购买特价商品
|
|
$this->purchaseLimitService->ssdbPurchaseRecord($orderGoods,$data['user_id'],$dataMain['global_order_id']);
|
|
|
|
// 修改总订单金额,金额是计算来的
|
|
// TODO 这部分其实可以结合处理优化一下,循环前后关联处理太多
|
|
$updateOrderMain = OrderMain::query()->where(['id' => $orderMainId])->update(['money' => $orderAmountTotal, 'total_money' => $dataMain['money']]);
|
|
if (!$updateOrderMain) {
|
|
Db::rollBack();
|
|
return '订单总金额记录失败';
|
|
}
|
|
|
|
// 处理红包的使用
|
|
$canUseCoupons = CouponRec::select(['id', 'user_id', 'number', 'number_remain', 'system_coupon_user_id'])
|
|
->whereIn('id', $receiveCouponIds)
|
|
->get()->toArray();
|
|
if (is_array($canUseCoupons)&&!empty($canUseCoupons)) {
|
|
# 使用记录、更新当前优惠券
|
|
foreach ($canUseCoupons as $key => &$coupon) {
|
|
|
|
$couponUse = [
|
|
'user_id' => $coupon['user_id'],
|
|
'user_receive_id' => $coupon['id'],
|
|
'system_coupon_id' => $coupon['system_coupon_user_id'],
|
|
'order_main_id' => $orderMainId,
|
|
'use_time' => $currentTime,
|
|
'return_time' => 0,
|
|
'number' => 1,
|
|
'status' => 1,
|
|
'update_time' => 0,
|
|
];
|
|
|
|
$insertRes = CouponUserUse::query()->insert($couponUse);
|
|
|
|
if ($insertRes) {
|
|
$numberRemain = $coupon['number_remain'] - 1;
|
|
if ($numberRemain == 0) {
|
|
$status = 2;
|
|
} elseif ($numberRemain > 0 && $numberRemain < $coupon['number']) {
|
|
$status = 1;
|
|
} elseif ($numberRemain == $coupon['number']) {
|
|
$status = 0;
|
|
}
|
|
|
|
$upRes = CouponRec::query()->where(['id' => $coupon['id']])->update(['number_remain' => $numberRemain, 'status' => $status]);
|
|
|
|
if (!$upRes) {
|
|
Db::rollBack();
|
|
return '优惠券使用失败';
|
|
}
|
|
|
|
// 缓存使用记录
|
|
$usedRes = $this->couponService->cacheTodayCouponUsed($coupon['user_id'], $coupon['system_coupon_user_id'], $coupon['id']);
|
|
if (!$usedRes) {
|
|
Db::rollBack();
|
|
return '优惠券使用失败';
|
|
}
|
|
|
|
} else {
|
|
Db::rollBack();
|
|
return '优惠券使用失败';
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
Db::commit();
|
|
return $orderMainId;
|
|
|
|
} catch (Exception $e) {
|
|
|
|
$this->log->event(
|
|
LogLabel::ORDER_LOG,
|
|
['message' => $e->getMessage()]
|
|
);
|
|
|
|
Db::rollBack();
|
|
return $e->getMessage();
|
|
|
|
}
|
|
}
|
|
|
|
public function check()
|
|
{
|
|
// TODO: Implement check() method.
|
|
}
|
|
|
|
public function undo()
|
|
{
|
|
// TODO: Implement undo() method.
|
|
}
|
|
|
|
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];
|
|
}
|
|
}
|