StoreOrderRefundServices.php 61 KB

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