StoreOrderRefundServices.php 61 KB

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