StoreOrderController.php 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\controller\api\v1\order;
  12. use app\Request;
  13. use app\services\pay\PayServices;
  14. use app\services\other\ExpressServices;
  15. use app\services\product\branch\StoreBranchProductServices;
  16. use app\services\user\UserAddressServices;
  17. use app\services\user\UserInvoiceServices;
  18. use app\services\user\UserServices;
  19. use app\services\activity\{collage\UserCollageServices,
  20. discounts\StoreDiscountsServices,
  21. lottery\LuckLotteryServices,
  22. bargain\StoreBargainServices,
  23. combination\StorePinkServices
  24. };
  25. use app\services\activity\coupon\StoreCouponIssueServices;
  26. use crmeb\services\wechat\MiniProgram;
  27. use app\services\order\{OtherOrderServices,
  28. StoreCartServices,
  29. StoreDeliveryOrderServices,
  30. StoreOrderCartInfoServices,
  31. StoreOrderCommentServices,
  32. StoreOrderComputedServices,
  33. StoreOrderCreateServices,
  34. StoreOrderEconomizeServices,
  35. StoreOrderRefundServices,
  36. StoreOrderServices,
  37. StoreOrderStatusServices,
  38. StoreOrderSuccessServices,
  39. StoreOrderTakeServices,
  40. StoreOrderPromotionsServices,
  41. StoreOrderWriteOffServices
  42. };
  43. use app\services\pay\OrderPayServices;
  44. use app\services\pay\YuePayServices;
  45. use app\services\product\product\StoreProductReplyServices;
  46. use app\services\product\shipping\ShippingTemplatesServices;
  47. use app\services\store\SystemStoreServices;
  48. use crmeb\services\CacheService;
  49. /**
  50. * 订单控制器
  51. * Class StoreOrderController
  52. * @package app\controller\api\order
  53. */
  54. class StoreOrderController
  55. {
  56. /**
  57. * @var StoreOrderServices
  58. */
  59. protected $services;
  60. /**
  61. * @var int[]
  62. */
  63. protected $getChennel = [
  64. 'weixin' => 0,
  65. 'routine' => 1,
  66. 'weixinh5' => 2,
  67. 'pc' => 3,
  68. 'app' => 4
  69. ];
  70. /**
  71. * 地址信息
  72. * @var string[]
  73. */
  74. protected $addressInfo = [
  75. 'id' => 0,
  76. 'real_name' => '',
  77. 'phone' => '',
  78. 'province' => '',
  79. 'city' => '',
  80. 'district' => '',
  81. 'street' => '',
  82. 'detail' => '',
  83. 'longitude' => '',
  84. 'latitude' => ''
  85. ];
  86. /**
  87. * StoreOrderController constructor.
  88. * @param StoreOrderServices $services
  89. */
  90. public function __construct(StoreOrderServices $services)
  91. {
  92. $this->services = $services;
  93. }
  94. /**
  95. * @param Request $request
  96. * @return mixed
  97. * @throws \Psr\SimpleCache\InvalidArgumentException
  98. */
  99. public function checkShipping(Request $request)
  100. {
  101. [$cartId, $new] = $request->postMore(['cartId', 'new'], true);
  102. return app('json')->successful($this->services->checkShipping($request->uid(), $cartId, $new));
  103. }
  104. /**
  105. * 订单确认
  106. * @param Request $request
  107. * @param ShippingTemplatesServices $services
  108. * @return mixed
  109. * @throws \Psr\SimpleCache\InvalidArgumentException
  110. * @throws \think\db\exception\DataNotFoundException
  111. * @throws \think\db\exception\DbException
  112. * @throws \think\db\exception\ModelNotFoundException
  113. */
  114. public function confirm(Request $request, ShippingTemplatesServices $services)
  115. {
  116. if (!$services->get(1, ['id'])) {
  117. return app('json')->fail('默认模板未配置,无法下单');
  118. }
  119. [$cartId, $new, $addressId, $shippingType, $storeId, $couponId, $luckRecordId, $deliveryType] = $request->postMore([
  120. 'cartId',
  121. 'new',
  122. ['addressId', 0],
  123. ['shipping_type', 1],
  124. ['store_id', 0],
  125. ['couponId', 0],
  126. ['luckRecordId', 0],
  127. ['delivery_type', 1],
  128. ], true);
  129. if (!is_string($cartId) || !$cartId) {
  130. return app('json')->fail('请提交购买的商品');
  131. }
  132. $user = $request->user()->toArray();
  133. return app('json')->successful($this->services->getOrderConfirmData($user, $cartId, !!$new, (int)$addressId, (int)$shippingType, (int)$storeId, (int)$couponId));
  134. }
  135. /**
  136. * 计算订单金额
  137. * @param Request $request
  138. * @param $key
  139. * @return mixed
  140. * @throws \think\Exception
  141. * @throws \think\db\exception\DataNotFoundException
  142. * @throws \think\db\exception\ModelNotFoundException
  143. * @throws \think\exception\DbException
  144. */
  145. public function computedOrder(Request $request, StoreOrderComputedServices $computedServices, $key)
  146. {
  147. if (!$key) return app('json')->fail('参数错误!');
  148. $uid = $request->uid();
  149. if ($checkOrder = $this->services->getOne(['order_id|unique' => $key, 'uid' => $uid, 'is_del' => 0], 'id,order_id'))
  150. return app('json')->status('extend_order', '订单已生成', ['orderId' => $checkOrder['order_id'], 'key' => $key]);
  151. [$addressId, $couponId, $payType, $useIntegral, $mark, $combinationId, $pinkId, $seckill_id, $bargainId, $newcomerId, $shipping_type, $delivery_type] = $request->postMore([
  152. 'addressId', 'couponId', ['payType', 'yue'], ['useIntegral', 0], 'mark', ['combinationId', 0], ['pinkId', 0], ['seckill_id', 0], ['bargainId', ''], ['newcomerId', 0],
  153. ['shipping_type', 1], ['delivery_type', 1],
  154. ], true);
  155. $payType = strtolower($payType);
  156. $cartGroup = $this->services->getCacheOrderInfo($uid, $key);
  157. if (!$cartGroup) return app('json')->fail('订单已过期,请刷新当前页面!');
  158. $priceGroup = $computedServices->setParamData([
  159. 'combinationId' => $combinationId,
  160. 'pinkId' => $pinkId,
  161. 'seckill_id' => $seckill_id,
  162. 'bargainId' => $bargainId,
  163. 'newcomerId' => $newcomerId
  164. ])->computedOrder($request->uid(), $request->user()->toArray(), $cartGroup, (int)$addressId, $payType, !!$useIntegral, (int)$couponId, (int)$shipping_type);
  165. if ($priceGroup)
  166. return app('json')->status('NONE', 'ok', $priceGroup);
  167. else
  168. return app('json')->fail('计算失败');
  169. }
  170. /**
  171. * 订单创建
  172. * @param Request $request
  173. * @param StoreOrderCreateServices $createServices
  174. * @param $key
  175. * @return mixed
  176. * @throws \Psr\SimpleCache\InvalidArgumentException
  177. * @throws \think\Exception
  178. * @throws \think\db\exception\DataNotFoundException
  179. * @throws \think\db\exception\DbException
  180. * @throws \think\db\exception\ModelNotFoundException
  181. */
  182. public function create(Request $request, StoreOrderCreateServices $createServices, $key)
  183. {
  184. if (!$key) return app('json')->fail('参数错误!');
  185. $uid = (int)$request->uid();
  186. if ($checkOrder = $this->services->getOne(['unique' => $key, 'uid' => $uid, 'is_del' => 0], 'id,order_id'))
  187. return app('json')->status('extend_order', '订单已创建,请点击查看完成支付', ['orderId' => $checkOrder['order_id'], 'key' => $key]);
  188. [$addressId, $couponId, $payType, $useIntegral, $mark, $combinationId, $pinkId, $seckill_id, $collate_code_id, $bargainId, $newcomerId, $from, $shipping_type, $real_name, $phone, $storeId, $news, $invoice_id, $quitUrl, $discountId, $customForm] = $request->postMore([
  189. [['addressId', 'd'], 0],
  190. [['couponId', 'd'], 0],
  191. ['payType', ''],
  192. ['useIntegral', 0],
  193. ['mark', ''],
  194. [['combinationId', 'd'], 0],
  195. [['pinkId', 'd'], 0],
  196. [['seckill_id', 'd'], 0],
  197. [['collate_code_id', 'd'], 0], //拼单ID 、桌码ID
  198. [['bargainId', 'd'], ''],
  199. [['newcomerId', 'd'], ''],
  200. ['from', 'weixin'],
  201. [['shipping_type', 'd'], 1],
  202. ['real_name', ''],
  203. ['phone', ''],
  204. [['store_id', 'd'], 0],
  205. ['new', 0],
  206. [['invoice_id', 'd'], 0],
  207. ['quitUrl', ''],
  208. [['discountId', 'd'], 0],
  209. ['custom_form', []],
  210. ], true);
  211. $cartGroup = $this->services->getCacheOrderInfo($uid, $key);
  212. if (!$cartGroup) {
  213. return app('json')->fail('请勿重复提交或订单已过期 请刷新当前页面!');
  214. }
  215. $cartInfo = $cartGroup['cartInfo'];
  216. if (!$cartInfo) {
  217. return app('json')->fail('订单已过期或提交的商品不在送达区域,请刷新当前页面或重新选择商品下单!');
  218. }
  219. $payType = strtolower($payType);
  220. if ($shipping_type == 1) {
  221. $cartInfo = $cartGroup['cartInfo'];
  222. $product_type = $cartInfo[0]['productInfo']['product_type'] ?? 0;
  223. //普通商品 验证地址
  224. if ($product_type == 0 && !$addressId) {
  225. return app('json')->fail('请选择收货地址!');
  226. }
  227. $addressInfo = ($cartGroup['addr'] ?? []) ?: $this->addressInfo;
  228. if ($addressId && (!$addressInfo || !isset($addressInfo['id']) || $addressInfo['id'] != $addressId)) {
  229. /** @var UserAddressServices $addressServices */
  230. $addressServices = app()->make(UserAddressServices::class);
  231. if (!$addressInfo = $addressServices->getOne(['uid' => $uid, 'id' => $addressId, 'is_del' => 0]))
  232. return app('json')->fail('地址选择有误!');
  233. $addressInfo = $addressInfo->toArray();
  234. }
  235. } elseif ($shipping_type == 4) {
  236. $addressInfo = $this->addressInfo;
  237. } else {
  238. if (!$real_name || !$phone) {
  239. return app('json')->fail('请填写姓名和电话');
  240. }
  241. $addressInfo = $this->addressInfo;
  242. $addressInfo['real_name'] = $real_name;
  243. $addressInfo['phone'] = $phone;
  244. }
  245. //下单前砍价验证
  246. if ($bargainId) {
  247. /** @var StoreBargainServices $bargainServices */
  248. $bargainServices = app()->make(StoreBargainServices::class);
  249. $bargainServices->checkBargainUser((int)$bargainId, $uid);
  250. }
  251. //下单前发票验证
  252. if ($invoice_id) {
  253. /** @var UserInvoiceServices $userInvoiceServices */
  254. $userInvoiceServices = app()->make(UserInvoiceServices::class);
  255. $userInvoiceServices->checkInvoice((int)$invoice_id, $uid);
  256. }
  257. if ($pinkId) {
  258. $pinkId = (int)$pinkId;
  259. /** @var StorePinkServices $pinkServices */
  260. $pinkServices = app()->make(StorePinkServices::class);
  261. if ($pinkServices->isPink($pinkId, $uid))
  262. return app('json')->status('ORDER_EXIST', '订单生成失败,你已经在该团内不能再参加了', ['orderId' => $this->services->getStoreIdPink($pinkId, $uid)]);
  263. if ($this->services->getIsOrderPink($pinkId, $uid))
  264. return app('json')->status('ORDER_EXIST', '订单生成失败,你已经参加该团了,请先支付订单', ['orderId' => $this->services->getStoreIdPink($pinkId, $uid)]);
  265. if (!CacheService::checkStock(md5($pinkId), 1, 3) || !CacheService::popStock(md5($pinkId), 1, 3)) {
  266. return app('json')->fail('该团人员已满');
  267. }
  268. }
  269. if ($from != 'pc') {
  270. if (!$this->services->checkPaytype($payType)) {
  271. return app('json')->fail('暂不支持该支付方式,请刷新页面或者联系管理员');
  272. }
  273. }
  274. $isChannel = $this->getChennel[$from] ?? ($request->isApp() ? 4 : 1);
  275. if ($seckill_id || $combinationId || $discountId || $bargainId) {
  276. //套餐限量库
  277. if ($discountId) {
  278. /** @var StoreDiscountsServices $discountService */
  279. $discountService = app()->make(StoreDiscountsServices::class);
  280. $discounts = $discountService->get((int)$discountId);
  281. if (!$discounts) {
  282. return app('json')->fail('套餐商品未找到!');
  283. }
  284. //套餐限量
  285. if ($discounts['is_limit'] && !CacheService::popStock(md5($discountId), 1, 5)) {
  286. return app('json')->fail('您购买的套餐不足');
  287. }
  288. }
  289. foreach ($cartInfo as $item) {
  290. if (!isset($item['product_attr_unique']) || !$item['product_attr_unique']) continue;
  291. $type = $item['type'];
  292. if (in_array($type, [1, 2, 3]) && (!CacheService::checkStock($item['product_attr_unique'], (int)$item['cart_num'], $type) || !CacheService::popStock($item['product_attr_unique'], (int)$item['cart_num'], $type))) {
  293. return app('json')->fail('您购买的商品库存已不足' . $item['cart_num'] . $item['productInfo']['unit_name']);
  294. }
  295. }
  296. }
  297. try {
  298. $msg = '';
  299. $order = $createServices->createOrder($uid, $key, $cartGroup, (int)$addressId, $payType, $addressInfo, $request->user()->toArray(), !!$useIntegral, $couponId, $mark, $pinkId, $isChannel, $shipping_type, $storeId, !!$news, $customForm, (int)$invoice_id, $from, (int)$collate_code_id);
  300. } catch (\Throwable $e) {
  301. $order = false;
  302. $msg = $e->getMessage();
  303. \think\facade\Log::error('订单生成失败,原因:' . $msg . $e->getFile() . $e->getLine());
  304. }
  305. if ($order === false) {
  306. if ($seckill_id || $combinationId || $discountId || $bargainId) {
  307. //回退套餐限量库
  308. if ($discountId) CacheService::setStock(md5($discountId), 1, 5, false);
  309. foreach ($cartInfo as $item) {
  310. if (!isset($item['product_attr_unique']) || !$item['product_attr_unique']) continue;
  311. $type = $item['type'];
  312. if (in_array($type, [1, 2, 3])) CacheService::setStock($item['product_attr_unique'], (int)$item['cart_num'], $type, false);
  313. }
  314. }
  315. return app('json')->fail($msg ?: '订单生成失败');
  316. }
  317. $orderId = $order['order_id'];
  318. if ($orderId) {
  319. $orderInfo = $order->toArray();
  320. if (!$orderInfo || !isset($orderInfo['paid'])) {
  321. return app('json')->fail('支付订单不存在!');
  322. }
  323. $info = compact('orderId', 'key');
  324. switch ($payType) {
  325. case PayServices::WEIXIN_PAY:
  326. if ($orderInfo['paid']) return app('json')->fail('支付已支付!');
  327. //支付金额为0
  328. if (bcsub((string)$orderInfo['pay_price'], '0', 2) <= 0) {
  329. //创建订单jspay支付
  330. /** @var StoreOrderSuccessServices $success */
  331. $success = app()->make(StoreOrderSuccessServices::class);
  332. $payPriceStatus = $success->zeroYuanPayment($orderInfo, $uid, PayServices::WEIXIN_PAY);
  333. if ($payPriceStatus)//0元支付成功
  334. return app('json')->status('success', '微信支付成功', $info);
  335. else
  336. return app('json')->status('pay_error');
  337. } else {
  338. /** @var OrderPayServices $payServices */
  339. $payServices = app()->make(OrderPayServices::class);
  340. if (!$from && $request->isApp()) {
  341. $from = 'weixin';
  342. }
  343. $info['jsConfig'] = $payServices->orderPay($orderInfo, $from);
  344. if ($from == 'weixinh5') {
  345. return app('json')->status('wechat_h5_pay', '订单创建成功', $info);
  346. } else {
  347. return app('json')->status('wechat_pay', '订单创建成功', $info);
  348. }
  349. }
  350. break;
  351. case PayServices::YUE_PAY:
  352. /** @var YuePayServices $yueServices */
  353. $yueServices = app()->make(YuePayServices::class);
  354. $pay = $yueServices->yueOrderPay($orderInfo, $uid);
  355. if ($pay['status'] === true)
  356. return app('json')->status('success', '余额支付成功', $info);
  357. else {
  358. if (is_array($pay))
  359. return app('json')->status($pay['status'], $pay['msg'], $info);
  360. else
  361. return app('json')->status('pay_error', $pay);
  362. }
  363. break;
  364. case PayServices::ALIAPY_PAY:
  365. if (!$quitUrl && ($request->isH5() || $request->isWechat())) {
  366. return app('json')->status('pay_error', '请传入支付宝支付回调URL', $info);
  367. }
  368. [$url, $param] = strpos($quitUrl, '?') ? explode('?', $quitUrl) : [$quitUrl, ''];
  369. if ($param) {
  370. $quitUrl = $quitUrl . '&order_id=' . $orderInfo['order_id'];
  371. } else {
  372. $quitUrl = $url . '?order_id=' . $orderInfo['order_id'];
  373. }
  374. //支付金额为0
  375. if (bcsub((string)$orderInfo['pay_price'], '0', 2) <= 0) {
  376. //创建订单jspay支付
  377. /** @var StoreOrderSuccessServices $success */
  378. $success = app()->make(StoreOrderSuccessServices::class);
  379. $payPriceStatus = $success->zeroYuanPayment($orderInfo, $uid, PayServices::ALIAPY_PAY);
  380. if ($payPriceStatus)//0元支付成功
  381. return app('json')->status('success', '支付宝支付成功', $info);
  382. else
  383. return app('json')->status('pay_error');
  384. } else {
  385. /** @var OrderPayServices $payServices */
  386. $payServices = app()->make(OrderPayServices::class);
  387. $info['jsConfig'] = $payServices->alipayOrder($orderInfo, $quitUrl, $from == 'routine');
  388. $payKey = md5($orderInfo['order_id']);
  389. CacheService::set($payKey, ['order_id' => $orderInfo['order_id'], 'other_pay_type' => false], 300);
  390. $info['pay_key'] = $payKey;
  391. return app('json')->status(PayServices::ALIAPY_PAY . '_pay', '订单创建成功', $info);
  392. }
  393. break;
  394. default:
  395. return app('json')->status('success', '订单创建成功', $info);
  396. break;
  397. }
  398. } else return app('json')->fail('订单生成失败!');
  399. }
  400. /**
  401. * 订单 再次下单
  402. * @param Request $request
  403. * @return mixed
  404. */
  405. public function again(Request $request, StoreCartServices $services)
  406. {
  407. [$uni] = $request->postMore([
  408. ['uni', ''],
  409. ], true);
  410. if (!$uni) return app('json')->fail('参数错误!');
  411. $order = $this->services->getUserOrderDetail($uni, (int)$request->uid());
  412. if (!$order) return app('json')->fail('订单不存在!');
  413. if (in_array($order['type'], [1, 2, 3, 5])) {
  414. $msg = '';
  415. switch ($order['type']) {
  416. case 1://秒杀
  417. $msg = '秒杀';
  418. break;
  419. case 2://砍价
  420. $msg = '砍价';
  421. break;
  422. case 3://拼团
  423. $msg = '拼团';
  424. break;
  425. case 5://套餐
  426. $msg = '套餐';
  427. break;
  428. }
  429. return app('json')->fail($msg . '商品不能再来一单,请在' . $msg . '商品内自行下单!');
  430. }
  431. $order = $this->services->tidyOrder($order, true);
  432. $cateIds = [];
  433. foreach ($order['cartInfo'] as $v) {
  434. if ($v['type'] == 0) {
  435. [$cartId, $cartNum] = $services->setCart($request->uid(), (int)$v['product_id'], (int)$v['cart_num'], isset($v['productInfo']['attrInfo']['unique']) ? $v['productInfo']['attrInfo']['unique'] : '');
  436. $cateIds[] = $cartId;
  437. }
  438. }
  439. if (!$cateIds) return app('json')->fail('再来一单失败,请重新下单!');
  440. return app('json')->successful('ok', ['cateId' => implode(',', $cateIds)]);
  441. }
  442. /**
  443. * 订单支付
  444. * @param Request $request
  445. * @param StorePinkServices $services
  446. * @param OrderPayServices $payServices
  447. * @param YuePayServices $yuePayServices
  448. * @return mixed
  449. */
  450. public function pay(Request $request, StorePinkServices $services, OrderPayServices $payServices, YuePayServices $yuePayServices)
  451. {
  452. [$uni, $paytype, $from, $quitUrl] = $request->postMore([
  453. ['uni', ''],
  454. ['paytype', 'weixin'],
  455. ['from', 'weixin'],
  456. ['quitUrl', '']
  457. ], true);
  458. if (!$uni) return app('json')->fail('参数错误!');
  459. $order = $this->services->getUserOrderDetail($uni, (int)$request->uid());
  460. if (!$order)
  461. return app('json')->fail('订单不存在!');
  462. if ($order['paid'])
  463. return app('json')->fail('该订单已支付!');
  464. if ($order['pink_id'] && $services->isPinkStatus($order['pink_id'])) {
  465. return app('json')->fail('该订单已失效!');
  466. }
  467. // $isChannel = $this->getChennel[$from] ?? ($request->isApp() ? 4 : 1);
  468. //缓存不存在 || 切换另一端支付
  469. // if (!CacheService::get('pay_' . $order['order_id']) || $isChannel != $order['is_channel']) {
  470. // mt_srand();
  471. // switch ($from) {
  472. // case 'weixin':
  473. // if (in_array($order->is_channel, [1, 2, 3, 4])) {//0
  474. // $order['order_id'] = mt_rand(100, 999) . '_' . $order['order_id'];
  475. // }
  476. // break;
  477. // case 'weixinh5':
  478. // if (in_array($order->is_channel, [0, 1, 3, 4])) {
  479. // $order['order_id'] = mt_rand(100, 999) . '_' . $order['order_id'];
  480. // }
  481. // break;
  482. // case 'routine':
  483. // if (in_array($order->is_channel, [0, 2, 3, 4])) {
  484. // $order['order_id'] = mt_rand(100, 999) . '_' . $order['order_id'];
  485. // }
  486. // break;
  487. // case 'pc':
  488. // case 'aliapy':
  489. // $order['order_id'] = mt_rand(100, 999) . '_' . $order['order_id'];
  490. // break;
  491. // }
  492. // }
  493. //只要重新支付就更新订单号
  494. if (in_array($paytype, [PayServices::ALIAPY_PAY, PayServices::WEIXIN_PAY])) {
  495. mt_srand();
  496. $order['order_id'] = mt_rand(100, 999) . '_' . $order['order_id'];
  497. if (sys_config('pay_routine_open', 0)) {
  498. /** @var StoreOrderCreateServices $orderCreateServices */
  499. $orderCreateServices = app()->make(StoreOrderCreateServices::class);
  500. $order['order_id'] = $orderCreateServices->getNewOrderId();
  501. $this->services->update($order['id'], ['unique' => $order['order_id']], 'id');
  502. }
  503. }
  504. $order['pay_type'] = $paytype; //重新支付选择支付方式
  505. switch ($order['pay_type']) {
  506. case PayServices::WEIXIN_PAY:
  507. $jsConfig = $payServices->orderPay($order->toArray(), $from);
  508. if ($from == 'weixinh5') {
  509. return app('json')->status('wechat_h5_pay', ['jsConfig' => $jsConfig, 'order_id' => $order['order_id']]);
  510. } elseif ($from == 'weixin' || $from == 'routine') {
  511. return app('json')->status('wechat_pay', ['jsConfig' => $jsConfig, 'order_id' => $order['order_id']]);
  512. } elseif ($from == 'pc') {
  513. return app('json')->status('wechat_pc_pay', ['jsConfig' => $jsConfig, 'order_id' => $order['order_id']]);
  514. }
  515. break;
  516. case PayServices::ALIAPY_PAY:
  517. if (!$quitUrl && $from != 'routine') {
  518. return app('json')->fail('请传入支付宝支付回调URL');
  519. }
  520. $isCode = $from == 'routine' || $from == 'pc';
  521. $jsConfig = $payServices->alipayOrder($order->toArray(), $quitUrl, $isCode);
  522. if ($isCode && !($jsConfig->invalid ?? false)) $jsConfig->invalid = time() + 60;
  523. $payKey = md5($order['order_id']);
  524. CacheService::set($payKey, ['order_id' => $order['order_id'], 'other_pay_type' => false], 300);
  525. return app('json')->status(PayServices::ALIAPY_PAY . '_pay', '订单创建成功', ['jsConfig' => $jsConfig, 'order_id' => $order['order_id'], 'pay_key' => $payKey]);
  526. break;
  527. case PayServices::YUE_PAY:
  528. $pay = $yuePayServices->yueOrderPay($order->toArray(), $request->uid());
  529. if ($pay['status'] === true)
  530. return app('json')->status('success', '余额支付成功');
  531. else {
  532. if (is_array($pay))
  533. return app('json')->status($pay['status'], $pay['msg']);
  534. else
  535. return app('json')->status('pay_error', $pay);
  536. }
  537. break;
  538. case PayServices::OFFLINE_PAY:
  539. if ($this->services->setOrderTypePayOffline($order['order_id']))
  540. return app('json')->status('success', '订单创建成功');
  541. else
  542. return app('json')->status('success', '支付失败');
  543. break;
  544. }
  545. return app('json')->fail('支付方式错误');
  546. }
  547. /**
  548. * 支付宝单独支付
  549. * @param OrderPayServices $payServices
  550. * @param OtherOrderServices $services
  551. * @param string $key
  552. * @param string $quitUrl
  553. * @return mixed
  554. * @throws \think\db\exception\DataNotFoundException
  555. * @throws \think\db\exception\DbException
  556. * @throws \think\db\exception\ModelNotFoundException
  557. */
  558. public function aliPay(OrderPayServices $payServices, OtherOrderServices $services, string $key, string $quitUrl)
  559. {
  560. if (!$key || !($orderCache = CacheService::get($key))) {
  561. return app('json')->fail('该订单无法支付');
  562. }
  563. if (!isset($orderCache['order_id'])) {
  564. return app('json')->fail('该订单无法支付');
  565. }
  566. $order_id = $orderCache['order_id'];
  567. if (strpos($orderCache['order_id'], '_')) {
  568. $orderArr = explode('_', $orderCache['order_id']);
  569. if (count($orderArr) == 2) {
  570. $order_id = $orderArr[1] ?? $order_id;
  571. }
  572. }
  573. $payType = isset($orderCache['other_pay_type']) && $orderCache['other_pay_type'] == true;
  574. if ($payType) {
  575. $orderInfo = $services->getOne(['order_id' => $order_id, 'is_del' => 0, 'paid' => 0]);
  576. } else {
  577. $orderInfo = $this->services->get(['order_id' => $order_id, 'paid' => 0, 'is_del' => 0]);
  578. }
  579. if (!$orderInfo) {
  580. return app('json')->fail('订单支付状态有误,无法进行支付');
  581. }
  582. if (!$quitUrl) {
  583. return app('json')->fail('请传入支付宝支付回调URL');
  584. }
  585. $payInfo = $payServices->alipayOrder($orderInfo->toArray(), $quitUrl);
  586. return app('json')->success(['pay_content' => $payInfo]);
  587. }
  588. /**
  589. * 订单列表
  590. * @param Request $request
  591. * @return mixed
  592. */
  593. public function lst(Request $request)
  594. {
  595. $where = $request->getMore([
  596. ['type', '', '', 'status'],
  597. ['search', '', '', 'real_name'],
  598. ['refund_type', '', '', 'refundTypes']
  599. ]);
  600. $where['uid'] = $request->uid();
  601. $where['is_del'] = 0;
  602. $where['is_system_del'] = 0;
  603. if ($where['status'] === '') {
  604. $where['pid'] = 0;
  605. } elseif (in_array($where['status'], [-1, -2, -3])) {
  606. $where['not_pid'] = 1;
  607. } elseif (in_array($where['status'], [0, 1, 2, 3, 4])) {
  608. $where['pid'] = 0;
  609. }
  610. $field = ['id', 'type', 'pid', 'order_id'];
  611. $list = $this->services->getOrderApiList($where);
  612. return app('json')->successful($list);
  613. }
  614. /**
  615. * 订单详情
  616. * @param Request $request
  617. * @param StoreOrderEconomizeServices $services
  618. * @param StoreOrderPromotionsServices $storeOrderPromotiosServices
  619. * @param $uni
  620. * @return mixed
  621. * @throws \think\db\exception\DataNotFoundException
  622. * @throws \think\db\exception\DbException
  623. * @throws \think\db\exception\ModelNotFoundException
  624. */
  625. public function detail(Request $request, StoreOrderEconomizeServices $services, StoreOrderPromotionsServices $storeOrderPromotiosServices, $uni)
  626. {
  627. if (!strlen(trim($uni))) return app('json')->fail('参数错误');
  628. $order = $this->services->getUserOrderDetail($uni, (int)$request->uid(), ['invoice', 'refund' => function ($query) {
  629. $query->field('id,store_order_id,refunded_price,refund_explain');
  630. }]);
  631. if (!$order) return app('json')->fail('订单不存在');
  632. if ($order['pid'] == -1) return app('json')->make(403, '订单已被拆分为多个订单,请查看订单列表');
  633. $order = $order->toArray();
  634. $order['split'] = [];
  635. //门店是否开启 || 门店自提是否开启
  636. if (!sys_config('store_func_status', 1) || !sys_config('store_self_mention')) {
  637. //关闭门店自提后 订单隐藏门店信息
  638. $order['shipping_type'] = 1;
  639. }
  640. if ($order['verify_code']) {
  641. $verify_code = $order['verify_code'];
  642. $verify[] = substr($verify_code, 0, 4);
  643. $verify[] = substr($verify_code, 4, 4);
  644. $verify[] = substr($verify_code, 8);
  645. $order['_verify_code'] = implode(' ', $verify);
  646. }
  647. //收银台订单 用户无信息 手机号
  648. if ($order['shipping_type'] == 4 && $order['uid'] && !$order['real_name']) {
  649. /** @var UserServices $userServices */
  650. $userServices = app()->make(UserServices::class);
  651. $userInfo = $userServices->getUserCacheInfo((int)$order['uid']);
  652. $order['real_name'] = $userInfo['nickname'];
  653. $order['user_phone'] = $userInfo['phone'];
  654. }
  655. $order['add_time_y'] = date('Y-m-d', $order['add_time']);
  656. $order['add_time_h'] = date('H:i:s', $order['add_time']);
  657. $order['system_store'] = false;
  658. $order['refunded_price'] = $order['refund'][0]['refunded_price'] ?? 0;
  659. $order['refund_explain'] = $order['refund'][0]['refund_explain'] ?? '';
  660. unset($order['refund']);
  661. if (!$order['store_id'] && $order['shipping_type'] == 2) {
  662. $order['store_id'] = $this->services->value(['pid' => $order['id']], 'store_id');
  663. }
  664. if ($order['store_id']) {
  665. /** @var SystemStoreServices $storeServices */
  666. $storeServices = app()->make(SystemStoreServices::class);
  667. $order['system_store'] = $storeServices->getStoreDisposeCache($order['store_id']);
  668. }
  669. $order['mapKey'] = sys_config('tengxun_map_key');
  670. $order['yue_pay_status'] = (int)sys_config('balance_func_status') && (int)sys_config('yue_pay_status') == 1 ? (int)1 : (int)2;//余额支付 1 开启 2 关闭
  671. $order['pay_weixin_open'] = (int)sys_config('pay_weixin_open') ?? 0;//微信支付 1 开启 0 关闭
  672. $order['ali_pay_status'] = (bool)sys_config('ali_pay_status');//支付包支付 1 开启 0 关闭
  673. $orderData = $this->services->tidyOrder($order, true, true);
  674. //核算优惠金额
  675. $vipTruePrice = 0;
  676. $refund_num = 0;
  677. foreach ($orderData['cartInfo'] ?? [] as $key => &$cart) {
  678. $vipTruePrice = bcadd((string)$vipTruePrice, (string)$cart['vip_sum_truePrice'], 2);
  679. $refund_num = bcadd((string)$refund_num, (string)$cart['refund_num'], 0);
  680. }
  681. $orderData['vip_true_price'] = $vipTruePrice;
  682. $orderData['total_price'] = floatval(bcsub((string)$orderData['total_price'], (string)$vipTruePrice, 2));
  683. //优惠活动优惠详情
  684. $orderData['promotions_detail'] = $storeOrderPromotiosServices->getOrderPromotionsDetail((int)$order['id']);
  685. //同步查询订单商品为查询到 查询缓存信息
  686. if (!$orderData['cartInfo']) {
  687. $cartGroup = $this->services->getCacheOrderInfo((int)$order['uid'], $order['unique']);
  688. $orderData['cartInfo'] = $cartGroup['cartInfo'] ?? [];
  689. }
  690. $economize = $services->get(['order_id' => $order['order_id']], ['postage_price', 'member_price']);
  691. if ($economize) {
  692. $orderData['postage_price'] = $economize['postage_price'];
  693. $orderData['member_price'] = $economize['member_price'];
  694. } else {
  695. $orderData['postage_price'] = 0;
  696. $orderData['member_price'] = 0;
  697. }
  698. $orderData['routine_contact_type'] = sys_config('routine_contact_type', 0);
  699. /** @var UserInvoiceServices $userInvoice */
  700. $userInvoice = app()->make(UserInvoiceServices::class);
  701. $invoice_func = $userInvoice->invoiceFuncStatus();
  702. $orderData['invoice_func'] = $invoice_func['invoice_func'];
  703. $orderData['special_invoice'] = $invoice_func['special_invoice'];
  704. $orderData['refund_cartInfo'] = [];
  705. $orderData['refund_total_num'] = $orderData['total_num'];
  706. $orderData['refund_pay_price'] = $orderData['pay_price'];
  707. $orderData['is_apply_refund'] = $orderData['total_num'] > $refund_num;
  708. $orderData['is_batch_refund'] = count($orderData['cartInfo']) > 1;
  709. $orderData['pinkStatus'] = null;
  710. if ($orderData['type'] == 3) {
  711. /** @var StorePinkServices $pinkService */
  712. $pinkService = app()->make(StorePinkServices::class);
  713. $orderData['pinkStatus'] = $pinkService->value(['order_id' => $orderData['order_id']], 'status');
  714. }
  715. /** @var StoreOrderStatusServices $statusServices */
  716. $statusServices = app()->make(StoreOrderStatusServices::class);
  717. $log = $statusServices->getColumn(['oid' => $order['id']], 'change_time', 'change_type');
  718. if (isset($log['delivery'])) {
  719. $delivery = date('Y-m-d', $log['delivery']);
  720. } elseif (isset($log['delivery_goods'])) {
  721. $delivery = date('Y-m-d', $log['delivery_goods']);
  722. } elseif (isset($log['delivery_fictitious'])) {
  723. $delivery = date('Y-m-d', $log['delivery_fictitious']);
  724. } else {
  725. $delivery = '';
  726. }
  727. $orderData['order_log'] = [
  728. 'create' => isset($log['cache_key_create_order']) ? date('Y-m-d', $log['cache_key_create_order']) : '',
  729. 'pay' => isset($log['pay_success']) ? date('Y-m-d', $log['pay_success']) : '',
  730. 'delivery' => $delivery,
  731. 'take' => isset($log['take_delivery']) ? date('Y-m-d', $log['take_delivery']) : '',
  732. 'complete' => isset($log['check_order_over']) ? date('Y-m-d', $log['check_order_over']) : '',
  733. ];
  734. if ($orderData['give_coupon']) {
  735. $couponIds = is_string($orderData['give_coupon']) ? explode(',', $orderData['give_coupon']) : $orderData['give_coupon'];
  736. /** @var StoreCouponIssueServices $couponIssueService */
  737. $couponIssueService = app()->make(StoreCouponIssueServices::class);
  738. $orderData['give_coupon'] = $couponIssueService->getColumn([['id', 'IN', $couponIds]], 'id,coupon_title');
  739. }
  740. $orderData['write_off'] = $orderData['write_times'] = 0;
  741. $orderData['write_day'] = '';
  742. $cart = $orderData['cartInfo'][0] ?? [];
  743. if ($orderData['product_type'] == 4 && $cart) {//次卡商品
  744. $orderData['write_off'] = $cart['write_off'] ?? max(bcsub((string)$cart['write_times'], (string)$cart['write_surplus_times'], 0), 0);
  745. $orderData['write_times'] = $cart['write_times'] ?? 0;
  746. $start = $cart['write_start'] ?? 0;
  747. $end = $cart['write_end'] ?? 0;
  748. if (!$start && !$end) {
  749. $orderData['write_day'] = '不限时';
  750. } else {
  751. $orderData['write_day'] = ($start ? date('Y-m-d', $start) : '') . '/' . ($end ? date('Y-m-d', $end) : '');
  752. }
  753. }
  754. // 判断是否开启小程序订单管理
  755. $orderData['order_shipping_open'] = false;
  756. if (sys_config('order_shipping_open', 0) && MiniProgram::isManaged() && $order['is_channel'] == 1 && $order['pay_type'] == 'weixin') {
  757. // 判断是否存在子未收货子订单
  758. if ($order['pid'] > 0) {
  759. if ($this->services->checkSubOrderNotTake((int)$order['pid'], (int)$order['id'])) {
  760. $orderData['order_shipping_open'] = true;
  761. }
  762. } else {
  763. $orderData['order_shipping_open'] = true;
  764. }
  765. }
  766. return app('json')->successful('ok', $orderData);
  767. }
  768. /**
  769. * 配送订单详情
  770. * @param Request $request
  771. * @param $id
  772. * @return mixed
  773. */
  774. public function deliveryOrderDetail(Request $request, $id)
  775. {
  776. if (!strlen(trim($id))) return app('json')->fail('参数错误');
  777. $uid = (int)$request->uid();
  778. $order = $this->services->getOne(['id' => $id, 'uid' => $uid, 'is_del' => 0], 'id,pid,order_id,status,delivery_type,delivery_id,delivery_name', ['deliveryOrder' => function ($query) {
  779. $query->field('id,oid,station_type,order_id,user_name,receiver_phone,to_address,delivery_no,finish_code,distance,fee,status');
  780. }]);
  781. if (!$order) return app('json')->fail('订单不存在');
  782. $order = $order->toArray();
  783. /** @var StoreOrderStatusServices $statusServices */
  784. $statusServices = app()->make(StoreOrderStatusServices::class);
  785. $log = $statusServices->getColumn(['oid' => $order['id']], 'change_time', 'change_type');
  786. /** @var StoreDeliveryOrderServices $deliverOrderSerives */
  787. $deliverOrderSerives = app()->make(StoreDeliveryOrderServices::class);
  788. $message = $deliverOrderSerives->getStatusMsg();
  789. $city_delivery = [];
  790. foreach ($log as $key => $value) {
  791. if (strpos($key, 'city_delivery') !== false) {
  792. $key = str_replace('city_delivery_', '', $key);
  793. $city_delivery[] = [
  794. 'time' => date('Y-m-d H:i:s', $value),
  795. 'label' => $message[$key] ?? '配送中',
  796. ];
  797. }
  798. }
  799. $order['order_log'] = [
  800. 'create' => isset($log['cache_key_create_order']) ? date('Y-m-d', $log['cache_key_create_order']) : '',
  801. 'pay' => isset($log['pay_success']) ? date('Y-m-d', $log['pay_success']) : '',
  802. 'city_delivery' => $city_delivery,
  803. 'take' => isset($log['take_delivery']) ? date('Y-m-d', $log['take_delivery']) : '',
  804. 'complete' => isset($log['check_order_over']) ? date('Y-m-d', $log['check_order_over']) : '',
  805. ];
  806. return app('json')->successful('ok', $order);
  807. }
  808. /**
  809. * 订单删除
  810. * @param Request $request
  811. * @return mixed
  812. */
  813. public function del(Request $request)
  814. {
  815. [$uni] = $request->postMore([
  816. ['uni', ''],
  817. ], true);
  818. if (!$uni) return app('json')->fail('参数错误!');
  819. $res = $this->services->removeOrder($uni, (int)$request->uid());
  820. if ($res) {
  821. return app('json')->successful();
  822. } else {
  823. return app('json')->fail('删除失败');
  824. }
  825. }
  826. /**
  827. * 订单收货
  828. * @param Request $request
  829. * @return mixed
  830. */
  831. public function take(Request $request, StoreOrderTakeServices $services, StoreCouponIssueServices $issueServices)
  832. {
  833. [$uni] = $request->postMore([
  834. ['uni', ''],
  835. ], true);
  836. if (!$uni) return app('json')->fail('参数错误!');
  837. $order = $services->takeOrder($uni, (int)$request->uid());
  838. if ($order) {
  839. return app('json')->successful('收货成功');
  840. } else
  841. return app('json')->fail('收货失败');
  842. }
  843. /**
  844. * 订单 查看物流
  845. * @param Request $request
  846. * @param StoreOrderCartInfoServices $services
  847. * @param ExpressServices $expressServices
  848. * @param $uni
  849. * @param string $type
  850. * @return mixed
  851. */
  852. public function express(Request $request, StoreOrderCartInfoServices $services, ExpressServices $expressServices, $uni, $type = '')
  853. {
  854. if ($type == 'refund') {
  855. /** @var StoreOrderRefundServices $refundService */
  856. $refundService = app()->make(StoreOrderRefundServices::class);
  857. $order = $refundService->refundDetail($uni);
  858. $express = $order['refund_express'];
  859. $cacheName = $uni . $express;
  860. $orderInfo = [];
  861. $info = [];
  862. $cartNew = [];
  863. foreach ($order['cart_info'] as $k => $cart) {
  864. $cartNew['cart_num'] = $cart['cart_num'];
  865. $cartNew['truePrice'] = $order['type'] == 8 ? 0 : $cart['truePrice'];
  866. $cartNew['productInfo']['image'] = $cart['productInfo']['image'];
  867. $cartNew['productInfo']['store_name'] = $cart['productInfo']['store_name'];
  868. $cartNew['productInfo']['unit_name'] = $cart['productInfo']['unit_name'] ?? '';
  869. array_push($info, $cartNew);
  870. unset($cart);
  871. }
  872. $orderInfo['cartInfo'] = $info;
  873. $orderInfo['delivery_id'] = $express;
  874. $orderInfo['delivery_name'] = $order['refund_express_name'];
  875. $orderInfo['delivery_code'] = '';
  876. $orderInfo['user_address'] = $order['user_address'];
  877. $orderInfo['user_mark'] = $order['refund_explain'];
  878. } else {
  879. if (!$uni || !($order = $this->services->getUserOrderDetail($uni, $request->uid()))) return app('json')->fail('查询订单不存在!');
  880. if ($type != 'refund') {
  881. if ($order['delivery_type'] != 'express') return app('json')->fail('该订单不是快递发货,无法查询物流信息');
  882. if (!$order['delivery_id']) return app('json')->fail('该订单不存在快递单号!');
  883. }
  884. $express = $type == 'refund' ? $order['refund_express'] : $order['delivery_id'];
  885. $cacheName = $uni . $express;
  886. $orderInfo = [];
  887. $cartInfo = $services->getCartColunm(['oid' => $order['id']], 'cart_info', 'unique');
  888. $info = [];
  889. $cartNew = [];
  890. foreach ($cartInfo as $k => $cart) {
  891. $cart = json_decode($cart, true);
  892. $cartNew['cart_num'] = $cart['cart_num'];
  893. $cartNew['truePrice'] = $order['type'] == 8 ? 0 : $cart['truePrice'];
  894. $cartNew['productInfo']['image'] = $cart['productInfo']['image'];
  895. $cartNew['productInfo']['store_name'] = $cart['productInfo']['store_name'];
  896. $cartNew['productInfo']['unit_name'] = $cart['productInfo']['unit_name'] ?? '';
  897. array_push($info, $cartNew);
  898. unset($cart);
  899. }
  900. $orderInfo['delivery_id'] = $express;
  901. $orderInfo['delivery_name'] = $type == 'refund' ? '用户退回' : $order['delivery_name'];;
  902. $orderInfo['delivery_code'] = $type == 'refund' ? '' : $order['delivery_code'];
  903. $orderInfo['delivery_type'] = $order['delivery_type'];
  904. $orderInfo['user_address'] = $order['user_address'];
  905. $orderInfo['user_mark'] = $order['mark'];
  906. $orderInfo['cartInfo'] = $info;
  907. }
  908. return app('json')->successful([
  909. 'order' => $orderInfo,
  910. 'express' => [
  911. 'result' => ['list' => $expressServices->query($cacheName, $orderInfo['delivery_id'], $orderInfo['delivery_code'])
  912. ]
  913. ]
  914. ]);
  915. }
  916. /**
  917. * 订单评价
  918. * @param Request $request
  919. * @return mixed
  920. * @throws \think\db\exception\DataNotFoundException
  921. * @throws \think\db\exception\ModelNotFoundException
  922. * @throws \think\exception\DbException
  923. */
  924. public function comment(Request $request, StoreOrderCartInfoServices $cartInfoServices, StoreProductReplyServices $replyServices, StoreOrderCommentServices $storeOrderCommentServices, UserCollageServices $collageservices)
  925. {
  926. $group = $request->postMore([
  927. ['unique', ''], ['comment', ''], ['pics', ''], ['product_score', 5], ['service_score', 5]
  928. ]);
  929. $unique = $group['unique'];
  930. unset($group['unique']);
  931. if (!$unique) return app('json')->fail('参数错误!');
  932. $cartInfo = $cartInfoServices->getOne(['unique' => $unique], 'id,oid,uid');
  933. $uid = (int)$request->uid();
  934. if (!$cartInfo || $uid != $cartInfo['uid']) return app('json')->fail('评价商品不存在!');
  935. $oid = (int)$cartInfo['oid'];
  936. if ($replyServices->be(['oid' => $oid, 'unique' => $unique])) return app('json')->fail('该商品已评价!');
  937. //保存评价
  938. $storeOrderCommentServices->comment($oid, $uid, $group, $unique);
  939. //修改拼单、桌码记录状态
  940. $order = $this->services->get($oid, ['type', 'activity_id']);
  941. if (in_array($order['type'], [9, 10])) {
  942. $collageservices->update($order['activity_id'], ['status' => 3]);
  943. }
  944. //缓存抽奖次数
  945. /** @var LuckLotteryServices $luckLotteryServices */
  946. $luckLotteryServices = app()->make(LuckLotteryServices::class);
  947. $luckLotteryServices->setCacheLotteryNum($uid, 'comment');
  948. $lottery = $luckLotteryServices->getFactorLottery(4);
  949. if (!$lottery) {
  950. return app('json')->successful(['to_lottery' => false]);
  951. }
  952. $lottery = $lottery->toArray();
  953. try {
  954. $luckLotteryServices->checkoutUserAuth($uid, (int)$lottery['id'], [], $lottery);
  955. $lottery_num = $luckLotteryServices->getLotteryNum($uid, (int)$lottery['id'], [], $lottery);
  956. if ($lottery_num > 0) return app('json')->successful(['to_lottery' => true]);
  957. } catch (\Exception $e) {
  958. return app('json')->successful(['to_lottery' => false]);
  959. }
  960. }
  961. /**
  962. * 订单统计数据
  963. * @param Request $request
  964. * @return mixed
  965. */
  966. public function data(Request $request)
  967. {
  968. return app('json')->successful($this->services->getOrderData((int)$request->uid()));
  969. }
  970. /**
  971. * 订单退款理由
  972. * @return mixed
  973. */
  974. public function refund_reason()
  975. {
  976. $reason = sys_config('stor_reason') ?: [];//退款理由
  977. $reason = str_replace("\r\n", "\n", $reason);//防止不兼容
  978. $reason = explode("\n", $reason);
  979. return app('json')->successful($reason);
  980. }
  981. /**
  982. * 获取退货商品列表
  983. * @param StoreOrderCartInfoServices $services
  984. * @param $id
  985. * @return mixed
  986. */
  987. public function refundCartInfo(Request $request, StoreOrderCartInfoServices $services, $id)
  988. {
  989. if (!$id) {
  990. return app('json')->fail('缺少发货ID');
  991. }
  992. [$cart_ids] = $request->postMore([
  993. ['cart_ids', []]
  994. ], true);
  995. $list = $services->getRefundCartList((int)$id);
  996. if ($cart_ids) {
  997. foreach ($cart_ids as $cart) {
  998. if (!isset($cart['cart_id']) || !$cart['cart_id'] || !isset($cart['cart_num']) || !$cart['cart_num'] || $cart['cart_num'] <= 0) {
  999. return app('json')->fail('请重新选择退款商品,或件数');
  1000. }
  1001. }
  1002. $cart_ids = array_combine(array_column($cart_ids, 'cart_id'), $cart_ids);
  1003. foreach ($list as &$item) {
  1004. if (isset($cart_ids[$item['cart_id']]['cart_num'])) $item['cart_num'] = $cart_ids[$item['cart_id']]['cart_num'];
  1005. }
  1006. }
  1007. return app('json')->success($list);
  1008. }
  1009. /**
  1010. * 获取退货商品列表
  1011. * @param StoreOrderCartInfoServices $services
  1012. * @param $id
  1013. * @return mixed
  1014. */
  1015. public function refundCartInfoList(Request $request)
  1016. {
  1017. [$cart_ids, $id] = $request->postMore([
  1018. ['cart_ids', []],
  1019. ['id', 0],
  1020. ], true);
  1021. if (!$id) {
  1022. return app('json')->fail('缺少发货ID');
  1023. }
  1024. return app('json')->success($this->services->refundCartInfoList((array)$cart_ids, (int)$id));
  1025. }
  1026. /**
  1027. * 用户申请退款
  1028. * @param Request $request
  1029. * @return mixed
  1030. */
  1031. public function applyRefund(Request $request, StoreOrderRefundServices $services, StoreOrderServices $storeOrderServices, $id)
  1032. {
  1033. if (!$id) {
  1034. return app('json')->fail('缺少参数!');
  1035. }
  1036. $data = $request->postMore([
  1037. ['text', ''],
  1038. ['refund_reason_wap_img', ''],
  1039. ['refund_reason_wap_explain', ''],
  1040. ['refund_type', 1],
  1041. ['refund_price', 0.00],
  1042. ['cart_ids', []]
  1043. ]);
  1044. if ($data['text'] == '') return app('json')->fail('参数错误!');
  1045. if ($data['cart_ids']) {
  1046. foreach ($data['cart_ids'] as $cart) {
  1047. if (!isset($cart['cart_id']) || !$cart['cart_id'] || !isset($cart['cart_num']) || !$cart['cart_num']) {
  1048. return app('json')->fail('请重新选择退款商品,或件数');
  1049. }
  1050. }
  1051. }
  1052. $order = $storeOrderServices->get($id);
  1053. $uid = (int)$request->uid();
  1054. if (!$order || $uid != $order['uid']) {
  1055. return app('json')->fail('订单不存在!');
  1056. }
  1057. if (!$order['paid']) {
  1058. return app('json')->fail('请先完成支付!');
  1059. }
  1060. // 开启 ERP 发货后不能申请退货
  1061. if (sys_config('erp_open') && $storeOrderServices->getDeliverNum($id, $order)) {
  1062. return app('json')->fail('订单已发货, 不能申请退货!');
  1063. }
  1064. $refundData = [
  1065. 'refund_reason' => $data['text'],
  1066. 'refund_explain' => $data['refund_reason_wap_explain'],
  1067. 'refund_img' => json_encode($data['refund_reason_wap_img'] != '' ? explode(',', $data['refund_reason_wap_img']) : []),
  1068. ];
  1069. $res = $services->applyRefund((int)$id, $uid, $order, $data['cart_ids'], (int)$data['refund_type'], (float)$data['refund_price'], $refundData);
  1070. if ($res)
  1071. return app('json')->successful('提交申请成功');
  1072. else
  1073. return app('json')->fail('提交失败');
  1074. }
  1075. /**
  1076. * 用户申请退款
  1077. * @param Request $request
  1078. * @return mixed
  1079. */
  1080. public function refund_verify(Request $request, StoreOrderRefundServices $services)
  1081. {
  1082. $data = $request->postMore([
  1083. ['text', ''],
  1084. ['refund_reason_wap_img', ''],
  1085. ['refund_reason_wap_explain', ''],
  1086. ['uni', ''],
  1087. ['refund_type', 1],
  1088. ['refund_price', 0.00],
  1089. ['cart_ids', []]
  1090. ]);
  1091. $uni = $data['uni'];
  1092. unset($data['uni']);
  1093. if (!$uni || $data['text'] == '') return app('json')->fail('参数错误!');
  1094. $refundData = [
  1095. 'refund_reason' => $data['text'],
  1096. 'refund_explain' => $data['refund_reason_wap_explain'],
  1097. 'refund_img' => json_encode($data['refund_reason_wap_img'] != '' ? explode(',', $data['refund_reason_wap_img']) : []),
  1098. ];
  1099. $order = $this->services->getUserOrderDetail($uni, (int)$request->uid());
  1100. if (!$order) {
  1101. return app('json')->fail('订单不存在!');
  1102. }
  1103. if (!$order['paid']) {
  1104. return app('json')->fail('请先完成支付!');
  1105. }
  1106. $uid = (int)$request->uid();
  1107. $res = $services->applyRefund((int)$order['id'], $uid, $order, $data['cart_ids'], (int)$data['refund_type'], (float)$data['refund_price'], $refundData);
  1108. if ($res)
  1109. return app('json')->successful('提交申请成功');
  1110. else
  1111. return app('json')->fail('提交失败');
  1112. }
  1113. /**
  1114. * 用户退货提交快递单号
  1115. * @param Request $request
  1116. * @param StoreOrderRefundServices $services
  1117. * @return mixed
  1118. */
  1119. public function refund_express(Request $request, StoreOrderRefundServices $services)
  1120. {
  1121. $data = $request->postMore([
  1122. ['id', ''],
  1123. ['refund_express', ''],
  1124. ['refund_phone', ''],
  1125. ['refund_express_name', ''],
  1126. ['refund_img', '', '', 'refund_goods_img'],
  1127. ['refund_explain', '', '', 'refund_goods_explain'],
  1128. ]);
  1129. if ($data['id'] == '') return app('json')->fail('参数错误!');
  1130. $data['refund_goods_img'] = json_encode($data['refund_goods_img'] != '' ? explode(',', $data['refund_goods_img']) : []);
  1131. $res = $services->editRefundExpress($data);
  1132. if ($res)
  1133. return app('json')->successful('提交成功');
  1134. else
  1135. return app('json')->fail('提交失败');
  1136. }
  1137. /**
  1138. * 订单取消 未支付的订单回退积分,回退优惠券,回退库存
  1139. * @param Request $request
  1140. * @return mixed
  1141. * @throws \think\db\exception\DataNotFoundException
  1142. * @throws \think\db\exception\ModelNotFoundException
  1143. * @throws \think\exception\DbException
  1144. */
  1145. public function cancel(Request $request)
  1146. {
  1147. [$id] = $request->postMore([
  1148. ['id', 0]
  1149. ], true);
  1150. if (!$id) return app('json')->fail('参数错误');
  1151. if ($this->services->cancelOrder($id, (int)$request->uid()))
  1152. return app('json')->successful('取消订单成功');
  1153. return app('json')->fail('取消订单失败');
  1154. }
  1155. /**
  1156. * 订单商品信息
  1157. * @param Request $request
  1158. * @return mixed
  1159. * @throws \think\db\exception\DataNotFoundException
  1160. * @throws \think\db\exception\ModelNotFoundException
  1161. * @throws \think\exception\DbException
  1162. */
  1163. public function product(Request $request, StoreOrderCartInfoServices $services)
  1164. {
  1165. [$unique] = $request->postMore([
  1166. ['unique', '']
  1167. ], true);
  1168. if (!$unique || !($cartInfo = $services->getOne(['unique' => $unique]))) return app('json')->fail('评价商品不存在!');
  1169. $cartInfo = $cartInfo->toArray();
  1170. $cartProduct = [];
  1171. $cartProduct['cart_num'] = $cartInfo['cart_info']['cart_num'];
  1172. $cartProduct['productInfo']['image'] = get_thumb_water($cartInfo['cart_info']['productInfo']['image'] ?? '');
  1173. $cartProduct['productInfo']['price'] = $cartInfo['cart_info']['productInfo']['price'] ?? 0;
  1174. $cartProduct['productInfo']['store_name'] = $cartInfo['cart_info']['productInfo']['store_name'] ?? '';
  1175. if (isset($cartInfo['cart_info']['productInfo']['attrInfo'])) {
  1176. $cartProduct['productInfo']['attrInfo']['product_id'] = $cartInfo['cart_info']['productInfo']['attrInfo']['product_id'] ?? '';
  1177. $cartProduct['productInfo']['attrInfo']['suk'] = $cartInfo['cart_info']['productInfo']['attrInfo']['suk'] ?? '';
  1178. $cartProduct['productInfo']['attrInfo']['price'] = $cartInfo['cart_info']['productInfo']['attrInfo']['price'] ?? '';
  1179. $cartProduct['productInfo']['attrInfo']['image'] = get_thumb_water($cartInfo['cart_info']['productInfo']['attrInfo']['image'] ?? '');
  1180. }
  1181. $cartProduct['product_id'] = $cartInfo['cart_info']['product_id'] ?? 0;
  1182. $cartProduct['type'] = $cartInfo['cart_info']['type'] ?? 0;
  1183. $cartProduct['activity_id'] = $cartInfo['cart_info']['activity_id'] ?? 0;
  1184. $cartProduct['order_id'] = $this->services->value(['id' => $cartInfo['oid']], 'order_id');
  1185. return app('json')->successful($cartProduct);
  1186. }
  1187. /**
  1188. * 门店线上支付订单详情
  1189. * @param Request $request
  1190. * @return mixed
  1191. * @throws \think\db\exception\DataNotFoundException
  1192. * @throws \think\db\exception\DbException
  1193. * @throws \think\db\exception\ModelNotFoundException
  1194. */
  1195. public function payCashierOrder(Request $request)
  1196. {
  1197. [$store_id] = $request->postMore([
  1198. ['store_id', '']
  1199. ], true);
  1200. $uid = $request->uid();
  1201. return app('json')->successful($this->services->payCashierOrder((int)$store_id, (int)$uid));
  1202. }
  1203. /**订单核销记录
  1204. * @param Request $request
  1205. * @param StoreOrderWriteOffServices $services
  1206. * @return \think\Response
  1207. * @throws \think\db\exception\DataNotFoundException
  1208. * @throws \think\db\exception\DbException
  1209. * @throws \think\db\exception\ModelNotFoundException
  1210. */
  1211. public function writeOffRecords(Request $request, StoreOrderWriteOffServices $services, $id)
  1212. {
  1213. if (!$id) return app('json')->fail('参数错误');
  1214. $uid = $request->uid();
  1215. return app('json')->successful($services->userOrderWriteOffRecords(['oid'=>$id, 'uid'=>$uid]));
  1216. }
  1217. }