BalanceLogsService.php 16 KB

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