where('agent_node_id', $agent->id)->first(); if ($profile === null) { return; } $expected = $this->calculateAllocatedCredit($agent); if ((int) $profile->allocated_credit === $expected) { return; } $profile->allocated_credit = $expected; $profile->save(); } public function syncForAgentId(int $agentNodeId): void { $agent = AgentNode::query()->find($agentNodeId); if ($agent === null) { return; } $this->syncForAgent($agent); } public function calculateAllocatedCredit(AgentNode $agent): int { $playerTotal = (int) DB::table('player_credit_accounts as pca') ->join('players as p', 'p.id', '=', 'pca.player_id') ->where('p.agent_node_id', $agent->id) ->sum('pca.credit_limit'); $childIds = AgentNode::query()->where('parent_id', $agent->id)->pluck('id'); $childAgentTotal = $childIds->isEmpty() ? 0 : (int) AgentProfile::query()->whereIn('agent_node_id', $childIds)->sum('credit_limit'); return $playerTotal + $childAgentTotal; } }