User.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. <?php
  2. namespace App\Http\Controllers\admin;
  3. use App\Constants\HttpStatus;
  4. use App\Http\Controllers\Controller;
  5. use App\Services\SecretService;
  6. use App\Services\TopUpService;
  7. use Illuminate\Support\Facades\App;
  8. use Illuminate\Support\Facades\DB;
  9. use App\Services\UserService;
  10. use App\Services\RegisterStatService;
  11. use Exception;
  12. use Illuminate\Validation\ValidationException;
  13. use App\Services\AddressService;
  14. use Illuminate\Http\JsonResponse;
  15. use App\Models\User as UserModel;
  16. use App\Models\UserSession;
  17. use App\Models\UserLogin;
  18. use App\Models\ThirdGameRecycle;
  19. use App\Models\Wallet;
  20. use App\Services\BalanceLogService;
  21. use App\Services\ThirdGameBalanceService;
  22. use Illuminate\Support\Facades\Cache;
  23. use Illuminate\Support\Str;
  24. class User extends Controller
  25. {
  26. //修改用户密码/资金密码
  27. function setPassword()
  28. {
  29. try {
  30. $params = request()->validate([
  31. 'member_id' => ['required', 'string', 'min:1'],
  32. 'password' => ['nullable', 'string', 'min:6', 'max:16'],
  33. 'payment_password' => ['nullable', 'string', 'min:6', 'max:16'],
  34. ]);
  35. $user = UserModel::where('member_id', $params['member_id'])->first();
  36. if (!$user) throw new Exception("用户不存在", HttpStatus::CUSTOM_ERROR);
  37. if (!empty($params['password'])) {
  38. $user->password = create_password($params['password']);
  39. $user->save();
  40. //删除缓存
  41. $token = UserSession::where('user_id', $params['member_id'])->orderByDesc('expire_time')->value('token');
  42. Cache::delete('token_user_' . $token);
  43. UserSession::where('user_id', $params['member_id'])->delete();
  44. }
  45. if (!empty($params['payment_password'])) {
  46. $user->payment_password = password_hash($params['payment_password'], PASSWORD_DEFAULT);
  47. $user->save();
  48. }
  49. } catch (ValidationException $e) {
  50. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  51. } catch (Exception $e) {
  52. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  53. }
  54. return $this->success();
  55. }
  56. function banned()
  57. {
  58. try {
  59. $params = request()->validate([
  60. 'member_id' => ['required', 'string', 'min:1'],
  61. 'is_banned' => ['required', 'integer', 'in:0,1'],
  62. ]);
  63. UserModel::where('member_id', $params['member_id'])->update(['is_banned' => $params['is_banned']]);
  64. if ($params['is_banned'] == 1) {
  65. //如果用户被禁用,删除所有会话
  66. UserSession::where('user_id', $params['member_id'])->delete();
  67. return $this->success();
  68. }
  69. } catch (ValidationException $e) {
  70. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  71. } catch (Exception $e) {
  72. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  73. }
  74. return $this->success();
  75. }
  76. function setNote()
  77. {
  78. try {
  79. $params = request()->validate([
  80. 'member_id' => ['required', 'string', 'min:1'],
  81. 'admin_note' => ['required', 'string', 'min:1', 'max:120'],
  82. ]);
  83. $user = UserModel::where('member_id', $params['member_id'])->first();
  84. if (!$user) throw new Exception("用户不存在", HttpStatus::CUSTOM_ERROR);
  85. $user->admin_note = $params['admin_note'];
  86. $user->save();
  87. } catch (ValidationException $e) {
  88. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  89. } catch (Exception $e) {
  90. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  91. }
  92. return $this->success();
  93. }
  94. /** 会员“查看”弹窗:历史总充值、总提现、总赠送彩金 */
  95. public function fundTotals(): JsonResponse
  96. {
  97. try {
  98. $params = request()->validate(['member_id' => ['required', 'string', 'min:1', 'max:64']]);
  99. // 和会员列表同一口径:只能查列表里看得到的会员(不含后台模拟会员)
  100. if (!\App\Support\MemberAudience::visibleUsers(DB::table('users'))->where('member_id', $params['member_id'])->exists()) {
  101. throw new Exception('会员不存在');
  102. }
  103. return $this->success(\App\Services\MemberFundTotalsService::totals($params['member_id']));
  104. } catch (ValidationException $e) {
  105. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  106. } catch (Exception $e) {
  107. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  108. }
  109. }
  110. public function index(): JsonResponse
  111. {
  112. try {
  113. $search = request()->validate([
  114. 'page' => ['nullable', 'integer', 'min:1'],
  115. 'limit' => ['nullable', 'integer', 'min:1'],
  116. 'member_id' => ['nullable', 'string', 'min:1'],
  117. 'account' => ['nullable', 'string', 'min:1'],
  118. 'like_first_name' => ['nullable', 'string', 'min:1'],
  119. 'username' => ['nullable', 'string', 'min:1'],
  120. 'register_ip' => ['nullable', 'string', 'min:1'],
  121. 'order' => ['nullable', 'string', 'in:asc,desc'],
  122. 'by' => ['nullable', 'string', 'in:available_balance,created_at,last_active_time,frozen_balance,yuebao,total_consume,wager_required,wager_completed,wager_remaining,third_game_total_balance'],
  123. 'sort_field' => ['nullable', 'string', 'in:available_balance,created_at,last_active_time,frozen_balance,yuebao,total_consume,wager_required,wager_completed,wager_remaining,third_game_total_balance'],
  124. 'sort_order' => ['nullable', 'string', 'in:asc,desc'],
  125. 'user_code' => ['nullable'],
  126. 'agent_user_code' => ['nullable'],
  127. 'level' => ['nullable'],
  128. 'from' => ['nullable'],
  129. 'is_online' => ['nullable', 'boolean'],
  130. 'start_time' => ['nullable', 'date', 'date_format:Y-m-d', 'required_with:end_time'],
  131. 'end_time' => ['nullable', 'date', 'date_format:Y-m-d', 'required_with:start_time'],
  132. 'recharge_channel_group_id' => ['nullable'],
  133. ]);
  134. $sortField = $search['sort_field'] ?? $search['by'] ?? 'created_at';
  135. $sortOrder = $search['sort_order'] ?? $search['order'] ?? 'desc';
  136. $result = UserService::paginate($search, $sortOrder, $sortField);
  137. } catch (ValidationException $e) {
  138. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first().'ssss');
  139. } catch (Exception $e) {
  140. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  141. }
  142. return $this->success($result);
  143. }
  144. /**
  145. * 查询指定用户在 ag、pg 等三方游戏平台的余额明细。
  146. */
  147. public function thirdGameDetail(ThirdGameBalanceService $service): JsonResponse
  148. {
  149. try {
  150. $params = request()->validate([
  151. 'member_id' => ['required', 'string', 'min:1'],
  152. ]);
  153. if (!UserModel::where('member_id', $params['member_id'])->exists()) {
  154. throw new Exception('用户不存在', HttpStatus::CUSTOM_ERROR);
  155. }
  156. $result = $service->detail((string) $params['member_id']);
  157. if (!$result['ok']) {
  158. throw new Exception($result['msg'], HttpStatus::CUSTOM_ERROR);
  159. }
  160. unset($result['ok']);
  161. return $this->success($result);
  162. } catch (ValidationException $e) {
  163. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  164. } catch (Exception $e) {
  165. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  166. }
  167. }
  168. /**
  169. * 一键回收指定用户的全部三方游戏余额并入账主钱包。
  170. */
  171. public function recycleThirdGameBalance(ThirdGameBalanceService $service): JsonResponse
  172. {
  173. $lock = null;
  174. $lockAcquired = false;
  175. try {
  176. $params = request()->validate([
  177. 'member_id' => ['required', 'string', 'min:1'],
  178. ]);
  179. $memberId = (string) $params['member_id'];
  180. if (!UserModel::where('member_id', $memberId)->exists()) {
  181. throw new Exception('用户不存在', HttpStatus::CUSTOM_ERROR);
  182. }
  183. if (!Wallet::where('member_id', $memberId)->exists()) {
  184. throw new Exception('用户钱包不存在', HttpStatus::CUSTOM_ERROR);
  185. }
  186. $lock = Cache::lock('admin_third_game_recycle:' . $memberId, 120);
  187. $lockAcquired = $lock->get();
  188. if (!$lockAcquired) {
  189. throw new Exception('该用户正在回收三方余额,请勿重复操作', HttpStatus::CUSTOM_ERROR);
  190. }
  191. $pendingCredit = ThirdGameRecycle::where('member_id', $memberId)
  192. ->where('status', ThirdGameRecycle::STATUS_PROVIDER_SUCCEEDED)
  193. ->orderBy('id')
  194. ->first();
  195. if ($pendingCredit) {
  196. try {
  197. $credited = $this->creditThirdGameRecycle($pendingCredit->id);
  198. } catch (Exception $e) {
  199. throw new Exception(
  200. '三方余额已回收但钱包补入账失败,流水号:' . $pendingCredit->operation_id,
  201. HttpStatus::CUSTOM_ERROR
  202. );
  203. }
  204. $credited['recovered_pending_operation'] = true;
  205. return $this->success($credited);
  206. }
  207. $unresolved = ThirdGameRecycle::where('member_id', $memberId)
  208. ->whereIn('status', [
  209. ThirdGameRecycle::STATUS_PENDING,
  210. ThirdGameRecycle::STATUS_UNCERTAIN,
  211. ])
  212. ->orderByDesc('id')
  213. ->first();
  214. if ($unresolved) {
  215. throw new Exception(
  216. '存在待核对的三方回收流水:' . $unresolved->operation_id . ',请先人工核对三方账单',
  217. HttpStatus::CUSTOM_ERROR
  218. );
  219. }
  220. $operation = ThirdGameRecycle::create([
  221. 'operation_id' => (string) Str::uuid(),
  222. 'member_id' => $memberId,
  223. 'player_id' => $service->playerId($memberId),
  224. 'status' => ThirdGameRecycle::STATUS_PENDING,
  225. ]);
  226. $recycled = $service->recycle($memberId);
  227. if (!$recycled['ok']) {
  228. $operation->status = !empty($recycled['uncertain'])
  229. ? ThirdGameRecycle::STATUS_UNCERTAIN
  230. : ThirdGameRecycle::STATUS_FAILED;
  231. $operation->error = $recycled['msg'];
  232. $operation->save();
  233. throw new Exception(
  234. $recycled['msg'] . ',流水号:' . $operation->operation_id,
  235. HttpStatus::CUSTOM_ERROR
  236. );
  237. }
  238. $operation->status = ThirdGameRecycle::STATUS_PROVIDER_SUCCEEDED;
  239. $operation->game_balance = $recycled['game_balance'];
  240. $operation->wallet_balance = $recycled['wallet_balance'];
  241. $operation->save();
  242. try {
  243. $credited = $this->creditThirdGameRecycle($operation->id);
  244. } catch (Exception $e) {
  245. throw new Exception(
  246. '三方余额已回收但钱包入账失败,请重试回收以补入账,流水号:' . $operation->operation_id,
  247. HttpStatus::CUSTOM_ERROR
  248. );
  249. }
  250. return $this->success($credited);
  251. } catch (ValidationException $e) {
  252. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  253. } catch (Exception $e) {
  254. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  255. } finally {
  256. if ($lockAcquired && $lock) {
  257. $lock->release();
  258. }
  259. }
  260. }
  261. /**
  262. * 将三方已回收的流水幂等入账;事务失败时保留 provider_succeeded 供下次补偿。
  263. */
  264. private function creditThirdGameRecycle(int $operationId): array
  265. {
  266. return DB::transaction(function () use ($operationId) {
  267. $operation = ThirdGameRecycle::where('id', $operationId)->lockForUpdate()->firstOrFail();
  268. if ($operation->status === ThirdGameRecycle::STATUS_COMPLETED) {
  269. $walletBalance = (float) Wallet::where('member_id', $operation->member_id)
  270. ->value('available_balance');
  271. return $this->recycleResponse($operation, $walletBalance);
  272. }
  273. if ($operation->status !== ThirdGameRecycle::STATUS_PROVIDER_SUCCEEDED) {
  274. throw new Exception('三方回收流水状态不可入账', HttpStatus::CUSTOM_ERROR);
  275. }
  276. $wallet = Wallet::where('member_id', $operation->member_id)->lockForUpdate()->firstOrFail();
  277. $before = (string) $wallet->available_balance;
  278. $walletGain = (string) $operation->wallet_balance;
  279. $after = bcadd($before, $walletGain, 10);
  280. if (bccomp($walletGain, '0', 10) > 0) {
  281. BalanceLogService::addLog(
  282. $operation->member_id,
  283. $walletGain,
  284. $before,
  285. $after,
  286. '三方游戏转出',
  287. $operation->id,
  288. '后台一键回收游戏余额'
  289. );
  290. $wallet->available_balance = $after;
  291. $wallet->save();
  292. }
  293. $operation->status = ThirdGameRecycle::STATUS_COMPLETED;
  294. $operation->credited_at = now();
  295. $operation->save();
  296. return $this->recycleResponse($operation, (float) $after);
  297. });
  298. }
  299. private function recycleResponse(ThirdGameRecycle $operation, float $walletBalance): array
  300. {
  301. return [
  302. 'operation_id' => $operation->operation_id,
  303. 'member_id' => $operation->member_id,
  304. 'recovered_game_balance' => (float) $operation->game_balance,
  305. 'recovered_balance' => (float) $operation->wallet_balance,
  306. 'wallet_balance' => $walletBalance,
  307. ];
  308. }
  309. /**
  310. * 查询三方游戏回收流水,用于核对 pending/uncertain 状态。
  311. */
  312. public function thirdGameRecycleRecords(): JsonResponse
  313. {
  314. try {
  315. $params = request()->validate([
  316. 'page' => ['nullable', 'integer', 'min:1'],
  317. 'limit' => ['nullable', 'integer', 'min:1', 'max:100'],
  318. 'member_id' => ['nullable', 'string', 'min:1'],
  319. 'status' => ['nullable', 'string', 'in:pending,provider_succeeded,completed,failed,uncertain'],
  320. ]);
  321. $page = (int) ($params['page'] ?? 1);
  322. $limit = (int) ($params['limit'] ?? 15);
  323. $query = ThirdGameRecycle::query()
  324. ->when(!empty($params['member_id']), function ($query) use ($params) {
  325. $query->where('member_id', $params['member_id']);
  326. })
  327. ->when(!empty($params['status']), function ($query) use ($params) {
  328. $query->where('status', $params['status']);
  329. });
  330. $total = (clone $query)->count();
  331. $list = $query->orderByDesc('id')->forPage($page, $limit)->get();
  332. return $this->success(['total' => $total, 'data' => $list]);
  333. } catch (ValidationException $e) {
  334. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  335. } catch (Exception $e) {
  336. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  337. }
  338. }
  339. /**
  340. * 人工核对待确认流水:确认未回收,或按三方实际金额补入账。
  341. */
  342. public function resolveThirdGameRecycle(ThirdGameBalanceService $service): JsonResponse
  343. {
  344. $lock = null;
  345. $lockAcquired = false;
  346. try {
  347. $params = request()->validate([
  348. 'operation_id' => ['required', 'uuid'],
  349. 'action' => ['required', 'string', 'in:failed,credit'],
  350. 'game_balance' => ['nullable', 'required_if:action,credit', 'numeric', 'min:0'],
  351. 'remark' => ['nullable', 'string', 'max:500'],
  352. ]);
  353. $operation = ThirdGameRecycle::where('operation_id', $params['operation_id'])->first();
  354. if (!$operation) {
  355. throw new Exception('三方回收流水不存在', HttpStatus::CUSTOM_ERROR);
  356. }
  357. $lock = Cache::lock('admin_third_game_recycle:' . $operation->member_id, 120);
  358. $lockAcquired = $lock->get();
  359. if (!$lockAcquired) {
  360. throw new Exception('该用户正在处理三方回收,请稍后再试', HttpStatus::CUSTOM_ERROR);
  361. }
  362. $operation = DB::transaction(function () use ($operation, $params, $service) {
  363. $operation = ThirdGameRecycle::where('id', $operation->id)->lockForUpdate()->firstOrFail();
  364. if (!in_array($operation->status, [
  365. ThirdGameRecycle::STATUS_PENDING,
  366. ThirdGameRecycle::STATUS_UNCERTAIN,
  367. ], true)) {
  368. throw new Exception('当前流水状态无需人工处理', HttpStatus::CUSTOM_ERROR);
  369. }
  370. $remark = trim((string) ($params['remark'] ?? ''));
  371. if ($params['action'] === 'failed') {
  372. $operation->status = ThirdGameRecycle::STATUS_FAILED;
  373. $operation->resolution_remark = '后台人工核对:确认三方未回收'
  374. . ($remark !== '' ? ';' . $remark : '');
  375. } else {
  376. $gameBalance = (float) $params['game_balance'];
  377. $operation->status = ThirdGameRecycle::STATUS_PROVIDER_SUCCEEDED;
  378. $operation->game_balance = $gameBalance;
  379. $operation->wallet_balance = $service->toWalletBalance($gameBalance);
  380. $operation->resolution_remark = '后台人工核对:确认三方已回收'
  381. . ($remark !== '' ? ';' . $remark : '');
  382. }
  383. $operation->save();
  384. return $operation;
  385. });
  386. if ($params['action'] === 'failed') {
  387. return $this->success([
  388. 'operation_id' => $operation->operation_id,
  389. 'member_id' => $operation->member_id,
  390. 'status' => $operation->status,
  391. ]);
  392. }
  393. try {
  394. $credited = $this->creditThirdGameRecycle($operation->id);
  395. } catch (Exception $e) {
  396. throw new Exception(
  397. '核对金额已保存但钱包入账失败,请再次提交回收操作补入账,流水号:' . $operation->operation_id,
  398. HttpStatus::CUSTOM_ERROR
  399. );
  400. }
  401. $credited['resolved_manually'] = true;
  402. return $this->success($credited);
  403. } catch (ValidationException $e) {
  404. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  405. } catch (Exception $e) {
  406. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  407. } finally {
  408. if ($lockAcquired && $lock) {
  409. $lock->release();
  410. }
  411. }
  412. }
  413. public function merge(): JsonResponse
  414. {
  415. DB::beginTransaction();
  416. try {
  417. $params = request()->validate([
  418. 'member_id' => ['required', 'string', 'min:1'],
  419. 'secret_key' => ['required', 'string', 'min:1'],
  420. ]);
  421. $res = SecretService::migration($params['member_id'], $params['secret_key']);
  422. if (!$res) {
  423. throw new Exception(lang("迁移失败"), HttpStatus::CUSTOM_ERROR);
  424. }
  425. $oldUser = UserModel::where('secret_key', $params['secret_key'])->first();
  426. $newUser = UserModel::where('member_id', $params['member_id'])->first();
  427. App::setLocale($oldUser->language);
  428. $text = lang('账户转移通知') . ":\n";
  429. $text .= lang('管理员已将您的账户转移至新用户') . "\n\n";
  430. $text .= lang('新用户信息') . "\n";
  431. $text .= lang('用户ID') . ":{$newUser->getMemberId()}\n";
  432. if ($newUser->getUsername()) {
  433. $text .= lang("用户名") . ":@{$newUser->getUsername()}\n";
  434. }
  435. $text .= lang('昵称') . ":{$newUser->getFirstName()}\n";
  436. TopUpService::notifyTransferSuccess($oldUser->getMemberId(), $text);
  437. App::setLocale($newUser->language);
  438. $text = lang("账户转移通知") . ":\n";
  439. $text .= lang("管理员已将指定账户转移至您的账户") . "\n\n";
  440. $text .= lang('原账户信息') . "\n\n";
  441. $text .= lang('用户ID') . ":{$oldUser->getMemberId()}\n";
  442. if ($oldUser->getUsername()) {
  443. $text .= lang('用户名') . ":@{$oldUser->getUsername()}\n";
  444. }
  445. $text .= lang('昵称') . ":{$oldUser->getFirstName()}\n";
  446. TopUpService::notifyTransferSuccess($newUser->getMemberId(), $text);
  447. DB::commit();
  448. } catch (ValidationException $e) {
  449. DB::rollBack();
  450. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  451. } catch (Exception $e) {
  452. DB::rollBack();
  453. if ($e->getCode() == HttpStatus::CUSTOM_ERROR) {
  454. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  455. }
  456. return $this->error(intval($e->getCode()));
  457. }
  458. return $this->success(msg: '已完成迁移');
  459. }
  460. public function address()
  461. {
  462. try {
  463. request()->validate([
  464. 'member_id' => ['required', 'integer', 'min:1'],
  465. ]);
  466. $search = request()->all();
  467. $result = AddressService::findAll($search);
  468. } catch (ValidationException $e) {
  469. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  470. } catch (Exception $e) {
  471. return $this->error(intval($e->getCode()));
  472. }
  473. return $this->success($result);
  474. }
  475. /**
  476. * 用户登录日志(只读,不写库、不打外网)
  477. */
  478. public function loginLog()
  479. {
  480. try {
  481. $params = request()->validate([
  482. 'page' => ['nullable', 'integer', 'min:1'],
  483. 'limit' => ['nullable', 'integer', 'min:1'],
  484. 'user_id' => ['nullable'],
  485. 'member_id' => ['nullable'],
  486. 'account' => ['nullable', 'string', 'max:64'],
  487. 'first_name' => ['nullable'],
  488. 'status' => ['nullable', 'integer', 'in:0,1'],
  489. 'start_time' => ['nullable', 'date', 'date_format:Y-m-d', 'required_with:end_time'],
  490. 'end_time' => ['nullable', 'date', 'date_format:Y-m-d', 'required_with:start_time'],
  491. ]);
  492. $page = (int)request()->input('page', 1);
  493. $limit = (int)request()->input('limit', 15);
  494. $query = UserLogin::query();
  495. $grammar = $query->getQuery()->getGrammar();
  496. // 历史表字段可能混用 general_ci / unicode_ci;显式统一比较规则,保留账号大小写不敏感语义。
  497. $collation = in_array($query->getConnection()->getDriverName(), ['mysql', 'mariadb'], true)
  498. ? ' COLLATE utf8mb4_unicode_ci' : '';
  499. $userIdMatch = $grammar->wrap('user_login.user_id') . $collation
  500. . ' = ' . $grammar->wrap('users.user_id') . $collation;
  501. $accountMatch = $grammar->wrap('customer_service_users.account') . $collation
  502. . ' = ' . $grammar->wrap('user_login.login_account') . $collation;
  503. $query
  504. ->leftJoin('users', function ($join) use ($userIdMatch) {
  505. $join->whereRaw($userIdMatch)
  506. // 无用户的失败日志不能关联到同样缺少 ID 的客服账号。
  507. ->where('user_login.user_id', '<>', '');
  508. })
  509. ->where(function ($q) {
  510. $q->whereNull('users.from')->orWhere('users.from', '<>', '0');
  511. })
  512. // 后台模拟会员的登录日志只在模拟管理里出现;无用户的失败日志保留
  513. ->tap(fn ($q) => \App\Support\MemberAudience::visibleMembers($q, 'user_login.user_id', 'user_id'))
  514. // 失败日志可能没有用户 ID,仍需按输入账号排除客服来源(from=0)。
  515. ->whereNotExists(function ($q) use ($accountMatch) {
  516. $q->selectRaw('1')->from('users as customer_service_users')
  517. ->where('customer_service_users.from', '0')
  518. ->where('user_login.login_account', '<>', '')
  519. ->whereRaw($accountMatch);
  520. })
  521. ->select([
  522. 'user_login.id',
  523. 'user_login.user_id',
  524. 'user_login.login_account',
  525. 'user_login.login_ip',
  526. 'user_login.login_domain',
  527. 'user_login.country',
  528. 'user_login.browser',
  529. 'user_login.os',
  530. 'user_login.platform',
  531. 'user_login.status',
  532. 'user_login.logout_time',
  533. 'user_login.online_duration',
  534. 'user_login.user_agent',
  535. 'user_login.created_at',
  536. 'user_login.updated_at',
  537. 'users.member_id',
  538. 'users.first_name',
  539. 'users.account',
  540. 'users.username',
  541. ]);
  542. if (!empty($params['user_id'])) {
  543. $query->where('user_login.user_id', $params['user_id']);
  544. }
  545. if (!empty($params['member_id'])) {
  546. $query->where('user_login.user_id', $params['member_id']);
  547. }
  548. if (!empty($params['account'])) {
  549. // 登录失败时可能匹配不到会员,同时按登录时输入的账号筛选
  550. $account = '%' . trim((string)$params['account']) . '%';
  551. $query->where(function ($q) use ($account) {
  552. $q->where('users.account', 'like', $account)
  553. ->orWhere('user_login.login_account', 'like', $account);
  554. });
  555. }
  556. if (!empty($params['first_name'])) {
  557. $query->where('users.first_name', 'like', "%{$params['first_name']}%");
  558. }
  559. if (array_key_exists('status', $params) && $params['status'] !== null) {
  560. $query->where('user_login.status', (int)$params['status']);
  561. }
  562. if (!empty($params['start_time'])) {
  563. $query->where('user_login.created_at', '>=', $params['start_time'] . ' 00:00:00');
  564. }
  565. if (!empty($params['end_time'])) {
  566. $query->where('user_login.created_at', '<=', $params['end_time'] . ' 23:59:59');
  567. }
  568. $count = (clone $query)->count();
  569. $list = $query
  570. ->forPage($page, $limit)
  571. ->orderByDesc('user_login.id')
  572. ->get();
  573. } catch (Exception $e) {
  574. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  575. }
  576. return $this->success(['total' => $count, 'data' => $list]);
  577. }
  578. /**
  579. * 会员注册走势图
  580. */
  581. public function registerTrend()
  582. {
  583. try {
  584. $params = request()->validate([
  585. 'type' => ['nullable', 'string', 'in:today,all'],
  586. 'start_time' => ['nullable', 'date', 'date_format:Y-m-d'],
  587. 'end_time' => ['nullable', 'date', 'date_format:Y-m-d', 'after_or_equal:start_time'],
  588. ]);
  589. $data = RegisterStatService::trend(
  590. $params['type'] ?? 'today',
  591. $params['start_time'] ?? null,
  592. $params['end_time'] ?? null
  593. );
  594. } catch (Exception $e) {
  595. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  596. }
  597. return $this->success($data);
  598. }
  599. /**
  600. * 域名登录人数统计
  601. */
  602. public function registerDomain()
  603. {
  604. try {
  605. $params = request()->validate([
  606. 'start_time' => ['nullable', 'date', 'date_format:Y-m-d'],
  607. 'end_time' => ['nullable', 'date', 'date_format:Y-m-d', 'after_or_equal:start_time'],
  608. 'page' => ['nullable', 'integer', 'min:1'],
  609. 'limit' => ['nullable', 'integer', 'min:1', 'max:200'],
  610. ]);
  611. $page = (int)request()->input('page', 1);
  612. $limit = (int)request()->input('limit', 50);
  613. $data = RegisterStatService::domain(
  614. $params['start_time'] ?? null,
  615. $params['end_time'] ?? null,
  616. $page,
  617. $limit
  618. );
  619. } catch (Exception $e) {
  620. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  621. }
  622. return $this->success($data);
  623. }
  624. /**
  625. * 给无上级的会员补绑上级。合营代理填 agent_username,会员填 superior_id。
  626. */
  627. function bindSuperior(\App\Services\MemberSuperiorService $service)
  628. {
  629. try {
  630. $params = request()->validate([
  631. 'member_id' => ['required', 'string', 'min:1'],
  632. 'type' => ['required', 'string', 'in:agent,member'],
  633. 'agent_username' => ['required_if:type,agent', 'missing_unless:type,agent', 'string', 'max:64'],
  634. 'superior_id' => ['required_if:type,member', 'missing_unless:type,member', 'string', 'max:64'],
  635. ], [
  636. 'agent_username.required_if' => '请输入合营代理账号',
  637. 'agent_username.missing_unless' => '绑定会员时请填写上级会员 ID',
  638. 'superior_id.required_if' => '请输入上级会员 ID',
  639. 'superior_id.missing_unless' => '绑定合营代理时请填写代理账号',
  640. ]);
  641. $target = $params['agent_username'] ?? $params['superior_id'];
  642. $result = $service->bind($params['member_id'], $params['type'], trim($target));
  643. } catch (ValidationException $e) {
  644. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  645. } catch (Exception $e) {
  646. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  647. }
  648. return $this->success($result);
  649. }
  650. function setRechargeChannelGroup()
  651. {
  652. try {
  653. $params = request()->validate([
  654. 'member_id' => ['required', 'array'],
  655. 'recharge_channel_group_id' => ['required', 'integer', 'min:1'],
  656. ]);
  657. DB::transaction(function () use ($params) {
  658. $group = \App\Models\RechargeChannelGroup::query()->lockForUpdate()->find($params['recharge_channel_group_id']);
  659. if (!$group) throw new Exception('层级不存在或已删除');
  660. UserModel::whereIn('member_id', $params['member_id'])->update(['recharge_channel_group_id' => $group->id]);
  661. }, 3);
  662. } catch (ValidationException $e) {
  663. return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
  664. } catch (Exception $e) {
  665. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  666. }
  667. return $this->success();
  668. }
  669. }