Order.php 21 KB

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