TbrBillingPreviewService.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace App\Services;
  3. use Carbon\Carbon;
  4. use Illuminate\Support\Collection;
  5. /**
  6. * Prévia de cobrança "da rede toda, mês corrente" usada pela tela de billing
  7. * preview. Delega para TbrCalculationService::previewBatch() para que a regra
  8. * (isenção 1-3, maior valor x faturamento, faixa de porte, flags de cobrança,
  9. * renovação pós-mês-60) seja sempre a mesma do cálculo oficial — só o formato
  10. * de saída é adaptado para o que a tela já espera.
  11. */
  12. class TbrBillingPreviewService
  13. {
  14. public function __construct(
  15. protected TbrCalculationService $calculationService,
  16. ) {}
  17. public function getAll(): Collection
  18. {
  19. $now = Carbon::now();
  20. return collect($this->calculationService->previewBatch($now->year, $now->month))
  21. ->reject(fn (array $item) => isset($item['error']))
  22. ->map(fn (array $item) => $this->toBillingPreview($item))
  23. ->values();
  24. }
  25. private function toBillingPreview(array $item): array
  26. {
  27. return [
  28. 'id' => $item['unit_id'],
  29. 'unit_name' => $item['unit_name'],
  30. 'tbr_value' => $item['tbr_value'],
  31. 'royalties_value' => $item['royalties_effective_value'],
  32. 'royalties_rule' => $this->ruleLabel(
  33. $item['contract_month_reference'],
  34. $item['royalties_effective_value'],
  35. $item['royalties_effective_percentage'],
  36. $item['royalties_bracket_percentage'],
  37. ),
  38. 'fnm_value' => $item['fnm_effective_value'],
  39. 'fnm_rule' => $this->ruleLabel(
  40. $item['contract_month_reference'],
  41. $item['fnm_effective_value'],
  42. $item['fnm_effective_percentage'],
  43. $item['fnm_bracket_percentage'],
  44. ),
  45. 'maintenance_value' => $item['maintenance_effective_value'],
  46. 'total' => $item['final_value'],
  47. ];
  48. }
  49. private function ruleLabel(int $contractMonth, float $effectiveValue, float $effectivePercentage, float $bracketPercentage): string
  50. {
  51. if ($contractMonth <= 3) {
  52. return 'Isento';
  53. }
  54. if ($effectiveValue <= 0.0) {
  55. return 'Não cobrado';
  56. }
  57. return abs($effectivePercentage - $bracketPercentage) < 0.0001 ? 'Fixo TBR' : '% Faturamento';
  58. }
  59. }