Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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