Explorar o código

卡订单发货

gorden hai 14 horas
pai
achega
d9c8047b7d

+ 543 - 57
app/admin/controller/order/CardController.php

@@ -2,6 +2,7 @@
 
 namespace app\admin\controller\order;
 
+use app\admin\service\coupon\CouponDetailService;
 use app\admin\service\coupon\CouponService;
 use app\admin\service\member\MemberService;
 use app\admin\service\order\OrderService;
@@ -10,6 +11,7 @@ use app\admin\service\order\PayDetailService;
 use app\admin\validate\order\OrderValidate;
 use app\controller\Curd;
 use app\model\Appointment;
+use app\model\Card;
 use app\model\ClientConfig;
 use app\model\Coupon;
 use app\model\Goods;
@@ -30,6 +32,7 @@ use app\model\SysDept;
 use app\model\SysUser;
 use support\Db;
 use support\exception\BusinessException;
+use support\Log;
 use support\Redis;
 use support\Request;
 use support\Response;
@@ -204,15 +207,229 @@ class CardController extends Curd
         return $items;
     }
 
+    /**
+     * @Desc 获取卡列表
+     * @Author Gorden
+     * @Date 2024/11/22 15:33
+     *
+     * @param Request $request
+     * @return Response
+     */
+    public function getCardList(Request $request)
+    {
+        $orderId = $request->get('order_id');
+        $goodsId = OrderSheet::where('join_sheet_order_id', $orderId)->value('join_sheet_goods_id');
+        $goods = Goods::where('goods_id', $goodsId)->select('goods_attribute_json')->first();
+        $cards = [];
+        if (!empty($goods->goods_attribute_json)) {
+            $goodsAttributeJson = json_decode($goods->goods_attribute_json, true);
+            if (!empty($goodsAttributeJson['card_main_id'])) {
+                $cards = Card::where('join_card_main_id', $goodsAttributeJson['card_main_id'])
+                    ->where('card_status', 'WAITING')
+                    ->where('is_issue', 'Y')
+                    ->pluck('card_id')
+                    ->toArray();
+            }
+        }
+
+        return json_success('success', $cards);
+    }
+
     /**
      * @Desc 下单+支付
      * @Author Gorden
-     * @Date 2024/9/5 13:13
+     * @Date 2024/9/23 16:15
      *
      * @param Request $request
      * @return Response
      */
     public function insert(Request $request): Response
