BalanceLogsService.php 21 KB

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