From 81e718b4f3a134b694969755acc78b2265d6f970 Mon Sep 17 00:00:00 2001 From: Giuliano Paschoalino Date: Wed, 21 Jan 2026 14:44:48 -0300 Subject: [PATCH] Enhance getGrossAnnualEconomy method to include logic for identifying the last fully consolidated year and generating sequential year data with estimated values for missing years. --- .../Economy/EconomyRepository.php | 49 ++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/app/Repositories/Economy/EconomyRepository.php b/app/Repositories/Economy/EconomyRepository.php index 32d0ecf..f18b41c 100644 --- a/app/Repositories/Economy/EconomyRepository.php +++ b/app/Repositories/Economy/EconomyRepository.php @@ -44,7 +44,7 @@ class EconomyRepository extends AbstractRepository implements EconomyContractInt "economia.dad_estimado" ]; - return $this->execute($params, $field) + $result = $this->execute($params, $field) ->where( DB::raw("TO_DATE(economia.mes, 'YYMM')"), ">=", @@ -74,6 +74,53 @@ class EconomyRepository extends AbstractRepository implements EconomyContractInt ->havingRaw("sum(custo_livre) > 0") ->orderBy(DB::raw("mes, ano, dad_estimado")) ->get(); + + // Find the last fully consolidated year (December with dad_estimado = false) + $lastConsolidatedYear = null; + foreach ($result as $item) { + if ($item->dad_estimado === false || $item->dad_estimado === 0) { + $month = (int)substr($item->mes, -2); + if ($month === 12) { + $year = (int)$item->ano; + if ($lastConsolidatedYear === null || $year > $lastConsolidatedYear) { + $lastConsolidatedYear = $year; + } + } + } + } + + // If no consolidated year found, use current year - 1 + if ($lastConsolidatedYear === null) { + $lastConsolidatedYear = (int)date('Y') - 1; + } + + // Create result array with sequential years (last consolidated + 6 more years) + $sequentialResult = []; + for ($year = $lastConsolidatedYear; $year <= $lastConsolidatedYear + 6; $year++) { + $yearData = $result->filter(function ($item) use ($year) { + return (int)$item->ano === $year; + }); + + if ($yearData->count() > 0) { + foreach ($yearData as $item) { + $sequentialResult[] = $item; + } + } else { + // Fill missing year with estimated data from closest available year + $closestData = $result->filter(function ($item) { + return (int)$item->ano > 0; + })->sortBy('ano')->last(); + + if ($closestData) { + $newItem = clone $closestData; + $newItem->ano = (string)$year; + $newItem->dad_estimado = true; + $sequentialResult[] = $newItem; + } + } + } + + return collect($sequentialResult); } /* Economia bruta mensal */