diff --git a/app/api/indicadores/[codigo]/[anio]/route.test.ts b/app/api/indicadores/[codigo]/[anio]/route.test.ts index 1bd2d83..64f9ba7 100644 --- a/app/api/indicadores/[codigo]/[anio]/route.test.ts +++ b/app/api/indicadores/[codigo]/[anio]/route.test.ts @@ -1,41 +1,99 @@ import { NextRequest } from 'next/server'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { GET } from '@/app/api/indicadores/[codigo]/[anio]/route'; -import type { SerieHistorica } from '@/types/indicador'; -const serie: SerieHistorica = { - codigo: 'uf', - nombre: 'Unidad de fomento (UF)', - unidad_medida: 'Pesos', - serie: [{ fecha: '2026-01-01T00:00:00.000Z', valor: 39731.79 }], -}; +// La API de Banco Central declara charset=ISO-8859-1: response.arrayBuffer() +// tiene que decodificar los bytes crudos como Latin-1 (ver bcentral-client.ts +// y su test). Estos mocks de fetch simulan exactamente ese formato de bytes. +function bufferLatin1(texto: string): ArrayBuffer { + const bytes = new Uint8Array(texto.length); + for (let i = 0; i < texto.length; i += 1) { + bytes[i] = texto.charCodeAt(i) & 0xff; + } + return bytes.buffer; +} + +function respuestaOk(): Response { + return { + arrayBuffer: async () => + bufferLatin1( + JSON.stringify({ + Codigo: 0, + Descripcion: 'Success', + Series: { + descripEsp: 'Unidad de fomento (UF)', + descripIng: 'Unit of account (UF)', + seriesId: 'F073.UFF.PRE.Z.D', + Obs: [{ indexDateString: '02-01-2020', value: '39731.79', statusCode: 'OK' }], + }, + SeriesInfos: [], + }), + ), + } as Response; +} + +function respuestaError(): Response { + return { + arrayBuffer: async () => + bufferLatin1( + JSON.stringify({ + Codigo: -50, + Descripcion: 'An internal error has occurred, information is not available.', + Series: { descripEsp: null, descripIng: null, seriesId: null, Obs: null }, + SeriesInfos: [], + }), + ), + } as Response; +} function callRoute(codigo: string, anio: string) { - const request = new NextRequest( - `http://localhost:3000/api/indicadores/${codigo}/${anio}`, - ); + const request = new NextRequest(`http://localhost:3000/api/indicadores/${codigo}/${anio}`); return GET(request, { params: Promise.resolve({ codigo, anio }) }); } describe('GET /api/indicadores/[codigo]/[anio]', () => { beforeEach(() => { vi.stubGlobal('fetch', vi.fn()); + vi.stubEnv('BCENTRAL_USER', 'usuario-test'); + vi.stubEnv('BCENTRAL_PASS', 'clave-test'); }); afterEach(() => { vi.unstubAllGlobals(); + vi.unstubAllEnvs(); }); it('responde 200 con la serie historica para un codigo y anio validos', async () => { - vi.mocked(fetch).mockResolvedValueOnce({ - ok: true, - json: async () => serie, - } as Response); + vi.mocked(fetch).mockResolvedValueOnce(respuestaOk()); - const response = await callRoute('uf', '2026'); + const response = await callRoute('uf', '2020'); expect(response.status).toBe(200); - await expect(response.json()).resolves.toEqual(serie); + const body = await response.json(); + expect(body.codigo).toBe('uf'); + expect(body.serie).toEqual([{ fecha: '2020-01-02T00:00:00.000Z', valor: 39731.79 }]); + }); + + it('construye firstdate/lastdate explicitos: 1 de enero a 31 de diciembre para un anio pasado', async () => { + vi.mocked(fetch).mockResolvedValueOnce(respuestaOk()); + + await callRoute('uf', '2020'); + + const url = vi.mocked(fetch).mock.calls[0][0] as URL; + expect(url.searchParams.get('firstdate')).toBe('2020-01-01'); + expect(url.searchParams.get('lastdate')).toBe('2020-12-31'); + }); + + it('corta lastdate en "hoy" cuando el anio pedido es el anio en curso (nunca omite el rango)', async () => { + vi.mocked(fetch).mockResolvedValueOnce(respuestaOk()); + const anioActual = String(new Date().getFullYear()); + + await callRoute('uf', anioActual); + + const url = vi.mocked(fetch).mock.calls[0][0] as URL; + expect(url.searchParams.get('firstdate')).toBe(`${anioActual}-01-01`); + expect(url.searchParams.get('lastdate')).not.toBeNull(); + expect(url.searchParams.get('lastdate')).not.toBe(`${anioActual}-12-31`); }); it('responde 400 cuando el codigo no es un indicador soportado', async () => { @@ -64,10 +122,20 @@ describe('GET /api/indicadores/[codigo]/[anio]', () => { expect(body.error).toContain('anio invalido'); }); - it('responde 502 cuando la API externa falla para un codigo y anio validos', async () => { + it('responde 502 cuando Banco Central falla (Codigo distinto de 0 con HTTP 200) para un codigo y anio validos', async () => { + vi.mocked(fetch).mockResolvedValueOnce(respuestaError()); + + const response = await callRoute('dolar', '2020'); + + expect(response.status).toBe(502); + const body = (await response.json()) as { error: string }; + expect(body.error).toContain('dolar'); + }); + + it('responde 502 cuando hay un error de red', async () => { vi.mocked(fetch).mockRejectedValueOnce(new Error('fetch failed')); - const response = await callRoute('dolar', '2026'); + const response = await callRoute('dolar', '2020'); expect(response.status).toBe(502); const body = (await response.json()) as { error: string }; diff --git a/app/api/indicadores/[codigo]/[anio]/route.ts b/app/api/indicadores/[codigo]/[anio]/route.ts index cae43fa..1fa78eb 100644 --- a/app/api/indicadores/[codigo]/[anio]/route.ts +++ b/app/api/indicadores/[codigo]/[anio]/route.ts @@ -1,14 +1,30 @@ import { NextResponse } from 'next/server'; -import { getHistorico } from '@/lib/mindicador-client'; +import { BancoCentralApiError, getSerieHistorica } from '@/lib/bcentral-client'; import { INDICADOR_CODIGOS, type IndicadorCodigo } from '@/types/indicador'; -const REVALIDATE_SECONDS = 3600; const MIN_ANIO = 1970; function isIndicadorCodigo(value: string): value is IndicadorCodigo { return (INDICADOR_CODIGOS as readonly string[]).includes(value); } +function fechaISO(date: Date): string { + return date.toISOString().slice(0, 10); +} + +// Banco Central pide rangos de fechas explicitos (firstdate/lastdate), no +// anios calendario como mindicador.cl. Se deriva el rango del anio pedido: 1 +// de enero a 31 de diciembre, salvo que sea el anio en curso, donde se corta +// en "hoy" para no pedir fechas futuras sin necesidad (ver +// docs/migracion-banco-central.md). +function rangoDelAnio(anio: number): { firstdate: string; lastdate: string } { + const hoy = new Date(); + const firstdate = `${anio}-01-01`; + const finDeAnio = new Date(Date.UTC(anio, 11, 31)); + const lastdate = anio === hoy.getUTCFullYear() ? fechaISO(hoy) : fechaISO(finDeAnio); + return { firstdate, lastdate }; +} + export async function GET( _request: Request, { params }: { params: Promise<{ codigo: string; anio: string }> }, @@ -33,12 +49,20 @@ export async function GET( ); } + const { firstdate, lastdate } = rangoDelAnio(anioNum); + try { - const historico = await getHistorico(codigo, anioNum, { revalidate: REVALIDATE_SECONDS }); + const historico = await getSerieHistorica(codigo, firstdate, lastdate); return NextResponse.json(historico, { status: 200 }); } catch (error) { + if (error instanceof BancoCentralApiError) { + return NextResponse.json( + { error: `Banco Central fallo para ${codigo}: ${error.message}` }, + { status: 502 }, + ); + } const message = - error instanceof Error ? error.message : 'Error desconocido al consultar mindicador.cl'; + error instanceof Error ? error.message : 'Error desconocido al consultar Banco Central'; return NextResponse.json({ error: message }, { status: 502 }); } }