# Google Sheets Export Agent

## Responsabilidad
Exportar reportes financieros del dashboard a Google Sheets con drill-down embebido via HYPERLINKs, preservando fórmulas y columnas del usuario.

## Trigger
- Usuario presiona "Exportar a Google Sheets" en cualquier reporte → `POST /api/export/google-sheets`

## Input
```json
{
  "reportType": "pnl",
  "periodStart": "2025-01-01",
  "periodEnd": "2025-06-30",
  "companies": ["solar", "hvac", "roofing"],
  "summarizeBy": "Month"
}
```

## Flujo

```
POST /api/export/google-sheets
  │
  ├─ 1. Validar input (reportType, period, companies)
  │
  ├─ 2. Leer cached_reports de MySQL para cada empresa
  │     └─ Si cache stale (> 1hr), trigger sync parcial primero
  │
  ├─ 3. Crear Google Spreadsheet
  │     └─ Título: "Sunbright P&L – Ene-Jun 2025"
  │     └─ Una tab por empresa + tab "Consolidado"
  │
  ├─ 4. Para cada tab:
  │   │
  │   ├─ a. Escribir headers (Row 1): meses como columnas
  │   │
  │   ├─ b. Escribir filas P&L con jerarquía:
  │   │     - Secciones (Income, COGS, Expenses) en bold
  │   │     - Line items con indent
  │   │     - Totales en bold + bottom border
  │   │
  │   ├─ c. Cada celda numérica incluye HYPERLINK:
  │   │     =HYPERLINK(
  │   │       "https://app.sunbright.com/api/transactions?account=Sales&company=solar&from=2025-01-01&to=2025-01-31",
  │   │       "$542,800"
  │   │     )
  │   │
  │   └─ d. Formateo: dark header, alternating rows, currency format
  │
  ├─ 5. Definir named range "DataZone" (columnas A-G)
  │     └─ En refresh futuro, solo se actualiza DataZone
  │     └─ Columnas H+ quedan intactas (fórmulas del usuario)
  │
  ├─ 6. Aplicar formato condicional:
  │     └─ Negativos en rojo
  │     └─ Varianza > 10% en amarillo
  │
  └─ 7. Retornar { spreadsheetId, spreadsheetUrl }
```

## Refresh sin sobrescribir
Cuando el usuario re-exporta o hace refresh:
1. Buscar Sheet existente por nombre/ID (almacenado en DB)
2. Limpiar solo columnas A-G (DataZone)
3. Re-escribir datos actualizados
4. Columnas H+ permanecen intactas

## Templates soportados (Fase 1)
- **P&L**: Income → COGS → Gross Profit → Expenses → Net Income
- **Balance Sheet**: Assets → Liabilities → Equity

## Templates futuros (Fase 2+)
- Cash Flow Statement
- WoW comparativo (semana actual vs anterior)
- MoM comparativo (mes actual vs anterior)
- Budget vs Actual

## Dependencias
- `GoogleSheetsService.php` — wrapper google/apiclient
- `CachedReport` model — lectura de reportes cacheados
- Google API credentials (service account key en `.env`)
