Order.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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\Enum\OrderEnum;
  14. use app\common\Service\CartService;
  15. /**
  16. * 订单接口
  17. */
  18. class Order extends Base
  19. {
  20. protected $noNeedLogin = [];
  21. public function __construct()
  22. {
  23. parent::__construct();
  24. }
  25. //计算邮费,判断商品 - 支持购物车和商品规格两种模式
  26. public function calculate()
  27. {
  28. // 验证请求参数
  29. $validate = new \app\api\validate\Order();
  30. $postData = $this->request->post();
  31. $postData['calculate_data'] = '1'; // 添加触发自定义验证的字段
  32. if (!$validate->scene('calculate')->check($postData)) {
  33. $this->error($validate->getError());
  34. }
  35. $userId = $this->auth->id;
  36. $config = get_addon_config('shop');
  37. $address_id = $postData['address_id'] ?? 0; // 地址id
  38. $user_coupon_id = $postData['user_coupon_id'] ?? 0; // 优惠券
  39. $cart_ids = $postData['cart_ids'] ?? []; // 购物车ID数组
  40. $goods_list = $postData['goods_list'] ?? []; // 商品列表
  41. $address = Address::get($address_id);
  42. $area_id = !empty($address) ? $address->area_id : 0;
  43. try {
  44. // 自动判断数据源类型并获取标准化的商品列表
  45. if (!empty($cart_ids) && !empty($goods_list)) {
  46. // 结算页有加减数量,需同步更新购物车
  47. CartService::updateCartByGoodsList($cart_ids, $goods_list, $userId);
  48. // goods_list 直接参与后续计算
  49. } elseif (!empty($cart_ids)) {
  50. $goods_list = CartService::convertCartToGoodsList($cart_ids, $userId);
  51. } elseif (empty($goods_list)) {
  52. throw new \Exception("请提供购物车ID或商品列表");
  53. }
  54. // 统一调用计算方法
  55. $result = OrderService::calculateOrder($goods_list, $userId, $area_id, $user_coupon_id);
  56. $orderItem = $result['orderItem'];
  57. $goodsList = $result['goodsList'];
  58. $orderInfo = $result['orderInfo'];
  59. $userCoupon = $result['userCoupon'];
  60. if (empty($goodsList)) {
  61. throw new \Exception("未找到商品");
  62. }
  63. } catch (\Exception $e) {
  64. $this->error($e->getMessage());
  65. }
  66. // 处理商品数据
  67. foreach ($goodsList as $item) {
  68. //$item->category_id = $item->goods->category_id;
  69. $item->brand_id = $item->goods->brand_id;
  70. $item->goods->visible(explode(',', 'id,title,image,price,marketprice'));
  71. }
  72. // 获取我的可以使用的优惠券
  73. $goods_ids = array_column($goodsList, 'goods_id');
  74. $category_ids = array_column($goodsList, 'category_id');
  75. $brand_ids = array_column($goodsList, 'brand_id');
  76. $this->success('获取成功', [
  77. 'coupons' => UserCoupon::myGoodsCoupon($userId, $goods_ids, $category_ids, $brand_ids),
  78. 'goods_list' => $goodsList,
  79. 'order_info' => $orderInfo,
  80. ]);
  81. }
  82. /**
  83. * 提交订单 - 统一接口
  84. */
  85. public function create()
  86. {
  87. // 验证请求参数
  88. $validate = new \app\api\validate\Order();
  89. if (!$validate->scene('create')->check($this->request->post())) {
  90. $this->error($validate->getError());
  91. }
  92. $address_id = $this->request->post('address_id/d'); // 地址id
  93. $user_coupon_id = $this->request->post('user_coupon_id/d'); // 优惠券id
  94. $remark = $this->request->post('remark','','trim'); // 备注
  95. $cart_ids = $this->request->post('cart_ids/a'); // 购物车ID数组
  96. $goods_list = $this->request->post('goods_list/a'); // 商品列表
  97. $userId = $this->auth->id;
  98. $order = null;
  99. try {
  100. if (!empty($cart_ids)) {
  101. // 购物车模式 - 校验购物车id合法性
  102. $row = (new Carts)->where('id', 'IN', $cart_ids)->where('user_id', '<>', $this->auth->id)->find();
  103. if ($row) {
  104. $this->error('存在不合法购物车数据');
  105. }
  106. // 先转换购物车为商品列表
  107. $goods_list = CartService::convertCartToGoodsList($cart_ids, $userId);
  108. // 创建订单
  109. $order = OrderService::createOrder($address_id, $userId, $goods_list, $user_coupon_id, $remark);
  110. // 购物车订单创建成功后清理购物车
  111. CartService::clear($cart_ids,$userId);
  112. } elseif (!empty($goods_list)) {
  113. // 商品列表模式 - 直接创建订单
  114. $order = OrderService::createOrder($address_id, $userId, $goods_list, $user_coupon_id, $remark);
  115. } else {
  116. $this->error('请提供购物车ID或商品列表');
  117. }
  118. } catch (\Exception $e) {
  119. $this->error($e->getMessage());
  120. }
  121. $this->success('下单成功!', array_intersect_key($order->toArray(), array_flip(['order_sn', 'id', 'order_status'])));
  122. }
  123. //订单详情
  124. public function detail()
  125. {
  126. // 验证请求参数
  127. $validate = new \app\api\validate\Order();
  128. $orderId = $this->request->get('orderId');
  129. $params = ['orderId' => $orderId];
  130. if (!$validate->scene('detail')->check($params)) {
  131. $this->error($validate->getError());
  132. }
  133. $order = OrderService::getDetail($orderId, $this->auth->id);
  134. if (empty($order)) {
  135. $this->error('未找到订单');
  136. }
  137. //$order->append(['order_status_text']);
  138. $address = OrderService::getAddressInfo($orderId);
  139. $order->address = $address;
  140. // $order->append(['status_text']);
  141. // $order->hidden(explode(',', 'method,transactionid,updatetime,deletetime'));
  142. // $order->expiretime = $order->expiretime - time();
  143. $order->order_status_text = OrderEnum::STATUS_TEXT_MAP[$order->order_status];
  144. // 处理商品的 发货信息
  145. foreach ($order->order_goods as $item) {
  146. $item->express_image = json_decode($item->express_image, true);
  147. }
  148. $this->success('', $order);
  149. }
  150. //订单列表
  151. public function index()
  152. {
  153. // 验证请求参数
  154. $validate = new \app\api\validate\Order();
  155. $param = $this->request->param();
  156. $param['time_range'] = '1'; // 添加触发时间范围验证的字段
  157. if (!$validate->scene('lists')->check($param)) {
  158. $this->error($validate->getError());
  159. }
  160. // 设置默认值
  161. $userId = $this->auth->id;
  162. $param['page'] = $this->request->param('page', 1, 'intval');
  163. $param['pageSize'] = $this->request->param('pageSize', 10, 'intval');
  164. $status = $this->request->param('status', 0, 'intval'); // 默认为0(全部订单)
  165. $param['keywords'] = $this->request->param('keywords', '', 'trim');
  166. $status = OrderEnum::SHOW_TYPE_STATUS_MAP[$status];
  167. $list = OrderService::getOrderList($userId ,$param, $status);
  168. foreach ($list as $item) {
  169. // $item->append(['order_status_text']);
  170. $field = 'id,order_sn,amount,goods_price,order_amount,express_name,express_no,order_goods,order_status_text,order_status';
  171. $item->visible(explode(',', $field));
  172. $item->order_status_text = OrderEnum::STATUS_TEXT_MAP[$item->order_status];
  173. }
  174. $this->success('获取成功', $list);
  175. }
  176. //取消订单
  177. public function cancel()
  178. {
  179. // 验证请求参数
  180. $validate = new \app\api\validate\Order();
  181. $orderId = $this->request->post('orderId');
  182. $params = ['orderId' => $orderId];
  183. if (!$validate->scene('cancel')->check($params)) {
  184. $this->error($validate->getError());
  185. }
  186. $order = OrderService::getByOrderId($orderId);
  187. if (empty($order)) {
  188. $this->error('订单不存在');
  189. }
  190. if ($order->user_id != $this->auth->id) {
  191. $this->error('不能越权操作');
  192. }
  193. if ($order->status == 'hidden') {
  194. $this->error('订单已失效!');
  195. }
  196. //可以取消
  197. if ($order->canCancelHandle()) {
  198. // 启动事务
  199. Db::startTrans();
  200. try {
  201. $order->order_status = OrderEnum::STATUS_CANCEL;
  202. $order->cancel_time = time();
  203. $order->save();
  204. foreach ($order->order_goods as $item) {
  205. $sku = $item->sku;
  206. $goods = $item->goods;
  207. //商品库存恢复
  208. if ($sku) {
  209. $sku->setInc('stocks', $item->nums);
  210. }
  211. if ($goods) {
  212. $goods->setInc('stocks', $item->nums);
  213. }
  214. }
  215. //恢复优惠券
  216. UserCoupon::resetUserCoupon($order->user_coupon_id, $order->order_sn);
  217. // 提交事务
  218. Db::commit();
  219. } catch (\Exception $e) {
  220. // 回滚事务
  221. Db::rollback();
  222. $this->error('订单取消失败');
  223. }
  224. //记录操作
  225. OrderAction::push($order->order_sn, '系统', '订单取消成功');
  226. $this->success('订单取消成功!', $order['status']);
  227. } else {
  228. $this->error('订单不允许取消');
  229. }
  230. }
  231. //确认收货
  232. public function receipt()
  233. {
  234. // 验证请求参数
  235. $validate = new \app\api\validate\Order();
  236. $orderId = $this->request->post('orderId');
  237. $params = ['orderId' => $orderId];
  238. if (!$validate->scene('detail')->check($params)) {
  239. $this->error($validate->getError());
  240. }
  241. $order = OrderService::getByOrderId($orderId);
  242. if (empty($order)) {
  243. $this->error('订单不存在');
  244. }
  245. if ($order->user_id != $this->auth->id) {
  246. $this->error('该订单不属于当前用户');
  247. }
  248. if ($order->canConfirmHandle()) {
  249. $order->order_status = OrderEnum::STATUS_CONFIRM;
  250. $order->receive_time = time();
  251. $order->save();
  252. //记录操作
  253. OrderAction::push($order->order_sn, '系统', '订单确认收货成功');
  254. $this->success('确认收货成功');
  255. }
  256. $this->error('订单不允许确认收货');
  257. }
  258. //查询物流
  259. public function logistics()
  260. {
  261. // 验证请求参数
  262. $validate = new \app\api\validate\Order();
  263. $params = ['order_sn' => $this->request->param('order_sn')];
  264. if (!$validate->scene('detail')->check($params)) {
  265. $this->error($validate->getError());
  266. }
  267. $order_sn = $this->request->param('order_sn');
  268. $order = OrderModel::getDetail($order_sn, $this->auth->id);
  269. if (empty($order)) {
  270. $this->error('未找到订单');
  271. }
  272. if (!$order->shippingstate) {
  273. $this->error('订单未发货');
  274. }
  275. $electronics = Db::name('shop_order_electronics')->where('order_sn', $order_sn)->where('status', 0)->find();
  276. if (!$electronics) {
  277. $this->error('订单未发货');
  278. }
  279. $result = KdApiExpOrder::getLogisticsQuery([
  280. 'order_sn' => $order_sn,
  281. 'logistic_code' => $electronics['logistic_code'],
  282. 'shipper_code' => $electronics['shipper_code']
  283. ]);
  284. if ($result['Success']) {
  285. $this->success('查询成功', $result['Traces']);
  286. }
  287. $this->error('查询失败');
  288. }
  289. // 获取状态订单统计
  290. public function getOrderStatusCount(){
  291. $userId = $this->auth->id;
  292. $info = OrderService::getOrderStatusCount($userId);
  293. $this->success('获取成功', $info);
  294. }
  295. }