StoreOrderRefundServices.php 57 KB

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