StoreOrderRefundServices.php 62 KB

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