BalanceLogsService.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. <?php
  2. namespace App\Services\Common;
  3. use App\Models\AccountLogModel;
  4. use App\Models\BalanceLogModel;
  5. use App\Models\MemberModel;
  6. use App\Models\AgentModel;
  7. use App\Models\StoreModel;
  8. use App\Services\BaseService;
  9. use App\Services\PaymentService;
  10. use Illuminate\Support\Facades\DB;
  11. /**
  12. * 统一余额日志服务(充值/提现)
  13. * 支持会员、代理、商户的充值和提现记录
  14. */
  15. class BalanceLogsService extends BaseService
  16. {
  17. protected static $instance = null;
  18. /**
  19. * 构造函数
  20. * @author laravel开发员
  21. * @since 2020/11/11
  22. * AccountService constructor.
  23. */
  24. public function __construct()
  25. {
  26. $this->model = new BalanceLogModel();
  27. }
  28. /**
  29. * 静态入口
  30. * @return static|null
  31. */
  32. public static function make()
  33. {
  34. if (!self::$instance) {
  35. self::$instance = (new static());
  36. }
  37. return self::$instance;
  38. }
  39. /**
  40. * 获取列表
  41. * @param array $params 请求参数
  42. * @param int $currentUserId 当前用户的 member_id(member 表的 ID),用于数据隔离
  43. */
  44. public function getList($params = [], $currentUserId = null)
  45. {
  46. // 获取参数
  47. if (empty($params)) {
  48. $params = request()->all();
  49. }
  50. $page = $params['page'] ?? 1;
  51. $limit = $params['limit'] ?? 20;
  52. $keyword = $params['keyword'] ?? '';
  53. $user_id = $params['user_id'] ?? '';
  54. $status = $params['status'] ?? '';
  55. $type = $params['type'] ?? ''; // 1-充值,2-提现
  56. $accountType = $params['account_type'] ?? ''; // 1-会员,2-代理,3-商户
  57. $startTime = $params['start_time'] ?? '';
  58. $endTime = $params['end_time'] ?? '';
  59. $query = BalanceLogModel::where('mark', 1);
  60. // 数据隔离:只查询当前用户的记录(基于 member 表的 user_id)
  61. if ($currentUserId) {
  62. $query->where('user_id', $currentUserId);
  63. }
  64. // 类型筛选
  65. if ($type !== '') {
  66. $query->where('type', $type);
  67. }
  68. // 账户类型筛选
  69. if ($accountType !== '') {
  70. $query->where('account_type', $accountType);
  71. }
  72. // 关键词搜索(订单号、姓名、手机号)
  73. if (!empty($keyword)) {
  74. $query->where(function($q) use ($keyword) {
  75. $q->where('order_no', 'like', "%{$keyword}%")
  76. ->orWhere('realname', 'like', "%{$keyword}%")
  77. ->orWhereHas('user', function($sq) use ($keyword) {
  78. $sq->where('realname', 'like', "%{$keyword}%")
  79. ->orWhere('nickname', 'like', "%{$keyword}%")
  80. ->orWhere('mobile', 'like', "%{$keyword}%");
  81. });
  82. });
  83. }
  84. if(!empty($user_id)){
  85. $query->where("user_id", $user_id);
  86. }
  87. // 状态筛选
  88. if ($status !== '') {
  89. $query->where('status', $status);
  90. }
  91. // 时间范围
  92. if (!empty($startTime)) {
  93. $query->where('create_time', '>=', strtotime($startTime));
  94. }
  95. if (!empty($endTime)) {
  96. $query->where('create_time', '<=', strtotime($endTime . ' 23:59:59'));
  97. }
  98. // 打印 SQL 语句用于调试
  99. \Log::info('BalanceLogsService getList SQL: ' . $query->toSql());
  100. \Log::info('BalanceLogsService getList Bindings: ' . json_encode($query->getBindings()));
  101. $total = $query->count();
  102. $list = $query->with(['user:id,realname,nickname,mobile,user_type'])
  103. ->orderBy('create_time', 'desc')
  104. ->offset(($page - 1) * $limit)
  105. ->limit($limit)
  106. ->get()
  107. ->toArray();
  108. // 格式化数据
  109. foreach ($list as &$item) {
  110. $item['money'] = number_format($item['money'], 2, '.', '');
  111. $item['actual_money'] = number_format($item['actual_money'], 2, '.', '');
  112. $item['create_time_text'] = date('Y-m-d H:i:s', $item['create_time']);
  113. $item['update_time_text'] = date('Y-m-d H:i:s', $item['update_time']);
  114. $item['status_text'] = $this->getStatusText($item['status']);
  115. $item['pay_type_text'] = $this->getPayTypeText($item['pay_type']);
  116. $item['account_type_text'] = $this->getAccountTypeText($item['account_type']);
  117. $item['type_text'] = $item['type'] == 1 ? '充值' : '提现';
  118. // 根据账户类型添加额外信息
  119. if (isset($item['user'])) {
  120. $item['user_realname'] = $item['user']['realname'] ?? '';
  121. $item['user_nickname'] = $item['user']['nickname'] ?? '';
  122. $item['user_mobile'] = $item['user']['mobile'] ?? '';
  123. $item['user_type'] = $item['user']['user_type'] ?? 0;
  124. }
  125. }
  126. return [
  127. 'code' => 0,
  128. 'msg' => '获取成功',
  129. 'data' => $list,
  130. 'count' => $total
  131. ];
  132. }
  133. /**
  134. * 获取详情
  135. * @param int $id 记录ID
  136. * @param int $currentUserId 当前用户的 member_id(member 表的 ID),用于数据隔离
  137. */
  138. public function getInfo($id = null, $currentUserId = null)
  139. {
  140. // 如果没有传入ID,从请求中获取
  141. if ($id === null) {
  142. $id = request()->input('id');
  143. }
  144. $query = BalanceLogModel::where('id', $id)
  145. ->where('mark', 1);
  146. // 数据隔离:只能查看自己的记录(基于 member 表的 user_id)
  147. if ($currentUserId) {
  148. $query->where('user_id', $currentUserId);
  149. }
  150. $info = $query->with(['user:id,realname,nickname,mobile,user_type'])
  151. ->first();
  152. if (!$info) {
  153. return ['code' => 1, 'msg' => '记录不存在或无权访问'];
  154. }
  155. $info = $info->toArray();
  156. $info['money'] = number_format($info['money'], 2, '.', '');
  157. $info['actual_money'] = number_format($info['actual_money'], 2, '.', '');
  158. $info['create_time_text'] = date('Y-m-d H:i:s', $info['create_time']);
  159. $info['update_time_text'] = date('Y-m-d H:i:s', $info['update_time']);
  160. $info['status_text'] = $this->getStatusText($info['status']);
  161. $info['pay_type_text'] = $this->getPayTypeText($info['pay_type']);
  162. $info['account_type_text'] = $this->getAccountTypeText($info['account_type']);
  163. $info['type_text'] = $info['type'] == 1 ? '充值' : '提现';
  164. // 根据账户类型添加额外信息
  165. if (isset($info['user'])) {
  166. $info['user_realname'] = $info['user']['realname'] ?? '';
  167. $info['user_nickname'] = $info['user']['nickname'] ?? '';
  168. $info['user_mobile'] = $info['user']['mobile'] ?? '';
  169. $info['user_type'] = $info['user']['user_type'] ?? 0;
  170. }
  171. return [
  172. 'code' => 0,
  173. 'msg' => '获取成功',
  174. 'data' => $info
  175. ];
  176. }
  177. /**
  178. * 提交结算申请(商家/代理/会员提交)
  179. */
  180. public function apply($data)
  181. {
  182. try {
  183. $money = $data['money'] ?? 0;
  184. $account = $data['account'] ?? '';
  185. if($money<=0){
  186. return [
  187. 'code' => 1,
  188. 'msg' => '请输入提现金额'
  189. ];
  190. }
  191. if(empty($account)){
  192. return [
  193. 'code' => 1,
  194. 'msg' => '请输入提现账户'
  195. ];
  196. }
  197. $storeInfo = StoreModel::where(['user_id'=>$data['user_id']])->select(['id','balance','status'])
  198. ->first();
  199. $balance = isset($storeInfo['balance'])?$storeInfo['balance'] : 0;
  200. $status = isset($storeInfo['status'])?$storeInfo['status'] : 0;
  201. if(empty($storeInfo) || $status != 1){
  202. return [
  203. 'code' => 1,
  204. 'msg' => '商家账户不存在或已冻结,请联系客服'
  205. ];
  206. }
  207. if($balance<$money){
  208. return [
  209. 'code' => 1,
  210. 'msg' => '商家可提现余额不足'
  211. ];
  212. }
  213. // 扣除余额
  214. DB::beginTransaction();
  215. if(!StoreModel::where(['user_id'=>$data['user_id']])->update(['balance'=>DB::raw("balance - {$money}"),'update_time'=>time()])){
  216. DB::rollBack();
  217. return [
  218. 'code' => 1,
  219. 'msg' => '商家可提现余额不足'
  220. ];
  221. }
  222. // 生成订单号
  223. $orderNo = 'BL' . date('YmdHis') . rand(1000, 9999);
  224. $record = new BalanceLogModel();
  225. $record->order_no = $orderNo;
  226. $record->user_id = $data['user_id'] ?? 0; // 选择的用户ID
  227. $record->type = $data['type'] ?? 2; // 1-充值,2-提现
  228. $record->account_type = $data['account_type'] ?? 1;
  229. $record->realname = $data['realname'] ?? '';
  230. $record->money = $money;
  231. $record->actual_money = $data['money'] ?? 0; // 默认实际到账等于申请金额
  232. $record->pay_type = $data['pay_type'] ?? 10;
  233. $record->account = $account;
  234. $record->account_remark = $data['account_remark'] ?? '';
  235. $record->pay_status = 10; // 10-待支付
  236. $record->status = 1; // 1-待审核
  237. $record->date = date('Y-m-d H:i:s');
  238. $record->create_time = time();
  239. $record->update_time = time();
  240. $record->mark = 1;
  241. $record->save();
  242. DB::commit();
  243. return [
  244. 'code' => 0,
  245. 'msg' => '申请提交成功',
  246. 'data' => ['order_no' => $orderNo]
  247. ];
  248. } catch (\Exception $e) {
  249. return [
  250. 'code' => 1,
  251. 'msg' => '提交失败:' . $e->getMessage()
  252. ];
  253. }
  254. }
  255. /**
  256. * 审核结算申请(管理员审核)
  257. */
  258. public function audit($id = null, $status = null, $payStatus=null, $actualMoney = null, $remark = '', $payImg = '',)
  259. {
  260. // 如果没有传入参数,从请求中获取
  261. if ($id === null) {
  262. $params = request()->all();
  263. $id = $params['id'] ?? null;
  264. $status = $params['status'] ?? null;
  265. $actualMoney = $params['actual_money'] ?? null;
  266. $remark = $params['confirm_remark'] ?? ($params['remark'] ?? '');
  267. $payImg = $params['pay_img'] ?? '';
  268. }
  269. if (empty($id) || !in_array($status, [2, 3])) {
  270. return ['code' => 1, 'msg' => '参数错误'];
  271. }
  272. var_dump($status);
  273. var_dump($payImg);
  274. var_dump($payStatus);
  275. var_dump($actualMoney);
  276. DB::beginTransaction();
  277. try {
  278. $record = BalanceLogModel::with(['member'])->where('id', $id)
  279. ->where('mark', 1)
  280. ->lockForUpdate()
  281. ->first();
  282. if (!$record) {
  283. throw new \Exception('申请记录不存在');
  284. }
  285. if ($record->status != 1) {
  286. throw new \Exception('该记录已处理,无法重复审核');
  287. }
  288. // 更新状态
  289. $record->status = $status;
  290. $record->confirm_remark = $remark;
  291. $record->update_time = time();
  292. // 更新实际到账金额
  293. if ($actualMoney !== null) {
  294. $record->actual_money = $actualMoney;
  295. }
  296. // 如果是通过,更新支付状态和打款凭证
  297. if ($status == 2) {
  298. // 微信
  299. if($record->pay_type==10){
  300. // 若立即打款
  301. if($payStatus==20){
  302. $member = isset($record->member)?$record->member : [];
  303. $openid = isset($member['openid'])?$member['openid']: '';
  304. $wechatOpenid = isset($member['wechat_openid'])?$member['wechat_openid']: '';
  305. $openid = $openid?$openid:$wechatOpenid;
  306. if(empty($openid)){
  307. throw new \Exception('微信OPENID不为空,请确认该用户已授权登录过才可打款');
  308. }
  309. // 打款请求
  310. $order = [
  311. 'order_no'=> $record->order_no,
  312. 'pay_money'=> $record->actual_money,
  313. 'account'=> $openid,
  314. 'real_name'=> $record->realname,
  315. 'body'=>'收入提现',
  316. ];
  317. if(!$result = PaymentService::make()->transfer($order)){
  318. throw new \Exception(PaymentService::make()->getError());
  319. }
  320. var_dump($result);
  321. $record->batch_id = isset($result['batch_id'])?$result['batch_id']:''; //
  322. $record->pay_status = 20; // 20-已支付
  323. $record->pay_at = date('Y-m-d H:i:s');
  324. if (!empty($payImg)) {
  325. $record->pay_img = $payImg;
  326. }
  327. }
  328. }else{
  329. $record->pay_status = 20; // 20-已支付
  330. $record->pay_at = date('Y-m-d H:i:s');
  331. if (!empty($payImg)) {
  332. $record->pay_img = $payImg;
  333. }
  334. }
  335. // 如果是代理提现审核通过,更新代理表的累计提现金额
  336. if ($record->account_type == 2 && $record->type == 2) {
  337. $this->updateAgentWithdrawTotal($record);
  338. }
  339. }
  340. $record->save();
  341. // 如果是驳回且是提现,退回金额
  342. if ($status == 3 && $record->type == 2) {
  343. $this->refundBalance($record);
  344. }
  345. DB::commit();
  346. return ['code' => 0, 'msg' => '审核成功'];
  347. } catch (\Exception $e) {
  348. DB::rollBack();
  349. return ['code' => 1, 'msg' => '审核失败:' . $e->getMessage()];
  350. }
  351. }
  352. /**
  353. * 打款
  354. * @param $adminId
  355. * @param $params
  356. * @return array|false
  357. */
  358. public function payment($adminId, $id)
  359. {
  360. $info = $this->model->with(['member'])->where(['id'=> $id,'mark'=>1])->first();
  361. $userInfo = isset($info['member'])? $info['member'] : [];
  362. $openid = isset($userInfo['openid'])?$userInfo['openid']:'';
  363. $wechatOpenid = isset($userInfo['wechat_openid'])?$userInfo['wechat_openid']:'';
  364. $orderStatus = isset($info['status'])? $info['status'] : 0;
  365. $payType = isset($info['pay_type'])? $info['pay_type'] : 0;
  366. $payStatus = isset($info['pay_status'])? $info['pay_status'] : 0;
  367. $orderNo = isset($info['order_no'])? $info['order_no'] : '';
  368. $source = isset($info['source'])? $info['source'] : '';
  369. $realname = isset($info['realname'])? $info['realname'] : '';
  370. $orderUserId = isset($info['user_id'])? $info['user_id'] : 0;
  371. $money = isset($info['money'])? $info['money'] : 0;
  372. if(empty($info) || $orderUserId<=0 || $money<=0){
  373. $this->error = '提现信息不存在或参数错误';
  374. return false;
  375. }
  376. if($orderStatus != 2){
  377. $this->error = '请先审核提现';
  378. return false;
  379. }
  380. if($payStatus != 10){
  381. $this->error = '该提现已打款';
  382. return false;
  383. }
  384. // 是否微信
  385. if($payType != 10){
  386. $this->error = '该收款方式未开放线上打款';
  387. return false;
  388. }
  389. // 公众号
  390. if(empty($openid)){
  391. $openid = $wechatOpenid;
  392. }
  393. if(empty($openid)){
  394. $this->error = '微信OPENID不为空,请确认该用户已授权登录过';
  395. return false;
  396. }
  397. // 微信打款
  398. $order = [
  399. 'order_no'=> $orderNo,
  400. 'pay_money'=> $money,
  401. 'account'=> $openid,
  402. 'real_name'=> $realname,
  403. 'body'=>'收入提现',
  404. ];
  405. if(!$result = PaymentService::make()->transfer($order)){
  406. $this->error = PaymentService::make()->getError();
  407. return false;
  408. }
  409. DB::beginTransaction();
  410. $batchId = isset($result['batch_id'])?$result['batch_id']:'';
  411. $updateData = ['pay_status'=> 20,'pay_at'=>date('Y-m-d H:i:s'),'batch_id'=>$batchId,'receive_status'=> 2,'update_time'=>time()];
  412. if(!$this->model->where(['id'=> $id])->update($updateData)){
  413. DB::rollBack();
  414. $this->error = '提现打款处理失败';
  415. return false;
  416. }
  417. DB::commit();
  418. $this->error = '提现打款成功,请提醒用户确认收款';
  419. return ['id'=>$id,'money'=>$money,'result'=>$result];
  420. }
  421. /**
  422. * 更新代理表的累计提现金额
  423. */
  424. private function updateAgentWithdrawTotal($record)
  425. {
  426. // 查找代理记录
  427. $agent = AgentModel::where('user_id', $record->user_id)
  428. ->where('mark', 1)
  429. ->first();
  430. if ($agent) {
  431. // 累加提现金额到 withdraw_total
  432. $agent->withdraw_total = bcadd($agent->withdraw_total ?? 0, $record->actual_money, 2);
  433. $agent->save();
  434. }
  435. }
  436. /**
  437. * 退回余额(根据账户类型退回到对应的表)
  438. */
  439. private function refundBalance($record)
  440. {
  441. switch ($record->account_type) {
  442. case 1: // 会员账户
  443. $user = MemberModel::find($record->user_id);
  444. if ($user) {
  445. $user->balance = bcadd($user->balance, $record->money, 2);
  446. $user->save();
  447. }
  448. break;
  449. case 2: // 代理账户
  450. $agent = AgentModel::where('user_id', $record->user_id)
  451. ->where('mark', 1)
  452. ->first();
  453. if ($agent) {
  454. $agent->balance = bcadd($agent->balance, $record->money, 2);
  455. $agent->save();
  456. }
  457. break;
  458. case 3: // 商户账户
  459. $store = StoreModel::where('user_id', $record->user_id)
  460. ->where('mark', 1)
  461. ->first();
  462. if ($store) {
  463. $store->balance = bcadd($store->balance, $record->money, 2);
  464. $store->save();
  465. }
  466. break;
  467. }
  468. }
  469. /**
  470. * 删除记录
  471. * @param int $id 记录ID
  472. * @param int $currentUserId 当前用户的 member_id(member 表的 ID),用于数据隔离
  473. */
  474. public function delete($id = null, $currentUserId = null)
  475. {
  476. // 获取参数
  477. if ($id === null) {
  478. $id = request()->input('id');
  479. }
  480. $query = BalanceLogModel::where('id', $id)
  481. ->where('mark', 1);
  482. // 数据隔离:只能删除自己的记录(基于 member 表的 user_id)
  483. if ($currentUserId) {
  484. $query->where('user_id', $currentUserId);
  485. }
  486. $record = $query->first();
  487. if (!$record) {
  488. return ['code' => 1, 'msg' => '记录不存在或无权删除'];
  489. }
  490. if ($record->status == 1) {
  491. return ['code' => 1, 'msg' => '待审核的记录不能删除'];
  492. }
  493. $record->mark = 0;
  494. $record->save();
  495. return ['code' => 0, 'msg' => '删除成功'];
  496. }
  497. /**
  498. * 批量删除
  499. * @param array $ids 记录ID数组
  500. * @param int $currentUserId 当前用户的 member_id(member 表的 ID),用于数据隔离
  501. */
  502. public function deleteAll($ids = null, $currentUserId = null)
  503. {
  504. // 如果没有传入参数,从请求中获取
  505. if ($ids === null) {
  506. $ids = request()->input('ids', []);
  507. }
  508. $query = BalanceLogModel::whereIn('id', $ids)
  509. ->where('mark', 1)
  510. ->where('status', '!=', 1);
  511. // 数据隔离:只能删除自己的记录(基于 member 表的 user_id)
  512. if ($currentUserId) {
  513. $query->where('user_id', $currentUserId);
  514. }
  515. $count = $query->update(['mark' => 0]);
  516. return [
  517. 'code' => 0,
  518. 'msg' => "成功删除{$count}条记录"
  519. ];
  520. }
  521. /**
  522. * 获取状态文本
  523. */
  524. private function getStatusText($status)
  525. {
  526. $statusMap = [
  527. -1 => '已取消',
  528. 1 => '待审核',
  529. 2 => '已审核/到账',
  530. 3 => '审核失败'
  531. ];
  532. return $statusMap[$status] ?? '未知';
  533. }
  534. /**
  535. * 获取支付方式文本
  536. */
  537. private function getPayTypeText($payType)
  538. {
  539. $payTypeMap = [
  540. 10 => '微信',
  541. 20 => '支付宝',
  542. 50 => '银行卡'
  543. ];
  544. return $payTypeMap[$payType] ?? '未知';
  545. }
  546. /**
  547. * 获取账户类型文本
  548. */
  549. private function getAccountTypeText($accountType)
  550. {
  551. $accountTypeMap = [
  552. 1 => '会员',
  553. 2 => '代理',
  554. 3 => '商户'
  555. ];
  556. return $accountTypeMap[$accountType] ?? '未知';
  557. }
  558. /**
  559. * 获取代理等级文本
  560. */
  561. private function getAgentLevelText($level)
  562. {
  563. $levelMap = [
  564. 1 => '一级代理',
  565. 2 => '二级代理',
  566. 3 => '三级代理'
  567. ];
  568. return $levelMap[$level] ?? '未知';
  569. }
  570. }