Order.php 20 KB

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