diff --git a/app/Constants/v3/SmsTemplateCode.php b/app/Constants/v3/SmsTemplateCode.php index 3a2b1d1..e616f83 100644 --- a/app/Constants/v3/SmsTemplateCode.php +++ b/app/Constants/v3/SmsTemplateCode.php @@ -13,5 +13,5 @@ class SmsTemplateCode extends AbstractConstants /** * @Message("短信验证码") */ - const ALI_VERIFY_CODE = 'SMS_200690862'; + const ALI_VERIFY_CODE = 'SMS_201650612'; } \ No newline at end of file diff --git a/app/Controller/v3/OrderOnlineController.php b/app/Controller/v3/OrderOnlineController.php index 95a1cd6..74ad680 100644 --- a/app/Controller/v3/OrderOnlineController.php +++ b/app/Controller/v3/OrderOnlineController.php @@ -6,6 +6,7 @@ use App\Constants\v3\ErrorCode; use App\Controller\BaseController; use App\Exception\ErrorCodeException; use App\Request\v3\OrderOnlineDetailRequest; +use App\Request\v3\OrderOnlineRequest; use App\Service\CouponServiceInterface; use Hyperf\Di\Annotation\Inject; use App\Service\v3\Interfaces\OrderOnlineServiceInterface; @@ -136,4 +137,32 @@ class OrderOnlineController extends BaseController $params = $request->validated(); return $this->success(['detail' => $this->orderOnlineService->detailByUser($params['order_id'], $params['user_id'])]); } + + /** + * 下单并进行支付,返回支付参数 + * 1、用户传参,用户地址ID,用于获取用户地址经纬度来计算配送费 + * 2、用户传参,购物车IDs,去获取购物车里的商品详情 + * 3、预约送达时间 + * 4、优惠券IDs + * 5、订单总金额,用于校验比对 + * 6、下单成功,请求支付 + * @param OrderOnlineRequest $request + * @return ResponseInterface + */ + public function add(OrderOnlineRequest $request){ + + // 下单 + $params = $request->validated(); + $data = $this->orderOnlineService->do( + $params['market_id'], + $params['user_id'], + $params['user_address_id'], + explode(',', $params['cart_ids']), + $params['total_money'], + $params['delivery_time_note'], + explode(',', $params['coupon_ids']) + ); + + return $this->success(['data' => $data]); + } } \ No newline at end of file diff --git a/app/Model/v3/Coupon.php b/app/Model/v3/Coupon.php new file mode 100644 index 0000000..931abac --- /dev/null +++ b/app/Model/v3/Coupon.php @@ -0,0 +1,14 @@ +hasOne('App\Models\CouponUser','id','system_coupon_user_id'); + } +} diff --git a/app/Model/v3/ShoppingCart.php b/app/Model/v3/ShoppingCart.php index 1ae9403..958ecec 100644 --- a/app/Model/v3/ShoppingCart.php +++ b/app/Model/v3/ShoppingCart.php @@ -1,13 +1,14 @@ 'array' + ]; +} \ No newline at end of file diff --git a/app/Request/v3/OrderOnlineRequest.php b/app/Request/v3/OrderOnlineRequest.php new file mode 100644 index 0000000..1e9a36d --- /dev/null +++ b/app/Request/v3/OrderOnlineRequest.php @@ -0,0 +1,48 @@ + 'required|nonempty|integer', + 'user_id' => 'required|nonempty|integer', + 'user_address_id' => 'required|nonempty|integer', + 'cart_ids' => 'required|nonempty', + 'delivery_time_note' => 'required|nonempty', + 'total_money' => 'required|nonempty', + 'coupon_ids' => 'nonempty', + ]; + } + + public function messages(): array + { + return [ + '*.*' => ':attribute 参数异常' + ]; + } + + public function attributes(): array + { + return [ + + ]; + } +} diff --git a/app/Service/v3/Implementations/DeliveryMoneyService.php b/app/Service/v3/Implementations/DeliveryMoneyService.php new file mode 100644 index 0000000..fc97aed --- /dev/null +++ b/app/Service/v3/Implementations/DeliveryMoneyService.php @@ -0,0 +1,24 @@ +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() diff --git a/app/Service/v3/Implementations/SmsAliSendService.php b/app/Service/v3/Implementations/SmsAliSendService.php index a6cd9ac..81929d1 100644 --- a/app/Service/v3/Implementations/SmsAliSendService.php +++ b/app/Service/v3/Implementations/SmsAliSendService.php @@ -72,7 +72,7 @@ class SmsAliSendService implements SmsSendServiceInterface public function doVerifyCode($tel, $code) { - $params = ['user_name' => '疯狂的水叔叔', 'market_name' => '验证码', 'money' => $code]; + $params = ['code' => $code]; return $this->do($tel, SmsTemplateCode::ALI_VERIFY_CODE, json_encode($params)); } diff --git a/app/Service/v3/Interfaces/DeliveryMoneyServiceInterface.php b/app/Service/v3/Interfaces/DeliveryMoneyServiceInterface.php new file mode 100644 index 0000000..046a4df --- /dev/null +++ b/app/Service/v3/Interfaces/DeliveryMoneyServiceInterface.php @@ -0,0 +1,10 @@ + \App\Service\v3\Implementations\TabsService::class, \App\Service\v3\Interfaces\LocationServiceInterface::class => \App\Service\v3\Implementations\LocationService::class, \App\Service\v3\Interfaces\GoodsActivityServiceInterface::class => \App\Service\v3\Implementations\GoodsActivityService::class, + \App\Service\v3\Interfaces\DeliveryMoneyServiceInterface::class => \App\Service\v3\Implementations\DeliveryMoneyService::class, ]; diff --git a/config/routes.php b/config/routes.php index 9939e49..a7951ab 100644 --- a/config/routes.php +++ b/config/routes.php @@ -112,4 +112,5 @@ Router::addGroup('/v3/', function () { Router::post('home/storeIndex', 'App\Controller\v3\HomeController@storeIndex'); Router::post('orderList/onlineForStore', 'App\Controller\v3\OrderListController@onlineForStore'); Router::post('orderList/offlineForStore', 'App\Controller\v3\OrderListController@offlineForStore'); + Router::post('orderOnline/add', 'App\Controller\v3\OrderOnlineController@add'); },['middleware' => [\App\Middleware\Auth\ApiMiddleware::class, \App\Middleware\Auth\UserMiddleware::class]]); \ No newline at end of file