doge vor 1 Tag
Ursprung
Commit
7631afee26

+ 29 - 0
app/Console/Commands/SimulationRenameMembers.php

@@ -0,0 +1,29 @@
+<?php
+
+namespace App\Console\Commands;
+
+use App\Services\Simulation\SimulationMemberService;
+use Illuminate\Console\Command;
+
+class SimulationRenameMembers extends Command
+{
+    protected $signature = 'simulation:rename-members {--dry-run : 只统计会改多少,不写库}';
+
+    protected $description = '给早期创建的模拟会员改名:去掉账号 sim_ 前缀和“模拟”昵称,换成随机的真实风格;不清空数据,可重复执行';
+
+    public function handle(): int
+    {
+        $dryRun = (bool) $this->option('dry-run');
+        try {
+            $counts = SimulationMemberService::renameLegacy($dryRun);
+        } catch (\Throwable $e) {
+            $this->error($e->getMessage());
+            return self::FAILURE;
+        }
+        $labels = ['members' => '涉及的模拟会员', 'accounts' => '改账号', 'nicknames' => '改昵称', 'ips' => '改注册 IP', 'login_logs' => '登录日志',
+            'third_game_orders' => '第三方注单', 'withdraw_orders' => '提现单', 'sport_orders' => '体育注单'];
+        $this->info($dryRun ? '试运行,没有修改任何数据。将要改动:' : '已完成。改动:');
+        foreach ($counts as $key => $count) $this->line(sprintf('  %s:%d', $labels[$key] ?? $key, $count));
+        return self::SUCCESS;
+    }
+}

+ 13 - 3
app/Services/Simulation/SimulationBetService.php

@@ -219,6 +219,14 @@ final class SimulationBetService
         return count($ids);
         return count($ids);
     }
     }
 
 
+    /** 随机两支不同球队的对阵,没指定赛事时用。 */
+    public static function randomMatch(): string
+    {
+        $teams = (array) array_rand(array_flip(self::TEAMS), 2);
+        shuffle($teams);
+        return $teams[0] . ' VS ' . $teams[1];
+    }
+
     /** 生成一张体育注单并扣款。 */
     /** 生成一张体育注单并扣款。 */
     public static function sport($memberId, $amount, $odd, string $title = '', string $selection = ''): Order
     public static function sport($memberId, $amount, $odd, string $title = '', string $selection = ''): Order
     {
     {
@@ -226,7 +234,7 @@ final class SimulationBetService
         $user = SimulationSettings::member($memberId);
         $user = SimulationSettings::member($memberId);
         $amount = SimulationSettings::assertAmount($amount);
         $amount = SimulationSettings::assertAmount($amount);
         if (!is_numeric($odd) || $odd <= 1 || $odd > 100) throw new Exception('赔率应大于 1 且不超过 100', HttpStatus::CUSTOM_ERROR);
         if (!is_numeric($odd) || $odd <= 1 || $odd > 100) throw new Exception('赔率应大于 1 且不超过 100', HttpStatus::CUSTOM_ERROR);
-        $title = $title !== '' ? $title : '模拟主队 VS 模拟客队';
+        if ($title === '') $title = self::randomMatch();
         $selection = $selection !== '' ? $selection : '主胜';
         $selection = $selection !== '' ? $selection : '主胜';
         return DB::transaction(function () use ($user, $amount, $odd, $title, $selection) {
         return DB::transaction(function () use ($user, $amount, $odd, $title, $selection) {
             $wallet = Wallet::where('member_id', $user->member_id)->lockForUpdate()->first();
             $wallet = Wallet::where('member_id', $user->member_id)->lockForUpdate()->first();
@@ -247,7 +255,9 @@ final class SimulationBetService
         });
         });
     }
     }
 
 
