StoreOrderRefundServices.php 58 KB

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