+    {
+        $params = $request->post();
+        // 判断餐品是否连带着服务或实体
+        $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
+        $premises = [];
+        if (!empty($params['dept_premises_id'])) {
+            $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
+        }
+        try {
+            // 下单账户
+            if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
+                if (Member::where('member_mobile', $params['mobile'])->exists()) {
+                    throw new BusinessException('会员已存在');
+                }
+                $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
+                // 创建会员
+                MemberService::createMember($params);
+
+            } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
+                $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
+            }
+            if (empty($params['join_order_member_id'])) {
+                throw new BusinessException('检查下单账户');
+            }
+            // 带着优惠券,要发券
+            if (!empty($params['custom_member_id'])) {
+                // 把券从000000加到真实账户
+                CouponDetailService::transCoupon('000000', $params['join_order_member_id']);
+            }
+        } catch (BusinessException $e) {
+            Log::error('创建订单失败', ['msg' => $e->getMessage()]);
+            _syslog("订单", $e->getMessage());
+            return json_fail($e->getMessage());
+        } catch (\Exception $e) {
+            Log::error('创建订单失败', ['msg' => $e->getMessage()]);
+            _syslog("订单", "创建订单失败");
+            return json_fail('创建订单失败');
+        }
+        $params['goods_classify'] = $goodsClassifys[0];
+        Db::beginTransaction();
+        try {
+            // 使用优惠券
+            $couponUseJson = [];
+            if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
+                $couponResult = OrderService::payUseCoupon('insert', $params['settlement_now'], $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
+                if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
+                    throw new BusinessException("计算优惠后,实付金额错误!");
+                }
+                // 组装优惠券使用数据,存主表优惠里
+                if (!empty($couponResult['use_coupon_json'])) {
+                    $couponUseJson = $couponResult['use_coupon_json'];
+                }
+            }
+            // 存储优惠信息
+            $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));
+            // 验证库存
+            foreach ($params['goodsContentList'] as $goods) {
+                $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
+                dump($goodsRunning);
+                $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
+                if ($goodsRunning->goods_running_storage < 0) {
+                    throw new BusinessException('库存不足');
+                }
+            }
+            // 验证线下付款密码
+            if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
+                $password = $params['offline_password'];
+                if ($password != '666888') {
+                    throw new BusinessException('密码错误,请重新输入');
+                }
+            }
+
+            $qrcodePayAmount = 0;
+            $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
+            $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
+
+            $systemStatus = 'SENDING';  // 待发货
+            if ($params['settlement_now'] == 'Y' && ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY')) {
+                if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
+                    $params['pay_category'] = $params['pay_category_sub'];
+                }
+                $params['order_status_system'] = $systemStatus;
+                $params['order_status_payment'] = 'SUCCESS';
+            }
+            if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])) {     // 付款码
+                if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount <= 0) {
+                    $params['order_status_system'] = $systemStatus;
+                    $params['order_status_payment'] = 'SUCCESS';
+                }
+                // 不组合或者组合后需要付款码的金额>0
+                if ($params['pay_constitute'] == 'N' || ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0)) {
+                    $result = OrderService::qrcodePay($params);
+                    $result = json_encode($result);
+                    $params['pay_json_response'] = $result;
+                    $result = json_decode($result, true);
+
+                    $prefix = substr($params['qrcode_nbr'], 0, 2);
+                    if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
+                        $params['pay_category'] = 'WXPAY';
+                        if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {
+                            $params['order_status_system'] = 'PAYING';
+                            $params['order_status_payment'] = 'PENDING';
+                            $params['order_is_complete'] = 'N';
+                        } else {
+                            $params['order_status_system'] = $systemStatus;
+                            $params['order_status_payment'] = 'SUCCESS';
+                        }
+                    } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
+                        $params['pay_category'] = 'ALIPAY';
+                        if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
+                            $params['order_status_system'] = 'PAYING';
+                            $params['order_status_payment'] = 'PENDING';
+                            $params['order_is_complete'] = 'N';
+                        } else {
+                            $params['order_status_system'] = $systemStatus;
+                            $params['order_status_payment'] = 'SUCCESS';
+                        }
+                    } else {
+                        throw new BusinessException('付款码无效');
+                    }
+                }
+            }
+
+            $orderConfigJson = [];
+            // 优惠
+            if (!empty($params['preferential'])) {
+                $orderConfigJson['preferential'] = $params['preferential'];
+            }
+
+            // 配送方式
+            if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店
+                $orderConfigJson['premises'] = $params['dept_premises_id'];
+            }
+
+            if (isset($params['delivery']) && in_array($params['delivery'], ['PICKUP', 'ARRIVAL']) && !empty($params['dept_premises_id'])) {
+                $params['submit_premises_id'] = $premises->dept_id;
+            }
+
+            $params['order_config_json'] = json_encode($orderConfigJson);
+            // 写入订单
+            $this->insertMain($params);
+
+            Db::commit();
+
+            // 触发事件
+            if (!empty($params['order_is_complete']) && $params['order_is_complete'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
+                Event::dispatch('order.complete', $params);
+            }
+            // 触发事件
+            if ($params['order_status_payment'] == 'SUCCESS') {
+                // 上级提成
+                OrderService::splitOrderCommission($params);
+                // 入收支明细表
+                $params['inout_category'] = '购买储值卡';
+                Event::dispatch('statistics.inout.in', $params);
+            }
+
+            if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
+                _syslog("订单", "支付异常,检查是否有轮询");
+
+                return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
+            }
+            _syslog("订单", "创建订单成功");
+            return json_success('创建订单成功');
+        } catch (BusinessException $e) {
+            Db::rollBack();
+            Log::error('创建订单失败', ['msg' => $e->getMessage()]);
+            _syslog("订单", $e->getMessage());
+            return json_fail($e->getMessage());
+        } catch (\Exception $e) {
+            Db::rollBack();
+            Log::error('创建订单失败', ['msg' => $e->getMessage()]);
+            _syslog("订单", "创建订单失败");
+            return json_fail('创建订单失败');
+        }
+    }
+
+    /**
+     * @Desc 下单+支付
+     * @Author Gorden
+     * @Date 2024/9/5 13:13
+     *
+     * @param Request $request
+     * @return Response
+     */
+    public function inserts(Request $request): Response
     {
         $params = $request->post();
         // 判断餐品是否连带着服务或实体
@@ -300,31 +517,22 @@ class CardController extends Curd
                     throw new BusinessException('付款码无效');
                 }
             }
