feat: 增强管理员功能与数据处理

- 在多个控制器中引入 agent_node_id,以支持基于代理节点的权限和数据过滤。
- 更新 AdminRole 和 AdminUser 模型,新增角色范围和代理节点相关功能,提升角色管理的灵活性。
- 在请求验证中添加 agent_node_id 字段,确保 API 接口支持代理节点的相关操作。
- 优化 LotterySettings 服务,支持批量写入设置,提升配置管理的效率。
- 更新仪表板和报告服务,增强数据统计功能,确保管理员能够获取更全面的统计信息。
This commit is contained in:
2026-06-02 14:36:58 +08:00
parent d5232c756f
commit 0841fbed32
96 changed files with 5004 additions and 182 deletions

View File

@@ -0,0 +1,192 @@
<?php
use App\Models\AdminUser;
use App\Models\AgentNode;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function (): void {
$this->artisan('lottery:admin-auth-sync')->assertExitCode(0);
});
function grantDelegationAgentOperator(AdminUser $admin, AgentNode $agent, bool $manage = true): void
{
$now = now();
$roleId = DB::table('admin_roles')->insertGetId([
'slug' => 'agent_ops_'.$admin->id,
'code' => 'agent_ops_'.$admin->id,
'name' => 'Agent Ops',
'description' => null,
'status' => 1,
'is_system' => false,
'sort_order' => 0,
'created_at' => $now,
'updated_at' => $now,
]);
$codes = $manage
? ['agent.node.view', 'agent.node.manage']
: ['agent.node.view'];
$actionIds = DB::table('admin_menu_actions')
->whereIn('permission_code', $codes)
->pluck('id');
foreach ($actionIds as $actionId) {
DB::table('admin_role_menu_actions')->insert([
'role_id' => $roleId,
'menu_action_id' => (int) $actionId,
]);
}
DB::table('admin_user_site_roles')->insert([
'admin_user_id' => $admin->id,
'site_id' => (int) $agent->admin_site_id,
'role_id' => $roleId,
'granted_at' => $now,
]);
DB::table('admin_user_agents')->insert([
'admin_user_id' => $admin->id,
'agent_node_id' => (int) $agent->id,
'is_primary' => true,
'granted_at' => $now,
]);
}
test('parent agent can sync delegation grants for direct child', function (): void {
$siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
$rootId = (int) DB::table('agent_nodes')->where('admin_site_id', $siteId)->where('depth', 0)->value('id');
$service = app(\App\Services\Agent\AgentNodeService::class);
$super = AdminUser::query()->create([
'username' => 'deleg_super',
'name' => 'Super',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($super);
$parent = $service->createChild($super, [
'parent_id' => $rootId,
'code' => 'deleg-parent',
'name' => 'Deleg Parent',
]);
$child = $service->createChild($super, [
'parent_id' => $parent->id,
'code' => 'deleg-child',
'name' => 'Deleg Child',
]);
$parentAdmin = AdminUser::query()->create([
'username' => 'deleg_parent_admin',
'name' => 'Parent Admin',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantDelegationAgentOperator($parentAdmin, $parent, manage: true);
$viewActionId = (int) DB::table('admin_menu_actions')
->where('permission_code', 'agent.node.view')
->value('id');
$token = $parentAdmin->createToken('test', ['*'], now()->addDay())->plainTextToken;
$this->withHeader('Authorization', 'Bearer '.$token)
->putJson('/api/v1/admin/agent-nodes/'.$child->id.'/delegation-grants', [
'grants' => [
['menu_action_id' => $viewActionId, 'can_delegate' => true],
],
])
->assertOk()
->assertJsonPath('data.child_agent_id', $child->id)
->assertJsonCount(1, 'data.grants');
$this->withHeader('Authorization', 'Bearer '.$token)
->getJson('/api/v1/admin/agent-nodes/'.$child->id.'/delegation-grants')
->assertOk()
->assertJsonPath('data.grants.0.can_delegate', true);
});
test('delegation ceiling blocks role permissions beyond child grants', function (): void {
$siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
$rootId = (int) DB::table('agent_nodes')->where('admin_site_id', $siteId)->where('depth', 0)->value('id');
$service = app(\App\Services\Agent\AgentNodeService::class);
$super = AdminUser::query()->create([
'username' => 'ceil_super',
'name' => 'Super',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($super);
$branch = $service->createChild($super, [
'parent_id' => $rootId,
'code' => 'ceil-branch',
'name' => 'Ceil Branch',
]);
$viewActionId = (int) DB::table('admin_menu_actions')
->where('permission_code', 'agent.node.view')
->value('id');
DB::table('agent_delegation_grants')->insert([
'parent_agent_id' => $rootId,
'child_agent_id' => $branch->id,
'menu_action_id' => $viewActionId,
'can_delegate' => true,
'granted_at' => now(),
'created_at' => now(),
'updated_at' => now(),
]);
$operator = AdminUser::query()->create([
'username' => 'ceil_ops',
'name' => 'Ops',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantDelegationAgentOperator($operator, $branch, manage: true);
$token = $operator->createToken('test', ['*'], now()->addDay())->plainTextToken;
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/v1/admin/agent-nodes/'.$branch->id.'/roles', [
'slug' => 'ceil_ok',
'name' => 'OK',
'permission_slugs' => ['prd.agent.view'],
])
->assertOk();
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/v1/admin/agent-nodes/'.$branch->id.'/roles', [
'slug' => 'ceil_bad',
'name' => 'Bad',
'permission_slugs' => ['prd.dashboard.view'],
])
->assertStatus(422);
});
test('auth me includes delegation ceiling for agent user', function (): void {
$siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
$root = AgentNode::query()->where('admin_site_id', $siteId)->where('depth', 0)->firstOrFail();
$admin = AdminUser::query()->create([
'username' => 'me_deleg',
'name' => 'Me',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantDelegationAgentOperator($admin, $root, manage: false);
$token = $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;
$this->withHeader('Authorization', 'Bearer '.$token)
->getJson('/api/v1/admin/auth/me')
->assertOk()
->assertJsonStructure(['data' => ['admin' => ['delegation_ceiling']]]);
});

View File

@@ -0,0 +1,280 @@
<?php
use App\Models\AdminUser;
use App\Models\AgentNode;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function (): void {
$this->artisan('lottery:admin-auth-sync')->assertExitCode(0);
});
function agentRootNodeId(int $siteId): int
{
return (int) DB::table('agent_nodes')
->where('admin_site_id', $siteId)
->where('depth', 0)
->value('id');
}
function grantAgentOperatorRole(AdminUser $admin, AgentNode $agent, bool $manage = true): void
{
$now = now();
$roleId = DB::table('admin_roles')->insertGetId([
'slug' => 'agent_ops_'.$admin->id,
'code' => 'agent_ops_'.$admin->id,
'name' => 'Agent Ops',
'description' => null,
'status' => 1,
'is_system' => false,
'sort_order' => 0,
'created_at' => $now,
'updated_at' => $now,
]);
$codes = $manage
? ['agent.node.view', 'agent.node.manage']
: ['agent.node.view'];
$actionIds = DB::table('admin_menu_actions')
->whereIn('permission_code', $codes)
->pluck('id');
foreach ($actionIds as $actionId) {
DB::table('admin_role_menu_actions')->insert([
'role_id' => $roleId,
'menu_action_id' => (int) $actionId,
]);
}
DB::table('admin_user_site_roles')->insert([
'admin_user_id' => $admin->id,
'site_id' => (int) $agent->admin_site_id,
'role_id' => $roleId,
'granted_at' => $now,
]);
DB::table('admin_user_agents')->insert([
'admin_user_id' => $admin->id,
'agent_node_id' => (int) $agent->id,
'is_primary' => true,
'granted_at' => $now,
]);
}
test('each admin site has exactly one root agent node after migration', function (): void {
$siteIds = DB::table('admin_sites')->pluck('id');
foreach ($siteIds as $siteId) {
expect(
DB::table('agent_nodes')->where('admin_site_id', (int) $siteId)->where('depth', 0)->count()
)->toBe(1);
}
});
test('super admin can load full agent tree', function (): void {
$siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
$admin = AdminUser::query()->create([
'username' => 'agent_super',
'name' => 'Super',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($admin);
$token = $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;
$this->withHeader('Authorization', 'Bearer '.$token)
->getJson('/api/v1/admin/agent-nodes/tree?admin_site_id='.$siteId)
->assertOk()
->assertJsonPath('code', 0)
->assertJsonStructure(['data' => ['admin_site_id', 'tree']]);
});
test('agent operator only sees own subtree', function (): void {
$siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
$rootId = agentRootNodeId($siteId);
$service = app(\App\Services\Agent\AgentNodeService::class);
$super = AdminUser::query()->create([
'username' => 'bootstrap',
'name' => 'Bootstrap',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($super);
$nodeA = $service->createChild($super, [
'parent_id' => $rootId,
'code' => 'branch-a',
'name' => 'Branch A',
'status' => 1,
]);
$service->createChild($super, [
'parent_id' => $rootId,
'code' => 'branch-b',
'name' => 'Branch B',
'status' => 1,
]);
$operator = AdminUser::query()->create([
'username' => 'agent_a_ops',
'name' => 'A Ops',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantAgentOperatorRole($operator, $nodeA);
$token = $operator->createToken('test', ['*'], now()->addDay())->plainTextToken;
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->getJson('/api/v1/admin/agent-nodes/tree');
$response->assertOk();
$tree = $response->json('data.tree');
expect($tree)->toBeArray()->and(count($tree))->toBe(1);
expect($tree[0]['code'])->toBe('branch-a');
expect(collect($tree)->pluck('code'))->not->toContain('branch-b');
});
test('agent operator can create child under own node but not under sibling', function (): void {
$siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
$rootId = agentRootNodeId($siteId);
$service = app(\App\Services\Agent\AgentNodeService::class);
$super = AdminUser::query()->create([
'username' => 'bootstrap2',
'name' => 'Bootstrap',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($super);
$nodeA = $service->createChild($super, [
'parent_id' => $rootId,
'code' => 'branch-a2',
'name' => 'Branch A',
]);
$nodeB = $service->createChild($super, [
'parent_id' => $rootId,
'code' => 'branch-b2',
'name' => 'Branch B',
]);
$operator = AdminUser::query()->create([
'username' => 'agent_a2_ops',
'name' => 'A Ops',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantAgentOperatorRole($operator, $nodeA);
$token = $operator->createToken('test', ['*'], now()->addDay())->plainTextToken;
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/v1/admin/agent-nodes', [
'parent_id' => $nodeA->id,
'code' => 'a-child',
'name' => 'A Child',
])
->assertOk()
->assertJsonPath('data.code', 'a-child');
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/v1/admin/agent-nodes', [
'parent_id' => $nodeB->id,
'code' => 'hack-child',
'name' => 'Hack',
])
->assertForbidden();
});
test('auth me returns agent context for bound operator', function (): void {
$siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
$rootId = agentRootNodeId($siteId);
$service = app(\App\Services\Agent\AgentNodeService::class);
$super = AdminUser::query()->create([
'username' => 'bootstrap3',
'name' => 'Bootstrap',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($super);
$node = $service->createChild($super, [
'parent_id' => $rootId,
'code' => 'me-branch',
'name' => 'Me Branch',
]);
$operator = AdminUser::query()->create([
'username' => 'me_agent_ops',
'name' => 'Ops',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantAgentOperatorRole($operator, $node);
$token = $operator->createToken('test', ['*'], now()->addDay())->plainTextToken;
$this->withHeader('Authorization', 'Bearer '.$token)
->getJson('/api/v1/admin/auth/me')
->assertOk()
->assertJsonPath('data.admin.agent.code', 'me-branch')
->assertJsonPath('data.admin.is_super_admin', false);
});
test('agent node deletion requires leaf node without bindings', function (): void {
$siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
$rootId = agentRootNodeId($siteId);
$service = app(\App\Services\Agent\AgentNodeService::class);
$super = AdminUser::query()->create([
'username' => 'delete_agent_super',
'name' => 'Delete Super',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($super);
$token = $super->createToken('test', ['*'], now()->addDay())->plainTextToken;
$nodeWithChild = $service->createChild($super, [
'parent_id' => $rootId,
'code' => 'delete-parent',
'name' => 'Delete Parent',
]);
$service->createChild($super, [
'parent_id' => $nodeWithChild->id,
'code' => 'delete-child',
'name' => 'Delete Child',
]);
$this->withHeader('Authorization', 'Bearer '.$token)
->deleteJson('/api/v1/admin/agent-nodes/'.$rootId)
->assertStatus(422)
->assertJsonPath('msg', __('admin.agent_root_delete_denied'));
$this->withHeader('Authorization', 'Bearer '.$token)
->deleteJson('/api/v1/admin/agent-nodes/'.$nodeWithChild->id)
->assertStatus(422)
->assertJsonPath('msg', __('admin.agent_node_has_children_cannot_delete'));
$leaf = $service->createChild($super, [
'parent_id' => $rootId,
'code' => 'delete-leaf',
'name' => 'Delete Leaf',
]);
$this->withHeader('Authorization', 'Bearer '.$token)
->deleteJson('/api/v1/admin/agent-nodes/'.$leaf->id)
->assertOk()
->assertJsonPath('code', 0);
expect(AgentNode::query()->find($leaf->id))->toBeNull();
});

View File

@@ -0,0 +1,205 @@
<?php
use App\Models\AdminUser;
use App\Models\AgentNode;
use App\Models\Player;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function (): void {
$this->artisan('lottery:admin-auth-sync')->assertExitCode(0);
});
function grantAgentRoleManager(AdminUser $admin, AgentNode $agent): void
{
$now = now();
$roleId = DB::table('admin_roles')->insertGetId([
'slug' => 'agent_mgr_'.$admin->id,
'code' => 'agent_mgr_'.$admin->id,
'name' => 'Agent Manager',
'scope_type' => 'system',
'status' => 1,
'is_system' => false,
'sort_order' => 0,
'created_at' => $now,
'updated_at' => $now,
]);
$codes = ['agent.node.view', 'agent.node.manage', 'service.players.view'];
$actionIds = DB::table('admin_menu_actions')->whereIn('permission_code', $codes)->pluck('id');
foreach ($actionIds as $actionId) {
DB::table('admin_role_menu_actions')->insert([
'role_id' => $roleId,
'menu_action_id' => (int) $actionId,
]);
}
$siteId = (int) $agent->admin_site_id;
DB::table('admin_user_site_roles')->insert([
'admin_user_id' => $admin->id,
'site_id' => $siteId,
'role_id' => $roleId,
'granted_at' => $now,
]);
DB::table('admin_user_agents')->insert([
'admin_user_id' => $admin->id,
'agent_node_id' => $agent->id,
'is_primary' => true,
'granted_at' => $now,
]);
DB::table('admin_user_agent_roles')->insert([
'admin_user_id' => $admin->id,
'agent_node_id' => $agent->id,
'role_id' => $roleId,
'granted_at' => $now,
]);
}
test('agent operator can create role with subset of own permissions', function (): void {
$siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
$rootId = (int) DB::table('agent_nodes')->where('admin_site_id', $siteId)->where('depth', 0)->value('id');
$service = app(\App\Services\Agent\AgentNodeService::class);
$super = AdminUser::query()->create([
'username' => 'super_role',
'name' => 'Super',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($super);
$branch = $service->createChild($super, [
'parent_id' => $rootId,
'code' => 'role-branch',
'name' => 'Role Branch',
]);
$operator = AdminUser::query()->create([
'username' => 'role_ops',
'name' => 'Ops',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantAgentRoleManager($operator, $branch);
$token = $operator->createToken('test', ['*'], now()->addDay())->plainTextToken;
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/v1/admin/agent-nodes/'.$branch->id.'/roles', [
'slug' => 'branch_cs',
'name' => 'Branch CS',
'permission_slugs' => ['prd.agent.view', 'prd.agent.role.view'],
])
->assertOk()
->assertJsonPath('data.scope_type', 'agent')
->assertJsonPath('data.owner_agent_id', $branch->id);
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/v1/admin/agent-nodes/'.$branch->id.'/roles', [
'slug' => 'branch_hack',
'name' => 'Hack',
'permission_slugs' => ['prd.dashboard.view'],
])
->assertStatus(422);
});
test('agent scoped roles are excluded from global admin roles index', function (): void {
$siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
$rootId = (int) DB::table('agent_nodes')->where('admin_site_id', $siteId)->where('depth', 0)->value('id');
$service = app(\App\Services\Agent\AgentNodeService::class);
$super = AdminUser::query()->create([
'username' => 'super_idx',
'name' => 'Super',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($super);
$token = $super->createToken('test', ['*'], now()->addDay())->plainTextToken;
$branch = $service->createChild($super, [
'parent_id' => $rootId,
'code' => 'idx-branch',
'name' => 'Idx Branch',
]);
DB::table('admin_roles')->insert([
'slug' => 'idx_agent_role',
'code' => 'idx_agent_role',
'name' => 'Idx Agent Role',
'scope_type' => 'agent',
'owner_agent_id' => $branch->id,
'status' => 1,
'is_system' => false,
'sort_order' => 0,
'created_at' => now(),
'updated_at' => now(),
]);
$slugs = collect($this->withHeader('Authorization', 'Bearer '.$token)
->getJson('/api/v1/admin/admin-roles')
->json('data.items'))
->pluck('slug');
expect($slugs)->not->toContain('idx_agent_role');
});
test('players list respects agent subtree when agent_node_id is set', function (): void {
$siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
$siteCode = (string) DB::table('admin_sites')->where('id', $siteId)->value('code');
$rootId = (int) DB::table('agent_nodes')->where('admin_site_id', $siteId)->where('depth', 0)->value('id');
$service = app(\App\Services\Agent\AgentNodeService::class);
$super = AdminUser::query()->create([
'username' => 'super_player',
'name' => 'Super',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($super);
$branchA = $service->createChild($super, ['parent_id' => $rootId, 'code' => 'pa', 'name' => 'A']);
$branchB = $service->createChild($super, ['parent_id' => $rootId, 'code' => 'pb', 'name' => 'B']);
Player::query()->create([
'site_code' => $siteCode,
'agent_node_id' => $branchA->id,
'site_player_id' => 'p-a',
'username' => 'pa',
'nickname' => 'PA',
'default_currency' => 'NPR',
'status' => 0,
]);
Player::query()->create([
'site_code' => $siteCode,
'agent_node_id' => $branchB->id,
'site_player_id' => 'p-b',
'username' => 'pb',
'nickname' => 'PB',
'default_currency' => 'NPR',
'status' => 0,
]);
$operator = AdminUser::query()->create([
'username' => 'player_ops',
'name' => 'Ops',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantAgentRoleManager($operator, $branchA);
$token = $operator->createToken('test', ['*'], now()->addDay())->plainTextToken;
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->getJson('/api/v1/admin/players?site_code='.$siteCode);
$response->assertOk();
$usernames = collect($response->json('data.items'))->pluck('username');
expect($usernames)->toContain('pa')->not->toContain('pb');
});

View File

@@ -91,7 +91,10 @@ test('admin login returns bearer token when captcha passes validation', function
->assertJsonPath('data.admin.nickname', '测试昵称')
->assertJsonPath('data.admin.navigation.0.segment', 'dashboard')
->assertJsonPath('data.admin.navigation.0.href', '/admin')
->assertJsonPath('data.admin.navigation.1.segment', 'draws')
->assertJsonPath('data.admin.navigation.0.nav_group', 'overview')
->assertJsonPath('data.admin.navigation.1.segment', 'agents')
->assertJsonPath('data.admin.navigation.1.nav_group', 'agent')
->assertJsonPath('data.admin.navigation.2.segment', 'draws')
->assertJsonStructure(['data' => ['token', 'token_type', 'admin' => ['id', 'username', 'nickname', 'email', 'permissions', 'navigation']]]);
$token = $resp->json('data.token');
@@ -103,6 +106,67 @@ test('admin login returns bearer token when captcha passes validation', function
->assertJsonPath('data.scope', 'admin');
});
test('agent operator auth me omits platform-only navigation', function (): void {
$this->artisan('lottery:admin-auth-sync')->assertExitCode(0);
$siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
$rootId = (int) DB::table('agent_nodes')->where('admin_site_id', $siteId)->where('depth', 0)->value('id');
$admin = AdminUser::query()->create([
'username' => 'agent_nav_ops',
'name' => 'Agent Nav',
'email' => null,
'password' => 'secret-strong',
'status' => 0,
]);
$now = now();
$roleId = DB::table('admin_roles')->insertGetId([
'slug' => 'agent_nav_ops_role',
'code' => 'agent_nav_ops_role',
'name' => 'Agent Nav Ops',
'description' => null,
'status' => 1,
'is_system' => false,
'sort_order' => 0,
'created_at' => $now,
'updated_at' => $now,
]);
$codes = ['agent.node.view', 'service.report.view'];
$actionIds = DB::table('admin_menu_actions')->whereIn('permission_code', $codes)->pluck('id');
foreach ($actionIds as $actionId) {
DB::table('admin_role_menu_actions')->insert([
'role_id' => $roleId,
'menu_action_id' => (int) $actionId,
]);
}
DB::table('admin_user_site_roles')->insert([
'admin_user_id' => $admin->id,
'site_id' => $siteId,
'role_id' => $roleId,
'granted_at' => $now,
]);
DB::table('admin_user_agents')->insert([
'admin_user_id' => $admin->id,
'agent_node_id' => $rootId,
'is_primary' => true,
'granted_at' => $now,
]);
$token = $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;
$segments = $this->withHeader('Authorization', 'Bearer '.$token)
->getJson('/api/v1/admin/auth/me')
->assertOk()
->json('data.admin.navigation');
$keys = array_column($segments, 'segment');
expect($keys)->toContain('agents', 'reports')
->and($keys)->not->toContain('admin_users', 'admin_roles', 'settings', 'integration', 'rules_plays');
});
test('admin captcha exposes key and image base64', function () {
$resp = $this->getJson('/api/v1/admin/auth/captcha');

View File

@@ -0,0 +1,149 @@
<?php
use App\Models\AdminUser;
use App\Models\Player;
use App\Models\TransferOrder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function (): void {
$this->artisan('lottery:admin-auth-sync')->assertExitCode(0);
});
test('orphan players can be backfilled to site root agent', function (): void {
$siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
$siteCode = (string) DB::table('admin_sites')->where('id', $siteId)->value('code');
$rootId = (int) DB::table('agent_nodes')->where('admin_site_id', $siteId)->where('depth', 0)->value('id');
$playerId = Player::query()->create([
'site_code' => $siteCode,
'site_player_id' => 'orphan-1',
'username' => 'orphan',
'nickname' => null,
'default_currency' => 'NPR',
'status' => 0,
'agent_node_id' => null,
])->id;
DB::table('players')
->where('site_code', $siteCode)
->whereNull('agent_node_id')
->update(['agent_node_id' => $rootId]);
expect((int) Player::query()->find($playerId)?->agent_node_id)->toBe($rootId);
});
test('transfer list excludes players outside agent subtree', function (): void {
$siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
$siteCode = (string) DB::table('admin_sites')->where('id', $siteId)->value('code');
$rootId = (int) DB::table('agent_nodes')->where('admin_site_id', $siteId)->where('depth', 0)->value('id');
$service = app(\App\Services\Agent\AgentNodeService::class);
$super = AdminUser::query()->create([
'username' => 'bind_super',
'name' => 'Super',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($super);
$branch = $service->createChild($super, ['parent_id' => $rootId, 'code' => 'bind-a', 'name' => 'A']);
$other = $service->createChild($super, ['parent_id' => $rootId, 'code' => 'bind-b', 'name' => 'B']);
$inPlayer = Player::query()->create([
'site_code' => $siteCode,
'agent_node_id' => $branch->id,
'site_player_id' => 'bind-in',
'username' => 'bind_in',
'nickname' => null,
'default_currency' => 'NPR',
'status' => 0,
]);
$outPlayer = Player::query()->create([
'site_code' => $siteCode,
'agent_node_id' => $other->id,
'site_player_id' => 'bind-out',
'username' => 'bind_out',
'nickname' => null,
'default_currency' => 'NPR',
'status' => 0,
]);
foreach ([$inPlayer, $outPlayer] as $index => $player) {
TransferOrder::query()->create([
'transfer_no' => 'TR-BIND-'.$index,
'player_id' => $player->id,
'direction' => 'in',
'currency_code' => 'NPR',
'amount' => 100,
'status' => 'completed',
'idempotent_key' => 'idem-bind-'.$index,
'external_ref_no' => 'ext-'.$index,
'fail_reason' => null,
'created_at' => now(),
'updated_at' => now(),
'finished_at' => now(),
]);
}
$operator = AdminUser::query()->create([
'username' => 'bind_ops',
'name' => 'Ops',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantAgentOpsForBinding($operator, $branch);
$token = $operator->createToken('test', ['*'], now()->addDay())->plainTextToken;
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->getJson('/api/v1/admin/wallet/transfer-orders?site_code='.$siteCode);
$response->assertOk();
$playerIds = collect($response->json('data.items'))->pluck('player_id')->map(static fn ($id): int => (int) $id);
expect($playerIds)->toContain($inPlayer->id)->not->toContain($outPlayer->id);
});
function grantAgentOpsForBinding(AdminUser $admin, \App\Models\AgentNode $agent): void
{
$now = now();
$roleId = DB::table('admin_roles')->insertGetId([
'slug' => 'bind_ops_'.$admin->id,
'code' => 'bind_ops_'.$admin->id,
'name' => 'Bind Ops',
'scope_type' => 'system',
'status' => 1,
'is_system' => false,
'sort_order' => 0,
'created_at' => $now,
'updated_at' => $now,
]);
foreach (['agent.node.view', 'service.wallet.view', 'service.reconcile.view'] as $code) {
$actionId = DB::table('admin_menu_actions')->where('permission_code', $code)->value('id');
if ($actionId) {
DB::table('admin_role_menu_actions')->insert([
'role_id' => $roleId,
'menu_action_id' => (int) $actionId,
]);
}
}
DB::table('admin_user_site_roles')->insert([
'admin_user_id' => $admin->id,
'site_id' => (int) $agent->admin_site_id,
'role_id' => $roleId,
'granted_at' => $now,
]);
DB::table('admin_user_agents')->insert([
'admin_user_id' => $admin->id,
'agent_node_id' => (int) $agent->id,
'is_primary' => true,
'granted_at' => $now,
]);
}

View File

@@ -0,0 +1,184 @@
<?php
use App\Models\AdminUser;
use App\Models\AgentNode;
use App\Models\Draw;
use App\Models\Player;
use App\Models\TicketItem;
use App\Models\TicketOrder;
use App\Lottery\DrawStatus;
use App\Services\Admin\AdminReportQueryService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function (): void {
$this->artisan('lottery:admin-auth-sync')->assertExitCode(0);
});
test('player win loss report excludes players outside agent subtree', function (): void {
$siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
$siteCode = (string) DB::table('admin_sites')->where('id', $siteId)->value('code');
$rootId = (int) DB::table('agent_nodes')->where('admin_site_id', $siteId)->where('depth', 0)->value('id');
$service = app(\App\Services\Agent\AgentNodeService::class);
$super = AdminUser::query()->create([
'username' => 'rpt_super',
'name' => 'Super',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($super);
$branch = $service->createChild($super, [
'parent_id' => $rootId,
'code' => 'rpt-branch',
'name' => 'Report Branch',
]);
$otherBranch = $service->createChild($super, [
'parent_id' => $rootId,
'code' => 'rpt-other',
'name' => 'Other Branch',
]);
$today = now()->toDateString();
$draw = Draw::query()->create([
'draw_no' => 'RPT-'.now()->format('YmdHis'),
'business_date' => $today,
'sequence_no' => 901,
'status' => DrawStatus::Open->value,
'start_time' => now()->subMinute(),
'close_time' => now()->addHour(),
'draw_time' => now()->addHours(2),
'cooling_end_time' => null,
'result_source' => null,
'current_result_version' => 0,
'settle_version' => 0,
'is_reopened' => false,
]);
$inScope = Player::query()->create([
'site_code' => $siteCode,
'site_player_id' => 'rpt-in',
'username' => 'rpt_in',
'nickname' => null,
'default_currency' => 'NPR',
'status' => 0,
'agent_node_id' => $branch->id,
]);
$outScope = Player::query()->create([
'site_code' => $siteCode,
'site_player_id' => 'rpt-out',
'username' => 'rpt_out',
'nickname' => null,
'default_currency' => 'NPR',
'status' => 0,
'agent_node_id' => $otherBranch->id,
]);
foreach ([$inScope, $outScope] as $index => $player) {
$order = TicketOrder::query()->create([
'order_no' => 'RPT-ORD-'.$index,
'player_id' => $player->id,
'draw_id' => $draw->id,
'currency_code' => 'NPR',
'total_bet_amount' => 1000,
'total_rebate_amount' => 0,
'total_actual_deduct' => 1000,
'total_estimated_payout' => 0,
'status' => 'placed',
'submit_source' => 'h5',
'client_trace_id' => 'rpt-trace-'.$index,
'created_at' => now(),
'updated_at' => now(),
]);
TicketItem::query()->create([
'ticket_no' => 'RPT-TK-'.$index,
'order_id' => $order->id,
'player_id' => $player->id,
'draw_id' => $draw->id,
'original_number' => '1234',
'normalized_number' => '1234',
'play_code' => 'big',
'dimension' => 4,
'digit_slot' => null,
'bet_mode' => 'single',
'unit_bet_amount' => 1000,
'total_bet_amount' => 1000,
'rebate_rate_snapshot' => '0.0000',
'commission_rate_snapshot' => '0.0000',
'actual_deduct_amount' => 1000,
'win_amount' => 0,
'jackpot_win_amount' => 0,
'status' => 'placed',
]);
}
$operator = AdminUser::query()->create([
'username' => 'rpt_ops',
'name' => 'Ops',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantReportAgentManager($operator, $branch);
$query = app(AdminReportQueryService::class);
$scoped = $query->playerWinLossPaginated(null, $today, $today, 1, 20, $operator);
$all = $query->playerWinLossPaginated(null, $today, $today, 1, 20, null);
$scopedUsernames = collect($scoped->items())->pluck('username')->all();
$allUsernames = collect($all->items())->pluck('username')->all();
expect($scopedUsernames)->toContain('rpt_in')->not->toContain('rpt_out')
->and($allUsernames)->toContain('rpt_in', 'rpt_out');
});
function grantReportAgentManager(AdminUser $admin, AgentNode $agent): void
{
$now = now();
$roleId = DB::table('admin_roles')->insertGetId([
'slug' => 'rpt_mgr_'.$admin->id,
'code' => 'rpt_mgr_'.$admin->id,
'name' => 'Report Manager',
'scope_type' => 'system',
'status' => 1,
'is_system' => false,
'sort_order' => 0,
'created_at' => $now,
'updated_at' => $now,
]);
$codes = ['agent.node.view', 'agent.node.manage', 'service.players.view', 'service.report.view'];
$actionIds = DB::table('admin_menu_actions')->whereIn('permission_code', $codes)->pluck('id');
foreach ($actionIds as $actionId) {
DB::table('admin_role_menu_actions')->insert([
'role_id' => $roleId,
'menu_action_id' => (int) $actionId,
]);
}
$siteId = (int) $agent->admin_site_id;
DB::table('admin_user_site_roles')->insert([
'admin_user_id' => $admin->id,
'site_id' => $siteId,
'role_id' => $roleId,
'granted_at' => $now,
]);
DB::table('admin_user_agents')->insert([
'admin_user_id' => $admin->id,
'agent_node_id' => (int) $agent->id,
'is_primary' => true,
'granted_at' => $now,
]);
DB::table('admin_user_agent_roles')->insert([
'admin_user_id' => $admin->id,
'agent_node_id' => (int) $agent->id,
'role_id' => $roleId,
'granted_at' => $now,
]);
}

View File

@@ -0,0 +1,103 @@
<?php
use App\Models\AdminRole;
use App\Models\AdminUser;
use App\Models\LotterySetting;
use App\Services\LotterySettings;
use Illuminate\Support\Facades\Hash;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
function settingsAdminToken(): string
{
$admin = AdminUser::query()->create([
'username' => 'settings_editor',
'name' => 'Settings Editor',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
$role = AdminRole::query()->create([
'slug' => 'settings_role',
'name' => 'Settings Role',
]);
$role->syncLegacyPermissionSlugs(['prd.payout.manage']);
$admin->roles()->sync([
(int) $role->id => [
'site_id' => AdminUser::defaultAdminSiteId(),
'granted_at' => now(),
],
]);
return $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;
}
test('admin can batch update settings in one request', function (): void {
LotterySettings::put('draw.interval_minutes', 5, 'draw');
LotterySettings::put('draw.cooldown_minutes', 15, 'draw');
$token = settingsAdminToken();
$this->withHeader('Authorization', 'Bearer '.$token)
->putJson('/api/v1/admin/settings/batch', [
'items' => [
['key' => 'draw.interval_minutes', 'value' => 10],
['key' => 'draw.cooldown_minutes', 'value' => 20],
],
])
->assertOk()
->assertJsonPath('data.items.0.key', 'draw.cooldown_minutes');
expect(LotterySetting::query()->where('setting_key', 'draw.interval_minutes')->value('value_json'))->toBe(10)
->and(LotterySetting::query()->where('setting_key', 'draw.cooldown_minutes')->value('value_json'))->toBe(20);
});
test('admin settings batch update rejects empty items', function (): void {
$token = settingsAdminToken();
$this->withHeader('Authorization', 'Bearer '.$token)
->putJson('/api/v1/admin/settings/batch', ['items' => []])
->assertUnprocessable();
});
test('admin can batch update settings with false and empty string values', function (): void {
LotterySettings::put('settlement.auto_run_on_tick', true, 'settlement');
LotterySettings::put('frontend.play_rules_html_zh', '<div>old</div>', 'frontend');
$token = settingsAdminToken();
$this->withHeader('Authorization', 'Bearer '.$token)
->putJson('/api/v1/admin/settings/batch', [
'items' => [
['key' => 'settlement.auto_run_on_tick', 'value' => false],
['key' => 'frontend.play_rules_html_zh', 'value' => ''],
],
])
->assertOk()
->assertJsonPath('data.items.0.key', 'frontend.play_rules_html_zh')
->assertJsonPath('data.items.0.value', '')
->assertJsonPath('data.items.1.key', 'settlement.auto_run_on_tick')
->assertJsonPath('data.items.1.value', false);
expect(LotterySetting::query()->where('setting_key', 'settlement.auto_run_on_tick')->value('value_json'))->toBeFalse()
->and(LotterySetting::query()->where('setting_key', 'frontend.play_rules_html_zh')->value('value_json'))->toBe('');
});
test('admin can update single setting with false value', function (): void {
LotterySettings::put('settlement.apply_rebate_to_payout', true, 'settlement');
$token = settingsAdminToken();
$this->withHeader('Authorization', 'Bearer '.$token)
->putJson('/api/v1/admin/settings/settlement.apply_rebate_to_payout', [
'value' => false,
])
->assertOk()
->assertJsonPath('data.key', 'settlement.apply_rebate_to_payout')
->assertJsonPath('data.value', false);
expect(LotterySetting::query()->where('setting_key', 'settlement.apply_rebate_to_payout')->value('value_json'))->toBeFalse();
});

View File

@@ -148,30 +148,32 @@ test('permission catalog groups permissions by admin navigation order', function
expect(array_column($groups, 'key'))->toBe([
'dashboard',
'agents',
'draws',
'tickets',
'players',
'settlement',
'wallet',
'reconcile',
'reports',
'rules_plays',
'rules_odds',
'jackpot',
'risk_cap',
'wallet',
'settlement',
'reconcile',
'reports',
'currencies',
'integration',
'currencies',
'admin_users',
'admin_roles',
'risk',
'audit',
'settings',
'risk',
]);
expect($groups[1]['key'])->toBe('draws');
expect($groups[14]['label'])->toBe('管理列表');
expect(array_column($groups[14]['permissions'], 'slug'))->toBe(['prd.admin_user.manage']);
expect($groups[15]['label'])->toBe('角色管理');
expect(array_column($groups[15]['permissions'], 'slug'))->toBe(['prd.admin_role.manage']);
expect($groups[1]['key'])->toBe('agents');
expect($groups[2]['key'])->toBe('draws');
expect($groups[15]['label'])->toBe('管理列表');
expect(array_column($groups[15]['permissions'], 'slug'))->toBe(['prd.admin_user.manage']);
expect($groups[16]['label'])->toBe('角色管理');
expect(array_column($groups[16]['permissions'], 'slug'))->toBe(['prd.admin_role.manage']);
$groupsByKey = collect($groups)->keyBy('key');
expect(array_column($groupsByKey['tickets']['permissions'], 'slug'))->toBe([

View File

@@ -71,3 +71,16 @@ function grantSuperAdminRole(AdminUser $admin): void
['granted_at' => $now],
);
}
/** 为后台测试账号挂上代理节点(需已存在 agent_nodes / admin_user_agents 表)。 */
function bindAdminUserToAgent(AdminUser $admin, int $agentNodeId): void
{
DB::table('admin_user_agents')->updateOrInsert(
['admin_user_id' => $admin->id],
[
'agent_node_id' => $agentNodeId,
'is_primary' => true,
'granted_at' => now(),
],
);
}