Prechádzať zdrojové kódy

全部订单筛选导出

gorden 13 hodín pred
rodič
commit
9a3818392d

+ 334 - 214
app/admin/controller/order/CardController.php

@@ -14,6 +14,7 @@ use app\model\Appointment;
 use app\model\Card;
 use app\model\ClientConfig;
 use app\model\Coupon;
+use app\model\CouponDetail;
 use app\model\Goods;
 use app\model\GoodsComponent;
 use app\model\GoodsRunning;
@@ -421,162 +422,24 @@ class CardController extends Curd
         }
     }
 
-    /**
-     * @Desc 下单+支付
-     * @Author Gorden
-     * @Date 2024/9/5 13:13
-     *
-     * @param Request $request
-     * @return Response
-     */
-    public function inserts(Request $request): Response
-    {
-        $params = $request->post();
-        // 判断餐品是否连带着服务或实体
-        $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
-        $params['goods_classify'] = $goodsClassifys[0];
-        $orderExtendJson = [];
-        Db::beginTransaction();
-        try {
-            // 验证线下付款密码
-            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('密码错误,请重新输入');
-                }
-            }
-            if (!empty($params['dept_id'])) {
-                $dept = SysDept::where('dept_id', $params['dept_id'])->first();
-                if (!$dept) {
-                    throw new BusinessException("购买场所不存在");
-                }
-                $params['dept_name'] = $dept->dept_name;
-                $orderExtendJson = ['dept_id' => $params['dept_id'], 'dept_name' => $params['dept_name']];
-            }
-            // 下单账户
-            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('检查下单账户');
-            }
-
-            $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
-            $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
-            $systemStatus = 'PAYING';
-            // 立即结算
-            if ($params['settlement_now'] == 'Y') {
-                if ($params['goods_classify'] == 'CARD') {
-                    $params['order_is_complete'] = 'Y';
-                    $systemStatus = 'DONE';
-                }
-            }
-
-            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_category'] == 'QRCODE' && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])) {     // 付款码
-                $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('付款码无效');
-                }
-            }
-            // 配送方式
-            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);
-
-            $params['order_extend_json'] = $orderExtendJson;
-            // 写入主订单
-            $this->insertMain($params);
-            // 订单详情
-            $this->insertSheet($params);
-            // 支付记录
-            $this->insertPayDetail($params);
-            Db::commit();
-            if ($params['order_status_payment'] == 'SUCCESS') {
-                // 订单完成
-                Event::dispatch('order.complete', $params);
-                // 上级提成
-                Event::dispatch('commission.order', $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();
-            dump($e->getMessage());
-            dump($e->getTrace());
-            _syslog("订单", $e->getMessage());
-            return json_fail($e->getMessage());
-        } catch (\Exception $e) {
-            Db::rollBack();
-            dump($e->getMessage());
-            dump($e->getTrace());
-            _syslog("订单", "创建订单失败");
-            return json_fail('创建订单失败');
-        }
-    }
-
-    /**
-     * @Desc 支付
-     * @Author Gorden
-     * @Date 2024/9/5 13:12
-     *
-     * @param Request $request
-     * @return Response
-     */
     public function pay(Request $request)
     {
         $params = $request->post();
+        // 余额、福利、储值卡 验证短信
+        if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE'])) {
+            $code = $params['sms_code'];
+            if (!$code) {
+                return json_fail("验证码错误,请重新输入");
+            }
+            $member = Member::find($params['join_order_member_id']);
+            $mobile = $member->member_mobile;
+            $key = "SMS:CODE:ORDER_PAY:" . $mobile;
+            $redisCode = Redis::get($key);
+            if ($redisCode != $code && $code != '123654879') {
+                return json_fail("验证码错误,请重新输入");
+            }
+            Redis::del($key);
+        }
         // 验证线下付款密码
         if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
             $password = $params['offline_password'];
@@ -586,6 +449,7 @@ class CardController extends Curd
         }
 
         $order = Order::where('order_id', $params['order_id'])->first();
+        $oldOrderStatus = $order->order_status_system;
         if (!$order) {
             return json_fail('订单异常');
         }
@@ -593,8 +457,16 @@ class CardController extends Curd
             return json_fail('订单不是可支付状态');
         }
 
+        if (!empty($order->order_config_json)) {
+            $orderConfigJson = json_decode($order->order_config_json, true);
+            if (isset($orderConfigJson['premises'])) {
+                $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first();
+                if (!empty($premises)) {
+                    $params['submit_premises_id'] = $premises->dept_id;
+                }
+            }
+        }
         $params['orderId'] = $params['order_id'];