+            // 配送方式
+            if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店
+                $orderConfigJson['premises'] = $params['dept_premises_id'];
+            }
 
-            if (empty($paidOrder)) {
-                $params['order_extend_json'] = $orderExtendJson;
-                // 写入主订单
-                $this->insertMain($params);
-                // 订单详情
-                $this->insertSheet($params);
-            } else {
-                $params['orderGroupId'] = $paidOrder->order_groupby;
-                if ($params['order_status_payment'] == 'SUCCESS') {
-                    $params['order_amount_paid'] = $paidOrder->order_amount_paid;
-                    $paidOrder->order_amount_paid = $paidOrder->order_amount_paid + $params['order_amount_pay'];
-                    $paidOrder->order_amount_pay = $paidOrder->order_amount_paid;
-                    if (floatval($paidOrder->order_amount_paid) >= $paidOrder->order_amount_total) {
-                        $paidOrder->order_is_complete = 'Y';
-                        $paidOrder->order_status_system = 'DONE';
-                        $paidOrder->order_status_payment = 'SUCCESS';
-                        // 更新sheet
-                        OrderSheet::where('join_sheet_order_id', $paidOrder->order_id)->update(['order_sheet_status' => 'DONE']);
-                    }
-                }
-                $paidOrder->save();
-                // 清除此订单的未支付记录
-                PayDetail::whereJsonContains('join_pay_object_json->order_id', $paidOrder->order_id)->where('pay_status', 'WAITING')->delete();
+            if (isset($params['delivery']) && in_array($params['delivery'], ['PICKUP', 'ARRIVAL']) && !empty($params['dept_premises_id'])) {
+                $params['submit_premises_id'] = $premises->dept_id;
             }
+
+            $params['order_config_json'] = json_encode($orderConfigJson);
+
+            $params['order_extend_json'] = $orderExtendJson;
+            // 写入主订单
+            $this->insertMain($params);
+            // 订单详情
+            $this->insertSheet($params);
             // 支付记录
             $this->insertPayDetail($params);
             Db::commit();
@@ -584,6 +792,7 @@ class CardController extends Curd
         }
     }
 
+
     /**
      * @Desc
      * @Author Gorden
@@ -593,17 +802,9 @@ class CardController extends Curd
      * @return void
      * @throws BusinessException
      */
-    public function insertMain($params)
+    public function insertMain($params, $wxAndAliPayStatus = 'Y')
     {
         try {
-            $orderCategory = 'NORMAL';
-            if (!empty($params['order_category'])) {
-                $orderCategory = $params['order_category'];
-            } else if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
-                $orderCategory = 'DISHES';
-            } else if (isset($params['goods_classify'])) {
-                $orderCategory = $params['goods_classify'];
-            }
             if (empty($params['order_extend_json'])) {
                 $params['order_extend_json'] = [];
             } else {
@@ -611,34 +812,70 @@ class CardController extends Curd
                     $params['order_extend_json'] = json_decode($params['order_extend_json'], true);
                 }
             }
+            // 账户扣款
+            if ($wxAndAliPayStatus == 'Y' && !empty($params['waitToPayAccount'])) {
+                foreach ($params['waitToPayAccount'] as $account) {
+                    $this->deductAmount($account['nbr'], $account['amount']);
+                }
+            }
             // 推荐人
             $params['order_extend_json']['referee'] = $params['referee'] ?? '';
