RefundController.php 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. <?php
  2. namespace app\admin\controller\order;
  3. use app\admin\service\member\MemberService;
  4. use app\admin\validate\order\ReturnValidate;
  5. use app\controller\Curd;
  6. use app\model\CouponDetail;
  7. use app\model\GoodsComponent;
  8. use app\model\Member;
  9. use app\model\MemberAccount;
  10. use app\model\Order;
  11. use app\model\OrderExpress;
  12. use app\model\OrderReturn;
  13. use app\model\OrderSheet;
  14. use app\model\PayDetail;
  15. use app\model\SysUser;
  16. use Payment\Common\PayException;
  17. use support\Db;
  18. use support\exception\BusinessException;
  19. use support\Log;
  20. use support\Request;
  21. use support\Response;
  22. use Tinywan\Jwt\JwtToken;
  23. use Webman\Event\Event;
  24. use Yansongda\Pay\Pay;
  25. class RefundController extends Curd
  26. {
  27. public function __construct()
  28. {
  29. $this->model = new OrderReturn();
  30. $this->validate = true;
  31. $this->validateClass = new ReturnValidate();
  32. }
  33. public function select(Request $request): Response
  34. {
  35. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  36. $order = $request->get('order', 'desc');
  37. $type = $request->get('type', '');
  38. $field = $field ?? 'order_return_addtimes';
  39. $where['order_return_category'] = ['in', ['退款', '会员退款']];
  40. if (!empty($where['order_return_addtimes'])) {
  41. $where['order_return_addtimes'][0] = strtotime($where['order_return_addtimes'][0]);
  42. $where['order_return_addtimes'][1] = strtotime($where['order_return_addtimes'][1]);
  43. }
  44. if ($type == 'today') {
  45. $where['order_return_addtimes'] = [
  46. strtotime(date('Y-m-d') . ' 00:00:00'),
  47. strtotime(date('Y-m-d') . ' 23:59:59')
  48. ];
  49. }
  50. $query = $this->doSelect($where, $field, $order);
  51. return $this->doFormat($query, $format, $limit);
  52. }
  53. protected function doSelect(array $where, string $field = null, string $order = 'desc')
  54. {
  55. $model = $this->model->with([
  56. 'member' => function ($query) {
  57. $query->select('member_id', 'member_mobile');
  58. },
  59. 'cert' => function ($query) {
  60. $query->select('join_cert_member_id', 'member_cert_name');
  61. },
  62. 'order' => function ($query) {
  63. $query->select('order_id', 'order_name');
  64. }
  65. ]);
  66. foreach ($where as $column => $value) {
  67. if (is_array($value)) {
  68. if ($value[0] === 'like' || $value[0] === 'not like') {
  69. $model = $model->where($column, $value[0], "%$value[1]%");
  70. } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
  71. $model = $model->where($column, $value[0], $value[1]);
  72. } elseif ($value[0] == 'in' && !empty($value[1])) {
  73. $valArr = $value[1];
  74. if (is_string($value[1])) {
  75. $valArr = explode(",", trim($value[1]));
  76. }
  77. $model = $model->whereIn($column, $valArr);
  78. } elseif ($value[0] == 'not in' && !empty($value[1])) {
  79. $valArr = $value[1];
  80. if (is_string($value[1])) {
  81. $valArr = explode(",", trim($value[1]));
  82. }
  83. $model = $model->whereNotIn($column, $valArr);
  84. } elseif ($value[0] == 'null') {
  85. $model = $model->whereNull($column);
  86. } elseif ($value[0] == 'not null') {
  87. $model = $model->whereNotNull($column);
  88. } elseif ($value[0] !== '' || $value[1] !== '') {
  89. $model = $model->whereBetween($column, $value);
  90. }
  91. } else {
  92. $model = $model->where($column, $value);
  93. }
  94. }
  95. if ($field) {
  96. $model = $model->orderBy($field, $order);
  97. }
  98. return $model;
  99. }
  100. public function afterQuery($items)
  101. {
  102. foreach ($items as &$item) {
  103. if (!empty($item['order'])) {
  104. $orderSheet = OrderSheet::with([
  105. 'goods' => function ($query) {
  106. $query->select('goods_id', 'goods_name');
  107. }
  108. ])->select('join_sheet_order_id', 'join_sheet_goods_id')
  109. ->where('join_sheet_order_id', $item['order']->order_id)
  110. ->get()
  111. ->toArray();
  112. $goodsName = !empty($orderSheet) ? $orderSheet[0]['goods']['goods_name'] : '';
  113. if (count($orderSheet) > 1) {
  114. $goodsName .= ' 等';
  115. }
  116. $item['goods_name'] = $goodsName;
  117. }
  118. if (!empty($item['order_return_apply_json']) && is_json($item['order_return_apply_json'])) {
  119. // $json = json_decode($item['order_return_apply_json'], true);
  120. // $item['order_return_apply_json'] = $json['apply'] ?? '';
  121. }
  122. if (!empty($item['order_return_recharge_json']) && is_json($item['order_return_recharge_json'])) {
  123. $json = json_decode($item['order_return_recharge_json'], true);
  124. $item['order_return_recharge_json'] = $json['change'] ?? '';
  125. }
  126. if (!empty($item['order_return_refund_json']) && is_json($item['order_return_refund_json'])) {
  127. $returnRefundJson = json_decode($item['order_return_refund_json'], true);
  128. if (!empty($returnRefundJson['user_id'])) {
  129. $item['userName'] = SysUser::where('user_id', $returnRefundJson['user_id'])->value('user_name');
  130. }
  131. }
  132. }
  133. return $items;
  134. }
  135. /**
  136. * @Desc 退款管理顶部统计
  137. * @Author Gorden
  138. * @Date 2024/10/31 11:37
  139. *
  140. * @param Request $request
  141. * @return Response
  142. */
  143. public function statistics(Request $request)
  144. {
  145. $status = $request->get('order_return_status');
  146. $memberId = $request->get('join_return_member_id');
  147. $orderId = $request->get('orderId');
  148. $orderReturnAddtimes = $request->get('order_return_addtimes');
  149. if (!empty($orderReturnAddtimes)) {
  150. $orderReturnAddtimes[0] = strtotime($orderReturnAddtimes[0]);
  151. $orderReturnAddtimes[1] = strtotime($orderReturnAddtimes[1]);
  152. }
  153. $returnModel = OrderReturn::when(!empty($status), function ($query) use ($status) {
  154. $query->where('order_return_status', $status);
  155. })->when(!empty($memberId), function ($query) use ($memberId) {
  156. $query->where('join_return_member_id', $memberId);
  157. })->when(!empty($orderId), function ($query) use ($orderId) {
  158. $query->where('join_return_order_id', 'like', '%' . $orderId . '%');
  159. })->when(!empty($orderReturnAddtimes), function ($query) use ($orderReturnAddtimes) {
  160. $query->whereBetween('order_return_addtimes', $orderReturnAddtimes);
  161. });
  162. $totalModel = clone $returnModel;
  163. $total = $totalModel->selectRaw("SUM(JSON_UNQUOTE(JSON_EXTRACT(order_return_apply_json,'$.amount'))) as amount,count(orders_return_id) as total")
  164. ->first()
  165. ->toArray();
  166. $total['amount'] = sprintf('%.2f', round($total['amount'], 2));
  167. $pendingTotalModel = clone $returnModel;
  168. $pendingTotal = $pendingTotalModel->where('order_return_status', 'PENDING')
  169. ->selectRaw("SUM(JSON_UNQUOTE(JSON_EXTRACT(order_return_apply_json,'$.amount'))) as amount,count(orders_return_id) as total")
  170. ->first()
  171. ->toArray();
  172. $pendingTotal['amount'] = sprintf('%.2f', round($pendingTotal['amount'], 2));
  173. $doingTotalModel = clone $returnModel;
  174. $doingTotal = $doingTotalModel->where('order_return_status', 'DOING')
  175. ->selectRaw("SUM(JSON_UNQUOTE(JSON_EXTRACT(order_return_apply_json,'$.amount'))) as amount,count(orders_return_id) as total")
  176. ->first()
  177. ->toArray();
  178. $doingTotal['amount'] = sprintf('%.2f', round($doingTotal['amount'], 2));
  179. $disagreeTotalModel = clone $returnModel;
  180. $disagreeTotal = $disagreeTotalModel->where('order_return_status', 'DISAGREE')
  181. ->selectRaw("SUM(JSON_UNQUOTE(JSON_EXTRACT(order_return_apply_json,'$.amount'))) as amount,count(orders_return_id) as total")
  182. ->first()
  183. ->toArray();
  184. $disagreeTotal['amount'] = sprintf('%.2f', round($disagreeTotal['amount'], 2));
  185. $doneTotalModel = clone $returnModel;
  186. $doneTotal = $doneTotalModel->where('order_return_status', 'DONE')
  187. ->selectRaw("SUM(JSON_UNQUOTE(JSON_EXTRACT(order_return_apply_json,'$.amount'))) as amount,count(orders_return_id) as total")
  188. ->first()
  189. ->toArray();
  190. $doneTotal['amount'] = sprintf('%.2f', round($doneTotal['amount'], 2));
  191. return json_success('success', [
  192. 'total' => $total,
  193. 'pendingTotal' => $pendingTotal,
  194. 'doingTotal' => $doingTotal,
  195. 'disagreeTotal' => $disagreeTotal,
  196. 'doneTotal' => $doneTotal
  197. ]);
  198. }
  199. protected function updateInput(Request $request): array
  200. {
  201. $primary_key = $this->model->getKeyName();
  202. $id = $request->post($primary_key);
  203. $data = $this->inputFilter($request->post());
  204. $model = $this->model->find($id);
  205. if (!$model) {
  206. throw new BusinessException('记录不存在', 2);
  207. }
  208. if (empty($model->order_return_accept_datetimes) && $model->order_return_status == 'PENDING' && $data['order_return_status'] == 'DOING') {
  209. $data['order_return_accept_datetimes'] = date('Y-m-d H:i:s');
  210. }
  211. if (!empty($data['order_return_apply_json'])) {
  212. $data['order_return_apply_json'] = json_encode(['apply' => $data['order_return_apply_json']]);
  213. }
  214. if (!empty($data['order_return_recharge_json'])) {
  215. $data['order_return_recharge_json'] = json_encode(['change' => $data['order_return_recharge_json']]);
  216. }
  217. unset($data[$primary_key]);
  218. return [$id, $data];
  219. }
  220. /**
  221. * @Desc 订单商品详情
  222. * @Author Gorden
  223. * @Date 2024/3/29 8:50
  224. *
  225. * @param Request $request
  226. * @return Response
  227. */
  228. public function sheet(Request $request)
  229. {
  230. $orderId = $request->get('order_id');
  231. $orderSheet = OrderSheet::with([
  232. 'member' => function ($query) {
  233. $query->select('member_id', 'member_mobile', 'join_member_role_id', 'member_is_owner', 'member_is_vip', 'member_is_partner', 'member_is_referrer', 'member_is_franchisee');
  234. },
  235. 'goods' => function ($query) {
  236. $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_market_price', 'goods_sales_price', 'goods_classify');
  237. },
  238. 'sku' => function ($query) {
  239. $query->select('goods_sku_id', 'join_sku_goods_id', 'goods_sku_specs_json', 'goods_sku_sales_price');
  240. },
  241. 'memberInfo',
  242. 'cert',
  243. 'refund'
  244. ])->where('join_sheet_order_id', $orderId)
  245. ->get()
  246. ->toArray();
  247. $member = [];
  248. $cert = [];
  249. $memberInfo = [];
  250. $sheets = [];
  251. foreach ($orderSheet as &$item) {
  252. if (isset($item['member']) && empty($member)) {
  253. $member = $item['member'];
  254. $member['level'] = MemberService::getRoleName($member['join_member_role_id'] ?? '');
  255. }
  256. if (isset($item['cert']) && empty($cert)) {
  257. $cert = $item['cert'];
  258. }
  259. if (isset($item['member_info']) && empty($memberInfo)) {
  260. $memberInfo = $item['member_info'];
  261. $memberInfo['member_info_nickname'] = $memberInfo['member_info_nickname'] ?? MemberService::getMemberNickname($member['member_mobile'] ?? '');
  262. $memberInfo['member_info_headimg'] = MemberService::getAvatarUrl($memberInfo['member_info_headimg'] ?? '');
  263. }
  264. $item['goods']['goods_cover'] = getenv('STORAGE_DOMAIN') . $item['goods']['goods_cover'];
  265. if (!empty($item['goods']) && $item['goods']['goods_classify'] == 'PACKAGE') {
  266. $components = GoodsComponent::with('goods')
  267. ->where('join_component_master_goods_id', $item['goods']['goods_id'])
  268. ->select('join_component_master_goods_id', 'join_component_goods_id', 'goods_component_price',
  269. 'goods_component_price')
  270. ->get()
  271. ->toArray();
  272. $goodsArr = [];
  273. foreach ($components as $component) {
  274. $configJson = !empty($component['goods_component_config_json']) ? json_decode($component['goods_component_config_json'], true) : [];
  275. if (!empty($component['goods'])) {
  276. $goodsArr[] = [
  277. 'goods_name' => $component['goods']['goods_name'],
  278. 'goods_cover' => getenv('STORAGE_DOMAIN') . $component['goods']['goods_cover'],
  279. 'nbr' => $configJson['nbr'] ?? 0,
  280. ];
  281. }
  282. }
  283. $item['goods']['components'] = $goodsArr;
  284. }
  285. if (!empty($item['sku'])) {
  286. if (!empty($item['sku']['goods_sku_specs_json'])) {
  287. $specsJson = json_decode($item['sku']['goods_sku_specs_json'], true);
  288. $skuName = '';
  289. foreach ($specsJson as $specsKey => $skuSpecs) {
  290. if (is_array($skuSpecs)) {
  291. $skuName = $skuName . ' ' . implode(' ', $skuSpecs) . ';';
  292. } else {
  293. $skuName = $skuName . ' ' . $skuSpecs . ';';
  294. }
  295. }
  296. $item['sku']['goods_sku_title'] = rtrim($skuName, ';');
  297. }
  298. }
  299. if (!empty($item['refund'])) {
  300. if (!empty($item['refund']['order_return_apply_json']) && is_json($item['refund']['order_return_apply_json'])) {
  301. $json = json_decode($item['refund']['order_return_apply_json'], true);
  302. $item['refund']['order_return_apply_json'] = $json['reason'] ?? '';
  303. }
  304. if (!empty($item['refund']['order_return_recharge_json']) && is_json($item['refund']['order_return_recharge_json'])) {
  305. $json = json_decode($item['refund']['order_return_recharge_json'], true);
  306. $item['refund']['order_return_recharge_json'] = $json['change'] ?? '';
  307. }
  308. }
  309. }
  310. $order = Order::where('order_id', $orderId)->first();
  311. $return = OrderReturn::where('join_return_order_id', $orderId)->first();
  312. if (!empty($return->order_return_refund_json)) {
  313. $returnRefundJson = json_decode($return->order_return_refund_json, true);
  314. if (!empty($returnRefundJson['user_id'])) {
  315. $return->userName = SysUser::where('user_id', $returnRefundJson['user_id'])->value('user_name');
  316. }
  317. }
  318. if (!empty($return->order_return_apply_json)) {
  319. $returnApplyJson = json_decode($return->order_return_apply_json, true);
  320. if (!empty($returnApplyJson['order_id'])) {
  321. $sheets = OrderSheet::with([
  322. 'goods' => function ($query) {
  323. $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_market_price', 'goods_sales_price', 'goods_classify');
  324. },
  325. 'sku' => function ($query) {
  326. $query->select('goods_sku_id', 'join_sku_goods_id', 'goods_sku_specs_json', 'goods_sku_sales_price');
  327. },
  328. ])->whereIn('join_sheet_order_id', $returnApplyJson['order_id'])
  329. ->select('order_sheet_id', 'join_sheet_goods_id', 'join_sheet_goods_sku_id', 'order_sheet_num', 'order_sheet_price', 'order_sheet_amount')
  330. ->get()
  331. ->toArray();
  332. foreach ($sheets as $key => $sheetsItem) {
  333. if (empty($sheetsItem['goods'])) {
  334. unset($sheets[$key]);
  335. continue;
  336. }
  337. $sheets[$key]['goods']['goods_cover'] = getenv('STORAGE_DOMAIN') . $sheetsItem['goods']['goods_cover'];
  338. if (!empty($sheetsItem['sku'])) {
  339. if (!empty($item['sku']['goods_sku_specs_json'])) {
  340. $specsJson = json_decode($item['sku']['goods_sku_specs_json'], true);
  341. $skuName = '';
  342. foreach ($specsJson as $specsKey => $skuSpecs) {
  343. if (is_array($skuSpecs)) {
  344. $skuName = $skuName . ' ' . implode(' ', $skuSpecs) . ';';
  345. } else {
  346. $skuName = $skuName . ' ' . $skuSpecs . ';';
  347. }
  348. }
  349. $sheets[$key]['sku']['goods_sku_title'] = rtrim($skuName, ';');
  350. }
  351. }
  352. }
  353. $sheets = array_values($sheets);
  354. }
  355. }
  356. $express = OrderExpress::where('join_express_order_id', $orderId)->first();
  357. $payDetails = PayDetail::where('join_pay_order_id', $order->order_groupby)
  358. ->whereJsonContains('join_pay_object_json->order_id', $orderId)
  359. ->where('pay_status', 'SUCCESS')
  360. ->where('pay_category', '<>', 'REFUND')
  361. ->get()
  362. ->toArray();
  363. if (count($payDetails) > 1) {
  364. $order->pay_category = 'CONSTITUTE';
  365. }
  366. $payDetail = !empty($payDetails) && count($payDetails) > 0 ? $payDetails[0] : [];
  367. if (!empty($payDetail) && !empty($payDetail['pay_prepayid'])) {
  368. $categoryArray = explode('-', $payDetail['pay_prepayid']);
  369. if (isset($categoryArray[1])) {
  370. $payDetail['pay_category'] = $categoryArray[1];
  371. } else if (in_array($categoryArray[0], ['WXPAY', 'ALIPAY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY', 'MONEY'])) {
  372. $payDetail['pay_category'] = $categoryArray[0];
  373. }
  374. }
  375. $data = [
  376. 'member' => $member,
  377. 'cert' => $cert,
  378. 'member_info' => $memberInfo,
  379. 'order' => $order,
  380. 'refund' => $return,
  381. 'sheet' => $orderSheet,
  382. 'sheets' => $sheets,
  383. 'express' => $express,
  384. 'payDetail' => json_decode(json_encode($payDetail)),
  385. 'payDetails' => json_decode(json_encode($payDetails))
  386. ];
  387. return json_success('', $data);
  388. }
  389. /**
  390. * @Desc 会员退款详情
  391. * @Author Gorden
  392. * @Date 2024/10/25 9:21
  393. *
  394. * @param Request $request
  395. * @return Response
  396. */
  397. public function rechargeSheet(Request $request)
  398. {
  399. $returnId = $request->get('return_id');
  400. if (!$returnId) {
  401. return json_fail("参数异常");
  402. }
  403. $return = OrderReturn::with([
  404. 'member' => function ($query) {
  405. $query->select('member_id', 'member_mobile', 'join_member_role_id', 'member_is_owner', 'member_is_vip', 'member_is_partner', 'member_is_referrer');
  406. },
  407. 'info' => function ($query) {
  408. $query->select('join_info_member_id', 'member_info_nickname', 'member_info_headimg');
  409. },
  410. 'cert' => function ($query) {
  411. $query->select('join_cert_member_id', 'member_cert_name');
  412. },
  413. ])->where('orders_return_id', $returnId)
  414. ->first();
  415. if (!$return) {
  416. return json_fail('数据异常');
  417. }
  418. $return = $return->toArray();
  419. $return['role_name'] = MemberService::getRoleName(!empty($return['member']) ? $return['member']['join_member_role_id'] : '');
  420. $return['info']['member_info_nickname'] = MemberService::getNickname(!empty($return['info']) ? $return['info']['member_info_nickname'] : '', !empty($return['member']) ? $return['member']['member_mobile'] : '');
  421. $return['info']['member_info_headimg'] = MemberService::getAvatarUrl(!empty($return['info']) ? $return['info']['member_info_headimg'] : '');
  422. if (!empty($return['order_return_apply_json']) && is_json($return['order_return_apply_json'])) {
  423. $json = json_decode($return['order_return_apply_json'], true);
  424. $return['reason'] = $json['reason'] ?? '';
  425. $return['order_return_apply_json'] = $json;
  426. }
  427. if (!empty($return['order_return_recharge_json']) && is_json($return['order_return_recharge_json'])) {
  428. $json = json_decode($return['order_return_recharge_json'], true);
  429. $return['change'] = $json['change'] ?? '';
  430. }
  431. if (!empty($return['join_order_return_user_id'])) {
  432. $return['disposeUserName'] = SysUser::where('user_id', $return['join_order_return_user_id'])->value('user_name');
  433. }
  434. if (!empty($return['order_return_refund_json'])) {
  435. $returnRefundJson = json_decode($return['order_return_refund_json'], true);
  436. if (!empty($returnRefundJson['user_id'])) {
  437. $return['userName'] = SysUser::where('user_id', $returnRefundJson['user_id'])->value('user_name');
  438. }
  439. }
  440. $data = [
  441. 'refund' => $return,
  442. ];
  443. return json_success('', $data);
  444. }
  445. public function customRefund(Request $request)
  446. {
  447. $orderId = $request->post('order_id', '');
  448. $amount = $request->post('refund_amount', 0);
  449. $password = $request->post('refund_password', '');
  450. $remark = $request->post('refund_remark', '');
  451. if (!$orderId || !$amount || !$password) {
  452. return json_fail('参数异常');
  453. }
  454. if ($password != '123456') {
  455. return json_fail('支付密码错误');
  456. }
  457. $order = Order::where('order_id', $orderId)->where('order_status_payment', 'SUCCESS')->first();
  458. if (!$order) {
  459. return json_fail("订单异常");
  460. }
  461. if ($amount > $order->order_amount_pay) {
  462. return json_fail("退款金额不能超过支付金额");
  463. }
  464. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)
  465. ->whereJsonContains('join_pay_object_json->order_id', $orderId)
  466. ->where('pay_status', 'SUCCESS')
  467. ->where('pay_prepayid', '<>', '')
  468. ->whereIn('pay_category', ['GOODS', 'SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DISHES', 'VIP', 'PACKAGE'])
  469. ->get()
  470. ->toArray();
  471. if (empty($payDetail)) {
  472. return json_fail("支付状态异常");
  473. }
  474. $refundPayIds = array_column($payDetail, 'pay_id');
  475. $response = [];
  476. Db::beginTransaction();
  477. try {
  478. // 全额退款,检查优惠券,恢复可使用
  479. if (sprintf("%.2f", $amount) == sprintf("%.2f", $order->order_amount_pay)) {
  480. if (!empty($order->order_discount_json)) {
  481. $discountJson = json_decode($order->order_discount_json, true);
  482. foreach ($discountJson as $item) {
  483. if (empty($item['coupon_id'])) {
  484. continue;
  485. }
  486. // 是否有其他订单一起使用优惠券
  487. if (!Order::where('order_groupby', $order->order_groupby)->where('order_id', '<>', $order->order_id)->where('order_is_complete', '<>', 'R')->exists()) {
  488. foreach ($item['coupon_detail_id'] as $detailId) {
  489. CouponDetail::where('coupon_detail_id', $detailId)->update([
  490. 'coupon_detail_status' => 'ACTIVED',
  491. 'coupon_detail_used_datetime' => ''
  492. ]);
  493. }
  494. }
  495. }
  496. }
  497. }
  498. // 主订单,退款作为优惠入库
  499. $this->updateMainOrderByRefund($order, $amount, $remark);
  500. // return 表记录
  501. $return = OrderReturn::where('join_return_order_id', $orderId)->first();
  502. if (empty($return)) {
  503. $returnId = $this->createReturnRecord($order, $amount, $remark);
  504. } else {
  505. $returnId = $return->orders_return_id;
  506. //['amount' => $amount, 'user_id' => JwtToken::getCurrentId(), 'datetime' => date('Y-m-d H:i:s'), 'remark' => $remark ?? '']
  507. OrderReturn::where('join_return_order_id', $orderId)->update([
  508. 'order_return_status' => 'DONE',
  509. 'order_return_refund_json' => json_encode([
  510. 'amount' => $amount,
  511. 'user_id' => JwtToken::getCurrentId(),
  512. 'datetime' => date('Y-m-d H:i:s'),
  513. 'remark' => $remark ?? ''
  514. ])
  515. ]);
  516. }
  517. // 组合支付,退到余额账户
  518. $prepayid = '';
  519. if (count($payDetail) > 1) {
  520. $prepayid = $order->join_order_member_id . '-CASH';
  521. $this->refundToCash($order->join_order_member_id, $amount);
  522. $response = ['order_id' => $order->order_id, 'member_id' => $order->join_order_member_id];
  523. } else if (count($payDetail) == 1) {
  524. $payDetail0 = $payDetail[0];
  525. $payWay = explode('-', $payDetail0['pay_prepayid']);
  526. if ($payWay[0] == 'WXPAY') {
  527. $prepayid = 'WXPAY';
  528. $response = $this->refundToWx($payDetail0, $returnId, $amount);
  529. } elseif ($payWay[0] == 'ALIPAY') {
  530. $prepayid = 'ALIPAY';
  531. $payDetail0['order_id'] = $order->order_id;
  532. $response = $this->refundToAlipay($payDetail0, $amount);
  533. } elseif ($payWay[0] == 'MONEY') {
  534. $prepayid = 'MONEY';
  535. // $response = $this->refundToCash($order->join_order_member_id, $amount);
  536. } elseif (isset($payWay[1]) && $payWay[1] == 'CASH') {
  537. $prepayid = $order->join_order_member_id . '-CASH';
  538. $this->refundToCash($order->join_order_member_id, $amount);
  539. $response = ['order_id' => $order->order_id, 'member_id' => $order->join_order_member_id];
  540. } elseif (isset($payWay[1]) && $payWay[1] == 'WELFARE') {
  541. $prepayid = $order->join_order_member_id . '-WELFARE';
  542. $this->refundToWelfare($order->join_order_member_id, $amount);
  543. $response = ['order_id' => $order->order_id, 'member_id' => $order->join_order_member_id];
  544. } elseif (isset($payWay[1]) && $payWay[1] == 'VIP') {
  545. $prepayid = $order->join_order_member_id . '-VIP';
  546. $this->refundToVIP($order->join_order_member_id, $amount);
  547. $response = ['order_id' => $order->order_id, 'member_id' => $order->join_order_member_id];
  548. } elseif (isset($payWay['1']) && $payWay[1] == 'CARD') {
  549. $prepayid = $order->join_order_member_id . '-CARD';
  550. $this->refundToCard($order->join_order_member_id, $amount);
  551. $response = ['order_id' => $order->order_id, 'member_id' => $order->join_order_member_id];
  552. } elseif ($payWay[0] == 'OFFLINE') {
  553. $prepayid = 'OFFLINE';
  554. $response = [];
  555. } elseif ($payWay[0] == 'OFFLINE_ALIPAY') {
  556. $prepayid = 'OFFLINE_ALIPAY';
  557. $response = [];
  558. } elseif ($payWay[0] == 'OFFLINE_WXPAY') {
  559. $prepayid = 'OFFLINE_WXPAY';
  560. $response = [];
  561. }
  562. }
  563. // payDetail 表记录
  564. $this->createReturnPayDetail($order, $refundPayIds, $prepayid, $amount, $response);
  565. Db::commit();
  566. // 退款入收支
  567. $params['orderId'] = $orderId;
  568. $params['type'] = 'refund';
  569. Event::dispatch('statistics.inout.out', $params);
  570. return json_success('success');
  571. } catch (BusinessException $e) {
  572. Db::rollBack();
  573. Log::info("退款失败", ['msg' => $e->getMessage()]);
  574. return json_fail($e->getMessage());
  575. } catch (\Exception $e) {
  576. Db::rollBack();
  577. Log::info("退款失败", ['msg' => $e->getMessage()]);
  578. return json_fail("退款失败");
  579. }
  580. }
  581. /**
  582. * @Desc 退款到余额
  583. * @Author Gorden
  584. * @Date 2024/8/20 11:54
  585. *
  586. * @param $memberId
  587. * @param $amount
  588. * @return void
  589. * @throws BusinessException
  590. */
  591. private function refundToCash($memberId, $amount)
  592. {
  593. $account = MemberAccount::where('join_account_member_id', $memberId)->where('member_account_classify', 'CASH')->first();
  594. if (!$account) {
  595. throw new BusinessException("余额账户异常");
  596. }
  597. $account->member_account_surplus = $account->member_account_surplus + $amount;
  598. $account->member_account_expend = $account->member_account_expend - $amount;
  599. $account->member_account_update_user_id = JwtToken::getCurrentId();
  600. $account->member_account_updatetimes = time();
  601. $account->save();
  602. }
  603. /**
  604. * @Desc 退款到福利账户
  605. * @Author Gorden
  606. * @Date 2024/9/20 17:09
  607. *
  608. * @param $memberId
  609. * @param $amount
  610. * @return void
  611. * @throws BusinessException
  612. */
  613. private function refundToWelfare($memberId, $amount)
  614. {
  615. $account = MemberAccount::where('join_account_member_id', $memberId)->where('member_account_classify', 'WELFARE')->first();
  616. if (!$account) {
  617. throw new BusinessException("余额账户异常");
  618. }
  619. $account->member_account_surplus = $account->member_account_surplus + $amount;
  620. $account->member_account_expend = $account->member_account_expend - $amount;
  621. $account->member_account_update_user_id = JwtToken::getCurrentId();
  622. $account->member_account_updatetimes = time();
  623. $account->save();
  624. }
  625. /**
  626. * @Desc 退款到VIP账户
  627. * @Author Gorden
  628. * @Date 2024/9/20 17:12
  629. *
  630. * @param $memberId
  631. * @param $amount
  632. * @return void
  633. * @throws BusinessException
  634. */
  635. private function refundToVIP($memberId, $amount)
  636. {
  637. $account = MemberAccount::where('join_account_member_id', $memberId)->where('member_account_classify', 'VIP')->first();
  638. if (!$account) {
  639. throw new BusinessException("余额账户异常");
  640. }
  641. $account->member_account_surplus = $account->member_account_surplus + $amount;
  642. $account->member_account_expend = $account->member_account_expend - $amount;
  643. $account->member_account_update_user_id = JwtToken::getCurrentId();
  644. $account->member_account_updatetimes = time();
  645. $account->save();
  646. }
  647. /**
  648. * @Desc 退款到储蓄卡
  649. * @Author Gorden
  650. * @Date 2024/8/20 14:47
  651. *
  652. * @param $memberId
  653. * @param $amount
  654. * @return void
  655. * @throws BusinessException
  656. */
  657. private function refundToCard($cardNbr, $amount)
  658. {
  659. $account = MemberAccount::where('member_account_nbr', $cardNbr)->where('member_account_classify', 'CARD')->first();
  660. if (!$account) {
  661. throw new BusinessException("储值卡账户异常");
  662. }
  663. $account->member_account_surplus = $account->member_account_surplus + $amount;
  664. $account->member_account_expend = $account->member_account_expend - $amount;
  665. $account->member_account_update_user_id = JwtToken::getCurrentId();
  666. $account->member_account_updatetimes = time();
  667. $account->save();
  668. }
  669. /**
  670. * @Desc
  671. * @Author Gorden
  672. * @Date 2024/8/20 14:17
  673. *
  674. * @param $params
  675. * @param $returnId
  676. * @param $amount
  677. * @return mixed
  678. * @throws BusinessException
  679. * @throws \Yansongda\Pay\Exceptions\GatewayException
  680. * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
  681. * @throws \Yansongda\Pay\Exceptions\InvalidSignException
  682. */
  683. private function refundToWx($params, $returnId, $amount)
  684. {
  685. try {
  686. $data = [
  687. 'type' => 'app',
  688. 'out_trade_no' => $params['join_pay_order_id'],
  689. 'out_refund_no' => $returnId,
  690. 'total_fee' => $params['pay_amount'] * 100,
  691. 'refund_fee' => $amount * 100,
  692. 'refund_desc' => '退款',
  693. ];
  694. $res = Pay::wechat(config('payment.wxpay'))->refund($data);
  695. $resArray = json_decode($res, true);
  696. if ($resArray['result_code'] != 'SUCCESS' || $resArray['return_code'] != 'SUCCESS') {
  697. Log::channel('pay')->error('WXPAY_REFUND_FAIL', $resArray);
  698. throw new BusinessException("退款失败");
  699. }
  700. Log::info("退款响应", $resArray);
  701. return $resArray;
  702. } catch (\Exception $e) {
  703. Log::error("微信退款失败", ['msg' => $e->getMessage()]);
  704. throw new BusinessException("退款失败");
  705. }
  706. }
  707. /**
  708. * @Desc 支付宝退款
  709. * @Author Gorden
  710. * @Date 2024/8/20 14:40
  711. *
  712. * @param $params
  713. * @param $amount
  714. * @return mixed
  715. * @throws BusinessException
  716. */
  717. private function refundToAlipay($params, $amount)
  718. {
  719. $data = [
  720. 'out_trade_no' => $params['join_pay_order_id'],
  721. 'refund_amount' => $amount,
  722. 'out_request_no' => $params['order_id']
  723. ];
  724. Log::error("支付宝退款参数", $data);
  725. try {
  726. $res = Pay::alipay(config('payment.alipay'))->refund($data);
  727. $resArray = json_decode($res, true);
  728. if ($resArray['fund_change'] != 'Y' || $resArray['msg'] != 'Success') {
  729. Log::channel('pay')->error('ALIPAY_REFUND_FAIL', $resArray);
  730. throw new BusinessException("退款失败");
  731. }
  732. return $resArray;
  733. } catch (\Exception $e) {
  734. Log::error("支付宝退款失败", ['msg' => $e->getMessage()]);
  735. throw new BusinessException("退款失败");
  736. }
  737. }
  738. /**
  739. * @Desc 更新主订单
  740. * @Author Gorden
  741. * @Date 2024/8/20 14:56
  742. *
  743. * @param $order
  744. * @param $amount
  745. * @param $remark
  746. * @return void
  747. * @throws BusinessException
  748. */
  749. private function updateMainOrderByRefund($order, $amount, $remark)
  750. {
  751. $orderDiscountJson = [];
  752. if (!empty($order->order_discount_json)) {
  753. $orderDiscountJson = json_decode($order->order_discount_json, true);
  754. }
  755. try {
  756. $orderDiscountJson[date('Y-m-d H:i:s')] = [
  757. 'coupon_id' => null,
  758. 'coupon_value' => $amount,
  759. 'coupon_classify' => '退款',
  760. 'coupon_detail_id' => [$remark]
  761. ];
  762. $order->order_discount_json = json_encode($orderDiscountJson, JSON_UNESCAPED_UNICODE);
  763. $order->order_is_complete = 'R';
  764. $order->order_category = 'RETURN';
  765. // $order->order_amount_pay = $order->order_amount_pay - $amount;
  766. $order->save();
  767. } catch (\Exception $e) {
  768. throw new BusinessException("退款失败");
  769. }
  770. }
  771. /**
  772. * @Desc
  773. * @Author Gorden
  774. * @Date 2024/8/20 13:51
  775. *
  776. * @param $order
  777. * @return int
  778. * @throws BusinessException
  779. */
  780. private function createReturnRecord($order, $amount, $remark)
  781. {
  782. try {
  783. return OrderReturn::insertGetId([
  784. 'join_order_return_user_id' => JwtToken::getCurrentId(),
  785. 'join_return_member_id' => $order->join_order_member_id,
  786. 'join_return_order_id' => $order->order_id,
  787. 'order_return_status' => 'DONE',
  788. 'order_return_category' => '退款',
  789. 'order_return_apply_datetime' => date('Y-m-d H:i:s'),
  790. 'order_return_apply_json' => json_encode(['reason' => '后台自定义退款', 'amount' => $amount]),
  791. 'order_return_accept_datetime' => date('Y-m-d H:i:s'),
  792. 'order_return_refund_json' => json_encode(['amount' => $amount, 'user_id' => JwtToken::getCurrentId(), 'datetime' => date('Y-m-d H:i:s'), 'remark' => $remark ?? '']),
  793. 'order_return_addtimes' => time()
  794. ]);
  795. } catch (\Exception $e) {
  796. throw new BusinessException("创建退款信息失败");
  797. }
  798. }
  799. private function createReturnPayDetail($order, $refundPayIds, $prepayid, $amount, $response = [])
  800. {
  801. try {
  802. return PayDetail::insert([
  803. 'join_pay_member_id' => $order->join_order_member_id,
  804. 'join_pay_order_id' => $order->order_groupby,
  805. 'pay_status' => 'SUCCESS',
  806. 'pay_category' => 'REFUND',
  807. 'pay_amount' => $amount,
  808. 'pay_paytimes' => date('Y-m-d H:i:s'),
  809. 'pay_prepayid' => $prepayid,
  810. 'join_pay_object_json' => json_encode(['order_id' => $order->order_id, 'refund_pay_ids' => $refundPayIds]),
  811. 'pay_json_request' => json_encode(['order_id' => $order->order_id]),
  812. 'pay_json_response' => json_encode($response),
  813. 'pay_addtimes' => time()
  814. ]);
  815. } catch (\Exception $e) {
  816. }
  817. }
  818. /**
  819. * @Desc 充值退款详情
  820. * @Author Gorden
  821. * @Date 2024/10/16 11:40
  822. *
  823. * @param Request $request
  824. * @return Response
  825. */
  826. // public function rechargeSheet(Request $request)
  827. // {
  828. // $refundId = $request->get('return_id');
  829. // if (!$refundId) {
  830. // return json_fail("参数异常");
  831. // }
  832. //
  833. // $refund = OrderReturn::where('orders_return_id', $refundId)
  834. // ->first();
  835. // if (!empty($refund->order_return_apply_json)) {
  836. // $refund->order_return_apply_json = json_decode($refund->order_return_apply_json);
  837. // }
  838. //
  839. //
  840. // return json_success('', $refund);
  841. // }
  842. /**
  843. * @Desc 充值退款
  844. * @Author Gorden
  845. * @Date 2024/10/16 11:42
  846. *
  847. * @param Request $request
  848. * @return Response
  849. */
  850. public function rechargeRefund(Request $request)
  851. {
  852. $memberId = $request->post('member_id');
  853. $refundId = $request->post('return_id');
  854. $password = $request->post('refund_password', '');
  855. if (!$memberId) {
  856. return json_fail('参数异常');
  857. }
  858. if ($password != '123456') {
  859. return json_fail('支付密码错误');
  860. }
  861. $returnOrder = OrderReturn::where('orders_return_id', $refundId)
  862. ->where('join_return_member_id', $memberId)
  863. ->where('order_return_status', 'DOING')
  864. ->where('order_return_category', '会员退款')
  865. ->first();
  866. if (!$returnOrder) {
  867. return json_fail("退款数据异常");
  868. }
  869. $memberAccount = MemberAccount::where('join_account_member_id', $memberId)
  870. ->where('member_account_classify', 'CASH')
  871. ->where('member_account_status', 'ACTIVED')
  872. ->first();
  873. if (!$memberAccount) {
  874. return json_fail('会员账户异常');
  875. }
  876. try {
  877. Db::beginTransaction();
  878. $refundApplyJson = json_decode($returnOrder->order_return_apply_json, true);
  879. // 应减金额等于 扣除金额 + 银行打款金额
  880. $amount = $refundApplyJson['surplus'] + $refundApplyJson['amount'];
  881. $addedAmount = $refundApplyJson['added'];
  882. $refundApplyJson['added_amount'] = $addedAmount;
  883. $refundApplyJson['user_id'] = JwtToken::getCurrentId();
  884. $refundApplyJson['datetime'] = date('Y-m-d H:i:s');
  885. $refundApplyJson['remark'] = $request->post('refund_remark', '');
  886. $returnOrder->order_return_refund_json = json_encode($refundApplyJson);
  887. $returnOrder->order_return_status = 'DONE';
  888. $returnOrder->order_return_remark = $request->post('refund_remark', '');
  889. $returnOrder->save();
  890. // 账户剩余
  891. if ($memberAccount->member_account_surplus < $amount) {
  892. throw new BusinessException("账户本金余额不足");
  893. }
  894. if ($memberAccount->member_account_added < $addedAmount) {
  895. throw new BusinessException("账户增值余额不足");
  896. }
  897. // 本金
  898. $memberAccount->member_account_surplus = $memberAccount->member_account_surplus - $amount;
  899. // 增值
  900. $memberAccount->member_account_added = $memberAccount->member_account_added - $addedAmount;
  901. $memberAccount->member_account_update_user_id = JwtToken::getCurrentId();
  902. $memberAccount->member_account_updatetimes = time();
  903. $memberAccount->save();
  904. // 删除会员身份
  905. Member::where('member_id', $memberId)
  906. ->update([
  907. 'join_member_role_id' => '',
  908. 'member_role_begintime' => '',
  909. 'member_role_config_json' => '[]'
  910. ]);
  911. // 没用的优惠券失效
  912. CouponDetail::where('join_coupon_detail_member_id', $memberId)
  913. ->where('coupon_detail_status', '<>', 'USED')
  914. ->whereJsonContains('coupon_detail_extend_json->gettype', 'ROLE')
  915. ->update([
  916. 'coupon_detail_status' => 'DISABLED'
  917. ]);
  918. // 产生两条退款记录 (pay_detail)
  919. $payDetailInsertData = [
  920. 'join_pay_member_id' => $memberId,
  921. 'join_pay_order_id' => 'ROLE_REFUND',
  922. 'join_pay_object_json' => '[]',
  923. 'pay_status' => 'SUCCESS',
  924. 'pay_category' => 'ROLE_REFUND',
  925. 'pay_amount' => $refundApplyJson['amount'],
  926. 'pay_paytimes' => date('Y-m-d H:i:s'),
  927. 'pay_prepayid' => $memberId . '-CASH',
  928. 'pay_addtimes' => time()
  929. ];
  930. // 退款记录
  931. PayDetail::insert($payDetailInsertData);
  932. // 扣除记录
  933. $payDetailInsertData['join_pay_order_id'] = 'ROLE_DEDUCT';
  934. $payDetailInsertData['pay_category'] = 'ROLE_DEDUCT';
  935. $payDetailInsertData['pay_amount'] = $refundApplyJson['surplus'] + $addedAmount;
  936. PayDetail::insert($payDetailInsertData);
  937. Db::commit();
  938. return json_success('success');
  939. } catch (BusinessException $e) {
  940. Db::rollBack();
  941. return json_fail($e->getMessage());
  942. } catch (\Exception $e) {
  943. Db::rollBack();
  944. return json_fail('退款失败');
  945. }
  946. }
  947. }