StoreOrderRefundServices.php 60 KB

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