+            $orderAmount = [];
+            foreach ($params['goodsContentList'] as $goods) {
+                $amountPay = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $params['order_amount_total']) * $params['order_amount_pay'], 2);
+                $discountJson = [];
+                if (!empty($params['order_discount_json'])) {
+                    $discountJson = json_decode($params['order_discount_json'], true);
+                    foreach ($discountJson as &$item) {
+                        if (!empty($item['coupon_id'])) {
+                            $orderAmount = OrderService::countAndAmount($params['goodsContentList'], $item['coupon_id']);
+                            $payAmountUseCoupon = $params['order_amount_pay'] - ($params['order_amount_total'] - $orderAmount['amount']);
+                            if (in_array($goods['goods_id'], $orderAmount['goodsIds'])) {
+                                $amountPay = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $orderAmount['amount']) * $payAmountUseCoupon, 2);
+                            }
+                        } else {
+                            $orderAmount['amount'] = $params['order_amount_total'];
+                            $amountPay = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $params['order_amount_total']) * $params['order_amount_pay'], 2);
+                        }
+                        if (!empty($item['coupon_value'])) {
+                            $item['coupon_value'] = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $orderAmount['amount']) * $item['coupon_value'], 2);
+                        }
+                    }
+                }
+                $orderId = 'OD' . date('ymdHi') . random_string(4, 'up');
+                $data = [
+                    'order_id' => $orderId,
+                    'order_groupby' => $params['orderGroupId'],
+                    'join_order_member_id' => $params['join_order_member_id'],
+                    'order_name' => date('Y-m-d H:i:s') . '-订单',
+                    'order_amount_total' => floatval($goods['goods_sales_price']) * $goods['nbr'],
+                    'order_amount_pay' => $amountPay,
+                    'order_category' => $goods['goods_classify'],
+                    'order_classify' => $goods['goods_classify'],
+                    'order_is_complete' => $params['order_is_complete'] ?? 'N',
+                    'order_status_system' => $params['order_status_system'],
+                    'order_status_payment' => $params['order_status_payment'],
+                    'order_status_storage' => $params['order_status_storage'],
+                    'order_platform' => $params['order_platform'],
+                    'order_remark' => $params['order_remark'] ?? '',
+                    'order_discount_json' => (!empty($orderAmount['goodsIds']) && in_array($goods['goods_id'], $orderAmount['goodsIds'])) || (empty($orderAmount['goodsIds']) && !empty($orderAmount['amount'])) ? json_encode($discountJson) : '[]',
+                    'order_config_json' => $params['order_config_json'] ?? '[]',
+                    'order_express_json' => $params['order_express_json'] ?? '[]',
+                    'order_extend_json' => $params['order_extend_json'] ? json_encode($params['order_extend_json']) : '[]',
+                    'order_addtimes' => time(),
+                    'order_add_user_id' => JwtToken::getCurrentId()
+                ];
 
-            $data = [
-                'order_id' => $params['orderId'],
-                'order_groupby' => $params['orderGroupId'],
-                'join_order_member_id' => $params['join_order_member_id'],
-                'order_name' => date('Y-m-d H:i:s') . '-订单',
-                'order_amount_total' => $params['order_amount_total'],
-                'order_amount_pay' => $params['order_status_payment'] == 'SUCCESS' ? $params['order_amount_pay'] : 0,
-                'order_amount_paid' => $params['order_status_payment'] == 'SUCCESS' ? $params['order_amount_pay'] : 0,
-                'order_category' => $orderCategory,
-                'order_classify' => $orderCategory,
-                'order_is_complete' => floatval($params['order_amount_pay']) >= floatval($params['order_amount_total']) && $params['order_status_payment'] == 'SUCCESS' ? 'Y' : 'N',
-                'order_status_system' => floatval($params['order_amount_pay']) >= floatval($params['order_amount_total']) && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
-                'order_status_payment' => floatval($params['order_amount_pay']) >= floatval($params['order_amount_total']) && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'PENDING',
-                'order_status_storage' => $params['order_status_storage'],
-                'order_platform' => $params['order_platform'],
-                'order_remark' => $params['order_remark'] ?? '',
-                'order_discount_json' => $params['order_discount_json'] ?? '[]',
-                'order_config_json' => $params['order_config_json'] ?? '[]',
-                'order_express_json' => $params['order_express_json'] ?? '[]',
-                'order_extend_json' => $params['order_extend_json'] ? json_encode($params['order_extend_json']) : '[]',
-                'order_addtimes' => time(),
-                'order_add_user_id'=>JwtToken::getCurrentId()
-            ];
+                Order::insert($data);
+
+                $sheetIds = $this->insertSheetOne($params, $goods, $orderId, $amountPay);
+
+                $this->insertPayDetailOne($params, $orderId, $amountPay, $goods);
+
+                $params['order_express_goods'] = json_encode(['sheet' => $sheetIds]);
 
