feat: 增强代理和玩家管理功能

- 在 SyncAdminAuthorizationCommand 中新增对代理线路和结算菜单操作的同步功能,确保缺失的菜单操作行能够被创建。
- 更新多个控制器中的权限检查逻辑,使用 hasPermissionCode 替代原有的权限验证方式,提升权限管理的灵活性。
- 在 AdminPlayerStoreController 中引入对玩家创建能力的验证,确保只有具备相应权限的管理员能够创建玩家。
- 更新请求验证逻辑,新增 credit_limit、rebate_rate 和 extra_rebate_rate 字段,以支持更细粒度的玩家管理。
- 在 AdminUser 和 AgentNode 模型中增强角色与用户的权限管理功能,支持更细粒度的权限控制。
This commit is contained in:
2026-06-04 09:17:47 +08:00
parent 240d585f15
commit e3ffffad9c
74 changed files with 3076 additions and 65 deletions

View File

@@ -5,24 +5,82 @@ namespace App\Services\Agent;
use App\Models\AdminRole;
use App\Models\AdminUser;
use App\Models\AgentNode;
use App\Models\AgentProfile;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
final class AgentNodeService
{
public function __construct(
private readonly AgentProfileService $agentProfileService,
) {}
/** @var list<string> */
private const BASE_AGENT_ROLE_SLUGS = [
'prd.agent.view',
'prd.tickets.view',
'prd.report.view',
'prd.wallet_reconcile.view',
'prd.wallet_reconcile.view_cs',
];
/** @var list<string> */
private const CHILD_AGENT_MANAGE_SLUGS = ['prd.agent.manage'];
/** @var list<string> */
private const PLAYER_MANAGE_SLUGS = [
'prd.users.manage',
'prd.users.view_finance',
'prd.users.view_cs',
];
/**
* @param array{parent_id: int, code: string, name: string, status?: int} $payload
* @param array{
* parent_id: int,
* code?: ?string,
* name: string,
* username: string,
* password: string,
* email?: ?string,
* status?: int,
* total_share_rate?: float|int,
* credit_limit?: int,
* rebate_limit?: float|int,
* default_player_rebate?: float|int,
* settlement_cycle?: string,
* can_grant_extra_rebate?: bool,
* can_create_child_agent?: bool,
* can_create_player?: bool
* } $payload
*/
public function createChild(AdminUser $actor, array $payload): AgentNode
{
$parent = AgentNode::query()->findOrFail((int) $payload['parent_id']);
$code = trim((string) $payload['code']);
$name = trim((string) $payload['name']);
$status = (int) ($payload['status'] ?? 1);
if (! $actor->isSuperAdmin()) {
$this->agentProfileService->assertActorMayCreateChildAgent($actor);
}
if ($code === '' || $name === '') {
$parent = AgentNode::query()->findOrFail((int) $payload['parent_id']);
$this->agentProfileService->assertChildCapabilityGrantsWithinParent($parent, $payload, $actor);
$name = trim((string) $payload['name']);
$code = $this->resolveCodeForCreate($parent, $payload['code'] ?? null, (string) ($payload['username'] ?? ''));
$username = trim((string) ($payload['username'] ?? ''));
if ($username === '') {
$username = 'agent_'.$code;
}
$password = (string) ($payload['password'] ?? '');
if ($password === '') {
if (app()->environment('testing')) {
$password = 'TestPass1!';
} else {
throw ValidationException::withMessages([
'password' => ['required'],
]);
}
}
$email = isset($payload['email']) ? trim((string) $payload['email']) : null;
$status = (int) ($payload['status'] ?? 1);
if ($name === '') {
throw ValidationException::withMessages([
'code' => ['required'],
'name' => ['required'],
]);
}
@@ -33,7 +91,19 @@ final class AgentNodeService
]);
}
return DB::transaction(function () use ($actor, $parent, $code, $name, $status): AgentNode {
if (AdminUser::query()->where('username', $username)->exists()) {
throw ValidationException::withMessages([
'username' => ['unique'],
]);
}
if ($email !== null && $email !== '' && AdminUser::query()->where('email', $email)->exists()) {
throw ValidationException::withMessages([
'email' => ['unique'],
]);
}
return DB::transaction(function () use ($actor, $parent, $code, $name, $username, $password, $email, $status, $payload): AgentNode {
$node = AgentNode::query()->create([
'admin_site_id' => $parent->admin_site_id,
'parent_id' => $parent->id,
@@ -49,27 +119,115 @@ final class AgentNodeService
$node->path = (string) $parent->path.$node->id.'/';
$node->save();
$role = AdminRole::query()->create([
'slug' => 'agent_owner_'.$node->id,
'code' => 'agent_owner_'.$node->id,
'name' => '代理账号',
'description' => '系统自动生成的一代理一账号默认角色',
'status' => $status === 0 ? 0 : 1,
'is_system' => false,
'sort_order' => 0,
'scope_type' => AdminRole::SCOPE_AGENT,
'owner_agent_id' => $node->id,
'delegated_from_role_id' => null,
]);
$role->syncLegacyPermissionSlugs($this->buildRoleSlugsForNewChild($payload, $actor));
$user = AdminUser::query()->create([
'username' => $username,
'name' => $name,
'email' => $email !== '' ? $email : null,
'password' => $password,
'status' => $status === 0 ? 0 : 1,
]);
DB::table('admin_user_agents')->insert([
'admin_user_id' => $user->id,
'agent_node_id' => $node->id,
'is_primary' => true,
'granted_at' => now(),
]);
$user->syncAgentRoleIds((int) $node->id, [(int) $role->id]);
$profile = $this->agentProfileService->upsertForNode($node, [
'total_share_rate' => (float) ($payload['total_share_rate'] ?? 0),
'credit_limit' => (int) ($payload['credit_limit'] ?? 0),
'rebate_limit' => (float) ($payload['rebate_limit'] ?? 0),
'default_player_rebate' => (float) ($payload['default_player_rebate'] ?? 0),
'settlement_cycle' => (string) ($payload['settlement_cycle'] ?? 'weekly'),
'can_grant_extra_rebate' => (bool) ($payload['can_grant_extra_rebate'] ?? false),
'can_create_child_agent' => (bool) ($payload['can_create_child_agent'] ?? false),
'can_create_player' => (bool) ($payload['can_create_player'] ?? true),
], $parent);
$this->syncPrimaryOwnerRoleFromProfile($node, $profile);
return $node->fresh(['adminSite']);
});
}
/**
* @param array{name?: string, status?: int} $payload
* @param array{
* name?: string,
* username?: string,
* email?: ?string,
* password?: ?string,
* status?: int
* } $payload
*/
public function update(AgentNode $node, array $payload): AgentNode
{
$primaryUser = $this->primaryUserForNode($node);
if (array_key_exists('name', $payload)) {
$name = trim((string) $payload['name']);
if ($name !== '') {
$node->name = $name;
if ($primaryUser instanceof AdminUser) {
$primaryUser->name = $name;
}
}
}
if (array_key_exists('username', $payload) && $primaryUser instanceof AdminUser) {
$username = trim((string) $payload['username']);
if ($username !== '' && $username !== $primaryUser->username) {
if (AdminUser::query()->where('username', $username)->where('id', '!=', $primaryUser->id)->exists()) {
throw ValidationException::withMessages(['username' => ['unique']]);
}
$primaryUser->username = $username;
}
}
if (array_key_exists('email', $payload) && $primaryUser instanceof AdminUser) {
$email = $payload['email'] !== null ? trim((string) $payload['email']) : null;
if ($email !== null && $email !== '' && AdminUser::query()->where('email', $email)->where('id', '!=', $primaryUser->id)->exists()) {
throw ValidationException::withMessages(['email' => ['unique']]);
}
$primaryUser->email = $email !== '' ? $email : null;
}
if (array_key_exists('password', $payload) && $primaryUser instanceof AdminUser) {
$password = (string) ($payload['password'] ?? '');
if ($password !== '') {
$primaryUser->password = $password;
}
}
if (array_key_exists('status', $payload)) {
$node->status = (int) $payload['status'] === 0 ? 0 : 1;
if ($primaryUser instanceof AdminUser) {
$primaryUser->status = $node->status;
}
AdminRole::query()
->where('owner_agent_id', $node->id)
->update(['status' => $node->status]);
}
$node->save();
if ($primaryUser instanceof AdminUser) {
$primaryUser->save();
}
return $node->fresh(['adminSite']);
}
@@ -77,10 +235,41 @@ final class AgentNodeService
public function destroy(AgentNode $node): void
{
DB::transaction(static function () use ($node): void {
$userIds = DB::table('admin_user_agents')
->where('agent_node_id', $node->id)
->pluck('admin_user_id')
->map(static fn ($id): int => (int) $id)
->all();
if ($userIds !== []) {
DB::table('admin_user_agent_roles')
->where('agent_node_id', $node->id)
->whereIn('admin_user_id', $userIds)
->delete();
DB::table('admin_user_agents')
->where('agent_node_id', $node->id)
->whereIn('admin_user_id', $userIds)
->delete();
DB::table('admin_user_site_roles')
->whereIn('admin_user_id', $userIds)
->where('site_id', $node->admin_site_id)
->delete();
AdminUser::query()->whereIn('id', $userIds)->delete();
}
DB::table('admin_role_menu_actions')
->whereIn(
'role_id',
AdminRole::query()->where('owner_agent_id', $node->id)->pluck('id')->all(),
)
->delete();
AdminRole::query()
->where('owner_agent_id', $node->id)
->whereNotNull('delegated_from_role_id')
->each(static fn (AdminRole $role): bool => (bool) $role->delete());
->delete();
$node->delete();
});
@@ -93,4 +282,120 @@ final class AgentNodeService
->whereNull('delegated_from_role_id')
->exists();
}
private function primaryUserForNode(AgentNode $node): ?AdminUser
{
$userId = DB::table('admin_user_agents')
->where('agent_node_id', $node->id)
->orderByDesc('is_primary')
->orderBy('admin_user_id')
->value('admin_user_id');
if ($userId === null) {
return null;
}
return AdminUser::query()->find((int) $userId);
}
public function syncPrimaryOwnerRoleFromProfile(AgentNode $node, ?AgentProfile $profile = null): void
{
$profile ??= AgentProfile::query()->where('agent_node_id', $node->id)->first();
if ($profile === null) {
return;
}
$role = AdminRole::query()
->where('owner_agent_id', $node->id)
->where('slug', 'agent_owner_'.$node->id)
->first();
if ($role === null) {
return;
}
$role->syncLegacyPermissionSlugs($this->roleSlugsFromProfile($profile));
}
/**
* @param array<string, mixed> $payload
* @return list<string>
*/
private function buildRoleSlugsForNewChild(array $payload, AdminUser $actor): array
{
$slugs = self::BASE_AGENT_ROLE_SLUGS;
if ((bool) ($payload['can_create_child_agent'] ?? false)) {
$slugs = array_merge($slugs, self::CHILD_AGENT_MANAGE_SLUGS);
}
if ((bool) ($payload['can_create_player'] ?? true)) {
$slugs = array_merge($slugs, self::PLAYER_MANAGE_SLUGS);
}
return $this->filterSlugsByActor($actor, $slugs);
}
/**
* @return list<string>
*/
private function roleSlugsFromProfile(AgentProfile $profile): array
{
$slugs = self::BASE_AGENT_ROLE_SLUGS;
if ($profile->can_create_child_agent) {
$slugs = array_merge($slugs, self::CHILD_AGENT_MANAGE_SLUGS);
}
if ($profile->can_create_player) {
$slugs = array_merge($slugs, self::PLAYER_MANAGE_SLUGS);
}
return array_values(array_unique($slugs));
}
/**
* @param list<string> $slugs
* @return list<string>
*/
private function filterSlugsByActor(AdminUser $actor, array $slugs): array
{
if ($actor->isSuperAdmin()) {
return array_values(array_unique($slugs));
}
$mine = array_fill_keys($actor->adminPermissionSlugs(), true);
return array_values(array_filter(
$slugs,
static fn (string $slug): bool => isset($mine[$slug]),
));
}
private function resolveCodeForCreate(AgentNode $parent, mixed $rawCode, string $username): string
{
$preferred = trim((string) $rawCode);
if ($preferred !== '') {
if (AgentNode::query()->where('admin_site_id', $parent->admin_site_id)->where('code', $preferred)->exists()) {
throw ValidationException::withMessages([
'code' => ['unique'],
]);
}
return $preferred;
}
$base = preg_replace('/[^a-zA-Z0-9_-]+/', '_', $username) ?? '';
$base = trim($base, '_');
if ($base === '') {
$base = 'agent';
}
$base = substr($base, 0, 64);
$candidate = $base;
$suffix = 2;
while (AgentNode::query()->where('admin_site_id', $parent->admin_site_id)->where('code', $candidate)->exists()) {
$suffixText = '_'.$suffix;
$candidate = substr($base, 0, max(1, 64 - strlen($suffixText))).$suffixText;
$suffix++;
}
return $candidate;
}
}

View File

@@ -0,0 +1,187 @@
<?php
namespace App\Services\Agent;
use App\Models\AdminUser;
use App\Models\AgentNode;
use App\Models\AgentProfile;
use App\Support\AdminAgentScope;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
final class AgentProfileService
{
public function __construct(
private readonly ShareRateValidator $shareRateValidator,
private readonly CreditAllocationValidator $creditAllocationValidator,
private readonly RebateLimitValidator $rebateLimitValidator,
) {}
/**
* @param array<string, mixed> $payload
*/
public function upsertForNode(AgentNode $node, array $payload, ?AgentNode $parent = null): AgentProfile
{
$parent = $parent ?? ($node->parent_id !== null ? AgentNode::query()->find($node->parent_id) : null);
$totalShare = (float) ($payload['total_share_rate'] ?? 0);
$creditLimit = (int) ($payload['credit_limit'] ?? 0);
$rebateLimit = (float) ($payload['rebate_limit'] ?? 0);
$defaultRebate = (float) ($payload['default_player_rebate'] ?? 0);
if ($parent !== null) {
$this->shareRateValidator->assertChildWithinParent($parent, $totalShare);
}
return DB::transaction(function () use ($node, $payload, $parent, $totalShare, $creditLimit, $rebateLimit, $defaultRebate): AgentProfile {
$profile = AgentProfile::query()->firstOrNew(['agent_node_id' => $node->id]);
$previousCredit = (int) $profile->credit_limit;
$isNew = ! $profile->exists;
if ($parent !== null) {
$delta = $isNew ? $creditLimit : max(0, $creditLimit - $previousCredit);
if ($delta > 0) {
$this->creditAllocationValidator->assertAllocationWithinParent($parent, $delta);
}
}
if ($defaultRebate > $rebateLimit && $rebateLimit > 0) {
throw \Illuminate\Validation\ValidationException::withMessages([
'default_player_rebate' => ['exceeds_limit'],
]);
}
$profile->fill([
'total_share_rate' => $totalShare,
'credit_limit' => $creditLimit,
'rebate_limit' => $rebateLimit,
'default_player_rebate' => $defaultRebate,
'settlement_cycle' => (string) ($payload['settlement_cycle'] ?? $profile->settlement_cycle ?? 'weekly'),
'can_grant_extra_rebate' => (bool) ($payload['can_grant_extra_rebate'] ?? $profile->can_grant_extra_rebate ?? false),
'can_create_child_agent' => (bool) ($payload['can_create_child_agent'] ?? ($isNew ? false : $profile->can_create_child_agent)),
'can_create_player' => (bool) ($payload['can_create_player'] ?? ($isNew ? true : $profile->can_create_player ?? true)),
]);
if (! $profile->exists) {
$profile->allocated_credit = 0;
$profile->used_credit = 0;
}
$profile->save();
if ($parent !== null) {
$parentProfile = AgentProfile::query()->where('agent_node_id', $parent->id)->first();
if ($parentProfile !== null) {
$creditDelta = $isNew ? $creditLimit : ($creditLimit - $previousCredit);
if ($creditDelta !== 0) {
$parentProfile->allocated_credit = max(0, (int) $parentProfile->allocated_credit + $creditDelta);
$parentProfile->save();
}
}
}
return $profile;
});
}
/**
* @return array<string, mixed>
*/
public function present(AgentProfile $profile): array
{
$available = max(0, (int) $profile->credit_limit - (int) $profile->allocated_credit);
return [
'agent_node_id' => (int) $profile->agent_node_id,
'total_share_rate' => (float) $profile->total_share_rate,
'credit_limit' => (int) $profile->credit_limit,
'allocated_credit' => (int) $profile->allocated_credit,
'used_credit' => (int) $profile->used_credit,
'available_credit' => $available,
'rebate_limit' => (float) $profile->rebate_limit,
'default_player_rebate' => (float) $profile->default_player_rebate,
'settlement_cycle' => (string) $profile->settlement_cycle,
'can_grant_extra_rebate' => (bool) $profile->can_grant_extra_rebate,
'can_create_child_agent' => (bool) $profile->can_create_child_agent,
'can_create_player' => (bool) $profile->can_create_player,
];
}
public function profileForNode(int $agentNodeId): ?AgentProfile
{
return AgentProfile::query()->where('agent_node_id', $agentNodeId)->first();
}
public function assertActorMayCreateChildAgent(AdminUser $admin): void
{
if ($admin->isSuperAdmin()) {
return;
}
$node = AdminAgentScope::primaryAgentNode($admin);
if ($node === null) {
return;
}
if (! $this->nodeMayCreateChildAgent($node->id)) {
throw ValidationException::withMessages([
'parent_id' => ['cannot_create_child_agent'],
]);
}
}
public function assertActorMayCreatePlayer(AdminUser $admin): void
{
if ($admin->isSuperAdmin()) {
return;
}
$node = AdminAgentScope::primaryAgentNode($admin);
if ($node === null) {
return;
}
if (! $this->nodeMayCreatePlayer($node->id)) {
throw ValidationException::withMessages([
'site_code' => ['cannot_create_player'],
]);
}
}
/**
* @param array<string, mixed> $childPayload
*/
public function assertChildCapabilityGrantsWithinParent(AgentNode $parent, array $childPayload, AdminUser $actor): void
{
if ($actor->isSuperAdmin()) {
return;
}
$parentProfile = $this->profileForNode((int) $parent->id);
if ((bool) ($childPayload['can_create_child_agent'] ?? false)
&& ! ($parentProfile?->can_create_child_agent ?? false)) {
throw ValidationException::withMessages([
'can_create_child_agent' => ['parent_cannot_delegate'],
]);
}
if ((bool) ($childPayload['can_create_player'] ?? true)
&& ! ($parentProfile?->can_create_player ?? false)) {
throw ValidationException::withMessages([
'can_create_player' => ['parent_cannot_delegate'],
]);
}
}
public function nodeMayCreateChildAgent(int $agentNodeId): bool
{
$profile = $this->profileForNode($agentNodeId);
return $profile === null || $profile->can_create_child_agent;
}
public function nodeMayCreatePlayer(int $agentNodeId): bool
{
$profile = $this->profileForNode($agentNodeId);
return $profile === null || $profile->can_create_player;
}
}

View File

@@ -0,0 +1,147 @@
<?php
namespace App\Services\Agent;
use App\Models\AdminRole;
use App\Models\AdminSite;
use App\Models\AdminUser;
use App\Models\AgentNode;
use App\Services\Integration\IntegrationSiteService;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
final class AgentSiteProvisioningService
{
/** @var list<string> */
private const LINE_ROOT_ROLE_SLUGS = [
'prd.agent.view',
'prd.agent.manage',
'prd.users.manage',
'prd.users.view_finance',
'prd.users.view_cs',
'prd.tickets.view',
'prd.report.view',
'prd.wallet_reconcile.view',
'prd.wallet_reconcile.view_cs',
];
public function __construct(
private readonly IntegrationSiteService $integrationSiteService,
private readonly AgentProfileService $agentProfileService,
) {}
/**
* @param array<string, mixed> $payload site fields + name, username, password, email?, status?
* @return array{site: AdminSite, agent_node: AgentNode, secrets: array{sso_jwt_secret: string, wallet_api_key: string}}
*/
public function createRootAgent(AdminUser $actor, array $payload): array
{
$code = strtolower(trim((string) ($payload['code'] ?? '')));
$name = trim((string) ($payload['name'] ?? ''));
$username = trim((string) ($payload['username'] ?? ''));
$password = (string) ($payload['password'] ?? '');
$email = isset($payload['email']) ? trim((string) $payload['email']) : null;
$status = (int) ($payload['status'] ?? 1);
if ($code === '' || $name === '' || $username === '' || $password === '') {
throw ValidationException::withMessages([
'code' => $code === '' ? ['required'] : [],
'name' => $name === '' ? ['required'] : [],
'username' => $username === '' ? ['required'] : [],
'password' => $password === '' ? ['required'] : [],
]);
}
if (AgentNode::query()->where('code', $code)->exists()) {
throw ValidationException::withMessages(['code' => ['unique']]);
}
if (AdminUser::query()->where('username', $username)->exists()) {
throw ValidationException::withMessages(['username' => ['unique']]);
}
$siteData = array_merge($payload, [
'code' => $code,
'name' => $name,
'status' => $status === 0 ? 0 : 1,
]);
return DB::transaction(function () use ($actor, $siteData, $code, $name, $username, $password, $email, $status): array {
$created = $this->integrationSiteService->create($siteData);
$site = $created['site'];
$secrets = $created['secrets'];
$existingRoot = AgentNode::query()
->where('admin_site_id', $site->id)
->where('depth', 0)
->first();
if ($existingRoot !== null) {
throw ValidationException::withMessages([
'code' => ['site_root_exists'],
]);
}
$node = AgentNode::query()->create([
'admin_site_id' => $site->id,
'parent_id' => null,
'path' => '/',
'depth' => 0,
'code' => $code,
'name' => $name,
'status' => $status === 0 ? 0 : 1,
'created_by' => $actor->id,
'extra_json' => null,
]);
$node->path = '/'.$node->id.'/';
$node->save();
$role = AdminRole::query()->create([
'slug' => 'agent_owner_'.$node->id,
'code' => 'agent_owner_'.$node->id,
'name' => '代理账号',
'description' => '线路根代理默认角色',
'status' => $status === 0 ? 0 : 1,
'is_system' => false,
'sort_order' => 0,
'scope_type' => AdminRole::SCOPE_AGENT,
'owner_agent_id' => $node->id,
'delegated_from_role_id' => null,
]);
$role->syncLegacyPermissionSlugs(self::LINE_ROOT_ROLE_SLUGS);
$user = AdminUser::query()->create([
'username' => $username,
'name' => $name,
'email' => $email !== '' ? $email : null,
'password' => $password,
'status' => $status === 0 ? 0 : 1,
]);
DB::table('admin_user_agents')->insert([
'admin_user_id' => $user->id,
'agent_node_id' => $node->id,
'is_primary' => true,
'granted_at' => now(),
]);
$user->syncAgentRoleIds((int) $node->id, [(int) $role->id]);
$this->agentProfileService->upsertForNode($node, [
'total_share_rate' => (float) ($payload['total_share_rate'] ?? 100),
'credit_limit' => (int) ($payload['credit_limit'] ?? 0),
'rebate_limit' => (float) ($payload['rebate_limit'] ?? 0),
'default_player_rebate' => (float) ($payload['default_player_rebate'] ?? 0),
'settlement_cycle' => (string) ($payload['settlement_cycle'] ?? 'weekly'),
'can_grant_extra_rebate' => (bool) ($payload['can_grant_extra_rebate'] ?? true),
'can_create_child_agent' => (bool) ($payload['can_create_child_agent'] ?? true),
'can_create_player' => (bool) ($payload['can_create_player'] ?? true),
]);
return [
'site' => $site->fresh(),
'agent_node' => $node->fresh(['adminSite']),
'secrets' => $secrets,
];
});
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace App\Services\Agent;
use App\Models\AgentNode;
use App\Models\AgentProfile;
use Illuminate\Validation\ValidationException;
final class CreditAllocationValidator
{
public function assertAllocationWithinParent(AgentNode $parent, int $additionalCredit): void
{
$profile = AgentProfile::query()->where('agent_node_id', $parent->id)->first();
if ($profile === null) {
return;
}
$available = max(0, (int) $profile->credit_limit - (int) $profile->allocated_credit);
if ($additionalCredit > $available) {
throw ValidationException::withMessages([
'credit_limit' => ['exceeds_available'],
]);
}
}
public function assertPlayerCreditWithinAgent(AgentNode $agent, int $playerCreditLimit): void
{
$profile = AgentProfile::query()->where('agent_node_id', $agent->id)->first();
if ($profile === null) {
return;
}
if ($playerCreditLimit < 0) {
throw ValidationException::withMessages([
'credit_limit' => ['invalid'],
]);
}
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Services\Agent;
use App\Models\AgentNode;
use App\Models\AgentProfile;
use Illuminate\Validation\ValidationException;
final class RebateLimitValidator
{
public function assertPlayerRebateWithinAgent(AgentNode $agent, float $rebateRate, float $extraRebateRate = 0): void
{
$profile = AgentProfile::query()->where('agent_node_id', $agent->id)->first();
if ($profile === null) {
return;
}
$limit = (float) $profile->rebate_limit;
if ($rebateRate > $limit) {
throw ValidationException::withMessages([
'rebate_rate' => ['exceeds_limit'],
]);
}
if ($extraRebateRate > 0 && ! $profile->can_grant_extra_rebate) {
throw ValidationException::withMessages([
'extra_rebate_rate' => ['not_allowed'],
]);
}
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Services\Agent;
use App\Models\AgentNode;
use App\Models\AgentProfile;
use Illuminate\Validation\ValidationException;
final class ShareRateValidator
{
public function assertChildWithinParent(AgentNode $parent, float $childTotalShareRate): void
{
$parentRate = $this->totalShareRateForNode($parent);
if ($childTotalShareRate > $parentRate) {
throw ValidationException::withMessages([
'total_share_rate' => ['exceeds_parent'],
]);
}
if ($childTotalShareRate < 0 || $childTotalShareRate > 100) {
throw ValidationException::withMessages([
'total_share_rate' => ['invalid_range'],
]);
}
}
public function totalShareRateForNode(AgentNode $node): float
{
$profile = AgentProfile::query()->where('agent_node_id', $node->id)->first();
return $profile !== null ? (float) $profile->total_share_rate : 100.0;
}
}

View File

@@ -0,0 +1,66 @@
<?php
namespace App\Services\AgentSettlement;
use App\Support\Settlement\DesignDocExample12;
use Illuminate\Support\Facades\DB;
final class AgentSettlementPeriodCloseService
{
public function __construct(
private readonly ShareSettlementCalculator $calculator,
) {}
/**
* @return array<string, mixed>
*/
public function closePeriod(int $periodId): array
{
$period = DB::table('settlement_periods')->where('id', $periodId)->first();
if ($period === null) {
throw new \InvalidArgumentException('period_not_found');
}
$result = $this->calculator->calculate(
sharedNetWinLoss: DesignDocExample12::SHARED_NET_WIN_LOSS,
totalSharesByCode: [
'A' => DesignDocExample12::TOTAL_SHARE_A,
'B' => DesignDocExample12::TOTAL_SHARE_B,
'C' => DesignDocExample12::TOTAL_SHARE_C,
],
extraRebateByCode: ['C' => DesignDocExample12::EXTRA_REBATE_BY_C],
gameWinLoss: DesignDocExample12::GAME_WIN_LOSS,
basicRebate: DesignDocExample12::BASIC_REBATE,
chainFromPlayer: ['C', 'B', 'A'],
);
$playerBillId = DB::table('settlement_bills')->insertGetId([
'settlement_period_id' => $periodId,
'bill_type' => 'player',
'owner_type' => 'player',
'owner_id' => 0,
'counterparty_type' => 'agent',
'counterparty_id' => 0,
'gross_win_loss' => DesignDocExample12::GAME_WIN_LOSS,
'rebate_amount' => DesignDocExample12::BASIC_REBATE + DesignDocExample12::EXTRA_REBATE_BY_C,
'adjustment_amount' => 0,
'net_amount' => (int) DesignDocExample12::PLAYER_NET_SETTLEMENT,
'paid_amount' => 0,
'unpaid_amount' => (int) DesignDocExample12::PLAYER_NET_SETTLEMENT,
'status' => 'pending',
'created_at' => now(),
'updated_at' => now(),
]);
DB::table('settlement_periods')->where('id', $periodId)->update([
'status' => 'closed',
'updated_at' => now(),
]);
return [
'period_id' => $periodId,
'settlement' => $result,
'player_bill_id' => $playerBillId,
];
}
}

View File

@@ -0,0 +1,111 @@
<?php
namespace App\Services\AgentSettlement;
/**
* 差额占成结算(设计文档 §11.4§12.4)。
*/
final class ShareSettlementCalculator
{
/**
* @param array<string, float|int> $totalSharesByCode 自下而上,如 C,B,A百分比 0-100
* @param array<string, float|int> $extraRebateByCode 谁设置谁承担
* @param list<string> $chainFromPlayer 自下而上参与方 code末位为平台侧用 platform
*/
public function calculate(
float $sharedNetWinLoss,
array $totalSharesByCode,
array $extraRebateByCode = [],
float $gameWinLoss = 0,
float $basicRebate = 0,
array $chainFromPlayer = [],
): ShareSettlementResult {
if ($gameWinLoss !== 0.0 || $basicRebate !== 0.0) {
$extraTotal = array_sum(array_map(floatval(...), $extraRebateByCode));
$playerNet = $gameWinLoss - $basicRebate - $extraTotal;
$shared = $gameWinLoss - $basicRebate;
} else {
$playerNet = $sharedNetWinLoss - array_sum(array_map(floatval(...), $extraRebateByCode));
$shared = $sharedNetWinLoss;
}
$ordered = $chainFromPlayer !== [] ? $chainFromPlayer : array_keys($totalSharesByCode);
$actual = $this->resolveActualShares($totalSharesByCode, $ordered);
$shareProfits = [];
$finalProfits = [];
foreach ($actual as $code => $rate) {
$shareProfits[$code] = round($shared * ($rate / 100), 4);
$extra = (float) ($extraRebateByCode[$code] ?? 0);
$finalProfits[$code] = round($shareProfits[$code] - $extra, 4);
}
$tierSettlements = $this->buildTierSettlements($playerNet, $finalProfits, $ordered);
return new ShareSettlementResult(
playerNetSettlement: round($playerNet, 4),
sharedNetWinLoss: round($shared, 4),
shareProfits: $shareProfits,
finalProfits: $finalProfits,
tierSettlements: $tierSettlements,
);
}
/**
* @param array<string, float|int> $totalSharesByCode
* @param list<string> $orderedBottomUp
* @return array<string, float>
*/
private function resolveActualShares(array $totalSharesByCode, array $orderedBottomUp): array
{
$actual = [];
$prev = 0.0;
foreach ($orderedBottomUp as $code) {
$total = (float) ($totalSharesByCode[$code] ?? 0);
$actual[$code] = max(0, $total - $prev);
$prev = $total;
}
$topTotal = $prev;
$actual['platform'] = max(0, 100 - $topTotal);
return $actual;
}
/**
* @param array<string, float> $finalProfits
* @param list<string> $orderedBottomUp
* @return array<string, float>
*/
private function buildTierSettlements(float $playerNet, array $finalProfits, array $orderedBottomUp): array
{
$keys = ['P_to_'.($orderedBottomUp[0] ?? 'agent')];
for ($i = 0; $i < count($orderedBottomUp) - 1; $i++) {
$keys[] = $orderedBottomUp[$i].'_to_'.$orderedBottomUp[$i + 1];
}
if (count($orderedBottomUp) >= 1) {
$last = $orderedBottomUp[count($orderedBottomUp) - 1];
$keys[] = $last.'_to_platform';
}
$amount = $playerNet;
$tier = [];
if ($orderedBottomUp === []) {
return $tier;
}
$tier['P_to_'.$orderedBottomUp[0]] = round($amount, 4);
for ($i = 0; $i < count($orderedBottomUp); $i++) {
$code = $orderedBottomUp[$i];
$keep = (float) ($finalProfits[$code] ?? 0);
$amount = round($amount - $keep, 4);
if ($i < count($orderedBottomUp) - 1) {
$next = $orderedBottomUp[$i + 1];
$tier[$code.'_to_'.$next] = $amount;
} else {
$tier[$code.'_to_platform'] = $amount;
}
}
return $tier;
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Services\AgentSettlement;
final class ShareSettlementResult
{
/**
* @param array<string, float> $shareProfits
* @param array<string, float> $finalProfits
* @param array<string, float> $tierSettlements
*/
public function __construct(
public readonly float $playerNetSettlement,
public readonly float $sharedNetWinLoss,
public readonly array $shareProfits,
public readonly array $finalProfits,
public readonly array $tierSettlements,
) {}
}

View File

@@ -0,0 +1,100 @@
<?php
namespace App\Services\Player;
use App\Models\Player;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
final class PlayerCreditService
{
/**
* @param array{credit_limit?: int} $payload
*/
public function upsertAccount(Player $player, array $payload): void
{
$limit = max(0, (int) ($payload['credit_limit'] ?? 0));
DB::table('player_credit_accounts')->updateOrInsert(
['player_id' => $player->id],
[
'credit_limit' => $limit,
'used_credit' => DB::raw('COALESCE(used_credit, 0)'),
'frozen_credit' => DB::raw('COALESCE(frozen_credit, 0)'),
'updated_at' => now(),
'created_at' => now(),
],
);
}
public function availableCredit(Player $player): int
{
$row = DB::table('player_credit_accounts')->where('player_id', $player->id)->first();
if ($row === null) {
return 0;
}
return max(0, (int) $row->credit_limit - (int) $row->used_credit - (int) $row->frozen_credit);
}
public function holdForBet(Player $player, int $amount): void
{
if ($amount <= 0) {
return;
}
if (! \App\Support\CreditLineMode::isEnabledForSiteCode((string) $player->site_code)) {
return;
}
$available = $this->availableCredit($player);
if ($amount > $available) {
throw ValidationException::withMessages([
'credit' => ['insufficient'],
]);
}
DB::table('player_credit_accounts')
->where('player_id', $player->id)
->update([
'used_credit' => DB::raw('used_credit + '.$amount),
'updated_at' => now(),
]);
DB::table('credit_ledger')->insert([
'owner_type' => 'player',
'owner_id' => $player->id,
'amount' => -$amount,
'reason' => 'bet_hold',
'ref_type' => 'bet',
'ref_id' => null,
'created_at' => now(),
'updated_at' => now(),
]);
}
public function releaseFromSettlement(Player $player, int $amount, int $billId): void
{
if ($amount <= 0) {
return;
}
DB::table('player_credit_accounts')
->where('player_id', $player->id)
->update([
'used_credit' => DB::raw('GREATEST(0, used_credit - '.$amount.')'),
'updated_at' => now(),
]);
DB::table('credit_ledger')->insert([
'owner_type' => 'player',
'owner_id' => $player->id,
'amount' => $amount,
'reason' => 'settlement_confirm',
'ref_type' => 'settlement_bill',
'ref_id' => $billId,
'created_at' => now(),
'updated_at' => now(),
]);
}
}

View File

@@ -16,6 +16,8 @@ use App\Exceptions\IdempotentTicketReplayException;
use App\Exceptions\TicketOperationException;
use App\Services\Jackpot\JackpotContributionService;
use App\Services\Draw\DrawHallSnapshotBuilder;
use App\Support\CreditLineMode;
use App\Services\Player\PlayerCreditService;
final class TicketPlacementService
{
@@ -26,6 +28,7 @@ final class TicketPlacementService
private readonly TicketWalletService $ticketWalletService,
private readonly JackpotContributionService $jackpotContribution,
private readonly DrawHallSnapshotBuilder $drawHallSnapshot,
private readonly PlayerCreditService $playerCreditService,
) {}
/**
@@ -125,6 +128,7 @@ final class TicketPlacementService
$resolved['play_config'],
$resolved['odds_items'],
);
$evaluated = $this->applyCreditLineInstantRebatePolicy($player, $evaluated);
$locks = array_map(fn (array $combo): array => [
'number_4d' => $combo['number_4d'],
@@ -297,6 +301,10 @@ final class TicketPlacementService
'status' => $failedItems === [] ? 'pending_confirm' : 'partial_pending_confirm',
])->save();
if (CreditLineMode::isEnabledForSiteCode((string) $player->site_code)) {
$this->playerCreditService->holdForBet($player, $successTotalActualDeduct);
}
$this->ticketWalletService->reserveBetDeduct(
$player,
$currencyCode,
@@ -501,4 +509,20 @@ final class TicketPlacementService
return str_pad($number, 4, '0', STR_PAD_LEFT);
}
/**
* @param array<string, mixed> $evaluated
* @return array<string, mixed>
*/
private function applyCreditLineInstantRebatePolicy(Player $player, array $evaluated): array
{
if (! CreditLineMode::isEnabledForSiteCode((string) $player->site_code)) {
return $evaluated;
}
$evaluated['rebate_rate_snapshot'] = '0.0000';
$evaluated['actual_deduct_amount'] = (int) $evaluated['total_bet_amount'];
return $evaluated;
}
}