Order.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\model\UserCoupon;
  4. use app\common\model\Carts;
  5. use app\common\model\Order as OrderModel;
  6. use app\common\model\Address;
  7. use app\common\model\Third;
  8. use app\common\model\OrderAction;
  9. use app\common\model\OrderGoods;
  10. use app\common\library\KdApiExpOrder;
  11. use think\Db;
  12. use app\common\Service\OrderService;
  13. use app\common\Service\ParentOrderService;
  14. use app\common\Enum\OrderEnum;
  15. use app\common\Service\CartService;
  16. use app\common\Service\Pay\PayOperService;
  17. /**
  18. * 订单接口
  19. */
  20. class Order extends Base
  21. {
  22. protected $noNeedLogin = [];
  23. public function __construct()
  24. {
  25. parent::__construct();
  26. }
  27. //计算邮费,判断商品 - 支持购物车和商品规格两种模式
  28. public function calculate()
  29. {
  30. // 验证请求参数
  31. $validate = new \app\api\validate\Order();
  32. $postData = $this->request->post();
  33. $postData['calculate_data'] = '1'; // 添加触发自定义验证的字段
  34. if (!$validate->scene('calculate')->check($postData)) {
  35. $this->error($validate->getError());
  36. }
  37. $userId = $this->auth->id;
  38. $config = get_addon_config('shop');
  39. $address_id = $postData['address_id'] ?? 0; // 地址id
  40. $user_coupon_id = $postData['user_coupon_id'] ?? 0; // 优惠券
  41. $cart_ids = $postData['cart_ids'] ?? []; // 购物车ID数组
  42. $goods_list = $postData['goods_list'] ?? []; // 商品列表
  43. $address = Address::get($address_id);
  44. $area_id = !empty($address) ? $address->area_id : 0;
  45. try {
  46. // 自动判断数据源类型并获取标准化的商品列表
  47. if (!empty($cart_ids) && !empty($goods_list)) {
  48. // 结算页有加减数量,需同步更新购物车
  49. CartService::updateCartByGoodsList($cart_ids, $goods_list, $userId);
  50. // goods_list 直接参与后续计算
  51. } elseif (!empty($cart_ids)) {
  52. $goods_list = CartService::convertCartToGoodsList($cart_ids, $userId);
  53. } elseif (empty($goods_list)) {
  54. throw new \Exception("请提供购物车ID或商品列表");
  55. }
  56. // 统一调用计算方法
  57. $result = OrderService::calculateOrder($goods_list, $userId, $area_id, $user_coupon_id);
  58. $orderItem = $result['orderItem'];
  59. $goodsList = $result['goodsList'];
  60. $orderInfo = $result['orderInfo'];
  61. $userCoupon = $result['userCoupon'];
  62. if (empty($goodsList)) {
  63. throw new \Exception("未找到商品");
  64. }
  65. } catch (\Exception $e) {
  66. $this->error($e->getMessage());
  67. }
  68. // 处理商品数据
  69. foreach ($goodsList as $item) {
  70. //$item->category_id = $item->goods->category_id;
  71. $item->brand_id = $item->goods->brand_id;
  72. $item->goods->visible(explode(',', 'id,title,image,price,marketprice'));
  73. }
  74. // 获取我的可以使用的优惠券
  75. $goods_ids = array_column($goodsList, 'goods_id');
  76. $category_ids = array_column($goodsList, 'category_id');
  77. $brand_ids = array_column($goodsList, 'brand_id');
  78. $this->success('获取成功', [
  79. 'coupons' => UserCoupon::myGoodsCoupon($userId, $goods_ids, $category_ids, $brand_ids),
  80. 'goods_list' => $goodsList,
  81. 'order_info' => $orderInfo,
  82. ]);
  83. }
  84. /**
  85. * 提交订单 - 统一接口
  86. */
  87. public function create()
  88. {
  89. // 验证请求参数
  90. $validate = new \app\api\validate\Order();
  91. if (!$validate->scene('create')->check($this->request->post())) {
  92. $this->error($validate->getError());
  93. }
  94. $address_id = $this->request->post('address_id/d'); // 地址id
  95. $user_coupon_id = $this->request->post('user_coupon_id/d'); // 优惠券id
  96. $remark = $this->request->post('remark','','trim'); // 备注
  97. $cart_ids = $this->request->post('cart_ids/a'); // 购物车ID数组
  98. $goods_list = $this->request->post('goods_list/a'); // 商品列表
  99. $userId = $this->auth->id;
  100. $order = null;
  101. try {
  102. if (!empty($cart_ids)) {
  103. // 购物车模式 - 校验购物车id合法性
  104. $row = (new Carts)->where('id', 'IN', $cart_ids)->where('user_id', '<>', $this->auth->id)->find();
  105. if ($row) {
  106. $this->error('存在不合法购物车数据');
  107. }
  108. // 先转换购物车为商品列表
  109. $goods_list = CartService::convertCartToGoodsList($cart_ids, $userId);
  110. // 创建订单
  111. $order = OrderService::createOrder($address_id, $userId, $goods_list, $user_coupon_id, $remark);
  112. // 购物车订单创建成功后清理购物车
  113. CartService::clear($cart_ids,$userId);
  114. } elseif (!empty($goods_list)) {
  115. // 商品列表模式 - 直接创建订单
  116. $order = OrderService::createOrder($address_id, $userId, $goods_list, $user_coupon_id, $remark);
  117. } else {
  118. $this->error('请提供购物车ID或商品列表');
  119. }
  120. } catch (\Exception $e) {
  121. $this->error($e->getMessage());
  122. }
  123. $this->success('下单成功!', array_intersect_key($order->toArray(), array_flip(['order_sn', 'id', 'order_status'])));
  124. }
  125. /**
  126. * 创建单商品订单 - 一个商品一个订单
  127. */
  128. public function createSingleGoods()
  129. {
  130. // 验证请求参数
  131. $validate = new \app\api\validate\Order();
  132. if (!$validate->scene('create')->check($this->request->post())) {
  133. $this->error($validate->getError());
  134. }
  135. $address_id = $this->request->post('address_id/d'); // 地址id
  136. $user_coupon_id = $this->request->post('user_coupon_id/d'); // 优惠券id(仅用于第一个订单)
  137. $remark = $this->request->post('remark','','trim'); // 备注
  138. $cart_ids = $this->request->post('cart_ids/a'); // 购物车ID数组
  139. $goods_list = $this->request->post('goods_list/a'); // 商品列表
  140. $userId = $this->auth->id;
  141. $orders = [];
  142. try {
  143. if (!empty($cart_ids)) {
  144. // 购物车模式 - 校验购物车id合法性
  145. $row = (new Carts)->where('id', 'IN', $cart_ids)->where('user_id', '<>', $this->auth->id)->find();
  146. if ($row) {
  147. $this->error('存在不合法购物车数据');
  148. }
  149. // 先转换购物车为商品列表
  150. $goods_list = CartService::convertCartToGoodsList($cart_ids, $userId);
  151. // 创建单商品订单
  152. $orders = OrderService::createSingleGoodsOrders($address_id, $userId, $goods_list, $user_coupon_id, $remark);
  153. // 购物车订单创建成功后清理购物车
  154. CartService::clear($cart_ids, $userId);
  155. } elseif (!empty($goods_list)) {
  156. // 商品列表模式 - 直接创建单商品订单
  157. $orders = OrderService::createSingleGoodsOrders($address_id, $userId, $goods_list, $user_coupon_id, $remark);
  158. } else {
  159. $this->error('请提供购物车ID或商品列表');
  160. }
  161. } catch (\Exception $e) {
  162. $this->error($e->getMessage());
  163. }
  164. // 格式化返回数据
  165. $orderResults = [];
  166. foreach ($orders as $order) {
  167. $orderResults[] = array_intersect_key($order->toArray(), array_flip(['order_sn', 'id', 'order_status']));
  168. }
  169. $this->success('下单成功!共创建 ' . count($orders) . ' 个订单', [
  170. 'order_count' => count($orders),
  171. 'orders' => $orderResults
  172. ]);
  173. }
  174. /**
  175. * 创建父子订单 - 每个商品一个子订单,统一支付父订单
  176. */
  177. public function createParentChild()
  178. {
  179. // 验证请求参数
  180. $validate = new \app\api\validate\Order();
  181. if (!$validate->scene('create')->check($this->request->post())) {
  182. $this->error($validate->getError());
  183. }
  184. $address_id = $this->request->post('address_id/d'); // 地址id
  185. $user_coupon_id = $this->request->post('user_coupon_id/d'); // 优惠券id
  186. $remark = $this->request->post('remark','','trim'); // 备注
  187. $cart_ids = $this->request->post('cart_ids/a'); // 购物车ID数组
  188. $goods_list = $this->request->post('goods_list/a'); // 商品列表
  189. $userId = $this->auth->id;
  190. $parentOrder = null;
  191. try {
  192. if (!empty($cart_ids)) {
  193. // 购物车模式 - 校验购物车id合法性
  194. $row = (new Carts)->where('id', 'IN', $cart_ids)->where('user_id', '<>', $this->auth->id)->find();
  195. if ($row) {
  196. $this->error('存在不合法购物车数据');
  197. }
  198. // 先转换购物车为商品列表
  199. $goods_list = CartService::convertCartToGoodsList($cart_ids, $userId);
  200. // 创建父子订单
  201. $parentOrder = ParentOrderService::createParentChildOrders($address_id, $userId, $goods_list, $user_coupon_id, $remark);
  202. // 购物车订单创建成功后清理购物车
  203. CartService::clear($cart_ids, $userId);
  204. } elseif (!empty($goods_list)) {
  205. // 商品列表模式 - 直接创建父子订单
  206. $parentOrder = ParentOrderService::createParentChildOrders($address_id, $userId, $goods_list, $user_coupon_id, $remark);
  207. } else {
  208. $this->error('请提供购物车ID或商品列表');
  209. }
  210. } catch (\Exception $e) {
  211. $this->error($e->getMessage());
  212. }
  213. // 获取子订单信息
  214. $childOrders = [];
  215. foreach ($parentOrder->childOrders as $childOrder) {
  216. $childOrders[] = [
  217. 'order_sn' => $childOrder->order_sn,
  218. 'id' => $childOrder->id,
  219. 'order_status' => $childOrder->order_status,
  220. 'amount' => $childOrder->amount,
  221. 'goods_price' => $childOrder->goods_price,
  222. 'express_fee' => $childOrder->express_fee
  223. ];
  224. }
  225. $this->success('父子订单创建成功!', [
  226. 'parent_order' => [
  227. 'parent_order_sn' => $parentOrder->parent_order_sn,
  228. 'id' => $parentOrder->id,
  229. 'order_status' => $parentOrder->order_status,
  230. 'pay_status' => $parentOrder->pay_status,
  231. 'total_amount' => $parentOrder->total_amount,
  232. 'pay_amount' => $parentOrder->pay_amount,
  233. 'child_order_count' => count($childOrders)
  234. ],
  235. 'child_orders' => $childOrders
  236. ]);
  237. }
  238. //订单详情
  239. public function detail()
  240. {
  241. // 验证请求参数
  242. $validate = new \app\api\validate\Order();
  243. $orderId = $this->request->get('orderId');
  244. $params = ['orderId' => $orderId];
  245. if (!$validate->scene('detail')->check($params)) {
  246. $this->error($validate->getError());
  247. }
  248. $order = OrderService::getDetail($orderId, $this->auth->id);
  249. if (empty($order)) {
  250. $this->error('未找到订单');
  251. }
  252. //$order->append(['order_status_text']);
  253. $address = OrderService::getAddressInfo($orderId);
  254. $order->address = $address;
  255. // $order->append(['status_text']);
  256. // $order->hidden(explode(',', 'method,transactionid,updatetime,deletetime'));
  257. // $order->expiretime = $order->expiretime - time();
  258. $order->order_status_text = OrderEnum::STATUS_TEXT_MAP[$order->order_status];
  259. // 处理商品的 发货信息
  260. foreach ($order->order_goods as $item) {
  261. $item->express_image = json_decode($item->express_image, true);
  262. }
  263. // 查询支付信息
  264. $payInfo = PayOperService::getPayInfoByOrderId($orderId, 1);
  265. $order->pay_info = $payInfo;
  266. $this->success('', $order);
  267. }
  268. //订单列表
  269. public function index()
  270. {
  271. // 验证请求参数
  272. $validate = new \app\api\validate\Order();
  273. $param = $this->request->param();
  274. $param['time_range'] = '1'; // 添加触发时间范围验证的字段
  275. if (!$validate->scene('lists')->check($param)) {
  276. $this->error($validate->getError());
  277. }
  278. // 设置默认值
  279. $userId = $this->auth->id;
  280. $param['page'] = $this->request->param('page', 1, 'intval');
  281. $param['pageSize'] = $this->request->param('pageSize', 10, 'intval');
  282. $status = $this->request->param('status', 0, 'intval'); // 默认为0(全部订单)
  283. $param['keywords'] = $this->request->param('keywords', '', 'trim');
  284. $status = OrderEnum::SHOW_TYPE_STATUS_MAP[$status];
  285. $list = OrderService::getOrderList($userId ,$param, $status);
  286. // 查询支付信息
  287. $orderIds = $list->column('id');
  288. $payInfo = PayOperService::getPayInfoByOrderIds($orderIds, 1);
  289. // 形成kv
  290. $payInfoKV = [];
  291. foreach ($payInfo as $item) {
  292. $payInfoKV[$item->order_id] = $item;
  293. }
  294. $list->each(function($row) use ($payInfoKV) {
  295. $row->pay_info = $payInfoKV[$row->id] ?? [];
  296. });
  297. foreach ($list as $item) {
  298. // $item->append(['order_status_text']);
  299. $field = 'id,order_sn,amount,goods_price,order_amount,express_name,express_no,order_goods,order_status_text,order_status,pay_info';
  300. $item->visible(explode(',', $field));
  301. $item->order_status_text = OrderEnum::STATUS_TEXT_MAP[$item->order_status];
  302. }
  303. $this->success('获取成功', $list);
  304. }
  305. //取消订单
  306. public function cancel()
  307. {
  308. // 验证请求参数
  309. $validate = new \app\api\validate\Order();
  310. $orderId = $this->request->post('orderId');
  311. $params = ['orderId' => $orderId];
  312. if (!$validate->scene('cancel')->check($params)) {
  313. $this->error($validate->getError());
  314. }
  315. $order = OrderService::getByOrderId($orderId);
  316. if (empty($order)) {
  317. $this->error('订单不存在');
  318. }
  319. if ($order->user_id != $this->auth->id) {
  320. $this->error('不能越权操作');
  321. }
  322. if ($order->status == 'hidden') {
  323. $this->error('订单已失效!');
  324. }
  325. //可以取消
  326. if ($order->canCancelHandle()) {
  327. // 启动事务
  328. Db::startTrans();
  329. try {
  330. $order->order_status = OrderEnum::STATUS_CANCEL;
  331. $order->cancel_time = time();
  332. $order->save();
  333. foreach ($order->order_goods as $item) {
  334. $sku = $item->sku;
  335. $goods = $item->goods;
  336. //商品库存恢复
  337. if ($sku) {
  338. $sku->setInc('stocks', $item->nums);
  339. }
  340. if ($goods) {
  341. $goods->setInc('stocks', $item->nums);
  342. }
  343. }
  344. //恢复优惠券
  345. UserCoupon::resetUserCoupon($order->user_coupon_id, $order->order_sn);
  346. // 提交事务
  347. Db::commit();
  348. } catch (\Exception $e) {
  349. // 回滚事务
  350. Db::rollback();
  351. $this->error('订单取消失败');
  352. }
  353. //记录操作
  354. OrderAction::push($order->order_sn, '系统', '订单取消成功');
  355. $this->success('订单取消成功!', $order['status']);
  356. } else {
  357. $this->error('订单不允许取消');
  358. }
  359. }
  360. //确认收货
  361. public function receipt()
  362. {
  363. // 验证请求参数
  364. $validate = new \app\api\validate\Order();
  365. $orderId = $this->request->post('orderId');
  366. $params = ['orderId' => $orderId];
  367. if (!$validate->scene('detail')->check($params)) {
  368. $this->error($validate->getError());
  369. }
  370. $order = OrderService::getByOrderId($orderId);
  371. if (empty($order)) {
  372. $this->error('订单不存在');
  373. }
  374. if ($order->user_id != $this->auth->id) {
  375. $this->error('该订单不属于当前用户');
  376. }
  377. if ($order->canConfirmHandle()) {
  378. $order->order_status = OrderEnum::STATUS_CONFIRM;
  379. $order->receive_time = time();
  380. $order->save();
  381. //记录操作
  382. OrderAction::push($order->order_sn, '系统', '订单确认收货成功');
  383. $this->success('确认收货成功');
  384. }
  385. $this->error('订单不允许确认收货');
  386. }
  387. //查询物流
  388. public function logistics()
  389. {
  390. // 验证请求参数
  391. $validate = new \app\api\validate\Order();
  392. $params = ['order_sn' => $this->request->param('order_sn')];
  393. if (!$validate->scene('detail')->check($params)) {
  394. $this->error($validate->getError());
  395. }
  396. $order_sn = $this->request->param('order_sn');
  397. $order = OrderModel::getDetail($order_sn, $this->auth->id);
  398. if (empty($order)) {
  399. $this->error('未找到订单');
  400. }
  401. if (!$order->shippingstate) {
  402. $this->error('订单未发货');
  403. }
  404. $electronics = Db::name('shop_order_electronics')->where('order_sn', $order_sn)->where('status', 0)->find();
  405. if (!$electronics) {
  406. $this->error('订单未发货');
  407. }
  408. $result = KdApiExpOrder::getLogisticsQuery([
  409. 'order_sn' => $order_sn,
  410. 'logistic_code' => $electronics['logistic_code'],
  411. 'shipper_code' => $electronics['shipper_code']
  412. ]);
  413. if ($result['Success']) {
  414. $this->success('查询成功', $result['Traces']);
  415. }
  416. $this->error('查询失败');
  417. }
  418. // 获取状态订单统计
  419. public function getOrderStatusCount(){
  420. $userId = $this->auth->id;
  421. $info = OrderService::getOrderStatusCount($userId);
  422. $this->success('获取成功', $info);
  423. }
  424. public function getWechatMiniProgramOrderDelivery(){
  425. $orderId = $this->request->post('order_id');
  426. if(empty($orderId )){
  427. $this->error('请上传正确的参数');
  428. }
  429. $arrReturn = [];
  430. $arrReturn['errcode'] = 0;
  431. $arrReturn['order_state'] = 3;
  432. $this->success('获取成功', $arrReturn);
  433. }
  434. }