StoreOrderRefundServices.php 61 KB

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