gorden vor 1 Monat
Ursprung
Commit
d97d3c084f

+ 148 - 168
app/admin/controller/order/GoodsController.php

@@ -546,7 +546,7 @@ class GoodsController extends Curd
 
             $params['order_config_json'] = json_encode($orderConfigJson);
             // 写入订单
-            $this->insertMain($params,$premises);
+            $this->insertMain($params);
 
             Db::commit();
 
@@ -589,7 +589,6 @@ class GoodsController extends Curd
     public function insertConstitute(Request $request): Response
     {
         $params = $request->post();
-        // 判断餐品是否连带着服务或实体
         $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
         $premises = [];
         if (!empty($params['dept_premises_id'])) {
@@ -614,7 +613,7 @@ class GoodsController extends Curd
             $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));
             $orderAmountPay = $params['order_amount_pay'];
             $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category');
-
+            // 验证金额
             $constituteAmount = 0;
             foreach ($params['pay_category_constitute_list'] as $item) {
                 $constituteAmount = sprintf("%.2f", $constituteAmount) + sprintf("%.2f", $item['amount']);
@@ -677,16 +676,14 @@ class GoodsController extends Curd
             $systemStatus = 'SENDING';  // 待发货
             // 立即结算
             if ($params['settlement_now'] == 'Y') {
-                if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
-                    $params['order_is_complete'] = 'Y';
-                    $systemStatus = 'DONE';
-                }
                 if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
                     $params['order_is_complete'] = 'N';
                     $systemStatus = "WAITING";
                 }
             }
             $params['pay_detail_item'] = [];
+            $waitToPayAccount = [];
+            $wxAndAliPayStatus = 'Y';
             if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) {      // 线下支付
                 $params['order_status_system'] = $systemStatus;
                 $params['order_status_payment'] = 'SUCCESS';
@@ -732,25 +729,31 @@ class GoodsController extends Curd
                 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->save();
+//                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->save();
+                // 余额账户扣款数据
+                $params['waitToPayAccount']['cash'] = [
+                    'group_id' => $params['orderGroupId'],
+                    'member_id' => $params['join_order_member_id'],
+                    'amount' => $constituteList['CASH'],
+                    'nbr' => $params['join_order_member_id'] . '-CASH'
+                ];
 
                 $params['order_status_system'] = $systemStatus;
                 $params['order_status_payment'] = 'SUCCESS';
 
                 // 生成支付记录
-//                OrderService::createPayDetail($params);
                 $params['pay_detail_item'][] = $params;
                 $params['order_amount_pay'] = $orderAmountPay;
 
@@ -777,27 +780,32 @@ class GoodsController extends Curd
                 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->save();
-
+//                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->save();
+                // 储值卡账户扣款数据
+                $params['waitToPayAccount']['card'] = [
+                    'group_id' => $params['orderGroupId'],
+                    'member_id' => $params['join_order_member_id'],
+                    'amount' => $constituteList['CARD'],
+                    'nbr' => $params['join_order_member_id'] . '-CARD'
+                ];
 
                 $params['order_status_system'] = $systemStatus;
                 $params['order_status_payment'] = 'SUCCESS';
                 // 生成支付记录
                 $params['pay_detail_item'][] = $params;
-//                OrderService::createPayDetail($params);
 
                 $params['order_amount_pay'] = $orderAmountPay;
             }
@@ -818,6 +826,8 @@ class GoodsController 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')) {
+                            // 标记支付状态
+                            $wxAndAliPayStatus = 'N';
                             $params['order_status_system'] = 'PAYING';
                             $params['order_status_payment'] = 'PENDING';
                             $params['order_is_complete'] = 'N';
@@ -830,6 +840,8 @@ class GoodsController extends Curd
                     } 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')) {
+                            // 标记支付状态
+                            $wxAndAliPayStatus = 'N';
                             $params['order_status_system'] = 'PAYING';
                             $params['order_status_payment'] = 'PENDING';
                             $params['order_is_complete'] = 'N';
@@ -862,7 +874,7 @@ class GoodsController extends Curd
             }
             $params['order_config_json'] = json_encode($orderConfigJson);
             // 写入订单
-            $this->insertMain($params, $premises);
+            $this->insertMain($params, $wxAndAliPayStatus);
 
             Db::commit();
 
@@ -880,20 +892,18 @@ class GoodsController extends Curd
                 }
                 $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
 
-                return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
+                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('创建订单失败');
         }
@@ -1243,9 +1253,6 @@ class GoodsController extends Curd
                 $orderConfigJson = json_decode($order->order_config_json, true);
             }
             $orderConfigJson['preferential'] = $params['preferential'] ?? '';
-            if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) {
-                SysDept::where('dept_id', $orderConfigJson['tableid'])->where('dept_category', '桌台')->update(['dept_status' => 'ACTIVED']);
-            }
             $order->order_config_json = json_encode($orderConfigJson);
             $order->order_amount_pay = $params['order_amount_pay'] + $qrcodePayAmount;
             // 主订单
@@ -1302,27 +1309,6 @@ class GoodsController extends Curd
 
             $writeOffDate = [];
             $applyData = [];
-            // 有预约单,状态已完成
-            $appointment = Appointment::where('join_appointment_order_id', $params['order_id'])->first();
-            if ($order->order_status_payment == 'SUCCESS' && $appointment) {
-                $writeOffDate = OrderService::generateWriteOffData($params);
-                $applyData = OrderService::generateAppointmentApplyData($params);
-
-                $appointment->appointment_status = 'DONE';
-                $appointment->appointment_done_datetime = date('Y-m-d H:i:s');
-                $appointment->appointment_done_json = json_encode($writeOffDate);
-                if (empty($appointment->appointment_apply_datetime)) {
-                    $appointment->appointment_apply_datetime = date('Y-m-d H:i:s');
-                }
-                if (empty($appointment->appointment_apply_json)) {
-                    $appointment->appointment_apply_json = json_encode($applyData);
-                }
-                if (empty($appointment->appointment_datetime)) {
-                    $appointment->appointment_datetime = date('Y-m-d');
-                }
-
-                $appointment->save();
-            }
 
             Db::commit();
 
@@ -1333,9 +1319,9 @@ class GoodsController extends Curd
                 // 会员升级
                 Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
             }
-            if($order->order_status_payment == 'SUCCESS'){
+            if ($order->order_status_payment == 'SUCCESS') {
                 // 上级提成
-                Event::dispatch('commission.order',$params);
+                Event::dispatch('commission.order', $params);
             }
 
             // 打小票
@@ -1370,7 +1356,7 @@ class GoodsController extends Curd
                     $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
                 }
 
-                return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
+                return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
             }
             _syslog("订单", "订单支付成功");
             return json_success('支付成功');
@@ -1496,7 +1482,11 @@ class GoodsController extends Curd
             if (sprintf("%.2f", $params['order_amount_pay']) != sprintf("%.2f", $constituteAmount)) {
                 throw new BusinessException('组合支付金额与应付金额不一致');
             }
-            $params['pay_detail_item'] = [];
+
+            $wxAndAliPayStatus = 'Y';
+            $waitToPayAccount = [];
+            // 清除订单的支付记录,重建
+            PayDetail::whereJsonContains('join_pay_object_json->order_id', $params['orderId'])->delete();
             if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) {  //线下付款
                 $order->order_status_system = $systemStatus;
                 $order->order_status_payment = 'SUCCESS';
@@ -1506,9 +1496,9 @@ class GoodsController extends Curd
                 if (isset($constituteList['OFFLINE'])) {
                     $params['order_amount_pay'] = $constituteList['OFFLINE'];
                     // 生成支付记录
-                    OrderService::createPayConstituteDetail($params, $payDetail);
+                    $params['order_status_payment'] = 'PENDING';
+                    OrderService::createProductPayConstituteDetail($params);
                     $params['order_status_payment'] = 'SUCCESS';
-                    $params['pay_detail_item'][] = $params;
                 }
                 $params['order_amount_pay'] = $orderAmountPay;
             }
@@ -1521,9 +1511,9 @@ class GoodsController extends Curd
                 if (isset($constituteList['MONEY'])) {
                     $params['order_amount_pay'] = $constituteList['MONEY'];
                     // 生成支付记录
-                    OrderService::createPayConstituteDetail($params, $payDetail);
+                    $params['order_status_payment'] = 'PENDING';
+                    OrderService::createProductPayConstituteDetail($params);
                     $params['order_status_payment'] = 'SUCCESS';
-                    $params['pay_detail_item'][] = $params;
                 }
                 $params['order_amount_pay'] = $orderAmountPay;
             }