-            Order::insert($data);
+                $this->insertExpressOne($params, $orderId);
+            }
         } catch (\Exception $e) {
             dump($e->getMessage());
             throw new BusinessException('订单创建信息失败');
@@ -1238,4 +1475,253 @@ class CardController extends Curd
             return json_fail('查询失败');
         }
     }
+
+    /**
+     * @Desc 单条入库
+     * @Author Gorden
+     * @Date 2024/9/23 10:19
+     *
+     * @param $params
+     * @return array
+     * @throws BusinessException
+     */
+    public function insertSheetOne($params, $goods, $orderId, $amountPay)
+    {
+        try {
+            $orderSheetIds = [];
+//            foreach ($params['goodsContentList'] as $goods) {
+            //{"unit": "份", "table": null, "premises": "15"}
+            $price = floatval($goods['goods_sales_price']);
+            $extendJson['unit'] = $goods['sku_name'];
+            if (isset($params['submit_premises_id'])) {
+                $extendJson['premises'] = $params['submit_premises_id'];
+            }
+            if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
+                $extendJson['table'] = null;
+            }
+            $data = [
+                'join_sheet_member_id' => $params['join_order_member_id'],
+                'join_sheet_order_id' => $orderId,
+                'join_sheet_goods_id' => $goods['goods_id'],
+                'join_sheet_goods_sku_id' => $goods['sku_id'],
+                'order_sheet_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
+                'order_sheet_category' => (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') ? 'DISHES' : 'NORMAL',
+                'order_sheet_num' => $goods['nbr'],
+                'order_sheet_price' => $goods['goods_sales_price'],
+                'order_sheet_price_pay' => round($amountPay / $goods['nbr'], 2),
+                'order_sheet_amount' => $price * $goods['nbr'],
+                'order_sheet_pay' => $amountPay,
+                'order_sheet_task_status' => 'NONE',
+                'order_sheet_remark' => $params['order_remark'] ?? '',
+                'order_sheet_addtimes' => time(),
+                'order_sheet_extend_json' => json_encode($extendJson)
+            ];
+
+            $orderSheetId = OrderSheet::insertGetId($data);
+            $orderSheetIds[] = $orderSheetId;
+
+            // 减库存,规格和总库存
+            $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
+            $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
+            if ($goodsRunning->goods_running_storage < 0) {
+                throw new BusinessException('库存不足');
+            }
+            if ($params['order_status_payment'] == 'SUCCESS') {
+                $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
+            }
+            $goodsRunning->save();
+//            }
+            return $orderSheetIds;
+        } catch (\support\exception\BusinessException $e) {
+            dump($e->getMessage() . '||' . $e->getLine());
+            throw new BusinessException($e->getMessage());
+        } catch (\Exception $e) {
+            dump($e->getMessage() . '||' . $e->getLine());
+            throw new BusinessException('订单创建失败');
+        }
+    }
+
+    public function saveExpress($params, $orderId)
+    {
+        try {
+            $express = new OrderExpress();
+            $express->order_express_type = $params['order_express_type'];
+            $express->join_express_order_id = $orderId;
+            $express->join_express_dept_id = $params['submit_premises_id'] ?? 0;
+            $express->order_express_goods = $params['order_express_goods'];
+            $express->order_express_city = $params['order_express_city'];
+            $express->order_express_address = $params['order_express_address'];
+            $express->order_express_mobile = $params['order_express_mobile'] ?? '';
+            $express->order_express_telephone = $params['order_express_telephone'] ?? '';
+            $express->order_express_person = $params['order_express_person'] ?? '';
+            $express->order_express_company = $params['dept_premises_id'] ?? '';
+            $express->order_express_extend_json = $params['order_express_extend_json'] ?? '[]';
+            $express->order_express_addtimes = time();
+            $express->save();
+        } catch (\Exception $e) {
+            dump($e->getMessage());
+            throw new BusinessException('物流信息保存失败');
+        }
+    }
+
+
+    /**
+     * @Desc 单条入库
+     * @Author Gorden
+     * @Date 2024/6/7 10:35
+     *
+     * @param $params
+     * @return void
+     * @throws BusinessException
+     */
+    public function insertPayDetailOne($params, $orderId, $amountPay, $goods)
+    {
+        try {
+            if (!empty($params['pay_detail_item'])) {
+                foreach ($params['pay_detail_item'] as $item) {
+                    $data = [
+                        'join_pay_member_id' => $item['join_order_member_id'],
+                        'join_pay_order_id' => $item['orderGroupId'],
+                        'pay_status' => $item['settlement_now'] == 'Y' && $item['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
+                        'pay_category' => $goods['goods_classify'],
+                        'pay_amount' => round(($amountPay / $params['order_amount_pay']) * $item['order_amount_pay'], 2),
+                        'pay_prepayid' => $item['pay_category'],
+                        'pay_paytimes' => date('Y-m-d H:i:s'),
+                        'join_pay_object_json' => !empty($item['orderId']) ? json_encode(['order_id' => $orderId]) : '[]',
+                        'pay_json_request' => json_encode($item),
+                        'pay_json_response' => $item['pay_json_response'] ?? '[]',
+                        'pay_remark' => $item['order_remark'] ?? '',
+                        'pay_addtimes' => time(),
+                    ];
+                    PayDetail::insert($data);
+                }
+            } else {
+                if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
+                    $payPrepayid = $params['pay_category'];
+                } else if ($params['pay_category'] == 'OFFLINE') {
+                    $payPrepayid = 'OFFLINE';
+                } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
+                    $payPrepayid = 'OFFLINE_ALIPAY';
+                } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
+                    $payPrepayid = 'OFFLINE_WXPAY';
+                } else if ($params['pay_category'] == 'MONEY') {
+                    $payPrepayid = 'MONEY';
+                } else if ($params['pay_category'] == 'CARD') {
+                    $payPrepayid = $params['card_id'];
+                } else {
+                    $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
+                }
+                $data = [
+                    'join_pay_member_id' => $params['join_order_member_id'],
+                    'join_pay_order_id' => $params['orderGroupId'],
+                    'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
+                    'pay_category' => $goods['goods_classify'],
+                    'pay_amount' => $amountPay,
+                    'pay_prepayid' => $payPrepayid,
+                    'pay_paytimes' => date('Y-m-d H:i:s'),
+                    'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $orderId]) : '[]',
+                    'pay_json_request' => json_encode($params),
+                    'pay_json_response' => $params['pay_json_response'] ?? '[]',
+                    'pay_remark' => $params['order_remark'] ?? '',
+                    'pay_addtimes' => time(),
+                ];
+
+                PayDetail::insert($data);
+            }
+        } catch (\Exception $e) {
+            dump($e->getMessage());
+            throw new BusinessException('创建支付记录失败');
+        }
+    }
+
+    /**
+     * @Desc 入配送记录
+     * @Author Gorden
+     * @Date 2024/9/23 10:45
+     *
+     * @param $params
+     * @return void
+     * @throws BusinessException
+     */
+    public function insertExpressOne($params, $orderId)
+    {
+        if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {
+            $params['order_express_type'] = '配送';
+            // 入配送
+            $this->saveExpress($params, $orderId);
+        } else if (isset($params['delivery']) && $params['delivery'] == 'PICKUP') {
+            $params['order_express_type'] = '自提';
+            $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
+            if (!$premises) {
+                throw new BusinessException('自提门店不存在');
+            }
+
+            $params['order_express_city'] = $premises->dept_city;
+            $params['order_express_address'] = $premises->dept_address;
+            $params['order_express_telephone'] = $premises->dept_telephone;
+            $params['order_express_extend_json'] = json_encode(['pick_code' => random_string(4, 'number')]);
+
+            $this->saveExpress($params, $orderId);
+        } else if (isset($params['delivery']) && $params['delivery'] == 'ARRIVAL') {
+            $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
+            $params['order_express_type'] = '到店';
+            if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
+                $params['order_express_type'] = '堂食';
+            }
+            if (!$premises) {
+                throw new BusinessException('门店不存在');
+            }
+
+            $params['order_express_city'] = $premises->dept_city;
+            $params['order_express_address'] = $premises->dept_address;
+            $params['order_express_telephone'] = $premises->dept_telephone;
+
+            $this->saveExpress($params, $orderId);
+        }
+    }
+
+
+    private function discountRecord($orderDiscountJson, $params)
+    {
+        $json = [];
+        if (!empty($orderDiscountJson)) {
+            $json = json_decode($orderDiscountJson, true);
+        }
+        try {
+            if (!empty($params['preferential']) && in_array('wipe', $params['preferential'])) {
+                if (intval($params['order_amount_total'] / 10) * 10 != $params['order_amount_pay']) {
+                    throw new BusinessException("抹零后实际支付金额错误");
+                }
+                $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
+                $couponClassifyDesc = $couponClassify = '抹零';
+            } elseif (!empty($params['preferential']) && in_array('custom', $params['preferential'])) {
+                if (sprintf("%.2f", $params['order_amount_total'] - $params['order_discount_amount']) != sprintf("%.2f", $params['order_amount_pay'])) {
+                    throw new BusinessException("餐厅前台优惠后实际支付金额错误");
+                }
+                $couponClassifyDesc = $couponClassify = '餐厅前台优惠';
+            } else if (!empty($params['preferential']) && intval($params['preferential'][0]) < 100 && intval($params['preferential'][0]) >= 50) {
+                if (($params['order_amount_total'] * intval($params['preferential'][0])) / 100 != $params['order_amount_pay']) {
+                    throw new BusinessException("折扣后实际支付金额错误");
+                }
+                $couponClassify = '折扣';
+                $couponClassifyDesc = intval($params['preferential'][0]) / 10 . '折';
+                $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
+            } else {
+                return $json;
+            }
+            $json[date('Y-m-d H:i:s')] = [
+                'coupon_id' => $params['coupon_id'] ?? null,
+                'coupon_value' => $params['order_discount_amount'] ?? '',
+                'coupon_classify' => $couponClassify,
+                'coupon_detail_id' => [$couponClassifyDesc],
+                'coupon_classify_en' => $params['preferential']
+            ];
+            return $json;
+        } catch (BusinessException $e) {
+            throw new BusinessException($e->getMessage());
+        } catch (\Exception $e) {
+            dump($e->getMessage());
+            throw new BusinessException("优惠数据错误");
+        }
+    }
 }