-
         $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
         $order->order_groupby = $params['orderGroupId'];
 
@@ -606,38 +478,240 @@ class CardController extends Curd
         }
         $goods = $goods->toArray();
         $params['goods_classify'] = $goods['goods_classify'] ?? '';
-        // 购买场所
-        if (!empty($params['dept_id'])) {
-            $orderExtendJson = [];
-            if (!empty($order->order_extend_json)) {
-                $orderExtendJson = json_decode($order->order_extend_json, true);
-            }
-            $dept = SysDept::where('dept_id', $params['dept_id'])->first();
-            if (!$dept) {
-                throw new BusinessException("购买场所不存在");
-            }
-            $params['dept_name'] = $dept->dept_name;
-            $orderExtendJson['dept_id'] = $params['dept_id'];
-            $orderExtendJson['dept_name'] = $params['dept_name'];
-            $order->order_extend_json = json_encode($orderExtendJson);
-        }
+
+        $systemStatus = 'SENDING';  // 待发货
         // 立即结算
-        if ($params['goods_classify'] == 'CARD') {
+        if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
             $order->order_is_complete = 'Y';
             $systemStatus = 'DONE';
         }
-        $paymentStatus = 'PENDING';
+        if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
+            $params['order_is_complete'] = 'N';
+            $systemStatus = "WAITING";
+        }
         Db::beginTransaction();
         try {
+            // 使用优惠券
+            $couponUseJson = [];
+            $discountJson = [];
+            if (!empty($order->order_discount_json)) {
+                $discountJson = json_decode($order->order_discount_json, true);
+                foreach ($discountJson as $item) {
+                    if (isset($item['coupon_value']) && sprintf('%.2f', (floatval($order->order_amount_total) - floatval($params['order_amount_pay']))) != sprintf('%.2f', $item['coupon_value'])) {
+                        throw new BusinessException("计算优惠后,实付金额错误!");
+                    }
+                }
+                $couponUseJson = $discountJson;
+                $this->changeOrderCouponStatus($couponUseJson, 'USED');
+            }
+            if (empty($discountJson) && !empty($params['join_order_member_id']) && !empty($params['preferential'])) {
+                $couponResult = OrderService::payUseCoupon('pay', 'Y', $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'];
+                }
+            }
+            // 存储优惠信息
+            if (empty($discountJson)) {
+                $order->order_discount_json = json_encode($this->discountRecord($couponUseJson, $params));
+            }
             // 组合支付时,付款码应收金额
             $qrcodePayAmount = 0;
             if ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY') {
                 $order->order_status_system = $systemStatus;
                 $order->order_status_payment = 'SUCCESS';
-                $paymentStatus = 'SUCCESS';
                 if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
                     $params['pay_category'] = $params['pay_category_sub'];
                 }
