Enhance getGrossAnnualEconomy method to include logic for identifying the last fully consolidated year and generating sequential year data with estimated values for missing years.

This commit is contained in:
Giuliano Paschoalino 2026-01-21 14:44:48 -03:00
parent e82d8a1df2
commit 81e718b4f3

View File

@ -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 */