StoreOrderRefundServices.php 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  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('notice.notice', [['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. $res = true;
  411. //回退优惠卷 拆分子订单不退优惠券
  412. if (!$order['pid'] && $order['coupon_id'] && $order['coupon_price']) {
  413. /** @var StoreCouponUserServices $coumonUserServices */
  414. $coumonUserServices = app()->make(StoreCouponUserServices::class);
  415. $res = $res && $coumonUserServices->recoverCoupon((int)$order['coupon_id']);
  416. }
  417. //回退积分
  418. $order = $this->regressionIntegral($order);
  419. /** @var StoreOrderStatusServices $statusService */
  420. $statusService = app()->make(StoreOrderStatusServices::class);
  421. $statusService->save([
  422. 'oid' => $order['id'],
  423. 'change_type' => 'integral_back',
  424. 'change_message' => '商品退积分',
  425. 'change_time' => time()
  426. ]);
  427. return $res && $order->save();
  428. }
  429. /**
  430. * 回退使用积分和赠送积分
  431. * @param $order
  432. * @return bool
  433. */
  434. public function regressionIntegral($order)
  435. {
  436. /** @var UserServices $userServices */
  437. $userServices = app()->make(UserServices::class);
  438. $userInfo = $userServices->get($order['uid'], ['integral']);
  439. if (!$userInfo) {
  440. $order->back_integral = $order->use_integral;
  441. return $order;
  442. }
  443. $integral = $userInfo['integral'];
  444. if ($order['status'] == -2 || $order['is_del']) {
  445. return $order;
  446. }
  447. $res1 = $res2 = $res3 = $res4 = true;
  448. //订单赠送积分
  449. /** @var UserBillServices $userBillServices */
  450. $userBillServices = app()->make(UserBillServices::class);
  451. $order_gain = $userBillServices->sum([
  452. 'category' => 'integral',
  453. 'type' => 'gain',
  454. 'link_id' => $order['id'],
  455. 'uid' => $order['uid']
  456. ], 'number');
  457. //商品赠送
  458. $product_gain = $userBillServices->sum([
  459. 'category' => 'integral',
  460. 'type' => 'product_gain',
  461. 'link_id' => $order['id'],
  462. 'uid' => $order['uid']
  463. ], 'number');
  464. $give_integral = $order_gain + $product_gain;
  465. if ($give_integral) {
  466. //判断订单是否已经回退积分
  467. $count = $userBillServices->count(['category' => 'integral', 'type' => 'integral_refund', 'link_id' => $order['id']]);
  468. if (!$count) {
  469. $res1 = $userServices->bcDec($order['uid'], 'integral', $give_integral);
  470. //记录赠送积分收回
  471. $integral = $integral - $give_integral;
  472. $res2 = $userBillServices->income('integral_refund', $order['uid'], $give_integral, $integral, $order['id']);
  473. }
  474. }
  475. //返还下单使用积分
  476. $use_integral = $order['use_integral'];
  477. if ($use_integral > 0) {
  478. $res3 = $userServices->bcInc($order['uid'], 'integral', $use_integral);
  479. //记录下单使用积分还回
  480. $res4 = $userBillServices->income('pay_product_integral_back', $order['uid'], (int)$use_integral, $integral + $use_integral, $order['id']);
  481. }
  482. if (!($res1 && $res2 && $res3 && $res4)) {
  483. throw new ApiException(400494);
  484. }
  485. if ($use_integral > $give_integral) {
  486. $order->back_integral = bcsub($use_integral, $give_integral, 2);
  487. }
  488. return $order;
  489. }
  490. /**
  491. * 回退库存
  492. * @param $order
  493. * @return bool
  494. */
  495. public function regressionStock($order)
  496. {
  497. if ($order['status'] == -2 || $order['is_del']) return true;
  498. $combination_id = $order['combination_id'];
  499. $seckill_id = $order['seckill_id'];
  500. $bargain_id = $order['bargain_id'];
  501. $advance_id = $order['advance_id'];
  502. $res5 = true;
  503. /** @var StoreOrderCartInfoServices $cartServices */
  504. $cartServices = app()->make(StoreOrderCartInfoServices::class);
  505. /** @var StoreProductServices $services */
  506. $services = app()->make(StoreProductServices::class);
  507. /** @var StoreSeckillServices $seckillServices */
  508. $seckillServices = app()->make(StoreSeckillServices::class);
  509. /** @var StoreCombinationServices $pinkServices */
  510. $pinkServices = app()->make(StoreCombinationServices::class);
  511. /** @var StoreBargainServices $bargainServices */
  512. $bargainServices = app()->make(StoreBargainServices::class);
  513. /** @var StoreAdvanceServices $advanceServices */
  514. $advanceServices = app()->make(StoreAdvanceServices::class);
  515. $cartInfo = $cartServices->getCartInfoList(['cart_id' => $order['cart_id']], ['cart_info']);
  516. foreach ($cartInfo as $cart) {
  517. $cart['cart_info'] = is_array($cart['cart_info']) ? $cart['cart_info'] : json_decode($cart['cart_info'], true);
  518. //增库存减销量
  519. $unique = isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '';
  520. $cart_num = (int)$cart['cart_info']['cart_num'];
  521. $type = 0;
  522. if ($combination_id) {
  523. $type = 3;
  524. $res5 = $res5 && $pinkServices->incCombinationStock($cart_num, (int)$combination_id, $unique);
  525. } else if ($seckill_id) {
  526. $type = 1;
  527. $res5 = $res5 && $seckillServices->incSeckillStock($cart_num, (int)$seckill_id, $unique);
  528. } else if ($bargain_id) {
  529. $type = 2;
  530. $res5 = $res5 && $bargainServices->incBargainStock($cart_num, (int)$bargain_id, $unique);
  531. } else {
  532. $res5 = $res5 && $services->incProductStock($cart_num, (int)$cart['cart_info']['productInfo']['id'], $unique);
  533. }
  534. if ($type) CacheService::setStock($unique, $cart_num, $type, false);
  535. }
  536. return $res5;
  537. }
  538. /**
  539. * 同意退款成功发送模板消息和记录订单状态
  540. * @param $data
  541. * @param $order
  542. * @param $refund_price
  543. * @param $id
  544. */
  545. public function storeProductOrderRefundY($data, $order, $refund_price)
  546. {
  547. /** @var StoreOrderStatusServices $statusService */
  548. $statusService = app()->make(StoreOrderStatusServices::class);
  549. $statusService->save([
  550. 'oid' => $order['id'],
  551. 'change_type' => 'refund_price',
  552. 'change_message' => '退款给用户:' . $refund_price . '元',
  553. 'change_time' => time()
  554. ]);
  555. /** @var CapitalFlowServices $capitalFlowServices */
  556. $capitalFlowServices = app()->make(CapitalFlowServices::class);
  557. /** @var UserServices $userServices */
  558. $userServices = app()->make(UserServices::class);
  559. $userInfo = $userServices->get($order['uid']);
  560. $order['nickname'] = $userInfo['nickname'];
  561. $order['phone'] = $userInfo['phone'];
  562. if ($order['pay_type'] == 'alipay' || $order['pay_type'] == 'weixin' || $order['pay_type'] == 'offline') {
  563. $capitalFlowServices->setFlow($order, 'refund');
  564. }
  565. event('notice.notice', [['data' => $data, 'order' => $order], 'order_refund']);
  566. }
  567. /**
  568. * 同意退款退款失败写入订单记录
  569. * @param int $id
  570. * @param $refund_price
  571. */
  572. public function storeProductOrderRefundYFasle(int $id, $refund_price)
  573. {
  574. /** @var StoreOrderStatusServices $statusService */
  575. $statusService = app()->make(StoreOrderStatusServices::class);
  576. $statusService->save([
  577. 'oid' => $id,
  578. 'change_type' => 'refund_price',
  579. 'change_message' => '退款给用户:' . $refund_price . '元失败',
  580. 'change_time' => time()
  581. ]);
  582. }
  583. /**
  584. * 不退款记录订单变更状态
  585. * @param int $id
  586. * @param string $refundReason
  587. */
  588. public function storeProductOrderRefundNo(int $id, string $refundReason)
  589. {
  590. /** @var StoreOrderStatusServices $statusService */
  591. $statusService = app()->make(StoreOrderStatusServices::class);
  592. $statusService->save([
  593. 'oid' => $id,
  594. 'change_type' => 'refund_n',
  595. 'change_message' => '不退款原因:' . $refundReason,
  596. 'change_time' => time()
  597. ]);
  598. }
  599. /**
  600. * 不退款表单
  601. * @param int $id
  602. * @return array
  603. * @throws \FormBuilder\Exception\FormBuilderException
  604. */
  605. public function noRefundForm(int $id)
  606. {
  607. $order = $this->dao->get($id);
  608. if (!$order) {
  609. throw new AdminException(100026);
  610. }
  611. $f[] = Form::input('order_id', '不退款单号', $order->getData('order_id'))->disabled(true);
  612. $f[] = Form::input('refund_reason', '不退款原因')->type('textarea')->required('请填写不退款原因');
  613. return create_form('不退款原因', $f, $this->url('refund/no_refund/' . $id), 'PUT');
  614. }
  615. /**
  616. * 拒绝退款
  617. * @param int $id
  618. * @param array $data
  619. * @param array $orderRefundInfo
  620. * @return bool
  621. * @throws \think\db\exception\DataNotFoundException
  622. * @throws \think\db\exception\DbException
  623. * @throws \think\db\exception\ModelNotFoundException
  624. */
  625. public function refuseRefund(int $id, array $data, $orderRefundInfo = [])
  626. {
  627. if (!$orderRefundInfo) {
  628. $orderRefundInfo = $this->dao->get(['id' => $id, 'is_cancel' => 0]);
  629. }
  630. if (!$orderRefundInfo) {
  631. throw new ApiException(400495);
  632. }
  633. /** @var StoreOrderServices $storeOrderServices */
  634. $storeOrderServices = app()->make(StoreOrderServices::class);
  635. $this->transaction(function () use ($id, $data, $orderRefundInfo, $storeOrderServices) {
  636. //处理售后订单
  637. $this->dao->update($id, $data);
  638. //处理订单
  639. $oid = (int)$orderRefundInfo['store_order_id'];
  640. $storeOrderServices->update($oid, ['refund_status' => 0, 'refund_type' => 3]);
  641. //处理订单商品cart_info
  642. $this->cancelOrderRefundCartInfo($id, $oid, $orderRefundInfo);
  643. //记录
  644. /** @var StoreOrderStatusServices $statusService */
  645. $statusService = app()->make(StoreOrderStatusServices::class);
  646. $statusService->save([
  647. 'oid' => $id,
  648. 'change_type' => 'refund_n',
  649. 'change_message' => '不退款原因:' . ($data['refund_reason'] ?? ''),
  650. 'change_time' => time()
  651. ]);
  652. });
  653. event('notice.notice', [['orderInfo' => $orderRefundInfo], 'send_order_refund_no_status']);
  654. return true;
  655. }
  656. /**
  657. * 退积分表单创建
  658. * @param int $id
  659. * @return array
  660. * @throws \FormBuilder\Exception\FormBuilderException
  661. */
  662. public function refundIntegralForm(int $id)
  663. {
  664. if (!$orderInfo = $this->dao->get($id))
  665. throw new AdminException(400118);
  666. if ($orderInfo->use_integral < 0 || $orderInfo->use_integral == $orderInfo->back_integral)
  667. throw new AdminException(400496);
  668. if (!$orderInfo->paid)
  669. throw new AdminException(400497);
  670. $f[] = Form::input('order_id', '退款单号', $orderInfo->getData('order_id'))->disabled(1);
  671. $f[] = Form::number('use_integral', '使用的积分', (float)$orderInfo->getData('use_integral'))->min(0)->disabled(1);
  672. $f[] = Form::number('use_integrals', '已退积分', (float)$orderInfo->getData('back_integral'))->min(0)->disabled(1);
  673. $f[] = Form::number('back_integral', '可退积分', (float)bcsub($orderInfo->getData('use_integral'), $orderInfo->getData('back_integral')))->min(0)->precision(0)->required('请输入可退积分');
  674. return create_form('退积分', $f, $this->url('/order/refund_integral/' . $id), 'PUT');
  675. }
  676. /**
  677. * 单独退积分处理
  678. * @param $orderInfo
  679. * @param $back_integral
  680. */
  681. public function refundIntegral($orderInfo, $back_integral)
  682. {
  683. /** @var UserServices $userServices */
  684. $userServices = app()->make(UserServices::class);
  685. $integral = $userServices->value(['uid' => $orderInfo['uid']], 'integral');
  686. return $this->transaction(function () use ($userServices, $orderInfo, $back_integral, $integral) {
  687. $res1 = $userServices->bcInc($orderInfo['uid'], 'integral', $back_integral, 'uid');
  688. /** @var UserBillServices $userBillServices */
  689. $userBillServices = app()->make(UserBillServices::class);
  690. $res2 = $userBillServices->income('pay_product_integral_back', $orderInfo['uid'], (int)$back_integral, $integral + $back_integral, $orderInfo['id']);
  691. /** @var StoreOrderStatusServices $statusService */
  692. $statusService = app()->make(StoreOrderStatusServices::class);
  693. $res3 = $statusService->save([
  694. 'oid' => $orderInfo['id'],
  695. 'change_type' => 'integral_back',
  696. 'change_message' => '商品退积分:' . $back_integral,
  697. 'change_time' => time()
  698. ]);
  699. $res4 = $orderInfo->save();
  700. $res = $res1 && $res2 && $res3 && $res4;
  701. if (!$res) {
  702. throw new AdminException(400498);
  703. }
  704. return true;
  705. });
  706. }
  707. /**
  708. * 订单申请退款
  709. * @param $uni
  710. * @param $uid
  711. * @param string $refundReasonWap
  712. * @param string $refundReasonWapExplain
  713. * @param array $refundReasonWapImg
  714. * @return bool|void
  715. */
  716. public function orderApplyRefund($order, string $refundReasonWap = '', string $refundReasonWapExplain = '', array $refundReasonWapImg = [], int $refundType = 0, $cart_id = 0, $refund_num = 0)
  717. {
  718. if (!$order) {
  719. throw new ApiException(410173);
  720. }
  721. if ($order['refund_status'] == 2) {
  722. throw new ApiException(410226);
  723. }
  724. if ($order['refund_status'] == 1) {
  725. throw new ApiException(410250);
  726. }
  727. if ($order['total_num'] < $refund_num) {
  728. throw new ApiException(410252);
  729. }
  730. $this->transaction(function () use ($order, $refundReasonWap, $refundReasonWapExplain, $refundReasonWapImg, $refundType, $refund_num, $cart_id) {
  731. $status = 0;
  732. $order_id = (int)$order['id'];
  733. if ($cart_id) {
  734. /** @var StoreOrderCartInfoServices $storeOrderCartInfoServices */
  735. $storeOrderCartInfoServices = app()->make(StoreOrderCartInfoServices::class);
  736. $cart_ids = [];
  737. $cart_ids[0] = ['cart_id' => $cart_id, 'cart_num' => $refund_num];
  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. } elseif (in_array($order['pid'], [0, -1]) && $this->storeOrderServices->count(['pid' => $order_id])) {
  744. /** @var StoreOrderCartInfoServices $storeOrderCartInfoServices */
  745. $storeOrderCartInfoServices = app()->make(StoreOrderCartInfoServices::class);
  746. $cart_info = $storeOrderCartInfoServices->getSplitCartList($order_id, 'cart_info');
  747. if (!$cart_info) {
  748. throw new ApiException(410253);
  749. }
  750. $cart_ids = [];
  751. foreach ($cart_info as $key => $cart) {
  752. $cart_ids[$key] = ['cart_id' => $cart['id'], 'cart_num' => $refund_num];
  753. }
  754. /** @var StoreOrderSplitServices $storeOrderSplitServices */
  755. $storeOrderSplitServices = app()->make(StoreOrderSplitServices::class);
  756. //拆单
  757. $status = $order['status'];
  758. $order = $storeOrderSplitServices->split($order_id, $cart_ids, $order);
  759. }
  760. $data = [
  761. 'refund_status' => 1,
  762. 'refund_reason_time' => time(),
  763. 'refund_reason_wap' => $refundReasonWap,
  764. 'refund_reason_wap_explain' => $refundReasonWapExplain,
  765. 'refund_reason_wap_img' => json_encode($refundReasonWapImg),
  766. 'refund_type' => $refundType
  767. ];
  768. if ($status) $data['status'] = $status;
  769. /** @var StoreOrderStatusServices $statusService */
  770. $statusService = app()->make(StoreOrderStatusServices::class);
  771. $res1 = false !== $statusService->save([
  772. 'oid' => $order['id'],
  773. 'change_type' => 'apply_refund',
  774. 'change_message' => '用户申请退款,原因:' . $refundReasonWap,
  775. 'change_time' => time()
  776. ]);
  777. $res2 = false !== $this->storeOrderServices->update(['id' => $order['id']], $data);
  778. $res = $res1 && $res2;
  779. if (!$res)
  780. throw new ApiException(410254);
  781. //子订单申请退款
  782. if ($order['pid'] > 0) {
  783. $p_order = $this->storeOrderServices->get((int)$order['pid']);
  784. $split_order = $this->storeOrderServices->count(['pid' => $order['pid'], 'refund_status' => 0]);
  785. if ($split_order || (!$split_order && $p_order['status'] == 4) || $cart_id) {
  786. $this->storeOrderServices->update(['id' => $order['pid']], ['refund_status' => 3, 'refund_reason_time' => time()]);
  787. } else {
  788. $this->storeOrderServices->update(['id' => $order['pid']], ['refund_status' => 4, 'refund_reason_time' => time()]);
  789. }
  790. } else {
  791. /** @var StoreOrderCartInfoServices $orderCartInfoService */
  792. $orderCartInfoService = app()->make(StoreOrderCartInfoServices::class);
  793. // if (!$orderCartInfoService->getSplitCartList()) {
  794. //
  795. // }
  796. }
  797. });
  798. try {
  799. ChannelService::instance()->send('NEW_REFUND_ORDER', ['order_id' => $order['order_id']]);
  800. } catch (\Exception $e) {
  801. }
  802. //提醒推送
  803. event('notice.notice', [['order' => $order], 'send_order_apply_refund']);
  804. return true;
  805. }
  806. /**
  807. * 写入退款快递单号
  808. * @param $order
  809. * @param $express
  810. * @return bool
  811. */
  812. public function editRefundExpress($data)
  813. {
  814. $this->transaction(function () use ($data) {
  815. $id = $data['id'];
  816. $data['refund_type'] = 5;
  817. /** @var StoreOrderStatusServices $statusService */
  818. $statusService = app()->make(StoreOrderStatusServices::class);
  819. $res1 = false !== $statusService->save([
  820. 'oid' => $id,
  821. 'change_type' => 'refund_express',
  822. 'change_message' => '用户已退货,订单号:' . $data['refund_express'],
  823. 'change_time' => time()
  824. ]);
  825. if ($data['refund_img'] != '') unset($data['refund_img']);
  826. if ($data['refund_explain'] != '') unset($data['refund_explain']);
  827. $res2 = false !== $this->dao->update(['id' => $id], $data);
  828. $res = $res1 && $res2;
  829. if (!$res)
  830. throw new ApiException(100018);
  831. });
  832. return true;
  833. }
  834. /**
  835. * 订单申请退款
  836. * @param int $id
  837. * @param int $uid
  838. * @param array $order
  839. * @param array $cart_ids
  840. * @param int $refundType
  841. * @param float $refundPrice
  842. * @param array $refundData
  843. * @param int $isPink
  844. * @return mixed
  845. * @throws \Psr\SimpleCache\InvalidArgumentException
  846. * @throws \think\db\exception\DataNotFoundException
  847. * @throws \think\db\exception\DbException
  848. * @throws \think\db\exception\ModelNotFoundException
  849. */
  850. public function applyRefund(int $id, int $uid, $order = [], array $cart_ids = [], int $refundType = 0, float $refundPrice = 0.00, array $refundData = [], $isPink = 0)
  851. {
  852. /** 查询订单是否存在 */
  853. /** @var StoreOrderServices $orderServices */
  854. $orderServices = app()->make(StoreOrderServices::class);
  855. if (!$order) {
  856. $order = $orderServices->get($id);
  857. }
  858. if (!$order) {
  859. throw new ApiException(410173);
  860. }
  861. $is_now = $this->dao->getCount([
  862. ['store_order_id', '=', $id],
  863. ['refund_type', 'in', [1, 2, 4, 5]],
  864. ['is_cancel', '=', 0],
  865. ['is_del', '=', 0],
  866. ['is_pink_cancel', '=', 0]
  867. ]);
  868. if ($is_now) throw new ApiException(410255);
  869. $refund_num = $order['total_num'];
  870. $refund_price = $order['pay_price'];
  871. /** @var StoreOrderCartInfoServices $storeOrderCartInfoServices */
  872. $storeOrderCartInfoServices = app()->make(StoreOrderCartInfoServices::class);
  873. //退部分
  874. $cartInfo = [];
  875. $cartInfos = $storeOrderCartInfoServices->getCartColunm(['oid' => $id], 'id,cart_id,cart_num,refund_num,cart_info');
  876. if ($cart_ids) {
  877. $cartInfo = array_combine(array_column($cartInfos, 'cart_id'), $cartInfos);
  878. $refund_num = 0;
  879. foreach ($cart_ids as $cart) {
  880. if ($cart['cart_num'] + $cartInfo[$cart['cart_id']]['refund_num'] > $cartInfo[$cart['cart_id']]['cart_num']) {
  881. throw new ApiException(410252);
  882. }
  883. $refund_num = bcadd((string)$refund_num, (string)$cart['cart_num'], 0);
  884. }
  885. //总共申请多少件
  886. $total_num = array_sum(array_column($cart_ids, 'cart_num'));
  887. if ($total_num < $order['total_num']) {
  888. /** @var StoreOrderSplitServices $storeOrderSpliteServices */
  889. $storeOrderSpliteServices = app()->make(StoreOrderSplitServices::class);
  890. $cartInfos = $storeOrderSpliteServices->getSplitOrderCartInfo($id, $cart_ids, $order);
  891. $total_price = $pay_postage = 0;
  892. foreach ($cartInfos as $cart) {
  893. $_info = is_string($cart['cart_info']) ? json_decode($cart['cart_info'], true) : $cart['cart_info'];
  894. $total_price = bcadd((string)$total_price, bcmul((string)($_info['truePrice'] ?? 0), (string)$cart['cart_num'], 4), 2);
  895. $pay_postage = bcadd((string)$pay_postage, (string)($_info['postage_price'] ?? 0), 2);
  896. }
  897. $refund_pay_price = bcadd((string)$total_price, (string)$pay_postage, 2);
  898. //订单实际支付金额
  899. $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);
  900. if ($order_pay_price != $order['pay_price'] && $refund_pay_price != $order_pay_price) {//有改价
  901. $refund_price = bcmul((string)bcdiv((string)$order['pay_price'], (string)$order_pay_price, 4), (string)$refund_pay_price, 2);
  902. } else {
  903. $refund_price = $refund_pay_price;
  904. }
  905. }
  906. } else {
  907. foreach ($cartInfos as $cart) {
  908. if ($cart['refund_num'] > 0) {
  909. throw new ApiException(410252);
  910. }
  911. }
  912. }
  913. foreach ($cartInfos as &$cart) {
  914. $cart['cart_info'] = is_string($cart['cart_info']) ? json_decode($cart['cart_info'], true) : $cart['cart_info'];
  915. }
  916. $refundData['uid'] = $uid;
  917. $refundData['store_id'] = $order['store_id'];
  918. $refundData['store_order_id'] = $id;
  919. $refundData['refund_num'] = $refund_num;
  920. $refundData['refund_type'] = $refundType;
  921. $refundData['refund_price'] = $refund_price;
  922. $refundData['order_id'] = $order['refund_no'] = app()->make(StoreOrderCreateServices::class)->getNewOrderId('');
  923. $refundData['add_time'] = time();
  924. $refundData['cart_info'] = json_encode(array_column($cartInfos, 'cart_info'));
  925. $refundData['is_pink_cancel'] = $isPink;
  926. $res = $this->transaction(function () use ($id, $order, $cart_ids, $refundData, $storeOrderCartInfoServices, $cartInfo, $orderServices, $cartInfos) {
  927. /** @var StoreOrderStatusServices $statusService */
  928. $statusService = app()->make(StoreOrderStatusServices::class);
  929. $res1 = false !== $statusService->save([
  930. 'oid' => $order['id'],
  931. 'change_type' => 'apply_refund',
  932. 'change_message' => '用户申请退款,原因:' . $refundData['refund_reason'],
  933. 'change_time' => time()
  934. ]);
  935. $res2 = true;
  936. //添加退款数据
  937. /** @var StoreOrderRefundServices $storeOrderRefundServices */
  938. $storeOrderRefundServices = app()->make(StoreOrderRefundServices::class);
  939. $res3 = $storeOrderRefundServices->save($refundData);
  940. if (!$res3) {
  941. throw new ApiException(410251);
  942. }
  943. $res4 = true;
  944. if ($cart_ids) {
  945. //修改订单商品退款信息
  946. foreach ($cart_ids as $cart) {
  947. $res4 = $res4 && $storeOrderCartInfoServices->update(['oid' => $id, 'cart_id' => $cart['cart_id']], ['refund_num' => (($cartInfo[$cart['cart_id']]['refund_num'] ?? 0) + $cart['cart_num'])]);
  948. }
  949. } else {
  950. //修改原订单状态
  951. $res2 = false !== $orderServices->update(['id' => $order['id']], ['refund_status' => 1]);
  952. foreach ($cartInfos as $cart) {
  953. $res4 = $res4 && $storeOrderCartInfoServices->update(['oid' => $id, 'cart_id' => $cart['cart_id']], ['refund_num' => $cart['cart_num']]);
  954. }
  955. }
  956. return $res1 && $res2 && $res3 && $res4;
  957. });
  958. $storeOrderCartInfoServices->clearOrderCartInfo($order['id']);
  959. //申请退款事件
  960. event('order.orderRefundCreateAfter', [$order]);
  961. //提醒推送
  962. event('notice.notice', [['order' => $order], 'send_order_apply_refund']);
  963. //推送订单
  964. event('out.outPush', ['refund_create_push', ['order_id' => (int)$order['id']]]);
  965. try {
  966. ChannelService::instance()->send('NEW_REFUND_ORDER', ['order_id' => $order['order_id']]);
  967. } catch (\Exception $e) {
  968. }
  969. return $res;
  970. }
  971. /**
  972. * 获取某个字段总金额
  973. * @param $cartInfo
  974. * @param string $key
  975. * @param bool $is_unit
  976. * @return int|string
  977. */
  978. public function getOrderSumPrice($cartInfo, $key = 'truePrice', $is_unit = true)
  979. {
  980. $SumPrice = 0;
  981. foreach ($cartInfo as $cart) {
  982. if (isset($cart['cart_info'])) $cart = $cart['cart_info'];
  983. if ($is_unit) {
  984. $SumPrice = bcadd($SumPrice, bcmul($cart['cart_num'] ?? 1, $cart[$key] ?? 0, 2), 2);
  985. } else {
  986. $SumPrice = bcadd($SumPrice, $cart[$key] ?? 0, 2);
  987. }
  988. }
  989. return $SumPrice;
  990. }
  991. /**
  992. * 退款订单列表
  993. * @param $where
  994. * @return array
  995. */
  996. public function refundList($where)
  997. {
  998. [$page, $limit] = $this->getPageValue();
  999. $list = $this->dao->getList($where, $page, $limit);
  1000. $count = $this->dao->count($where);
  1001. if ($list) {
  1002. foreach ($list as &$item) {
  1003. $item['paid'] = 1;
  1004. $item['add_time'] = isset($item['add_time']) ? date('Y-m-d H:i', (int)$item['add_time']) : '';
  1005. $item['cartInfo'] = $item['cart_info'];
  1006. if (in_array($item['refund_type'], [1, 2, 4, 5])) {
  1007. $item['refund_status'] = 1;
  1008. } elseif ($item['refund_type'] == 6) {
  1009. $item['refund_status'] = 2;
  1010. } elseif ($item['refund_type'] == 3) {
  1011. $item['refund_status'] = 3;
  1012. }
  1013. foreach ($item['cart_info'] as $items) {
  1014. $item['_info'][]['cart_info'] = $items;
  1015. }
  1016. $item['total_num'] = $item['refund_num'];
  1017. $item['pay_price'] = $item['refund_price'];
  1018. $item['pay_postage'] = floatval($this->getOrderSumPrice($item['cart_info'], 'postage_price', false));
  1019. if (in_array($item['refund_type'], [1, 2, 4, 5])) {
  1020. $_type = -1;
  1021. $_title = '申请退款中';
  1022. } elseif ($item['refund_type'] == 3) {
  1023. $_type = -3;
  1024. $_title = '拒绝退款';
  1025. } else {
  1026. $_type = -2;
  1027. $_title = '已退款';
  1028. }
  1029. $item['_status'] = [
  1030. '_type' => $_type,
  1031. '_title' => $_title,
  1032. ];
  1033. }
  1034. }
  1035. $data['list'] = $list;
  1036. $data['count'] = $count;
  1037. $del_where = ['is_cancel' => 0];
  1038. $data['num'] = [
  1039. 0 => ['name' => '全部', 'num' => $this->dao->count($del_where)],
  1040. 1 => ['name' => '仅退款', 'num' => $this->dao->count($del_where + ['refund_type' => 1])],
  1041. 2 => ['name' => '退货退款', 'num' => $this->dao->count($del_where + ['refund_type' => 2])],
  1042. 3 => ['name' => '拒绝退款', 'num' => $this->dao->count($del_where + ['refund_type' => 3])],
  1043. 4 => ['name' => '商品待退货', 'num' => $this->dao->count($del_where + ['refund_type' => 4])],
  1044. 5 => ['name' => '退货待收货', 'num' => $this->dao->count($del_where + ['refund_type' => 5])],
  1045. 6 => ['name' => '已退款', 'num' => $this->dao->count($del_where + ['refund_type' => 6])]
  1046. ];
  1047. return $data;
  1048. }
  1049. /**
  1050. * 退款订单详情
  1051. * @param $uni
  1052. * @return array
  1053. * @throws \think\db\exception\DataNotFoundException
  1054. * @throws \think\db\exception\DbException
  1055. * @throws \think\db\exception\ModelNotFoundException
  1056. * @author 吴汐
  1057. * @email 442384644@qq.com
  1058. * @date 2023/02/17
  1059. */
  1060. public function refundDetail($uni)
  1061. {
  1062. if (!strlen(trim($uni))) throw new ApiException(100100);
  1063. $order = $this->dao->get(['order_id' => $uni], ['*']);
  1064. if (!$order) throw new ApiException(410173);
  1065. $order = $order->toArray();
  1066. /** @var StoreOrderServices $orderServices */
  1067. $orderServices = app()->make(StoreOrderServices::class);
  1068. $orderInfo = $orderServices->get($order['store_order_id']);
  1069. /** @var UserServices $userServices */
  1070. $userServices = app()->make(UserServices::class);
  1071. $userInfo = $userServices->get($order['uid']);
  1072. $order['mapKey'] = sys_config('tengxun_map_key');
  1073. $order['yue_pay_status'] = (int)sys_config('balance_func_status') && (int)sys_config('yue_pay_status') == 1 ? (int)1 : (int)2;//余额支付 1 开启 2 关闭
  1074. $order['pay_weixin_open'] = (int)sys_config('pay_weixin_open') ?? 0;//微信支付 1 开启 0 关闭
  1075. $order['ali_pay_status'] = sys_config('ali_pay_status') ? true : false;//支付包支付 1 开启 0 关闭
  1076. $orderData = $order;
  1077. $orderData['store_order_sn'] = $orderInfo['order_id'];
  1078. $orderData['cartInfo'] = $orderData['cart_info'];
  1079. $orderData['_pay_time'] = date('Y-m-d H:i:s', $orderInfo['pay_time']);
  1080. $orderData['type'] = 0;
  1081. if ($orderInfo['seckill_id'] || $orderInfo['bargain_id'] || $orderInfo['combination_id']) {
  1082. if ($orderInfo['seckill_id']) $orderData['type'] = 1;
  1083. if ($orderInfo['bargain_id']) $orderData['type'] = 2;
  1084. if ($orderInfo['combination_id']) $orderData['type'] = 3;
  1085. }
  1086. //核算优惠金额
  1087. $vipTruePrice = 0;
  1088. $total_price = 0;
  1089. $pay_postage = '0';
  1090. foreach ($orderData['cartInfo'] ?? [] as $key => &$cart) {
  1091. if (!isset($cart['sum_true_price'])) $cart['sum_true_price'] = bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 2);
  1092. $cart['vip_sum_truePrice'] = bcmul($cart['vip_truePrice'], $cart['cart_num'] ? $cart['cart_num'] : 1, 2);
  1093. $vipTruePrice = bcadd((string)$vipTruePrice, (string)$cart['vip_sum_truePrice'], 2);
  1094. if (isset($order['split']) && $order['split']) {
  1095. $orderData['cartInfo'][$key]['cart_num'] = $cart['surplus_num'];
  1096. if (!$cart['surplus_num']) unset($orderData['cartInfo'][$key]);
  1097. }
  1098. $total_price = bcadd($total_price, $cart['sum_true_price'], 2);
  1099. $pay_postage = bcadd($cart['postage_price'], $pay_postage, 2);
  1100. }
  1101. $orderData['use_integral'] = $this->getOrderSumPrice($orderData['cartInfo'], 'use_integral', false);
  1102. $orderData['integral_price'] = $this->getOrderSumPrice($orderData['cartInfo'], 'integral_price', false);
  1103. $orderData['coupon_price'] = $this->getOrderSumPrice($orderData['cartInfo'], 'coupon_price', false);
  1104. $orderData['deduction_price'] = $this->getOrderSumPrice($orderData['cartInfo'], 'integral_price', false);
  1105. $total_price = bcadd((string)$total_price, (string)bcadd((string)$orderData['deduction_price'], (string)$orderData['coupon_price'], 2), 2);
  1106. $orderData['vip_true_price'] = $vipTruePrice;
  1107. $orderData['postage_price'] = 0;
  1108. $orderData['pay_postage'] = $this->getOrderSumPrice($orderData['cart_info'], 'origin_postage_price', false);
  1109. $orderData['member_price'] = 0;
  1110. $orderData['routine_contact_type'] = sys_config('routine_contact_type', 0);
  1111. switch ($orderInfo['pay_type']) {
  1112. case PayServices::WEIXIN_PAY:
  1113. $pay_type_name = '微信支付';
  1114. break;
  1115. case PayServices::YUE_PAY:
  1116. $pay_type_name = '余额支付';
  1117. break;
  1118. case PayServices::OFFLINE_PAY:
  1119. $pay_type_name = '线下支付';
  1120. break;
  1121. case PayServices::ALIAPY_PAY:
  1122. $pay_type_name = '支付宝支付';
  1123. break;
  1124. default:
  1125. $pay_type_name = '其他支付';
  1126. break;
  1127. }
  1128. $orderData['_add_time'] = date('Y-m-d H:i:s', $orderData['add_time']);
  1129. $orderData['add_time_y'] = date('Y-m-d', $orderData['add_time']);
  1130. $orderData['add_time_h'] = date('H:i:s', $orderData['add_time']);
  1131. if (in_array($orderData['refund_type'], [1, 2, 4, 5])) {
  1132. $_type = -1;
  1133. $_msg = '商家审核中,请耐心等待';
  1134. $_title = '申请退款中';
  1135. } elseif ($orderData['refund_type'] == 3) {
  1136. $_type = -3;
  1137. $_title = '拒绝退款';
  1138. $_msg = '商家拒绝退款,请联系商家';
  1139. } else {
  1140. $_type = -2;
  1141. $_title = '已退款';
  1142. $_msg = '已为您退款,感谢您的支持';
  1143. }
  1144. $refund_name = sys_config('refund_name', '');
  1145. $refund_phone = sys_config('refund_phone', '');
  1146. $refund_address = sys_config('refund_address', '');
  1147. $orderData['_status'] = [
  1148. '_type' => $_type,
  1149. '_title' => $_title,
  1150. '_msg' => $_msg ?? '',
  1151. '_payType' => $pay_type_name,
  1152. 'refund_name' => $refund_name,
  1153. 'refund_phone' => $refund_phone,
  1154. 'refund_address' => $refund_address,
  1155. ];
  1156. $orderData['real_name'] = $orderInfo['real_name'];
  1157. $orderData['user_phone'] = $orderInfo['user_phone'];
  1158. $orderData['user_address'] = $orderInfo['user_address'];
  1159. $orderData['nickname'] = $userInfo['nickname'] ?? '';
  1160. $orderData['total_num'] = $orderData['refund_num'];
  1161. $orderData['pay_price'] = $orderData['refund_price'];
  1162. $orderData['refund_status'] = in_array($orderData['refund_type'], [1, 2, 4, 5]) ? 1 : 2;
  1163. $orderData['total_price'] = $total_price;
  1164. $orderData['paid'] = 1;
  1165. $orderData['mark'] = $orderData['refund_explain'];
  1166. $orderData['express_list'] = $orderData['refund_type'] == 4 ? app()->make(ExpressServices::class)->expressList(['is_show' => 1]) : [];
  1167. $orderData['custom_form'] = [];
  1168. $orderData['help_info'] = [
  1169. 'pay_uid' => $orderInfo['pay_uid'],
  1170. 'pay_nickname' => '',
  1171. 'pay_avatar' => '',
  1172. 'help_status' => 0
  1173. ];
  1174. if ($orderInfo['uid'] != $orderInfo['pay_uid']) {
  1175. /** @var UserServices $userServices */
  1176. $userServices = app()->make(UserServices::class);
  1177. $payUser = $userServices->get($orderInfo['pay_uid']);
  1178. $orderData['help_info'] = [
  1179. 'pay_uid' => $orderInfo['pay_uid'],
  1180. 'pay_nickname' => $payUser['nickname'],
  1181. 'pay_avatar' => $payUser['avatar'],
  1182. 'help_status' => 1
  1183. ];
  1184. }
  1185. $orderData['pay_postage'] = $pay_postage;
  1186. return $orderData;
  1187. }
  1188. /**
  1189. * 取消申请、后台拒绝处理cart_info refund_num数据
  1190. * @param int $id
  1191. * @param int $oid
  1192. * @param array $orderRefundInfo
  1193. * @return bool
  1194. * @throws \think\db\exception\DataNotFoundException
  1195. * @throws \think\db\exception\DbException
  1196. * @throws \think\db\exception\ModelNotFoundException
  1197. */
  1198. public function cancelOrderRefundCartInfo(int $id, int $oid, $orderRefundInfo = [])
  1199. {
  1200. if (!$orderRefundInfo) {
  1201. $orderRefundInfo = $this->dao->get(['id' => $id, 'is_cancel' => 0]);
  1202. }
  1203. if (!$orderRefundInfo) {
  1204. throw new ApiException(410173);
  1205. }
  1206. $cart_ids = array_column($orderRefundInfo['cart_info'], 'id');
  1207. /** @var StoreOrderCartInfoServices $storeOrderCartInfoServices */
  1208. $storeOrderCartInfoServices = app()->make(StoreOrderCartInfoServices::class);
  1209. $cartInfos = $storeOrderCartInfoServices->getColumn([['oid', '=', $oid], ['cart_id', 'in', $cart_ids]], 'cart_id,refund_num', 'cart_id');
  1210. foreach ($orderRefundInfo['cart_info'] as $cart) {
  1211. $cart_refund_num = $cartInfos[$cart['id']]['refund_num'] ?? 0;
  1212. if ($cart['cart_num'] >= $cart_refund_num) {
  1213. $refund_num = 0;
  1214. } else {
  1215. $refund_num = bcsub((string)$cart_refund_num, (string)$cart['cart_num'], 0);
  1216. }
  1217. $storeOrderCartInfoServices->update(['oid' => $oid, 'cart_id' => $cart['id']], ['refund_num' => $refund_num]);
  1218. }
  1219. $storeOrderCartInfoServices->clearOrderCartInfo($oid);
  1220. //写入订单记录表
  1221. /** @var StoreOrderStatusServices $statusService */
  1222. $statusService = app()->make(StoreOrderStatusServices::class);
  1223. $statusService->save([
  1224. 'oid' => $oid,
  1225. 'change_type' => 'cancel_refund_order',
  1226. 'change_message' => '取消退款',
  1227. 'change_time' => time()
  1228. ]);
  1229. //售后订单取消后置事件
  1230. event('order.orderRefundCancelAfter', [$orderRefundInfo]);
  1231. // 推送订单
  1232. event('out.outPush', ['refund_cancel_push', ['order_id' => (int)$orderRefundInfo['id']]]);
  1233. return true;
  1234. }
  1235. /**
  1236. * 修改备注
  1237. * @param int $id
  1238. * @param string $remark
  1239. * @return bool
  1240. * @throws \think\db\exception\DataNotFoundException
  1241. * @throws \think\db\exception\DbException
  1242. * @throws \think\db\exception\ModelNotFoundException
  1243. */
  1244. public function updateRemark(int $id, string $remark)
  1245. {
  1246. if (!$id) {
  1247. throw new AdminException(100100);
  1248. }
  1249. if (!$remark) {
  1250. throw new AdminException(410177);
  1251. }
  1252. if (!$order = $this->dao->get($id)) {
  1253. throw new AdminException(410173);
  1254. }
  1255. $order->remark = $remark;
  1256. if (!$order->save()) {
  1257. throw new AdminException(100025);
  1258. }
  1259. return true;
  1260. }
  1261. /**
  1262. * 拒绝退款
  1263. * @param int $id
  1264. * @param string $refund_reason
  1265. * @return void
  1266. * @throws \think\db\exception\DataNotFoundException
  1267. * @throws \think\db\exception\DbException
  1268. * @throws \think\db\exception\ModelNotFoundException
  1269. */
  1270. public function refuse(int $id, string $refund_reason)
  1271. {
  1272. if (!$refund_reason) {
  1273. throw new AdminException(400499);
  1274. }
  1275. if (!$id || !($orderRefundInfo = $this->dao->get($id))) {
  1276. throw new AdminException(400118);
  1277. }
  1278. $refundData = [
  1279. 'refuse_reason' => $refund_reason,
  1280. 'refund_type' => 3,
  1281. 'refunded_time' => time()
  1282. ];
  1283. //拒绝退款处理
  1284. $this->refuseRefund($id, $refundData, $orderRefundInfo);
  1285. }
  1286. }