StoreOrderRefundServices.php 58 KB

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