StoreOrderRefundServices.php 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  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\services\order;
  12. use app\dao\order\StoreOrderRefundDao;
  13. use app\jobs\ProductLogJob;
  14. use app\services\activity\advance\StoreAdvanceServices;
  15. use app\services\activity\bargain\StoreBargainServices;
  16. use app\services\activity\combination\StoreCombinationServices;
  17. use app\services\activity\combination\StorePinkServices;
  18. use app\services\activity\seckill\StoreSeckillServices;
  19. use app\services\BaseServices;
  20. use app\services\activity\coupon\StoreCouponIssueUserServices;
  21. use app\services\activity\coupon\StoreCouponUserServices;
  22. use app\services\pay\PayServices;
  23. use app\services\product\product\StoreProductServices;
  24. use app\services\shipping\ExpressServices;
  25. use app\services\statistic\CapitalFlowServices;
  26. use app\services\user\UserBillServices;
  27. use app\services\user\UserBrokerageServices;
  28. use app\services\user\UserMoneyServices;
  29. use app\services\user\UserServices;
  30. use crmeb\services\AliPayService;
  31. use crmeb\services\CacheService;
  32. use crmeb\services\FormBuilder as Form;
  33. use crmeb\services\MiniProgramService;
  34. use crmeb\services\WechatService;
  35. use crmeb\services\workerman\ChannelService;
  36. use think\exception\ValidateException;
  37. use think\facade\Log;
  38. /**
  39. * 订单退款
  40. * Class StoreOrderRefundServices
  41. * @method getOrderRefundMoneyByWhere
  42. * @package app\services\order
  43. */
  44. class StoreOrderRefundServices extends BaseServices
  45. {
  46. /**
  47. * 订单services
  48. * @var StoreOrderServices
  49. */
  50. protected $storeOrderServices;
  51. /**
  52. * 构造方法
  53. * StoreOrderRefundServices constructor.
  54. * @param StoreOrderRefundDao $dao
  55. */
  56. public function __construct(StoreOrderRefundDao $dao, StoreOrderServices $storeOrderServices)
  57. {
  58. $this->dao = $dao;
  59. $this->storeOrderServices = $storeOrderServices;
  60. }
  61. /**
  62. * 订单退款表单
  63. * @param int $id
  64. * @return array
  65. * @throws \FormBuilder\Exception\FormBuilderException
  66. */
  67. public function refundOrderForm(int $id, $type = 'refund')
  68. {
  69. if ($type == 'refund') {//售后订单
  70. $orderRefund = $this->dao->get($id);
  71. if (!$orderRefund) {
  72. throw new ValidateException('未查到订单');
  73. }
  74. $order = $this->storeOrderServices->get((int)$orderRefund['store_order_id']);
  75. if (!$order) {
  76. throw new ValidateException('未查到订单');
  77. }
  78. if (!$order['paid']) {
  79. throw new ValidateException('未支付无法退款');
  80. }
  81. if ($orderRefund['refund_price'] > 0 && in_array($orderRefund['refund_type'], [1, 5])) {
  82. if ($orderRefund['refund_price'] <= $orderRefund['refunded_price']) {
  83. throw new ValidateException('订单已退款');
  84. }
  85. }
  86. $f[] = Form::input('order_id', '退款单号', $orderRefund->getData('order_id'))->disabled(true);
  87. $f[] = Form::number('refund_price', '退款金额', (float)bcsub((string)$orderRefund->getData('refund_price'), (string)$orderRefund->getData('refunded_price'), 2))->min(0)->required('请输入退款金额');
  88. return create_form('退款处理', $f, $this->url('/refund/refund/' . $id), 'PUT');
  89. } else {//订单主动退款
  90. $order = $this->storeOrderServices->get((int)$id);
  91. if (!$order) {
  92. throw new ValidateException('未查到订单');
  93. }
  94. if (!$order['paid']) {
  95. throw new ValidateException('未支付无法退款');
  96. }
  97. if ($order['pay_price'] > 0 && in_array($order['refund_status'], [0, 1])) {
  98. if ($order['pay_price'] <= $order['refund_price']) {
  99. throw new ValidateException('订单已退款');
  100. }
  101. }
  102. $f[] = Form::input('order_id', '退款单号', $order->getData('order_id'))->disabled(true);
  103. $f[] = Form::number('refund_price', '退款金额', (float)bcsub((string)$order->getData('pay_price'), (string)$order->getData('refund_price'), 2))->precision(2)->required('请输入退款金额');
  104. return create_form('退款处理', $f, $this->url('/order/refund/' . $id), 'PUT');
  105. }
  106. }
  107. /**
  108. * 同意退款:拆分退款单、退积分、佣金等
  109. * @param int $id
  110. * @param array $refundData
  111. * @return bool
  112. * @throws \think\db\exception\DataNotFoundException
  113. * @throws \think\db\exception\DbException
  114. * @throws \think\db\exception\ModelNotFoundException
  115. */
  116. public function agreeRefund(int $id, array $refundData)
  117. {
  118. $order = $this->transaction(function () use ($id, $refundData) {
  119. //退款拆分
  120. $orderRefundInfo = $this->dao->get($id);
  121. if (!$orderRefundInfo) throw new ValidateException('数据不存在');
  122. $cart_ids = [];
  123. if ($orderRefundInfo['cart_info']) {
  124. foreach ($orderRefundInfo['cart_info'] as $cart) {
  125. $cart_ids[] = [
  126. 'cart_id' => $cart['id'],
  127. 'cart_num' => $cart['cart_num'],
  128. ];
  129. }
  130. }
  131. if (!$cart_ids) return false;
  132. $orderInfo = $this->storeOrderServices->get($orderRefundInfo['store_order_id']);
  133. /** @var StoreOrderSplitServices $storeOrderSplitServices */
  134. $storeOrderSplitServices = app()->make(StoreOrderSplitServices::class);
  135. [$splitOrderInfo, $otherOrder] = $storeOrderSplitServices->equalSplit($orderRefundInfo['store_order_id'], $cart_ids, $orderInfo);
  136. //回退积分和优惠卷
  137. if (!$this->integralAndCouponBack($splitOrderInfo)) {
  138. throw new ValidateException('回退积分和优惠卷失败');
  139. }
  140. //退拼团
  141. if ($splitOrderInfo['pid'] == 0 && !$splitOrderInfo['pink_id']) {
  142. /** @var StorePinkServices $pinkServices */
  143. $pinkServices = app()->make(StorePinkServices::class);
  144. if (!$pinkServices->setRefundPink($splitOrderInfo)) {
  145. throw new ValidateException('拼团修改失败!');
  146. }
  147. }
  148. //退佣金
  149. /** @var UserBrokerageServices $userBrokerageServices */
  150. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  151. if (!$userBrokerageServices->orderRefundBrokerageBack($splitOrderInfo)) {
  152. throw new ValidateException('回退佣金失败');
  153. }
  154. //回退库存
  155. if ($splitOrderInfo['status'] == 0) {
  156. /** @var StoreOrderStatusServices $services */
  157. $services = app()->make(StoreOrderStatusServices::class);
  158. if (!$services->count(['oid' => $splitOrderInfo['id'], 'change_type' => 'refund_price'])) {
  159. $this->regressionStock($splitOrderInfo);
  160. }
  161. }
  162. //退金额
  163. if ($refundData['refund_price'] > 0) {
  164. if (!isset($refundData['refund_id']) || !$refundData['refund_id']) {
  165. mt_srand();
  166. $refundData['refund_id'] = $splitOrderInfo['order_id'] . rand(100, 999);
  167. }
  168. if ($splitOrderInfo['pid'] > 0) {//子订单
  169. $refundOrder = $this->storeOrderServices->get((int)$splitOrderInfo['pid']);
  170. $refundData['pay_price'] = $refundOrder['pay_price'];
  171. } else {
  172. $refundOrder = $splitOrderInfo;
  173. }
  174. switch ($refundOrder['pay_type']) {
  175. case PayServices::WEIXIN_PAY:
  176. $no = $refundOrder['order_id'];
  177. if ($refundOrder['trade_no']) {
  178. $no = $refundOrder['trade_no'];
  179. $refundData['type'] = 'trade_no';
  180. }
  181. if ($refundOrder['is_channel'] == 1) {
  182. //小程序退款
  183. MiniProgramService::payOrderRefund($no, $refundData);//小程序
  184. } else {
  185. //微信公众号退款
  186. WechatService::payOrderRefund($no, $refundData);//公众号
  187. }
  188. break;
  189. case PayServices::YUE_PAY:
  190. //余额退款
  191. if (!$this->yueRefund($refundOrder, $refundData)) {
  192. throw new ValidateException('余额退款失败');
  193. }
  194. break;
  195. case PayServices::ALIAPY_PAY:
  196. mt_srand();
  197. $refund_id = $refundData['refund_id'] ?? $refundOrder['order_id'] . rand(100, 999);
  198. //支付宝退款
  199. AliPayService::instance()->refund(strpos($refundOrder['trade_no'], '_') !== false ? $refundOrder['trade_no'] : $refundOrder['order_id'], floatval($refundData['refund_price']), $refund_id);
  200. break;
  201. }
  202. }
  203. //订单记录
  204. /** @var StoreOrderStatusServices $statusService */
  205. $statusService = app()->make(StoreOrderStatusServices::class);
  206. $statusService->save([
  207. 'oid' => $splitOrderInfo['id'],
  208. 'change_type' => 'refund_price',
  209. 'change_message' => '退款给用户:' . $refundData['refund_price'] . '元',
  210. 'change_time' => time()
  211. ]);
  212. $this->storeOrderServices->update($splitOrderInfo['id'], [
  213. 'status' => -2,
  214. 'refund_status' => 2,
  215. 'refund_type' => $orderRefundInfo['refund_type'],
  216. 'refund_express' => $orderRefundInfo['refund_express'],
  217. 'refund_express_name' => $orderRefundInfo['refund_express_name'],
  218. 'refund_reason_wap_img' => $orderRefundInfo['refund_img'],
  219. 'refund_reason_wap_explain' => $orderRefundInfo['refund_explain'],
  220. 'refund_reason_time' => $orderRefundInfo['refunded_time'],
  221. 'refund_reason_wap' => $orderRefundInfo['refund_reason'],
  222. 'refund_price' => $orderRefundInfo['refund_price'],
  223. ], 'id');
  224. $this->dao->update($id, ['store_order_id' => $splitOrderInfo['id']]);
  225. if ($otherOrder['id'] != 0 && $orderInfo['id'] != $otherOrder['id']) {//拆分生成新订单了
  226. //修改原订单还在申请的退款单
  227. $this->dao->update(['store_order_id' => $orderInfo['id']], ['store_order_id' => $otherOrder['id']]);
  228. }
  229. /** @var CapitalFlowServices $capitalFlowServices */
  230. $capitalFlowServices = app()->make(CapitalFlowServices::class);
  231. /** @var UserServices $userServices */
  232. $userServices = app()->make(UserServices::class);
  233. $userInfo = $userServices->get($splitOrderInfo['uid']);
  234. $splitOrderInfo['nickname'] = $userInfo['nickname'];
  235. $splitOrderInfo['phone'] = $userInfo['phone'];
  236. if ($splitOrderInfo['pay_type'] == 'alipay' || $splitOrderInfo['pay_type'] == 'weixin' || $splitOrderInfo['pay_type'] == 'offline') {
  237. $capitalFlowServices->setFlow($splitOrderInfo, 'refund');
  238. }
  239. return $splitOrderInfo;
  240. });
  241. //订单退款记录
  242. ProductLogJob::dispatch(['refund', ['uid' => $order['uid'], 'order_id' => $order['id']]]);
  243. //订单同意退款事件
  244. event('order.refund', [$refundData, $order, 'order_refund']);
  245. event('notice.notice', [['data' => $refundData, 'order' => $order], 'order_refund']);
  246. return true;
  247. }
  248. /**
  249. * 商家同意用户退货
  250. * @param $id
  251. * @return bool
  252. */
  253. public function agreeExpress($id)
  254. {
  255. $this->dao->update($id, ['refund_type' => 4], 'id');
  256. return true;
  257. }
  258. /**
  259. * 订单退款处理
  260. * @param int $type
  261. * @param $order
  262. * @param array $refundData
  263. * @return mixed
  264. */
  265. public function payOrderRefund(int $type, $order, array $refundData)
  266. {
  267. return $this->transaction(function () use ($type, $order, $refundData) {
  268. //回退积分和优惠卷
  269. if (!$this->integralAndCouponBack($order)) {
  270. throw new ValidateException('回退积分和优惠卷失败');
  271. }
  272. //虚拟商品优惠券退款处理
  273. if ($order['virtual_type'] == 2) {
  274. /** @var StoreCouponUserServices $couponUser */
  275. $couponUser = app()->make(StoreCouponUserServices::class);
  276. $res = $couponUser->delUserCoupon(['cid' => $order['virtual_info'], 'uid' => $order['uid'], 'status' => 0]);
  277. if (!$res) throw new ValidateException('购买的优惠券已使用或者已过期');
  278. /** @var StoreCouponIssueUserServices $couponIssueUser */
  279. $couponIssueUser = app()->make(StoreCouponIssueUserServices::class);
  280. $couponIssueUser->delIssueUserCoupon(['issue_coupon_id' => $order['virtual_info'], 'uid' => $order['uid']]);
  281. }
  282. //退拼团
  283. if ($type == 1) {
  284. /** @var StorePinkServices $pinkServices */
  285. $pinkServices = app()->make(StorePinkServices::class);
  286. if (!$pinkServices->setRefundPink($order)) {
  287. throw new ValidateException('拼团修改失败!');
  288. }
  289. }
  290. //退佣金
  291. /** @var UserBrokerageServices $userBrokerageServices */
  292. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  293. if (!$userBrokerageServices->orderRefundBrokerageBack($order)) {
  294. throw new ValidateException('回退佣金失败');
  295. }
  296. //回退库存
  297. if ($order['status'] == 0) {
  298. /** @var StoreOrderStatusServices $services */
  299. $services = app()->make(StoreOrderStatusServices::class);
  300. if (!$services->count(['oid' => $order['id'], 'change_type' => 'refund_price'])) {
  301. $this->regressionStock($order);
  302. }
  303. }
  304. //退金额
  305. if ($refundData['refund_price'] > 0) {
  306. if (!isset($refundData['refund_id']) || !$refundData['refund_id']) {
  307. mt_srand();
  308. $refundData['refund_id'] = $order['order_id'] . rand(100, 999);
  309. }
  310. if ($order['pid'] > 0) {//子订单
  311. $refundOrder = $this->storeOrderServices->get((int)$order['pid']);
  312. $refundData['pay_price'] = $refundOrder['pay_price'];
  313. } else {
  314. $refundOrder = $order;
  315. }
  316. switch ($refundOrder['pay_type']) {
  317. case PayServices::WEIXIN_PAY:
  318. $no = $refundOrder['order_id'];
  319. if ($refundOrder['trade_no']) {
  320. $no = $refundOrder['trade_no'];
  321. $refundData['type'] = 'trade_no';
  322. }
  323. if ($refundOrder['is_channel'] == 1) {
  324. //小程序退款
  325. MiniProgramService::payOrderRefund($no, $refundData);//小程序
  326. } else {
  327. //微信公众号退款
  328. WechatService::payOrderRefund($no, $refundData);//公众号
  329. }
  330. break;
  331. case PayServices::YUE_PAY:
  332. //余额退款
  333. if (!$this->yueRefund($refundOrder, $refundData)) {
  334. throw new ValidateException('余额退款失败');
  335. }
  336. break;
  337. case PayServices::ALIAPY_PAY:
  338. mt_srand();
  339. $refund_id = $refundData['refund_id'] ?? $refundOrder['order_id'] . rand(100, 999);
  340. //支付宝退款
  341. AliPayService::instance()->refund(strpos($refundOrder['trade_no'], '_') !== false ? $refundOrder['trade_no'] : $refundOrder['order_id'], floatval($refundData['refund_price']), $refund_id);
  342. break;
  343. }
  344. }
  345. //修改开票数据退款状态
  346. $orderInvoiceServices = app()->make(StoreOrderInvoiceServices::class);
  347. $orderInvoiceServices->update(['order_id' => $order['id']], ['is_refund' => 1]);
  348. });
  349. }
  350. /**
  351. * 余额退款
  352. * @param $order
  353. * @param array $refundData
  354. * @return bool
  355. */
  356. public function yueRefund($order, array $refundData)
  357. {
  358. /** @var UserServices $userServices */
  359. $userServices = app()->make(UserServices::class);
  360. $userMoney = $userServices->value(['uid' => $order['uid']], 'now_money');
  361. $res = $userServices->bcInc($order['uid'], 'now_money', $refundData['refund_price'], 'uid');
  362. /** @var UserMoneyServices $userMoneyServices */
  363. $userMoneyServices = app()->make(UserMoneyServices::class);
  364. return $res && $userMoneyServices->income('pay_product_refund', $order['uid'], $refundData['refund_price'], bcadd((string)$userMoney, (string)$refundData['refund_price'], 2), $order['id']);
  365. }
  366. /**
  367. * 回退积分和优惠卷
  368. * @param $order
  369. * @return bool
  370. */
  371. public function integralAndCouponBack($order)
  372. {
  373. $res = true;
  374. //回退优惠卷 拆分子订单不退优惠券
  375. if (!$order['pid'] && $order['coupon_id'] && $order['coupon_price']) {
  376. /** @var StoreCouponUserServices $coumonUserServices */
  377. $coumonUserServices = app()->make(StoreCouponUserServices::class);
  378. $res = $res && $coumonUserServices->recoverCoupon((int)$order['coupon_id']);
  379. }
  380. //回退积分
  381. $order = $this->regressionIntegral($order);
  382. /** @var StoreOrderStatusServices $statusService */
  383. $statusService = app()->make(StoreOrderStatusServices::class);
  384. $statusService->save([
  385. 'oid' => $order['id'],
  386. 'change_type' => 'integral_back',
  387. 'change_message' => '商品退积分',
  388. 'change_time' => time()
  389. ]);
  390. return $res && $order->save();
  391. }
  392. /**
  393. * 回退使用积分和赠送积分
  394. * @param $order
  395. * @return bool
  396. */
  397. public function regressionIntegral($order)
  398. {
  399. /** @var UserServices $userServices */
  400. $userServices = app()->make(UserServices::class);
  401. $userInfo = $userServices->get($order['uid'], ['integral']);
  402. if (!$userInfo) {
  403. $order->back_integral = $order->use_integral;
  404. return $order;
  405. }
  406. $integral = $userInfo['integral'];
  407. if ($order['status'] == -2 || $order['is_del']) {
  408. return $order;
  409. }
  410. $res1 = $res2 = $res3 = $res4 = true;
  411. //订单赠送积分
  412. /** @var UserBillServices $userBillServices */
  413. $userBillServices = app()->make(UserBillServices::class);
  414. $order_gain = $userBillServices->sum([
  415. 'category' => 'integral',
  416. 'type' => 'gain',
  417. 'link_id' => $order['id'],
  418. 'uid' => $order['uid']
  419. ], 'number');
  420. //商品赠送
  421. $product_gain = $userBillServices->sum([
  422. 'category' => 'integral',
  423. 'type' => 'product_gain',
  424. 'link_id' => $order['id'],
  425. 'uid' => $order['uid']
  426. ], 'number');
  427. $give_integral = $order_gain + $product_gain;
  428. if ($give_integral) {
  429. //判断订单是否已经回退积分
  430. $count = $userBillServices->count(['category' => 'integral', 'type' => 'integral_refund', 'link_id' => $order['id']]);
  431. if (!$count) {
  432. $res1 = $userServices->bcDec($order['uid'], 'integral', $give_integral);
  433. //记录赠送积分收回
  434. $integral = $integral - $give_integral;
  435. $res2 = $userBillServices->income('integral_refund', $order['uid'], $give_integral, $integral, $order['id']);
  436. }
  437. }
  438. //返还下单使用积分
  439. $use_integral = $order['use_integral'];
  440. if ($use_integral > 0) {
  441. $res3 = $userServices->bcInc($order['uid'], 'integral', $use_integral);
  442. //记录下单使用积分还回
  443. $res4 = $userBillServices->income('pay_product_integral_back', $order['uid'], (int)$use_integral, $integral + $use_integral, $order['id']);
  444. }
  445. if (!($res1 && $res2 && $res3 && $res4)) {
  446. throw new ValidateException('回退积分增加失败');
  447. }
  448. if ($use_integral > $give_integral) {
  449. $order->back_integral = bcsub($use_integral, $give_integral, 2);
  450. }
  451. return $order;
  452. }
  453. /**
  454. * 回退库存
  455. * @param $order
  456. * @return bool
  457. */
  458. public function regressionStock($order)
  459. {
  460. if ($order['status'] == -2 || $order['is_del']) return true;
  461. $combination_id = $order['combination_id'];
  462. $seckill_id = $order['seckill_id'];
  463. $bargain_id = $order['bargain_id'];
  464. $advance_id = $order['advance_id'];
  465. $res5 = true;
  466. /** @var StoreOrderCartInfoServices $cartServices */
  467. $cartServices = app()->make(StoreOrderCartInfoServices::class);
  468. /** @var StoreProductServices $services */
  469. $services = app()->make(StoreProductServices::class);
  470. /** @var StoreSeckillServices $seckillServices */
  471. $seckillServices = app()->make(StoreSeckillServices::class);
  472. /** @var StoreCombinationServices $pinkServices */
  473. $pinkServices = app()->make(StoreCombinationServices::class);
  474. /** @var StoreBargainServices $bargainServices */
  475. $bargainServices = app()->make(StoreBargainServices::class);
  476. /** @var StoreAdvanceServices $advanceServices */
  477. $advanceServices = app()->make(StoreAdvanceServices::class);
  478. $cartInfo = $cartServices->getCartInfoList(['cart_id' => $order['cart_id']], ['cart_info']);
  479. foreach ($cartInfo as $cart) {
  480. $cart['cart_info'] = is_array($cart['cart_info']) ? $cart['cart_info'] : json_decode($cart['cart_info'], true);
  481. //增库存减销量
  482. $unique = isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '';
  483. $cart_num = (int)$cart['cart_info']['cart_num'];
  484. $type = 0;
  485. if ($combination_id) {
  486. $type = 3;
  487. $res5 = $res5 && $pinkServices->incCombinationStock($cart_num, (int)$combination_id, $unique);
  488. } else if ($seckill_id) {
  489. $type = 1;
  490. $res5 = $res5 && $seckillServices->incSeckillStock($cart_num, (int)$seckill_id, $unique);
  491. } else if ($bargain_id) {
  492. $type = 2;
  493. $res5 = $res5 && $bargainServices->incBargainStock($cart_num, (int)$bargain_id, $unique);
  494. } else {
  495. $res5 = $res5 && $services->incProductStock($cart_num, (int)$cart['cart_info']['productInfo']['id'], $unique);
  496. }
  497. if ($type) CacheService::setStock($unique, $cart_num, $type, false);
  498. }
  499. return $res5;
  500. }
  501. /**
  502. * 同意退款成功发送模板消息和记录订单状态
  503. * @param $data
  504. * @param $order
  505. * @param $refund_price
  506. * @param $id
  507. */
  508. public function storeProductOrderRefundY($data, $order, $refund_price)
  509. {
  510. /** @var StoreOrderStatusServices $statusService */
  511. $statusService = app()->make(StoreOrderStatusServices::class);
  512. $statusService->save([
  513. 'oid' => $order['id'],
  514. 'change_type' => 'refund_price',
  515. 'change_message' => '退款给用户:' . $refund_price . '元',
  516. 'change_time' => time()
  517. ]);
  518. /** @var CapitalFlowServices $capitalFlowServices */
  519. $capitalFlowServices = app()->make(CapitalFlowServices::class);
  520. /** @var UserServices $userServices */
  521. $userServices = app()->make(UserServices::class);
  522. $userInfo = $userServices->get($order['uid']);
  523. $order['nickname'] = $userInfo['nickname'];
  524. $order['phone'] = $userInfo['phone'];
  525. if ($order['pay_type'] == 'alipay' || $order['pay_type'] == 'weixin' || $order['pay_type'] == 'offline') {
  526. $capitalFlowServices->setFlow($order, 'refund');
  527. }
  528. event('notice.notice', [['data' => $data, 'order' => $order], 'order_refund']);
  529. }
  530. /**
  531. * 同意退款退款失败写入订单记录
  532. * @param int $id
  533. * @param $refund_price
  534. */
  535. public function storeProductOrderRefundYFasle(int $id, $refund_price)
  536. {
  537. /** @var StoreOrderStatusServices $statusService */
  538. $statusService = app()->make(StoreOrderStatusServices::class);
  539. $statusService->save([
  540. 'oid' => $id,
  541. 'change_type' => 'refund_price',
  542. 'change_message' => '退款给用户:' . $refund_price . '元失败',
  543. 'change_time' => time()
  544. ]);
  545. }
  546. /**
  547. * 不退款记录订单变更状态
  548. * @param int $id
  549. * @param string $refundReason
  550. */
  551. public function storeProductOrderRefundNo(int $id, string $refundReason)
  552. {
  553. /** @var StoreOrderStatusServices $statusService */
  554. $statusService = app()->make(StoreOrderStatusServices::class);
  555. $statusService->save([
  556. 'oid' => $id,
  557. 'change_type' => 'refund_n',
  558. 'change_message' => '不退款原因:' . $refundReason,
  559. 'change_time' => time()
  560. ]);
  561. }
  562. /**
  563. * 不退款表单
  564. * @param int $id
  565. * @return array
  566. * @throws \FormBuilder\Exception\FormBuilderException
  567. */
  568. public function noRefundForm(int $id)
  569. {
  570. $order = $this->dao->get($id);
  571. if (!$order) {
  572. throw new ValidateException('Data does not exist!');
  573. }
  574. $f[] = Form::input('order_id', '不退款单号', $order->getData('order_id'))->disabled(true);
  575. $f[] = Form::input('refund_reason', '不退款原因')->type('textarea')->required('请填写不退款原因');
  576. return create_form('不退款原因', $f, $this->url('refund/no_refund/' . $id), 'PUT');
  577. }
  578. /**
  579. * 拒绝退款
  580. * @param int $id
  581. * @param array $data
  582. * @param array $orderRefundInfo
  583. * @return bool
  584. * @throws \think\db\exception\DataNotFoundException
  585. * @throws \think\db\exception\DbException
  586. * @throws \think\db\exception\ModelNotFoundException
  587. */
  588. public function refuseRefund(int $id, array $data, $orderRefundInfo = [])
  589. {
  590. if (!$orderRefundInfo) {
  591. $orderRefundInfo = $this->dao->get(['id' => $id, 'is_cancel' => 0]);
  592. }
  593. if (!$orderRefundInfo) {
  594. throw new ValidateException('售后订单不存在');
  595. }
  596. /** @var StoreOrderServices $storeOrderServices */
  597. $storeOrderServices = app()->make(StoreOrderServices::class);
  598. $this->transaction(function () use ($id, $data, $orderRefundInfo, $storeOrderServices) {
  599. //处理售后订单
  600. $this->dao->update($id, $data);
  601. //处理订单
  602. $oid = (int)$orderRefundInfo['store_order_id'];
  603. $storeOrderServices->update($oid, ['refund_status' => 0, 'refund_type' => 3]);
  604. //处理订单商品cart_info
  605. $this->cancelOrderRefundCartInfo($id, $oid, $orderRefundInfo);
  606. //记录
  607. /** @var StoreOrderStatusServices $statusService */
  608. $statusService = app()->make(StoreOrderStatusServices::class);
  609. $statusService->save([
  610. 'oid' => $id,
  611. 'change_type' => 'refund_n',
  612. 'change_message' => '不退款原因:' . ($data['refund_reason'] ?? ''),
  613. 'change_time' => time()
  614. ]);
  615. });
  616. event('notice.notice', [['orderInfo' => $orderRefundInfo], 'send_order_refund_no_status']);
  617. return true;
  618. }
  619. /**
  620. * 退积分表单创建
  621. * @param int $id
  622. * @return array
  623. * @throws \FormBuilder\Exception\FormBuilderException
  624. */
  625. public function refundIntegralForm(int $id)
  626. {
  627. if (!$orderInfo = $this->dao->get($id))
  628. throw new ValidateException('订单不存在');
  629. if ($orderInfo->use_integral < 0 || $orderInfo->use_integral == $orderInfo->back_integral)
  630. throw new ValidateException('积分已退或者积分为零无法再退');
  631. if (!$orderInfo->paid)
  632. throw new ValidateException('未支付无法退积分');
  633. $f[] = Form::input('order_id', '退款单号', $orderInfo->getData('order_id'))->disabled(1);
  634. $f[] = Form::number('use_integral', '使用的积分', (float)$orderInfo->getData('use_integral'))->min(0)->disabled(1);
  635. $f[] = Form::number('use_integrals', '已退积分', (float)$orderInfo->getData('back_integral'))->min(0)->disabled(1);
  636. $f[] = Form::number('back_integral', '可退积分', (float)bcsub($orderInfo->getData('use_integral'), $orderInfo->getData('back_integral')))->min(0)->precision(0)->required('请输入可退积分');
  637. return create_form('退积分', $f, $this->url('/order/refund_integral/' . $id), 'PUT');
  638. }
  639. /**
  640. * 单独退积分处理
  641. * @param $orderInfo
  642. * @param $back_integral
  643. */
  644. public function refundIntegral($orderInfo, $back_integral)
  645. {
  646. /** @var UserServices $userServices */
  647. $userServices = app()->make(UserServices::class);
  648. $integral = $userServices->value(['uid' => $orderInfo['uid']], 'integral');
  649. return $this->transaction(function () use ($userServices, $orderInfo, $back_integral, $integral) {
  650. $res1 = $userServices->bcInc($orderInfo['uid'], 'integral', $back_integral, 'uid');
  651. /** @var UserBillServices $userBillServices */
  652. $userBillServices = app()->make(UserBillServices::class);
  653. $res2 = $userBillServices->income('pay_product_integral_back', $orderInfo['uid'], (int)$back_integral, $integral + $back_integral, $orderInfo['id']);
  654. /** @var StoreOrderStatusServices $statusService */
  655. $statusService = app()->make(StoreOrderStatusServices::class);
  656. $res3 = $statusService->save([
  657. 'oid' => $orderInfo['id'],
  658. 'change_type' => 'integral_back',
  659. 'change_message' => '商品退积分:' . $back_integral,
  660. 'change_time' => time()
  661. ]);
  662. $res4 = $orderInfo->save();
  663. $res = $res1 && $res2 && $res3 && $res4;
  664. if (!$res) {
  665. throw new ValidateException('订单退积分失败');
  666. }
  667. return true;
  668. });
  669. }
  670. /**
  671. * 订单申请退款
  672. * @param $uni
  673. * @param $uid
  674. * @param string $refundReasonWap
  675. * @param string $refundReasonWapExplain
  676. * @param array $refundReasonWapImg
  677. * @return bool|void
  678. */
  679. public function orderApplyRefund($order, string $refundReasonWap = '', string $refundReasonWapExplain = '', array $refundReasonWapImg = [], int $refundType = 0, $cart_id = 0, $refund_num = 0)
  680. {
  681. if (!$order) {
  682. throw new ValidateException('支付订单不存在!');
  683. }
  684. if ($order['refund_status'] == 2) {
  685. throw new ValidateException('订单已退款!');
  686. }
  687. if ($order['refund_status'] == 1) {
  688. throw new ValidateException('正在申请退款中!');
  689. }
  690. if ($order['total_num'] < $refund_num) {
  691. throw new ValidateException('退款件数大于订单件数!');
  692. }
  693. $this->transaction(function () use ($order, $refundReasonWap, $refundReasonWapExplain, $refundReasonWapImg, $refundType, $refund_num, $cart_id) {
  694. $status = 0;
  695. $order_id = (int)$order['id'];
  696. if ($cart_id) {
  697. /** @var StoreOrderCartInfoServices $storeOrderCartInfoServices */
  698. $storeOrderCartInfoServices = app()->make(StoreOrderCartInfoServices::class);
  699. $cart_ids = [];
  700. $cart_ids[0] = ['cart_id' => $cart_id, 'cart_num' => $refund_num];
  701. /** @var StoreOrderSplitServices $storeOrderSplitServices */
  702. $storeOrderSplitServices = app()->make(StoreOrderSplitServices::class);
  703. //拆单
  704. $status = $order['status'];
  705. $order = $storeOrderSplitServices->split($order_id, $cart_ids, $order);
  706. } elseif (in_array($order['pid'], [0, -1]) && $this->storeOrderServices->count(['pid' => $order_id])) {
  707. /** @var StoreOrderCartInfoServices $storeOrderCartInfoServices */
  708. $storeOrderCartInfoServices = app()->make(StoreOrderCartInfoServices::class);
  709. $cart_info = $storeOrderCartInfoServices->getSplitCartList($order_id, 'cart_info');
  710. if (!$cart_info) {
  711. throw new ValidateException('该订单已全部拆分发货,请去自订单申请');
  712. }
  713. $cart_ids = [];
  714. foreach ($cart_info as $key => $cart) {
  715. $cart_ids[$key] = ['cart_id' => $cart['id'], 'cart_num' => $refund_num];
  716. }
  717. /** @var StoreOrderSplitServices $storeOrderSplitServices */
  718. $storeOrderSplitServices = app()->make(StoreOrderSplitServices::class);
  719. //拆单
  720. $status = $order['status'];
  721. $order = $storeOrderSplitServices->split($order_id, $cart_ids, $order);
  722. }
  723. $data = [
  724. 'refund_status' => 1,
  725. 'refund_reason_time' => time(),
  726. 'refund_reason_wap' => $refundReasonWap,
  727. 'refund_reason_wap_explain' => $refundReasonWapExplain,
  728. 'refund_reason_wap_img' => json_encode($refundReasonWapImg),
  729. 'refund_type' => $refundType
  730. ];
  731. if ($status) $data['status'] = $status;
  732. /** @var StoreOrderStatusServices $statusService */
  733. $statusService = app()->make(StoreOrderStatusServices::class);
  734. $res1 = false !== $statusService->save([
  735. 'oid' => $order['id'],
  736. 'change_type' => 'apply_refund',
  737. 'change_message' => '用户申请退款,原因:' . $refundReasonWap,
  738. 'change_time' => time()
  739. ]);
  740. $res2 = false !== $this->storeOrderServices->update(['id' => $order['id']], $data);
  741. $res = $res1 && $res2;
  742. if (!$res)
  743. throw new ValidateException('申请退款失败!');
  744. //子订单申请退款
  745. if ($order['pid'] > 0) {
  746. $p_order = $this->storeOrderServices->get((int)$order['pid']);
  747. $split_order = $this->storeOrderServices->count(['pid' => $order['pid'], 'refund_status' => 0]);
  748. if ($split_order || (!$split_order && $p_order['status'] == 4) || $cart_id) {
  749. $this->storeOrderServices->update(['id' => $order['pid']], ['refund_status' => 3, 'refund_reason_time' => time()]);
  750. } else {
  751. $this->storeOrderServices->update(['id' => $order['pid']], ['refund_status' => 4, 'refund_reason_time' => time()]);
  752. }
  753. } else {
  754. /** @var StoreOrderCartInfoServices $orderCartInfoService */
  755. $orderCartInfoService = app()->make(StoreOrderCartInfoServices::class);
  756. // if (!$orderCartInfoService->getSplitCartList()) {
  757. //
  758. // }
  759. }
  760. });
  761. try {
  762. ChannelService::instance()->send('NEW_REFUND_ORDER', ['order_id' => $order['order_id']]);
  763. } catch (\Exception $e) {
  764. }
  765. //提醒推送
  766. event('notice.notice', [['order' => $order], 'send_order_apply_refund']);
  767. return true;
  768. }
  769. /**
  770. * 写入退款快递单号
  771. * @param $order
  772. * @param $express
  773. * @return bool
  774. */
  775. public function editRefundExpress($data)
  776. {
  777. $this->transaction(function () use ($data) {
  778. $id = $data['id'];
  779. $data['refund_type'] = 5;
  780. /** @var StoreOrderStatusServices $statusService */
  781. $statusService = app()->make(StoreOrderStatusServices::class);
  782. $res1 = false !== $statusService->save([
  783. 'oid' => $id,
  784. 'change_type' => 'refund_express',
  785. 'change_message' => '用户已退货,订单号:' . $data['refund_express'],
  786. 'change_time' => time()
  787. ]);
  788. if ($data['refund_img'] != '') unset($data['refund_img']);
  789. if ($data['refund_explain'] != '') unset($data['refund_explain']);
  790. $res2 = false !== $this->dao->update(['id' => $id], $data);
  791. $res = $res1 && $res2;
  792. if (!$res)
  793. throw new ValidateException('提交失败!');
  794. });
  795. return true;
  796. }
  797. /**
  798. * 订单申请退款
  799. * @param int $id
  800. * @param int $uid
  801. * @param array $order
  802. * @param array $cart_ids
  803. * @param int $refundType
  804. * @param float $refundPrice
  805. * @param array $refundData
  806. * @param int $isPink
  807. * @return mixed
  808. * @throws \Psr\SimpleCache\InvalidArgumentException
  809. * @throws \think\db\exception\DataNotFoundException
  810. * @throws \think\db\exception\DbException
  811. * @throws \think\db\exception\ModelNotFoundException
  812. */
  813. public function applyRefund(int $id, int $uid, $order = [], array $cart_ids = [], int $refundType = 0, float $refundPrice = 0.00, array $refundData = [], $isPink = 0)
  814. {
  815. /** 查询订单是否存在 */
  816. /** @var StoreOrderServices $orderServices */
  817. $orderServices = app()->make(StoreOrderServices::class);
  818. if (!$order) {
  819. $order = $orderServices->get($id);
  820. }
  821. if (!$order) {
  822. throw new ValidateException('支付订单不存在!');
  823. }
  824. $is_now = $this->dao->getCount([
  825. ['store_order_id', '=', $id],
  826. ['refund_type', 'in', [1, 2, 4, 5]],
  827. ['is_cancel', '=', 0],
  828. ['is_del', '=', 0],
  829. ['is_pink_cancel', '=', 0]
  830. ]);
  831. if ($is_now) throw new ValidateException('存在待处理退款单,请稍后再试');
  832. $refund_num = $order['total_num'];
  833. $refund_price = $order['pay_price'];
  834. /** @var StoreOrderCartInfoServices $storeOrderCartInfoServices */
  835. $storeOrderCartInfoServices = app()->make(StoreOrderCartInfoServices::class);
  836. //退部分
  837. $cartInfo = [];
  838. $cartInfos = $storeOrderCartInfoServices->getCartColunm(['oid' => $id], 'id,cart_id,cart_num,refund_num,cart_info');
  839. if ($cart_ids) {
  840. $cartInfo = array_combine(array_column($cartInfos, 'cart_id'), $cartInfos);
  841. $refund_num = 0;
  842. foreach ($cart_ids as $cart) {
  843. if ($cart['cart_num'] + $cartInfo[$cart['cart_id']]['refund_num'] > $cartInfo[$cart['cart_id']]['cart_num']) {
  844. throw new ValidateException('超出订单中商品数量,请重新选择!');
  845. }
  846. $refund_num = bcadd((string)$refund_num, (string)$cart['cart_num'], 0);
  847. }
  848. //总共申请多少件
  849. $total_num = array_sum(array_column($cart_ids, 'cart_num'));
  850. if ($total_num < $order['total_num']) {
  851. /** @var StoreOrderSplitServices $storeOrderSpliteServices */
  852. $storeOrderSpliteServices = app()->make(StoreOrderSplitServices::class);
  853. $cartInfos = $storeOrderSpliteServices->getSplitOrderCartInfo($id, $cart_ids, $order);
  854. $total_price = $pay_postage = 0;
  855. foreach ($cartInfos as $cart) {
  856. $_info = is_string($cart['cart_info']) ? json_decode($cart['cart_info'], true) : $cart['cart_info'];
  857. $total_price = bcadd((string)$total_price, bcmul((string)($_info['truePrice'] ?? 0), (string)$cart['cart_num'], 4), 2);
  858. $pay_postage = bcadd((string)$pay_postage, (string)($_info['postage_price'] ?? 0), 2);
  859. }
  860. $refund_pay_price = bcadd((string)$total_price, (string)$pay_postage, 2);
  861. //订单实际支付金额
  862. $order_pay_price = bcsub((string)bcadd((string)$order['total_price'], (string)$order['pay_postage'], 2), (string)bcadd((string)$order['deduction_price'], (string)$order['coupon_price'], 2), 2);
  863. if ($order_pay_price != $order['pay_price'] && $refund_pay_price != $order_pay_price) {//有改价
  864. $refund_price = bcmul((string)bcdiv((string)$order['pay_price'], (string)$order_pay_price, 4), (string)$refund_pay_price, 2);
  865. } else {
  866. $refund_price = $refund_pay_price;
  867. }
  868. }
  869. } else {
  870. foreach ($cartInfos as $cart) {
  871. if ($cart['refund_num'] > 0) {
  872. throw new ValidateException('超出订单中商品数量,请重新选择!');
  873. }
  874. }
  875. }
  876. foreach ($cartInfos as &$cart) {
  877. $cart['cart_info'] = is_string($cart['cart_info']) ? json_decode($cart['cart_info'], true) : $cart['cart_info'];
  878. }
  879. $refundData['uid'] = $uid;
  880. $refundData['store_id'] = $order['store_id'];
  881. $refundData['store_order_id'] = $id;
  882. $refundData['refund_num'] = $refund_num;
  883. $refundData['refund_type'] = $refundType;
  884. $refundData['refund_price'] = $refund_price;
  885. $refundData['order_id'] = app()->make(StoreOrderCreateServices::class)->getNewOrderId('');
  886. $refundData['add_time'] = time();
  887. $refundData['cart_info'] = json_encode(array_column($cartInfos, 'cart_info'));
  888. $refundData['is_pink_cancel'] = $isPink;
  889. $res = $this->transaction(function () use ($id, $order, $cart_ids, $refundData, $storeOrderCartInfoServices, $cartInfo, $orderServices, $cartInfos) {
  890. /** @var StoreOrderStatusServices $statusService */
  891. $statusService = app()->make(StoreOrderStatusServices::class);
  892. $res1 = false !== $statusService->save([
  893. 'oid' => $order['id'],
  894. 'change_type' => 'apply_refund',
  895. 'change_message' => '用户申请退款,原因:' . $refundData['refund_reason'],
  896. 'change_time' => time()
  897. ]);
  898. $res2 = true;
  899. //添加退款数据
  900. /** @var StoreOrderRefundServices $storeOrderRefundServices */
  901. $storeOrderRefundServices = app()->make(StoreOrderRefundServices::class);
  902. $res3 = $storeOrderRefundServices->save($refundData);
  903. if (!$res3) {
  904. throw new ValidateException('添加退款申请失败');
  905. }
  906. $res4 = true;
  907. if ($cart_ids) {
  908. //修改订单商品退款信息
  909. foreach ($cart_ids as $cart) {
  910. $res4 = $res4 && $storeOrderCartInfoServices->update(['oid' => $id, 'cart_id' => $cart['cart_id']], ['refund_num' => (($cartInfo[$cart['cart_id']]['refund_num'] ?? 0) + $cart['cart_num'])]);
  911. }
  912. } else {
  913. //修改原订单状态
  914. $res2 = false !== $orderServices->update(['id' => $order['id']], ['refund_status' => 1]);
  915. foreach ($cartInfos as $cart) {
  916. $res4 = $res4 && $storeOrderCartInfoServices->update(['oid' => $id, 'cart_id' => $cart['cart_id']], ['refund_num' => $cart['cart_num']]);
  917. }
  918. }
  919. return $res1 && $res2 && $res3 && $res4;
  920. });
  921. $storeOrderCartInfoServices->clearOrderCartInfo($order['id']);
  922. try {
  923. ChannelService::instance()->send('NEW_REFUND_ORDER', ['order_id' => $order['order_id']]);
  924. } catch (\Exception $e) {
  925. }
  926. //申请退款事件
  927. event('order.orderRefund', [$order]);
  928. return $res;
  929. }
  930. /**
  931. * 获取某个字段总金额
  932. * @param $cartInfo
  933. * @param string $key
  934. * @param bool $is_unit
  935. * @return int|string
  936. */
  937. public function getOrderSumPrice($cartInfo, $key = 'truePrice', $is_unit = true)
  938. {
  939. $SumPrice = 0;
  940. foreach ($cartInfo as $cart) {
  941. if (isset($cart['cart_info'])) $cart = $cart['cart_info'];
  942. if ($is_unit) {
  943. $SumPrice = bcadd($SumPrice, bcmul($cart['cart_num'] ?? 1, $cart[$key] ?? 0, 2), 2);
  944. } else {
  945. $SumPrice = bcadd($SumPrice, $cart[$key] ?? 0, 2);
  946. }
  947. }
  948. return $SumPrice;
  949. }
  950. /**
  951. * 退款订单列表
  952. * @param $where
  953. * @return array
  954. */
  955. public function refundList($where)
  956. {
  957. [$page, $limit] = $this->getPageValue();
  958. $list = $this->dao->getList($where, $page, $limit);
  959. $count = $this->dao->count($where);
  960. if ($list) {
  961. foreach ($list as &$item) {
  962. $item['paid'] = 1;
  963. $item['add_time'] = isset($item['add_time']) ? date('Y-m-d H:i', (int)$item['add_time']) : '';
  964. $item['cartInfo'] = $item['cart_info'];
  965. if (in_array($item['refund_type'], [1, 2, 4, 5])) {
  966. $item['refund_status'] = 1;
  967. } elseif ($item['refund_type'] == 6) {
  968. $item['refund_status'] = 2;
  969. } elseif ($item['refund_type'] == 3) {
  970. $item['refund_status'] = 3;
  971. }
  972. foreach ($item['cart_info'] as $items) {
  973. $item['_info'][]['cart_info'] = $items;
  974. }
  975. $item['total_num'] = $item['refund_num'];
  976. $item['pay_price'] = $item['refund_price'];
  977. $item['pay_postage'] = floatval($this->getOrderSumPrice($item['cart_info'], 'postage_price', false));
  978. if (in_array($item['refund_type'], [1, 2, 4, 5])) {
  979. $_type = -1;
  980. $_title = '申请退款中';
  981. } elseif ($item['refund_type'] == 3) {
  982. $_type = -3;
  983. $_title = '拒绝退款';
  984. } else {
  985. $_type = -2;
  986. $_title = '已退款';
  987. }
  988. $item['_status'] = [
  989. '_type' => $_type,
  990. '_title' => $_title,
  991. ];
  992. }
  993. }
  994. $data['list'] = $list;
  995. $data['count'] = $count;
  996. $del_where = ['is_cancel' => 0];
  997. $data['num'] = [
  998. 0 => ['name' => '全部', 'num' => $this->dao->count($del_where)],
  999. 1 => ['name' => '仅退款', 'num' => $this->dao->count($del_where + ['refund_type' => 1])],
  1000. 2 => ['name' => '退货退款', 'num' => $this->dao->count($del_where + ['refund_type' => 2])],
  1001. 3 => ['name' => '拒绝退款', 'num' => $this->dao->count($del_where + ['refund_type' => 3])],
  1002. 4 => ['name' => '商品待退货', 'num' => $this->dao->count($del_where + ['refund_type' => 4])],
  1003. 5 => ['name' => '退货待收货', 'num' => $this->dao->count($del_where + ['refund_type' => 5])],
  1004. 6 => ['name' => '已退款', 'num' => $this->dao->count($del_where + ['refund_type' => 6])]
  1005. ];
  1006. return $data;
  1007. }
  1008. /**
  1009. * 退款订单详情
  1010. * @param $uni
  1011. * @return mixed
  1012. */
  1013. public function refundDetail($uni)
  1014. {
  1015. if (!strlen(trim($uni))) throw new ValidateException('参数错误');
  1016. $order = $this->dao->get(['order_id' => $uni], ['*']);
  1017. if (!$order) throw new ValidateException('订单不存在');
  1018. $order = $order->toArray();
  1019. /** @var StoreOrderServices $orderServices */
  1020. $orderServices = app()->make(StoreOrderServices::class);
  1021. $orderInfo = $orderServices->get($order['store_order_id']);
  1022. /** @var UserServices $userServices */
  1023. $userServices = app()->make(UserServices::class);
  1024. $userInfo = $userServices->get($order['uid']);
  1025. $order['mapKey'] = sys_config('tengxun_map_key');
  1026. $order['yue_pay_status'] = (int)sys_config('balance_func_status') && (int)sys_config('yue_pay_status') == 1 ? (int)1 : (int)2;//余额支付 1 开启 2 关闭
  1027. $order['pay_weixin_open'] = (int)sys_config('pay_weixin_open') ?? 0;//微信支付 1 开启 0 关闭
  1028. $order['ali_pay_status'] = sys_config('ali_pay_status') ? true : false;//支付包支付 1 开启 0 关闭
  1029. $orderData = $order;
  1030. $orderData['store_order_sn'] = $orderInfo['order_id'];
  1031. $orderData['cartInfo'] = $orderData['cart_info'];
  1032. //核算优惠金额
  1033. $vipTruePrice = 0;
  1034. $total_price = 0;
  1035. foreach ($orderData['cartInfo'] ?? [] as $key => &$cart) {
  1036. if (!isset($cart['sum_true_price'])) $cart['sum_true_price'] = bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 2);
  1037. $cart['vip_sum_truePrice'] = bcmul($cart['vip_truePrice'], $cart['cart_num'] ? $cart['cart_num'] : 1, 2);
  1038. $vipTruePrice = bcadd((string)$vipTruePrice, (string)$cart['vip_sum_truePrice'], 2);
  1039. if (isset($order['split']) && $order['split']) {
  1040. $orderData['cartInfo'][$key]['cart_num'] = $cart['surplus_num'];
  1041. if (!$cart['surplus_num']) unset($orderData['cartInfo'][$key]);
  1042. }
  1043. $total_price = bcadd($total_price, $cart['sum_true_price'], 2);
  1044. }
  1045. $orderData['use_integral'] = $this->getOrderSumPrice($orderData['cartInfo'], 'use_integral', false);
  1046. $orderData['integral_price'] = $this->getOrderSumPrice($orderData['cartInfo'], 'integral_price', false);
  1047. $orderData['coupon_price'] = $this->getOrderSumPrice($orderData['cartInfo'], 'coupon_price', false);
  1048. $orderData['deduction_price'] = $this->getOrderSumPrice($orderData['cartInfo'], 'integral_price', false);
  1049. $total_price = bcadd((string)$total_price, (string)bcadd((string)$orderData['deduction_price'], (string)$orderData['coupon_price'], 2), 2);
  1050. $orderData['vip_true_price'] = $vipTruePrice;
  1051. $orderData['postage_price'] = 0;
  1052. $orderData['pay_postage'] = $this->getOrderSumPrice($orderData['cart_info'], 'postage_price', false);
  1053. $orderData['member_price'] = 0;
  1054. $orderData['routine_contact_type'] = sys_config('routine_contact_type', 0);
  1055. switch ($orderInfo['pay_type']) {
  1056. case PayServices::WEIXIN_PAY:
  1057. $pay_type_name = '微信支付';
  1058. break;
  1059. case PayServices::YUE_PAY:
  1060. $pay_type_name = '余额支付';
  1061. break;
  1062. case PayServices::OFFLINE_PAY:
  1063. $pay_type_name = '线下支付';
  1064. break;
  1065. case PayServices::ALIAPY_PAY:
  1066. $pay_type_name = '支付宝支付';
  1067. break;
  1068. default:
  1069. $pay_type_name = '其他支付';
  1070. break;
  1071. }
  1072. $orderData['_add_time'] = date('Y-m-d H:i:s', $orderData['add_time']);
  1073. $orderData['add_time_y'] = date('Y-m-d', $orderData['add_time']);
  1074. $orderData['add_time_h'] = date('H:i:s', $orderData['add_time']);
  1075. if (in_array($orderData['refund_type'], [1, 2, 4, 5])) {
  1076. $_type = -1;
  1077. $_msg = '商家审核中,请耐心等待';
  1078. $_title = '申请退款中';
  1079. } elseif ($orderData['refund_type'] == 3) {
  1080. $_type = -3;
  1081. $_title = '拒绝退款';
  1082. $_msg = '商家拒绝退款,请联系商家';
  1083. } else {
  1084. $_type = -2;
  1085. $_title = '已退款';
  1086. $_msg = '已为您退款,感谢您的支持';
  1087. }
  1088. $refund_name = sys_config('refund_name', '');
  1089. $refund_phone = sys_config('refund_phone', '');
  1090. $refund_address = sys_config('refund_address', '');
  1091. $orderData['_status'] = [
  1092. '_type' => $_type,
  1093. '_title' => $_title,
  1094. '_msg' => $_msg ?? '',
  1095. '_payType' => $pay_type_name,
  1096. 'refund_name' => $refund_name,
  1097. 'refund_phone' => $refund_phone,
  1098. 'refund_address' => $refund_address,
  1099. ];
  1100. $orderData['real_name'] = $orderInfo['real_name'];
  1101. $orderData['user_phone'] = $orderInfo['user_phone'];
  1102. $orderData['user_address'] = $orderInfo['user_address'];
  1103. $orderData['nickname'] = $userInfo['nickname'] ?? '';
  1104. $orderData['total_num'] = $orderData['refund_num'];
  1105. $orderData['pay_price'] = $orderData['refund_price'];
  1106. $orderData['refund_status'] = in_array($orderData['refund_type'], [1, 2, 4, 5]) ? 1 : 2;
  1107. $orderData['total_price'] = $total_price;
  1108. $orderData['paid'] = 1;
  1109. $orderData['mark'] = $orderData['refund_explain'];
  1110. $orderData['express_list'] = $orderData['refund_type'] == 4 ? app()->make(ExpressServices::class)->expressList(['is_show' => 1]) : [];
  1111. $orderData['custom_form'] = [];
  1112. $orderData['help_info'] = [
  1113. 'pay_uid' => $orderInfo['pay_uid'],
  1114. 'pay_nickname' => '',
  1115. 'pay_avatar' => '',
  1116. 'help_status' => 0
  1117. ];
  1118. if ($orderInfo['uid'] != $orderInfo['pay_uid']) {
  1119. /** @var UserServices $userServices */
  1120. $userServices = app()->make(UserServices::class);
  1121. $payUser = $userServices->get($orderInfo['pay_uid']);
  1122. $orderData['help_info'] = [
  1123. 'pay_uid' => $orderInfo['pay_uid'],
  1124. 'pay_nickname' => $payUser['nickname'],
  1125. 'pay_avatar' => $payUser['avatar'],
  1126. 'help_status' => 1
  1127. ];
  1128. }
  1129. return $orderData;
  1130. }
  1131. /**
  1132. * 取消申请、后台拒绝处理cart_info refund_num数据
  1133. * @param int $id
  1134. * @param int $oid
  1135. * @param array $orderRefundInfo
  1136. * @return bool
  1137. * @throws \think\db\exception\DataNotFoundException
  1138. * @throws \think\db\exception\DbException
  1139. * @throws \think\db\exception\ModelNotFoundException
  1140. */
  1141. public function cancelOrderRefundCartInfo(int $id, int $oid, $orderRefundInfo = [])
  1142. {
  1143. if (!$orderRefundInfo) {
  1144. $orderRefundInfo = $this->dao->get(['id' => $id, 'is_cancel' => 0]);
  1145. }
  1146. if (!$orderRefundInfo) {
  1147. throw new ValidateException('售后订单不存在');
  1148. }
  1149. $cart_ids = array_column($orderRefundInfo['cart_info'], 'id');
  1150. /** @var StoreOrderCartInfoServices $storeOrderCartInfoServices */
  1151. $storeOrderCartInfoServices = app()->make(StoreOrderCartInfoServices::class);
  1152. $cartInfos = $storeOrderCartInfoServices->getColumn([['oid', '=', $oid], ['cart_id', 'in', $cart_ids]], 'cart_id,refund_num', 'cart_id');
  1153. foreach ($orderRefundInfo['cart_info'] as $cart) {
  1154. $cart_refund_num = $cartInfos[$cart['id']]['refund_num'] ?? 0;
  1155. if ($cart['cart_num'] >= $cart_refund_num) {
  1156. $refund_num = 0;
  1157. } else {
  1158. $refund_num = bcsub((string)$cart_refund_num, (string)$cart['cart_num'], 0);
  1159. }
  1160. $storeOrderCartInfoServices->update(['oid' => $oid, 'cart_id' => $cart['id']], ['refund_num' => $refund_num]);
  1161. }
  1162. $storeOrderCartInfoServices->clearOrderCartInfo($oid);
  1163. return true;
  1164. }
  1165. }