-    public const THIRD_GAMES = [1 => '模拟视讯', 2 => '模拟老虎机', 3 => '模拟彩票', 4 => '模拟体育', 5 => '模拟电竞', 6 => '模拟捕猎', 7 => '模拟棋牌'];
+    public const THIRD_GAMES = [1 => '百家乐', 2 => '财神到', 3 => '幸运快艇', 4 => '足球滚球', 5 => '英雄联盟', 6 => '捕鱼达人', 7 => '斗地主'];
+    private const TEAMS = ['曼城', '阿森纳', '利物浦', '切尔西', '皇家马德里', '巴塞罗那', '拜仁慕尼黑', '多特蒙德', '国际米兰', 'AC米兰', '尤文图斯', '巴黎圣日耳曼',
+        '马德里竞技', '热刺', '曼联', '那不勒斯', '勒沃库森', '本菲卡', '波尔图', '阿贾克斯'];
     public const THIRD_PLATFORM = 'SIM';
     public const THIRD_PLATFORM = 'SIM';
 
 
     /**
     /**
@@ -278,7 +288,7 @@ final class SimulationBetService
                 'first_name' => (string) ($user->first_name ?? ''), 'player_id' => $playerId, 'platform' => self::THIRD_PLATFORM,
                 'first_name' => (string) ($user->first_name ?? ''), 'player_id' => $playerId, 'platform' => self::THIRD_PLATFORM,
                 'currency' => (string) config('third_game.currency', 'CNY'), 'game_type' => $gameType, 'game_name' => self::THIRD_GAMES[$gameType],
                 'currency' => (string) config('third_game.currency', 'CNY'), 'game_type' => $gameType, 'game_name' => self::THIRD_GAMES[$gameType],
                 'round_no' => $gameOrderId, 'table_no' => '', 'seat' => '', 'bet_amount' => $amount, 'valid_amount' => $amount, 'settled_amount' => $profit,
                 'round_no' => $gameOrderId, 'table_no' => '', 'seat' => '', 'bet_amount' => $amount, 'valid_amount' => $amount, 'settled_amount' => $profit,
-                'bet_content' => '模拟注单', 'status' => 1, 'game_order_id' => $gameOrderId, 'bet_time' => $now, 'last_update_time' => $now]);
+                'bet_content' => self::THIRD_GAMES[$gameType], 'status' => 1, 'game_order_id' => $gameOrderId, 'bet_time' => $now, 'last_update_time' => $now]);
             $after = bcadd($before, $profit, 10);
             $after = bcadd($before, $profit, 10);
             $wallet->available_balance = $after;
             $wallet->available_balance = $after;
             $wallet->save();
             $wallet->save();

+ 12 - 2
app/Services/Simulation/SimulationFundService.php

@@ -66,6 +66,16 @@ final class SimulationFundService
         });
         });
     }
     }
 
 
+    public static function randomBank(): string
+    {
+        return ['工商银行', '建设银行', '农业银行', '中国银行', '招商银行', '交通银行', '邮储银行'][mt_rand(0, 6)];
+    }
+
+    public static function randomCard(): string
+    {
+        return '62' . str_pad((string) mt_rand(0, 99999999), 8, '0', STR_PAD_LEFT) . str_pad((string) mt_rand(0, 999999999), 9, '0', STR_PAD_LEFT);
+    }
+
     /** 人工提现申请:校验打码量、冻结资金、建待审核提现单。 */
     /** 人工提现申请:校验打码量、冻结资金、建待审核提现单。 */
     public static function withdrawApply($memberId, $amount): PaymentOrder
     public static function withdrawApply($memberId, $amount): PaymentOrder
     {
     {
@@ -77,8 +87,8 @@ final class SimulationFundService
             if ($wallet) WageringService::resetCycle($wallet, 'simulation', null, '模拟提现跳过打码量');
             if ($wallet) WageringService::resetCycle($wallet, 'simulation', null, '模拟提现跳过打码量');
         }
         }
         $data = ['type' => PaymentOrderService::TYPE_SELF_PAYOUT, 'member_id' => $user->member_id, 'amount' => $amount, 'channel' => self::CHANNEL,
         $data = ['type' => PaymentOrderService::TYPE_SELF_PAYOUT, 'member_id' => $user->member_id, 'amount' => $amount, 'channel' => self::CHANNEL,
-            'order_no' => PaymentOrderService::createOrderNo('sim4_', $user->member_id), 'bank_name' => '模拟银行', 'account' => (string) $user->first_name,
-            'card_no' => 'SIM' . $user->member_id, 'status' => PaymentOrderService::STATUS_STAY] + PaymentOrderService::feeFields($amount, 0);
+            'order_no' => PaymentOrderService::createOrderNo('sim4_', $user->member_id), 'bank_name' => self::randomBank(), 'account' => (string) $user->first_name,
+            'card_no' => self::randomCard(), 'status' => PaymentOrderService::STATUS_STAY] + PaymentOrderService::feeFields($amount, 0);
         [$order] = WithdrawFundsService::hold((string) $user->member_id, $amount, '人工提现', '模拟提现', WithdrawFundsService::PAYMENT_ORDERS,
         [$order] = WithdrawFundsService::hold((string) $user->member_id, $amount, '人工提现', '模拟提现', WithdrawFundsService::PAYMENT_ORDERS,
             function () use ($data, $user) {
             function () use ($data, $user) {
                 $pending = PaymentOrder::where('type', PaymentOrderService::TYPE_SELF_PAYOUT)->where('member_id', $user->member_id)
                 $pending = PaymentOrder::where('type', PaymentOrderService::TYPE_SELF_PAYOUT)->where('member_id', $user->member_id)

+ 126 - 4
app/Services/Simulation/SimulationMemberService.php

@@ -33,21 +33,142 @@ final class SimulationMemberService
             $user = DB::transaction(function () use ($domain) {
             $user = DB::transaction(function () use ($domain) {
                 $sn = self::serial();
                 $sn = self::serial();
                 $user = (new User())->forceFill([
                 $user = (new User())->forceFill([
-                    'member_id' => $sn, 'user_id' => $sn, 'account' => 'sim_' . $sn, 'first_name' => '模拟_' . substr($sn, -4),
+                    'member_id' => $sn, 'user_id' => $sn, 'account' => self::account(), 'first_name' => self::nickname(),
                     'username' => '', 'from' => '2', 'user_type' => MemberAudience::TYPE_SIMULATED,
                     'username' => '', 'from' => '2', 'user_type' => MemberAudience::TYPE_SIMULATED,
-                    'register_ip' => '127.0.0.1', 'register_domain' => $domain, 'last_active_time' => time(),
+                    'register_ip' => self::ip(), 'register_domain' => $domain, 'last_active_time' => time(),
                 ]);
                 ]);
                 $user->save();
                 $user->save();
                 (new Wallet())->forceFill(['user_id' => $user->id, 'member_id' => $sn, 'coin' => 'USDT', 'net' => 'TRC20', 'available_balance' => 0])->save();
                 (new Wallet())->forceFill(['user_id' => $user->id, 'member_id' => $sn, 'coin' => 'USDT', 'net' => 'TRC20', 'available_balance' => 0])->save();
                 return $user;
                 return $user;
             });
             });
             MemberAudience::remember($user->member_id);
             MemberAudience::remember($user->member_id);
-            if (is_numeric($initial) && $initial > 0) SimulationFundService::adjust($user->member_id, $initial, 'credit', '模拟会员初始余额');
+            if (is_numeric($initial) && $initial > 0) SimulationFundService::adjust($user->member_id, $initial, 'credit', '初始余额');
             $created[] = ['id' => (int) $user->id, 'member_id' => (string) $user->member_id, 'account' => (string) $user->account];
             $created[] = ['id' => (int) $user->id, 'member_id' => (string) $user->member_id, 'account' => (string) $user->account];
         }
         }
         return $created;
         return $created;
     }
     }
 
 
