app = new Application(dirname(__DIR__, 2)); $this->app->instance('config', new Repository(['app' => ['locale' => 'zh'], 'agent' => []])); Facade::setFacadeApplication($this->app); $db = new Manager($this->app); $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']); $db->setEventDispatcher(new Dispatcher($this->app)); $db->setAsGlobal(); $db->bootEloquent(); $this->app->instance('db', $db->getDatabaseManager()); $this->app->bind('db.schema', fn () => $db->schema()); $this->app->instance('hash', new BcryptHasher(['rounds' => 4])); $translator = new Translator(new ArrayLoader(), 'zh'); $this->app->instance('translator', $translator); $this->app->instance('validator', new Factory($translator, $this->app)); $this->app->instance('request', Request::create('/')); Request::macro('validate', function (array $rules) { return app('validator')->make($this->all(), $rules)->validate(); }); $responses = new class { public function json($data, $status = 200, $headers = [], $options = 0) { return new JsonResponse($data, $status, $headers, $options); } }; $this->app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, $responses); Schema::create('users', function (Blueprint $t) { $t->id(); $t->string('member_id'); $t->string('username'); $t->string('first_name')->default(''); $t->integer('status')->default(1); $t->string('register_ip')->default(''); $t->string('register_domain')->default(''); $t->timestamps(); }); foreach (['2026_08_24_140000_create_agent_system_tables.php', '2026_08_28_120000_create_agent_profit_profiles_and_rebate_records.php'] as $file) { (require dirname(__DIR__, 2) . '/database/migrations/' . $file)->up(); } // Flow migration repairs MySQL information_schema indexes; use equivalent SQLite test tables. Schema::create('agent_flow_commission_profiles', function (Blueprint $t) { $t->id(); $t->string('name'); $t->integer('is_default')->default(0); $t->timestamps(); foreach (AgentFlowCommissionProfile::RATE_FIELDS as $field) $t->decimal($field, 8, 4)->default(0); }); Schema::create('agent_flow_commission_assignments', function (Blueprint $t) { $t->id(); $t->unsignedBigInteger('agent_id'); $t->unsignedBigInteger('flow_commission_profile_id'); $t->string('profile_name'); $t->date('effective_from'); $t->unsignedBigInteger('created_by')->nullable(); foreach (AgentFlowCommissionProfile::RATE_FIELDS as $field) $t->decimal($field, 8, 4)->default(0); $t->timestamps(); $t->unique(['agent_id', 'effective_from']); }); Schema::table('agents', fn (Blueprint $t) => $t->unsignedBigInteger('flow_commission_profile_id')->nullable()); DB::table('agent_flow_commission_profiles')->insert(['name' => 'Default', 'is_default' => 1]); foreach (['agent_flow_commission_profiles', 'agent_profit_commission_profiles'] as $table) { Schema::table($table, fn (Blueprint $t) => $t->unsignedBigInteger('owner_agent_id')->nullable()); } foreach (['recharges', 'withdraws', 'payment_orders'] as $table) { Schema::create($table, function (Blueprint $t) { $t->id(); $t->string('member_id'); $t->integer('status'); $t->string('type')->nullable(); $t->decimal('amount', 18, 4); $t->timestamps(); }); } Schema::create('wallets', function (Blueprint $t) { $t->id(); $t->string('member_id'); $t->decimal('available_balance', 18, 4)->default(0); $t->decimal('frozen_balance', 18, 4)->default(0); }); Schema::create('balance_logs', function (Blueprint $t) { $t->id(); $t->string('member_id'); $t->string('change_type'); $t->integer('related_id')->nullable(); $t->decimal('amount', 18, 4); $t->timestamps(); }); $this->agents = new AgentService(new AgentFlowCommissionAssignmentService(), new AgentProfitCommissionAssignmentService()); } protected function tearDown(): void { DB::disconnect(); Facade::clearResolvedInstances(); Carbon::setTestNow(); parent::tearDown(); } private function agent(?Agent $parent = null): Agent { static $number = 0; return $this->agents->create([ 'username' => 'agent' . ++$number, 'password' => 'old-password', 'withdraw_password' => 'withdraw-old', 'flow_commission_profile_id' => AgentFlowCommissionProfile::officialDefaultId(), ], null, $parent); } private function token(Agent $agent): string { $plain = 'test-token-' . $agent->id; AgentToken::query()->create(['agent_id' => $agent->id, 'token_hash' => hash('sha256', $plain), 'expires_at' => now()->addDay(), 'last_used_at' => now(), 'ip' => '', 'device' => 'pc']); return $plain; } public function test_admin_password_reset_revokes_old_login(): void { $agent = $this->agent(); $token = $this->token($agent); $this->agents->update($agent, ['password' => 'new-password']); $this->assertSame(0, AgentToken::query()->where('agent_id', $agent->id)->count()); $request = Request::create('/agent/profile'); $request->headers->set('Authorization', 'Bearer ' . $token); $response = (new AgentAuthMiddleware())->handle($request, fn () => new JsonResponse(['code' => 0])); $this->assertSame(101011, $response->getData(true)['code']); } public function test_disable_then_enable_does_not_restore_old_login(): void { $agent = $this->agent(); $this->token($agent); $this->agents->update($agent, ['status' => 0]); $this->agents->update($agent, ['status' => 1]); $this->assertSame(0, AgentToken::query()->count()); } public function test_non_sensitive_edit_preserves_login(): void { $agent = $this->agent(); $this->token($agent); $this->agents->update($agent, ['real_name' => 'new name']); $this->assertSame(1, AgentToken::query()->count()); } public function test_finance_counts_include_only_successful_in_range_provider_orders(): void { $agent = $this->agent(); DB::table('users')->insert(['member_id' => 'm1', 'username' => 'member', 'agent_id' => $agent->id, 'created_at' => '2026-01-01 00:00:00']); $base = ['member_id' => 'm1', 'amount' => 10, 'created_at' => now()]; DB::table('recharges')->insert($base + ['status' => 1]); DB::table('withdraws')->insert($base + ['status' => 1]); foreach ([PaymentOrderService::TYPE_PAY, PaymentOrderService::TYPE_PAYOUT, PaymentOrderService::TYPE_SELF_PAYOUT] as $type) { DB::table('payment_orders')->insert($base + ['type' => $type, 'status' => PaymentOrderService::STATUS_SUCCESS]); } DB::table('payment_orders')->insert($base + ['type' => PaymentOrderService::TYPE_PAY, 'status' => -99]); DB::table('payment_orders')->insert(array_merge($base, ['type' => PaymentOrderService::TYPE_PAY, 'status' => PaymentOrderService::STATUS_SUCCESS, 'created_at' => '2026-08-01 00:00:00'])); DB::table('payment_orders')->insert(array_merge($base, ['type' => PaymentOrderService::TYPE_PAY, 'status' => PaymentOrderService::STATUS_SUCCESS, 'member_id' => 'unrelated'])); $result = (new AgentMemberService(new AgentReportService()))->finance($agent, []); $member = $result['list'][0]; $this->assertSame(2, $member->recharge_count); $this->assertSame(3, $member->withdraw_count); $this->assertSame('20.0000', $member->recharge_amount); $this->assertSame('30.0000', $member->withdraw_amount); } public function test_login_logs_filter_login_time_not_record_creation_time(): void { $agent = $this->agent(); AgentLoginLog::query()->create(['agent_id' => $agent->id, 'username' => $agent->username, 'login_at' => '2026-09-06 23:59:59', 'created_at' => '2026-09-07 00:00:01']); $controller = new AdminAgent(); $request = Request::create('/admin/agent/login-logs', 'GET', ['start_date' => '2026-09-06', 'end_date' => '2026-09-06']); $this->assertSame(1, $controller->loginLogs($request)->getData(true)['data']['total']); } private function fundedAccount(Agent $agent): AgentWithdrawAccount { Agent::query()->whereKey($agent->id)->update(['balance' => 100]); return AgentWithdrawAccount::query()->create(['agent_id' => $agent->id, 'type' => 'bank', 'account' => 'test-account', 'status' => 1]); } public function test_withdrawal_uses_current_password_not_stale_request_model(): void { $agent = $this->agent(); $account = $this->fundedAccount($agent); $this->agents->update($agent, ['withdraw_password' => 'withdraw-new']); $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('提现密码错误'); (new AgentWithdrawalService())->request($agent, $account->id, '10', 'withdraw-old', 'stale'); } public function test_disabled_agent_cannot_submit_with_stale_request_model(): void { $agent = $this->agent(); $account = $this->fundedAccount($agent); $this->agents->update($agent, ['status' => 0]); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('代理账号已禁用'); (new AgentWithdrawalService())->request($agent, $account->id, '10', 'withdraw-old', 'disabled'); } public function test_withdrawal_retry_and_rejection_move_funds_once(): void { $agent = $this->agent(); $account = $this->fundedAccount($agent); $service = new AgentWithdrawalService(); $one = $service->request($agent, $account->id, '10', 'withdraw-old', 'retry'); $two = $service->request($agent, $account->id, '10', 'withdraw-old', 'retry'); $this->assertSame($one->id, $two->id); $this->assertSame('90.0000', $agent->fresh()->balance); $this->assertSame('10.0000', $agent->fresh()->frozen_balance); $service->audit($one->id, 'reject', 1); $this->assertSame('100.0000', $agent->fresh()->balance); $this->assertSame('0.0000', $agent->fresh()->frozen_balance); $this->assertSame(1, AgentWithdrawal::query()->count()); $this->assertSame(2, AgentBalanceLog::query()->count()); } public function test_transfer_rechecks_current_parent_inside_service(): void { $root = $this->agent(); $child = $this->agent($root); $other = $this->agent(); Agent::query()->whereKey($root->id)->update(['balance' => 100]); Agent::query()->whereKey($child->id)->update(['parent_id' => $other->id, 'path' => $other->path . $child->id . '/']); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('只能操作当前直属下级的额度'); (new AgentWalletService())->transfer($root->id, $child->id, '10', 'test', 'moved', $root->id); } public function test_transfer_retry_and_reclaim_from_disabled_child(): void { $root = $this->agent(); $child = $this->agent($root); Agent::query()->whereKey($root->id)->update(['balance' => 100]); $wallets = new AgentWalletService(); $wallets->transfer($root->id, $child->id, '10', 'test', 'once', $root->id); $wallets->transfer($root->id, $child->id, '10', 'test', 'once', $root->id); $this->assertSame('90.0000', $root->fresh()->balance); $this->agents->update($child, ['status' => 0]); $wallets->transfer($child->id, $root->id, '10', 'test', 'reclaim', $root->id); $this->assertSame('100.0000', $root->fresh()->balance); $this->assertSame('0.0000', $child->fresh()->balance); } public function test_historical_settlement_ignores_new_agents_and_new_children(): void { Carbon::setTestNow(Carbon::parse('2026-09-06 12:00:00')); $root = $this->agent(); Carbon::setTestNow(Carbon::parse('2026-09-07 12:00:00')); $this->agent($root); $this->agent(); $service = new AgentCommissionService(new AgentReportService(), new AgentWalletService(), new AgentFlowCommissionAssignmentService(), new AgentProfitCommissionAssignmentService()); $this->assertSame(['created' => 0, 'credited' => 0], $service->settle('2026-09-06', false)); } public function test_daily_game_stats_work_with_bot_table_prefix(): void { $agent = $this->agent(); DB::table('users')->insert(['member_id' => 'm1', 'username' => 'member', 'agent_id' => $agent->id]); Schema::create('bets', function (Blueprint $t) { $t->id(); $t->string('member_id'); $t->integer('status'); $t->decimal('amount', 18, 4); $t->decimal('profit', 18, 4); $t->timestamps(); }); DB::table('bets')->insert(['member_id' => 'm1', 'status' => 2, 'amount' => 10, 'profit' => 0, 'created_at' => now()]); foreach (['sport_game_order', 'jisu_game_order'] as $table) { Schema::create($table, function (Blueprint $t) { $t->id(); $t->string('member_id'); $t->integer('status'); $t->decimal('amount', 18, 4); $t->decimal('profit_and_loss', 18, 4); $t->timestamps(); }); DB::table($table)->insert(['member_id' => 'm1', 'status' => 1, 'amount' => 10, 'profit_and_loss' => 0, 'created_at' => now()]); } Schema::create('lhc_order', function (Blueprint $t) { $t->id(); $t->string('member_id'); $t->integer('lottery_status'); $t->decimal('amount', 18, 4); $t->decimal('total_amount', 18, 4)->nullable(); $t->decimal('win_amount', 18, 4); $t->integer('created_at'); }); DB::table('lhc_order')->insert(['member_id' => 'm1', 'lottery_status' => 1, 'amount' => 10, 'total_amount' => null, 'win_amount' => 0, 'created_at' => now()->timestamp]); (require dirname(__DIR__, 2) . '/database/migrations/2026_08_21_120000_create_third_game_orders_table.php')->up(); DB::table('third_game_orders')->insert(['user_id' => DB::table('users')->value('id'), 'member_id' => 'm1', 'order_key' => 'test', 'game_order_id' => 'test', 'player_id' => 'test', 'currency' => 'CNY', 'platform' => 'TEST', 'game_type' => 1, 'status' => 1, 'bet_amount' => 10, 'valid_amount' => 10, 'settled_amount' => -10, 'last_update_time' => now()]); $reports = new AgentReportService(); $this->assertSame(5, $reports->refreshDailyGameStats('2026-09-07')); foreach (AgentDailyGameStat::query()->get() as $stat) { $this->assertSame('10.0000', $stat->valid_bet_amount); $this->assertSame('-10.0000', $stat->win_loss); } $summary = $reports->summaryForTree($agent, '2026-09-07', '2026-09-07'); $this->assertSame(5, $summary['bet_count']); $this->assertSame('50.0000', $summary['valid_bet_amount']); $this->assertSame('-50.0000', $summary['win_loss']); } public function test_member_finance_does_not_include_other_agent_tree(): void { $root = $this->agent(); $child = $this->agent($root); $other = $this->agent(); foreach ([$root, $child, $other] as $agent) { DB::table('users')->insert(['member_id' => 'm' . $agent->id, 'username' => 'member' . $agent->id, 'agent_id' => $agent->id, 'created_at' => now()]); } $service = new AgentMemberService(new AgentReportService()); $this->assertSame(2, $service->finance($root, [])['total']); $this->assertSame(0, $service->finance($root, ['agent_id' => $other->id])['total']); $this->assertSame(1, $service->finance($child, [])['total']); } public function test_sub_agent_cannot_take_profile_higher_than_parent(): void { $root = $this->agent(); $profile = AgentFlowCommissionProfile::query()->create(['name' => 'High rate', 'live_rate' => 90]); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('下级代理流水佣金方案不能高于上级方案'); $this->agents->create(['username' => 'child-high', 'password' => 'password', 'flow_commission_profile_id' => $profile->id], null, $root); } public function test_business_errors_keep_existing_response_contract(): void { $controller = new class extends AgentApiController { public function trigger() { return $this->execute(fn () => throw new \RuntimeException('代理余额不足')); } }; $data = $controller->trigger()->getData(true); $this->assertSame(['code', 'timestamp', 'msg', 'data'], array_keys($data)); $this->assertSame(-3, $data['code']); $this->assertSame('代理余额不足', $data['msg']); } public function test_settlement_preview_credit_and_retry_preserve_paid_snapshot(): void { Carbon::setTestNow(Carbon::parse('2026-09-06 12:00:00')); DB::table('agent_flow_commission_profiles')->update(['live_rate' => 1]); DB::table('agent_profit_commission_profiles')->update(['live_rate' => 2]); $agent = $this->agent(); DB::table('agent_daily_game_stats')->insert(['stat_date' => '2026-09-06', 'agent_id' => $agent->id, 'platform' => 'test', 'game_type' => 1, 'bet_count' => 1, 'bet_amount' => 100, 'valid_bet_amount' => 100, 'win_loss' => -50]); Carbon::setTestNow(Carbon::parse('2026-09-07 12:00:00')); $service = new AgentCommissionService(new AgentReportService(), new AgentWalletService(), new AgentFlowCommissionAssignmentService(), new AgentProfitCommissionAssignmentService()); $this->assertSame(['created' => 1, 'credited' => 0], $service->settle('2026-09-06', false)); $this->assertSame('0.0000', $agent->fresh()->balance); $this->assertSame(['created' => 0, 'credited' => 2], $service->settle('2026-09-06')); $this->assertSame('2.0000', $agent->fresh()->balance); DB::table('agent_daily_game_stats')->update(['valid_bet_amount' => 200]); $this->assertSame(['created' => 0, 'credited' => 0], $service->settle('2026-09-06')); $this->assertSame('2.0000', $agent->fresh()->balance); $this->assertSame('100.0000', AgentRebateRecord::query()->firstOrFail()->valid_bet_amount); $this->assertSame(2, AgentBalanceLog::query()->count()); } public function test_settlement_command_rejects_invalid_and_unfinished_dates(): void { $handler = $this->createMock(ExceptionHandler::class); $handler->expects($this->exactly(3))->method('report'); $this->app->instance(ExceptionHandler::class, $handler); $reports = $this->createMock(AgentReportService::class); $reports->expects($this->never())->method('refreshDaily'); $this->app->instance(AgentReportService::class, $reports); $commissions = $this->createMock(AgentCommissionService::class); $commissions->expects($this->never())->method('settle'); $this->app->instance(AgentCommissionService::class, $commissions); foreach (['2026-02-30', '2026-09-07', '2026-09-08'] as $date) { $command = new \App\Console\Commands\AgentDailySettle(); $command->setLaravel($this->app); $tester = new \Symfony\Component\Console\Tester\CommandTester($command); $this->assertSame(1, $tester->execute(['date' => $date])); } } public function test_sql_errors_are_logged_but_not_returned_to_frontend(): void { $handler = $this->createMock(ExceptionHandler::class); $handler->expects($this->once())->method('report'); $this->app->instance(ExceptionHandler::class, $handler); $controller = new class extends AgentApiController { public function trigger() { return $this->execute(fn () => throw new QueryException('select sensitive_table', ['secret'], new \PDOException('internal database error'))); } }; $data = $controller->trigger()->getData(true); $this->assertSame(-3, $data['code']); $this->assertSame('系统处理失败,请稍后重试', $data['msg']); $this->assertSame([], $data['data']); } }