StoreOrderRefundServices.php 62 KB

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