fix(analysis): compute variation for oldest month in 12-month table

The last row of the monthly variation table (oldest month of the rolling
window) always showed only the inflation value: the window started exactly
at that month, so there was no previous month to compare against, the
variation was null and the currency cells rendered '--' (hiding the prices
too).

- Backend: fetch 13 months (12 displayed + 1 base) so the oldest displayed
  month gets its previous month; bump cache key to monthly-last-v3.
- Backend: fix external fallback filter comparing a full date against a
  month key ('2026-10-14' > '2026-10' is always true), which silently
  dropped the most recent month whenever it was missing from the DB.
  Now filters by month key only.
- Backend: normalize subtractMonths to the 1st of the target month to avoid
  month shifts; skip external quotes without a buy value.
- Frontend: compute variations over the 13 months and render the last 12;
  show the current price when a variation is unavailable so no row is blank.
- Add regression tests for the window size and the external fallback.
This commit is contained in:
Jose Selesan
2026-10-14 12:05:27 -03:00
parent 28e1a732e0
commit 0f62a13246
3 changed files with 207 additions and 52 deletions

View File

@@ -31,19 +31,23 @@ function getMonthKey(date: Date): string {
}
function subtractMonths(date: Date, months: number): Date {
const result = new Date(date);
result.setMonth(result.getMonth() - months);
return result;
// Normalizamos al día 1 del mes destino para evitar corrimientos cuando el
// día actual no existe en ese mes (ej. 31/03 - 1 mes => 03/03).
return new Date(date.getFullYear(), date.getMonth() - months, 1);
}
// La tabla muestra 12 meses, pero traemos un mes extra al principio para poder
// calcular la variación del mes más antiguo mostrado (necesita su mes previo).
const DISPLAY_MONTHS = 12;
export async function getMonthlyLast(c: Context) {
const cacheKey = "quotes:monthly-last-v2";
const cacheKey = "quotes:monthly-last-v3";
const cached = cache.get(cacheKey);
if (cached) return c.json(cached);
const today = new Date();
const currentMonthKey = getMonthKey(today);
const startMonth = subtractMonths(today, 11);
const startMonth = subtractMonths(today, DISPLAY_MONTHS);
const startDate = new Date(
startMonth.getFullYear(),
@@ -107,9 +111,6 @@ export async function getMonthlyLast(c: Context) {
for (const months of missingByType.values()) {
for (const m of months) neededMonths.add(m);
}
const sortedNeeded = [...neededMonths].sort();
const minNeeded = sortedNeeded[0];
const maxNeeded = sortedNeeded[sortedNeeded.length - 1];
const externalData = new Map<string, Map<string, number>>();
@@ -133,9 +134,12 @@ export async function getMonthlyLast(c: Context) {
const monthLast = new Map<string, { fecha: string; compra: number }>();
for (const q of quotes) {
const fecha = q.fecha.slice(0, 10);
if (fecha < minNeeded || fecha > maxNeeded) continue;
if (q.compra === null || q.compra === undefined) continue;
// Comparamos por clave de mes ("YYYY-MM"), nunca la fecha completa
// contra la clave: "2026-10-14" > "2026-10" siempre es true y
// descartaría el mes más reciente.
const fecha = q.fecha.slice(0, 10);
const monthKey = fecha.slice(0, 7);
if (!neededMonths.has(monthKey)) continue;

View File

@@ -0,0 +1,143 @@
import {
afterEach,
beforeEach,
describe,
expect,
mock,
setSystemTime,
test,
} from "bun:test";
import type { Context } from "hono";
const mockQueryRaw = mock();
mock.module("../src/lib/prisma", () => ({
prisma: { $queryRaw: mockQueryRaw },
}));
const { getMonthlyLast } = await import(
"../src/modules/quotes/handlers/getMonthlyLast"
);
const { cache } = await import("../src/lib/cache");
type Row = { month: string; type: string; buy: number };
const originalFetch = globalThis.fetch;
function fakeCasaData(casa: string): unknown[] {
// Un único día por mes, cubriendo de 2025-10 a 2026-10.
const 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",
];
return months.map((m, i) => ({
casa,
fecha: `${m}-15`,
compra: 1000 + i,
venta: 1010 + i,
}));
}
function mockExternalApi() {
globalThis.fetch = mock(async (url: string | URL) => {
const casa = String(url).split("/").pop() ?? "";
return {
ok: true,
status: 200,
json: async () => fakeCasaData(casa),
} as unknown as Response;
}) as unknown as typeof fetch;
}
const context = { json: (data: unknown) => data } as unknown as Context;
beforeEach(() => {
mockQueryRaw.mockClear();
cache.clear();
setSystemTime(new Date("2026-10-14T12:00:00Z"));
});
afterEach(() => {
globalThis.fetch = originalFetch;
setSystemTime();
});
describe("getMonthlyLast", () => {
test("trae 13 meses (12 a mostrar + 1 base) y no descarta el mes en curso del fallback externo", async () => {
mockQueryRaw.mockResolvedValue([]);
mockExternalApi();
const rows = (await getMonthlyLast(context)) as Row[];
const months = [...new Set(rows.map((r) => r.month))].sort();
expect(months).toEqual([
"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
// reciente nunca llegaba desde la API externa.
expect(rows).toContainEqual({
month: "2026-10",
type: "BELO",
buy: 1012,
source: "external",
});
});
test("usa la DB cuando el dato existe y no pega a la API externa", async () => {
const dbRows: Row[] = [];
const 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"]) {
dbRows.push({ month, type, buy: 500 });
}
}
mockQueryRaw.mockResolvedValue(dbRows);
const fetchMock = mock();
globalThis.fetch = fetchMock as unknown as typeof fetch;
const rows = (await getMonthlyLast(context)) as Row[];
expect(fetchMock).not.toHaveBeenCalled();
expect(rows.every((r) => r.source === "db")).toBe(true);
expect(rows).toHaveLength(13 * 3);
});
});

View File

@@ -35,6 +35,10 @@ const MONTH_NAMES = [
"Diciembre",
];
// La ventana trae 12 meses a mostrar + 1 mes "base" al inicio, que se usa para
// calcular la variación del mes más antiguo mostrado.
const DISPLAY_MONTHS = 12;
function formatMonth(monthKey: string): string {
const [y, m] = monthKey.split("-");
return `${MONTH_NAMES[Number(m) - 1]} ${y}`;
@@ -107,6 +111,11 @@ function VariationIndicator({
<span className="text-xs text-muted-foreground inline-flex items-center gap-1">
<ArrowRight className="size-3" />
--
{current !== null && (
<span className="text-[10px] tabular-nums">
{formatPrice(current)}
</span>
)}
</span>
);
}
@@ -195,51 +204,50 @@ export function MonthlyVariationTable() {
return ((currentVal - prevVal) / prevVal) * 100;
};
return sortedMonths
.map((month, i) => {
const prev = i > 0 ? sortedMonths[i - 1] : null;
const current = monthsMap.get(month);
const prevData = prev ? monthsMap.get(prev) : null;
const allRows = sortedMonths.map((month, i) => {
const prev = i > 0 ? sortedMonths[i - 1] : null;
const current = monthsMap.get(month);
const prevData = prev ? monthsMap.get(prev) : null;
const beloVar = calcVariation(
current?.BELO ?? null,
prevData?.BELO ?? null,
);
const blueVar = calcVariation(
current?.BLUE ?? null,
prevData?.BLUE ?? null,
);
const bnaVar = calcVariation(
current?.BNA ?? null,
prevData?.BNA ?? null,
);
const beloVar = calcVariation(
current?.BELO ?? null,
prevData?.BELO ?? null,
);
const blueVar = calcVariation(
current?.BLUE ?? null,
prevData?.BLUE ?? null,
);
const bnaVar = calcVariation(current?.BNA ?? null, prevData?.BNA ?? null);
let inflation: number | null = null;
inflation = inflationMap.get(month) ?? null;
let inflation: number | null = null;
inflation = inflationMap.get(month) ?? null;
return {
month,
label: formatMonth(month),
fromDb: (current?.dbTypes.size ?? 0) > 0,
BELO: {
variation: beloVar,
prev: prevData?.BELO ?? null,
current: current?.BELO ?? null,
},
BLUE: {
variation: blueVar,
prev: prevData?.BLUE ?? null,
current: current?.BLUE ?? null,
},
BNA: {
variation: bnaVar,
prev: prevData?.BNA ?? null,
current: current?.BNA ?? null,
},
inflation,
};
})
.reverse();
return {
month,
label: formatMonth(month),
fromDb: (current?.dbTypes.size ?? 0) > 0,
BELO: {
variation: beloVar,
prev: prevData?.BELO ?? null,
current: current?.BELO ?? null,
},
BLUE: {
variation: blueVar,
prev: prevData?.BLUE ?? null,
current: current?.BLUE ?? null,
},
BNA: {
variation: bnaVar,
prev: prevData?.BNA ?? null,
current: current?.BNA ?? null,
},
inflation,
};
});
// Descartamos el mes base (el más antiguo) del render: ya cumplió su
// función como mes previo para calcular la variación del primero mostrado.
return allRows.slice(-DISPLAY_MONTHS).reverse();
}, [monthlyData, inflationData]);
const summary = useMemo(() => {