Parcourir la source

Merge branch 'dev'

gorden il y a 1 mois
Parent
commit
e3e8b4ff90

+ 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('核销失败');

+ 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;
     }
 

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

@@ -274,6 +274,45 @@ 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';
+
+            $this->doInsert($data);
+
+            // 金额累加到福利账户
+            $memberAccount = MemberAccount::where('join_account_member_id', $data['join_pay_member_id'])->where('member_account_classify', 'WELFARE')->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();
+
+            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 +386,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 +446,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'] = number_format($data['pay_amount'] * $rate, 2, '.', '');
+        $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)];
         }
 

+ 109 - 44
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,13 +821,17 @@ 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 {
             // 使用优惠券
@@ -1423,11 +1429,12 @@ 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();
@@ -1989,11 +1996,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 +2373,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 +2388,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) {
@@ -2595,11 +2603,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 +2858,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 +2873,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) {
@@ -3793,27 +3802,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 +3842,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 +3890,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 +4183,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,31 +4212,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;
             }
+            dump($orderIds);
+        }
+        if (!empty($orderId) || !empty($goodsName)) {
+            $where['order_id'] = ['in', implode(',', $orderIds)];
         }
         $order = $request->get('order', 'desc');
         $field = $field ?? 'order_addtimes';
@@ -4240,7 +4302,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 +4317,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'];

+ 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 "赠品券":

+ 3 - 3
app/admin/service/member/MemberService.php

@@ -697,12 +697,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'])) {
                 $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'])) {
                 if (!empty($item['pay_extend_json'])) {
                     $extendJson = json_decode($item['pay_extend_json'], true);
                     if (!isset($extendJson['added_amount'])) {
@@ -731,7 +731,7 @@ class MemberService
                 continue;
             }
 
-            if (in_array($item['pay_category'], ['RECHARGE', 'REFUND'])) {
+            if (in_array($item['pay_category'], ['RECHARGE', 'REFUND','GIVE'])) {
                 if (!empty($item['pay_extend_json'])) {
                     $extendJson = json_decode($item['pay_extend_json'], true);
                     if (isset($extendJson['added_amount']) && floatval($extendJson['added_amount']) > 0) {

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

@@ -185,6 +185,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 +205,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'] ?? ''

+ 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']);
         });