SimulationMemberService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. <?php
  2. namespace App\Services\Simulation;
  3. use App\Constants\HttpStatus;
  4. use App\Models\User;
  5. use App\Models\UserLogin;
  6. use App\Models\Wallet;
  7. use App\Support\MemberAudience;
  8. use Exception;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Schema;
  11. /** 后台模拟会员:users.user_type = 2、from = 2、没有代理和上级,不能登录前台。 */
  12. final class SimulationMemberService
  13. {
  14. /** @return list<array{id:int,member_id:string,account:string}> */
  15. public static function create(int $count, array $options = []): array
  16. {
  17. SimulationSettings::assertEnabled();
  18. $settings = SimulationSettings::all();
  19. if ($count < 1 || $count > (int) $settings['simulation_max_members_per_task']) {
  20. throw new Exception('一次最多创建 ' . $settings['simulation_max_members_per_task'] . ' 个模拟会员', HttpStatus::CUSTOM_ERROR);
  21. }
  22. $existing = DB::table('users')->where('user_type', MemberAudience::TYPE_SIMULATED)->count();
  23. if ($existing + $count > (int) $settings['simulation_max_members_total']) {
  24. throw new Exception('模拟会员总数将超过上限 ' . $settings['simulation_max_members_total'], HttpStatus::CUSTOM_ERROR);
  25. }
  26. $domain = trim((string) ($options['domain'] ?? '')) ?: $settings['simulation_default_domain'];
  27. $initial = $options['initial_balance'] ?? $settings['simulation_initial_balance'];
  28. $created = [];
  29. for ($i = 0; $i < $count; $i++) {
  30. $user = DB::transaction(function () use ($domain) {
  31. $sn = self::serial();
  32. $user = (new User())->forceFill([
  33. 'member_id' => $sn, 'user_id' => $sn, 'account' => self::account(), 'first_name' => self::nickname(),
  34. 'username' => '', 'from' => '2', 'user_type' => MemberAudience::TYPE_SIMULATED,
  35. 'register_ip' => self::ip(), 'register_domain' => $domain, 'last_active_time' => time(),
  36. ]);
  37. $user->save();
  38. (new Wallet())->forceFill(['user_id' => $user->id, 'member_id' => $sn, 'coin' => 'USDT', 'net' => 'TRC20', 'available_balance' => 0])->save();
  39. return $user;
  40. });
  41. MemberAudience::remember($user->member_id);
  42. if (is_numeric($initial) && $initial > 0) SimulationFundService::adjust($user->member_id, $initial, 'credit', '初始余额');
  43. $created[] = ['id' => (int) $user->id, 'member_id' => (string) $user->member_id, 'account' => (string) $user->account];
  44. }
  45. return $created;
  46. }
  47. private const SURNAMES = ['wang', 'li', 'zhang', 'liu', 'chen', 'yang', 'huang', 'zhao', 'wu', 'zhou', 'xu', 'sun', 'ma', 'zhu', 'hu', 'guo', 'he', 'lin', 'gao', 'luo',
  48. 'zheng', 'liang', 'xie', 'song', 'tang', 'han', 'feng', 'deng', 'cao', 'peng', 'zeng', 'xiao', 'tian', 'dong', 'pan', 'yuan', 'cai', 'jiang', 'yu', 'du'];
  49. private const GIVEN = ['wei', 'fang', 'na', 'min', 'jing', 'lei', 'qiang', 'jun', 'yang', 'yong', 'jie', 'juan', 'tao', 'ming', 'chao', 'xia', 'ping', 'gang', 'hui', 'yan',
  50. 'ling', 'bo', 'hao', 'yu', 'xin', 'peng', 'fei', 'kai', 'long', 'bin', 'ting', 'xue', 'dan', 'rui', 'chen', 'hong', 'lan', 'feng', 'shuai', 'kun'];
  51. private const WORDS = ['lucky', 'happy', 'sunny', 'tiger', 'dragon', 'star', 'moon', 'king', 'boss', 'cool', 'super', 'win', 'gold', 'ace', 'fly', 'sky', 'blue', 'fox', 'wolf', 'bear'];
  52. private const SURNAMES_CN = ['王', '李', '张', '刘', '陈', '杨', '黄', '赵', '吴', '周', '徐', '孙', '马', '朱', '胡', '郭', '何', '林', '高', '罗', '郑', '梁', '谢', '宋', '唐', '韩', '冯', '邓', '曹', '彭'];
  53. private const GIVEN_CN = ['伟', '芳', '娜', '敏', '静', '磊', '强', '军', '洋', '勇', '杰', '娟', '涛', '明', '超', '霞', '平', '刚', '辉', '燕', '玲', '波', '浩', '宇', '欣', '鹏', '飞', '凯', '龙', '斌',
  54. '婷', '雪', '丹', '瑞', '晨', '红', '兰', '峰', '帅', '坤', '子轩', '浩然', '雨涵', '梓涵', '一鸣', '思远', '佳怡', '俊杰', '志强', '晓东'];
  55. private const NICKNAMES = ['风一样的男子', '小幸运', '夜空中最亮的星', '快乐每一天', '往事随风', '平安是福', '一路向北', '海阔天空', '知足常乐', '顺其自然', '好运连连', '财源滚滚',
  56. '阳光明媚', '淡定', '大圣归来', '追风少年', '南方姑娘', '老司机', '独行侠', '清风徐来', '人间烟火', '星辰大海', '江湖再见', '稳稳的幸福', '发发发', '明天会更好'];
  57. private static function pick(array $list): string
  58. {
  59. return $list[random_int(0, count($list) - 1)];
  60. }
  61. /** 像真实会员自己起的登录账号:拼音姓名或英文词加数字,6~16 位,字母开头,全库唯一。 */
  62. private static function account(): string
  63. {
  64. for ($try = 0; $try < 50; $try++) {
  65. $base = match (random_int(0, 3)) {
  66. 0 => self::pick(self::SURNAMES) . self::pick(self::GIVEN),
  67. 1 => self::pick(self::SURNAMES) . self::pick(self::GIVEN) . self::pick(self::GIVEN),
  68. 2 => self::pick(self::WORDS) . self::pick(self::SURNAMES),
  69. default => substr(self::pick(self::SURNAMES), 0, 1) . substr(self::pick(self::GIVEN), 0, 1) . substr(self::pick(self::GIVEN), 0, 1),
  70. };
  71. $digits = match (random_int(0, 3)) {
  72. 0 => (string) random_int(1975, 2005), 1 => (string) random_int(10, 99),
  73. 2 => str_pad((string) random_int(1, 1231), 4, '0', STR_PAD_LEFT), default => (string) random_int(100, 999999),
  74. };
  75. $account = substr($base . $digits, 0, 16);
  76. if (strlen($account) >= 6 && !DB::table('users')->where('account', $account)->exists()) return $account;
  77. }
  78. throw new Exception('会员账号生成失败,请重试', HttpStatus::CUSTOM_ERROR);
  79. }
  80. /** 像真实会员的昵称:中文姓名、网名,偶尔带数字。 */
  81. private static function nickname(): string
  82. {
  83. return match (random_int(0, 4)) {
  84. 0, 1 => self::pick(self::SURNAMES_CN) . self::pick(self::GIVEN_CN),
  85. 2 => self::pick(self::NICKNAMES),
  86. 3 => self::pick(self::NICKNAMES) . random_int(1, 999),
  87. default => ucfirst(self::pick(self::WORDS)) . random_int(10, 9999),
  88. };
  89. }
  90. /** 随机的公网 IPv4(避开保留网段)。 */
  91. private static function ip(): string
  92. {
  93. do {
  94. $first = random_int(1, 223);
  95. } while (in_array($first, [10, 100, 127, 169, 172, 192, 198, 203], true));
  96. return $first . '.' . random_int(0, 255) . '.' . random_int(0, 255) . '.' . random_int(1, 254);
  97. }
  98. /**
  99. * 给早期创建的模拟会员改名:账号 sim_ 开头、昵称“模拟_”开头、IP 为 127.0.0.1 的,换成和新会员一样的随机真实风格;
  100. * 同时改掉这些会员名下记录里存的旧名字,以及旧的“模拟主队 / 模拟视讯 / 模拟银行”等展示名。
  101. * 只动 users.user_type = 2 的会员及其记录;会员编号、余额、金额、订单都不变。可重复执行,改过的不会再改。
  102. * @return array<string,int> 各项改动的行数;$dryRun 时只统计不写库
  103. */
  104. public static function renameLegacy(bool $dryRun = false): array
  105. {
  106. if (!MemberAudience::enabled()) throw new Exception('用户类型字段尚未迁移', HttpStatus::CUSTOM_ERROR);
  107. $counts = ['members' => 0, 'accounts' => 0, 'nicknames' => 0, 'ips' => 0, 'login_logs' => 0, 'third_game_orders' => 0, 'withdraw_orders' => 0, 'sport_orders' => 0];
  108. $has = fn (string $table, string $column) => Schema::hasTable($table) && Schema::hasColumn($table, $column);
  109. $members = DB::table('users')->where('user_type', MemberAudience::TYPE_SIMULATED)->orderBy('id')->get();
  110. foreach ($members as $user) {
  111. $oldAccount = (string) $user->account;
  112. $oldName = (string) $user->first_name;
  113. $changes = [];
  114. if (str_starts_with($oldAccount, 'sim_')) { $changes['account'] = self::account(); $counts['accounts']++; }
  115. if (str_starts_with($oldName, '模拟')) { $changes['first_name'] = self::nickname(); $counts['nicknames']++; }
  116. if (in_array((string) ($user->register_ip ?? ''), ['127.0.0.1', ''], true)) { $changes['register_ip'] = self::ip(); $counts['ips']++; }
  117. $ip = $changes['register_ip'] ?? (string) $user->register_ip;
  118. $name = $changes['first_name'] ?? $oldName;
  119. $work = function () use ($user, $changes, $oldAccount, $oldName, $name, $ip, $has, $dryRun, &$counts) {
  120. if ($changes && !$dryRun) DB::table('users')->where('id', $user->id)->where('user_type', MemberAudience::TYPE_SIMULATED)->update($changes);
  121. // 登录日志里存的账号和 IP
  122. if ($has('user_login', 'login_account')) {
  123. $logs = DB::table('user_login')->where('user_id', (string) $user->user_id)
  124. ->where(fn ($q) => $q->whereRaw("SUBSTR(login_account, 1, 4) = 'sim_'")->orWhere('login_ip', '127.0.0.1'));
  125. $counts['login_logs'] += $dryRun ? $logs->count() : $logs->update(['login_account' => $changes['account'] ?? $oldAccount, 'login_ip' => $ip]);
  126. }
  127. // 第三方注单里存的昵称,以及旧的“模拟视讯”等游戏名
  128. if (Schema::hasTable('third_game_orders')) {
  129. foreach (DB::table('third_game_orders')->where('user_id', $user->id)->where(fn ($q) => $q->where('first_name', 'like', '模拟%')
  130. ->orWhere('game_name', 'like', '模拟%'))->get(['id', 'game_type']) as $order) {
  131. $game = SimulationBetService::THIRD_GAMES[(int) $order->game_type] ?? '百家乐';
  132. if (!$dryRun) DB::table('third_game_orders')->where('id', $order->id)->update(['first_name' => $name, 'game_name' => $game, 'bet_content' => $game]);
  133. $counts['third_game_orders']++;
  134. }
  135. }
  136. // 提现单上的收款人、银行和卡号
  137. if (Schema::hasTable('payment_orders')) {
  138. foreach (DB::table('payment_orders')->where('member_id', (string) $user->member_id)->where('type', 4)
  139. ->where(fn ($q) => $q->where('account', 'like', '模拟%')->orWhere('bank_name', '模拟银行')->orWhere('card_no', 'like', 'SIM%'))->pluck('id') as $id) {
  140. if (!$dryRun) DB::table('payment_orders')->where('id', $id)->update(['account' => $name, 'bank_name' => SimulationFundService::randomBank(), 'card_no' => SimulationFundService::randomCard()]);
  141. $counts['withdraw_orders']++;
  142. }
  143. }
  144. // 体育注单的“模拟主队 VS 模拟客队”
  145. if ($has('sport_order', 'odd_name')) {
  146. foreach (DB::table('sport_order')->where('user_id', (string) $user->user_id)->where('odd_name', 'like', '%模拟%')->get(['id', 'detail']) as $order) {
  147. $match = SimulationBetService::randomMatch();
  148. $detail = json_decode((string) $order->detail, true);
  149. $update = ['odd_name' => $match];
  150. if (is_array($detail) && isset($detail['title'])) $update['detail'] = json_encode(['title' => $match] + $detail, JSON_UNESCAPED_UNICODE);
  151. if (!$dryRun) DB::table('sport_order')->where('id', $order->id)->update($update);
  152. $counts['sport_orders']++;
  153. }
  154. }
  155. };
  156. $before = array_sum($counts);
  157. $dryRun ? $work() : DB::transaction($work);
  158. if ($changes || array_sum($counts) > $before) $counts['members']++;
  159. }
  160. return $counts;
  161. }
  162. /** 8 位 1-9 数字,与前台会员编号同形;纯数字是因为 wallets.member_id 是 bigint。 */
  163. private static function serial(): string
  164. {
  165. for ($try = 0; $try < 50; $try++) {
  166. $sn = '';
  167. for ($i = 0; $i < 8; $i++) $sn .= (string) random_int(1, 9);
  168. if (!DB::table('users')->where('member_id', $sn)->orWhere('user_id', $sn)->exists()) return $sn;
  169. }
  170. throw new Exception('会员编号生成失败,请重试', HttpStatus::CUSTOM_ERROR);
  171. }
  172. public static function setBanned($memberId, int $banned): void
  173. {
  174. $user = SimulationSettings::member($memberId);
  175. DB::table('users')->where('id', $user->id)->update(['is_banned' => $banned ? 1 : 0]);
  176. }
  177. /** 只写登录日志,不建会话、不签发 token:模拟会员没有可登录前台的凭证。 */
  178. public static function login($memberId, string $platform = 'H5', ?string $domain = null): array
  179. {
  180. SimulationSettings::assertEnabled();
  181. $user = SimulationSettings::member($memberId);
  182. self::logout($memberId);
  183. $row = ['user_id' => (string) $user->user_id, 'login_account' => (string) $user->account,
  184. 'login_ip' => filter_var((string) ($user->register_ip ?? ''), FILTER_VALIDATE_IP) ? (string) $user->register_ip : self::ip(),
  185. 'login_domain' => $domain ?: SimulationSettings::get('simulation_default_domain'), 'platform' => $platform, 'status' => UserLogin::STATUS_SUCCESS,
  186. 'created_at' => now(), 'updated_at' => now()];
  187. $row = array_filter($row, fn ($column) => Schema::hasColumn('user_login', $column), ARRAY_FILTER_USE_KEY);
  188. $id = DB::table('user_login')->insertGetId($row);
  189. $update = ['last_active_time' => time()];
  190. if (Schema::hasColumn('users', 'last_login_time')) $update += ['last_login_time' => time(), 'login_count' => DB::raw('COALESCE(login_count, 0) + 1')];
  191. DB::table('users')->where('id', $user->id)->update($update);
  192. return ['id' => $id, 'member_id' => (string) $user->member_id];
  193. }
  194. public static function logout($memberId): int
  195. {
  196. $user = SimulationSettings::member($memberId);
  197. if (!Schema::hasColumn('user_login', 'logout_time')) return 0;
  198. $open = DB::table('user_login')->where('user_id', (string) $user->user_id)->where('status', UserLogin::STATUS_SUCCESS)->whereNull('logout_time')->get(['id', 'created_at']);
  199. foreach ($open as $row) {
  200. DB::table('user_login')->where('id', $row->id)->update(['logout_time' => now(),
  201. 'online_duration' => max(0, now()->getTimestamp() - strtotime((string) $row->created_at)), 'updated_at' => now()]);
  202. }
  203. return $open->count();
  204. }
  205. /** 当前“在线”的模拟会员:有未登出的成功登录记录。 */
  206. public static function onlineUserIds()
  207. {
  208. $query = DB::table('user_login')->where('status', UserLogin::STATUS_SUCCESS)->whereIn('user_id', MemberAudience::simulatedMembers('user_id'));
  209. if (Schema::hasColumn('user_login', 'logout_time')) $query->whereNull('logout_time');
  210. return $query->distinct()->pluck('user_id');
  211. }
  212. public static function detail($memberId): array
  213. {
  214. $user = SimulationSettings::member($memberId);
  215. $wallet = DB::table('wallets')->where('member_id', $user->member_id)->first();
  216. return [
  217. 'user' => ['id' => $user->id, 'member_id' => $user->member_id, 'account' => $user->account, 'first_name' => $user->first_name,
  218. 'is_banned' => (int) ($user->is_banned ?? 0), 'register_domain' => $user->register_domain ?? '', 'created_at' => $user->created_at],
  219. 'wallet' => $wallet ? ['available_balance' => (string) $wallet->available_balance, 'frozen_balance' => (string) $wallet->frozen_balance,
  220. 'wager_required' => (string) ($wallet->wager_required ?? 0), 'wager_completed' => (string) ($wallet->wager_completed ?? 0)] : null,
  221. 'logs' => DB::table('balance_logs')->where('member_id', $user->member_id)->orderByDesc('id')->limit(20)->get(),
  222. ];
  223. }
  224. }