15 コミット b40478d9da ... 0b8f230417

作者 SHA1 メッセージ 日付
  gorden 0b8f230417 会员合伙人 2 ヶ月 前
  gorden f047f06569 合伙人 2 ヶ月 前
  gorden d182ccae16 Merge branch 'dev' 2 ヶ月 前
  yb 478f47d53e fixbug:调整来源渠道类型 2 ヶ月 前
  gorden 0dfbd89ee2 业务赠送 2 ヶ月 前
  gorden 21ef4fd6d7 会员加筛选条件 2 ヶ月 前
  gorden 0310628152 自动取消订单恢复优惠券 2 ヶ月 前
  gorden ac3e967422 fixbug:支付异常,释放优惠券 2 ヶ月 前
  gorden e3e8b4ff90 Merge branch 'dev' 2 ヶ月 前
  gorden b43753de32 业务招待 2 ヶ月 前
  gorden 64bbe73821 订单搜索 2 ヶ月 前
  gorden 79e2102b76 周期券 2 ヶ月 前
  gorden 8e12b82d6f 充值订单归类 2 ヶ月 前
  gorden 42feee1ef0 充值订单归类 2 ヶ月 前
  gorden 4107e2ba21 核销加服务人员 2 ヶ月 前

+ 105 - 9
app/admin/controller/coupon/CouponController.php

@@ -45,7 +45,7 @@ class CouponController extends Curd
         if (!empty($joinCouponCategoryId)) {
             $where['join_coupon_category_id'] = ['in', implode(',', $joinCouponCategoryId)];
         }
-        if (!empty($where['coupon_addtimes'])){
+        if (!empty($where['coupon_addtimes'])) {
             $where['coupon_addtimes'][0] = strtotime($where['coupon_addtimes'][0]);
             $where['coupon_addtimes'][1] = strtotime($where['coupon_addtimes'][1]);
         }
@@ -125,7 +125,7 @@ class CouponController extends Curd
                                 }
                             }
                         }
-                    }else if(!isset($couponJson['member']['where']) || empty($couponJson['member']['where'])){
+                    } else if (!isset($couponJson['member']['where']) || empty($couponJson['member']['where'])) {
                         $item['coupon_use_member'] = 'all';
                     }
                 }
@@ -135,6 +135,13 @@ class CouponController extends Curd
                     $item['premises_range'] = 'all';
                 }
             }
+            if (!empty($item['coupon_period_json'])) {
+                $periodJson = json_decode($item['coupon_period_json'], true);
+                $item['period'] = $periodJson['length'] ?? '';
+                $item['period_unit'] = $periodJson['unit'] ?? '';
+                $item['period_unit_num'] = $periodJson['val'] ?? '';
+                $item['period_nbr'] = $periodJson['nbr'] ?? '';
+            }
             if (!empty($item['coupon_validdate_begin']) && !empty($item['coupon_validdate_end'])) {
                 $item['coupon_use_time'] = 'date';
             } elseif ($item['coupon_validdate_day']) {
@@ -155,7 +162,7 @@ class CouponController extends Curd
                     }
                 }
             }
-            $item['coupon_explain'] = CouponService::couponClassifyInfo($item['coupon_classify'],$item['coupon_category'], $item['coupon_value'], $item['coupon_minimum_limit']);
+            $item['coupon_explain'] = CouponService::couponClassifyInfo($item['coupon_classify'], $item['coupon_category'], $item['coupon_value'], $item['coupon_minimum_limit']);
             unset($item['detail']);
         }
 
@@ -298,9 +305,57 @@ class CouponController extends Curd
 
         $data['coupon_json'] = json_encode($couponJson, JSON_UNESCAPED_UNICODE);
 
+        // 处理周期优惠券
+        if ($params['coupon_is_period'] != 'N') {
+            $this->disposePeriod($params);
+            $data['coupon_period_json'] = json_encode([
+                'length' => $params['period'],
+                'unit' => $params['period_unit'],
+                'val' => $params['period_unit_num'],
+                'nbr' => $params['period_nbr']
+            ]);
+        }
+
         return $data;
     }
 