+    private const SURNAMES = ['wang', 'li', 'zhang', 'liu', 'chen', 'yang', 'huang', 'zhao', 'wu', 'zhou', 'xu', 'sun', 'ma', 'zhu', 'hu', 'guo', 'he', 'lin', 'gao', 'luo',
+        'zheng', 'liang', 'xie', 'song', 'tang', 'han', 'feng', 'deng', 'cao', 'peng', 'zeng', 'xiao', 'tian', 'dong', 'pan', 'yuan', 'cai', 'jiang', 'yu', 'du'];
+    private const GIVEN = ['wei', 'fang', 'na', 'min', 'jing', 'lei', 'qiang', 'jun', 'yang', 'yong', 'jie', 'juan', 'tao', 'ming', 'chao', 'xia', 'ping', 'gang', 'hui', 'yan',
+        'ling', 'bo', 'hao', 'yu', 'xin', 'peng', 'fei', 'kai', 'long', 'bin', 'ting', 'xue', 'dan', 'rui', 'chen', 'hong', 'lan', 'feng', 'shuai', 'kun'];
+    private const WORDS = ['lucky', 'happy', 'sunny', 'tiger', 'dragon', 'star', 'moon', 'king', 'boss', 'cool', 'super', 'win', 'gold', 'ace', 'fly', 'sky', 'blue', 'fox', 'wolf', 'bear'];
+    private const SURNAMES_CN = ['王', '李', '张', '刘', '陈', '杨', '黄', '赵', '吴', '周', '徐', '孙', '马', '朱', '胡', '郭', '何', '林', '高', '罗', '郑', '梁', '谢', '宋', '唐', '韩', '冯', '邓', '曹', '彭'];
+    private const GIVEN_CN = ['伟', '芳', '娜', '敏', '静', '磊', '强', '军', '洋', '勇', '杰', '娟', '涛', '明', '超', '霞', '平', '刚', '辉', '燕', '玲', '波', '浩', '宇', '欣', '鹏', '飞', '凯', '龙', '斌',
+        '婷', '雪', '丹', '瑞', '晨', '红', '兰', '峰', '帅', '坤', '子轩', '浩然', '雨涵', '梓涵', '一鸣', '思远', '佳怡', '俊杰', '志强', '晓东'];
+    private const NICKNAMES = ['风一样的男子', '小幸运', '夜空中最亮的星', '快乐每一天', '往事随风', '平安是福', '一路向北', '海阔天空', '知足常乐', '顺其自然', '好运连连', '财源滚滚',
+        '阳光明媚', '淡定', '大圣归来', '追风少年', '南方姑娘', '老司机', '独行侠', '清风徐来', '人间烟火', '星辰大海', '江湖再见', '稳稳的幸福', '发发发', '明天会更好'];
+
+    private static function pick(array $list): string
+    {
+        return $list[random_int(0, count($list) - 1)];
+    }
+
+    /** 像真实会员自己起的登录账号:拼音姓名或英文词加数字,6~16 位,字母开头,全库唯一。 */
+    private static function account(): string
+    {
+        for ($try = 0; $try < 50; $try++) {
+            $base = match (random_int(0, 3)) {
+                0 => self::pick(self::SURNAMES) . self::pick(self::GIVEN),
+                1 => self::pick(self::SURNAMES) . self::pick(self::GIVEN) . self::pick(self::GIVEN),
+                2 => self::pick(self::WORDS) . self::pick(self::SURNAMES),
+                default => substr(self::pick(self::SURNAMES), 0, 1) . substr(self::pick(self::GIVEN), 0, 1) . substr(self::pick(self::GIVEN), 0, 1),
+            };
+            $digits = match (random_int(0, 3)) {
+                0 => (string) random_int(1975, 2005), 1 => (string) random_int(10, 99),
+                2 => str_pad((string) random_int(1, 1231), 4, '0', STR_PAD_LEFT), default => (string) random_int(100, 999999),
+            };
+            $account = substr($base . $digits, 0, 16);
+            if (strlen($account) >= 6 && !DB::table('users')->where('account', $account)->exists()) return $account;
+        }
+        throw new Exception('会员账号生成失败,请重试', HttpStatus::CUSTOM_ERROR);
+    }
+
+    /** 像真实会员的昵称:中文姓名、网名,偶尔带数字。 */
+    private static function nickname(): string
+    {
+        return match (random_int(0, 4)) {
+            0, 1 => self::pick(self::SURNAMES_CN) . self::pick(self::GIVEN_CN),
+            2 => self::pick(self::NICKNAMES),
+            3 => self::pick(self::NICKNAMES) . random_int(1, 999),
+            default => ucfirst(self::pick(self::WORDS)) . random_int(10, 9999),
+        };
+    }
+
+    /** 随机的公网 IPv4(避开保留网段)。 */
+    private static function ip(): string
+    {
+        do {
+            $first = random_int(1, 223);
+        } while (in_array($first, [10, 100, 127, 169, 172, 192, 198, 203], true));
+        return $first . '.' . random_int(0, 255) . '.' . random_int(0, 255) . '.' . random_int(1, 254);
+    }
+
+    /**
+     * 给早期创建的模拟会员改名:账号 sim_ 开头、昵称“模拟_”开头、IP 为 127.0.0.1 的,换成和新会员一样的随机真实风格;
+     * 同时改掉这些会员名下记录里存的旧名字,以及旧的“模拟主队 / 模拟视讯 / 模拟银行”等展示名。
+     * 只动 users.user_type = 2 的会员及其记录;会员编号、余额、金额、订单都不变。可重复执行,改过的不会再改。
+     * @return array<string,int> 各项改动的行数;$dryRun 时只统计不写库
+     */
+    public static function renameLegacy(bool $dryRun = false): array
+    {
+        if (!MemberAudience::enabled()) throw new Exception('用户类型字段尚未迁移', HttpStatus::CUSTOM_ERROR);
+        $counts = ['members' => 0, 'accounts' => 0, 'nicknames' => 0, 'ips' => 0, 'login_logs' => 0, 'third_game_orders' => 0, 'withdraw_orders' => 0, 'sport_orders' => 0];
+        $has = fn (string $table, string $column) => Schema::hasTable($table) && Schema::hasColumn($table, $column);
+        $members = DB::table('users')->where('user_type', MemberAudience::TYPE_SIMULATED)->orderBy('id')->get();
+        foreach ($members as $user) {
+            $oldAccount = (string) $user->account;
+            $oldName = (string) $user->first_name;
+            $changes = [];
+            if (str_starts_with($oldAccount, 'sim_')) { $changes['account'] = self::account(); $counts['accounts']++; }
+            if (str_starts_with($oldName, '模拟')) { $changes['first_name'] = self::nickname(); $counts['nicknames']++; }
+            if (in_array((string) ($user->register_ip ?? ''), ['127.0.0.1', ''], true)) { $changes['register_ip'] = self::ip(); $counts['ips']++; }
+            $ip = $changes['register_ip'] ?? (string) $user->register_ip;
+            $name = $changes['first_name'] ?? $oldName;
+            $work = function () use ($user, $changes, $oldAccount, $oldName, $name, $ip, $has, $dryRun, &$counts) {
+                if ($changes && !$dryRun) DB::table('users')->where('id', $user->id)->where('user_type', MemberAudience::TYPE_SIMULATED)->update($changes);
+                // 登录日志里存的账号和 IP
+                if ($has('user_login', 'login_account')) {
+                    $logs = DB::table('user_login')->where('user_id', (string) $user->user_id)
+                        ->where(fn ($q) => $q->whereRaw("SUBSTR(login_account, 1, 4) = 'sim_'")->orWhere('login_ip', '127.0.0.1'));
+                    $counts['login_logs'] += $dryRun ? $logs->count() : $logs->update(['login_account' => $changes['account'] ?? $oldAccount, 'login_ip' => $ip]);
+                }
+                // 第三方注单里存的昵称,以及旧的“模拟视讯”等游戏名
+                if (Schema::hasTable('third_game_orders')) {
+                    foreach (DB::table('third_game_orders')->where('user_id', $user->id)->where(fn ($q) => $q->where('first_name', 'like', '模拟%')
+                        ->orWhere('game_name', 'like', '模拟%'))->get(['id', 'game_type']) as $order) {
+                        $game = SimulationBetService::THIRD_GAMES[(int) $order->game_type] ?? '百家乐';
+                        if (!$dryRun) DB::table('third_game_orders')->where('id', $order->id)->update(['first_name' => $name, 'game_name' => $game, 'bet_content' => $game]);
+                        $counts['third_game_orders']++;
+                    }
+                }
+                // 提现单上的收款人、银行和卡号
+                if (Schema::hasTable('payment_orders')) {
+                    foreach (DB::table('payment_orders')->where('member_id', (string) $user->member_id)->where('type', 4)
+                        ->where(fn ($q) => $q->where('account', 'like', '模拟%')->orWhere('bank_name', '模拟银行')->orWhere('card_no', 'like', 'SIM%'))->pluck('id') as $id) {
+                        if (!$dryRun) DB::table('payment_orders')->where('id', $id)->update(['account' => $name, 'bank_name' => SimulationFundService::randomBank(), 'card_no' => SimulationFundService::randomCard()]);
+                        $counts['withdraw_orders']++;
+                    }
+                }
+                // 体育注单的“模拟主队 VS 模拟客队”
+                if ($has('sport_order', 'odd_name')) {
+                    foreach (DB::table('sport_order')->where('user_id', (string) $user->user_id)->where('odd_name', 'like', '%模拟%')->get(['id', 'detail']) as $order) {
+                        $match = SimulationBetService::randomMatch();
+                        $detail = json_decode((string) $order->detail, true);
+                        $update = ['odd_name' => $match];
+                        if (is_array($detail) && isset($detail['title'])) $update['detail'] = json_encode(['title' => $match] + $detail, JSON_UNESCAPED_UNICODE);
+                        if (!$dryRun) DB::table('sport_order')->where('id', $order->id)->update($update);
+                        $counts['sport_orders']++;
+                    }
+                }
+            };
+            $before = array_sum($counts);
+            $dryRun ? $work() : DB::transaction($work);
+            if ($changes || array_sum($counts) > $before) $counts['members']++;
+        }
+        return $counts;
+    }
+
     /** 8 位 1-9 数字,与前台会员编号同形;纯数字是因为 wallets.member_id 是 bigint。 */
     /** 8 位 1-9 数字,与前台会员编号同形;纯数字是因为 wallets.member_id 是 bigint。 */
     private static function serial(): string
     private static function serial(): string
     {
     {
@@ -71,7 +192,8 @@ final class SimulationMemberService
         SimulationSettings::assertEnabled();
         SimulationSettings::assertEnabled();
         $user = SimulationSettings::member($memberId);
         $user = SimulationSettings::member($memberId);
         self::logout($memberId);
         self::logout($memberId);
-        $row = ['user_id' => (string) $user->user_id, 'login_account' => (string) $user->account, 'login_ip' => '127.0.0.1',
+        $row = ['user_id' => (string) $user->user_id, 'login_account' => (string) $user->account,
+            'login_ip' => filter_var((string) ($user->register_ip ?? ''), FILTER_VALIDATE_IP) ? (string) $user->register_ip : self::ip(),
             'login_domain' => $domain ?: SimulationSettings::get('simulation_default_domain'), 'platform' => $platform, 'status' => UserLogin::STATUS_SUCCESS,
             'login_domain' => $domain ?: SimulationSettings::get('simulation_default_domain'), 'platform' => $platform, 'status' => UserLogin::STATUS_SUCCESS,
             'created_at' => now(), 'updated_at' => now()];
             'created_at' => now(), 'updated_at' => now()];
         $row = array_filter($row, fn ($column) => Schema::hasColumn('user_login', $column), ARRAY_FILTER_USE_KEY);
         $row = array_filter($row, fn ($column) => Schema::hasColumn('user_login', $column), ARRAY_FILTER_USE_KEY);

+ 28 - 0
app/Services/Simulation/SimulationRunner.php

@@ -114,6 +114,34 @@ final class SimulationRunner
 
 
     /** 执行一个动作。返回要写进事件的字段;返回 null 表示还要等(彩票未开奖)。 */
     /** 执行一个动作。返回要写进事件的字段;返回 null 表示还要等(彩票未开奖)。 */
     private static function perform(array $step, string $memberId): ?array
     private static function perform(array $step, string $memberId): ?array
+    {
+        if (isset($step['amount'])) {
+            $amount = self::amount($step, $memberId);
+            // 区间金额下余额连最小值都不够:这一次跳过,不算失败(真实会员没钱时也只是不下注、不提现)
+            if ($amount === null) return ['amount' => null, 'message' => '余额不足最小金额 ' . (float) $step['amount'] . ',本次跳过'];
+            $step['amount'] = $amount;
+        }
+        $result = self::act($step, $memberId);
+        return $result === null || !isset($step['amount']) || array_key_exists('amount', $result) ? $result : $result + ['amount' => $step['amount']];
+    }
+
+    /**
+     * 这一次动作的金额。固定金额原样返回;区间(amount~amount_max)随机取整数,
+     * 下注和提现不超过当前可用余额,余额不足区间最小值时返回 null。
+     */
+    private static function amount(array $step, string $memberId): ?string
+    {
+        if (!isset($step['amount_max'])) return (string) $step['amount'];
+        $min = (int) ceil((float) $step['amount']);
+        $max = (int) floor((float) $step['amount_max']);
+        if ($step['type'] !== 'recharge') {
+            $balance = (float) DB::table('wallets')->where('member_id', $memberId)->value('available_balance');
+            $max = min($max, (int) floor($balance));
+        }
+        return $max < $min ? null : (string) mt_rand($min, $max);
+    }
+
+    private static function act(array $step, string $memberId): ?array
     {
     {
         switch ($step['type']) {
         switch ($step['type']) {
             case 'register':
             case 'register':

+ 10 - 3
app/Services/Simulation/SimulationSettings.php

@@ -25,11 +25,15 @@ final class SimulationSettings
         'simulation_show_to_equity_agents' => ['1', 0, 1],
         'simulation_show_to_equity_agents' => ['1', 0, 1],
         // 一键启动的默认任务:注册 → 登录 → 充值 → 下注 → 结算 → 提现 → 退出
         // 一键启动的默认任务:注册 → 登录 → 充值 → 下注 → 结算 → 提现 → 退出
         'simulation_task_members' => ['5', 1, 200],
         'simulation_task_members' => ['5', 1, 200],
-        'simulation_task_recharge' => ['1000', 1, 1000000],
+        // 金额都是区间:每次动作在 最小~最大 之间随机取整数;最大不大于最小时就是固定金额
+        'simulation_task_recharge' => ['500', 1, 1000000],
+        'simulation_task_recharge_max' => ['3000', 1, 1000000],
         'simulation_task_bet_category' => ['mixed', null, null],
         'simulation_task_bet_category' => ['mixed', null, null],
-        'simulation_task_bet_amount' => ['100', 1, 1000000],
+        'simulation_task_bet_amount' => ['20', 1, 1000000],
+        'simulation_task_bet_amount_max' => ['500', 1, 1000000],
         'simulation_task_bet_count' => ['3', 1, 50],
         'simulation_task_bet_count' => ['3', 1, 50],
-        'simulation_task_withdraw' => ['200', 0, 1000000],
+        'simulation_task_withdraw' => ['100', 0, 1000000],
+        'simulation_task_withdraw_max' => ['500', 0, 1000000],
         'simulation_task_interval' => ['2', 0, 3600],
         'simulation_task_interval' => ['2', 0, 3600],
         // 持续运行:在日期区间内一轮接一轮地自动启动上面的默认任务
         // 持续运行:在日期区间内一轮接一轮地自动启动上面的默认任务
         'simulation_schedule_enabled' => ['0', 0, 1],
         'simulation_schedule_enabled' => ['0', 0, 1],
@@ -74,6 +78,9 @@ final class SimulationSettings
             else DB::table('config')->insert(['field' => $key, 'val' => $value]);
             else DB::table('config')->insert(['field' => $key, 'val' => $value]);
         }
         }
         $after = self::all();
         $after = self::all();
+        foreach (['simulation_task_recharge' => '充值', 'simulation_task_bet_amount' => '下注', 'simulation_task_withdraw' => '提现'] as $key => $label) {
+            if ((float) $after[$key . '_max'] < (float) $after[$key]) throw new Exception("一键任务的{$label}金额:最大值不能小于最小值", HttpStatus::CUSTOM_ERROR);
+        }
         if ($after['simulation_schedule_enabled'] === '1') {
         if ($after['simulation_schedule_enabled'] === '1') {
             [$start, $end] = [$after['simulation_schedule_start'], $after['simulation_schedule_end']];
             [$start, $end] = [$after['simulation_schedule_start'], $after['simulation_schedule_end']];
             if ($start === '' || $end === '' || $start > $end) throw new Exception('开启持续运行前,请填写正确的开始和结束日期', HttpStatus::CUSTOM_ERROR);
             if ($start === '' || $end === '' || $start > $end) throw new Exception('开启持续运行前,请填写正确的开始和结束日期', HttpStatus::CUSTOM_ERROR);

+ 13 - 5
app/Services/Simulation/SimulationTaskService.php

@@ -29,7 +29,13 @@ final class SimulationTaskService
             if (!in_array($type, self::STEP_TYPES, true)) throw new Exception('任务步骤类型不正确:' . $type, HttpStatus::CUSTOM_ERROR);
             if (!in_array($type, self::STEP_TYPES, true)) throw new Exception('任务步骤类型不正确:' . $type, HttpStatus::CUSTOM_ERROR);
             $row = ['type' => $type, 'count' => in_array($type, self::ONCE, true) ? 1 : min(50, max(1, (int) ($step['count'] ?? 1))),
             $row = ['type' => $type, 'count' => in_array($type, self::ONCE, true) ? 1 : min(50, max(1, (int) ($step['count'] ?? 1))),
                 'interval' => min(3600, max(0, (int) ($step['interval'] ?? 2)))];
                 'interval' => min(3600, max(0, (int) ($step['interval'] ?? 2)))];
-            if (in_array($type, ['recharge', 'bet', 'withdraw'], true)) $row['amount'] = SimulationSettings::assertAmount($step['amount'] ?? 100);
+            if (in_array($type, ['recharge', 'bet', 'withdraw'], true)) {
+                $row['amount'] = SimulationSettings::assertAmount($step['amount'] ?? 100);
+                // 给了更大的 amount_max 时,每次在 amount~amount_max 之间随机取整数
+                if (is_numeric($step['amount_max'] ?? null) && (float) $step['amount_max'] > (float) $row['amount']) {
+                    $row['amount_max'] = SimulationSettings::assertAmount($step['amount_max']);
+                }
+            }
             if ($type === 'bet') $row['category'] = in_array($step['category'] ?? '', self::BET_CATEGORIES, true) ? $step['category'] : 'mixed';
             if ($type === 'bet') $row['category'] = in_array($step['category'] ?? '', self::BET_CATEGORIES, true) ? $step['category'] : 'mixed';
             if ($type === 'settle') $row['settle_mode'] = in_array($step['settle_mode'] ?? 'random', ['random', 'win', 'lose'], true) ? ($step['settle_mode'] ?? 'random') : 'random';
             if ($type === 'settle') $row['settle_mode'] = in_array($step['settle_mode'] ?? 'random', ['random', 'win', 'lose'], true) ? ($step['settle_mode'] ?? 'random') : 'random';
             if (in_array($type, ['register', 'login'], true)) $row['platform'] = substr((string) ($step['platform'] ?? 'H5'), 0, 16);
             if (in_array($type, ['register', 'login'], true)) $row['platform'] = substr((string) ($step['platform'] ?? 'H5'), 0, 16);
@@ -99,7 +105,7 @@ final class SimulationTaskService
         $s = SimulationSettings::all();
         $s = SimulationSettings::all();
         $interval = (int) $s['simulation_task_interval'];
         $interval = (int) $s['simulation_task_interval'];
         $max = (float) $s['simulation_max_amount'];
         $max = (float) $s['simulation_max_amount'];
-        foreach (['simulation_task_recharge' => '充值金额', 'simulation_task_bet_amount' => '下注金额', 'simulation_task_withdraw' => '提现金额'] as $key => $label) {
+        foreach (['simulation_task_recharge_max' => '充值金额', 'simulation_task_bet_amount_max' => '下注金额', 'simulation_task_withdraw_max' => '提现金额'] as $key => $label) {
             if ((float) $s[$key] > $max) throw new Exception("默认任务的{$label}超过了单次金额上限 {$s['simulation_max_amount']},请在模拟设置中调整", HttpStatus::CUSTOM_ERROR);
             if ((float) $s[$key] > $max) throw new Exception("默认任务的{$label}超过了单次金额上限 {$s['simulation_max_amount']},请在模拟设置中调整", HttpStatus::CUSTOM_ERROR);
         }
         }
         if ((int) $s['simulation_task_members'] > (int) $s['simulation_max_members_per_task']) {
         if ((int) $s['simulation_task_members'] > (int) $s['simulation_max_members_per_task']) {
@@ -108,12 +114,14 @@ final class SimulationTaskService
         $steps = [
         $steps = [
             ['type' => 'register', 'interval' => $interval],
             ['type' => 'register', 'interval' => $interval],
             ['type' => 'login', 'interval' => $interval],
             ['type' => 'login', 'interval' => $interval],
-            ['type' => 'recharge', 'amount' => $s['simulation_task_recharge'], 'interval' => $interval],
+            ['type' => 'recharge', 'amount' => $s['simulation_task_recharge'], 'amount_max' => $s['simulation_task_recharge_max'], 'interval' => $interval],
             ['type' => 'bet', 'category' => $s['simulation_task_bet_category'], 'amount' => $s['simulation_task_bet_amount'],
             ['type' => 'bet', 'category' => $s['simulation_task_bet_category'], 'amount' => $s['simulation_task_bet_amount'],
-                'count' => (int) $s['simulation_task_bet_count'], 'interval' => $interval],
+                'amount_max' => $s['simulation_task_bet_amount_max'], 'count' => (int) $s['simulation_task_bet_count'], 'interval' => $interval],
             ['type' => 'settle', 'settle_mode' => 'random', 'interval' => $interval],
             ['type' => 'settle', 'settle_mode' => 'random', 'interval' => $interval],
         ];
         ];
-        if ((float) $s['simulation_task_withdraw'] > 0) $steps[] = ['type' => 'withdraw', 'amount' => $s['simulation_task_withdraw'], 'interval' => $interval];
+        if ((float) $s['simulation_task_withdraw'] > 0) {
+            $steps[] = ['type' => 'withdraw', 'amount' => $s['simulation_task_withdraw'], 'amount_max' => $s['simulation_task_withdraw_max'], 'interval' => $interval];
+        }
         $steps[] = ['type' => 'logout', 'interval' => $interval];
         $steps[] = ['type' => 'logout', 'interval' => $interval];
         $count = (int) $s['simulation_task_members'];
         $count = (int) $s['simulation_task_members'];
         $input = ['name' => ($scheduled ? self::SCHEDULED_PREFIX : '一键任务') . ' ' . now()->format('m-d H:i:s'), 'steps' => $steps, 'member_count' => $count];
         $input = ['name' => ($scheduled ? self::SCHEDULED_PREFIX : '一键任务') . ' ' . now()->format('m-d H:i:s'), 'steps' => $steps, 'member_count' => $count];

+ 84 - 3
tests/Integration/SimulationTest.php

@@ -247,6 +247,16 @@ class SimulationTest extends TestCase
 
 
         [$a, $b] = array_column(SimulationMemberService::create(2, ['initial_balance' => 1000]), 'member_id');
         [$a, $b] = array_column(SimulationMemberService::create(2, ['initial_balance' => 1000]), 'member_id');
         $user = DB::table('users')->where('member_id', $a)->first();
         $user = DB::table('users')->where('member_id', $a)->first();
+        // 账号、昵称、IP 都是随机的真实风格,不带“模拟 / sim”字样
+        foreach (DB::table('users')->where('user_type', 2)->get() as $created) {
+            $this->assertMatchesRegularExpression('/^[a-z][a-z0-9]{5,15}$/', $created->account);
+            $this->assertStringNotContainsString('sim', $created->account);
+            $this->assertStringNotContainsString('模拟', $created->first_name);
+            $this->assertNotSame('', $created->first_name);
+            $this->assertNotSame('127.0.0.1', $created->register_ip);
+            $this->assertNotFalse(filter_var($created->register_ip, FILTER_VALIDATE_IP));
+        }
+        $this->assertSame(2, DB::table('users')->where('user_type', 2)->distinct()->count('account'));
         $this->assertSame(['2', 2, null], [(string) $user->from, (int) $user->user_type, $user->agent_id]);
         $this->assertSame(['2', 2, null], [(string) $user->from, (int) $user->user_type, $user->agent_id]);
         $this->assertSame([1000.0, 0.0], $this->wallet($a));
         $this->assertSame([1000.0, 0.0], $this->wallet($a));
 
 
@@ -372,19 +382,44 @@ class SimulationTest extends TestCase
         $this->assertSame('mixed', SimulationSettings::get('simulation_task_bet_category'), 'the default task bets on every category');
         $this->assertSame('mixed', SimulationSettings::get('simulation_task_bet_category'), 'the default task bets on every category');
         // 这里用体育:彩票要等真实开奖,测试里不会开奖
         // 这里用体育:彩票要等真实开奖,测试里不会开奖
         SimulationSettings::save(['simulation_task_bet_category' => 'sport', 'simulation_task_members' => 2, 'simulation_task_recharge' => 500, 'simulation_task_bet_amount' => 50,
         SimulationSettings::save(['simulation_task_bet_category' => 'sport', 'simulation_task_members' => 2, 'simulation_task_recharge' => 500, 'simulation_task_bet_amount' => 50,
-            'simulation_task_bet_count' => 2, 'simulation_task_withdraw' => 100, 'simulation_task_interval' => 0]);
+            'simulation_task_bet_count' => 2, 'simulation_task_withdraw' => 100, 'simulation_task_interval' => 0,
+            // 金额区间:充值 500~900,下注 50~80,提现 100~150
+            'simulation_task_recharge_max' => 900, 'simulation_task_bet_amount_max' => 80, 'simulation_task_withdraw_max' => 150]);
         $quickId = SimulationTaskService::quickStart(1);
         $quickId = SimulationTaskService::quickStart(1);
         for ($i = 0; $i < 60 && in_array(DB::table('simulation_task_runs')->where('id', $quickId)->value('status'), ['queued', 'running'], true); $i++) SimulationRunner::tick();
         for ($i = 0; $i < 60 && in_array(DB::table('simulation_task_runs')->where('id', $quickId)->value('status'), ['queued', 'running'], true); $i++) SimulationRunner::tick();
         $quick = DB::table('simulation_task_runs')->where('id', $quickId)->first();
         $quick = DB::table('simulation_task_runs')->where('id', $quickId)->first();
         $this->assertSame(['completed', 16, 16, 0], [$quick->status, (int) $quick->total, (int) $quick->completed, (int) $quick->failed], (string) $quick->last_error);
         $this->assertSame(['completed', 16, 16, 0], [$quick->status, (int) $quick->total, (int) $quick->completed, (int) $quick->failed], (string) $quick->last_error);
         $this->assertSame(['register', 'login', 'recharge', 'bet', 'settle', 'withdraw', 'logout'], array_column(json_decode($quick->steps, true), 'type'));
         $this->assertSame(['register', 'login', 'recharge', 'bet', 'settle', 'withdraw', 'logout'], array_column(json_decode($quick->steps, true), 'type'));
-        SimulationSettings::save(['simulation_task_recharge' => 20000]);
+        // 每次动作的金额都落在各自的区间内,并且是整数;同一步骤不是每次都一样
+        $amounts = fn (string $action) => DB::table('simulation_task_events')->where('run_id', $quickId)->where('action', $action)->pluck('amount')->map(fn ($a) => (float) $a)->all();
+        foreach (['recharge' => [500, 900], 'bet' => [50, 80], 'withdraw' => [100, 150]] as $action => [$min, $max]) {
+            foreach ($amounts($action) as $amount) {
+                $this->assertTrue($amount >= $min && $amount <= $max && floor($amount) === $amount, "$action $amount is within $min-$max");
+            }
+        }
+        $this->assertSame([2, 4, 2], [count($amounts('recharge')), count($amounts('bet')), count($amounts('withdraw'))]);
+        $this->assertSame((float) DB::table('payment_orders')->whereIn('member_id', json_decode($quick->member_ids, true))->where('type', 1)->sum('amount'), array_sum($amounts('recharge')));
+        try { SimulationSettings::save(['simulation_task_bet_amount' => 90]); $this->fail('max below min'); }
+        catch (\Exception $e) { $this->assertStringContainsString('最大值不能小于最小值', $e->getMessage()); }
+        $this->assertSame('50', SimulationSettings::get('simulation_task_bet_amount'));
+        // 余额不够区间最小值:跳过这一次,不算失败,也不会把整轮拖成失败
+        $poor = SimulationMemberService::create(1)[0]['member_id'];
+        $skipId = SimulationTaskService::start(['name' => '余额不足', 'member_ids' => [$poor], 'steps' => [
+            ['type' => 'bet', 'category' => 'sport', 'amount' => 50, 'amount_max' => 80, 'count' => 3, 'interval' => 0],
+            ['type' => 'withdraw', 'amount' => 100, 'amount_max' => 150, 'interval' => 0]]], 1);
+        for ($i = 0; $i < 20 && in_array(DB::table('simulation_task_runs')->where('id', $skipId)->value('status'), ['queued', 'running'], true); $i++) SimulationRunner::tick();
+        $skip = DB::table('simulation_task_runs')->where('id', $skipId)->first();
+        $this->assertSame(['completed', 4, 0, 0], [$skip->status, (int) $skip->completed, (int) $skip->failed, DB::table('sport_order')->where('user_id', $poor)->count()]);
+        $this->assertStringContainsString('本次跳过', DB::table('simulation_task_events')->where('run_id', $skipId)->value('message'));
+        DB::table('users')->where('member_id', $poor)->delete();
+        DB::table('wallets')->where('member_id', $poor)->delete();
+        SimulationSettings::save(['simulation_task_recharge_max' => 20000]);
         try { SimulationTaskService::quickStart(1); $this->fail('defaults above the amount cap are refused'); }
         try { SimulationTaskService::quickStart(1); $this->fail('defaults above the amount cap are refused'); }
         catch (\Exception $e) { $this->assertStringContainsString('单次金额上限', $e->getMessage()); }
         catch (\Exception $e) { $this->assertStringContainsString('单次金额上限', $e->getMessage()); }
         $this->assertSame($before, $this->realView());
         $this->assertSame($before, $this->realView());
 
 
         // 持续运行:日期区间内一轮接一轮;区间外、间隔未到、上一轮没结束时都不启动
         // 持续运行:日期区间内一轮接一轮;区间外、间隔未到、上一轮没结束时都不启动
-        SimulationSettings::save(['simulation_task_recharge' => 500]);
+        SimulationSettings::save(['simulation_task_recharge_max' => 900]);
         try { SimulationSettings::save(['simulation_schedule_enabled' => 1, 'simulation_schedule_start' => '', 'simulation_schedule_end' => '']); $this->fail('dates are required'); }
         try { SimulationSettings::save(['simulation_schedule_enabled' => 1, 'simulation_schedule_start' => '', 'simulation_schedule_end' => '']); $this->fail('dates are required'); }
         catch (\Exception $e) { $this->assertStringContainsString('开始和结束日期', $e->getMessage()); }
         catch (\Exception $e) { $this->assertStringContainsString('开始和结束日期', $e->getMessage()); }
         $this->assertSame('0', SimulationSettings::get('simulation_schedule_enabled'), 'a refused save changes nothing');
         $this->assertSame('0', SimulationSettings::get('simulation_schedule_enabled'), 'a refused save changes nothing');
@@ -493,6 +528,52 @@ class SimulationTest extends TestCase
         $this->assertSame($before, $this->realView());
         $this->assertSame($before, $this->realView());
     }
     }
 
 
+    /** 早期的模拟会员(sim_ 账号、“模拟_”昵称)原地改名:名下记录里的旧名字一起换,钱和订单不动,真实会员不动,可重复执行。 */
+    public function test_legacy_simulated_members_are_renamed_in_place(): void
+    {
+        [$a, $b] = array_column(SimulationMemberService::create(2, ['initial_balance' => 1000]), 'member_id');
+        SimulationMemberService::login($a);
+        SimulationBetService::settleSport(SimulationBetService::sport($a, 50, 2)->id, 'win');
+        SimulationBetService::third($a, 40, 2, 'lose');
+        $withdraw = SimulationFundService::withdrawApply($a, 100);
+        // 还原成旧版本创建出来的样子
+        $user = DB::table('users')->where('member_id', $a)->first();
+        DB::table('users')->where('member_id', $a)->update(['account' => 'sim_' . $a, 'first_name' => '模拟_1234', 'register_ip' => '127.0.0.1']);
+        DB::table('user_login')->where('user_id', $a)->update(['login_account' => 'sim_' . $a, 'login_ip' => '127.0.0.1']);
+        DB::table('third_game_orders')->where('user_id', $user->id)->update(['first_name' => '模拟_1234', 'game_name' => '模拟老虎机', 'bet_content' => '模拟注单']);
+        DB::table('payment_orders')->where('id', $withdraw->id)->update(['account' => '模拟_1234', 'bank_name' => '模拟银行', 'card_no' => 'SIM' . $a]);
+        DB::table('sport_order')->where('user_id', $a)->update(['odd_name' => '模拟主队 VS 模拟客队', 'detail' => json_encode(['simulation' => true, 'title' => '模拟主队 VS 模拟客队', 'selection' => '主胜'])]);
+        $untouched = (array) DB::table('users')->where('member_id', $b)->first();
+        $real = (array) DB::table('users')->where('member_id', 'r1')->first();
+        $money = [$this->wallet($a), DB::table('balance_logs')->where('member_id', $a)->sum('amount'), DB::table('payment_orders')->where('member_id', $a)->sum('amount')];
+
+        $preview = SimulationMemberService::renameLegacy(true);
+        $this->assertSame(['members' => 1, 'accounts' => 1, 'nicknames' => 1, 'ips' => 1, 'login_logs' => 1, 'third_game_orders' => 1, 'withdraw_orders' => 1, 'sport_orders' => 1], $preview);
+        $this->assertSame('sim_' . $a, DB::table('users')->where('member_id', $a)->value('account'), 'a dry run writes nothing');
+
+        $this->assertSame($preview, SimulationMemberService::renameLegacy());
+        $renamed = DB::table('users')->where('member_id', $a)->first();
+        $this->assertMatchesRegularExpression('/^[a-z][a-z0-9]{5,15}$/', $renamed->account);
+        $this->assertStringNotContainsString('模拟', $renamed->first_name);
+        $this->assertNotSame('127.0.0.1', $renamed->register_ip);
+        $this->assertSame([$user->id, $a, 2], [$renamed->id, $renamed->member_id, (int) $renamed->user_type], 'identity is unchanged');
+        $login = DB::table('user_login')->where('user_id', $a)->first();
+        $this->assertSame([$renamed->account, $renamed->register_ip], [$login->login_account, $login->login_ip]);
+        $third = DB::table('third_game_orders')->where('user_id', $user->id)->first();
+        $this->assertSame([$renamed->first_name, '财神到', '财神到'], [$third->first_name, $third->game_name, $third->bet_content]);
+        $order = DB::table('payment_orders')->where('id', $withdraw->id)->first();
+        $this->assertSame($renamed->first_name, $order->account);
+        $this->assertStringNotContainsString('模拟', $order->bank_name);
+        $this->assertMatchesRegularExpression('/^62\d{17}$/', $order->card_no);
+        $sport = DB::table('sport_order')->where('user_id', $a)->first();
+        $this->assertStringNotContainsString('模拟', $sport->odd_name);
+        $this->assertSame($sport->odd_name, json_decode($sport->detail, true)['title']);
+
+        $this->assertSame($money, [$this->wallet($a), DB::table('balance_logs')->where('member_id', $a)->sum('amount'), DB::table('payment_orders')->where('member_id', $a)->sum('amount')]);
+        $this->assertSame([$untouched, $real], [(array) DB::table('users')->where('member_id', $b)->first(), (array) DB::table('users')->where('member_id', 'r1')->first()]);
+        $this->assertSame(0, array_sum(SimulationMemberService::renameLegacy()), 'nothing left to rename');
+    }
+
     public function test_guards_refuse_real_members_and_a_closed_switch(): void
     public function test_guards_refuse_real_members_and_a_closed_switch(): void
     {
     {
         foreach ([fn () => SimulationFundService::recharge('r1', 10), fn () => SimulationFundService::adjust('g1', 10, 'credit', 'x'),
         foreach ([fn () => SimulationFundService::recharge('r1', 10), fn () => SimulationFundService::adjust('g1', 10, 'credit', 'x'),