UnitFinancialDashboardService.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace App\Services;
  3. use App\Models\StudentContractInstallment;
  4. use App\Models\UnitAccountPayable;
  5. use Carbon\Carbon;
  6. /**
  7. * Visão geral financeira da unidade: agrega Contas a Receber (parcelas de aluno)
  8. * e Contas a Pagar (unit_account_payables) do mês corrente.
  9. */
  10. class UnitFinancialDashboardService
  11. {
  12. public function overview(int $unitId): array
  13. {
  14. $start = Carbon::now()->startOfMonth()->toDateString();
  15. $end = Carbon::now()->endOfMonth()->toDateString();
  16. $today = Carbon::today()->toDateString();
  17. // Recebíveis = parcelas de aluno
  18. $recPendingQ = StudentContractInstallment::where('unit_id', $unitId)->where('status', 'pending');
  19. $recReceivedQ = StudentContractInstallment::where('unit_id', $unitId)
  20. ->where('status', 'paid')->whereBetween('payment_date', [$start, $end]);
  21. $recOverdueQ = StudentContractInstallment::where('unit_id', $unitId)
  22. ->where('status', 'pending')->where('due_date', '<', $today);
  23. // Pagáveis
  24. $payPendingQ = UnitAccountPayable::where('unit_id', $unitId)->where('status', 'pending');
  25. $payPaidQ = UnitAccountPayable::where('unit_id', $unitId)
  26. ->where('status', 'paid')->whereBetween('payment_date', [$start, $end]);
  27. $payOverdueQ = UnitAccountPayable::where('unit_id', $unitId)
  28. ->where('status', 'pending')->where('due_date', '<', $today);
  29. $receivedMonth = (float) (clone $recReceivedQ)->sum('paid_value');
  30. $paidMonth = (float) (clone $payPaidQ)->sum('paid_value');
  31. return [
  32. 'received_month' => round($receivedMonth, 2),
  33. 'received_month_count' => (clone $recReceivedQ)->count(),
  34. 'paid_month' => round($paidMonth, 2),
  35. 'paid_month_count' => (clone $payPaidQ)->count(),
  36. 'result_month' => round($receivedMonth - $paidMonth, 2),
  37. 'receivable_pending' => round((float) (clone $recPendingQ)->sum('value'), 2),
  38. 'receivable_pending_count' => (clone $recPendingQ)->count(),
  39. 'payable_pending' => round((float) (clone $payPendingQ)->sum('value'), 2),
  40. 'payable_pending_count' => (clone $payPendingQ)->count(),
  41. 'overdue_receivable' => round((float) (clone $recOverdueQ)->sum('value'), 2),
  42. 'overdue_receivable_count' => (clone $recOverdueQ)->count(),
  43. 'overdue_payable' => round((float) (clone $payOverdueQ)->sum('value'), 2),
  44. 'overdue_payable_count' => (clone $payOverdueQ)->count(),
  45. ];
  46. }
  47. }