@@ -1543,23 +1533,17 @@ class GoodsController extends Curd
                 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->save();
+                // 余额账户扣款数据
+                $waitToPayAccount['cash'] = [
+                    'group_id' => $params['orderGroupId'],
+                    'member_id' => $params['join_order_member_id'],
+                    'amount' => $constituteList['CASH'],
+                    'nbr' => $params['join_order_member_id'] . '-CASH'
+                ];
                 // 生成支付记录
-                OrderService::createPayConstituteDetail($params, $payDetail);
+                $params['order_status_payment'] = 'PENDING';
+                OrderService::createProductPayConstituteDetail($params);
                 $params['order_status_payment'] = 'SUCCESS';
-                $params['pay_detail_item'][] = $params;
                 $params['order_amount_pay'] = $orderAmountPay;
                 $order->order_status_system = $systemStatus;
                 $order->order_status_payment = 'SUCCESS';
@@ -1586,23 +1570,17 @@ class GoodsController extends Curd
                 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->save();
+                // 储值卡账户扣款数据
+                $waitToPayAccount['card'] = [
+                    'group_id' => $params['orderGroupId'],
+                    'member_id' => $params['join_order_member_id'],
+                    'amount' => $constituteList['CARD'],
+                    'nbr' => $params['join_order_member_id'] . '-CARD'
+                ];
                 // 生成支付记录
-                OrderService::createPayConstituteDetail($params, $payDetail);
+                $params['order_status_payment'] = 'PENDING';
+                OrderService::createProductPayConstituteDetail($params);
                 $params['order_status_payment'] = 'SUCCESS';
-                $params['pay_detail_item'][] = $params;
                 $params['order_amount_pay'] = $orderAmountPay;
                 $order->order_status_system = $systemStatus;
                 $order->order_status_payment = 'SUCCESS';
@@ -1621,26 +1599,30 @@ class GoodsController 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')) {
+                            // 标记支付状态
+                            $wxAndAliPayStatus = 'N';
                             $order->order_status_system = 'PAYING';
                             $order->order_status_payment = 'PENDING';
                             $order->order_is_complete = 'N';
-//                        Db::rollBack();
-//                        return json_fail('支付失败');
+                            $params['order_status_payment'] = 'PAYING';
                         } else {
                             $order->order_status_system = $systemStatus;
                             $order->order_status_payment = 'SUCCESS';
+                            $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')) {
+                            // 标记支付状态
+                            $wxAndAliPayStatus = 'N';
                             $order->order_status_system = 'PAYING';
                             $order->order_status_payment = 'PENDING';
                             $order->order_is_complete = 'N';
-//                        Db::rollBack();
-//                        return json_fail('支付失败');
+                            $params['order_status_payment'] = 'PAYING';
                         } else {
                             $order->order_status_system = $systemStatus;
                             $order->order_status_payment = 'SUCCESS';
+                            $params['order_status_payment'] = 'SUCCESS';
                         }
                     } else {
                         throw new BusinessException('付款码无效');
@@ -1648,7 +1630,7 @@ class GoodsController extends Curd
                 }
 
                 // 生成支付记录
-                OrderService::createPayConstituteDetail($params, $payDetail);
+                OrderService::createProductPayConstituteDetail($params);
                 // 账户支付的金额
                 $params['order_amount_pay'] = $orderAmountPay;
             }
@@ -1657,9 +1639,6 @@ class GoodsController extends Curd
                 $orderConfigJson = json_decode($order->order_config_json, true);
             }
             $orderConfigJson['preferential'] = $params['preferential'] ?? '';
-            if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) {
-                SysDept::where('dept_id', $orderConfigJson['tableid'])->where('dept_category', '桌台')->update(['dept_status' => 'ACTIVED']);
-            }
             $order->order_config_json = json_encode($orderConfigJson);
             $order->order_amount_pay = $params['order_amount_pay'];
 
@@ -1671,35 +1650,27 @@ class GoodsController extends Curd
                     'order_sheet_status' => $systemStatus,
                 ]);
             }
-            // 清除paydetail 中的未支付记录
-            PayDetail::where('join_pay_order_id', $params['orderGroupId'])
-                ->whereJsonContains('join_pay_object_json->order_id', $params['order_id'])
-                ->where('pay_status', '<>', 'SUCCESS')
-                ->delete();
-
-            $writeOffDate = [];
-            $applyData = [];
-            // 有预约单,状态已完成
-            $appointment = Appointment::where('join_appointment_order_id', $params['order_id'])->first();
-            if ($order->order_status_payment == 'SUCCESS' && $appointment) {
-                $writeOffDate = OrderService::generateWriteOffData($params);
-                $applyData = OrderService::generateAppointmentApplyData($params);
 
-                $appointment->appointment_status = 'DONE';
-                $appointment->appointment_done_datetime = date('Y-m-d H:i:s');
-                $appointment->appointment_done_json = json_encode($writeOffDate);
-                if (empty($appointment->appointment_apply_datetime)) {
-                    $appointment->appointment_apply_datetime = date('Y-m-d H:i:s');
-                }
-                if (empty($appointment->appointment_apply_json)) {
-                    $appointment->appointment_apply_json = json_encode($applyData);
-                }
-                if (empty($appointment->appointment_datetime)) {
-                    $appointment->appointment_datetime = date('Y-m-d');
+            if ($wxAndAliPayStatus == 'Y') {
+                PayDetail::whereJsonContains('join_pay_object_json->order_id', $params['orderId'])->update([
+                    'pay_status' => 'SUCCESS',
+                    'pay_paytimes' => date('Y-m-d H:i:s')
+                ]);
+                // 扣款
+                foreach ($waitToPayAccount as $item) {
+                    $accountNbr = $item['nbr'];
+                    $account = MemberAccount::where('member_account_nbr', $accountNbr)->first();
+                    $account->member_account_expend = $account->member_account_expend + $amount;
+                    if ($account->member_account_surplus < $amount && strpos($accountNbr, 'CASH') !== false) {
+                        $account->member_account_added = $account->member_account_added - ($amount - $account->member_account_surplus);
+                        $account->member_account_surplus = 0;
+                    } else {
+                        $account->member_account_surplus = $account->member_account_surplus - $amount;
+                    }
+                    $account->save();
                 }
-
-                $appointment->save();
             }
+
             Db::commit();
             // 触发事件
             if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {
@@ -1708,9 +1679,9 @@ class GoodsController extends Curd
                 // 会员升级
                 Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
             }
-            if($order->order_status_payment == 'SUCCESS'){
+            if ($order->order_status_payment == 'SUCCESS') {
                 // 上级提成
-                Event::dispatch('commission.order',$params);
+                Event::dispatch('commission.order', $params);
             }
 
             // 打小票
@@ -1746,7 +1717,7 @@ class GoodsController extends Curd
                 // 清除支付记录,恢复账户金额
 //                $this->restoreAccount($params['pay_detail_item']);
 
-                return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
+                return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
             }
             _syslog("订单", "订单支付成功");
             return json_success('支付成功');
@@ -1758,31 +1729,6 @@ class GoodsController extends Curd
         }
     }
 
-    public function restoreAccount($payDetailItem)
-    {
-        foreach ($payDetailItem as $item) {
-            $prepayId = '';
-            if ($item['order_status_payment'] == 'SUCCESS') {
-                if (in_array($item['pay_category'], ['MONEY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY'])) {
-                    $prepayId = $item['pay_category'];
-                }
-                if (strpos($item['pay_category'],'CASH') !== false || strpos($item['pay_category'],'CARD') !== false || strpos($item['pay_category'],'WELFARE') !== false || strpos($item['pay_category'],'VIP') !== false){
-                    $prepayId = $item['pay_category'];
-                    $account = MemberAccount::where('member_account_nbr', $prepayId)->first();
-                    $account->member_account_expend = $account->member_account_expend - $item['order_amount_pay'];
-                    $account->member_account_surplus = $account->member_account_surplus + $item['order_amount_pay'];
-                    $account->save();
-                }
-            }
-            if (!empty($prepayId)) {
-                PayDetail::where('pay_prepayid', $prepayId)
-                    ->where('join_pay_order_id', $item['orderGroupId'])
-                    ->whereJsonContains('join_pay_object_json->order_id',$item['orderId'])
-                    ->update(['pay_status' => 'WAITING']);
-            }
-        }
-    }
-
     /**
      * @Desc
      * @Author Gorden
@@ -1792,7 +1738,7 @@ class GoodsController extends Curd
      * @return void
      * @throws BusinessException
      */
