StoreOrderController.php 58 KB

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