BalanceLogsService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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, $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. DB::beginTransaction();
  273. try {
  274. $record = BalanceLogModel::where('id', $id)
  275. ->where('mark', 1)
  276. ->lockForUpdate()
  277. ->first();
  278. if (!$record) {
  279. throw new \Exception('申请记录不存在');
  280. }
  281. if ($record->status != 1) {
  282. throw new \Exception('该记录已处理,无法重复审核');
  283. }
  284. // 更新状态
  285. $record->status = $status;
  286. $record->confirm_remark = $remark;
  287. $record->update_time = time();
  288. // 更新实际到账金额
  289. if ($actualMoney !== null) {
  290. $record->actual_money = $actualMoney;
  291. }
  292. // 如果是通过,更新支付状态和打款凭证
  293. if ($status == 2) {
  294. $record->pay_status = 20; // 20-已支付
  295. $record->pay_at = date('Y-m-d H:i:s');
  296. if (!empty($payImg)) {
  297. $record->pay_img = $payImg;
  298. }
  299. // 如果是代理提现审核通过,更新代理表的累计提现金额
  300. if ($record->account_type == 2 && $record->type == 2) {
  301. $this->updateAgentWithdrawTotal($record);
  302. }
  303. }
  304. $record->save();
  305. // 如果是驳回且是提现,退回金额
  306. if ($status == 3 && $record->type == 2) {
  307. $this->refundBalance($record);
  308. }
  309. DB::commit();
  310. return ['code' => 0, 'msg' => '审核成功'];
  311. } catch (\Exception $e) {
  312. DB::rollBack();
  313. return ['code' => 1, 'msg' => '审核失败:' . $e->getMessage()];
  314. }
  315. }
  316. /**
  317. * 打款
  318. * @param $adminId
  319. * @param $params
  320. * @return array|false
  321. */
  322. public function payment($adminId, $id)
  323. {
  324. $info = $this->model->with(['member'])->where(['id'=> $id,'mark'=>1])->first();
  325. $userInfo = isset($info['member'])? $info['member'] : [];
  326. $openid = isset($userInfo['openid'])?$userInfo['openid']:'';
  327. $wechatOpenid = isset($userInfo['wechat_openid'])?$userInfo['wechat_openid']:'';
  328. $orderStatus = isset($info['status'])? $info['status'] : 0;
  329. $payType = isset($info['pay_type'])? $info['pay_type'] : 0;
  330. $payStatus = isset($info['pay_status'])? $info['pay_status'] : 0;
  331. $orderNo = isset($info['order_no'])? $info['order_no'] : '';
  332. $source = isset($info['source'])? $info['source'] : '';
  333. $realname = isset($info['realname'])? $info['realname'] : '';
  334. $orderUserId = isset($info['user_id'])? $info['user_id'] : 0;
  335. $money = isset($info['money'])? $info['money'] : 0;
  336. if(empty($info) || $orderUserId<=0 || $money<=0){
  337. $this->error = '提现信息不存在或参数错误';
  338. return false;
  339. }
  340. if($orderStatus != 2){
  341. $this->error = '请先审核提现';
  342. return false;
  343. }
  344. if($payStatus != 10){
  345. $this->error = '该提现已打款';
  346. return false;
  347. }
  348. // 是否微信
  349. if($payType != 10){
  350. $this->error = '该收款方式未开放线上打款';
  351. return false;
  352. }
  353. // 公众号
  354. if(empty($openid)){
  355. $openid = $wechatOpenid;
  356. }
  357. if(empty($openid)){
  358. $this->error = '微信OPENID不为空,请确认该用户已授权登录过';
  359. return false;
  360. }
  361. // 微信打款
  362. $order = [
  363. 'order_no'=> $orderNo,
  364. 'pay_money'=> $money,
  365. 'account'=> $openid,
  366. 'real_name'=> $realname,
  367. 'body'=>'收入提现',
  368. ];
  369. if(!$result = PaymentService::make()->transfer($order)){
  370. $this->error = PaymentService::make()->getError();
  371. return false;
  372. }
  373. DB::beginTransaction();
  374. $batchId = isset($result['batch_id'])?$result['batch_id']:'';
  375. $updateData = ['pay_status'=> 20,'pay_at'=>date('Y-m-d H:i:s'),'batch_id'=>$batchId,'receive_status'=> 2,'update_time'=>time()];
  376. if(!$this->model->where(['id'=> $id])->update($updateData)){
  377. DB::rollBack();
  378. $this->error = '提现打款处理失败';
  379. return false;
  380. }
  381. DB::commit();
  382. $this->error = '提现打款成功,请提醒用户确认收款';
  383. return ['id'=>$id,'money'=>$money,'result'=>$result];
  384. }
  385. /**
  386. * 更新代理表的累计提现金额
  387. */
  388. private function updateAgentWithdrawTotal($record)
  389. {
  390. // 查找代理记录
  391. $agent = AgentModel::where('user_id', $record->user_id)
  392. ->where('mark', 1)
  393. ->first();
  394. if ($agent) {
  395. // 累加提现金额到 withdraw_total
  396. $agent->withdraw_total = bcadd($agent->withdraw_total ?? 0, $record->actual_money, 2);
  397. $agent->save();
  398. }
  399. }
  400. /**
  401. * 退回余额(根据账户类型退回到对应的表)
  402. */
  403. private function refundBalance($record)
  404. {
  405. switch ($record->account_type) {
  406. case 1: // 会员账户
  407. $user = MemberModel::find($record->user_id);
  408. if ($user) {
  409. $user->balance = bcadd($user->balance, $record->money, 2);
  410. $user->save();
  411. }
  412. break;
  413. case 2: // 代理账户
  414. $agent = AgentModel::where('user_id', $record->user_id)
  415. ->where('mark', 1)
  416. ->first();
  417. if ($agent) {
  418. $agent->balance = bcadd($agent->balance, $record->money, 2);
  419. $agent->save();
  420. }
  421. break;
  422. case 3: // 商户账户
  423. $store = StoreModel::where('user_id', $record->user_id)
  424. ->where('mark', 1)
  425. ->first();
  426. if ($store) {
  427. $store->balance = bcadd($store->balance, $record->money, 2);
  428. $store->save();
  429. }
  430. break;
  431. }
  432. }
  433. /**
  434. * 删除记录
  435. * @param int $id 记录ID
  436. * @param int $currentUserId 当前用户的 member_id(member 表的 ID),用于数据隔离
  437. */
  438. public function delete($id = null, $currentUserId = null)
  439. {
  440. // 获取参数
  441. if ($id === null) {
  442. $id = request()->input('id');
  443. }
  444. $query = BalanceLogModel::where('id', $id)
  445. ->where('mark', 1);
  446. // 数据隔离:只能删除自己的记录(基于 member 表的 user_id)
  447. if ($currentUserId) {
  448. $query->where('user_id', $currentUserId);
  449. }
  450. $record = $query->first();
  451. if (!$record) {
  452. return ['code' => 1, 'msg' => '记录不存在或无权删除'];
  453. }
  454. if ($record->status == 1) {
  455. return ['code' => 1, 'msg' => '待审核的记录不能删除'];
  456. }
  457. $record->mark = 0;
  458. $record->save();
  459. return ['code' => 0, 'msg' => '删除成功'];
  460. }
  461. /**
  462. * 批量删除
  463. * @param array $ids 记录ID数组
  464. * @param int $currentUserId 当前用户的 member_id(member 表的 ID),用于数据隔离
  465. */
  466. public function deleteAll($ids = null, $currentUserId = null)
  467. {
  468. // 如果没有传入参数,从请求中获取
  469. if ($ids === null) {
  470. $ids = request()->input('ids', []);
  471. }
  472. $query = BalanceLogModel::whereIn('id', $ids)
  473. ->where('mark', 1)
  474. ->where('status', '!=', 1);
  475. // 数据隔离:只能删除自己的记录(基于 member 表的 user_id)
  476. if ($currentUserId) {
  477. $query->where('user_id', $currentUserId);
  478. }
  479. $count = $query->update(['mark' => 0]);
  480. return [
  481. 'code' => 0,
  482. 'msg' => "成功删除{$count}条记录"
  483. ];
  484. }
  485. /**
  486. * 获取状态文本
  487. */
  488. private function getStatusText($status)
  489. {
  490. $statusMap = [
  491. -1 => '已取消',
  492. 1 => '待审核',
  493. 2 => '已审核/到账',
  494. 3 => '审核失败'
  495. ];
  496. return $statusMap[$status] ?? '未知';
  497. }
  498. /**
  499. * 获取支付方式文本
  500. */
  501. private function getPayTypeText($payType)
  502. {
  503. $payTypeMap = [
  504. 10 => '微信',
  505. 20 => '支付宝',
  506. 50 => '银行卡'
  507. ];
  508. return $payTypeMap[$payType] ?? '未知';
  509. }
  510. /**
  511. * 获取账户类型文本
  512. */
  513. private function getAccountTypeText($accountType)
  514. {
  515. $accountTypeMap = [
  516. 1 => '会员',
  517. 2 => '代理',
  518. 3 => '商户'
  519. ];
  520. return $accountTypeMap[$accountType] ?? '未知';
  521. }
  522. /**
  523. * 获取代理等级文本
  524. */
  525. private function getAgentLevelText($level)
  526. {
  527. $levelMap = [
  528. 1 => '一级代理',
  529. 2 => '二级代理',
  530. 3 => '三级代理'
  531. ];
  532. return $levelMap[$level] ?? '未知';
  533. }
  534. }