-    public function insertMain($params,$premises)
+    public function insertMain($params, $wxAndAliPayStatus = 'Y')
     {
         try {
             if (empty($params['order_extend_json'])) {
@@ -1802,6 +1748,12 @@ class GoodsController 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'] ?? '';
             foreach ($params['goodsContentList'] as $goods) {
@@ -1848,8 +1800,6 @@ class GoodsController extends Curd
                 $params['order_express_goods'] = json_encode(['sheet' => $sheetIds]);
 
                 $this->insertExpressOne($params, $orderId);
-                // 打小票
-//                $this->printerTicket($params, $premises, $orderId);
             }
         } catch (\Exception $e) {
             dump($e->getMessage());
@@ -1857,6 +1807,35 @@ class GoodsController extends Curd
         }
     }
 
+    /**
+     * @Desc 扣除账户金额
+     * @Author Gorden
+     * @Date 2024/9/26 14:16
+     *
+     * @param $accountNbr
+     * @param $amount
+     * @return void
+     */
+    public function deductAmount($accountNbr, $amount)
+    {
+        try {
+            $account = MemberAccount::where('member_account_nbr', $accountNbr)->first();
+            $account->member_account_expend = $account->member_account_expend + $amount;
+            if ($account->member_account_surplus < $amount && strpos($accountNbr, 'CASH') !== false) {
+                $account->member_account_added = $account->member_account_added - ($amount - $account->member_account_surplus);
+                $account->member_account_surplus = 0;
+            } else {
+                $account->member_account_surplus = $account->member_account_surplus - $amount;
+            }
+
+            $account->save();
+        } catch (\Exception $e) {
+            _syslog("下单扣款", "扣款失败");
+
+            throw new BusinessException("账户扣款失败");
+        }
+    }
+
     /**
      * @Desc 打小票
      * @Author Gorden
@@ -1889,6 +1868,7 @@ class GoodsController extends Curd
             }
         }
     }
+
     /**
      * @Desc
      * @Author Gorden

+ 151 - 124
app/admin/controller/order/PackagesController.php

@@ -685,7 +685,7 @@ class PackagesController extends Curd
 
             $params['order_config_json'] = json_encode($orderConfigJson);
             // 写入订单
-            $this->insertMain($params, $premises);
+            $this->insertMain($params);
 
             Db::commit();
 
@@ -728,7 +728,6 @@ class PackagesController extends Curd
     public function insertConstitute(Request $request): Response
     {
         $params = $request->post();
-        // 判断餐品是否连带着服务或实体
         $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
         $premises = [];
         if (!empty($params['dept_premises_id'])) {
@@ -819,16 +818,13 @@ class PackagesController extends Curd
             $systemStatus = 'SENDING';  // 待发货
             // 立即结算
             if ($params['settlement_now'] == 'Y') {
-                if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
-                    $params['order_is_complete'] = 'Y';
-                    $systemStatus = 'DONE';
-                }
                 if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
                     $params['order_is_complete'] = 'N';
                     $systemStatus = "WAITING";
                 }
             }
             $params['pay_detail_item'] = [];
+            $wxAndAliPayStatus = 'Y';
             if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) {      // 线下支付
                 $params['order_status_system'] = $systemStatus;
                 $params['order_status_payment'] = 'SUCCESS';
@@ -874,25 +870,31 @@ class PackagesController extends Curd
                 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->save();
+//                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->save();
+                // 余额账户扣款数据
+                $params['waitToPayAccount']['cash'] = [
+                    'group_id' => $params['orderGroupId'],
+                    'member_id' => $params['join_order_member_id'],
+                    'amount' => $constituteList['CASH'],
+                    'nbr' => $params['join_order_member_id'] . '-CASH'
+                ];
 
                 $params['order_status_system'] = $systemStatus;
                 $params['order_status_payment'] = 'SUCCESS';
 
                 // 生成支付记录
-//                OrderService::createPayDetail($params);
                 $params['pay_detail_item'][] = $params;
                 $params['order_amount_pay'] = $orderAmountPay;
 
@@ -919,27 +921,32 @@ class PackagesController extends Curd
                 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->save();
-
+//                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->save();
+                // 储值卡账户扣款数据
+                $params['waitToPayAccount']['card'] = [
+                    'group_id' => $params['orderGroupId'],
+                    'member_id' => $params['join_order_member_id'],
+                    'amount' => $constituteList['CARD'],
+                    'nbr' => $params['join_order_member_id'] . '-CARD'
+                ];
 
                 $params['order_status_system'] = $systemStatus;
                 $params['order_status_payment'] = 'SUCCESS';
                 // 生成支付记录
                 $params['pay_detail_item'][] = $params;
-//                OrderService::createPayDetail($params);
 
                 $params['order_amount_pay'] = $orderAmountPay;
             }
@@ -960,6 +967,8 @@ class PackagesController 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')) {
+                            // 标记支付状态
+                            $wxAndAliPayStatus = 'N';
                             $params['order_status_system'] = 'PAYING';
                             $params['order_status_payment'] = 'PENDING';
                             $params['order_is_complete'] = 'N';
@@ -972,6 +981,8 @@ class PackagesController extends Curd
                     } 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')) {
+                            // 标记支付状态
+                            $wxAndAliPayStatus = 'N';
                             $params['order_status_system'] = 'PAYING';
                             $params['order_status_payment'] = 'PENDING';
                             $params['order_is_complete'] = 'N';
@@ -1000,7 +1011,7 @@ class PackagesController extends Curd
             }
             $params['order_config_json'] = json_encode($orderConfigJson);
             // 写入订单
-            $this->insertMain($params, $premises);
+            $this->insertMain($params, $wxAndAliPayStatus);
 
             Db::commit();
 
@@ -1018,20 +1029,18 @@ class PackagesController extends Curd
                 }
                 $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
 
-                return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
+                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('创建订单失败');
         }
@@ -1426,7 +1435,7 @@ class PackagesController extends Curd
             }
             $payData['join_pay_member_id'] = $params['join_order_member_id'];
             $payData['join_pay_order_id'] = $order->order_groupby;
-            $payData['pay_status'] = $payData['pay_status'] == 'SUCCESS' ? $payData['pay_status'] : 'WAITING';
+            $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"}
@@ -1516,9 +1525,9 @@ class PackagesController extends Curd
                 // 会员升级
                 Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
             }
-            if($order->order_status_payment == 'SUCCESS'){
+            if ($order->order_status_payment == 'SUCCESS') {
                 // 上级提成
-                Event::dispatch('commission.order',$params);
+                Event::dispatch('commission.order', $params);
             }
 
             // 打小票
@@ -1553,7 +1562,7 @@ class PackagesController extends Curd
                     $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
                 }
 
-                return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
+                return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
             }
             _syslog("订单", "订单支付成功");
             return json_success('支付成功');
@@ -1679,7 +1688,11 @@ class PackagesController extends Curd
             if (sprintf("%.2f", $params['order_amount_pay']) != sprintf("%.2f", $constituteAmount)) {
                 throw new BusinessException('组合支付金额与应付金额不一致');
             }
-            $params['pay_detail_item'] = [];
+
+            $wxAndAliPayStatus = 'Y';
+            $waitToPayAccount = [];
+            // 清除订单的支付记录,重建
+            PayDetail::whereJsonContains('join_pay_object_json->order_id', $params['orderId'])->delete();
             if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) {  //线下付款
                 $order->order_status_system = $systemStatus;
                 $order->order_status_payment = 'SUCCESS';
@@ -1689,9 +1702,9 @@ class PackagesController extends Curd
                 if (isset($constituteList['OFFLINE'])) {
                     $params['order_amount_pay'] = $constituteList['OFFLINE'];
                     // 生成支付记录
-                    OrderService::createPayConstituteDetail($params, $payDetail);
+                    $params['order_status_payment'] = 'PENDING';
+                    OrderService::createProductPayConstituteDetail($params);
                     $params['order_status_payment'] = 'SUCCESS';
-                    $params['pay_detail_item'][] = $params;
                 }
                 $params['order_amount_pay'] = $orderAmountPay;
             }
@@ -1704,9 +1717,9 @@ class PackagesController extends Curd
                 if (isset($constituteList['MONEY'])) {
                     $params['order_amount_pay'] = $constituteList['MONEY'];
                     // 生成支付记录
-                    OrderService::createPayConstituteDetail($params, $payDetail);
+                    $params['order_status_payment'] = 'PENDING';
+                    OrderService::createProductPayConstituteDetail($params, $payDetail);
                     $params['order_status_payment'] = 'SUCCESS';
-                    $params['pay_detail_item'][] = $params;
                 }
                 $params['order_amount_pay'] = $orderAmountPay;
             }
@@ -1726,23 +1739,17 @@ class PackagesController extends Curd
                 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->save();
+                // 余额账户扣款数据
+                $waitToPayAccount['cash'] = [
+                    'group_id' => $params['orderGroupId'],
+                    'member_id' => $params['join_order_member_id'],
+                    'amount' => $constituteList['CASH'],
+                    'nbr' => $params['join_order_member_id'] . '-CASH'
+                ];
                 // 生成支付记录
-                OrderService::createPayConstituteDetail($params, $payDetail);
+                $params['order_status_payment'] = 'PENDING';
+                OrderService::createProductPayConstituteDetail($params);
                 $params['order_status_payment'] = 'SUCCESS';
-                $params['pay_detail_item'][] = $params;
                 $params['order_amount_pay'] = $orderAmountPay;
                 $order->order_status_system = $systemStatus;
                 $order->order_status_payment = 'SUCCESS';
@@ -1769,23 +1776,17 @@ class PackagesController extends Curd
                 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->save();
+                // 储值卡账户扣款数据
+                $waitToPayAccount['card'] = [
+                    'group_id' => $params['orderGroupId'],
+                    'member_id' => $params['join_order_member_id'],
+                    'amount' => $constituteList['CARD'],
+                    'nbr' => $params['join_order_member_id'] . '-CARD'
+                ];
                 // 生成支付记录
-                OrderService::createPayConstituteDetail($params, $payDetail);
+                $params['order_status_payment'] = 'PENDING';
+                OrderService::createProductPayConstituteDetail($params);
                 $params['order_status_payment'] = 'SUCCESS';
-                $params['pay_detail_item'][] = $params;
                 $params['order_amount_pay'] = $orderAmountPay;
                 $order->order_status_system = $systemStatus;
                 $order->order_status_payment = 'SUCCESS';
@@ -1804,26 +1805,30 @@ class PackagesController 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')) {
+                            // 标记支付状态
+                            $wxAndAliPayStatus = 'N';
                             $order->order_status_system = 'PAYING';
                             $order->order_status_payment = 'PENDING';
                             $order->order_is_complete = 'N';
-//                        Db::rollBack();
-//                        return json_fail('支付失败');
+                            $params['order_status_payment'] = 'PAYING';
                         } else {
                             $order->order_status_system = $systemStatus;
                             $order->order_status_payment = 'SUCCESS';
+                            $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')) {
+                            // 标记支付状态
+                            $wxAndAliPayStatus = 'N';
                             $order->order_status_system = 'PAYING';
                             $order->order_status_payment = 'PENDING';
                             $order->order_is_complete = 'N';
-//                        Db::rollBack();
-//                        return json_fail('支付失败');
+                            $params['order_status_payment'] = 'PAYING';
                         } else {
                             $order->order_status_system = $systemStatus;
                             $order->order_status_payment = 'SUCCESS';
+                            $params['order_status_payment'] = 'SUCCESS';
                         }
                     } else {
                         throw new BusinessException('付款码无效');
@@ -1831,7 +1836,7 @@ class PackagesController extends Curd
                 }
 
                 // 生成支付记录
-                OrderService::createPayConstituteDetail($params, $payDetail);
+                OrderService::createProductPayConstituteDetail($params);
                 // 账户支付的金额
                 $params['order_amount_pay'] = $orderAmountPay;
             }
@@ -1840,9 +1845,6 @@ class PackagesController extends Curd
                 $orderConfigJson = json_decode($order->order_config_json, true);
             }
             $orderConfigJson['preferential'] = $params['preferential'] ?? '';
-            if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) {
-                SysDept::where('dept_id', $orderConfigJson['tableid'])->where('dept_category', '桌台')->update(['dept_status' => 'ACTIVED']);
-            }
             $order->order_config_json = json_encode($orderConfigJson);
             $order->order_amount_pay = $params['order_amount_pay'];
 
@@ -1854,34 +1856,25 @@ class PackagesController extends Curd
                     'order_sheet_status' => $systemStatus,
                 ]);
             }
-            // 清除paydetail 中的未支付记录
-            PayDetail::where('join_pay_order_id', $params['orderGroupId'])
-                ->whereJsonContains('join_pay_object_json->order_id', $params['order_id'])
-                ->where('pay_status', '<>', 'SUCCESS')
-                ->delete();
-
-            $writeOffDate = [];
-            $applyData = [];
-            // 有预约单,状态已完成
-            $appointment = Appointment::where('join_appointment_order_id', $params['order_id'])->first();
-            if ($order->order_status_payment == 'SUCCESS' && $appointment) {
-                $writeOffDate = OrderService::generateWriteOffData($params);
-                $applyData = OrderService::generateAppointmentApplyData($params);
 
-                $appointment->appointment_status = 'DONE';
-                $appointment->appointment_done_datetime = date('Y-m-d H:i:s');
-                $appointment->appointment_done_json = json_encode($writeOffDate);
-                if (empty($appointment->appointment_apply_datetime)) {
-                    $appointment->appointment_apply_datetime = date('Y-m-d H:i:s');
-                }
-                if (empty($appointment->appointment_apply_json)) {
-                    $appointment->appointment_apply_json = json_encode($applyData);
-                }
-                if (empty($appointment->appointment_datetime)) {
-                    $appointment->appointment_datetime = date('Y-m-d');
+            if ($wxAndAliPayStatus == 'Y') {
+                PayDetail::whereJsonContains('join_pay_object_json->order_id', $params['orderId'])->update([
+                    'pay_status' => 'SUCCESS',
+                    'pay_paytimes' => date('Y-m-d H:i:s')
+                ]);
+                // 扣款
+                foreach ($waitToPayAccount as $item) {
+                    $accountNbr = $item['nbr'];
+                    $account = MemberAccount::where('member_account_nbr', $accountNbr)->first();
+                    $account->member_account_expend = $account->member_account_expend + $amount;
+                    if ($account->member_account_surplus < $amount && strpos($accountNbr, 'CASH') !== false) {
+                        $account->member_account_added = $account->member_account_added - ($amount - $account->member_account_surplus);
+                        $account->member_account_surplus = 0;
+                    } else {
+                        $account->member_account_surplus = $account->member_account_surplus - $amount;
+                    }
+                    $account->save();
                 }
-
-                $appointment->save();
             }
             // 买单个服务
             if ($order->order_status_payment == 'SUCCESS' && empty($appointment)) {
@@ -1939,9 +1932,9 @@ class PackagesController extends Curd
                 // 会员升级
                 Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
             }
-            if($order->order_status_payment == 'SUCCESS'){
+            if ($order->order_status_payment == 'SUCCESS') {
                 // 上级提成
-                Event::dispatch('commission.order',$params);
+                Event::dispatch('commission.order', $params);
             }
 
             // 打小票
@@ -1977,7 +1970,7 @@ class PackagesController extends Curd
                 // 清除支付记录,恢复账户金额
 //                $this->restoreAccount($params['pay_detail_item']);
 
-                return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
+                return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
             }
             _syslog("订单", "订单支付成功");
             return json_success('支付成功');
@@ -1997,7 +1990,7 @@ class PackagesController extends Curd
                 if (in_array($item['pay_category'], ['MONEY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY'])) {
                     $prepayId = $item['pay_category'];
                 }
-                if (strpos($item['pay_category'],'CASH') !== false || strpos($item['pay_category'],'CARD') !== false || strpos($item['pay_category'],'WELFARE') !== false || strpos($item['pay_category'],'VIP') !== false){
+                if (strpos($item['pay_category'], 'CASH') !== false || strpos($item['pay_category'], 'CARD') !== false || strpos($item['pay_category'], 'WELFARE') !== false || strpos($item['pay_category'], 'VIP') !== false) {
                     $prepayId = $item['pay_category'];
                     $account = MemberAccount::where('member_account_nbr', $prepayId)->first();
                     $account->member_account_expend = $account->member_account_expend - $item['order_amount_pay'];
@@ -2008,7 +2001,7 @@ class PackagesController extends Curd
             if (!empty($prepayId)) {
                 PayDetail::where('pay_prepayid', $prepayId)
                     ->where('join_pay_order_id', $item['orderGroupId'])
-                    ->whereJsonContains('join_pay_object_json->order_id',$item['orderId'])
+                    ->whereJsonContains('join_pay_object_json->order_id', $item['orderId'])
                     ->update(['pay_status' => 'WAITING']);
             }
         }
@@ -2023,7 +2016,7 @@ class PackagesController extends Curd
      * @return void
      * @throws BusinessException
      */
-    public function insertMain($params, $premises)
+    public function insertMain($params, $wxAndAliPayStatus = 'Y')
     {
         try {
             if (empty($params['order_extend_json'])) {
@@ -2033,6 +2026,12 @@ class PackagesController 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'] ?? '';
             foreach ($params['goodsContentList'] as $goods) {
@@ -2080,10 +2079,9 @@ class PackagesController extends Curd
 
                 $this->insertExpressOne($params, $orderId);
                 // 写到权益里
-                $this->insertBenefitOne($params, $goods, $orderId);
-
-                // 打小票
-//                $this->printerTicket($params, $premises, $orderId);
+                if ($params['order_status_payment'] == 'SUCCESS') {
+                    $this->insertBenefitOne($params, $goods, $orderId);
+                }
             }
         } catch (\Exception $e) {
             dump($e->getMessage() . '|' . $e->getLine());
@@ -2091,6 +2089,35 @@ class PackagesController extends Curd
         }
     }
 
+    /**
+     * @Desc 扣除账户金额
+     * @Author Gorden
+     * @Date 2024/9/26 14:16
+     *
+     * @param $accountNbr
+     * @param $amount
+     * @return void
+     */
+    public function deductAmount($accountNbr, $amount)
+    {
+        try {
+            $account = MemberAccount::where('member_account_nbr', $accountNbr)->first();
+            $account->member_account_expend = $account->member_account_expend + $amount;
+            if ($account->member_account_surplus < $amount && strpos($accountNbr, 'CASH') !== false) {
+                $account->member_account_added = $account->member_account_added - ($amount - $account->member_account_surplus);
+                $account->member_account_surplus = 0;
+            } else {
+                $account->member_account_surplus = $account->member_account_surplus - $amount;
+            }
+
+            $account->save();
+        } catch (\Exception $e) {
+            _syslog("下单扣款", "扣款失败");
+
+            throw new BusinessException("账户扣款失败");
+        }
+    }
+
     /**
      * @Desc 打小票
      * @Author Gorden
@@ -2390,7 +2417,7 @@ class PackagesController extends Curd
                     $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_status' => $params['settlement_now'] == 'Y' && $params['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'],

+ 153 - 128
app/admin/controller/order/ServicesController.php

@@ -528,7 +528,7 @@ class ServicesController extends Curd
 
             $params['order_config_json'] = json_encode($orderConfigJson);
             // 写入订单
-            $this->insertMain($params, $premises);
+            $this->insertMain($params);
 
             Db::commit();
 
@@ -658,16 +658,13 @@ class ServicesController extends Curd
             $systemStatus = 'SENDING';  // 待发货
             // 立即结算
             if ($params['settlement_now'] == 'Y') {
-                if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
-                    $params['order_is_complete'] = 'Y';
-                    $systemStatus = 'DONE';
-                }
                 if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
                     $params['order_is_complete'] = 'N';
                     $systemStatus = "WAITING";
                 }
             }
             $params['pay_detail_item'] = [];
+            $wxAndAliPayStatus = 'Y';
             if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) {      // 线下支付
                 $params['order_status_system'] = $systemStatus;
                 $params['order_status_payment'] = 'SUCCESS';
@@ -713,25 +710,31 @@ class ServicesController extends Curd
                 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->save();
+//                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->save();
+                // 余额账户扣款数据
+                $params['waitToPayAccount']['cash'] = [
+                    'group_id' => $params['orderGroupId'],
+                    'member_id' => $params['join_order_member_id'],
+                    'amount' => $constituteList['CASH'],
+                    'nbr' => $params['join_order_member_id'] . '-CASH'
+                ];
 
                 $params['order_status_system'] = $systemStatus;
                 $params['order_status_payment'] = 'SUCCESS';
 
                 // 生成支付记录
-//                OrderService::createPayDetail($params);
                 $params['pay_detail_item'][] = $params;
                 $params['order_amount_pay'] = $orderAmountPay;
 
@@ -758,27 +761,32 @@ class ServicesController extends Curd
                 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->save();
-
+//                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->save();
+                // 储值卡账户扣款数据
+                $params['waitToPayAccount']['card'] = [
+                    'group_id' => $params['orderGroupId'],
+                    'member_id' => $params['join_order_member_id'],
+                    'amount' => $constituteList['CARD'],
+                    'nbr' => $params['join_order_member_id'] . '-CARD'
+                ];
 
                 $params['order_status_system'] = $systemStatus;
                 $params['order_status_payment'] = 'SUCCESS';
                 // 生成支付记录
                 $params['pay_detail_item'][] = $params;
-//                OrderService::createPayDetail($params);
 
                 $params['order_amount_pay'] = $orderAmountPay;
             }
@@ -799,6 +807,8 @@ class ServicesController 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')) {
+                            // 标记支付状态
+                            $wxAndAliPayStatus = 'N';
                             $params['order_status_system'] = 'PAYING';
                             $params['order_status_payment'] = 'PENDING';
                             $params['order_is_complete'] = 'N';
@@ -811,6 +821,8 @@ class ServicesController extends Curd
                     } 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')) {
+                            // 标记支付状态
+                            $wxAndAliPayStatus = 'N';
                             $params['order_status_system'] = 'PAYING';
                             $params['order_status_payment'] = 'PENDING';
                             $params['order_is_complete'] = 'N';
@@ -843,8 +855,8 @@ class ServicesController extends Curd
             }
             $params['order_config_json'] = json_encode($orderConfigJson);
             // 写入订单
-            $this->insertMain($params, $premises);
-            
+            $this->insertMain($params, $wxAndAliPayStatus);
+
             Db::commit();
 
             // 会员升级
@@ -861,50 +873,23 @@ class ServicesController extends Curd
                 }
                 $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
 
-                return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
+                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('创建订单失败');
         }
     }
 
-    public function restoreAccount($payDetailItem)
-    {
-        foreach ($payDetailItem as $item) {
-            $prepayId = '';
-            if ($item['order_status_payment'] == 'SUCCESS') {
-                if (in_array($item['pay_category'], ['MONEY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY'])) {
-                    $prepayId = $item['pay_category'];
-                }
-                if (strpos($item['pay_category'],'CASH') !== false || strpos($item['pay_category'],'CARD') !== false || strpos($item['pay_category'],'WELFARE') !== false || strpos($item['pay_category'],'VIP') !== false){
-                    $prepayId = $item['pay_category'];
-                    $account = MemberAccount::where('member_account_nbr', $prepayId)->first();
-                    $account->member_account_expend = $account->member_account_expend - $item['order_amount_pay'];
-                    $account->member_account_surplus = $account->member_account_surplus + $item['order_amount_pay'];
-                    $account->save();
-                }
-            }
-            if (!empty($prepayId)) {
-                PayDetail::where('pay_prepayid', $prepayId)
-                    ->where('join_pay_order_id', $item['orderGroupId'])
-                    ->whereJsonContains('join_pay_object_json->order_id',$item['orderId'])
-                    ->update(['pay_status' => 'WAITING']);
-            }
-        }
-    }
-
     public function pay(Request $request)
     {
         $params = $request->post();
@@ -988,7 +973,7 @@ class ServicesController extends Curd
                 }
                 $couponUseJson = $discountJson;
                 $this->changeOrderCouponStatus($couponUseJson, 'USED');
-//                // 释放下单时选的优惠券
+                // 释放下单时选的优惠券
 //                $order->order_discount_json = $this->releaseCoupon($discountJson);
             }
             if (empty($discountJson) && !empty($params['join_order_member_id']) && !empty($params['preferential'])) {
@@ -1294,9 +1279,9 @@ class ServicesController extends Curd
             }
             $payData['join_pay_member_id'] = $params['join_order_member_id'];
             $payData['join_pay_order_id'] = $order->order_groupby;
-            $payData['pay_paytimes'] = date('Y-m-d H:i:s');
             $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' ? (!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']]) : '[]';
@@ -1384,9 +1369,9 @@ class ServicesController extends Curd
                 // 会员升级
                 Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
             }
-            if($order->order_status_payment == 'SUCCESS'){
+            if ($order->order_status_payment == 'SUCCESS') {
                 // 上级提成
-                Event::dispatch('commission.order',$params);
+                Event::dispatch('commission.order', $params);
             }
 
             // 打小票
@@ -1421,7 +1406,7 @@ class ServicesController extends Curd
                     $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
                 }
 
-                return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
+                return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
             }
             _syslog("订单", "订单支付成功");
             return json_success('支付成功');
@@ -1547,7 +1532,11 @@ class ServicesController extends Curd
             if (sprintf("%.2f", $params['order_amount_pay']) != sprintf("%.2f", $constituteAmount)) {
                 throw new BusinessException('组合支付金额与应付金额不一致');
             }
-            $params['pay_detail_item'] = [];
+
+            $wxAndAliPayStatus = 'Y';
+            $waitToPayAccount = [];
+            // 清除订单的支付记录,重建
+            PayDetail::whereJsonContains('join_pay_object_json->order_id', $params['orderId'])->delete();
             if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) {  //线下付款
                 $order->order_status_system = $systemStatus;
                 $order->order_status_payment = 'SUCCESS';
@@ -1557,9 +1546,9 @@ class ServicesController extends Curd
                 if (isset($constituteList['OFFLINE'])) {
                     $params['order_amount_pay'] = $constituteList['OFFLINE'];
                     // 生成支付记录
-                    OrderService::createPayConstituteDetail($params, $payDetail);
+                    $params['order_status_payment'] = 'PENDING';
+                    OrderService::createProductPayConstituteDetail($params);
                     $params['order_status_payment'] = 'SUCCESS';
-                    $params['pay_detail_item'][] = $params;
                 }
                 $params['order_amount_pay'] = $orderAmountPay;
             }
@@ -1572,9 +1561,9 @@ class ServicesController extends Curd
                 if (isset($constituteList['MONEY'])) {
                     $params['order_amount_pay'] = $constituteList['MONEY'];
                     // 生成支付记录
-                    OrderService::createPayConstituteDetail($params, $payDetail);
+                    $params['order_status_payment'] = 'PENDING';
+                    OrderService::createProductPayConstituteDetail($params);
                     $params['order_status_payment'] = 'SUCCESS';
-                    $params['pay_detail_item'][] = $params;
                 }
                 $params['order_amount_pay'] = $orderAmountPay;
             }
@@ -1594,23 +1583,17 @@ class ServicesController extends Curd
                 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->save();
+                // 余额账户扣款数据
+                $waitToPayAccount['cash'] = [
+                    'group_id' => $params['orderGroupId'],
+                    'member_id' => $params['join_order_member_id'],
+                    'amount' => $constituteList['CASH'],
+                    'nbr' => $params['join_order_member_id'] . '-CASH'
+                ];
                 // 生成支付记录
-                OrderService::createPayConstituteDetail($params, $payDetail);
+                $params['order_status_payment'] = 'PENDING';
+                OrderService::createProductPayConstituteDetail($params);
                 $params['order_status_payment'] = 'SUCCESS';
-                $params['pay_detail_item'][] = $params;
                 $params['order_amount_pay'] = $orderAmountPay;
                 $order->order_status_system = $systemStatus;
                 $order->order_status_payment = 'SUCCESS';
@@ -1637,23 +1620,17 @@ class ServicesController extends Curd
                 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->save();
+                // 储值卡账户扣款数据
+                $waitToPayAccount['card'] = [
+                    'group_id' => $params['orderGroupId'],
+                    'member_id' => $params['join_order_member_id'],
+                    'amount' => $constituteList['CARD'],
+                    'nbr' => $params['join_order_member_id'] . '-CARD'
+                ];
                 // 生成支付记录
-                OrderService::createPayConstituteDetail($params, $payDetail);
+                $params['order_status_payment'] = 'PENDING';
+                OrderService::createProductPayConstituteDetail($params);
                 $params['order_status_payment'] = 'SUCCESS';
-                $params['pay_detail_item'][] = $params;
                 $params['order_amount_pay'] = $orderAmountPay;
                 $order->order_status_system = $systemStatus;
                 $order->order_status_payment = 'SUCCESS';
@@ -1672,26 +1649,30 @@ class ServicesController 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')) {
+                            // 标记支付状态
+                            $wxAndAliPayStatus = 'N';
                             $order->order_status_system = 'PAYING';
                             $order->order_status_payment = 'PENDING';
                             $order->order_is_complete = 'N';
-//                        Db::rollBack();
-//                        return json_fail('支付失败');
+                            $params['order_status_payment'] = 'PAYING';
                         } else {
                             $order->order_status_system = $systemStatus;
                             $order->order_status_payment = 'SUCCESS';
+                            $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')) {
+                            // 标记支付状态
+                            $wxAndAliPayStatus = 'N';
                             $order->order_status_system = 'PAYING';
                             $order->order_status_payment = 'PENDING';
                             $order->order_is_complete = 'N';
-//                        Db::rollBack();
-//                        return json_fail('支付失败');
+                            $params['order_status_payment'] = 'PAYING';
                         } else {
                             $order->order_status_system = $systemStatus;
                             $order->order_status_payment = 'SUCCESS';
+                            $params['order_status_payment'] = 'SUCCESS';
                         }
                     } else {
                         throw new BusinessException('付款码无效');
@@ -1699,7 +1680,7 @@ class ServicesController extends Curd
                 }
 
                 // 生成支付记录
-                OrderService::createPayConstituteDetail($params, $payDetail);
+                OrderService::createProductPayConstituteDetail($params);
                 // 账户支付的金额
                 $params['order_amount_pay'] = $orderAmountPay;
             }
@@ -1708,9 +1689,6 @@ class ServicesController extends Curd
                 $orderConfigJson = json_decode($order->order_config_json, true);
             }
             $orderConfigJson['preferential'] = $params['preferential'] ?? '';
-            if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) {
-                SysDept::where('dept_id', $orderConfigJson['tableid'])->where('dept_category', '桌台')->update(['dept_status' => 'ACTIVED']);
-            }
             $order->order_config_json = json_encode($orderConfigJson);
             $order->order_amount_pay = $params['order_amount_pay'];
 
@@ -1722,12 +1700,26 @@ class ServicesController extends Curd
                     'order_sheet_status' => $systemStatus,
                 ]);
             }
-            // 清除paydetail 中的未支付记录
-            PayDetail::where('join_pay_order_id', $params['orderGroupId'])
-                ->whereJsonContains('join_pay_object_json->order_id', $params['order_id'])
-                ->where('pay_status', '<>', 'SUCCESS')
-                ->delete();
 
+            if ($wxAndAliPayStatus == 'Y') {
+                PayDetail::whereJsonContains('join_pay_object_json->order_id', $params['orderId'])->update([
+                    'pay_status' => 'SUCCESS',
+                    'pay_paytimes' => date('Y-m-d H:i:s')
+                ]);
+                // 扣款
+                foreach ($waitToPayAccount as $item) {
+                    $accountNbr = $item['nbr'];
+                    $account = MemberAccount::where('member_account_nbr', $accountNbr)->first();
+                    $account->member_account_expend = $account->member_account_expend + $amount;
+                    if ($account->member_account_surplus < $amount && strpos($accountNbr, 'CASH') !== false) {
+                        $account->member_account_added = $account->member_account_added - ($amount - $account->member_account_surplus);
+                        $account->member_account_surplus = 0;
+                    } else {
+                        $account->member_account_surplus = $account->member_account_surplus - $amount;
+                    }
+                    $account->save();
+                }
+            }
             $writeOffDate = [];
             $applyData = [];
             // 有预约单,状态已完成
@@ -1807,9 +1799,9 @@ class ServicesController extends Curd
                 // 会员升级
                 Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
             }
-            if($order->order_status_payment == 'SUCCESS'){
+            if ($order->order_status_payment == 'SUCCESS') {
                 // 上级提成
-                Event::dispatch('commission.order',$params);
+                Event::dispatch('commission.order', $params);
             }
 
             // 打小票
@@ -1845,7 +1837,7 @@ class ServicesController extends Curd
                 // 清除支付记录,恢复账户金额
 //                $this->restoreAccount($params['pay_detail_item']);
 
-                return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
+                return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
             }
             _syslog("订单", "订单支付成功");
             return json_success('支付成功');
@@ -1866,7 +1858,7 @@ class ServicesController extends Curd
      * @return void
      * @throws BusinessException
      */
-    public function insertMain($params, $premises)
+    public function insertMain($params, $wxAndAliPayStatus = 'Y')
     {
         try {
             if (empty($params['order_extend_json'])) {
@@ -1876,6 +1868,12 @@ class ServicesController 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'] ?? '';
             foreach ($params['goodsContentList'] as $goods) {
@@ -1922,12 +1920,10 @@ class ServicesController extends Curd
                 $params['order_express_goods'] = json_encode(['sheet' => $sheetIds]);
 
                 $this->insertExpressOne($params, $orderId);
-
                 // 写到权益里
-                $this->insertBenefitOne($params, $goods, $orderId);
-
-                // 打小票
-//                $this->printerTicket($params, $premises, $orderId);
+                if ($params['order_status_payment'] == 'SUCCESS') {
+                    $this->insertBenefitOne($params, $goods, $orderId);
+                }
             }
         } catch (\Exception $e) {
             dump($e->getMessage());
@@ -1935,6 +1931,35 @@ class ServicesController extends Curd
         }
     }
 
+    /**
+     * @Desc 扣除账户金额
+     * @Author Gorden
+     * @Date 2024/9/26 14:16
+     *
+     * @param $accountNbr
+     * @param $amount
+     * @return void
+     */
+    public function deductAmount($accountNbr, $amount)
+    {
+        try {
+            $account = MemberAccount::where('member_account_nbr', $accountNbr)->first();
+            $account->member_account_expend = $account->member_account_expend + $amount;
+            if ($account->member_account_surplus < $amount && strpos($accountNbr, 'CASH') !== false) {
+                $account->member_account_added = $account->member_account_added - ($amount - $account->member_account_surplus);
+                $account->member_account_surplus = 0;
+            } else {
+                $account->member_account_surplus = $account->member_account_surplus - $amount;
+            }
+
+            $account->save();
+        } catch (\Exception $e) {
+            _syslog("下单扣款", "扣款失败");
+
+            throw new BusinessException("账户扣款失败");
+        }
+    }
+
     /**
      * @Desc 打小票
      * @Author Gorden
@@ -2224,7 +2249,7 @@ class ServicesController extends Curd
                     $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_status' => $params['settlement_now'] == 'Y' && $params['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'],

+ 274 - 4
app/admin/controller/order/WholeController.php

@@ -3352,8 +3352,8 @@ class WholeController extends Curd
                 'join_benefit_goods_sku_id' => $goods['skuId'] ?? '',
                 'join_benefit_order_id' => $params['orderId'],
                 'member_benefit_status' => 'ACTIVED',
-                'member_benefit_category' => $goods['category'],
-                'member_benefit_name' => $goods['goods_name'],
+                'member_benefit_category' => $goods['category'] ?? '',
+                'member_benefit_name' => $goods['goods_name'] ?? '',
                 'member_benefit_limit_count' => $params['order_sheet_num'],
                 'member_benefit_used_count' => 0,
                 'member_benefit_remark' => $params['order_remark'] ?? '',
@@ -4748,8 +4748,7 @@ class WholeController extends Curd
                     }
                     // 支付记录
                     PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_prepayid', 'WXPAY')->update(['pay_status' => 'SUCCESS']);
-                    // 其他支付方式 扣
-//                    $this->deductAccount($order->order_groupby, 'WXPAY');
+
                     // 优惠券标记使用
                     $this->changeOrderCouponStatus($discountJson, 'USED');
 
@@ -4803,6 +4802,277 @@ class WholeController extends Curd
         }
     }
 
+    /**
+     * @Desc 查询订单状态
+     * @Author Gorden
+     * @Date 2024/8/19 11:55
+     *
+     * @param Request $request
+     * @return Response|void
+     */
+    public function getProductOrderPayStatus(Request $request)
+    {
+        $groupId = $request->get('group_id');
+        if (!$groupId) {
+            return json_fail('订单不存在');
+        }
+
+        $orders = Order::where('order_groupby', $groupId)->get()->toArray();
+        if (empty($orders)) {
+            return json_fail('订单不存在');
+        }
+
+        $payDetailType = PayDetail::where('join_pay_order_id', $groupId)->pluck('pay_prepayid')->toArray();
+        try {
+            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);
+                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) {
+                        $orderUpdateData = ['order_status_payment' => 'SUCCESS'];
+                        if (in_array($order['order_category'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE'])) {
+                            $orderUpdateData['order_status_system'] = 'WAITING';
+                        } else {
+                            $orderUpdateData['order_status_system'] = 'SENDING';
+                        }
+                        // 主订单
+                        Order::where('order_groupby', $groupId)->update($orderUpdateData);
+                        // Sheet
+                        OrderSheet::where('join_sheet_order_id', $order['order_id'])->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
+
+                        // 支付记录
+                        PayDetail::where('join_pay_order_id', $order['order_groupby'])->where('pay_prepayid', 'WXPAY')->update(['pay_status' => 'SUCCESS']);
+
+                        $discountJson = [];
+                        if (!empty($orders[0]['order_discount_json'])) {
+                            $discountJson = json_decode($orders[0]['order_discount_json'], true);
+                        }
+                        // 优惠券标记使用
+                        $this->changeOrderCouponStatus($discountJson, 'USED');
+                    }
+                }
+            } else if (in_array('ALIPAY', $payDetailType)) {
+                $result = Pay::alipay(config('payment.alipay'))->find($groupId);
+                $result = json_decode(json_encode($result), true);
+//                $result = '{"code":"10000","msg":"Success","buyer_logon_id":"138******93","buyer_pay_amount":"5.87","fund_bill_list":[{"amount":"5.69","fund_channel":"ALIPAYACCOUNT"},{"amount":"0.18","fund_channel":"COUPON"},{"amount":"0.13","fund_channel":"DISCOUNT"}],"invoice_amount":"5.69","out_trade_no":"OD2409251550Q07A","point_amount":"0.00","receipt_amount":"6.00","send_pay_date":"2024-09-25 15:50:22","total_amount":"6.00","trade_no":"2024092523001439431419750998","trade_status":"TRADE_SUCCESS","buyer_open_id":"04309N2aVhSZz4cKwN_DN2DQa7ekM3z5n8kscQHsmIZOJsf"}';
+//                $result = json_decode($result, true);
+                if (!empty($result['code']) && $result['code'] == '10000' && !empty($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') {
+                    $payStatus = 'Y';
+                    foreach ($orders as $order) {
+                        $orderUpdateData = ['order_status_payment' => 'SUCCESS'];
+                        if (in_array($order['order_category'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE'])) {
+                            $orderUpdateData['order_status_system'] = 'WAITING';
+                        } else {
+                            $orderUpdateData['order_status_system'] = 'SENDING';
+                        }
+                        // 主订单
+                        Order::where('order_groupby', $groupId)->update($orderUpdateData);
+                        // Sheet
+                        OrderSheet::where('join_sheet_order_id', $order['order_id'])->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
+                        // 支付记录
+                        PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_prepayid', 'ALIPAY')->update(['pay_status' => 'SUCCESS']);
+                        // 优惠券标记使用
+                        $discountJson = [];
+                        if (!empty($orders[0]['order_discount_json'])) {
+                            $discountJson = json_decode($orders[0]['order_discount_json'], true);
+                        }
+                        $this->changeOrderCouponStatus($discountJson, 'USED');
+                    }
+                }
+            }
+            if ($payStatus == 'Y') {
+                // 如果有余额、VIP、福利账户支付
+                if (in_array($orders[0]['join_order_member_id'] . '-CASH', $payDetailType)) {
+                    $cashAmount = PayDetail::where('join_pay_order_id', $groupId)
+                        ->where('pay_prepayid', $orders[0]['join_order_member_id'] . '-CASH')
+                        ->sum('pay_amount');
+                    $this->deductAccountOne($groupId, $orders[0]['join_order_member_id'] . '-CASH', $cashAmount);
+                }
+                if (in_array($orders[0]['join_order_member_id'] . '-VIP', $payDetailType)) {
+                    $cashAmount = PayDetail::where('join_pay_order_id', $groupId)
+                        ->where('pay_prepayid', $orders[0]['join_order_member_id'] . '-VIP')
+                        ->sum('pay_amount');
+                    $this->deductAccountOne($groupId, $orders[0]['join_order_member_id'] . '-VIP', $cashAmount);
+                }
+                if (in_array($orders[0]['join_order_member_id'] . '-WELFARE', $payDetailType)) {
+                    $cashAmount = PayDetail::where('join_pay_order_id', $groupId)
+                        ->where('pay_prepayid', $orders[0]['join_order_member_id'] . '-WELFARE')
+                        ->sum('pay_amount');
+                    $this->deductAccountOne($groupId, $orders[0]['join_order_member_id'] . 'WELFARE', $cashAmount);
+                }
+
+                Db::commit();
+
+                // 服务产生权益
+                if (in_array($orders[0]['order_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
+                    $this->insertBenefitService($groupId);
+                }
+                // 产生套包权益
+                if (in_array($orders[0]['order_classify'], ['PACKAGE'])) {
+                    $this->insertBenefitPackage($groupId);
+                }
+
+                return json_success('success');
+            }
+
+
+            Db::rollBack();
+            return json_fail('没有查询到记录');
+        } catch (BusinessException $e) {
+            Db::rollBack();
+            _syslog("支付轮询", '订单支付异常:' . $e->getMessage());
+            return json_fail($e->getMessage());
+        } catch (\Exception $e) {
+            dump($e->getMessage());
+            Db::rollBack();
+            return json_fail('查询失败');
+        }
+    }
+
+    /**
+     * @Desc 大额支付轮询中的账户扣款
+     * @Author Gorden
+     * @Date 2024/9/26 13:36
+     *
+     * @param $accountNbr
+     * @param $amount
+     * @return void
+     * @throws BusinessException
+     */
+    public function deductAccountOne($groupId, $accountNbr, $amount)
+    {
+        try {
+            $account = MemberAccount::where('member_account_nbr', $accountNbr)->first();
+            $account->member_account_expend = $account->member_account_expend + $amount;
+            if ($account->member_account_surplus < $amount && strpos($accountNbr, 'CASH') !== false) {
+                $account->member_account_added = $account->member_account_added - ($amount - $account->member_account_surplus);
+                $account->member_account_surplus = 0;
+            } else {
+                $account->member_account_surplus = $account->member_account_surplus - $amount;
+            }
+            $account->save();
+
+            PayDetail::where('pay_prepayid', $accountNbr)
+                ->where('join_pay_order_id', $groupId)
+                ->update([
+                    'pay_paytimes' => date('Y-m-d H:i:s'),
+                    'pay_status' => 'SUCCESS'
+                ]);
+        } catch (\Exception $e) {
+            Log::info("获取大额支付状态:扣除账户金额失败", ['nbr' => $accountNbr, 'amount' => $account]);
+
+            throw new BusinessException("账户金额扣除失败");
+        }
+    }
+
+    /**
+     * @Desc 服务权益设置
+     * @Author Gorden
+     * @Date 2024/9/26 16:34
+     *
+     * @param $groupId
+     * @return void
+     */
+    public function insertBenefitService($groupId)
+    {
+        try {
+            $orders = Order::where('order_groupby', $groupId)->select('order_id', 'order_classify')->get()->toArray();
+            $orderIds = array_column($orders, 'order_id');
+            $sheets = OrderSheet::whereIn('join_sheet_order_id', $orderIds)->get()->toArray();
+            foreach ($sheets as $sheet) {
+                $params = [];
+                foreach ($orders as $order) {
+                    if ($sheet['join_sheet_order_id'] == $order['order_id']) {
+                        $params['goods_classify'] = $order['order_classify'];
+                    }
+                }
+                $params['join_order_member_id'] = $sheet['join_sheet_member_id'];
+                $params['join_sheet_goods_id'] = $sheet['join_sheet_goods_id'];
+                $params['join_sheet_goods_sku_id'] = $sheet['join_sheet_goods_sku_id'];
+                $params['orderId'] = $sheet['join_sheet_order_id'];
+                $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
+                for ($i = 0; $i < $sheet['order_sheet_num']; $i++) {
+                    $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
+                    $this->insertAppointment($params, []);
+                }
+
+                $goodsModel = Goods::where('goods_id', $sheet['join_sheet_goods_id'])->first();
+                $goods = [];
+                if (!empty($goodsModel)) {
+                    $goods['goods_id'] = $sheet['join_sheet_goods_id'];
+                    $goods['skuId'] = $sheet['join_sheet_goods_sku_id'];
+                    $goods['category'] = $goodsModel->goods_classify;
+                    $goods['goods_name'] = $goodsModel->goods_name;
+                }
+                $params['order_sheet_num'] = $sheet['order_sheet_num'];
+                $this->insertMemberBenefit($params, $goods);
+            }
+        } catch (\Exception $e) {
+            _syslog("下单", '权益设置失败');
+        }
+    }
+
+    /**
+     * @Desc 套包权益设置
+     * @Author Gorden
+     * @Date 2024/9/26 16:34
+     *
+     * @param $groupId
+     * @return void
+     */
+    public function insertBenefitPackage($groupId)
+    {
+        try {
+            $orders = Order::where('order_groupby', $groupId)->select('order_id', 'order_classify')->get()->toArray();
+            $orderIds = array_column($orders, 'order_id');
+            $sheets = OrderSheet::whereIn('join_sheet_order_id', $orderIds)->get()->toArray();
+            foreach ($sheets as $sheet) {
+                $params = [];
+                $params['orderId'] = $sheet['join_sheet_order_id'];
+                foreach ($orders as $order) {
+                    if ($sheet['join_sheet_order_id'] == $order['order_id']) {
+                        $params['goods_classify'] = $order['order_classify'];
+                    }
+                }
+                $params['packageId'] = $sheet['join_sheet_goods_id'];;
+                $components = GoodsComponent::with([
+                    'goods' => function ($query) {
+                        $query->select('goods_id', 'goods_name', 'goods_classify');
+                    }
+                ])->where('join_component_master_goods_id', $params['packageId'])
+                    ->get()
+                    ->toArray();
+                $params['join_order_member_id'] = $sheet['join_sheet_member_id'];
+                foreach ($components as $component) {
+                    $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
+                    $componentJson = json_decode($component['goods_component_json'], true);
+                    $params['join_sheet_goods_id'] = $component['join_component_goods_id'];
+                    $params['order_sheet_num'] = $sheet['order_sheet_num'] * $componentJson['nbr'];
+                    $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
+                    for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
+                        $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
+                        // 入预约记录
+                        $this->insertAppointment($params, []);
+                    }
+                    $goods['goods_id'] = $component['join_component_goods_id'];
+                    $goods['goods_name'] = $component['goods']['goods_name'];
+                    $goods['goods_classify'] = $component['goods']['goods_classify'];
+                    $goods['skuId'] = $componentJson['sku_id'];
+                    $goods['category'] = 'SERVICE';
+                    // 权益表
+                    $this->insertMemberBenefit($params, $goods);
+                }
+            }
+        } catch (\Exception $e) {
+            _syslog("下单", '权益设置失败');
+        }
+    }
+
     public function deductAccount($orderId, $orderGroup, $payWay)
     {
         $payDetails = PayDetail::where('join_pay_order_id', $orderGroup)

+ 24 - 0
app/admin/service/order/OrderService.php

@@ -476,6 +476,30 @@ class OrderService
         $payDetail->save();
     }
 
+
+    /**
+     * 组合支付,PayDetail
+     */
+    public static function createProductPayConstituteDetail($params)
+    {
+        dump($params);
+        $payDetail = new PayDetail();
+        $payDetail->join_pay_member_id = $params['join_order_member_id'];
+        $payDetail->join_pay_order_id = $params['orderGroupId'];
+        $payDetail->pay_category = $params['goods_classify'] ?? '';
+        $payDetail->pay_json_request = json_encode($params);
+        $payDetail->pay_addtimes = time();
+        $payDetail->pay_prepayid = $params['pay_category'];
+        $payDetail->pay_json_response = $params['pay_json_response'] ?? json_encode([
+            'pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')
+        ]);
+        $payDetail->pay_amount = $params['order_amount_pay'];
+        $payDetail->pay_paytimes = date('Y-m-d H:i:s');
+        $payDetail->pay_status = $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING';
+        $payDetail->join_pay_object_json = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';
+        $payDetail->save();
+    }
+
     public static function getPayWayByPrepayId($prepayId)
     {
         $payWay = '';

+ 1 - 0
route/admin.php

@@ -938,6 +938,7 @@ Route::group('/admin', function () {
             Route::post('/printerWriterOff', [\app\admin\controller\order\WholeController::class, 'printerWriterOff']);
             Route::post('/cancelOrder', [\app\admin\controller\order\WholeController::class, 'cancelOrder']);
             Route::get('/getOrderPayStatus', [\app\admin\controller\order\WholeController::class, 'getOrderPayStatus']);
+            Route::get('/getProductOrderPayStatus', [\app\admin\controller\order\WholeController::class, 'getProductOrderPayStatus']);
             Route::get('/writeOffList', [\app\admin\controller\order\WholeController::class, 'writeOffList']);
         })->middleware([
             \app\middleware\AdminAuthCheck::class