Files
inq-roi-simulador-web/tests/e2e/etapa-6-pdfs.spec.ts
Marcos Benítez 84daf82e65
Some checks failed
/ Deploy to Cloudflare Pages (push) Has been cancelled
Sprint 4 — Etapa 8: reporte de entrega
Tier 1 — Automatizado
Build:  limpio
Lint:  limpio en archivos nuevos de Sprint 4 (separé resource-types.ts de resource-display.tsx para sacar 2 warnings de Fast Refresh; quedan 0 errores/warnings nuevos). Quedó 1 error preexistente en ReportPage.tsx (no tocado desde Sprint 3, fuera de scope) y ~102 warnings no-explicit-any preexistentes en tests viejos.
Tests unitarios:  521/521 verdes
Tests E2E: ⚠️ 43-44/48 verdes (varía levemente entre corridas) — detalle abajo
Auditoría inicial vs. estado final
Antes: 39/39 specs (100%) fallaban — ROJO-AUTH puro, todos por #bpmn-file-input nunca apareciendo (esperaban el flujo pre-Sprint-4 directamente en /).

Decisión tomada (con tu input): Opción A — sesión real. Creaste el usuario martin.bernal@inquality.com.py; yo verifiqué que no tenía fila en public.users y se la inserté con platform_role='platform_admin'. Implementé tests/e2e/setup/auth-setup.ts como globalSetup de Playwright: hace signInWithPassword, inyecta la sesión real en localStorage con el formato exacto que usa supabase-js v2, y genera tests/e2e/setup/auth-state.json (gitignored) en cada corrida.

Fix adicional necesario: todos los specs navegaban a / esperando el input de archivo ahí — ahora vive en /import. Corregí los 18 page.goto('/') → /import, incluyendo reescribir el flujo obsoleto de prod-smoke.spec.ts (esperaba una landing pre-auth que ya no existe).

Resultado: 33→43-44 specs pasan. Quedan 5-6 ROJO-OTRO, con dos causas raíz identificadas (no relacionadas con auth, fuera del mandato de esta etapa que pide no reescribir lógica de tests):

Botón "Guardar" en ActivityPanel queda deshabilitado (3 specs de PDF) — encontré algo extraño: el texto del botón dice "Guardar cambios" (que solo se renderiza si isDirty=true) pero Playwright lo sigue viendo disabled. Esto contradice la lógica simple de disabled={!isDirty} en el componente — sospecho un bug real de re-render en producción, pero diagnosticarlo a fondo requiere debugging en vivo. Recomiendo abrir esto como bug dedicado en un sprint futuro.
2 specs usan IndexedDB/Dexie directamente (export-pdf.spec.ts, validate-dod-etapa4.spec.ts) — Dexie se eliminó completamente en Etapa 4. Estos tests necesitan reescritura para inyectar datos vía Supabase en vez de IndexedDB — eso sí es "reescribir lógica de tests", explícitamente fuera de este alcance.
Los resultados varían levemente entre corridas porque Playwright corre specs en paralelo bajo la misma cuenta de test compartida — puede haber interferencia de datos entre specs concurrentes. Sugiero como mejora futura (no implementada ahora): --workers=1 para diagnóstico determinístico.

Entregables nuevos
tests/e2e/setup/auth-setup.ts — global setup con sesión real
tests/e2e/sprint-4-smoke.spec.ts — 9 tests (4 sin auth: login, redirects de /, /workspace, /recursos; 5 con auth: biblioteca sin 500, sin 406 en simulations, catálogo carga, avatar visible, import navega a workspace)
docs/CHECKLIST_ENTREGA.md — las 4 tiers completas
.env.test (gitignored) + .env.example documentado
.gitignore actualizado (.env.test, auth-state.json)
Polish
Textos de OwnershipBadge y "Compartir con equipo" ya estaban en español — sin cambios.
Tooltip "Disponible próximamente" para "Compartir con equipo": no lo agregué, tal como pedía el propio brief, consultarte antes. ¿Lo querés?
2026-06-19 11:22:50 -03:00

180 lines
8.1 KiB
TypeScript

