User.php 29 KB

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