Order.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. <?php
  2. namespace app\api\controller\inspection;
  3. use app\api\controller\inspection\Base;
  4. use app\common\Service\OrderService;
  5. use app\common\Enum\OrderEnum;
  6. use app\common\Service\OrderActionService;
  7. use app\common\Enum\OrderActionEnum;
  8. use app\common\Service\Order\OrderShipService;
  9. /**
  10. * 验货端订单接口
  11. *
  12. * 包含功能:
  13. * - 订单详情查询
  14. * - 订单列表查询
  15. * - 订单发货确认
  16. * - 订单统计功能(按日/月/年统计)
  17. * - 订单趋势数据
  18. *
  19. * 统计功能说明:
  20. * - 验收订单:已验货通过的订单
  21. * - 退回订单:验货不通过的订单
  22. * - 售后订单:退款相关的订单
  23. */
  24. class Order extends Base
  25. {
  26. protected $noNeedLogin = [];
  27. //订单详情
  28. public function detail()
  29. {
  30. // 验证请求参数
  31. $validate = new \app\api\validate\Order();
  32. $orderId = $this->request->get('orderId');
  33. $params = ['orderId' => $orderId];
  34. if (!$validate->scene('detail')->check($params)) {
  35. $this->error($validate->getError());
  36. }
  37. $order = OrderService::getDetail($orderId, $this->auth->id);
  38. if (empty($order)) {
  39. $this->error('未找到订单');
  40. }
  41. /** @var \app\common\model\Order $order */
  42. //$order->append(['order_status_text']);
  43. $address = OrderService::getAddressInfo($orderId);
  44. $order->address = $address;
  45. // $order->append(['status_text']);
  46. // $order->hidden(explode(',', 'method,transactionid,updatetime,deletetime'));
  47. // $order->expiretime = $order->expiretime - time();
  48. $order->order_status_text = OrderEnum::STATUS_TEXT_MAP_INSPECTION[$order->order_status];
  49. $this->success('', $order);
  50. }
  51. //订单列表
  52. public function index()
  53. {
  54. // 验证请求参数
  55. $validate = new \app\api\validate\inspection\Order();
  56. $param = $this->request->param();
  57. $param['time_range'] = '1'; // 添加触发时间范围验证的字段
  58. if (!$validate->scene('lists')->check($param)) {
  59. $this->error($validate->getError());
  60. }
  61. // 设置默认值
  62. $userId = 0;
  63. $param['page'] = $param['page'] ?? 1;
  64. $param['page_size'] = $param['page_size'] ?? 10;
  65. $status = $param['status'] ?? 0; // 默认为0(全部订单)
  66. $param['keywords'] = $param['keywords'] ?? '';
  67. $status = OrderEnum::SHOW_INSPECTION_TYPE_STATUS_MAP[$status];
  68. // 查询对应的工厂 信息
  69. $supplierId = $this->application->supplier_id;
  70. $list = OrderService::getSupplierOrderList($supplierId ,$userId, $param, $status);
  71. foreach ($list as $item) {
  72. // $item->append(['order_status_text']);
  73. $field = 'id,order_sn,amount,goods_price,order_amount,express_name,express_no,order_goods,order_status_text,order_status';
  74. $item->visible(explode(',', $field));
  75. $item->order_status_text = OrderEnum::STATUS_TEXT_MAP_INSPECTION[$item->order_status];
  76. }
  77. $this->success('获取成功', $list);
  78. }
  79. //确认发货
  80. public function send()
  81. {
  82. // 验证请求参数
  83. $userId = $this->auth->id;
  84. $validate = new \app\api\validate\inspection\Order();
  85. $params = [
  86. 'order_id' => $this->request->post('order_id'),
  87. 'order_goods_id' => $this->request->post('order_goods_id'),
  88. 'express_name' => $this->request->post('express_name'),
  89. 'express_no' => $this->request->post('express_no'),
  90. 'express_image' => $this->request->post('express_image/a', [])
  91. ];
  92. if (!$validate->scene('send')->check($params)) {
  93. $this->error($validate->getError());
  94. }
  95. $orderId = intval($params['order_id'] ?? 0);
  96. $orderGoodsId = intval($params['order_goods_id'] ?? 0);
  97. if (empty($orderId)) {
  98. $this->error('订单ID不能为空');
  99. }
  100. if (empty($orderGoodsId)) {
  101. $this->error('订单商品ID不能为空');
  102. }
  103. // 验证订单商品是否可以发货
  104. $orderData = OrderService::validateOrderGoodsForDelivery($orderId, $orderGoodsId);
  105. if (!$orderData) {
  106. $this->error('订单或订单商品不存在,或不允许发货');
  107. }
  108. $order = $orderData['order'];
  109. $orderGoods = $orderData['order_goods'];
  110. // 验证权限(根据业务需求,这里可能需要验证供应商权限而不是用户权限)
  111. if ($order->user_id != $this->auth->id) {
  112. $this->error('该订单不属于当前用户');
  113. }
  114. $expressName = trim($params['express_name'] ?? '');
  115. $expressNo = trim($params['express_no'] ?? '');
  116. $expressImage = $params['express_image'] ?? [];
  117. // 1. 更新订单商品发货状态
  118. $result = OrderService::updateOrderGoodsDeliveryStatus($orderGoodsId, $expressName, $expressNo, $expressImage);
  119. if (!$result) {
  120. $this->error('更新订单商品发货状态失败');
  121. }
  122. // 2. 检查并更新订单状态
  123. OrderService::updateOrderStatusByDeliveryResult($orderId, $userId);
  124. // 3. 记录操作日志
  125. $orderActionService = new OrderActionService();
  126. $orderActionService->addInspectionAction(
  127. $order->order_sn,
  128. OrderActionEnum::ACTION_SHIP,
  129. $userId,
  130. '订单商品发货,商品:' . $orderGoods->goods_title . ',快递公司:' . $expressName . ',快递单号:' . $expressNo,
  131. $userId,
  132. [
  133. 'order_goods_id' => $orderGoodsId,
  134. 'goods_title' => $orderGoods->goods_title,
  135. 'express_name' => $expressName,
  136. 'express_no' => $expressNo,
  137. ]
  138. );
  139. $this->success('发货成功');
  140. }
  141. // 统计订单
  142. public function statistics()
  143. {
  144. // 验证请求参数
  145. $validate = new \app\api\validate\Order();
  146. $params = [
  147. 'type' => $this->request->param('type', 'day'),
  148. 'date' => $this->request->param('date', date('Y-m-d'))
  149. ];
  150. if (!$validate->scene('statistics')->check($params)) {
  151. $this->error($validate->getError());
  152. }
  153. // 获取验证后的参数
  154. $type = $params['type'];
  155. $date = $params['date'];
  156. // 根据类型处理日期和时间范围
  157. switch ($type) {
  158. case 'day':
  159. $startTime = strtotime($date . ' 00:00:00');
  160. $endTime = strtotime($date . ' 23:59:59');
  161. $displayDate = date('m-d', $startTime);
  162. // 前一天
  163. $prevStartTime = strtotime($date . ' 00:00:00') - 86400;
  164. $prevEndTime = strtotime($date . ' 23:59:59') - 86400;
  165. break;
  166. case 'month':
  167. $startTime = strtotime(date('Y-m-01 00:00:00', strtotime($date)));
  168. $endTime = strtotime(date('Y-m-t 23:59:59', strtotime($date)));
  169. $displayDate = date('Y-m', $startTime);
  170. // 前一个月
  171. $prevStartTime = strtotime(date('Y-m-01 00:00:00', strtotime($date . ' -1 month')));
  172. $prevEndTime = strtotime(date('Y-m-t 23:59:59', strtotime($date . ' -1 month')));
  173. break;
  174. case 'year':
  175. $startTime = strtotime(date('Y-01-01 00:00:00', strtotime($date)));
  176. $endTime = strtotime(date('Y-12-31 23:59:59', strtotime($date)));
  177. $displayDate = date('Y', $startTime) . '年';
  178. // 前一年
  179. $prevStartTime = strtotime(date('Y-01-01 00:00:00', strtotime($date . ' -1 year')));
  180. $prevEndTime = strtotime(date('Y-12-31 23:59:59', strtotime($date . ' -1 year')));
  181. break;
  182. }
  183. // 获取当前用户ID
  184. $userId = $this->auth->id;
  185. // 如果需要根据工厂统计,可以在这里添加工厂相关逻辑
  186. // 目前先按用户统计,后续可以根据实际的工厂关联字段进行调整
  187. // 当前期间统计
  188. $currentStats = $this->getOrderStatistics($userId, $startTime, $endTime);
  189. // 上期统计(用于对比)
  190. $prevStats = $this->getOrderStatistics($userId, $prevStartTime, $prevEndTime);
  191. // 计算增长率
  192. $growthRate = [
  193. 'inspection_rate' => $this->calculateGrowthRate($prevStats['inspection_count'], $currentStats['inspection_count']),
  194. 'return_rate' => $this->calculateGrowthRate($prevStats['return_count'], $currentStats['return_count']),
  195. 'aftersale_rate' => $this->calculateGrowthRate($prevStats['aftersale_count'], $currentStats['aftersale_count'])
  196. ];
  197. // 返回统计数据
  198. $data = [
  199. 'date' => $displayDate,
  200. 'type' => $type,
  201. 'current_period' => $currentStats,
  202. 'previous_period' => $prevStats,
  203. 'growth_rate' => $growthRate,
  204. 'statistics' => [
  205. 'inspection_count' => $currentStats['inspection_count'],
  206. 'return_count' => $currentStats['return_count'],
  207. 'aftersale_count' => $currentStats['aftersale_count']
  208. ]
  209. ];
  210. $this->success('统计数据获取成功', $data);
  211. }
  212. /**
  213. * 获取订单统计数据
  214. */
  215. private function getOrderStatistics($userId, $startTime, $endTime)
  216. {
  217. // 统计验收订单(验货通过)
  218. $inspectionCount = \app\common\model\Order::where('user_id', $userId)
  219. ->where('order_status', OrderEnum::STATUS_INSPECTION_PASS)
  220. ->where('createtime', '>=', $startTime)
  221. ->where('createtime', '<=', $endTime)
  222. ->count();
  223. // 统计退回订单(验货不通过)
  224. $returnCount = \app\common\model\Order::where('user_id', $userId)
  225. ->where('order_status', OrderEnum::STATUS_INSPECTION_FAIL)
  226. ->where('createtime', '>=', $startTime)
  227. ->where('createtime', '<=', $endTime)
  228. ->count();
  229. // 统计待验收订单
  230. $aftersaleCount = \app\common\model\Order::where('user_id', $userId)
  231. ->whereIn('order_status', [OrderEnum::STATUS_PAY])
  232. ->where('createtime', '>=', $startTime)
  233. ->where('createtime', '<=', $endTime)
  234. ->count();
  235. return [
  236. 'inspection_count' => $inspectionCount,
  237. 'return_count' => $returnCount,
  238. 'aftersale_count' => $aftersaleCount
  239. ];
  240. }
  241. /**
  242. * 计算增长率
  243. */
  244. private function calculateGrowthRate($prevValue, $currentValue)
  245. {
  246. if ($prevValue == 0) {
  247. return $currentValue > 0 ? 100 : 0;
  248. }
  249. return round((($currentValue - $prevValue) / $prevValue) * 100, 2);
  250. }
  251. /**
  252. * 获取统计数据的时间范围选择
  253. */
  254. public function getStatisticsDateRange()
  255. {
  256. // 获取最早和最晚的订单时间
  257. $userId = $this->auth->id;
  258. $earliest = \app\common\model\Order::where('user_id', $userId)
  259. ->order('createtime', 'asc')
  260. ->value('createtime');
  261. $latest = \app\common\model\Order::where('user_id', $userId)
  262. ->order('createtime', 'desc')
  263. ->value('createtime');
  264. $data = [
  265. 'earliest_date' => $earliest ? date('Y-m-d', $earliest) : date('Y-m-d'),
  266. 'latest_date' => $latest ? date('Y-m-d', $latest) : date('Y-m-d'),
  267. 'current_date' => date('Y-m-d'),
  268. 'current_month' => date('Y-m'),
  269. 'current_year' => date('Y')
  270. ];
  271. $this->success('日期范围获取成功', $data);
  272. }
  273. /**
  274. * 获取历史趋势数据
  275. */
  276. public function getTrendData()
  277. {
  278. // 验证请求参数
  279. $validate = new \app\api\validate\Order();
  280. $params = [
  281. 'type' => $this->request->param('type', 'day'),
  282. 'days' => $this->request->param('days', 7)
  283. ];
  284. if (!$validate->scene('trend')->check($params)) {
  285. $this->error($validate->getError());
  286. }
  287. // 获取验证后的参数
  288. $type = $params['type'];
  289. $days = $params['days'];
  290. $userId = $this->auth->id;
  291. $trendData = [];
  292. for ($i = $days - 1; $i >= 0; $i--) {
  293. $date = date('Y-m-d', strtotime("-{$i} days"));
  294. $startTime = strtotime($date . ' 00:00:00');
  295. $endTime = strtotime($date . ' 23:59:59');
  296. $stats = $this->getOrderStatistics($userId, $startTime, $endTime);
  297. $trendData[] = [
  298. 'date' => $date,
  299. 'display_date' => date('m-d', $startTime),
  300. 'inspection_count' => $stats['inspection_count'],
  301. 'return_count' => $stats['return_count'],
  302. 'aftersale_count' => $stats['aftersale_count']
  303. ];
  304. }
  305. $this->success('趋势数据获取成功', $trendData);
  306. }
  307. // 获取快递公司列表
  308. public function getExpressCompany(){
  309. $list = OrderShipService::getExpressCompany();
  310. $this->success('快递公司列表获取成功', $list);
  311. }
  312. }