User.php 31 KB

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