/**
* Etapa 6 Sprint 1.5 — PDF ROI: Rediseño de página 1 con identidad InQ.
*
* Validaciones mandatorias:
* 1. PDF ROI tiene 5 páginas, todas portrait
* 2. Footer en todas las páginas: "InQ ROI", "Powered by InQuality", paginación "X de 5"
* 3. Página 1 contiene: "ANÁLISIS DE RETORNO DE INVERSIÓN", "AHORRO PROYECTADO A",
* "TOP 3 ACTIVIDADES POR AHORRO", "UN PRODUCTO DE", "InQuality"
* 4. Página 1 contiene KPI Hero con cifra de ahorro acumulado (USD)
* 5. PDFs Actual y Automatizado sin cambios: 4 páginas, ['portrait','landscape','portrait','portrait']
* 6. Sin regresiones de marca
* 7. Tests previos >= 483
*/
import { test, expect } from '@playwright/test'
import { resolve } from 'path'
import { mkdirSync, readFileSync } from 'fs'
import { fileURLToPath } from 'url'
import { PDFParse } from 'pdf-parse'
import { getDocument } from 'pdfjs-dist/legacy/build/pdf.mjs'
test.use({ storageState: 'tests/e2e/setup/auth-state.json' })
const __dirname = fileURLToPath(new URL('.', import.meta.url))
const BPMN_DIR = resolve(__dirname, '../../public/sample-processes')
const OUT_DIR = resolve(__dirname, './__output__')
test.beforeAll(() => { mkdirSync(OUT_DIR, { recursive: true }) })
// ─── Helpers ──────────────────────────────────────────────────────────────────
async function parsePdf(buffer: Buffer): Promise<{ numpages: number; text: string }> {
const parser = new PDFParse({ data: buffer })
const result = await parser.getText()
await parser.destroy()
return { numpages: result.total, text: result.text }
}
async function getPageOrientations(buffer: Buffer): Promise<Array<'portrait' | 'landscape'>> {
const uint8 = new Uint8Array(buffer)
const pdf = await getDocument({ data: uint8 }).promise
const orientations: Array<'portrait' | 'landscape'> = []
for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i)
const viewport = page.getViewport({ scale: 1 })
orientations.push(viewport.width > viewport.height ? 'landscape' : 'portrait')
}
return orientations
}
async function importBpmn(page: import('@playwright/test').Page, filename: string) {
await page.goto('/import')
await page.locator('#bpmn-file-input').setInputFiles(resolve(BPMN_DIR, filename))
await page.waitForURL(/\/workspace\//, { timeout: 15_000 })
await page.waitForSelector('button:has-text("Simular")', { timeout: 10_000 })
await page.waitForTimeout(800)
}
async function setActivityCosts(
page: import('@playwright/test').Page,
elementId: string, directCost: number, automatedCost: number
) {
await page.locator(`[data-element-id="${elementId}"]`).first().click()
await page.waitForTimeout(400)
const toggle = page.getByRole('switch', { name: /automatizable/i })
if (await toggle.getAttribute('aria-checked') === 'false') await toggle.click()
await page.waitForTimeout(200)
await page.getByLabel(/Costo directo fijo/i).fill(String(directCost))
await page.getByLabel(/Costo automatizado/i).fill(String(automatedCost))
await page.getByLabel(/Tiempo automatizado/i).fill('10')
await page.getByRole('button', { name: /Guardar/i }).click()
await page.waitForTimeout(400)
}
async function configureGlobal(page: import('@playwright/test').Page, freq: number, inv: number) {
await page.getByRole('tab', { name: /Global/i }).click()
await page.waitForTimeout(300)
await page.getByLabel(/Frecuencia anual/i).fill(String(freq))
await page.getByLabel(/Inversión en automatización/i).fill(String(inv))
await page.getByRole('button', { name: /Guardar/i }).click()
await page.waitForTimeout(400)
}
async function setupAndSimulate(page: import('@playwright/test').Page) {
await importBpmn(page, 'medium-with-gateways.bpmn')
await setActivityCosts(page, 'task_recv', 200, 20)
await setActivityCosts(page, 'task_score', 200, 20)
await setActivityCosts(page, 'task_analisis', 200, 20)
await configureGlobal(page, 5000, 80000)
await page.getByRole('button', { name: 'Simular' }).click()
await page.waitForURL(/\/report\//, { timeout: 20_000 })
await page.waitForSelector('button:has-text("Exportar PDF")', { timeout: 15_000 })
await page.waitForSelector('.bpmn-container .djs-group', { timeout: 30_000 })
await page.waitForTimeout(800)
}
async function downloadPdf(
page: import('@playwright/test').Page,
targetTab: 'actual' | 'automatizado' | 'roi',
outPath: string
) {
if (targetTab === 'actual') {
await page.getByRole('tab', { name: 'Actual' }).click()
await page.waitForTimeout(400)
} else if (targetTab === 'automatizado') {
await page.getByRole('tab', { name: 'Automatizado' }).click()
await page.waitForTimeout(400)
} else {
await page.getByRole('tab', { name: /Comparación/i }).click()
await page.waitForSelector('[data-testid="roi-kpi-card"]', { timeout: 10_000 })
await page.waitForTimeout(500)
}
const [download] = await Promise.all([
page.waitForEvent('download', { timeout: 30_000 }),
page.getByRole('button', { name: 'Exportar PDF' }).click(),
])
await download.saveAs(outPath)
return download.suggestedFilename()
}
function validateBrandStrings(text: string, filename: string) {
expect(text, `${filename}: debe contener "InQ ROI"`).toMatch(/InQ ROI/)
expect(text, `${filename}: debe contener "Powered by InQuality"`).toMatch(/Powered by InQuality/)
expect(text, `${filename}: no debe contener "Process Cost Platform"`).not.toContain('Process Cost Platform')
expect(text, `${filename}: no debe contener "v0.1.0"`).not.toContain('v0.1.0')
}
// ─── Tests ─────────────────────────────────────────────────────────────────────
test('etapa-6-roi.pdf — 5 páginas, todas portrait, página 1 rediseñada', async ({ page }) => {
await setupAndSimulate(page)
const outPath = resolve(OUT_DIR, 'etapa-6-roi.pdf')
await downloadPdf(page, 'roi', outPath)
const buffer = readFileSync(outPath)
const sizeKB = buffer.length / 1024
console.log(`Tamaño ROI: ${sizeKB.toFixed(1)} KB`)
expect(sizeKB, 'PDF ROI debe tener > 20 KB con imagen de gradiente').toBeGreaterThan(20)
const { numpages, text } = await parsePdf(buffer)
console.log(`Páginas ROI: ${numpages}`)
console.log(`Texto primeros 400: ${text.slice(0, 400).replace(/\n/g, ' ')}`)
expect(numpages).toBe(5)
validateBrandStrings(text, 'etapa-6-roi.pdf')
// Validaciones de contenido de página 1
expect(text, 'Debe contener cabecera del análisis').toMatch(/ANÁLISIS DE RETORNO DE INVERSIÓN/)
expect(text, 'Debe contener label del KPI Hero').toMatch(/AHORRO PROYECTADO A/)
expect(text, 'Debe contener título del Top3').toMatch(/TOP 3 ACTIVIDADES POR AHORRO/)
expect(text, 'Debe contener "UN PRODUCTO DE"').toMatch(/UN PRODUCTO DE/)
expect(text, 'Debe contener "InQuality"').toMatch(/InQuality/)
// Orientaciones
const orientations = await getPageOrientations(buffer)
console.log('Orientaciones ROI:', orientations)
expect(orientations).toEqual(['portrait', 'portrait', 'portrait', 'portrait', 'portrait'])
})
test('etapa-6: PDFs Actual y Automatizado sin cambios (4 págs, landscape en p.2)', async ({ page }) => {
await setupAndSimulate(page)
const actualPath = resolve(OUT_DIR, 'etapa-6-actual.pdf')
const autoPath = resolve(OUT_DIR, 'etapa-6-automatizado.pdf')
await downloadPdf(page, 'actual', actualPath)
await downloadPdf(page, 'automatizado', autoPath)
for (const [path, label] of [[actualPath, 'actual'], [autoPath, 'automatizado']] as const) {
const buffer = readFileSync(path)
const { numpages, text } = await parsePdf(buffer)
console.log(`Páginas ${label}: ${numpages}`)
expect(numpages, `${label}: debe tener 4 páginas`).toBe(4)
validateBrandStrings(text, `etapa-6-${label}.pdf`)
const orientations = await getPageOrientations(buffer)
console.log(`Orientaciones ${label}:`, orientations)
expect(orientations, `${label}: layout portrait-landscape-portrait-portrait`)
.toEqual(['portrait', 'landscape', 'portrait', 'portrait'])
}
})