AgentProfitCommissionAssignmentService.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. namespace App\Services\Agent;
  3. use App\Models\Agent\Agent;
  4. use App\Models\Agent\AgentProfitCommissionAssignment;
  5. use App\Models\Agent\AgentProfitCommissionProfile;
  6. use Carbon\Carbon;
  7. /** 记录代理在每个时刻使用的分成比例快照,实时分成按注单结算时间取比例。 */
  8. class AgentProfitCommissionAssignmentService
  9. {
  10. public function at(Agent $agent, string $time): ?AgentProfitCommissionAssignment
  11. {
  12. return AgentProfitCommissionAssignment::query()
  13. ->where('agent_id', $agent->id)
  14. ->where('effective_from', '<=', Carbon::parse($time)->format('Y-m-d H:i:s'))
  15. ->orderByDesc('effective_from')
  16. ->orderByDesc('id')
  17. ->first();
  18. }
  19. public function assign(Agent $agent, AgentProfitCommissionProfile $profile, ?int $createdBy = null): AgentProfitCommissionAssignment
  20. {
  21. $this->assignMany([(int) $agent->id], $profile, $createdBy);
  22. return AgentProfitCommissionAssignment::query()->where('agent_id', $agent->id)
  23. ->orderByDesc('effective_from')->orderByDesc('id')->firstOrFail();
  24. }
  25. public function assignMany(array $agentIds, AgentProfitCommissionProfile $profile, ?int $createdBy = null): void
  26. {
  27. $agentIds = array_values(array_unique(array_filter(array_map('intval', $agentIds))));
  28. $now = now()->format('Y-m-d H:i:s');
  29. $values = array_merge($profile->rateSnapshot(), [
  30. 'profit_commission_profile_id' => (int) $profile->id,
  31. 'profile_name' => (string) $profile->name,
  32. 'margin_amount' => (string) $profile->margin_amount,
  33. 'created_by' => $createdBy,
  34. ]);
  35. foreach ($agentIds as $agentId) {
  36. AgentProfitCommissionAssignment::query()->updateOrCreate(
  37. ['agent_id' => $agentId, 'effective_from' => $now],
  38. $values
  39. );
  40. }
  41. }
  42. }