Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

630 rader
22 KiB

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: zhengmingwei
  5. * Date: 2019/11/9
  6. * Time: 10:00 下午
  7. */
  8. namespace addons\unishop\controller;
  9. use addons\unishop\extend\Hashids;
  10. use addons\unishop\model\Area;
  11. use addons\unishop\model\Config;
  12. use addons\unishop\model\Evaluate;
  13. use addons\unishop\model\Product;
  14. use app\admin\model\unishop\Coupon as CouponModel;
  15. use addons\unishop\model\DeliveryRule as DeliveryRuleModel;
  16. use addons\unishop\model\OrderRefund;
  17. use app\admin\model\unishop\OrderRefundProduct;
  18. use think\Db;
  19. use think\Exception;
  20. use addons\unishop\model\Address as AddressModel;
  21. use think\Hook;
  22. use think\Loader;
  23. /**
  24. * 订单相关接口
  25. * Class Order
  26. * @package addons\unishop\controller
  27. */
  28. class Order extends Base
  29. {
  30. /**
  31. * 允许频繁访问的接口
  32. * @var array
  33. */
  34. protected $frequently = ['getorders'];
  35. protected $noNeedLogin = ['count','create','submit'];
  36. /**
  37. * 创建订单
  38. */
  39. public function create()
  40. {
  41. $productId = $this->request->post('id', 0);
  42. try {
  43. // $user_id = $this->auth->id;
  44. $user_id = 1;
  45. // 单个商品
  46. if ($productId) {
  47. $productId = \addons\unishop\extend\Hashids::decodeHex($productId);
  48. $product = (new Product)->where(['id' => $productId, 'switch' => Product::SWITCH_ON, 'deletetime' => null])->find();
  49. /** 产品基础数据 **/
  50. $spec = $this->request->post('spec', '');
  51. $productData[0] = $product->getDataOnCreateOrder($spec);
  52. } else {
  53. // 多个商品
  54. $cart = $this->request->post('cart');
  55. $carts = (new \addons\unishop\model\Cart)
  56. ->whereIn('id', $cart)
  57. ->with(['product'])
  58. ->order(['id' => 'desc'])
  59. ->select();
  60. foreach ($carts as $cart) {
  61. if ($cart->product instanceof Product) {
  62. $productData[] = $cart->product->getDataOnCreateOrder($cart->spec ? $cart->spec : '', $cart->number);
  63. }
  64. }
  65. }
  66. if (empty($productData) || !$productData) {
  67. $this->error(__('Product not exist'));
  68. }
  69. /** 默认地址 **/
  70. $address = (new AddressModel)->where(['user_id' => $user_id, 'is_default' => AddressModel::IS_DEFAULT_YES])->find();
  71. if ($address) {
  72. $area = (new Area)->whereIn('id', [$address->province_id, $address->city_id, $address->area_id])->column('name', 'id');
  73. $address = $address->toArray();
  74. $address['province']['name'] = $area[$address['province_id']];
  75. $address['city']['name'] = $area[$address['city_id']];
  76. $address['area']['name'] = $area[$address['area_id']];
  77. }
  78. /** 可用优惠券 **/
  79. $coupon = CouponModel::all(function ($query) {
  80. $time = time();
  81. $query
  82. ->where(['switch' => CouponModel::SWITCH_ON])
  83. ->where('starttime', '<', $time)
  84. ->where('endtime', '>', $time);
  85. });
  86. if ($coupon) {
  87. $coupon = collection($coupon)->toArray();
  88. }
  89. /** 运费数据 **/
  90. $cityId = $address['city_id'] ? $address['city_id'] : 0;
  91. $delivery = (new DeliveryRuleModel())->getDelivetyByArea($cityId);
  92. foreach ($productData as &$product) {
  93. $product['image'] = Config::getImagesFullUrl($product['image']);
  94. $product['sales_price'] = number_format($product['sales_price'], 2);
  95. $product['market_price'] = number_format($product['market_price'], 2);
  96. }
  97. $this->success('', [
  98. 'product' => $productData,
  99. 'address' => $address,
  100. 'coupon' => $coupon,
  101. 'delivery' => $delivery['list']
  102. ]);
  103. } catch (Exception $e) {
  104. $this->error($e->getMessage(), false);
  105. }
  106. }
  107. /**
  108. * 提交订单
  109. */
  110. public function submit()
  111. {
  112. $data = $this->request->post();
  113. try {
  114. $validate = Loader::validate('\\addons\\unishop\\validate\\Order');
  115. if (!$validate->check($data, [], 'submit')) {
  116. throw new Exception($validate->getError());
  117. }
  118. Db::startTrans();
  119. // 判断创建订单的条件
  120. if (empty(Hook::get('create_order_before'))) {
  121. Hook::add('create_order_before', 'addons\\unishop\\behavior\\Order');
  122. }
  123. // 减少商品库存,增加"已下单未支付数量"
  124. if (empty(Hook::get('create_order_after'))) {
  125. Hook::add('create_order_after', 'addons\\unishop\\behavior\\Order');
  126. }
  127. $orderModel = new \addons\unishop\model\Order();
  128. $result = $orderModel->createOrder(1, $data);
  129. Db::commit();
  130. $this->success('', $result);
  131. } catch (Exception $e) {
  132. Db::rollback();
  133. $this->error($e->getMessage(), false);
  134. }
  135. }
  136. /**
  137. * 获取运费模板
  138. */
  139. public function getDelivery()
  140. {
  141. $cityId = $this->request->get('city_id', 0);
  142. $delivery = (new DeliveryRuleModel())->getDelivetyByArea($cityId);
  143. $this->success('', $delivery['list']);
  144. }
  145. /**
  146. * 获取订单信息
  147. */
  148. public function getOrders()
  149. {
  150. // 0=全部,1=待付款,2=待发货,3=待收货,4=待评价,5=售后
  151. $type = $this->request->get('type', 0);
  152. $page = $this->request->get('page', 1);
  153. $pagesize = $this->request->get('pagesize', 10);
  154. try {
  155. $orderModel = new \addons\unishop\model\Order();
  156. $result = $orderModel->getOrdersByType($this->auth->id, $type, $page, $pagesize);
  157. $this->success('', $result);
  158. } catch (Exception $e) {
  159. $this->error($e->getMessage());
  160. }
  161. }
  162. /**
  163. * 取消订单
  164. * 未支付的订单才叫取消,已支付的叫退货
  165. */
  166. public function cancel()
  167. {
  168. $order_id = $this->request->get('order_id', 0);
  169. $order_id = \addons\unishop\extend\Hashids::decodeHex($order_id);
  170. $orderModel = new \addons\unishop\model\Order();
  171. $order = $orderModel->where(['id' => $order_id, 'user_id' => $this->auth->id])->find();
  172. if (!$order) {
  173. $this->error(__('Order not exist'));
  174. }
  175. switch ($order['status']) {
  176. case \addons\unishop\model\Order::STATUS_REFUND:
  177. $this->error('此订单已退款,无法取消');
  178. break;
  179. case \addons\unishop\model\Order::STATUS_CANCEL:
  180. $this->error('此订单已取消, 无需再取消');
  181. break;
  182. }
  183. if ($order['have_paid'] != \addons\unishop\model\Order::PAID_NO) {
  184. $this->error('此订单已支付,无法取消');
  185. }
  186. if ($order['status'] == \addons\unishop\model\Order::STATUS_NORMAL && $order['have_paid'] == \addons\unishop\model\Order::PAID_NO) {
  187. $order->status = \addons\unishop\model\Order::STATUS_CANCEL;
  188. $order->save();
  189. $this->success('取消成功', true);
  190. }
  191. }
  192. /**
  193. * 删除订单
  194. * 只能删除已取消或已退货的订单
  195. */
  196. public function delete()
  197. {
  198. $order_id = $this->request->get('order_id', 0);
  199. $order_id = \addons\unishop\extend\Hashids::decodeHex($order_id);
  200. $orderModel = new \addons\unishop\model\Order();
  201. $order = $orderModel->where(['id' => $order_id, 'user_id' => $this->auth->id])->find();
  202. if (!$order) {
  203. $this->error(__('Order not exist'));
  204. }
  205. if ($order['status'] == \addons\unishop\model\Order::STATUS_NORMAL) {
  206. $this->error('只能删除已取消或已退货的订单');
  207. }
  208. if ($order['status'] == \addons\unishop\model\Order::STATUS_REFUND && $order['refund_status'] == \addons\unishop\model\Order::REFUND_STATUS_APPLY) {
  209. $this->error('订单退款中,不可删除订单');
  210. }
  211. $order->delete();
  212. $this->success('删除成功', true);
  213. }
  214. /**
  215. * 确认收货
  216. */
  217. public function received()
  218. {
  219. $order_id = $this->request->get('order_id', 0);
  220. $order_id = \addons\unishop\extend\Hashids::decodeHex($order_id);
  221. $orderModel = new \addons\unishop\model\Order();
  222. $order = $orderModel->where(['id' => $order_id, 'user_id' => $this->auth->id])->find();
  223. if (!$order) {
  224. $this->error(__('Order not exist'));
  225. }
  226. if ($order->have_delivered == 0) {
  227. $this->error('未发货,不能确认收货');
  228. }
  229. $order->have_received = time();
  230. $order->save();
  231. $this->success('已确认收货', true);
  232. }
  233. /**
  234. * 发表评论
  235. */
  236. public function comment()
  237. {
  238. $rate = $this->request->post('rate', 5);
  239. $anonymous = $this->request->post('anonymous', 0);
  240. $comment = $this->request->post('comment');
  241. $order_id = $this->request->post('order_id', 0);
  242. $order_id = \addons\unishop\extend\Hashids::decodeHex($order_id);
  243. $product_id = $this->request->post('product_id');
  244. $product_id = \addons\unishop\extend\Hashids::decodeHex($product_id);
  245. $orderProductModel = new \addons\unishop\model\OrderProduct();
  246. $orderProduct = $orderProductModel->where(['product_id' => $product_id, 'order_id' => $order_id, 'user_id' => $this->auth->id])->find();
  247. $orderModel = new \addons\unishop\model\Order();
  248. $order = $orderModel->where(['id' => $order_id, 'user_id' => $this->auth->id])->find();
  249. if (!$orderProduct || !$order) {
  250. $this->error(__('Order not exist'));
  251. }
  252. if ($order->have_received == $orderModel::RECEIVED_NO) {
  253. $this->error(__('未收货,不可评价'));
  254. }
  255. $result = false;
  256. try {
  257. $evaluate = new Evaluate();
  258. $evaluate->user_id = $this->auth->id;
  259. $evaluate->order_id = $order_id;
  260. $evaluate->product_id = $product_id;
  261. $evaluate->rate = $rate;
  262. $evaluate->anonymous = $anonymous;
  263. $evaluate->comment = $comment;
  264. $evaluate->spec = $orderProduct->spec;
  265. $result = $evaluate->save();
  266. if ($result) {
  267. $order->have_commented = time();
  268. $order->save();
  269. }
  270. } catch (Exception $e) {
  271. $this->error($e->getMessage());
  272. }
  273. if ($result !== false) {
  274. $this->success(__('Thanks for the evaluation'));
  275. } else {
  276. $this->error(__('Evaluation failure'));
  277. }
  278. }
  279. /**
  280. * 获取订单数量
  281. */
  282. public function count()
  283. {
  284. if (!$this->auth->isLogin()) {
  285. $this->error('');
  286. }
  287. $order = new \addons\unishop\model\Order();
  288. $list = $order
  289. ->where([
  290. 'user_id' => $this->auth->id,
  291. ])
  292. ->where('status', '<>', \addons\unishop\model\Order::STATUS_CANCEL)
  293. ->where(function ($query) {
  294. $query
  295. ->whereOr([
  296. 'have_paid' => \addons\unishop\model\Order::PAID_NO,
  297. 'have_delivered' => \addons\unishop\model\Order::DELIVERED_NO,
  298. 'have_received' => \addons\unishop\model\Order::RECEIVED_NO,
  299. 'have_commented' => \addons\unishop\model\Order::COMMENTED_NO
  300. ])
  301. ->whereOr('refund_status', '>', \addons\unishop\model\Order::REFUND_STATUS_NONE);
  302. })
  303. ->field('have_paid,have_delivered,have_received,have_commented,refund_status,had_refund')
  304. ->select();
  305. $data = [
  306. 'unpaid' => 0,
  307. 'undelivered' => 0,
  308. 'unreceived' => 0,
  309. 'uncomment' => 0,
  310. 'refund' => 0
  311. ];
  312. foreach ($list as $item) {
  313. switch (true) {
  314. case $item['have_paid'] > 0 && $item['have_delivered'] > 0 && $item['have_received'] > 0 && $item['have_commented'] == 0 && $item['refund_status'] == 0:
  315. $data['uncomment']++;
  316. break;
  317. case $item['have_paid'] > 0 && $item['have_delivered'] > 0 && $item['have_received'] == 0 && $item['have_commented'] == 0 && $item['refund_status'] == 0:
  318. $data['unreceived']++;
  319. break;
  320. case $item['have_paid'] > 0 && $item['have_delivered'] == 0 && $item['have_received'] == 0 && $item['have_commented'] == 0 && $item['refund_status'] == 0:
  321. $data['undelivered']++;
  322. break;
  323. case $item['have_paid'] == 0 && $item['have_delivered'] == 0 && $item['have_received'] == 0 && $item['have_commented'] == 0 && $item['refund_status'] == 0:
  324. $data['unpaid']++;
  325. break;
  326. case $item['refund_status'] > 0 && $item['had_refund'] == 0 && $item['refund_status'] != 3:
  327. $data['refund']++;
  328. break;
  329. }
  330. }
  331. $this->success('', $data);
  332. }
  333. /**
  334. * 订单详情细节
  335. */
  336. public function detail()
  337. {
  338. $order_id = $this->request->get('order_id', 0);
  339. $order_id = \addons\unishop\extend\Hashids::decodeHex($order_id);
  340. try {
  341. $orderModel = new \addons\unishop\model\Order();
  342. $order = $orderModel
  343. ->with([
  344. 'products' => function ($query) {
  345. $query->field('id,order_id,image,number,price,spec,title,product_id');
  346. },
  347. 'extend' => function ($query) {
  348. $query->field('id,order_id,address_id,address_json,express_number');
  349. },
  350. 'evaluate' => function ($query) {
  351. $query->field('id,order_id,product_id');
  352. }
  353. ])
  354. ->where(['id' => $order_id, 'user_id' => $this->auth->id])->find();
  355. if ($order) {
  356. $order = $order->append(['state', 'paidtime', 'deliveredtime', 'receivedtime', 'commentedtime', 'pay_type_text', 'refund_status_text'])->toArray();
  357. // 快递单号
  358. $order['express_number'] = $order['extend']['express_number'];
  359. // 送货地址
  360. $address = json_decode($order['extend']['address_json'], true);
  361. $area = (new \addons\unishop\model\Area())
  362. ->whereIn('id', [$address['province_id'], $address['city_id'], $address['area_id']])
  363. ->column('name', 'id');
  364. $delivery['username'] = $address['name'];
  365. $delivery['mobile'] = $address['mobile'];
  366. $delivery['address'] = $area[$address['province_id']] . ' ' . $area[$address['city_id']] . ' ' . $area[$address['area_id']] . ' ' . $address['address'];
  367. $order['delivery'] = $delivery;
  368. // 是否已评论
  369. $evaluate = array_column($order['evaluate'], 'product_id');
  370. foreach ($order['products'] as &$product) {
  371. $product['image'] = Config::getImagesFullUrl($product['image']);
  372. if (in_array($product['id'], $evaluate)) {
  373. $product['evaluate'] = true;
  374. } else {
  375. $product['evaluate'] = false;
  376. }
  377. }
  378. unset($order['evaluate']);
  379. unset($order['extend']);
  380. }
  381. $this->success('', $order);
  382. } catch (Exception $e) {
  383. $this->error($e->getMessage());
  384. }
  385. }
  386. /**
  387. * 申请售后信息
  388. */
  389. public function refundInfo()
  390. {
  391. $order_id = $this->request->post('order_id');
  392. $order_id = \addons\unishop\extend\Hashids::decodeHex($order_id);
  393. $orderModel = new \addons\unishop\model\Order();
  394. $order = $orderModel
  395. ->with([
  396. 'products' => function ($query) {
  397. $query->field('id,order_id,image,number,price,spec,title,product_id,(1) as choose');
  398. },
  399. 'refund',
  400. 'refundProducts'
  401. ])
  402. ->field('id,status,total_price,delivery_price,have_commented,have_delivered,have_paid,have_received,refund_status')
  403. ->where(['id' => $order_id, 'user_id' => $this->auth->id])->find();
  404. if (!$order) {
  405. $this->error(__('Order not exist'));
  406. }
  407. $order = $order->append(['refund_status_text'])->toArray();
  408. foreach ($order['products'] as &$product) {
  409. $product['image'] = Config::getImagesFullUrl($product['image']);
  410. $product['choose'] = 0;
  411. // 如果是已提交退货的全选
  412. if ($order['status'] == \addons\unishop\model\Order::STATUS_REFUND) {
  413. foreach ($order['refund_products'] as $refundProduct) {
  414. if ($product['order_product_id'] == $refundProduct['order_product_id']) {
  415. $product['choose'] = 1;
  416. }
  417. }
  418. }
  419. }
  420. unset($order['refund_products']);
  421. $this->success('', $order);
  422. }
  423. /**
  424. * 申请售后
  425. * @throws \think\db\exception\DataNotFoundException
  426. * @throws \think\db\exception\ModelNotFoundException
  427. * @throws \think\exception\DbException
  428. */
  429. public function refund()
  430. {
  431. $order_id = $this->request->post('order_id');
  432. $order_id = Hashids::decodeHex($order_id);
  433. $orderModel = new \addons\unishop\model\Order();
  434. $order = $orderModel->where(['id' => $order_id, 'user_id' => $this->auth->id])->find();
  435. if (!$order) {
  436. $this->error(__('Order not exist'));
  437. }
  438. if ($order['have_paid'] == 0) {
  439. $this->error(__('订单未支付,可直接取消,无需申请售后'));
  440. }
  441. $amount = $this->request->post('amount', 0);
  442. $serviceType = $this->request->post('service_type');
  443. $receivingStatus = $this->request->post('receiving_status');
  444. $reasonType = $this->request->post('reason_type');
  445. $refundExplain = $this->request->post('refund_explain');
  446. $orderProductId = $this->request->post('order_product_id');
  447. if (!$orderProductId) {
  448. $this->error(__('Please select goods'));
  449. }
  450. if (!in_array($receivingStatus, [OrderRefund::UNRECEIVED, OrderRefund::RECEIVED])) {
  451. $this->error(__('Please select goods status'));
  452. }
  453. if (!in_array($serviceType, [OrderRefund::TYPE_REFUND_NORETURN, OrderRefund::TYPE_REFUND_RETURN, OrderRefund::TYPE_EXCHANGE])) {
  454. $this->error(__('Please select service type'));
  455. }
  456. if (in_array($serviceType, [OrderRefund::TYPE_REFUND_NORETURN, OrderRefund::TYPE_REFUND_RETURN]) && $order['total_price'] > 0) {
  457. if (!$amount) {
  458. $this->error(__('Please fill in the refund amount'));
  459. }
  460. }
  461. try {
  462. Db::startTrans();
  463. $orderRefund = new OrderRefund();
  464. $orderRefund->user_id = $this->auth->id;
  465. $orderRefund->order_id = $order_id;
  466. $orderRefund->receiving_status = $receivingStatus;
  467. $orderRefund->service_type = $serviceType;
  468. $orderRefund->reason_type = $reasonType;
  469. $orderRefund->amount = $amount;
  470. $orderRefund->refund_explain = $refundExplain;
  471. $orderRefund->save();
  472. $productIdArr = explode(',', $orderProductId);
  473. $refundProduct = [];
  474. foreach ($productIdArr as $orderProductId) {
  475. $tmp['order_product_id'] = $orderProductId;
  476. $tmp['order_id'] = $order_id;
  477. $tmp['user_id'] = $this->auth->id;
  478. $tmp['refund_id'] = $orderRefund['id'];
  479. $tmp['createtime'] = time();
  480. $refundProduct[] = $tmp;
  481. }
  482. (new OrderRefundProduct)->insertAll($refundProduct);
  483. $order->status = \addons\unishop\model\Order::STATUS_REFUND;
  484. $order->refund_status = \addons\unishop\model\Order::REFUND_STATUS_APPLY;
  485. $order->save();
  486. Db::commit();
  487. $this->success(__('Commit'), 1);
  488. } catch (Exception $e) {
  489. Db::rollback();
  490. $this->error($e->getMessage());
  491. }
  492. }
  493. /**
  494. * 售后发货
  495. */
  496. public function refundDelivery()
  497. {
  498. $orderId = $this->request->post('order_id');
  499. $expressNumber = $this->request->post('express_number');
  500. if (!$expressNumber) {
  501. $this->error(__('Please fill in the express number'));
  502. }
  503. $orderId = Hashids::decodeHex($orderId);
  504. $orderModel = new \addons\unishop\model\Order();
  505. $order = $orderModel
  506. ->where(['id' => $orderId, 'user_id' => $this->auth->id])
  507. ->with(['refund'])->find();
  508. if (!$order || !$order->refund) {
  509. $this->error(__('Order not exist'));
  510. }
  511. try {
  512. Db::startTrans();
  513. $order->refund->express_number = $expressNumber;
  514. $order->refund_status = \addons\unishop\model\Order::REFUND_STATUS_APPLY;
  515. if ($order->refund->save() && $order->save()) {
  516. Db::commit();
  517. $this->success('', 1);
  518. } else {
  519. throw new Exception(__('Operation failed'));
  520. }
  521. } catch (Exception $e) {
  522. Db::rollback();
  523. $this->success($e->getMessage());
  524. }
  525. }
  526. }