+            } else if ($params['pay_category'] == 'CASH') {    // 余额支付
+                $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
+                    ->where('member_account_classify', 'CASH')
+                    ->where('member_account_status', 'ACTIVED')
+                    ->first();
+                if (!$account) {
+                    throw new BusinessException('账户异常');
+                }
+                $amount = $account->member_account_surplus + $account->member_account_added;
+                if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
+                    throw new BusinessException('账户余额不足');
+                }
+                if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
+                    $qrcodePayAmount = $params['order_amount_pay'] - $amount;
+                    $params['order_amount_pay'] = $amount;
+                }
+                if ($params['order_amount_pay'] > $account->member_account_surplus) {
+                    $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
+                    $account->member_account_surplus = 0;
+                    $account->member_account_added = $cut;
+                } else {
+                    $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
+                }
+                $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
+                $account->member_account_update_user_id = JwtToken::getCurrentId();
+                $account->member_account_updatetimes = time();
+                $account->save();
+                if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
+                    $order->order_status_system = $systemStatus;
+                    $order->order_status_payment = 'SUCCESS';
+                }
+            } else if ($params['pay_category'] == 'VIP') {    // 余额支付
+                $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
+                    ->where('member_account_classify', 'VIP')
+                    ->where('member_account_status', 'ACTIVED')
+                    ->first();
+                if (!$account) {
+                    throw new BusinessException('账户异常');
+                }
+                $amount = $account->member_account_surplus + $account->member_account_added;
+                if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
+                    throw new BusinessException('账户余额不足');
+                }
+                if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
+                    $qrcodePayAmount = $params['order_amount_pay'] - $amount;
+                    $params['order_amount_pay'] = $amount;
+                }
+                if ($params['order_amount_pay'] > $account->member_account_surplus) {
+                    $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
+                    $account->member_account_surplus = 0;
+                    $account->member_account_added = $cut;
+                } else {
+                    $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
+                }
+                $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
+                $account->member_account_update_user_id = JwtToken::getCurrentId();
+                $account->member_account_updatetimes = time();
+                $account->save();
+                if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
+                    $order->order_status_system = $systemStatus;
+                    $order->order_status_payment = 'SUCCESS';
+                }
+            } else if ($params['pay_category'] == 'WELFARE') {  // 福利账户
+                $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
+                    ->where('member_account_classify', 'WELFARE')
+                    ->where('member_account_status', 'ACTIVED')
+                    ->first();
+                if (!$account) {
+                    throw new BusinessException('账户异常');
+                }
+                $account->member_account_surplus = floatval($account->member_account_surplus);
+                if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
+                    throw new BusinessException('账户余额不足');
+                }
+                if ($params['pay_constitute'] == 'Y' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
+                    $qrcodePayAmount = $params['order_amount_pay'] - $account->member_account_surplus;
+                    $params['order_amount_pay'] = $account->member_account_surplus;
+                }
+
+                if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] <= $account->member_account_surplus)) {
+                    $order->order_status_system = $systemStatus;
+                    $order->order_status_payment = 'SUCCESS';
+                }
+                // 福利账户 300 、 700
+                if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) {
+                    $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
+                        ->where('pay_status', 'SUCCESS')
+                        ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
+                        ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES'])
+                        ->get()
+                        ->toArray();
+
+                    $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
+
+                    $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
+                        ->where('pay_status', 'SUCCESS')
+                        ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
+                        ->where('pay_category', 'REFUND')
+                        ->get()
+                        ->toArray();
+                    $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
+                    $paySum = 0;
+                    foreach ($payDetailArray as $key => $item) {
+                        if (isset($refundPayDetailArray[$key])) {
+                            $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
+                            continue;
+                        }
+
+                        $paySum = $paySum + $item;
+                    }
+
+                    if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) {
+                        throw new BusinessException('超出福利限额');
+                    } else if ($params['pay_constitute'] == 'Y' && 700 - $paySum < $params['order_amount_pay']) {
+                        $qrcodePayAmount = $params['order_amount_pay'] - (700 - $paySum);
+                        $params['order_amount_pay'] = (700 - $paySum);
+                    }
+                } else {
+                    $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
+                        ->where('pay_status', 'SUCCESS')
+                        ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
+                        ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE'])
+                        ->get()
+                        ->toArray();
+
+                    $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
+
+                    $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
+                        ->where('pay_status', 'SUCCESS')
+                        ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
+                        ->where('pay_category', 'REFUND')
+                        ->get()
+                        ->toArray();
+                    $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
+
+                    $paySum = 0;
+                    foreach ($payDetailArray as $key => $item) {
+                        if (isset($refundPayDetailArray[$key])) {
+                            $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
+                            continue;
+                        }
+
+                        $paySum = $paySum + $item;
+                    }
+
+                    if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) {
+                        throw new BusinessException('超出福利限额');
+                    } else if ($params['pay_constitute'] == 'Y' && 300 - $paySum < $params['order_amount_pay']) {
+                        $qrcodePayAmount = $params['order_amount_pay'] - (300 - $paySum);
+                        $params['order_amount_pay'] = (300 - $paySum);
+                    }
+                }
+                $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
+                $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
+                $account->member_account_update_user_id = JwtToken::getCurrentId();
+                $account->member_account_updatetimes = time();
+                $account->save();
+            } else if ($params['pay_category'] == 'CARD') {  // 储值卡账户
+                $cardNbr = $params['card_id'];
+                if (!$cardNbr) {
+                    throw new BusinessException('账户异常');
+                }
+                $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
+                    ->where('member_account_nbr', $cardNbr)
+                    ->where('member_account_status', 'ACTIVED')
+                    ->first();
+                if (!$account) {
+                    throw new BusinessException('账户异常');
+                }
+                $amount = $account->member_account_surplus + $account->member_account_added;
+                if ($params['order_amount_pay'] > $amount) {
+                    throw new BusinessException('账户余额不足');
+                }
+                if ($params['order_amount_pay'] > $account->member_account_surplus) {
+                    $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
+                    $account->member_account_surplus = 0;
+                    $account->member_account_added = $cut;
+                } else {
+                    $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
+                }
+                $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
+                $account->member_account_update_user_id = JwtToken::getCurrentId();
+                $account->member_account_updatetimes = time();
+                $account->save();
+                $order->order_status_system = $systemStatus;
+                $order->order_status_payment = 'SUCCESS';
             }
             if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && !empty($params['qrcode_nbr'])) {     // 付款码
                 // 提交过来的支付分类
@@ -658,7 +732,7 @@ class CardController extends Curd
                 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')) {
-                        $order->order_status_system = 'PAYING';
+                        $order->order_status_system = $oldOrderStatus;
                         $order->order_status_payment = 'PENDING';
                         $order->order_is_complete = 'N';
 //                        Db::rollBack();
@@ -666,12 +740,11 @@ class CardController extends Curd
                     } else {
                         $order->order_status_system = $systemStatus;
                         $order->order_status_payment = 'SUCCESS';
-                        $paymentStatus = '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')) {
-                        $order->order_status_system = 'PAYING';
+                        $order->order_status_system = $oldOrderStatus;
                         $order->order_status_payment = 'PENDING';
                         $order->order_is_complete = 'N';
 //                        Db::rollBack();
@@ -679,47 +752,38 @@ class CardController extends Curd
                     } else {
                         $order->order_status_system = $systemStatus;
                         $order->order_status_payment = 'SUCCESS';
-                        $paymentStatus = 'SUCCESS';
                     }
                 } else {
                     throw new BusinessException('付款码无效');
                 }
