fix(analysis): mark sub-inflation growth orange and show 12 inflation months

Reserve red for negative variations across all currency columns and the total row. Show the last 12 months with inflation data plus the trailing months without it, and compute the accumulated inflation and total variation over the same 12-month window. Extend the monthly-last backend window to 15 months.
This commit is contained in:
Jose Selesan
2026-11-19 15:29:11 -03:00
parent e5382670a5
commit d156a2a8a4
3 changed files with 98 additions and 95 deletions

View File

@@ -36,18 +36,20 @@ function subtractMonths(date: Date, months: number): Date {
return new Date(date.getFullYear(), date.getMonth() - months, 1); return new Date(date.getFullYear(), date.getMonth() - months, 1);
} }
// La tabla muestra 12 meses, pero traemos un mes extra al principio para poder // La tabla compara 12 meses con dato de inflación. El mes actual y, a veces,
// calcular la variación del mes más antiguo mostrado (necesita su mes previo). // el anterior todavía no tienen inflación publicada, así que sumamos esos 2
const DISPLAY_MONTHS = 12; // meses y uno más al inicio como base para calcular la variación del mes más
// antiguo mostrado. El rango es inclusivo, por eso se resta 1 al mes actual.
const TOTAL_MONTHS = 15;
export async function getMonthlyLast(c: Context) { export async function getMonthlyLast(c: Context) {
const cacheKey = "quotes:monthly-last-v3"; const cacheKey = "quotes:monthly-last-v4";
const cached = cache.get(cacheKey); const cached = cache.get(cacheKey);
if (cached) return c.json(cached); if (cached) return c.json(cached);
const today = new Date(); const today = new Date();
const currentMonthKey = getMonthKey(today); const currentMonthKey = getMonthKey(today);
const startMonth = subtractMonths(today, DISPLAY_MONTHS); const startMonth = subtractMonths(today, TOTAL_MONTHS - 1);
const startDate = new Date( const startDate = new Date(
startMonth.getFullYear(), startMonth.getFullYear(),

View File

@@ -24,9 +24,10 @@ type Row = { month: string; type: string; buy: number };
const originalFetch = globalThis.fetch; const originalFetch = globalThis.fetch;
function fakeCasaData(casa: string): unknown[] { // 12 meses con inflación + 2 aún sin dato + 1 mes base, de 2025-08 a 2026-10.
// Un único día por mes, cubriendo de 2025-10 a 2026-10. const MONTHS = [
const months = [ "2025-08",
"2025-09",
"2025-10", "2025-10",
"2025-11", "2025-11",
"2025-12", "2025-12",
@@ -41,7 +42,10 @@ function fakeCasaData(casa: string): unknown[] {
"2026-09", "2026-09",
"2026-10", "2026-10",
]; ];
return months.map((m, i) => ({
function fakeCasaData(casa: string): unknown[] {
// Un único día por mes.
return MONTHS.map((m, i) => ({
casa, casa,
fecha: `${m}-15`, fecha: `${m}-15`,
compra: 1000 + i, compra: 1000 + i,
@@ -74,57 +78,28 @@ afterEach(() => {
}); });
describe("getMonthlyLast", () => { describe("getMonthlyLast", () => {
test("trae 13 meses (12 a mostrar + 1 base) y no descarta el mes en curso del fallback externo", async () => { test("trae 15 meses (12 con inflación + 2 sin dato + 1 base) y no descarta el mes en curso del fallback externo", async () => {
mockQueryRaw.mockResolvedValue([]); mockQueryRaw.mockResolvedValue([]);
mockExternalApi(); mockExternalApi();
const rows = (await getMonthlyLast(context)) as Row[]; const rows = (await getMonthlyLast(context)) as Row[];
const months = [...new Set(rows.map((r) => r.month))].sort(); const months = [...new Set(rows.map((r) => r.month))].sort();
expect(months).toEqual([ expect(months).toEqual(MONTHS);
"2025-10",
"2025-11",
"2025-12",
"2026-01",
"2026-02",
"2026-03",
"2026-04",
"2026-05",
"2026-06",
"2026-07",
"2026-08",
"2026-09",
"2026-10",
]);
// Regresión: "2026-10-14" > "2026-10" siempre daba true y el mes más // Regresión: "2026-10-14" > "2026-10" siempre daba true y el mes más
// reciente nunca llegaba desde la API externa. // reciente nunca llegaba desde la API externa.
expect(rows).toContainEqual({ expect(rows).toContainEqual({
month: "2026-10", month: "2026-10",
type: "BELO", type: "BELO",
buy: 1012, buy: 1014,
source: "external", source: "external",
}); });
}); });
test("usa la DB cuando el dato existe y no pega a la API externa", async () => { test("usa la DB cuando el dato existe y no pega a la API externa", async () => {
const dbRows: Row[] = []; const dbRows: Row[] = [];
const months = [ for (const month of MONTHS) {
"2025-10",
"2025-11",
"2025-12",
"2026-01",
"2026-02",
"2026-03",
"2026-04",
"2026-05",
"2026-06",
"2026-07",
"2026-08",
"2026-09",
"2026-10",
];
for (const month of months) {
for (const type of ["BELO", "BLUE", "BNA"]) { for (const type of ["BELO", "BLUE", "BNA"]) {
dbRows.push({ month, type, buy: 500 }); dbRows.push({ month, type, buy: 500 });
} }
@@ -138,6 +113,6 @@ describe("getMonthlyLast", () => {
expect(fetchMock).not.toHaveBeenCalled(); expect(fetchMock).not.toHaveBeenCalled();
expect(rows.every((r) => r.source === "db")).toBe(true); expect(rows.every((r) => r.source === "db")).toBe(true);
expect(rows).toHaveLength(13 * 3); expect(rows).toHaveLength(MONTHS.length * 3);
}); });
}); });

View File

@@ -35,9 +35,10 @@ const MONTH_NAMES = [
"Diciembre", "Diciembre",
]; ];
// La ventana trae 12 meses a mostrar + 1 mes "base" al inicio, que se usa para // Comparamos 12 meses con dato de inflación. El backend además trae hasta 2
// meses sin dato (el actual y el anterior) y 1 mes "base" al inicio para
// calcular la variación del mes más antiguo mostrado. // calcular la variación del mes más antiguo mostrado.
const DISPLAY_MONTHS = 12; const INFLATION_MONTHS = 12;
function formatMonth(monthKey: string): string { function formatMonth(monthKey: string): string {
const [y, m] = monthKey.split("-"); const [y, m] = monthKey.split("-");
@@ -58,6 +59,44 @@ function formatPrice(value: number): string {
return `$${priceFormatter.format(value)}`; return `$${priceFormatter.format(value)}`;
} }
type VariationTone = "positive" | "orange" | "negative";
// El rojo queda reservado a las caídas: crecer por debajo de la inflación es
// naranja, empatarla o superarla es verde.
function getVariationTone(
variation: number,
inflation: number | null,
): VariationTone {
if (variation < 0) return "negative";
if (inflation !== null && variation < inflation) return "orange";
return "positive";
}
const PLAIN_TONE_CLASSES: Record<VariationTone, string> = {
positive: "text-emerald-500",
orange: "text-orange-500",
negative: "text-red-500",
};
const COMPARED_TONE_CLASSES: Record<VariationTone, string> = {
positive:
"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400 px-1.5 py-0.5 rounded",
orange:
"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400 px-1.5 py-0.5 rounded",
negative:
"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400 px-1.5 py-0.5 rounded",
};
function getVariationClassName(
variation: number,
inflation: number | null,
): string {
const tone = getVariationTone(variation, inflation);
const toneClasses =
inflation !== null ? COMPARED_TONE_CLASSES[tone] : PLAIN_TONE_CLASSES[tone];
return `text-xs font-medium inline-flex items-center gap-1 tabular-nums ${toneClasses}`;
}
function TotalVariation({ function TotalVariation({
variation, variation,
inflation, inflation,
@@ -74,17 +113,7 @@ function TotalVariation({
} }
return ( return (
<span <span className={getVariationClassName(variation, inflation)}>
className={`text-xs font-medium inline-flex items-center gap-1 tabular-nums ${
inflation !== null
? variation > inflation
? "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400 px-1.5 py-0.5 rounded"
: "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400 px-1.5 py-0.5 rounded"
: variation >= 0
? "text-emerald-500"
: "text-red-500"
}`}
>
{variation >= 0 ? ( {variation >= 0 ? (
<ArrowUp className="size-3" /> <ArrowUp className="size-3" />
) : ( ) : (
@@ -121,17 +150,7 @@ function VariationIndicator({
} }
const indicator = ( const indicator = (
<span <span className={getVariationClassName(variation, inflation)}>
className={`text-xs font-medium inline-flex items-center gap-1 tabular-nums ${
inflation !== null
? variation > inflation
? "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400 px-1.5 py-0.5 rounded"
: "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400 px-1.5 py-0.5 rounded"
: variation >= 0
? "text-emerald-500"
: "text-red-500"
}`}
>
{variation >= 0 ? ( {variation >= 0 ? (
<ArrowUp className="size-3" /> <ArrowUp className="size-3" />
) : ( ) : (
@@ -219,8 +238,7 @@ export function MonthlyVariationTable() {
); );
const bnaVar = calcVariation(current?.BNA ?? null, prevData?.BNA ?? null); const bnaVar = calcVariation(current?.BNA ?? null, prevData?.BNA ?? null);
let inflation: number | null = null; const inflation: number | null = inflationMap.get(month) ?? null;
inflation = inflationMap.get(month) ?? null;
return { return {
month, month,
@@ -245,16 +263,27 @@ export function MonthlyVariationTable() {
}; };
}); });
// Descartamos el mes base (el más antiguo) del render: ya cumplió su // Mostramos los últimos 12 meses con dato de inflación y, desde el más
// función como mes previo para calcular la variación del primero mostrado. // antiguo de ellos hacia adelante, también los meses aún sin dato (el
return allRows.slice(-DISPLAY_MONTHS).reverse(); // actual y a veces el anterior). El mes inmediatamente anterior al primero
// visible se conserva fuera del render solo como base de su variación.
const monthsWithInflation = allRows.filter((row) => row.inflation !== null);
const firstVisibleIndex = Math.max(
0,
monthsWithInflation.length - INFLATION_MONTHS,
);
const firstVisibleMonth = monthsWithInflation[firstVisibleIndex]?.month;
if (!firstVisibleMonth) return [];
return allRows.filter((row) => row.month >= firstVisibleMonth).reverse();
}, [monthlyData, inflationData]); }, [monthlyData, inflationData]);
const summary = useMemo(() => { const summary = useMemo(() => {
if (rows.length < 2) return null; const inflationRows = rows.filter((row) => row.inflation !== null);
if (inflationRows.length < 2) return null;
const oldest = rows[rows.length - 1]; const oldest = inflationRows[inflationRows.length - 1];
const newest = rows[0]; const newest = inflationRows[0];
const totalVariation = ( const totalVariation = (
first: number | null, first: number | null,
@@ -264,18 +293,15 @@ export function MonthlyVariationTable() {
return ((last - first) / first) * 100; return ((last - first) / first) * 100;
}; };
const accumulatedInflation = rows.reduce<number | null>((acc, row) => { const accumulatedInflation = inflationRows.reduce<number>((acc, row) => {
if (row.inflation === null) return acc; return acc * (1 + (row.inflation ?? 0) / 100);
const factor = 1 + row.inflation / 100; }, 1);
return (acc ?? 1) * factor;
}, null);
return { return {
BELO: totalVariation(oldest.BELO.current, newest.BELO.current), BELO: totalVariation(oldest.BELO.current, newest.BELO.current),
BLUE: totalVariation(oldest.BLUE.current, newest.BLUE.current), BLUE: totalVariation(oldest.BLUE.current, newest.BLUE.current),
BNA: totalVariation(oldest.BNA.current, newest.BNA.current), BNA: totalVariation(oldest.BNA.current, newest.BNA.current),
inflation: inflation: (accumulatedInflation - 1) * 100,
accumulatedInflation !== null ? (accumulatedInflation - 1) * 100 : null,
period: `${oldest.label} – ${newest.label}`, period: `${oldest.label} – ${newest.label}`,
}; };
}, [rows]); }, [rows]);