Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 70 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,74 @@
# Agent Guidelines — Pulso (Dashboard Indicadores Económicos de Chile)

<!-- BEGIN:nextjs-agent-rules -->

# This is NOT the Next.js you know
## ⚠️ Next.js Version Constraint

This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
This version of Next.js has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
<!-- END:nextjs-agent-rules -->

---

## 🎯 System Context & Stack

- **Framework**: Next.js 16 (App Router, Turbopack) + React 19 + TypeScript.
- **Styling**: Tailwind CSS v4 (`@import "tailwindcss";` in `app/globals.css`).
- **Data Fetching**: SWR for client-side hydration, server-side caching & snapshot engine in `lib/bcentral-client.ts` and `lib/indicadores-snapshot.ts`.
- **External API**: Banco Central de Chile SI3 (`SieteRestWS`). Latin-1 encoding handled server-side.
- **Testing**: Vitest + Testing Library (unit/component), Playwright (E2E).

---

## 🚦 Execution Boundaries

### Always

- Keep environment secrets (`BCENTRAL_USER`, `BCENTRAL_PASS`) restricted to server-side executions (`lib/`, Route Handlers). NEVER add the `NEXT_PUBLIC_` prefix to secret variables.
- Run tests (`npm run test`) and linter (`npm run lint`) after making code modifications.
- Preserve existing API fallback mechanisms: when the external Banco Central API fails, return last-known-good cached data or handle gracefully.
- Follow TypeScript strict mode without using `any` or disabling type checks.

### Ask First

- Adding or upgrading npm dependencies in `package.json`.
- Modifying environment variable schemas or altering `.env.example`.
- Changing API route contracts under `/api/indicadores/`.

### Never

- Expose raw Banco Central credentials to the client browser.
- Perform direct external HTTP calls to `si3.bcentral.cl` from Client Components (all external requests MUST route through server-side handlers).
- Commit code that breaks existing Vitest unit tests or Playwright E2E suites.

---

## 🛠️ Verification & Development Commands

