Order.php 21 KB

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