StoreOrderRefundServices.php 61 KB

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