StoreOrderRefundServices.php 64 KB

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