| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- <?php
- namespace App\Services;
- use App\Models\FranchiseeContract;
- use Illuminate\Support\Collection;
- class TbrBillingPreviewService
- {
- private const MAINTENANCE_RATE = 0.30;
- private const EXEMPT_MONTHS = 3;
- public function getAll(): Collection
- {
- $latestContracts = FranchiseeContract::with('unit')
- ->whereNotNull('tbr_fixed_value')
- ->whereNotNull('unit_id')
- ->orderByDesc('created_at')
- ->get()
- ->unique('unit_id')
- ->values();
- return $latestContracts->map(fn ($contract) => $this->buildPreview($contract));
- }
- private function buildPreview(FranchiseeContract $contract): array
- {
- $tbrValue = (float) $contract->tbr_fixed_value;
- $contractMonth = $this->resolveContractMonth($contract);
- $isExempt = $contractMonth <= self::EXEMPT_MONTHS;
- $royaltiesValue = $isExempt ? 0.0 : round($tbrValue * (float) $contract->tbr_fixed_value_percentage, 2);
- $fnmValue = $isExempt ? 0.0 : round($tbrValue * (float) $contract->marketing_fund_percentage, 2);
- $maintenanceValue = round($tbrValue * self::MAINTENANCE_RATE, 2);
- return [
- 'id' => $contract->unit_id,
- 'unit_name' => $contract->unit?->fantasy_name,
- 'tbr_value' => $tbrValue,
- 'royalties_value' => $royaltiesValue,
- 'royalties_rule' => 'Fixo TBR',
- 'fnm_value' => $fnmValue,
- 'fnm_rule' => 'Fixo TBR',
- 'maintenance_value' => $maintenanceValue,
- 'total' => round($royaltiesValue + $fnmValue + $maintenanceValue, 2),
- ];
- }
- private function resolveContractMonth(FranchiseeContract $contract): int
- {
- $startDate = $contract->start_date ?? $contract->signature_date;
- if (!$startDate) {
- return 1;
- }
- return (int) $startDate->startOfMonth()->diffInMonths(now()->startOfMonth()) + 1;
- }
- }
|