| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439 | 
							- <?php
 
- namespace app\api\controller\inspection;
 
- use app\api\controller\inspection\Base;
 
- use app\common\Enum\PayEnum;
 
- use app\common\Service\OrderService;
 
- use app\common\Enum\OrderEnum;
 
- use app\common\Service\OrderActionService;
 
- use app\common\Enum\OrderActionEnum;
 
- use app\common\Enum\OrderGoodsEnum;
 
- use app\common\model\OrderGoods;
 
- use app\common\Service\Order\OrderShipService;
 
- use think\Db;
 
- use app\common\library\easywechatPlus\WechatMiniProgramShop;
 
- use app\common\facade\Wechat;
 
- /**
 
-  * 验货端订单接口
 
-  * 
 
-  * 包含功能:
 
-  * - 订单详情查询
 
-  * - 订单列表查询
 
-  * - 订单发货确认
 
-  * - 订单统计功能(按日/月/年统计)
 
-  * - 订单趋势数据
 
-  * 
 
-  * 统计功能说明:
 
-  * - 验收订单:已验货通过的订单
 
-  * - 退回订单:验货不通过的订单
 
-  * - 售后订单:退款相关的订单
 
-  */
 
- class Order extends Base
 
- {
 
-     protected $noNeedLogin = [];
 
-       //订单详情
 
-       public function detail()
 
-       {
 
-           // 验证请求参数
 
-           $validate = new \app\api\validate\Order();
 
-           $orderId = $this->request->get('orderId');
 
-           $params = ['orderId' => $orderId];
 
-           if (!$validate->scene('detail')->check($params)) {
 
-               $this->error($validate->getError());
 
-           }
 
-           
 
-           // 获取当前验货员所属的供应商ID
 
-           $supplierId = $this->application->supplier_id;
 
-           if (!$supplierId) {
 
-               $this->error('您未绑定供应商');
 
-           }
 
-           
 
-           // 使用供应商订单详情方法,只获取该供应商的商品
 
-           $order = OrderService::getSupplierOrderDetail($orderId, $supplierId, 0);
 
-           if (empty($order)) {
 
-               $this->error('未找到订单或该订单不包含您供应商的商品');
 
-           }
 
-           
 
-           /** @var \app\common\model\Order $order */
 
-           //$order->append(['order_status_text']);
 
-           $address = OrderService::getAddressInfo($orderId);
 
-           $order->address = $address;
 
-           // $order->append(['status_text']);
 
-           // $order->hidden(explode(',', 'method,transactionid,updatetime,deletetime'));
 
-           // $order->expiretime = $order->expiretime - time();
 
-           $order->order_status_text = OrderEnum::STATUS_TEXT_MAP_INSPECTION[$order->order_status];
 
-           $this->success('', $order);
 
-       }
 
-   
 
-       //订单列表
 
-       public function index()
 
-       {
 
-           // 验证请求参数
 
-           $validate = new \app\api\validate\inspection\Order();
 
-           $param = $this->request->param();
 
-           $param['time_range'] = '1'; // 添加触发时间范围验证的字段
 
-           
 
-           if (!$validate->scene('lists')->check($param)) {
 
-               $this->error($validate->getError());
 
-           }        
 
-           // 设置默认值
 
-           $userId = 0;
 
-           $param['page']     = $param['page'] ?? 1;
 
-           $param['page_size'] = $param['page_size'] ?? 10;
 
-           $status   = $param['status'] ?? 0; // 默认为0(全部订单)
 
-           $param['keywords'] = $param['keywords'] ?? '';
 
-           $status   = OrderEnum::SHOW_INSPECTION_TYPE_STATUS_MAP[$status];         
 
-           // 查询对应的工厂 信息
 
-           $supplierId = $this->application->supplier_id;
 
-           $list = OrderService::getSupplierOrderList($supplierId ,$userId, $param, $status);
 
-           foreach ($list as $item) {
 
-              // $item->append(['order_status_text']);
 
-               $field = 'id,order_sn,amount,goods_price,order_amount,express_name,express_no,order_goods,order_status_text,order_status';
 
-               $item->visible(explode(',', $field));
 
-               $item->order_status_text = OrderEnum::STATUS_TEXT_MAP_INSPECTION[$item->order_status];
 
-           }
 
-           $this->success('获取成功', $list);
 
-       }
 
-       //确认发货
 
-       public function send()
 
-       {
 
-         // 验证请求参数
 
-         $userId = 0;
 
-         $validate = new \app\api\validate\inspection\Order();
 
-         $params = [
 
-             'order_id' => $this->request->post('order_id'),
 
-             'order_goods_id' => $this->request->post('order_goods_id'),
 
-             'express_id' => $this->request->post('express_id'),
 
-             'express_no' => $this->request->post('express_no'),
 
-             'express_image' => $this->request->post('express_image/a', [])
 
-         ];
 
-         if (!$validate->scene('send')->check($params)) {
 
-             $this->error($validate->getError());
 
-         }
 
-         
 
-         //根据ID 查询快递公司
 
-         $expressId = intval($params['express_id'] ?? 0);
 
-         $express = OrderShipService::getExpressById($expressId);
 
-         if (empty($express)) {
 
-             $this->error('快递公司不存在');
 
-         }         
 
-         $orderId = intval($params['order_id'] ?? 0);
 
-         $orderGoodsId = intval($params['order_goods_id'] ?? 0);
 
-         
 
-         if (empty($orderId)) {
 
-             $this->error('订单ID不能为空');
 
-         }
 
-         
 
-         if (empty($orderGoodsId)) {
 
-             $this->error('订单商品ID不能为空');
 
-         }        
 
-         // 验证订单商品是否可以发货
 
-         $orderData = OrderService::validateOrderGoodsForDelivery($orderId, $orderGoodsId);
 
-         if (!$orderData) {
 
-             $this->error('订单或订单商品不存在,或不允许发货');
 
-         }
 
-         
 
-         $order = $orderData['order'];
 
-         $orderGoods = $orderData['order_goods'];
 
-         $expressName = $express->name;
 
-         $expressCode = $express->code;
 
-         $expressNo = trim($params['express_no'] ?? '');
 
-         $expressImage = $params['express_image'] ?? [];         
 
-         // 事务处理
 
-         Db::startTrans();
 
-         try{
 
-            // 创建包裹
 
-         $orderExpress = OrderShipService::createOrderExpress($orderId, $order['user_id'], $expressName, $expressCode, $expressNo, 'input', '', [], $expressImage);
 
-         if (!$orderExpress) {
 
-             Db::rollback();
 
-             $this->error('创建包裹失败');
 
-         }
 
-         // 1. 更新订单商品发货状态
 
-         $result = OrderService::updateOrderGoodsDeliveryStatus($orderGoodsId, $expressName, $expressNo, $expressImage,$orderExpress->id);
 
-         if (!$result) {
 
-             Db::rollback();
 
-             $this->error('更新订单商品发货状态失败');
 
-         }
 
-           
 
-         // 2. 检查并更新订单状态
 
-         OrderService::updateOrderStatusByDeliveryResult($orderId);
 
-           
 
-         // 3. 记录操作日志
 
-         $orderActionService = new OrderActionService();
 
-         $orderActionService->addInspectionAction(
 
-             $order->order_sn,
 
-             OrderActionEnum::ACTION_SHIP,
 
-             $userId,
 
-             '订单商品发货,商品:' . $orderGoods->goods_title . ',快递公司:' . $expressName . ',快递单号:' . $expressNo,
 
-             $userId,   
 
-             [
 
-                 'order_goods_id' => $orderGoodsId,
 
-                 'goods_title' => $orderGoods->goods_title,
 
-                 'express_name' => $expressName,
 
-                 'express_no' => $expressNo,
 
-             ]
 
-         ); 
 
-     
 
-         // 提交事务
 
-         Db::commit();   
 
-         } catch (\Exception $e) {
 
-             // 回滚事务
 
-             Db::rollback();
 
-             $this->error('发货失败'.$e->getMessage());
 
-         }
 
-          // 4. 同步微信小程序订单发货状态  todo 队列处理
 
-         $data = [
 
-             'order' => $order,
 
-             'items' => $orderGoods,
 
-             'express' => $orderExpress,
 
-             'delivery_type' => 'express',
 
-         ];
 
-         $this->syncWechatMiniProgramOrderDispatch($data,'send');
 
-         $this->success('发货成功');
 
-       }
 
-       private function syncWechatMiniProgramOrderDispatch($params =[],$type='send'){
 
-         $order = $params['order'];
 
-         $items = $params['items'];
 
-         $express = $params['express'];
 
-         $dispatch_type = $params['delivery_type'];
 
-         $uploadshoppingInfo = new WechatMiniProgramShop(Wechat::miniProgram());
 
-         // 微信小程序,并且存在微信发货管理权限时,才推送发货消息
 
-         if ($order['platform'] == 'WechatMiniProgram' && $uploadshoppingInfo->isTradeManaged()) {
 
-             $hasNosend = OrderGoods::where('order_id', $order['id'])
 
-             // ->where('refund_status', OrderGoodsEnum::REFUND_STATUS_NOREFUND)
 
-             ->where('delivery_status', OrderGoodsEnum::DELIVERY_STATUS_NOSEND)->count();
 
-             if ($type == 'send') {
 
-                 // if (!$hasNosend && in_array('wechat', $order->pay_type)) {
 
-                 if (!$hasNosend && $order->pay_type == PayEnum::METHOD_WECHAT) {
 
-                     // 所有 items 都已经发货,将交易信息上传微信
 
-                     $uploadshoppingInfo->uploadShippingInfos($order);
 
-                 }
 
-             } else {
 
-                 // 修改物流单
 
-                 // if (!$hasNosend && in_array('wechat', $order->pay_types)) {
 
-                 if (!$hasNosend && $order->pay_type == PayEnum::METHOD_WECHAT) {
 
-                     // 所有 items 都已经发货,将交易信息上传微信
 
-                     $uploadshoppingInfo->uploadShippingInfos($order, $express, 'change');
 
-                 }
 
-             }
 
-         }
 
-         // 添加自动确认收货队列,这个队列只自动确认 本次发货的 items
 
-         // $confirm_days = Config::getConfigField('shop.order.auto_confirm');
 
-         // $confirm_days = $confirm_days > 0 ? $confirm_days : 0;
 
-         // if ($confirm_days) {
 
-         //     // 小于等于0, 不自动确认收货
 
-         //     \think\Queue::later(($confirm_days * 86400), '\addons\shopro\job\OrderAutoOper@autoConfirm', $params, 'shopro');
 
-         // }
 
-            
 
-         
 
-       }
 
-       // 统计订单 
 
-       public function statistics()
 
-       {
 
-           // 验证请求参数
 
-           $validate = new \app\api\validate\Order();
 
-           $params = [
 
-               'type' => $this->request->param('type', 'day'),
 
-               'date' => $this->request->param('date', date('Y-m-d'))
 
-           ];
 
-           
 
-           if (!$validate->scene('statistics')->check($params)) {
 
-               $this->error($validate->getError());
 
-           }
 
-           
 
-           // 获取验证后的参数
 
-           $type = $params['type'];
 
-           $date = $params['date'];
 
-           
 
-           // 根据类型处理日期和时间范围
 
-           switch ($type) {
 
-               case 'day':
 
-                   $startTime = strtotime($date . ' 00:00:00');
 
-                   $endTime = strtotime($date . ' 23:59:59');
 
-                   $displayDate = date('m-d', $startTime);
 
-                   // 前一天
 
-                   $prevStartTime = strtotime($date . ' 00:00:00') - 86400;
 
-                   $prevEndTime = strtotime($date . ' 23:59:59') - 86400;
 
-                   break;
 
-               case 'month':
 
-                   $startTime = strtotime(date('Y-m-01 00:00:00', strtotime($date)));
 
-                   $endTime = strtotime(date('Y-m-t 23:59:59', strtotime($date)));
 
-                   $displayDate = date('Y-m', $startTime);
 
-                   // 前一个月
 
-                   $prevStartTime = strtotime(date('Y-m-01 00:00:00', strtotime($date . ' -1 month')));
 
-                   $prevEndTime = strtotime(date('Y-m-t 23:59:59', strtotime($date . ' -1 month')));
 
-                   break;
 
-               case 'year':
 
-                   $startTime = strtotime(date('Y-01-01 00:00:00', strtotime($date)));
 
-                   $endTime = strtotime(date('Y-12-31 23:59:59', strtotime($date)));
 
-                   $displayDate = date('Y', $startTime) . '年';
 
-                   // 前一年
 
-                   $prevStartTime = strtotime(date('Y-01-01 00:00:00', strtotime($date . ' -1 year')));
 
-                   $prevEndTime = strtotime(date('Y-12-31 23:59:59', strtotime($date . ' -1 year')));
 
-                   break;
 
-           }
 
-           
 
-           // 获取当前用户ID
 
-           $userId = $this->auth->id;
 
-           
 
-           // 如果需要根据工厂统计,可以在这里添加工厂相关逻辑
 
-           // 目前先按用户统计,后续可以根据实际的工厂关联字段进行调整
 
-           
 
-           // 当前期间统计
 
-           $currentStats = $this->getOrderStatistics($userId, $startTime, $endTime);
 
-           
 
-           // 上期统计(用于对比)
 
-           $prevStats = $this->getOrderStatistics($userId, $prevStartTime, $prevEndTime);
 
-           
 
-           // 计算增长率
 
-           $growthRate = [
 
-               'inspection_rate' => $this->calculateGrowthRate($prevStats['inspection_count'], $currentStats['inspection_count']),
 
-               'return_rate' => $this->calculateGrowthRate($prevStats['return_count'], $currentStats['return_count']),
 
-               'aftersale_rate' => $this->calculateGrowthRate($prevStats['aftersale_count'], $currentStats['aftersale_count'])
 
-           ];
 
-           
 
-           // 返回统计数据
 
-           $data = [
 
-               'date' => $displayDate,
 
-               'type' => $type,
 
-               'current_period' => $currentStats,
 
-               'previous_period' => $prevStats,
 
-               'growth_rate' => $growthRate,
 
-               'statistics' => [
 
-                   'inspection_count' => $currentStats['inspection_count'],
 
-                   'return_count' => $currentStats['return_count'],
 
-                   'aftersale_count' => $currentStats['aftersale_count']
 
-               ]
 
-           ];
 
-           
 
-           $this->success('统计数据获取成功', $data);
 
-       }
 
-       
 
-       /**
 
-        * 获取订单统计数据
 
-        */
 
-       private function getOrderStatistics($userId, $startTime, $endTime)
 
-       {
 
-           // 统计验收订单(验货通过)
 
-           $inspectionCount = \app\common\model\Order::where('user_id', $userId)
 
-               ->where('order_status', OrderEnum::STATUS_INSPECTION_PASS)
 
-               ->where('createtime', '>=', $startTime)
 
-               ->where('createtime', '<=', $endTime)
 
-               ->count();
 
-           
 
-           // 统计退回订单(验货不通过)
 
-           $returnCount = \app\common\model\Order::where('user_id', $userId)
 
-               ->where('order_status', OrderEnum::STATUS_INSPECTION_FAIL)
 
-               ->where('createtime', '>=', $startTime)
 
-               ->where('createtime', '<=', $endTime)
 
-               ->count();
 
-           
 
-           // 统计待验收订单
 
-           $aftersaleCount = \app\common\model\Order::where('user_id', $userId)
 
-               ->whereIn('order_status', [OrderEnum::STATUS_PAY])
 
-               ->where('createtime', '>=', $startTime)
 
-               ->where('createtime', '<=', $endTime)
 
-               ->count();
 
-           
 
-           return [
 
-               'inspection_count' => $inspectionCount,
 
-               'return_count' => $returnCount,
 
-               'aftersale_count' => $aftersaleCount
 
-           ];
 
-       }
 
-       
 
-       /**
 
-        * 计算增长率
 
-        */
 
-       private function calculateGrowthRate($prevValue, $currentValue)
 
-       {
 
-           if ($prevValue == 0) {
 
-               return $currentValue > 0 ? 100 : 0;
 
-           }
 
-           return round((($currentValue - $prevValue) / $prevValue) * 100, 2);
 
-       }
 
-       
 
-       /**
 
-        * 获取统计数据的时间范围选择
 
-        */
 
-       public function getStatisticsDateRange()
 
-       {
 
-           // 获取最早和最晚的订单时间
 
-           $userId = $this->auth->id;
 
-           
 
-           $earliest = \app\common\model\Order::where('user_id', $userId)
 
-               ->order('createtime', 'asc')
 
-               ->value('createtime');
 
-           
 
-           $latest = \app\common\model\Order::where('user_id', $userId)
 
-               ->order('createtime', 'desc')
 
-               ->value('createtime');
 
-           
 
-           $data = [
 
-               'earliest_date' => $earliest ? date('Y-m-d', $earliest) : date('Y-m-d'),
 
-               'latest_date' => $latest ? date('Y-m-d', $latest) : date('Y-m-d'),
 
-               'current_date' => date('Y-m-d'),
 
-               'current_month' => date('Y-m'),
 
-               'current_year' => date('Y')
 
-           ];
 
-           
 
-           $this->success('日期范围获取成功', $data);
 
-       }
 
-       
 
-        /**
 
-         * 获取历史趋势数据
 
-         */
 
-        public function getTrendData()
 
-        {
 
-            // 验证请求参数
 
-            $validate = new \app\api\validate\Order();
 
-            $params = [
 
-                'type' => $this->request->param('type', 'day'),
 
-                'days' => $this->request->param('days', 7)
 
-            ];
 
-            
 
-            if (!$validate->scene('trend')->check($params)) {
 
-                $this->error($validate->getError());
 
-            }
 
-            
 
-            // 获取验证后的参数
 
-            $type = $params['type'];
 
-            $days = $params['days'];
 
-           
 
-           $userId = $this->auth->id;
 
-           $trendData = [];
 
-           
 
-           for ($i = $days - 1; $i >= 0; $i--) {
 
-               $date = date('Y-m-d', strtotime("-{$i} days"));
 
-               $startTime = strtotime($date . ' 00:00:00');
 
-               $endTime = strtotime($date . ' 23:59:59');
 
-               
 
-               $stats = $this->getOrderStatistics($userId, $startTime, $endTime);
 
-               $trendData[] = [
 
-                   'date' => $date,
 
-                   'display_date' => date('m-d', $startTime),
 
-                   'inspection_count' => $stats['inspection_count'],
 
-                   'return_count' => $stats['return_count'],
 
-                   'aftersale_count' => $stats['aftersale_count']
 
-               ];
 
-           }
 
-           
 
-           $this->success('趋势数据获取成功', $trendData);
 
-       }
 
-       // 获取快递公司列表
 
-       public function getExpressCompany(){
 
-         $list = OrderShipService::getExpressCompany();
 
-         $this->success('快递公司列表获取成功', $list);
 
-       }
 
- }
 
 
  |