+    public function disposePeriod($params)
+    {
+        if (empty($params['period']) || empty($params['period_unit']) || empty($params['period_unit_num']) || empty($params['period_nbr'])) {
+            throw new BusinessException("周期数据异常");
+        }
+
+        if ($params['period'] != 'TO_EXPIRE') {
+            return $params;
+        }
+        if (empty($params['coupon_validdate_end'])) {
+            throw new BusinessException("周期数据异常");
+        }
+        try {
+            $endTimeUnix = strtotime($params['coupon_validdate_end']);
+            if ($params['period_unit'] == 'day') {
+                $diff = ceil(($endTimeUnix - time()) / (3600 * 24));
+            } else if ($params['period_unit'] == 'week') {
+                $diff = ceil(($endTimeUnix - time()) / (3600 * 24));
+                $diff = ceil($diff / 7);
+            } else if ($params['period_unit'] == 'month') {
+                $endTime = new \DateTime($params['coupon_validdate_end']);
+                $nowTime = new \DateTime(date('Y-m-d'));
+                $interval = $nowTime->diff($endTime);
+                $diff = $interval->y * 12 + $interval->m + 1;
+            }
+
+            if ($params['period_nbr'] != ceil($diff / $params['period_unit_num'])) {
+                throw new BusinessException("期数设置错误");
+            }
+
+            return $params;
+        } catch (\Exception $e) {
+
+            throw new BusinessException("周期数据异常");
+        }
+    }
+
     public function customSend(Request $request)
     {
         $chooseCoupons = $request->post('chooseCoupons', []);
@@ -334,20 +389,49 @@ class CouponController extends Curd
                             $params['coupon_detail_deadline_datetime'] = $coupon['coupon_validdate_end'];
                         } elseif ($coupon['coupon_validdate_day'] > 0) {
                             $endUnix = strtotime($chooseCoupon['gain_datetime']);
-                            $params['coupon_detail_deadline_datetime'] = date('Y-m-d H:i:s', $endUnix + ($coupon['coupon_validdate_day'] * 24 * 3600) -1);
+                            $params['coupon_detail_deadline_datetime'] = date('Y-m-d H:i:s', $endUnix + ($coupon['coupon_validdate_day'] * 24 * 3600) - 1);
                         }
                         foreach ($memberList as $item) {
                             $params['member_id'] = $item;
+                            if ($coupon['coupon_is_period'] == 'Y') {
+                                if (CouponDetail::where('join_coupon_detail_member_id', $item)->where('join_detail_coupon_id', $coupon['coupon_id'])->exists()) {
+                                    throw new BusinessException("请勿重复发放周期券");
+                                }
+                                $params['coupon_detail_period_num'] = 1;
+                                $periodJson = json_decode($coupon['coupon_period_json'], true);
+                                if ($periodJson['unit'] == 'day') {
+                                    $val = $periodJson['val'] - 1;
+                                    if ($val < 1) {
+                                        $params['coupon_detail_deadline_datetime'] = date('Y-m-d 23:59:59');
+                                    }else{
+                                        $params['coupon_detail_deadline_datetime'] = date('Y-m-t 23:59:59',strtotime("+".$val." day"));
+                                    }
+                                } elseif ($periodJson['unit'] == 'week') {
+                                    $val = $periodJson['val'] - 1;
+                                    if ($val < 1){
+                                        $params['coupon_detail_deadline_datetime'] = date('Y-m-d 23:59:59', strtotime('this week Sunday'));
+                                    }else{
+                                        $params['coupon_detail_deadline_datetime'] = date('Y-m-t 23:59:59',strtotime("+".$val.' week',date('Y-m-d',strtotime("+".$val." month"))));
+                                    }
+                                } elseif ($periodJson['unit'] == 'month'){
+                                    $val = $periodJson['val'] - 1;
+                                    if ($val < 1){
+                                        $params['coupon_detail_deadline_datetime'] = date('Y-m-t 23:59:59');
+                                    }else{
+                                        $params['coupon_detail_deadline_datetime'] = date('Y-m-t 23:59:59',strtotime("+".$val." month"));
+                                    }
+                                }
+                            }
                             if ($chooseCoupon['nbr'] > 0) {
                                 // 有发行数量
-                                if ($coupon['coupon_number'] != 0){
+                                if ($coupon['coupon_number'] != 0) {
                                     // 查询共发行了多少张了
-                                    $count = CouponDetail::where('join_detail_coupon_id',$coupon['coupon_id'])->count();
-                                    if (!isset($couponNbr[$coupon['coupon_id']])){
+                                    $count = CouponDetail::where('join_detail_coupon_id', $coupon['coupon_id'])->count();
+                                    if (!isset($couponNbr[$coupon['coupon_id']])) {
                                         $couponNbr[$coupon['coupon_id']] = $count;
                                     }
-                                    if ($couponNbr[$coupon['coupon_id']] + $chooseCoupon['nbr'] > $coupon['coupon_number']){
-                                        throw new BusinessException($coupon['coupon_name']."超出发行数量");
+                                    if ($couponNbr[$coupon['coupon_id']] + $chooseCoupon['nbr'] > $coupon['coupon_number']) {
+                                        throw new BusinessException($coupon['coupon_name'] . "超出发行数量");
                                     }
                                     $couponNbr[$coupon['coupon_id']] = $couponNbr[$coupon['coupon_id']] + $chooseCoupon['nbr'];
                                 }
@@ -593,6 +677,18 @@ class CouponController extends Curd
 
         $data['coupon_json'] = json_encode($couponJson, JSON_UNESCAPED_UNICODE);
 
+        $data['coupon_period_json'] = '[]';
+        // 处理周期优惠券
+        if ($params['coupon_is_period'] != 'N') {
+            $this->disposePeriod($params);
+            $data['coupon_period_json'] = json_encode([
+                'length' => $params['period'],
+                'unit' => $params['period_unit'],
+                'val' => $params['period_unit_num'],
+                'nbr' => $params['period_nbr']
+            ]);
+        }
+
         unset($data[$primary_key]);
         return [$id, $data];
     }

+ 55 - 8
app/admin/controller/member/BenefitController.php

@@ -8,11 +8,13 @@ use app\model\Appointment;
 use app\model\Member;
 use app\model\MemberBenefit;
 use app\model\Order;
+use app\model\SysDept;
 use app\model\SysUser;
 use support\Db;
 use support\exception\BusinessException;
 use support\Redis;
 use support\Request;
+use Webman\Event\Event;
 
 class BenefitController extends Curd
 {
@@ -123,7 +125,6 @@ class BenefitController extends Curd
         if ($redisCode != $code) {
             return json_fail("验证码错误,请重新输入");
         }
-        Redis::del($key);
 
         $benefit = MemberBenefit::where('member_benefit_id', $benefitId)
             ->where('join_benefit_member_id', $memberId)
@@ -141,19 +142,29 @@ class BenefitController extends Curd
         Db::beginTransaction();
         try {
             // 减额度
+            $benefitUsed = [];
+            $appointmentIds = [];
             $benefit->member_benefit_used_count = $benefit->member_benefit_used_count + $nbr;
+            if($benefit->member_benefit_used_count >= $benefit->member_benefit_limit_count){
+                $benefit->member_benefit_status = 'DONE';
+                if(!empty($benefit->join_benefit_order_id)){
+                    $benefitUsed[$benefit->join_benefit_order_id][] = $benefitId;
+//                    Order::where('order_id',$benefit->join_benefit_order_id)->update(['order_is_complete'=>'Y','order_status_system'=>'DONE']);
+                }
+            }
             $benefit->save();
             // 记录核销
             $params = [
-                'dept_premises_id' => $request->post('dept_premises_id'),
-                'order_remark'=>$request->post('remark'),
-                'write_off_member_id' => $request->post('write_off_member_id'),
-                'join_order_member_id' => $memberId
+                'dept_premises_id' => $request->post('dept_premises_id',''),
+                'order_remark'=>$request->post('remark',''),
+                'write_off_member_id' => $request->post('write_off_member_id',''),
+                'join_order_member_id' => $memberId,
+                'charge_waiter' => $request->post('charge_waiter'),
             ];
-            $writeOffData = OrderService::generateWriteOffDataByOrderProcess($params);
+            $writeOffData = OrderService::generateWriteOffData($params);
 
             $appointments = Appointment::where('join_appointment_member_benefit_id', $benefitId)
-                ->where('appointment_status', 'INIT')
+                ->whereIn('appointment_status', ['INIT','WAITING','PENDING','DOING'])
                 ->limit($nbr)
                 ->get();
             foreach ($appointments as $appointment) {
@@ -166,13 +177,49 @@ class BenefitController extends Curd
                     'appointment_done_json' => json_encode($writeOffData)
                 ]);
             }
+            // 订单服务是否用完了
+            foreach ($benefitUsed as $key => $item) {
+                $orderUsedComplete = 'Y';
+                $orderBenefits = MemberBenefit::where('join_benefit_order_id', $key)->get()->toArray();
+                foreach ($orderBenefits as $orderBenefit) {
+                    if ($orderBenefit['member_benefit_used_count'] >= $orderBenefit['member_benefit_limit_count']) {
+                        continue;
+                    }
+                    if (!in_array($orderBenefit['member_benefit_id'], $item)) {
+                        $orderUsedComplete = 'N';
+                    }
+                }
+                if ($orderUsedComplete == 'Y') {
+                    Order::where('order_id', $key)->update(['order_is_complete' => 'Y', 'order_status_system' => 'DONE']);
+                }
+            }
+
+            // 核销服务回写process
+            $dept = [];
+            if (!empty($request->post('dept_premises_id'))) {
+                $dept = SysDept::where('dept_id', $request->post('dept_premises_id'))
+                    ->orWhere('dept_name', $request->post('dept_premises_id'))
+                    ->select('dept_id', 'dept_name', 'dept_status', 'dept_category', 'dept_super_id', 'dept_super_path')
+                    ->first();
+            }
+            $params['charge_amount'] = $nbr;
+            $params['goods_id'] = !empty($benefit->join_benefit_goods_id) ? $benefit->join_benefit_goods_id : (!empty($benefit->join_benefit_package_id) ? $benefit->join_benefit_package_id : '');
+            $params['goods_sku_id'] = $benefit->join_benefit_goods_sku_id;
+            $params['order_id'] = $benefit->join_benefit_order_id;
+            $params['appointment_ids'] = $appointmentIds;
+            $params['dept'] = $dept;
+            $params['write_off_data'] = OrderService::generateWriteOffDataByOrderProcess($params);
+            // 触发事件
+            Event::dispatch('order.write_off', $params);
+
+            Redis::del($key);
 
             Db::commit();
 
             _syslog("核销","核销成功");
             return json_success('核销成功');
         } catch (\Exception $e) {
-            dump($e->getMessage());
+            dump($e->getMessage().$e->getLine());
             Db::rollBack();
             _syslog("核销","核销失败");
             return json_fail('核销失败');

+ 10 - 7
app/admin/controller/notify/RechargeController.php

@@ -133,13 +133,16 @@ class RechargeController
             $memberAccount->save();
            
             // 根据最新的数据,更新用户等级
-            $member = Member::find($payDetail->join_pay_member_id);
-            $roleId = RechargeService::disposeRole($payDetail->join_pay_member_id, $payDetail->pay_amount);
-            if ($roleId && $member->join_member_role_id != $roleId) {
-                $member->join_member_role_id = $roleId;
-                $member->save();
-                // 处理增值套包、组件
-                RechargeService::disposeAdded($roleId, $payDetail->join_pay_member_id);
+            // 临时屏蔽该会员升级
+            if (!in_array($payDetail->join_pay_member_id,['MR2409132254Z9VW'])) {
+                $member = Member::find($payDetail->join_pay_member_id);
+                $roleId = RechargeService::disposeRole($payDetail->join_pay_member_id, $payDetail->pay_amount);
+                if ($roleId && $member->join_member_role_id != $roleId) {
+                    $member->join_member_role_id = $roleId;
+                    $member->save();
+                    // 处理增值套包、组件
+                    RechargeService::disposeAdded($roleId, $payDetail->join_pay_member_id);
+                }
             }
             Db::commit();
 

+ 8 - 14
app/admin/controller/order/DishesController.php

@@ -32,6 +32,7 @@ class DishesController extends Curd
     {
         [$where, $format, $limit, $field, $order] = $this->selectInput($request);
 
+        $where['order_classify'] = 'DISHES';
         if (!empty($where['order_addtimes'])) {
             $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
             $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
@@ -40,38 +41,31 @@ class DishesController extends Curd
         $order = $request->get('order', 'desc');
         $orderId = $request->get('order_id', '');
         $field = $field ?? 'order_addtimes';
-        // $where['order_category'] = 'DISHES';
         if (!empty($where['order_status_system']) && in_array($where['order_status_system'], ['PENDING', 'WAITING', 'SENDING', 'RECVING', 'SIGNED', 'CONFIRM'])) {
             $where['order_is_complete'] = 'N';
             $where['order_category'] = ['<>', 'RETURN'];
         }
-        $goodsClassify = 'MEALS';
         $orderIds = [];
         if (!empty($orderId)) {
-            $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')->pluck('order_id')->toArray();
+            $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')
+                ->where('order_classify', 'DISHES')
+                ->pluck('order_id')
+                ->toArray();
         }
         $goodsName = $request->get('goods_name', '');
         if (!empty($goodsName)) {
-            $goodsIds = Goods::where('goods_classify', $goodsClassify)
+            $goodsIds = Goods::where('goods_classify', 'MEALS')
                 ->where('goods_name', 'like', '%' . $goodsName . '%')
                 ->pluck('goods_id')
                 ->toArray();
-        }else if(empty($orderIds)){
-            $goodsIds = Goods::where('goods_classify', $goodsClassify)
-                ->pluck('goods_id')
-                ->toArray();
-        }
-        if (!empty($goodsName) && empty($goodsIds)){
-            $orderIds = [];
-        }else if (!empty($goodsIds)) {
             $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
-            if (!empty($orderIds)){
+            if (!empty($where['order_id'])) {
                 $orderIds = array_intersect($orderIds, $goodsOrderIds);
             }else{
                 $orderIds = $goodsOrderIds;
             }
         }
-        if ($orderIds) {
+        if (!empty($orderId) || !empty($goodsName)) {
             $where['order_id'] = ['in', implode(',', $orderIds)];
         }
 

+ 27 - 30
app/admin/controller/order/GoodsController.php

@@ -10,7 +10,8 @@ use app\model\OrderSheet;
 use support\Request;
 use support\Response;
 
-class GoodsController extends Curd{
+class GoodsController extends Curd
+{
     public function __construct()
     {
         $this->model = new Order();
@@ -30,6 +31,8 @@ class GoodsController extends Curd{
     public function select(Request $request): Response
     {
         [$where, $format, $limit, $field, $order] = $this->selectInput($request);
+
+        $where['order_classify'] = 'GOODS';
         if (!empty($where['order_addtimes'])) {
             $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
             $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
@@ -38,45 +41,39 @@ class GoodsController extends Curd{
         $order = $request->get('order', 'desc');
         $field = $field ?? 'order_addtimes';
         if (!empty($where['order_status_system']) && in_array($where['order_status_system'], ['PENDING', 'WAITING', 'SENDING', 'RECVING', 'SIGNED', 'CONFIRM'])) {
-            if ($where['order_status_system'] == 'SENDING'){
+            if ($where['order_status_system'] == 'SENDING') {
                 $where['order_express.order_express_type'] = '配送';
             }
             $where['order_is_complete'] = 'N';
         }
 
         $orderId = $request->get('order_id', '');
-        $goodsClassify = 'GOODS';
         $orderIds = [];
         if (!empty($orderId)) {
-            $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')->pluck('order_id')->toArray();
+            $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')
+                ->where('order_classify', 'GOODS')
+                ->pluck('order_id')
+                ->toArray();
         }
         $goodsName = $request->get('goods_name', '');
         if (!empty($goodsName)) {
-            $goodsIds = Goods::where('goods_classify', $goodsClassify)
+            $goodsIds = Goods::where('goods_classify', 'GOODS')
                 ->where('goods_name', 'like', '%' . $goodsName . '%')
                 ->pluck('goods_id')
                 ->toArray();
-        }else if(empty($orderIds)){
-            $goodsIds = Goods::where('goods_classify', $goodsClassify)
-                ->pluck('goods_id')
-                ->toArray();
-        }
-        if (!empty($goodsName) && empty($goodsIds)){
-            $orderIds = [];
-        }else if (!empty($goodsIds)) {
             $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
-            if (!empty($orderIds)){
+            if (!empty($where['order_id'])) {
                 $orderIds = array_intersect($orderIds, $goodsOrderIds);
             }else{
                 $orderIds = $goodsOrderIds;
             }
         }
-        if ($orderIds) {
+        if (!empty($orderId) || !empty($goodsName)) {
             $where['order_id'] = ['in', implode(',', $orderIds)];
         }
-        
+
         // 自提订单        
-        if (!empty($where['order_status_system']) && $where['order_status_system'] == 'PICKUP'){
+        if (!empty($where['order_status_system']) && $where['order_status_system'] == 'PICKUP') {
             $where['order_is_complete'] = 'N';
             $where['order_status_system'] = 'SENDING';
             $where['order_express.order_express_type'] = '自提';
@@ -90,7 +87,7 @@ class GoodsController extends Curd{
     {
         $model = $this->model->with([
             'sheets' => function ($query) {
-                $query->select('join_sheet_order_id', 'order_sheet_id', 'join_sheet_goods_id', 'order_sheet_num','order_sheet_price');
+                $query->select('join_sheet_order_id', 'order_sheet_id', 'join_sheet_goods_id', 'order_sheet_num', 'order_sheet_price');
             },
             'member' => function ($query) {
                 $query->select('member_id', 'member_mobile');
@@ -108,8 +105,8 @@ class GoodsController extends Curd{
             // 'express' => function ($query) {
             //     $query->select('join_express_order_id', 'order_express_type');
             // }
-        ])->leftJoin('order_return','order_return.join_return_order_id','=','order.order_id')
-        ->leftJoin('order_express','order_express.join_express_order_id','=','order.order_id');
+        ])->leftJoin('order_return', 'order_return.join_return_order_id', '=', 'order.order_id')
+            ->leftJoin('order_express', 'order_express.join_express_order_id', '=', 'order.order_id');
         // ->leftJoin('order_sheet','join_sheet_order_id','=','order.order_id');
         foreach ($where as $column => $value) {
             if (is_array($value)) {
@@ -143,7 +140,7 @@ class GoodsController extends Curd{
         if ($field) {
             $model = $model->orderBy($field, $order);
         }
-        $model = $model->select('order.*','order_express.join_express_order_id','order_express.order_express_type','order_return.orders_return_id', 'order_return.join_return_order_id', 'order_return.order_return_status','order_return.order_return_apply_json','order_return.order_return_remark');
+        $model = $model->select('order.*', 'order_express.join_express_order_id', 'order_express.order_express_type', 'order_return.orders_return_id', 'order_return.join_return_order_id', 'order_return.order_return_status', 'order_return.order_return_apply_json', 'order_return.order_return_remark');
         return $model;
     }
 
@@ -154,29 +151,29 @@ class GoodsController extends Curd{
             $item['sheet'] = $item['sheets'][0] ?? [];
             if (!empty($item['sheet'])) {
                 $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first();
-                if(count($item['sheets']) > 1 && $goods->goods_classify == 'MEALS'){
+                if (count($item['sheets']) > 1 && $goods->goods_classify == 'MEALS') {
                     $sheetDeng = ' 等餐品';
                 }
-                $item['sheet']['goods_name'] = ($goods && $goods->goods_name) ? $goods->goods_name.$sheetDeng : '';
+                $item['sheet']['goods_name'] = ($goods && $goods->goods_name) ? $goods->goods_name . $sheetDeng : '';
                 $item['sheet']['goods_classify'] = $goods->goods_classify ?? '';
                 $item['sheet']['order_sheet_num'] = intval($item['sheet']['order_sheet_num']);
             }
             unset($item['sheets']);
-            if (isset($item['orders_return_id'])){
+            if (isset($item['orders_return_id'])) {
                 $item['return'] = [
-                    'orders_return_id'=>$item['orders_return_id'],
+                    'orders_return_id' => $item['orders_return_id'],
                     'join_return_order_id' => $item['join_return_order_id'],
                     'order_return_status' => $item['order_return_status'],
                     'order_return_apply_json' => $item['order_return_apply_json'],
-                    'order_return_remark'=>$item['order_return_remark']
+                    'order_return_remark' => $item['order_return_remark']
                 ];
             }
-            if (isset($item['join_express_order_id'])){
+            if (isset($item['join_express_order_id'])) {
                 $item['express'] = [
-                    'join_express_order_id'=>$item['join_express_order_id'],
-                    'order_express_type'=>$item['order_express_type']
+                    'join_express_order_id' => $item['join_express_order_id'],
+                    'order_express_type' => $item['order_express_type']
                 ];
-                unset($item['join_express_order_id'],$item['order_express_type']);
+                unset($item['join_express_order_id'], $item['order_express_type']);
             }
         }
 

+ 21 - 23
app/admin/controller/order/KangyangCityController.php

@@ -54,6 +54,7 @@ class KangyangCityController extends Curd
     public function select(Request $request): Response
     {
         [$where, $format, $limit, $field, $order] = $this->selectInput($request);
+        $where['order_classify'] = 'VIP';
         if (!empty($where['order_addtimes'])) {
             $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
             $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
@@ -61,32 +62,29 @@ class KangyangCityController extends Curd
 
         $order = $request->get('order', 'desc');
         $field = $field ?? 'order_addtimes';
-        // $where['order_id'] = '';
-        $where['order_category'] = 'VIP';
-        // $goodsClassify = 'VIP';
-        $goodsName = $request->get('goods_name', '');
-        if (!empty($goodsName) && empty($goodsClassify)) {
-            $goodsIds = Goods::where('goods_name', 'like', '%' . $request->get('goods_name') . '%')->pluck('goods_id')->toArray();
+        $orderIds = [];
+        if (!empty($orderId)) {
+            $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')
+                ->where('order_classify', 'VIP')
+                ->pluck('order_id')
+                ->toArray();
         }
-        // else if(!empty($goodsClassify)){
-        //     if($goodsClassify == 'SERVICE'){
-        //         $goodsModel = Goods::whereIn('goods_classify',['SERVICE','CHNMED','CHNNCD']);
-        //     }else{
-        //         $goodsModel = Goods::where('goods_classify',$goodsClassify);
-        //     }
-
-        //     if(!empty($goodsName)){
-        //         $goodsModel->where('goods_name','like','%'.$goodsName.'%');
-        //     }
-
-        //     $goodsIds = $goodsModel->pluck('goods_id')->toArray();
-        // }
-        if (!empty($goodsIds)) {
-            $orderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
-            if ($orderIds) {
-                $where['order_id'] = ['in', implode(',', $orderIds)];
+        $goodsName = trim($request->get('goods_name', ''));
+        if (!empty($goodsName)) {
+            $goodsIds = Goods::where('goods_classify', 'VIP')
+                ->where('goods_name', 'like', '%' . $goodsName . '%')
+                ->pluck('goods_id')
+                ->toArray();
+            $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
+            if (!empty($where['order_id'])) {
+                $orderIds = array_intersect($orderIds, $goodsOrderIds);
+            }else{
+                $orderIds = $goodsOrderIds;
             }
         }
+        if (!empty($orderId) || !empty($goodsName)) {
+            $where['order_id'] = ['in', implode(',', $orderIds)];
+        }
 
         $query = $this->doSelect($where, $field, $order);
         return $this->doFormat($query, $format, $limit);

+ 36 - 17
app/admin/controller/order/PackagesController.php

@@ -49,47 +49,55 @@ class PackagesController extends Curd
     public function select(Request $request): Response
     {
         [$where, $format, $limit, $field, $order] = $this->selectInput($request);
+        $where['order_classify'] = 'PACKAGE';
         if (!empty($where['order_addtimes'])) {
             $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
             $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
         }
 
         $order = $request->get('order', 'desc');
-        $orderId = $request->get('order_id', '');
         $field = $field ?? 'order_addtimes';
         if (!empty($where['order_status_system']) && in_array($where['order_status_system'], ['PENDING', 'WAITING', 'SENDING', 'RECVING', 'SIGNED', 'CONFIRM'])) {
             $where['order_is_complete'] = 'N';
         }
 
-        $goodsClassify = 'PACKAGE';
+        $orderId = trim($request->get('order_id', ''));
         $orderIds = [];
         if (!empty($orderId)) {
-            $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')->pluck('order_id')->toArray();
+            $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')
+                ->where('order_classify', 'PACKAGE')
+                ->pluck('order_id')
+                ->toArray();
         }
-        $goodsName = $request->get('goods_name', '');
+        $goodsName = trim($request->get('goods_name', ''));
         if (!empty($goodsName)) {
-            $goodsIds = Goods::where('goods_classify', $goodsClassify)
+            $goodsIds = Goods::where('goods_classify', 'PACKAGE')
                 ->where('goods_name', 'like', '%' . $goodsName . '%')
                 ->pluck('goods_id')
                 ->toArray();
-        } else if (empty($orderIds)) {
-            $goodsIds = Goods::where('goods_classify', $goodsClassify)
-                ->pluck('goods_id')
-                ->toArray();
-        }
-        if (!empty($goodsName) && empty($goodsIds)) {
-            $orderIds = [];
-        } else if (!empty($goodsIds)) {
             $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
-            if (!empty($orderIds)) {
+            if (!empty($where['order_id'])) {
                 $orderIds = array_intersect($orderIds, $goodsOrderIds);
-            } else {
+            }else{
                 $orderIds = $goodsOrderIds;
             }
         }
-        if ($orderIds) {
+        if (!empty($orderId) || !empty($goodsName)) {
             $where['order_id'] = ['in', implode(',', $orderIds)];
         }
+        if (!empty($where['order_status_system']) && in_array($where['order_status_system'], ['PENDING', 'WAITING', 'SENDING', 'RECVING', 'SIGNED', 'CONFIRM'])) {
+            if ($where['order_status_system'] == 'SENDING') {
+                $where['order_express.order_express_type'] = '配送';
+            }
+            $where['order_is_complete'] = 'N';
+//            $where['order_category'] = isset($where['order_category']) ? $where['order_category'] : ['in', 'SYSTEM,NORMAL,DISHES'];
+        }
+        // 自提订单
+        if (!empty($where['order_status_system']) && $where['order_status_system'] == 'PICKUP') {
+            $where['order_is_complete'] = 'N';
+            $where['order_status_system'] = 'SENDING';
+            $where['order_express.order_express_type'] = '自提';
+        }
 
         $query = $this->doSelect($where, $field, $order);
         return $this->doFormat($query, $format, $limit);
@@ -117,8 +125,18 @@ class PackagesController extends Curd
             'express' => function ($query) {
                 $query->select('join_express_order_id', 'order_express_type');
             }
-        ])->leftJoin('order_return', 'order_return.join_return_order_id', '=', 'order.order_id');
+        ])->leftJoin('order_return', 'order_return.join_return_order_id', '=', 'order.order_id')
+            ->leftJoin('order_express', 'order_express.join_express_order_id', '=', 'order.order_id');
         // ->leftJoin('order_sheet','join_sheet_order_id','=','order.order_id');
+        if (isset($where['order_status_system']) && $where['order_status_system'] == 'DONE'){
+            $model = $model->where(function($query){
+                $query->where('order_status_system','DONE')
+                ->orWhere(function($query2){
+                    $query2->where('order_status_system','CONFIRM')->where('order_is_complete','Y');
+                });
+            });
+            unset($where['order_status_system']);
+        }
         foreach ($where as $column => $value) {
             if (is_array($value)) {
                 if ($value[0] === 'like' || $value[0] === 'not like') {
@@ -152,6 +170,7 @@ class PackagesController extends Curd
             $model = $model->orderBy($field, $order);
         }
         $model = $model->select('order.*', 'order_return.orders_return_id', 'order_return.join_return_order_id', 'order_return.order_return_status', 'order_return.order_return_apply_json', 'order_return.order_return_remark');
+
         return $model;
     }
 

+ 123 - 0
app/admin/controller/order/PayDetailController.php

@@ -274,6 +274,46 @@ class PayDetailController extends Curd
         return json_success('success');
     }
 
+    /**
+     * 余额账户赠送
+     */
+    public function insertGive(Request $request): Response
+    {
+        if ($this->validate && !$this->validateClass->scene('add')->check($request->post())) {
+            return json_fail($this->validateClass->getError());
+        }
+
+        $password = $request->post('recharge_password', '');
+        if (!$password || $password != '123456') {
+            return json_fail('赠送密码错误');
+        }
+
+        Db::beginTransaction();
+        try {
+            $data = $this->insertGiveInput($request);
+            $data['pay_prepayid'] = $data['join_pay_member_id'] . '-CASH';
+
+
+            // 金额累加到福利账户
+            $memberAccount = MemberAccount::where('join_account_member_id', $data['join_pay_member_id'])->where('member_account_classify', 'CASH')->first();
+            $memberAccount->member_account_income = $memberAccount->member_account_income + $data['pay_amount'];
+            $memberAccount->member_account_surplus = $memberAccount->member_account_surplus + $data['pay_amount'];
+            $memberAccount->save();
+
+            $data['pay_amount'] = 0;
+            $this->doInsert($data);
+            Db::commit();
+        } catch (BusinessException $customException) {
+            Db::rollBack();
+            return json_fail($customException->getMessage());
+        } catch (\Exception $e) {
+            Db::rollBack();
+            dump($e->getMessage());
+            return json_fail('数据写入失败11');
+        }
+        return json_success('success');
+    }
+
 
     /**
      * 福利账户充值
@@ -347,6 +387,7 @@ class PayDetailController extends Curd
                 'order_amount_pay' => $data['pay_amount'],
                 'order_amount_json' => '{"tax": 0, "freight": 0}',
                 'order_status_payment' => 'SUCCESS',
+                'order_classify' => 'RECHARGE',
                 'order_category' => 'RECHARGE',
                 'order_status_system' => 'PAYING',
                 'order_status_storage' => 'PENDING',
@@ -406,6 +447,88 @@ class PayDetailController extends Curd
         return $data;
     }
 
+    /**
+     * @Desc
+     * @Author Gorden
+     * @Date 2024/6/5 13:39
+     *
+     * @param Request $request
+     * @return array
+     * @throws BusinessException
+     */
+    protected function insertGiveInput(Request $request, $type = "CASH"): array
+    {
+        $params = $request->post();
+        $data = $this->inputFilter($params);
+        $goods = Goods::find($params['goods_id']);
+        $extendJson = [];
+        // if (!$params['is_custom']) {
+        Db::beginTransaction();
+        try {
+            if (!$params['is_custom']) {
+                $data['pay_amount'] = $goods->goods_sales_price;
+            }
+
+//            $orderId = "OD" . date('ymdHi') . random_string(4, 'up');
+//            $orderGroupId = "OD" . date('ymdHi') . random_string(4, 'up');
+//            $orderData = [
+//                'order_id' => $orderId,
+//                'order_groupby' => $orderGroupId,
+//                'join_order_member_id' => $data['join_pay_member_id'],
+//                'order_name' => date('Y-m-d H:i:s') . '-订单',
+//                'order_amount_total' => $data['pay_amount'],
+//                'order_amount_pay' => $data['pay_amount'],
+//                'order_amount_json' => '{"tax": 0, "freight": 0}',
+//                'order_status_payment' => 'SUCCESS',
+//                'order_classify' => 'RECHARGE',
+//                'order_category' => 'RECHARGE',
+//                'order_status_system' => 'PAYING',
+//                'order_status_storage' => 'PENDING',
+//                'order_addtimes' => time()
+//            ];
+//            if ($type == 'WELFARE') {
+//                $orderData['order_is_complete'] = 'Y';
+//                $orderData['order_status_system'] = 'DONE';
+//                $orderData['order_status_storage'] = 'DONE';
+//            }
+//            $sku = GoodsSku::where('join_sku_goods_id', $params['goods_id'])->first();
+//
+//            Order::insert($orderData);
+//            $orderSheetData = [
+//                'join_sheet_member_id' => $data['join_pay_member_id'],
+//                'join_sheet_order_id' => $orderId,
+//                'join_sheet_goods_id' => $params['goods_id'],
+//                'join_sheet_goods_sku_id' => $sku ? $sku->goods_sku_id : 0,
+//                'order_sheet_status' => 'DONE',
+//                'order_sheet_category' => 'RECHARGE',
+//                'order_sheet_num' => 1,
+//                'order_sheet_price' => $data['pay_amount'],
+//                'order_sheet_amount' => $data['pay_amount'],
+//                'order_sheet_pay' => $data['pay_amount'],
+//                'order_sheet_addtimes' => time()
+//            ];
+//
+//            OrderSheet::insert($orderSheetData);
+
+            Db::commit();
+        } catch (\Exception $e) {
+            dump($e->getMessage());
+            Db::rollBack();
+
+            throw new BusinessException("数据错误");
+        }
+        $data['join_pay_order_id'] = "SYSTEM";
+        $data['join_pay_object_json'] = json_encode(['order_id' => 'SYSTEM']);
+
+        $rate = 0;
+        $extendJson['added_amount'] = $data['pay_amount'];
+        $extendJson['added_rate'] = $rate;
+        $data['pay_extend_json'] = json_encode($extendJson);
+        $data['pay_paytimes'] = date('Y-m-d H:i:s', strtotime($data['pay_paytimes']));
+        $data['pay_prepayid'] = 0;
+        return $data;
+    }
+
     /**
      * @Desc 加备注-门店、服务人员、业务人员
      * @Author Gorden

+ 10 - 15
app/admin/controller/order/ServicesController.php

@@ -35,41 +35,36 @@ class ServicesController extends Curd{
             $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
         }
 
+        $where['order_classify'] = ['in','SERVICE,CHNMED,CHNNCD'];
         $order = $request->get('order', 'desc');
         $field = $field ?? 'order_addtimes';
-        // $where['order_category'] = ['in','SERVICE,CHNMED,CHNNCD'];
         if (!empty($where['order_status_system']) && in_array($where['order_status_system'], ['PENDING', 'WAITING', 'SENDING', 'RECVING', 'SIGNED', 'CONFIRM'])) {
             $where['order_is_complete'] = 'N';
             $where['order_category'] = ['<>','RETURN'];
         }
 
-        $orderId = $request->get('order_id', '');
+        $orderId = trim($request->get('order_id', ''));
         $orderIds = [];
         if (!empty($orderId)) {
-            $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')->pluck('order_id')->toArray();
+            $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')
+                ->whereIn('order_classify', ['SERVICE','CHNMED','CHNNCD'])
+                ->pluck('order_id')
+                ->toArray();
         }
-        $goodsName = $request->get('goods_name', '');
+        $goodsName = trim($request->get('goods_name', ''));
         if (!empty($goodsName)) {
-            $goodsIds = Goods::whereIn('goods_classify',['SERVICE','CHNMED','CHNNCD'])
+            $goodsIds = Goods::whereIn('goods_classify', ['SERVICE','CHNMED','CHNNCD'])
                 ->where('goods_name', 'like', '%' . $goodsName . '%')
                 ->pluck('goods_id')
                 ->toArray();
-        }else if(empty($orderIds)){
-            $goodsIds = Goods::whereIn('goods_classify',['SERVICE','CHNMED','CHNNCD'])
-                ->pluck('goods_id')
-                ->toArray();
-        }
-        if (!empty($goodsName) && empty($goodsIds)){
-            $orderIds = [];
-        }else if (!empty($goodsIds)) {
             $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
-            if (!empty($orderIds)){
+            if (!empty($where['order_id'])) {
                 $orderIds = array_intersect($orderIds, $goodsOrderIds);
             }else{
                 $orderIds = $goodsOrderIds;
             }
         }
-        if ($orderIds) {
+        if (!empty($orderId) || !empty($goodsName)) {
             $where['order_id'] = ['in', implode(',', $orderIds)];
         }
 

+ 211 - 58
app/admin/controller/order/WholeController.php

@@ -44,7 +44,6 @@ use support\Response;
 use Tinywan\Jwt\JwtToken;
 use Webman\Event\Event;
 use Yansongda\Pay\Pay;
-use function Qiniu\Http\Middleware\compose;
 
 class WholeController extends Curd
 {
@@ -71,6 +70,11 @@ class WholeController extends Curd
             $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
             $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
         }
+        if ($request->get('goods_classify') && $request->get('goods_classify') == 'SERVICE') {
+            $where['order_classify'] = ['in', 'SERVICE,CHNMED,CHNNCD'];
+        } else if ($request->get('goods_classify')) {
+            $where['order_classify'] = $request->get('goods_classify');
+        }
 
         $order = $request->get('order', 'desc');
         $type = $request->get('type', '');
@@ -132,14 +136,12 @@ class WholeController extends Curd
         }
         if ($request->get('goods_classify') || $request->get('goods_name')) {
             $orderGoodsIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
-//            if ($orderGoodsIds) {
             if (!empty($where['order_id'])) {
                 $orderIds = array_intersect($orderIds, $orderGoodsIds);
                 $where['order_id'] = ['in', implode(',', $orderIds)];
             } else {
                 $where['order_id'] = ['in', implode(',', $orderGoodsIds)];
             }
-//            }
         } elseif (!empty($orderIds)) {
             $where['order_id'] = ['in', implode(',', $orderIds)];
         }
@@ -819,17 +821,25 @@ class WholeController extends Curd
 
         $systemStatus = 'SENDING';  // 待发货
         // 立即结算
-        if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'VIP'])) {
+        if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
             $order->order_is_complete = 'Y';
             $systemStatus = 'DONE';
         }
-        if ($params['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') {
+        if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
+            $params['order_is_complete'] = 'N';
             $systemStatus = "WAITING";
         }
+//        if ($params['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') {
+//            $systemStatus = "WAITING";
+//        }
         Db::beginTransaction();
         try {
             // 使用优惠券
             $couponUseJson = [];
+            if (!empty($order->order_discount_json)) {
+                // 释放下单时选的优惠券
+                $order->order_discount_json = $this->releaseCoupon(json_decode($order->order_discount_json, true));
+            }
             if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
                 $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
                 if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
@@ -838,12 +848,12 @@ class WholeController extends Curd
                 // 组装优惠券使用数据,存主表优惠里
                 if (!empty($couponResult['use_coupon_json'])) {
                     $couponUseJson = $couponResult['use_coupon_json'];
-                    if (!empty($order->order_discount_json)) {
-                        $orderDiscountJson = json_decode($order->order_discount_json, true);
-                        if (!empty($orderDiscountJson)) {
-                            $couponUseJson = json_encode(array_merge($orderDiscountJson, json_decode($couponUseJson, true)));
-                        }
-                    }
+//                    if (!empty($order->order_discount_json)) {
+//                        $orderDiscountJson = json_decode($order->order_discount_json, true);
+//                        if (!empty($orderDiscountJson)) {
+//                            $couponUseJson = json_encode(array_merge($orderDiscountJson, json_decode($couponUseJson, true)));
+//                        }
+//                    }
                 }
             }
             // 存储优惠信息
@@ -1302,6 +1312,9 @@ class WholeController extends Curd
 
             if ($order->order_status_payment != 'SUCCESS') {
                 _syslog("订单", "支付异常,检查是否有轮询");
+                // 恢复优惠券到已占用
+                $this->changeOrderCouponStatus(json_decode($couponUseJson, true), 'WAITING');
+
                 return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
             }
             _syslog("订单", "订单支付成功");
@@ -1423,17 +1436,22 @@ class WholeController extends Curd
 
         $systemStatus = 'SENDING';  // 待发货
         // 立即结算
-        if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'VIP'])) {
+        if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
             $order->order_is_complete = 'Y';
             $systemStatus = 'DONE';
         }
-        if ($params['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') {
+        if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
+            $params['order_is_complete'] = 'N';
             $systemStatus = "WAITING";
         }
         $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
         Db::beginTransaction();
         try {// 使用优惠券
             $couponUseJson = [];
+            if (!empty($order->order_discount_json)) {
+                // 释放下单时选的优惠券
+                $order->order_discount_json = $this->releaseCoupon(json_decode($order->order_discount_json, true));
+            }
             if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
                 $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
                 if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
@@ -1442,12 +1460,12 @@ class WholeController extends Curd
                 // 组装优惠券使用数据,存主表优惠里
                 if (!empty($couponResult['use_coupon_json'])) {
                     $couponUseJson = $couponResult['use_coupon_json'];
-                    if (!empty($order->order_discount_json)) {
-                        $orderDiscountJson = json_decode($order->order_discount_json, true);
-                        if (!empty($orderDiscountJson)) {
-                            $couponUseJson = json_encode(array_merge($orderDiscountJson, json_decode($couponUseJson, true)));
-                        }
-                    }
+//                    if (!empty($order->order_discount_json)) {
+//                        $orderDiscountJson = json_decode($order->order_discount_json, true);
+//                        if (!empty($orderDiscountJson)) {
+//                            $couponUseJson = json_encode(array_merge($orderDiscountJson, json_decode($couponUseJson, true)));
+//                        }
+//                    }
                 }
             }
             // 存储优惠信息
@@ -1744,6 +1762,8 @@ class WholeController extends Curd
             }
             if ($order->order_status_payment != 'SUCCESS') {
                 _syslog("订单", "支付异常,检查是否有轮询");
+                // 恢复优惠券到已占用
+                $this->changeOrderCouponStatus(json_decode($couponUseJson, true), 'WAITING');
                 return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
             }
             _syslog("订单", "订单支付成功");
@@ -1989,11 +2009,12 @@ class WholeController extends Curd
             $systemStatus = 'SENDING';  // 待发货
             // 立即结算
             if ($params['settlement_now'] == 'Y') {
-                if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'VIP'])) {
+                if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
                     $params['order_is_complete'] = 'Y';
                     $systemStatus = 'DONE';
                 }
-                if ($params['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') {
+                if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
+                    $params['order_is_complete'] = 'N';
                     $systemStatus = "WAITING";
                 }
             }
@@ -2365,7 +2386,7 @@ class WholeController extends Curd
             if ($params['order_status_payment'] == 'SUCCESS') {
                 foreach ($params['goodsContentList'] as $goods) {
                     $params['join_sheet_goods_id'] = $goods['goods_id'];
-                    if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
+                    if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD']) && $params['delivery'] == 'ARRIVAL') {
                         $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
                         $params['join_sheet_goods_sku_id'] = $goods['sku_id'];
                         $params['goods_id'] = $goods['goods_id'];
@@ -2380,7 +2401,7 @@ class WholeController extends Curd
                         $goods['category'] = $goods['goods_classify'];
                         // 权益表
                         $this->insertMemberBenefit($params, $goods);
-                    } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE') {  // 一个套餐买多个
+                    } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') {  // 一个套餐买多个
                         $params['packageId'] = $goods['goods_id'];
                         $components = GoodsComponent::with([
                             'goods' => function ($query) {
@@ -2481,6 +2502,9 @@ class WholeController extends Curd
 
             if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
                 _syslog("订单", "支付异常,检查是否有轮询");
+                // 恢复优惠券到已占用
+                $this->changeOrderCouponStatus(json_decode($couponUseJson, true), 'WAITING');
+
                 return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
             }
             _syslog("订单", "创建订单成功");
@@ -2500,6 +2524,68 @@ class WholeController extends Curd
         }
     }
 
+    /**
+     * @Desc 释放下单时选的优惠券
+     * @Author Gorden
+     * @Date 2024/9/19 9:56
+     *
+     * @param $coupon
+     * @return false|string
+     */
+    private function releaseCoupon($coupon)
+    {
+        if (!empty($coupon) && is_array($coupon)) {
+            $updateData = [
+                'coupon_detail_status'=>'ACTIVED',
+                'coupon_detail_used_datetime' => ''
+            ];
+            foreach ($coupon as $key => $item) {
+                if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {
+                    foreach ($item['coupon_detail_id'] as $detailId) {
+                        if (substr($detailId, 0, 4) == 'CUDT') {
+                            CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])
+                                ->where('coupon_detail_id', $detailId)
+                                ->where('coupon_detail_status', 'WAITING')
+                                ->update($updateData);
+                        }
+                    }
+                    unset($coupon[$key]);
+                }
+            }
+        }
+
+        return json_encode($coupon);
+    }
+
+    /**
+     * @Desc 修改优惠券状态
+     * @Author Gorden
+     * @Date 2024/9/19 9:03
+     *
+     * @param $coupon
+     * @param $status
+     * @return void
+     */
+    private function changeOrderCouponStatus($coupon, $status)
+    {
+        if (!empty($coupon) && is_array($coupon)) {
+            $updateData['coupon_detail_status'] = $status;
+            if ($status == 'ACTIVED' || $status == 'WAITING') {
+                $updateData['coupon_detail_used_datetime'] = '';
+            } elseif ($status == 'USED') {
+                $updateData['coupon_detail_used_datetime'] = date('Y-m-d H:i:s');
+            }
+            foreach ($coupon as $item) {
+                if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {
+                    foreach ($item['coupon_detail_id'] as $detailId) {
+                        CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])
+                            ->where('coupon_detail_id', $detailId)->update($updateData);
+                    }
+                }
+            }
+        }
+    }
+
     /**
      * 组合支付下单
      */
@@ -2595,11 +2681,12 @@ class WholeController extends Curd
             $systemStatus = 'SENDING';  // 待发货
             // 立即结算
             if ($params['settlement_now'] == 'Y') {
-                if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'VIP'])) {
+                if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
                     $params['order_is_complete'] = 'Y';
                     $systemStatus = 'DONE';
                 }
-                if ($params['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') {
+                if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
+                    $params['order_is_complete'] = 'N';
                     $systemStatus = "WAITING";
                 }
             }
@@ -2849,7 +2936,7 @@ class WholeController extends Curd
             if ($params['order_status_payment'] == 'SUCCESS') {
                 foreach ($params['goodsContentList'] as $goods) {
                     $params['join_sheet_goods_id'] = $goods['goods_id'];
-                    if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
+                    if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD']) && $params['delivery'] == 'ARRIVAL') {
                         $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
                         $params['join_sheet_goods_sku_id'] = $goods['sku_id'];
                         $params['goods_id'] = $goods['goods_id'];
@@ -2864,7 +2951,7 @@ class WholeController extends Curd
                         $goods['category'] = $goods['goods_classify'];
                         // 权益表
                         $this->insertMemberBenefit($params, $goods);
-                    } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE') {  // 一个套餐买多个
+                    } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') {  // 一个套餐买多个
                         $params['packageId'] = $goods['goods_id'];
                         $components = GoodsComponent::with([
                             'goods' => function ($query) {
@@ -2964,6 +3051,9 @@ class WholeController extends Curd
 
             if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
                 _syslog("订单", "支付异常,检查是否有轮询");
+                // 恢复优惠券到已占用
+                $this->changeOrderCouponStatus(json_decode($couponUseJson, true), 'WAITING');
+
                 return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]);
             }
             _syslog("订单", "创建订单成功");
@@ -3793,27 +3883,34 @@ class WholeController extends Curd
                 'dept_premises_id' => $request->post('dept_premises_id'),
                 'order_remark' => $request->post('remark'),
                 'write_off_member_id' => $request->post('write_off_member_id'),
-                'join_order_member_id' => $memberId
+                'join_order_member_id' => $memberId,
+                'charge_waiter' => $request->post('charge_waiter'),
             ];
             $writeOffData = OrderService::generateWriteOffData($params);
 
             // 开始减额度
+            $benefitUsed = [];
+            $appointmentIds = [];
             foreach ($benefits as $benefit) {
                 foreach ($benefitList as $list) {
                     if ($list['member_benefit_id'] == $benefit['member_benefit_id']) {
                         $usedCount = $benefit['member_benefit_used_count'] + intval($list['nbr']);
+                        $benefitUpdateData = ['member_benefit_used_count' => $usedCount];
                         // 用完了
                         if ($benefit['member_benefit_limit_count'] <= $usedCount && !empty($benefit['join_benefit_order_id'])) {
-                            Order::where('order_id', $benefit['join_benefit_order_id'])->update(['order_status_system' => 'DONE']);
+                            $benefitUpdateData['member_benefit_status'] = 'DONE';
+                            $benefitUsed[$benefit['join_benefit_order_id']][] = $benefit['member_benefit_id'];
+//                            Order::where('order_id', $benefit['join_benefit_order_id'])->update(['order_status_system' => 'DONE']);
                         }
                         // 更新benefit 表
-                        MemberBenefit::where('member_benefit_id', $benefit['member_benefit_id'])->update(['member_benefit_used_count' => $usedCount]);
+                        MemberBenefit::where('member_benefit_id', $benefit['member_benefit_id'])->update($benefitUpdateData);
                         // 更新Appointment 表
                         $appointments = Appointment::where('join_appointment_member_benefit_id', $benefit['member_benefit_id'])
                             ->where('appointment_status', 'INIT')
                             ->limit(intval($list['nbr']))
                             ->get();
                         foreach ($appointments as $appointment) {
+                            $appointmentIds[] = $appointment->appointment_id;
                             Appointment::where('appointment_id', $appointment->appointment_id)->update([
                                 'appointment_status' => 'DONE',
                                 'appointment_datetime' => $times,
@@ -3826,6 +3923,46 @@ class WholeController extends Curd
                     }
                 }
             }
+            // 订单服务是否用完了
+            foreach ($benefitUsed as $key => $item) {
+                $orderUsedComplete = 'Y';
+                $orderBenefits = MemberBenefit::where('join_benefit_order_id', $key)->get()->toArray();
+                foreach ($orderBenefits as $orderBenefit) {
+                    if ($orderBenefit['member_benefit_used_count'] >= $orderBenefit['member_benefit_limit_count']) {
+                        continue;
+                    }
+                    if (!in_array($orderBenefit['member_benefit_id'], $item)) {
+                        $orderUsedComplete = 'N';
+                    }
+                }
+                if ($orderUsedComplete == 'Y') {
+                    Order::where('order_id', $key)->update(['order_is_complete' => 'Y', 'order_status_system' => 'DONE']);
+                }
+            }
+
+            // 核销服务回写process
+            foreach ($benefits as $benefit) {
+                foreach ($benefitList as $list) {
+                    if ($list['member_benefit_id'] == $benefit['member_benefit_id'] && (!empty($benefit['join_benefit_goods_id']) || !empty($benefit['join_benefit_package_id'])) && !empty($benefit['join_benefit_order_id'])) {
+                        $dept = [];
+                        if (!empty($params['dept_premises_id'])) {
+                            $dept = SysDept::where('dept_id', $params['dept_premises_id'])
+                                ->orWhere('dept_name', $params['dept_premises_id'])
+                                ->select('dept_id', 'dept_name', 'dept_status', 'dept_category', 'dept_super_id', 'dept_super_path')
+                                ->first();
+                        }
+                        $params['charge_amount'] = $list['nbr'];
+                        $params['goods_id'] = !empty($benefit['join_benefit_goods_id']) ? $benefit['join_benefit_goods_id'] : (!empty($benefit['join_benefit_package_id']) ? $benefit['join_benefit_package_id'] : '');
+                        $params['goods_sku_id'] = $benefit['join_benefit_goods_sku_id'];
+                        $params['order_id'] = $benefit['join_benefit_order_id'];
+                        $params['appointment_ids'] = $appointmentIds;
+                        $params['dept'] = $dept;
+                        $params['write_off_data'] = OrderService::generateWriteOffDataByOrderProcess($params);
+                        // 触发事件
+                        Event::dispatch('order.write_off', $params);
+                    }
+                }
+            }
 
             Redis::del($key);
 
@@ -3834,7 +3971,7 @@ class WholeController extends Curd
             _syslog("订单", "核销成功");
             return json_success('核销成功');
         } catch (\Exception $e) {
-            dump($e->getMessage());
+            dump($e->getMessage() . $e->getLine());
             Db::rollBack();
             _syslog("订单", "核销失败");
             return json_fail('核销失败');
@@ -4127,6 +4264,13 @@ class WholeController extends Curd
     {
         $type = $request->get('type', '');
         [$where, $format, $limit, $field, $order] = $this->selectInput($request);
+
+        if ($request->get('goods_classify') && $request->get('goods_classify') == 'SERVICE') {
+            $where['order_classify'] = ['in', 'SERVICE,CHNMED,CHNNCD'];
+        } else if ($request->get('goods_classify')) {
+            $where['order_classify'] = $request->get('goods_classify');
+        }
+
         $where['order_category'] = ['<>', 'RECHARGE'];
         if (!empty($request->get('order_ids'))) {
             $where['order_id'] = ['in', $request->get('order_ids')];
@@ -4149,32 +4293,30 @@ class WholeController extends Curd
                 ->toArray();
             $where['order_groupby'] = ['in', $groupIds];
         }
-        if ($request->get('goods_classify') || $request->get('goods_name')) {
-            $where['order_id'] = '';
-            $goodsClassify = $request->get('goods_classify', '');
-            $goodsName = $request->get('goods_name', '');
-            if (!empty($goodsName) && empty($goodsClassify)) {
-                $goodsIds = Goods::where('goods_name', 'like', '%' . $request->get('goods_name') . '%')->pluck('goods_id')->toArray();
-            } else if (!empty($goodsClassify)) {
-                if ($goodsClassify == 'SERVICE') {
-                    $goodsModel = Goods::whereIn('goods_classify', ['SERVICE', 'CHNMED', 'CHNNCD']);
-                } else {
-                    $goodsModel = Goods::where('goods_classify', $goodsClassify);
-                }
-
-                if (!empty($goodsName)) {
-                    $goodsModel->where('goods_name', 'like', '%' . $goodsName . '%');
-                }
-
-                $goodsIds = $goodsModel->pluck('goods_id')->toArray();
-            }
-            if ($goodsIds) {
-                $orderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
-                if ($orderIds) {
-                    $where['order_id'] = ['in', implode(',', $orderIds)];
-                }
+        $orderId = trim($request->get('order_id', ''));
+        $orderIds = [];
+        if (!empty($orderId)) {
+            $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')
+                ->whereIn('order_classify', ['SERVICE', 'CHNMED', 'CHNNCD'])
+                ->pluck('order_id')
+                ->toArray();
+        }
+        $goodsName = trim($request->get('goods_name', ''));
+        if (!empty($goodsName)) {
+            $goodsIds = Goods::whereIn('goods_classify', ['SERVICE', 'CHNMED', 'CHNNCD'])
+                ->where('goods_name', 'like', '%' . $goodsName . '%')
+                ->pluck('goods_id')
+                ->toArray();
+            $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
+            if (!empty($where['order_id'])) {
+                $orderIds = array_intersect($orderIds, $goodsOrderIds);
+            } else {
+                $orderIds = $goodsOrderIds;
             }
         }
+        if (!empty($orderId) || !empty($goodsName)) {
+            $where['order_id'] = ['in', implode(',', $orderIds)];
+        }
         $order = $request->get('order', 'desc');
         $field = $field ?? 'order_addtimes';
 
@@ -4240,7 +4382,7 @@ class WholeController extends Curd
             ])
             ->select('order_id', 'join_order_member_id', 'order_is_complete', 'order_status_system')
             ->where("order_is_complete", 'N')
-            ->whereIn("order_category", ['NORMAL', 'SYSTEM'])
+//            ->whereIn("order_category", ['NORMAL', 'SYSTEM'])
             ->orderBy('order_addtimes', 'DESC')
             ->get()
             ->toArray();
@@ -4255,6 +4397,9 @@ class WholeController extends Curd
             foreach ($order['benefit'] as $benefit) {
                 $benefit['member_benefit_limit_count'] = intval($benefit['member_benefit_limit_count']);
                 $benefit['member_benefit_used_count'] = intval($benefit['member_benefit_used_count']);
+                if ($benefit['member_benefit_used_count'] >= $benefit['member_benefit_limit_count']) {
+                    continue;
+                }
                 $benefit['unused'] = $benefit['member_benefit_limit_count'] - $benefit['member_benefit_used_count'];
                 $orderOne['benefit'] = $benefit;
                 $orderOne['member_benefit_id'] = $benefit['member_benefit_id'];
@@ -4442,6 +4587,11 @@ class WholeController extends Curd
             return json_fail('订单不存在');
         }
 
+        $discountJson = [];
+        if (!empty($order->order_discount_json)) {
+            $discountJson = json_decode($order->order_discount_json, true);
+        }
+
         if ($order->order_status_payment == 'SUCCESS') {
             return json_success('success');
         }
@@ -4453,10 +4603,10 @@ class WholeController extends Curd
                 $result = Pay::wechat(config('payment.wxpay'))->find($order->order_groupby, 'pos');
                 $result = json_decode(json_encode($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') {
+                    $order->order_status_payment = 'SUCCESS';
                     if (in_array($order->order_category, ['SERVICE', 'CHNMED', 'CHNNCD', 'DISHES', 'MEALS', 'VIP'])) {
                         $order->order_is_complete = 'Y';
                         $order->order_status_system = 'DONE';
-                        $order->order_status_payment = 'SUCCESS';
                     } else {
                         $order->order_status_system = 'SENDING';
                     }
@@ -4465,6 +4615,8 @@ class WholeController extends Curd
                     OrderSheet::where('join_sheet_order_id', $orderId)->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']);
+                    // 优惠券标记使用
+                    $this->changeOrderCouponStatus($discountJson, 'USED');
 
                     Db::commit();
                     return json_success('success');
@@ -4485,7 +4637,8 @@ class WholeController extends Curd
                     OrderSheet::where('join_sheet_order_id', $orderId)->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']);
-
+                    // 优惠券标记使用
+                    $this->changeOrderCouponStatus($discountJson, 'USED');
                     Db::commit();
                     return json_success('success');
                 }

+ 1 - 0
app/admin/service/coupon/CouponDetailService.php

@@ -27,6 +27,7 @@ class CouponDetailService
                 'coupon_detail_status' => 'ACTIVED',
                 'coupon_detail_gain_datetime' => $params['coupon_detail_gain_datetime'],
                 'coupon_detail_deadline_datetime' => $params['coupon_detail_deadline_datetime'],
+                'coupon_detail_period_num' => $params['coupon_detail_period_num'] ?? 0,
                 'coupon_detail_extend_json'=>json_encode(['gettype'=>'SEND']),
                 'coupon_detail_addtimes' => time(),
             ]);

+ 79 - 3
app/admin/service/coupon/CouponService.php

@@ -2,6 +2,7 @@
 
 namespace app\admin\service\coupon;
 
+use app\model\Coupon;
 use app\model\CouponDetail;
 use support\Db;
 
@@ -26,6 +27,81 @@ class CouponService
         }
     }
 
+    /**
+     * @Desc
+     * @Author Gorden
+     * @Date 2024/9/18 11:44
+     *
+     * @return void
+     */
+    public static function sendPeriodCoupon()
+    {
+        Db::beginTransaction();
+        try {
+            $coupons = Coupon::where('coupon_is_period', 'Y')->where('coupon_status', 'ACTIVED')->get()->toArray();
+            foreach ($coupons as $coupon) {
+                if (time() > strtotime($coupon['coupon_validdate_end'])) {
+                    continue;
+                }
+                $details = CouponDetail::where('join_detail_coupon_id',$coupon['coupon_id'])
+                    ->select('join_coupon_detail_member_id')
+                    ->groupBy('join_coupon_detail_member_id')
+                    ->get();
+                foreach ($details as $item) {
+                    $detail = CouponDetail::where('join_detail_coupon_id', $coupon['coupon_id'])
+                        ->where('join_coupon_detail_member_id',$item->join_coupon_detail_member_id)
+                        ->orderBy('coupon_detail_addtimes', 'DESC')
+                        ->first();
+                    if (!empty($detail) && strtotime($detail->coupon_detail_deadline_datetime) > time()) {
+                        continue;
+                    }
+                    $params = [
+                        'coupon_detail_gain_datetime' => date('Y-m-d 00:00:00'),
+                        'coupon_id' => $coupon['coupon_id'],
+                        'member_id' => $detail->join_coupon_detail_member_id,
+                        'coupon_detail_period_num' => $detail->coupon_detail_period_num + 1
+                    ];
+                    if (!empty($coupon['coupon_period_json'])) {
+                        $periodJson = json_decode($coupon['coupon_period_json'], true);
+                        if ($periodJson['nbr'] < $params['coupon_detail_period_num']){
+                            continue;
+                        }
+                        if ($periodJson['unit'] == 'day') {
+                            $val = $periodJson['val'] - 1;
+                            if ($val < 1) {
+                                $params['coupon_detail_deadline_datetime'] = date('Y-m-d 23:59:59');
+                            } else {
+                                $params['coupon_detail_deadline_datetime'] = date('Y-m-t 23:59:59', strtotime("+" . $val . " day"));
+                            }
+                        } elseif ($periodJson['unit'] == 'week') {
+                            $val = $periodJson['val'] - 1;
+                            if ($val < 1) {
+                                $params['coupon_detail_deadline_datetime'] = date('Y-m-d 23:59:59', strtotime('this week Sunday'));
+                            } else {
+                                $params['coupon_detail_deadline_datetime'] = date('Y-m-t 23:59:59', strtotime("+" . $val . ' week', date('Y-m-d', strtotime("+" . $val . " month"))));
+                            }
+                        } elseif ($periodJson['unit'] == 'month') {
+                            $val = $periodJson['val'] - 1;
+                            if ($val < 1) {
+                                $params['coupon_detail_deadline_datetime'] = date('Y-m-t 23:59:59');
+                            } else {
+                                $params['coupon_detail_deadline_datetime'] = date('Y-m-t 23:59:59', strtotime("+" . $val . " month"));
+                            }
+                        }
+                    }
+                    // 写入优惠券
+                    CouponDetailService::customSendCoupon($params);
+
+                    _syslog("周期券", "发放周期券", false, $params, 1001);
+                }
+            }
+
+            Db::commit();
+        } catch (\Exception $e) {
+            Db::rollBack();
+        }
+    }
+
     public static function couponClassifyInfo($classify, $category, $value, $limit)
     {
         try {
@@ -33,7 +109,7 @@ class CouponService
                 case "满减券":
                     if (!empty($limit) && $category == 'NORMAL') {
                         return "满" . $limit . '减' . $value;
-                    }elseif (!empty($limit) && !empty($value) && $category == 'PIECE'){
+                    } elseif (!empty($limit) && !empty($value) && $category == 'PIECE') {
                         return "满" . intval($limit) . '件减' . $value;
                     }
                     break;
@@ -46,10 +122,10 @@ class CouponService
                 case "折扣券":
                     if (!empty($limit) && $category == 'NORMAL') {
                         return "满" . $limit . '打' . ($value / 10) . '折';
-                    }else if (!empty($limit) && !empty($value) && $category == 'PIECE') {
+                    } else if (!empty($limit) && !empty($value) && $category == 'PIECE') {
                         return "满" . intval($limit) . '件打' . ($value / 10) . '折';
                     } else {
-                        return $value/10 . '折';
+                        return $value / 10 . '折';
                     }
                     break;
                 case "赠品券":

+ 49 - 28
app/admin/service/member/MemberService.php

@@ -31,6 +31,7 @@ class MemberService
         $page = $request->get('page', 1);
         $pageSize = $request->get('pageSize', 10);
         $name = $request->get('name', '');
+        $nickname = $request->get('nickname', '');
         $mobile = $request->get('mobile', '');
         $level = $request->get('level', '');
         $isAuth = $request->get('is_auth', '');
@@ -80,6 +81,10 @@ class MemberService
                     $addtime[1] = strtotime(date('Y-m-t') . ' 23:59:59');
                 }
                 $query->whereBetween('member.member_addtimes', $addtime);
+            })->when(!empty($nickname), function ($query) use ($nickname) {
+                $query->where(function($query2) use ($nickname){
+                    $query2->where('member_info.member_info_nickname','like','%'.$nickname.'%')->orWhere('member.member_mobile','like','%'.$nickname.'%');
+                });
             })
             ->select('member_id', 'member_is_vip', 'member_is_owner', 'member_classify', 'member_status', 'member_mobile', 'member_from', 'member_addtimes', 'member_extend_json',
                 'member_info.member_info_nickname', 'member_info.member_info_headimg', 'member_info.member_info_referee', 'member_info.member_info_business', 'member_info.member_info_service', 'member_info.member_info_city', 'member_info.member_info_address', 'member_info.member_info_gender', 'member_info.member_info_birthday',
@@ -98,17 +103,17 @@ class MemberService
             $row['coupon_count'] = CouponDetail::where('join_coupon_detail_member_id', $row['member_id'])->count();
             $row['member_mobile'] = substr($row['member_mobile'], 0, 3) . '****' . substr($row['member_mobile'], 7);
             $row['info'] = [
-                'member_info_nickname' => !empty($row['member_info_nickname']) ? $row['member_info_nickname'] : substr($row['member_mobile'], -4, 4) . '用户',
+                'member_info_nickname' => !empty($row['member_info_nickname']) ? $row['member_info_nickname'] : substr($row['member_mobile'], -4, 4) . '会员',
                 'member_info_headimg' => !empty($row['member_info_headimg']) ? $row['member_info_headimg'] : '',
                 'member_info_referee' => !empty($row['member_info_referee']) ? $row['member_info_referee'] : '',
                 'member_info_business' => !empty($row['member_info_business']) ? $row['member_info_business'] : '',
                 'member_info_service' => !empty($row['member_info_service']) ? $row['member_info_service'] : '',
-                'member_info_city' => !empty($row['member_info_city']) ? explode('-',$row['member_info_city']) : '',
+                'member_info_city' => !empty($row['member_info_city']) ? explode('-', $row['member_info_city']) : '',
                 'member_info_address' => !empty($row['member_info_address']) ? $row['member_info_address'] : '',
                 'member_info_birthday' => !empty($row['member_info_birthday']) ? $row['member_info_birthday'] : '',
                 'member_info_gender' => !empty($row['member_info_gender']) ? $row['member_info_gender'] : '',
             ];
-            if (substr($row['info']['member_info_headimg'],0,2) == '..'){
+            if (substr($row['info']['member_info_headimg'], 0, 2) == '..') {
                 $row['info']['member_info_headimg'] = '';
             }
             if (!empty($row['info']['member_info_address']) && in_array($row['info']['member_info_address'], ['请选择', '省-市-区'])) {
@@ -343,7 +348,7 @@ class MemberService
             'member_info_referee' => !empty($member['info']) && !empty($member['info']['member_info_referee']) ? $member['info']['member_info_referee'] : '',
             'member_info_business' => !empty($member['info']) && !empty($member['info']['member_info_business']) ? $member['info']['member_info_business'] : '',
             'member_info_service' => !empty($member['info']) && !empty($member['info']['member_info_service']) ? $member['info']['member_info_service'] : '',
-            'member_info_city' => !empty($member['info']) && !empty($member['info']['member_info_city']) ? explode('-',$member['info']['member_info_city']) : '',
+            'member_info_city' => !empty($member['info']) && !empty($member['info']['member_info_city']) ? explode('-', $member['info']['member_info_city']) : '',
             'member_info_address' => !empty($member['info']) && !empty($member['info']['member_info_address']) ? $member['info']['member_info_address'] : '',
             'member_info_gender' => !empty($member['info']) && !empty($member['info']['member_info_gender']) ? $member['info']['member_info_gender'] : '',
             'member_info_birthday' => !empty($member['info']) && !empty($member['info']['member_info_birthday']) ? $member['info']['member_info_birthday'] : '',
@@ -363,10 +368,10 @@ class MemberService
             'member_cert_nation' => $member['cert']['member_cert_nation'] ?? '',
             'member_cert_addtimes' => $member['cert']['member_cert_addtimes'] ?? '',
         ];
-        if (!empty($member['cert']['member_cert_addtimes'])){
-            $member['cert']['member_cert_addtimes'] = date('Y-m-d',$member['cert']['member_cert_addtimes']);
-        }else{
-            $member['cert']['member_cert_addtimes'] = date('Y-m-d',strtotime($member['member_addtimes']));
+        if (!empty($member['cert']['member_cert_addtimes'])) {
+            $member['cert']['member_cert_addtimes'] = date('Y-m-d', $member['cert']['member_cert_addtimes']);
+        } else {
+            $member['cert']['member_cert_addtimes'] = date('Y-m-d', strtotime($member['member_addtimes']));
         }
         if (!empty($member['join_invite_member_id'])) {
             $inviteMember = Member::with([
@@ -434,6 +439,9 @@ class MemberService
         $account = MemberAccount::where('join_account_member_id', $memberId)
             ->where('member_account_classify', 'VIP')
             ->first();
+        if (!$account) {
+            return json_fail('暂无数据');
+        }
         $balance = $account->member_account_surplus + $account->member_account_added;
 
         $info = PayDetail::where(function ($query) use ($memberId) {
@@ -545,6 +553,9 @@ class MemberService
         $account = MemberAccount::where('join_account_member_id', $memberId)
             ->where('member_account_classify', 'WELFARE')
             ->first();
+        if (!$account) {
+            return json_fail('暂无数据');
+        }
         $balance = $account->member_account_surplus + $account->member_account_added;
 
         $info = PayDetail::where(function ($query) use ($memberId) {
@@ -657,6 +668,9 @@ class MemberService
         $account = MemberAccount::where('join_account_member_id', $memberId)
             ->where('member_account_classify', 'CASH')
             ->first();
+        if (!$account) {
+            return json_fail('暂无数据');
+        }
         $balance = $account->member_account_surplus + $account->member_account_added;
 
         $info = PayDetail::where(function ($query) use ($memberId) {
@@ -697,12 +711,12 @@ class MemberService
             if (mb_substr($item['goods_category'], 0, 7) == '自定义金额充值') {
                 $item['goods_category'] = '自定义金额充值';
             }
-            if (in_array($item['pay_category'], ['RECHARGE', 'REFUND'])) {
+            if (in_array($item['pay_category'], ['RECHARGE', 'REFUND', 'GIVE','PARTNER'])) {
                 $item['balance_type'] = 'add';
             } else {
                 $item['balance_type'] = 'cut';
             }
-            if ($key == 0 && in_array($item['pay_category'], ['RECHARGE', 'REFUND'])) {
+            if ($key == 0 && in_array($item['pay_category'], ['RECHARGE', 'REFUND', 'GIVE','PARTNER'])) {
                 if (!empty($item['pay_extend_json'])) {
                     $extendJson = json_decode($item['pay_extend_json'], true);
                     if (!isset($extendJson['added_amount'])) {
@@ -717,7 +731,7 @@ class MemberService
                             'join_pay_member_id' => $item['join_pay_member_id'],
                             'pay_addtimes' => $item['pay_addtimes'],
                             'pay_amount' => $extendJson['added_amount'],
-                            'pay_category' => 'ADDED',
+                            'pay_category' => $item['pay_category'] == 'GIVE' ? 'GIVE' : 'ADDED',
                             'balance' => number_format($balance, 2, '.', ''),
                             'balance_type' => 'add',
                         ];
@@ -727,11 +741,14 @@ class MemberService
 
                 $item['balance'] = number_format($balance, 2, '.', '');
                 $balance = $balance - $item['pay_amount'];
-                $data[] = $item;
+                if ($item['pay_category'] != 'GIVE'){
+                    $data[] = $item;
+                }
+
                 continue;
             }
 
-            if (in_array($item['pay_category'], ['RECHARGE', 'REFUND'])) {
+            if (in_array($item['pay_category'], ['RECHARGE', 'REFUND', 'GIVE','PARTNER'])) {
                 if (!empty($item['pay_extend_json'])) {
                     $extendJson = json_decode($item['pay_extend_json'], true);
                     if (isset($extendJson['added_amount']) && floatval($extendJson['added_amount']) > 0) {
@@ -739,7 +756,7 @@ class MemberService
                             'join_pay_member_id' => $item['join_pay_member_id'],
                             'pay_addtimes' => $item['pay_addtimes'],
                             'pay_amount' => $extendJson['added_amount'],
-                            'pay_category' => 'ADDED',
+                            'pay_category' => $item['pay_category'] == 'GIVE' ? 'GIVE' : 'ADDED',
                             'balance' => number_format($balance, 2, '.', ''),
                             'balance_type' => 'add',
                         ];
@@ -753,7 +770,9 @@ class MemberService
                 $balance = $balance + $item['pay_amount'];
             }
 
-            $data[] = $item;
+            if ($item['pay_category'] != 'GIVE') {
+                $data[] = $item;
+            }
         }
 
         $total = count($data);
@@ -768,7 +787,9 @@ class MemberService
         $account = MemberAccount::where('join_account_member_id', $memberId)
             ->where('member_account_classify', 'POINTS')
             ->first();
-
+        if (!$account) {
+            return json_fail('暂无数据');
+        }
         $balance = $account->member_account_surplus + $account->member_account_added;
         $points = ClientPoints::where('join_client_points_member_id', $memberId)->get()->toArray();
         $nowPoint = 0;
@@ -912,7 +933,7 @@ class MemberService
                 'member_info_service' => $params['member_info_service'] ?? '',
                 'member_info_city' => !empty($params['province']) ? implode('-', $params['province']) : '',
                 'member_info_address' => $params['member_info_address'] ?? '',
-                'member_info_birthday'=>$params['birth'] ? date('Y-m-d', strtotime($params['birth'])) : '',
+                'member_info_birthday' => $params['birth'] ? date('Y-m-d', strtotime($params['birth'])) : '',
                 'member_info_gender' => $params['gender'] ?? '',
             ];
             MemberInfo::insert($infoData);
@@ -1009,7 +1030,7 @@ class MemberService
                 'member_info_service' => $params['member_info_service'] ?? '',
                 'member_info_city' => !empty($params['province']) ? implode('-', $params['province']) : '',
                 'member_info_address' => $params['member_info_address'] ?? '',
-                'member_info_birthday'=>$params['birth'] ? date('Y-m-d', strtotime($params['birth'])) : '',
+                'member_info_birthday' => $params['birth'] ? date('Y-m-d', strtotime($params['birth'])) : '',
                 'member_info_gender' => $params['gender'] ?? '',
             ];
             if (!MemberInfo::where('join_info_member_id', $params['member_id'])->exists()) {
@@ -1018,25 +1039,25 @@ class MemberService
                 MemberInfo::where('join_info_member_id', $params['member_id'])->update($infoData);
             }
             // 福利账户
-            if (!empty($params['member_classify']) && $params['member_classify'] == 'EMPLOY' && !MemberAccount::where('member_account_nbr',$memberId.'-WELFARE')->exists()){
+            if (!empty($params['member_classify']) && $params['member_classify'] == 'EMPLOY' && !MemberAccount::where('member_account_nbr', $memberId . '-WELFARE')->exists()) {
                 $welfareData = [
-                    'join_account_member_id'=>$memberId,
-                    'member_account_classify'=>'WELFARE',
-                    'member_account_status'=>'ACTIVED',
-                    'member_account_category'=>'NORMAL',
-                    'member_account_nbr'=>$memberId.'-WELFARE',
-                    'member_account_name'=>'福利账户',
-                    'member_account_addtimes'=>time()
+                    'join_account_member_id' => $memberId,
+                    'member_account_classify' => 'WELFARE',
+                    'member_account_status' => 'ACTIVED',
+                    'member_account_category' => 'NORMAL',
+                    'member_account_nbr' => $memberId . '-WELFARE',
+                    'member_account_name' => '福利账户',
+                    'member_account_addtimes' => time()
                 ];
                 MemberAccount::insert($welfareData);
             }
 
             Db::commit();
-        }catch (BusinessException $e){
+        } catch (BusinessException $e) {
             Db::rollBack();
             dump($e->getMessage() . ';line:' . $e->getLine());
             return json_fail($e->getMessage());
-        }catch (\Exception $e) {
+        } catch (\Exception $e) {
             Db::rollBack();
             dump($e->getMessage() . ';line:' . $e->getLine());
             return json_fail("数据更新失败");

+ 18 - 3
app/admin/service/order/OrderService.php

@@ -111,7 +111,6 @@ class OrderService
             $orders = Order::where('order_status_system', 'PAYING')
                 ->where('order_category', '<>', 'DISHES')     // 点餐不自动取消
                 ->where('order_category', '<>', 'VIP')      // 康养城订单不自动取消,有分次付款
-                // ->where('order_platform','<>','SYSTEM')     // 后台产生的订单不自动取消
                 ->where(function ($query) {
                     $query->where('order_platform', '<>', 'SYSTEM')->orWhereNull('order_platform');
                 })
@@ -145,6 +144,20 @@ class OrderService
                         $goodsRunning->save();
                     }
                 }
+                // 释放优惠券
+                if (!empty($order->order_discount_json)) {
+                    $orderDiscountJson = json_decode($order->order_discount_json, true);
+                    foreach ($orderDiscountJson as $discount) {
+                        if (!empty($discount['coupon_id']) && !empty($discount['coupon_detail_id'])) {
+                            foreach ($discount['coupon_detail_id'] as $detailId) {
+                                if (substr($detailId, 0, 4) == 'CUDT') {
+                                    // 恢复优惠券
+                                    CouponDetail::where('coupon_detail_id', $detailId)->update(['coupon_detail_status' => 'ACTIVED']);
+                                }
+                            }
+                        }
+                    }
+                }
 
                 // 订单详情表
                 OrderSheet::where('join_sheet_order_id', $order->order_id)->update(['order_sheet_status' => 'CANCEL']);
@@ -185,6 +198,7 @@ class OrderService
                 'charge_content' => $params['order_remark'] ?? '',
                 'charge_user_id' => $params['write_off_member_id'],
                 'charge_premises' => $params['dept_premises_id'],
+                'charge_waiter' => $params['charge_waiter'] ?? ''
             ],
             'member_id' => $params['join_order_member_id']
         ];
@@ -204,6 +218,7 @@ class OrderService
             'charge' => [
                 'charge_amount' => $params['charge_amount'],
                 'charge_content' => $params['order_remark'] ?? '',
+                'charge_waiter' => $params['charge_waiter'] ?? '',
                 'charge_user_id' => $params['write_off_member_id'],
                 'charge_premises' => $params['dept_premises_id'],
                 'charge_premises_info' => $params['dept'] ?? ''
@@ -546,7 +561,7 @@ class OrderService
                     ->where('join_goods_coupon_id', $couponId)
                     ->where('coupon_detail.join_coupon_detail_member_id', $memberId);
                 if ($settlementNow == 'Y' && $type == 'pay') {
-                    $couponDetail = $couponDetail->whereIn('coupon_detail.coupon_detail_status', ['ACTIVED', 'WAITING']);
+                    $couponDetail = $couponDetail->whereIn('coupon_detail.coupon_detail_status', ['ACTIVED']);
                 } else {
                     $couponDetail = $couponDetail->where('coupon_detail.coupon_detail_status', 'ACTIVED');
                 }
@@ -729,7 +744,7 @@ class OrderService
                     ->where('join_goods_coupon_id', $couponId)
                     ->where('coupon_detail.join_coupon_detail_member_id', $memberId);
                 if ($settlementNow == 'Y') {
-                    $couponDetail = $couponDetail->whereIn('coupon_detail.coupon_detail_status', ['ACTIVED', 'WAITING']);
+                    $couponDetail = $couponDetail->whereIn('coupon_detail.coupon_detail_status', ['ACTIVED']);
                 } else {
                     $couponDetail = $couponDetail->where('coupon_detail.coupon_detail_status', 'ACTIVED');
                 }

+ 2 - 2
app/model/MarketCustomer.php

@@ -36,8 +36,8 @@ class MarketCustomer extends Model
             'age_range' => ['20岁以下', '21岁-30岁', '31岁-40岁', '41岁-50岁', '51岁-60岁', '61岁-80岁', '80岁以上'],
             'visit_type' => [
                 'common' => ['', '路过', '分销', '朋友介绍', '安居客、房天下', '微信朋友圈', '户外', '微信公众号', '工地围挡', '老带新', '圈层营销', '自拓'],
-                'type1' => ['100' => '派单', '101' => '城市展厅', '102' => '活动'],
-                'type2' => ['200' => '内渠', '201' => '自渠']
+                'type1' => ['100' => '派单', '101' => '城市展厅', '102' => '活动', '200' => '内渠', '201' => '自渠'],
+                'type2' => []
             ],
             'focus' => ['位置', '交通', '配套', '价格', '品牌', '适老化', '物业', '医疗', '运营'],
             'region' => ['唐冶', '历城', '历下', '高新', '天桥', '槐荫', '市中', '其他'],

+ 2 - 0
process/Task.php

@@ -40,6 +40,8 @@ class Task
             OrderService::AutomaticReceipt();
             // 发货后15天自动完成
             OrderService::AutomaticComplete();
+            // 发放周期券
+            CouponService::sendPeriodCoupon();
         });
     }
 }

+ 2 - 0
route/admin.php

@@ -713,6 +713,7 @@ Route::group('/admin', function () {
             Route::get('/my', [\app\admin\controller\member\BenefitController::class, 'my']);
             Route::get('/service', [\app\admin\controller\member\BenefitController::class, 'service']);
             Route::post('/add', [\app\admin\controller\member\BenefitController::class, 'insert']);
+            Route::post('/writeOff', [\app\admin\controller\member\BenefitController::class, 'writeOff']);
             Route::post('/update', [\app\admin\controller\member\BenefitController::class, 'update']);
             Route::delete('/delete', [\app\admin\controller\member\BenefitController::class, 'delete']);
         })->middleware([
@@ -1030,6 +1031,7 @@ Route::group('/admin', function () {
             Route::get('/welfareList', [\app\admin\controller\order\PayDetailController::class, 'selectWelfare']);
             Route::get('/goodsOrder', [\app\admin\controller\order\PayDetailController::class, 'goodsOrder']);
             Route::post('/insertRecharge', [\app\admin\controller\order\PayDetailController::class, 'insertRecharge']);
+            Route::post('/insertGive', [\app\admin\controller\order\PayDetailController::class, 'insertGive']);
             Route::post('/insertRechargeWelfare', [\app\admin\controller\order\PayDetailController::class, 'insertRechargeWelfare']);
 //            Route::get('/info', [\app\admin\controller\order\AppointmentController::class, 'info']);
         });