StoreOrderController.php 59 KB

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