Order.php 20 KB

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