| Command | Purpose |
| ---------------------- | --------------------------------------------------------------- |
| `npm run dev` | Start development server with Turbopack (http://localhost:3000) |
| `npm run build` | Validate production build |
| `npm run start` | Serve production build locally |
| `npm run lint` | Execute ESLint checks |
| `npm run format` | Format codebase using Prettier |
| `npm run format:check` | Check code formatting without modifying files |
| `npm run test` | Run unit and component test suite (Vitest) |
| `npm run test:watch` | Run Vitest in interactive watch mode |
| `npm run test:e2e` | Run End-to-End tests (Playwright) |

---

## 📂 Key Architecture & Map

```
app/
page.tsx → Home page (SSR + SWRConfig fallback)
api/indicadores/route.ts → GET snapshot of 10 economic indicators
api/indicadores/[codigo]/[anio]/ → GET historical annual series for an indicator
dev/ui/ → Component showcase (blocked in prod via proxy.ts)
components/ → UI Components (DashboardHome, IndicatorCard, HistoryChart, Converter)
hooks/ → Custom hooks (useIndicadores, useIndicadorHistory, useFavoritos)
lib/ → Services (bcentral-client.ts, indicadores-snapshot.ts)
types/ → Domain TypeScript definitions (indicador.ts)
docs/ → Complete internal technical documentation
```
99 changes: 99 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# Guía de Contribución — Pulso

¡Gracias por tu interés en contribuir a **Pulso**! Este documento proporciona las directrices e instrucciones necesarias para configurar tu entorno de desarrollo, ejecutar pruebas, seguir el estilo de código del proyecto y enviar tus cambios mediante Pull Requests.

---

## 🚀 Requisitos Previos

- **Node.js**: `v26.0.0` o superior.
- **npm**: Administrador de paquetes por defecto.
- **Git**: Sistema de control de versiones.

---

## 🛠️ Configuración del Entorno Local

1. **Clonar el repositorio**:

```bash
git clone https://github.com/mbarradev-debug/pulso.git
cd pulso
```

2. **Instalar dependencias**:

```bash
npm install
```

3. **Configurar variables de entorno**:
Copia el archivo de plantilla `.env.example` a `.env.local`:

```bash
cp .env.example .env.local
```

Abre `.env.local` y completa las credenciales de la API SI3 del Banco Central de Chile (`BCENTRAL_USER` y `BCENTRAL_PASS`). Si no posees una cuenta, puedes registrarte gratuitamente en [si3.bcentral.cl](https://si3.bcentral.cl).

4. **Iniciar el servidor de desarrollo**:
```bash
npm run dev
```
Abre [http://localhost:3000](http://localhost:3000) en tu navegador.

---

## 🧪 Verificación y Pruebas

Antes de subir tus cambios, asegúrate de que todos los linters, formateadores y suites de pruebas pasen exitosamente:

| Comando | Descripción |
| ---------------------- | ----------------------------------------------------------- |
| `npm run lint` | Ejecuta ESLint para validar reglas de código |
| `npm run format` | Aplica Prettier en todo el proyecto |
| `npm run format:check` | Verifica que los archivos sigan el formato esperado |
| `npm run test` | Corre los tests unitarios y de componentes con Vitest |
| `npm run test:e2e` | Corre los tests End-to-End con Playwright |
| `npm run build` | Valida que la compilación de producción compile sin errores |

---

## ⚓ Git Hooks y Commits

Este proyecto utiliza **Husky** y **lint-staged** para verificar automáticamente los archivos en staging antes de crear un commit.

- Al ejecutar `git commit`, Husky correrá automáticamente ESLint y Prettier sobre los archivos modificados.
- Si se detectan errores, corrige los fallos antes de reintentar el commit.

---

## 🔄 Flujo de Trabajo para Pull Requests (PRs)

1. **Crear una rama funcional**:

```bash
git checkout -b feature/nombre-de-tu-mejora
```

2. **Realizar commits claros e informativos**:
- Agrupa cambios lógicos en commits independientes.
- Escribe mensajes de commit descriptivos en presente indicativo.

3. **Integración Continua (CI)**:
Cada PR hacia `main` activará automáticamente los workflows de GitHub Actions (`.github/workflows/ci.yml`), verificando:
- Linting y verificación de formato.
- Comprobación de tipos de TypeScript.
- Pruebas unitarias en Vitest.
- Pruebas E2E en Playwright.
- Build de producción Next.js.

---

## 📚 Documentación Interna

Para comprender a fondo la arquitectura, el modelo de datos, la resiliencia ante fallos del Banco Central y los patrones utilizados, consulta el índice de documentación en:

- [`docs/INDEX.md`](docs/INDEX.md)
- [`docs/architecture.md`](docs/architecture.md)
- [`AGENTS.md`](AGENTS.md)
146 changes: 71 additions & 75 deletions app/opengraph-image.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,94 +16,90 @@ const trendBg = { up: 'rgba(52, 211, 153, 0.12)', down: 'rgba(248, 113, 113, 0.1

export default function Image() {
return new ImageResponse(
(
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
background: '#0a0a0b',
padding: '64px 72px',
fontFamily: 'sans-serif',
}}
>
<div style={{ display: 'flex', flexDirection: 'column' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
background: '#0a0a0b',
padding: '64px 72px',
fontFamily: 'sans-serif',
}}
>
<div style={{ display: 'flex', flexDirection: 'column' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
<div
style={{
display: 'flex',
width: 56,
height: 56,
borderRadius: 14,
background: '#e9b949',
color: '#171208',
fontSize: 30,
fontWeight: 700,
alignItems: 'center',
justifyContent: 'center',
}}
>
P
</div>
<div style={{ display: 'flex', fontSize: 56, fontWeight: 700, color: '#f5f5f4' }}>
Pulso
</div>
</div>
<div style={{ display: 'flex', marginTop: 20, fontSize: 30, color: '#a8a29e' }}>
Indicadores económicos de Chile en tiempo real
</div>
</div>

<div style={{ display: 'flex', gap: 20 }}>
{indicators.map((indicator) => (
<div
key={indicator.code}
style={{
display: 'flex',
flexDirection: 'column',
flex: 1,
background: '#141416',
border: '1px solid #26262a',
borderRadius: 16,
padding: '24px 28px',
}}
>
<div style={{ display: 'flex', fontSize: 24, color: '#a8a29e' }}>{indicator.code}</div>
<div
style={{
display: 'flex',
width: 56,
height: 56,
borderRadius: 14,
background: '#e9b949',
color: '#171208',
fontSize: 30,
marginTop: 12,
fontSize: 32,
fontWeight: 700,
alignItems: 'center',
justifyContent: 'center',
color: '#f5f5f4',
}}
>
P
</div>
<div style={{ display: 'flex', fontSize: 56, fontWeight: 700, color: '#f5f5f4' }}>
Pulso
{indicator.value}
</div>
</div>
<div style={{ display: 'flex', marginTop: 20, fontSize: 30, color: '#a8a29e' }}>
Indicadores económicos de Chile en tiempo real
</div>
</div>

<div style={{ display: 'flex', gap: 20 }}>
{indicators.map((indicator) => (
<div
key={indicator.code}
style={{
display: 'flex',
flexDirection: 'column',
flex: 1,
background: '#141416',
border: '1px solid #26262a',
borderRadius: 16,
padding: '24px 28px',
marginTop: 14,
fontSize: 20,
fontWeight: 600,
color: trendColor[indicator.trend],
background: trendBg[indicator.trend],
borderRadius: 999,
padding: '4px 12px',
alignSelf: 'flex-start',
}}
>
<div style={{ display: 'flex', fontSize: 24, color: '#a8a29e' }}>
{indicator.code}
</div>
<div
style={{
display: 'flex',
marginTop: 12,
fontSize: 32,
fontWeight: 700,
color: '#f5f5f4',
}}
>
{indicator.value}
</div>
<div
style={{
display: 'flex',
marginTop: 14,
fontSize: 20,
fontWeight: 600,
color: trendColor[indicator.trend],
background: trendBg[indicator.trend],
borderRadius: 999,
padding: '4px 12px',
alignSelf: 'flex-start',
}}
>
{indicator.delta}
</div>
{indicator.delta}
</div>
))}
</div>
</div>
))}
</div>
),
{ ...size }
</div>,
{ ...size },
);
}
4 changes: 3 additions & 1 deletion components/DashboardHome.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ export function DashboardHome() {

const codigosVisibles = useMemo(
() =>
soloFavoritos ? codigosOrdenados.filter((codigo) => favoritos.includes(codigo)) : codigosOrdenados,
soloFavoritos
? codigosOrdenados.filter((codigo) => favoritos.includes(codigo))
: codigosOrdenados,
[soloFavoritos, codigosOrdenados, favoritos],
);

Expand Down
4 changes: 3 additions & 1 deletion components/HistoryChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,9 @@ export function HistoryChart({ codigo, fechaReferencia, unidadMedida }: HistoryC
return data.filter((punto) => new Date(punto.fecha) >= corte).length;
};
// "1A" siempre queda visible como respaldo, aunque no alcance el minimo.
return RANGOS.filter((r) => r === '1A' || contarEnRango(MESES_POR_RANGO[r]) >= MIN_PUNTOS_RANGO);
return RANGOS.filter(
(r) => r === '1A' || contarEnRango(MESES_POR_RANGO[r]) >= MIN_PUNTOS_RANGO,
);
}, [data, fechaAncla]);

const rangosVisiblesKey = rangosVisibles.join(',');
Expand Down
Loading
Loading