Order.php 20 KB

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