where('agent_id', $agent->id) ->where('effective_from', '<=', Carbon::parse($time)->format('Y-m-d H:i:s')) ->orderByDesc('effective_from') ->orderByDesc('id') ->first(); } public function assign(Agent $agent, AgentProfitCommissionProfile $profile, ?int $createdBy = null): AgentProfitCommissionAssignment { $this->assignMany([(int) $agent->id], $profile, $createdBy); return AgentProfitCommissionAssignment::query()->where('agent_id', $agent->id) ->orderByDesc('effective_from')->orderByDesc('id')->firstOrFail(); } public function assignMany(array $agentIds, AgentProfitCommissionProfile $profile, ?int $createdBy = null): void { $agentIds = array_values(array_unique(array_filter(array_map('intval', $agentIds)))); $now = now()->format('Y-m-d H:i:s'); $values = array_merge($profile->rateSnapshot(), [ 'profit_commission_profile_id' => (int) $profile->id, 'profile_name' => (string) $profile->name, 'margin_amount' => (string) $profile->margin_amount, 'created_by' => $createdBy, ]); foreach ($agentIds as $agentId) { AgentProfitCommissionAssignment::query()->updateOrCreate( ['agent_id' => $agentId, 'effective_from' => $now], $values ); } } }