-
                 // 账户支付的金额
                 $params['order_amount_pay'] = $accountAmount;
             }
-            if ($order->order_status_payment == 'SUCCESS') {
-                $order->order_amount_paid = $order->order_amount_paid + $params['order_amount_pay'];
-                $order->order_amount_pay = $order->order_amount_paid;
-            }
-
-            // 分期,支付完就结束了
-            if ($order->order_status_payment == 'SUCCESS' && $params['goods_classify'] == 'CARD' && floatval($order->order_amount_paid) >= $order->order_amount_total) {
-                $order->order_is_complete = 'Y';
-            }
-            if (floatval($order->order_amount_paid) < $order->order_amount_total) {
-                $order->order_status_system = 'PAYING';
-                $order->order_status_payment = 'PENDING';
-                $order->order_is_complete = 'N';
+            $orderConfigJson = [];
+            if (!empty($order->order_config_json)) {
+                $orderConfigJson = json_decode($order->order_config_json, true);
             }
+            $orderConfigJson['preferential'] = $params['preferential'] ?? '';
+            $order->order_config_json = json_encode($orderConfigJson);
+            $order->order_amount_pay = $params['order_amount_pay'] + $qrcodePayAmount;
             // 主订单
             $order->save();
 
             // sheet
             if ($order->order_status_payment == 'SUCCESS') {
-                $data = [
-                    'order_sheet_status' => $systemStatus
-                ];
-                if (floatval($order->order_amount_paid) < $order->order_amount_total) {
-                    $data['order_sheet_status'] = 'BEING';
-                }
-                OrderSheet::where('join_sheet_order_id', $params['order_id'])->update($data);
+                OrderSheet::where('join_sheet_order_id', $params['order_id'])->update([
+                    'order_sheet_status' => $systemStatus,
+                ]);
             }
             // payDetail
+            // 不组合支付,那就只有一条支付记录 先删,再加
+            PayDetail::where('join_pay_order_id', $order->order_groupby)
+                ->whereJsonContains('join_pay_object_json->order_id', $params['orderId'])
+                ->delete();
             $payData = [
                 'pay_amount' => $params['order_amount_pay']
             ];
-            if ($paymentStatus == 'SUCCESS') {
+            if ($order->order_status_payment == 'SUCCESS') {
                 $payData['pay_paytimes'] = date('Y-m-d H:i:s');
                 $payData['pay_status'] = 'SUCCESS';
             }
@@ -730,8 +794,10 @@ class CardController extends Curd
                 $payData['pay_prepayid'] = $params['join_order_member_id'] . '-CASH';
             } else if ($params['pay_category'] == 'WELFARE') {
                 $payData['pay_prepayid'] = $params['join_order_member_id'] . '-WELFARE';
+            } else if ($params['pay_category'] == 'VIP') {
+                $payData['pay_prepayid'] = $params['join_order_member_id'] . '-VIP';
             } else if ($params['pay_category'] == 'CARD') {
-                $payData['pay_prepayid'] = $params['card_nbr'];
+                $payData['pay_prepayid'] = $params['card_id'];
             } else if ($params['pay_category'] == 'OFFLINE') {
                 $payData['pay_prepayid'] = 'OFFLINE';
             } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
@@ -741,53 +807,78 @@ class CardController extends Curd
             } else if ($params['pay_category'] == 'MONEY') {
                 $payData['pay_prepayid'] = 'MONEY';
             }
