Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

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