RefundController.php 42 KB

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