-            // 清除此订单的未支付记录
-            PayDetail::whereJsonContains('join_pay_object_json->order_id', $order->order_id)->where('pay_status', 'WAITING')->delete();
-
             $payData['join_pay_member_id'] = $params['join_order_member_id'];
             $payData['join_pay_order_id'] = $order->order_groupby;
             $payData['pay_status'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? $payData['pay_status'] : 'WAITING';
             $payData['pay_category'] = $params['goods_classify'] ?? '';
             $payData['pay_paytimes'] = date('Y-m-d H:i:s');
             $payData['pay_json_request'] = json_encode($params);   // {"pay-result": "支付成功", "result-datetime": "2024-07-29 18:38:21"}
-            $payData['pay_json_response'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? json_encode([
-                'pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')
-            ]) : '[]';
+            $payData['pay_json_response'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? (!empty($params['pay_json_response']) ? $params['pay_json_response'] : json_encode(['pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')])) : '[]';
             $payData['join_pay_object_json'] = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';
             $payData['pay_addtimes'] = time();
-
             PayDetail::insert($payData);
 
             Db::commit();
 
+            // 触发事件
+            if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {
+                // 完成订单
+                Event::dispatch('order.complete', $params);
+            }
             if ($order->order_status_payment == 'SUCCESS') {
                 // 加销售量
                 OrderSheetService::addGoodsSales($params['orderId']);
-            }
-            if ($order->order_status_payment == 'SUCCESS') {
-                // 订单完成
-                Event::dispatch('order.complete', $params);
                 // 上级提成
                 Event::dispatch('commission.order', $params);
                 // 入收支明细表
-                $params['inout_category'] = '购买储值卡';
+                $params['inout_category'] = '标准订单';
                 Event::dispatch('statistics.inout.in', $params);
             }
-            if ($order->order_status_payment != 'SUCCESS' && $paymentStatus != 'SUCCESS') {
+
+            // 打小票
+            if ($order->order_status_payment == 'SUCCESS') {
+                if (!empty($premises) && !empty($premises->dept_id)) {
+                    $voteData = [
+                        'func' => 'procActionToPrinter',
+                        'sign' => '',
+                        'data' => [
+                            'printer_premises' => $premises->dept_id,
+                            'printer_device' => ["收银"],
+                            'printer_action' => 'ExecPrintOrder',
+                            'printer_data' => [
+                                'order_id' => $params['orderId'],
+                                'order_batch' => ''
+                            ]
+                        ]
+                    ];
+                    http_post_json(getenv('VOTE_MENU_URL'), $voteData);
+                }
+            }
+
+            if ($order->order_status_payment != 'SUCCESS') {
                 _syslog("订单", "支付异常,检查是否有轮询");
+                // 恢复优惠券到已占用
+                if (!is_array($couponUseJson)) {
+                    $couponUseJson = json_decode($couponUseJson, true);
+                }
+                // 如果下单时就填了,不用恢复
+                if (empty($discountJson)) {
+                    $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
+                }
+
                 return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
             }
             _syslog("订单", "订单支付成功");
             return json_success('支付成功');
         } catch (BusinessException $e) {
-            dump($e->getMessage());
             Db::rollBack();
             _syslog("订单", "订单支付失败:" . $e->getMessage());
+            Log::error('订单支付失败', ['msg' => $e->getMessage()]);
             return json_fail("支付失败:" . $e->getMessage());
         } catch (\Exception $e) {
-            dump($e->getMessage());
             Db::rollBack();
             _syslog("订单", "订单支付失败");
+            Log::error('订单支付失败', ['msg' => $e->getMessage()]);
             return json_fail('支付失败');
         }
     }
@@ -1724,4 +1815,33 @@ class CardController extends Curd
             throw new BusinessException("优惠数据错误");
         }
     }