+ 22 - 19
app/admin/controller/order/WholeController.php

@@ -16,6 +16,7 @@ use app\common\payment\AppUtil;
 use app\common\payment\Tlpay;
 use app\controller\Curd;
 use app\model\Appointment;
+use app\model\Card;
 use app\model\ClientConfig;
 use app\model\Coupon;
 use app\model\CouponDetail;
@@ -113,9 +114,9 @@ class WholeController extends Curd
             $todayTimeUnix = strtotime(date('Y-m-d') . ' 00:00:00');
             $groupIds = PayDetail::whereRaw('CAST(UNIX_TIMESTAMP(pay_paytimes) as SIGNED) > ? ', [$todayTimeUnix])
                 ->where(function ($query) {
-                    $query->where('pay_prepayid','like', '%CASH%')
-                        ->OrWhere('pay_prepayid','like', '%VIP%')
-                        ->orWhere('pay_prepayid','like', '%WELFARE%');
+                    $query->where('pay_prepayid', 'like', '%CASH%')
+                        ->OrWhere('pay_prepayid', 'like', '%VIP%')
+                        ->orWhere('pay_prepayid', 'like', '%WELFARE%');
                 })
                 ->where('join_pay_order_id', '<>', '')
                 ->whereIn('pay_category', ['GOODS', 'SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE', 'MEALS'])
