| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- <?php
- namespace App\Services\Agent;
- use App\Models\Agent\Agent;
- use App\Models\Agent\AgentProfitCommissionAssignment;
- use App\Models\Agent\AgentProfitCommissionProfile;
- use Carbon\Carbon;
- /** 记录代理在每个时刻使用的分成比例快照,实时分成按注单结算时间取比例。 */
- class AgentProfitCommissionAssignmentService
- {
- public function at(Agent $agent, string $time): ?AgentProfitCommissionAssignment
- {
- return AgentProfitCommissionAssignment::query()
- ->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
- );
- }
- }
- }
|