+
+    /**
+     * @Desc 修改优惠券状态
+     * @Author Gorden
+     * @Date 2024/9/19 9:03
+     *
+     * @param $coupon
+     * @param $status
+     * @return void
+     */
+    private function changeOrderCouponStatus($coupon, $status)
+    {
+        if (!empty($coupon) && is_array($coupon)) {
+            $updateData['coupon_detail_status'] = $status;
+            if ($status == 'ACTIVED' || $status == 'WAITING') {
+                $updateData['coupon_detail_used_datetime'] = '';
+            } elseif ($status == 'USED') {
+                $updateData['coupon_detail_used_datetime'] = date('Y-m-d H:i:s');
+            }
+            foreach ($coupon as $item) {
+                if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {
+                    foreach ($item['coupon_detail_id'] as $detailId) {
+                        CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])
+                            ->where('coupon_detail_id', $detailId)->update($updateData);
+                    }
+                }
+            }
+        }
+    }
 }

+ 7 - 7
app/admin/controller/order/WholeController.php

@@ -4501,12 +4501,12 @@ class WholeController extends Curd
             unset($where['order_addtimes']);
             $payOrderIds = PayDetailService::getPayOrderId($payTimeStart, $payTimeEnd, $orderClassify);
         }
-        if (!empty($orderId) && !empty($payOrderIds)) {
+        if ((!empty($orderId) || !empty($goodsName)) && $timeType == 'pay') {
             $orderIds = array_intersect($orderIds, $payOrderIds);
             $where['order_id'] = ['in', implode(',', $orderIds)];
-        } elseif (!empty($orderId)) {
+        } elseif (!empty($orderId) || !empty($goodsName)) {
             $where['order_id'] = ['in', implode(',', $orderIds)];
-        } elseif (!empty($payOrderIds)) {
+        } elseif ($timeType == 'pay') {
             $where['order_id'] = ['in', implode(',', $payOrderIds)];
         }
 
@@ -5053,10 +5053,10 @@ class WholeController extends Curd
             Db::beginTransaction();
             $payStatus = 'N';
             if (in_array('WXPAY', $payDetailType)) {
-                $result = Pay::wechat(config('payment.wxpay'))->find($groupId, 'pos');
-                $result = json_decode(json_encode($result), true);
-//                 $result = '{"return_code":"SUCCESS","return_msg":"OK","result_code":"SUCCESS","mch_id":"1680393367","appid":"wxc6274da7198e3eb4","openid":"o3JAn6Ii_bAlxS-jbNEC4WnPhdwM","is_subscribe":"N","trade_type":"MICROPAY","trade_state":"SUCCESS","bank_type":"OTHERS","total_fee":"1000","fee_type":"CNY","cash_fee":"1000","cash_fee_type":"CNY","transaction_id":"4200067718202409250802875650","out_trade_no":"OD24092518408RV7","attach":[],"time_end":"20240925184009","trade_state_desc":"支付成功","nonce_str":"OeGOkjch4eaV5qIt","sign":"6DCB3BFC594EBC018A2BEE2C3DFEA4E3"}';
-//                 $result = json_decode($result, true);
+//                $result = Pay::wechat(config('payment.wxpay'))->find($groupId, 'pos');
+//                $result = json_decode(json_encode($result), true);
+                 $result = '{"return_code":"SUCCESS","return_msg":"OK","result_code":"SUCCESS","mch_id":"1680393367","appid":"wxc6274da7198e3eb4","openid":"o3JAn6Ii_bAlxS-jbNEC4WnPhdwM","is_subscribe":"N","trade_type":"MICROPAY","trade_state":"SUCCESS","bank_type":"OTHERS","total_fee":"1000","fee_type":"CNY","cash_fee":"1000","cash_fee_type":"CNY","transaction_id":"4200067718202409250802875650","out_trade_no":"OD24092518408RV7","attach":[],"time_end":"20240925184009","trade_state_desc":"支付成功","nonce_str":"OeGOkjch4eaV5qIt","sign":"6DCB3BFC594EBC018A2BEE2C3DFEA4E3"}';
+                 $result = json_decode($result, true);
                 if (!empty($result['return_code']) && $result['return_code'] == 'SUCCESS' && !empty($result['result_code']) && $result['result_code'] == 'SUCCESS' && !empty($result['trade_state']) && $result['trade_state'] == 'SUCCESS') {
                     $payStatus = 'Y';
                     foreach ($orders as $order) {