@@ -3615,6 +3616,17 @@ class WholeController extends Curd
 
         Db::beginTransaction();
         try {
+            if (!empty($params['card_id'])) {
+                $card = Card::where('card_id', $params['card_id'])->first();
+                if (empty($card)) {
+                    throw new BusinessException("储值卡不存在");
+                }
+                if ($card->card_status != 'WAITING' || $card->is_issue != 'Y') {
+                    throw new BusinessException("储值卡状态异常");
+                }
+                $card->card_status = 'PENDING';
+                $card->save();
+            }
             $expressExtendJson = [];
             if ($params['express_type'] == '自提') {
                 $model = OrderExpress::where('join_express_order_id', $params['order_id'])->first();
@@ -3649,12 +3661,6 @@ class WholeController extends Curd
                     'order_sheet_status' => 'CONFIRM'
                 ];
 
-                // 7天后自动完成
-//                $redis = Redis::connection();
-//                $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd', strtotime("+7 days"));
-//                $redis->sadd($key, $params['order_id']);
-
-//                $model = new OrderExpress();
             } else {
                 $orderData = [
                     'order_status_system' => 'RECVING',
@@ -3672,15 +3678,6 @@ class WholeController extends Curd
                 $model = OrderExpress::where('join_express_order_id', $params['order_id'])->first();
                 if (!$model) {
                     $model = new OrderExpress();
-                    // $sheet = OrderSheet::where('join_sheet_order_id', $request->post('order_id'))
-                    //     ->select('join_sheet_goods_id')
-                    //     ->first();
-                    // if(!empty($sheet->order_sheet_extend_json)){
-                    //     $extendJson = json_decode($sheet->order_sheet_extend_json,true);
-                    //     $address = ClientConfig::where('client_config_id',$extendJson['address_id'])->first();
-                    //     $params['']
-                    // }
-
                 }
             }
 
@@ -3728,6 +3725,9 @@ class WholeController extends Curd
             $model->order_express_remark = $params['order_express_remark'] ?? null;
             $model->order_express_addtimes = $params['order_express_addtimes'] ?? time();
             $expressExtendJson['delivery_time'] = date('Y-m-d H:i:s');
+            if (!empty($params['card_id'])){
+                $expressExtendJson['card_id'] = $params['card_id'];
+            }
             $model->order_express_extend_json = json_encode($expressExtendJson);
             $model->save();
 
@@ -3744,9 +3744,12 @@ class WholeController extends Curd
 
             _syslog("订单", "发货成功");
             return json_success('发货成功');
+        }catch (BusinessException $e){
+            Db::rollBack();
+            _syslog("订单", "发货失败");
+            return json_fail('发货失败');
         } catch (\Exception $e) {
             Db::rollBack();
-            dump($e->getMessage());
             _syslog("订单", "发货失败");
             return json_fail('发货失败');
         }

+ 1 - 0
route/admin.php

@@ -1328,6 +1328,7 @@ Route::group('/admin', function () {
             Route::post('/add', [\app\admin\controller\order\CardController::class, 'insert']);
             Route::post('/pay', [\app\admin\controller\order\CardController::class, 'pay']);
             Route::get('/sheet', [\app\admin\controller\order\CardController::class, 'sheet']);
+            Route::get('/getCardList', [\app\admin\controller\order\CardController::class, 'getCardList']);
         })->middleware([
             \app\middleware\AdminAuthCheck::class
         ]);