feat(sprint-1.5): rediseño visual PDF ROI + identidad InQ (Etapas 4-7)

- Header/footer compartidos con paleta InQ naranja en los 3 PDFs (Etapa 4)
- Layout híbrido portrait+landscape en PDFs Actual/Automatizado:
  página 2 landscape para diagrama BPMN heatmap (Etapa 5)
- Página 1 PDF ROI rediseñada: header denso, banner narrativo, KPI Hero
  con gradiente naranja→magenta, grid 2×2 de KPIs secundarios, Top 3
  actividades por ahorro (Etapa 6)
- Páginas 2-5 PDF ROI con identidad InQ: tabla con paleta naranja,
  análisis del ahorro, nota metodológica, trayectoria del ahorro
  acumulado con gráfico SVG nativo (Etapa 7)
- 500 tests verdes (+ 34 tests nuevos del Sprint 1.5)
- BACKLOG.md, TECH_DEBT.md, OBSERVATIONS.md: sistema de planificación
  reemplaza TODO.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-17 20:45:01 -03:00
parent 63c4fbac99
commit 2f4633a33c
20 changed files with 4163 additions and 117 deletions

View File

@@ -0,0 +1,181 @@
/**
* Etapa 4 Sprint 1.5 — Validación de PDFs con header/footer compartido InQ.
*
* Genera los 3 PDFs con setup realista y valida:
* 1. Palabras clave presentes ("InQ ROI", "Powered by InQuality")
* 2. Términos prohibidos ausentes ("Process Cost Platform", "v0.1.0", "INQ", "Inq")
* 3. Cantidad de páginas (actual=3, automatizado=3, roi=4)
* 4. Tamaño por página (1580 KB por página)
*/
import { test, expect } from '@playwright/test'
import { resolve } from 'path'
import { mkdirSync, readFileSync } from 'fs'
import { fileURLToPath } from 'url'
import { PDFParse } from 'pdf-parse'
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 importBpmn(page: import('@playwright/test').Page, filename: string) {
await page.goto('/')
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 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 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 validatePdfText(text: string, filename: string) {
// Palabras clave obligatorias
expect(text, `${filename}: debe contener "InQ ROI"`).toMatch(/InQ ROI/)
expect(text, `${filename}: debe contener "Powered by InQuality"`).toMatch(/Powered by InQuality/)
// Términos prohibidos
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')
expect(text, `${filename}: no debe contener "INQ" (mal ortografía)`).not.toContain('INQ')
expect(text, `${filename}: no debe contener "Inq" (mal ortografía)`).not.toContain('Inq')
}
// ─── Tests ────────────────────────────────────────────────────────────────────
test('etapa-4-actual.pdf — 3 páginas, marca InQ, sin términos prohibidos', async ({ page }) => {
await setupAndSimulate(page)
const outPath = resolve(OUT_DIR, 'etapa-4-actual.pdf')
const filename = await downloadPdf(page, 'actual', outPath)
console.log('Nombre archivo:', filename)
expect(filename).toMatch(/_actual\.pdf$/)
const buffer = readFileSync(outPath)
const sizeKB = buffer.length / 1024
console.log(`Tamaño: ${sizeKB.toFixed(1)} KB`)
expect(sizeKB, 'Tamaño total > 15 KB por página').toBeGreaterThan(15 * 3)
expect(sizeKB, 'Tamaño total < 80 KB por página (3 págs)').toBeLessThan(80 * 3)
const { numpages, text } = await parsePdf(buffer)
console.log(`Páginas: ${numpages}`)
console.log(`Primeros 300 chars: ${text.slice(0, 300).replace(/\n/g, ' ')}`)
expect(numpages).toBe(3)
validatePdfText(text, 'etapa-4-actual.pdf')
})
test('etapa-4-automatizado.pdf — 3 páginas, marca InQ, sin términos prohibidos', async ({ page }) => {
await setupAndSimulate(page)
const outPath = resolve(OUT_DIR, 'etapa-4-automatizado.pdf')
const filename = await downloadPdf(page, 'automatizado', outPath)
expect(filename).toMatch(/_automatizado\.pdf$/)
const buffer = readFileSync(outPath)
const sizeKB = buffer.length / 1024
console.log(`etapa-4-automatizado.pdf: ${sizeKB.toFixed(1)} KB`)
expect(sizeKB).toBeGreaterThan(15 * 3)
expect(sizeKB).toBeLessThan(80 * 3)
const { numpages, text } = await parsePdf(buffer)
console.log(`Páginas: ${numpages}`)
expect(numpages).toBe(3)
validatePdfText(text, 'etapa-4-automatizado.pdf')
})
test('etapa-4-roi.pdf — 4 páginas, marca InQ, keywords ROI, sin términos prohibidos', async ({ page }) => {
await setupAndSimulate(page)
const outPath = resolve(OUT_DIR, 'etapa-4-roi.pdf')
const filename = await downloadPdf(page, 'roi', outPath)
expect(filename).toMatch(/_roi\.pdf$/)
const buffer = readFileSync(outPath)
const sizeKB = buffer.length / 1024
console.log(`etapa-4-roi.pdf: ${sizeKB.toFixed(1)} KB`)
// ROI PDF no tiene imagen BPMN embebida → tamaño por página es menor (~8-12 KB texto puro)
expect(sizeKB, 'ROI PDF debe tener contenido mínimo (4 páginas texto)').toBeGreaterThan(20)
expect(sizeKB, 'ROI PDF no debe ser irrazonablemente grande').toBeLessThan(300)
const { numpages, text } = await parsePdf(buffer)
console.log(`Páginas: ${numpages}`)
console.log(`Primeros 400 chars: ${text.slice(0, 400).replace(/\n/g, ' ')}`)
expect(numpages).toBe(4)
validatePdfText(text, 'etapa-4-roi.pdf')
// Keywords específicos del PDF de ROI
expect(text).toMatch(/Payback|payback/)
expect(text).toMatch(/ahorro|Ahorro/)
expect(text).toContain('USD')
})

View File

@@ -0,0 +1,180 @@
/**
* Etapa 5 Sprint 1.5 — Validación de PDFs con layout híbrido portrait+landscape.
*
* Validaciones mandatorias:
* 1. Páginas: actual=3, automatizado=3, roi=4
* 2. Orientación: actual/auto = portrait/LANDSCAPE/portrait; roi = portrait×4
* 3. "InQ ROI" y "Powered by InQuality" en todas las páginas
* 4. Diagrama BPMN en página 2 del actual (verificado por tamaño PDF y texto)
* 5. Tests previos ≥ 469
* 6. Sin regresiones de marca
*/
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'
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('/')
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-5-actual.pdf — 4 págs, portrait-landscape-portrait-portrait, marca InQ', async ({ page }) => {
await setupAndSimulate(page)
const outPath = resolve(OUT_DIR, 'etapa-5-actual.pdf')
const filename = await downloadPdf(page, 'actual', outPath)
console.log('Nombre:', filename)
const buffer = readFileSync(outPath)
const sizeKB = buffer.length / 1024
console.log(`Tamaño: ${sizeKB.toFixed(1)} KB`)
const { numpages, text } = await parsePdf(buffer)
console.log(`Páginas: ${numpages}`)
console.log(`Texto primeros 200: ${text.slice(0, 200).replace(/\n/g, ' ')}`)
expect(numpages).toBe(4)
validateBrandStrings(text, 'etapa-5-actual.pdf')
// Validar orientaciones con pdfjs
const orientations = await getPageOrientations(buffer)
console.log('Orientaciones:', orientations)
expect(orientations).toEqual(['portrait', 'landscape', 'portrait', 'portrait'])
// La página 2 (landscape) debe ser más ancha que alta en dimensiones reales
expect(orientations[1]).toBe('landscape')
})
test('etapa-5-automatizado.pdf — 4 págs, portrait-landscape-portrait-portrait, marca InQ', async ({ page }) => {
await setupAndSimulate(page)
const outPath = resolve(OUT_DIR, 'etapa-5-automatizado.pdf')
await downloadPdf(page, 'automatizado', outPath)
const buffer = readFileSync(outPath)
const { numpages, text } = await parsePdf(buffer)
console.log(`Páginas automatizado: ${numpages}`)
expect(numpages).toBe(4)
validateBrandStrings(text, 'etapa-5-automatizado.pdf')
const orientations = await getPageOrientations(buffer)
console.log('Orientaciones automatizado:', orientations)
expect(orientations).toEqual(['portrait', 'landscape', 'portrait', 'portrait'])
})
test('etapa-5-roi.pdf — 5 págs todas portrait, sin regresiones', async ({ page }) => {
await setupAndSimulate(page)
const outPath = resolve(OUT_DIR, 'etapa-5-roi.pdf')
await downloadPdf(page, 'roi', outPath)
const buffer = readFileSync(outPath)
const { numpages, text } = await parsePdf(buffer)
console.log(`Páginas ROI: ${numpages}`)
expect(numpages).toBe(5)
validateBrandStrings(text, 'etapa-5-roi.pdf')
const orientations = await getPageOrientations(buffer)
console.log('Orientaciones ROI:', orientations)
expect(orientations).toEqual(['portrait', 'portrait', 'portrait', 'portrait', 'portrait'])
})

View File

@@ -0,0 +1,177 @@
/**
* 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'
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('/')
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'])
}
})

View File

@@ -0,0 +1,157 @@
/**
* Etapa 7 Sprint 1.5 — PDF ROI páginas 2-5 con identidad InQ.
*
* Validaciones mandatorias:
* 1. PDF ROI: 5 páginas, todas portrait
* 2. Página 5: "TRAYECTORIA DEL AHORRO ACUMULADO" presente (gráfico real, no placeholder)
* 3. Página 3: "COMPOSICIÓN DEL AHORRO", "TRAYECTORIA DEL AHORRO ACUMULADO" (uppercase)
* 4. Página 4: "NOTA METODOLOGICA" (sin caracteres Unicode)
* 5. Tamaño ROI > 30 KB (gráfico SVG + imagen gradiente)
* 6. Sin regresiones de marca: "InQ ROI", "Powered by InQuality"
* 7. PDFs Actual y Automatizado sin cambios: 4 páginas, ['portrait','landscape','portrait','portrait']
* 8. Tests previos >= 500
*/
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'
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 setupAndSimulate(page: import('@playwright/test').Page) {
await page.goto('/')
await page.locator('#bpmn-file-input').setInputFiles(resolve(BPMN_DIR, 'medium-with-gateways.bpmn'))
await page.waitForURL(/\/workspace\//, { timeout: 15_000 })
await page.waitForSelector('button:has-text("Simular")', { timeout: 10_000 })
await page.waitForTimeout(800)
for (const [id, cost, auto] of [['task_recv', 200, 20], ['task_score', 200, 20], ['task_analisis', 200, 20]] as [string, number, number][]) {
await page.locator(`[data-element-id="${id}"]`).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(cost))
await page.getByLabel(/Costo automatizado/i).fill(String(auto))
await page.getByLabel(/Tiempo automatizado/i).fill('10')
await page.getByRole('button', { name: /Guardar/i }).click()
await page.waitForTimeout(400)
}
await page.getByRole('tab', { name: /Global/i }).click()
await page.waitForTimeout(300)
await page.getByLabel(/Frecuencia anual/i).fill('5000')
await page.getByLabel(/Inversión en automatización/i).fill('80000')
await page.getByRole('button', { name: /Guardar/i }).click()
await page.waitForTimeout(400)
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, tab: 'actual' | 'automatizado' | 'roi', outPath: string) {
if (tab === 'actual') {
await page.getByRole('tab', { name: 'Actual' }).click()
await page.waitForTimeout(400)
} else if (tab === '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)
}
// ─── Tests ─────────────────────────────────────────────────────────────────────
test('etapa-7-roi.pdf — 5 págs, gráfico SVG real p.5, paleta InQ p.2-4', async ({ page }) => {
await setupAndSimulate(page)
const outPath = resolve(OUT_DIR, 'etapa-7-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 superar 30 KB').toBeGreaterThan(30)
const { numpages, text } = await parsePdf(buffer)
console.log(`Páginas: ${numpages}`)
console.log(`Texto primeros 600: ${text.slice(0, 600).replace(/\n/g, ' ')}`)
expect(numpages).toBe(5)
// Marcas globales
expect(text).toMatch(/InQ ROI/)
expect(text).toMatch(/Powered by InQuality/)
expect(text).not.toContain('Process Cost Platform')
expect(text).not.toContain('v0.1.0')
// Página 5: gráfico real (no placeholder)
expect(text, 'p.5 debe tener título del gráfico').toMatch(/TRAYECTORIA DEL AHORRO ACUMULADO/)
expect(text, 'p.5 no debe tener texto placeholder de Etapa 6').not.toContain('próxima versión del reporte')
// Página 3: títulos uppercase InQ
expect(text, 'p.3 debe tener sección COMPOSICIÓN').toMatch(/COMPOSICIÓN DEL AHORRO|COMPOSICION DEL AHORRO/)
// Página 4: nota metodológica
expect(text, 'p.4 debe tener nota metodológica').toMatch(/NOTA METODOLOGICA|NOTA METODOLÓGICA/)
const orientations = await getPageOrientations(buffer)
console.log('Orientaciones ROI:', orientations)
expect(orientations).toEqual(['portrait', 'portrait', 'portrait', 'portrait', 'portrait'])
})
test('etapa-7: PDFs Actual y Automatizado intactos (no-regresión)', async ({ page }) => {
await setupAndSimulate(page)
for (const [tab, label] of [['actual', 'actual'], ['automatizado', 'automatizado']] as ['actual' | 'automatizado', string][]) {
const outPath = resolve(OUT_DIR, `etapa-7-${label}.pdf`)
await downloadPdf(page, tab, outPath)
const buffer = readFileSync(outPath)
const { numpages, text } = await parsePdf(buffer)
console.log(`Páginas ${label}: ${numpages}`)
expect(numpages, `${label}: 4 páginas`).toBe(4)
expect(text).toMatch(/InQ ROI/)
expect(text).toMatch(/Powered by InQuality/)
const orientations = await getPageOrientations(buffer)
console.log(`Orientaciones ${label}:`, orientations)
expect(orientations).toEqual(['portrait', 'landscape', 'portrait', 'portrait'])
}
})

View File

@@ -0,0 +1,210 @@
/**
* Tests de orientación de páginas PDF — Etapa 5 Sprint 1.5.
*
* Verifica que:
* - PDF Actual/Automatizado: portrait → landscape → portrait
* - PDF ROI: todas portrait (no tiene página BPMN)
* - addPage se llama con el argumento correcto en cada caso
*
* Nota: estos tests usan mocks de jsPDF y verifican las llamadas a addPage.
* La orientación real del PDF se valida en los tests E2E (etapa-5-pdfs.spec.ts).
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
// ─── Mock de jsPDF ─────────────────────────────────────────────────────────────
const mockDoc = {
setProperties: vi.fn(),
setFont: vi.fn(),
setFontSize: vi.fn(),
setTextColor: vi.fn(),
setFillColor: vi.fn(),
setDrawColor: vi.fn(),
setLineWidth: vi.fn(),
text: vi.fn(),
rect: vi.fn(),
roundedRect: vi.fn(),
line: vi.fn(),
addImage: vi.fn(),
addPage: vi.fn(),
setPage: vi.fn(),
save: vi.fn(),
splitTextToSize: vi.fn().mockImplementation((t: string) => [t]),
lastAutoTable: { finalY: 150 },
internal: {
getNumberOfPages: vi.fn().mockReturnValue(3),
pageSize: {
getWidth: vi.fn().mockReturnValue(210),
getHeight: vi.fn().mockReturnValue(297),
},
},
}
vi.mock('jspdf', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function MockJsPDF(this: any) { return mockDoc }
return { jsPDF: MockJsPDF }
})
vi.mock('jspdf-autotable', () => ({
default: vi.fn(),
}))
import type { Process, Simulation } from '@/domain/types'
const mockProcess: Process = {
id: 'p1', name: 'Test Process',
clientName: 'Test Client',
bpmnXml: '', currency: 'USD',
overheadPercentage: 0.2,
annualFrequency: 1000, analysisHorizonYears: 3, automationInvestment: 50000,
createdAt: 0, updatedAt: 0,
}
const mockSimulation: Simulation = {
id: 'sim1', processId: 'p1',
executedAt: new Date('2026-05-17T10:00:00Z').getTime(),
result: {
totalCost: 1200, totalDirectCost: 1000, totalIndirectCost: 200,
totalTimeMinutes: 90,
perActivity: [{
activityId: 'a1', bpmnElementId: 'task1', activityName: 'Tarea 1',
expectedDirectCost: 1200, expectedIndirectCost: 200, expectedTotalCost: 1200,
percentOfTotal: 100, executionProbability: 1.0, expectedExecutions: 1.0,
executionTimeMinutes: 30, resourceCostBreakdown: [],
}],
perResource: [], warnings: [],
},
resultAutomated: {
totalCost: 300, totalDirectCost: 250, totalIndirectCost: 50,
totalTimeMinutes: 20,
perActivity: [{
activityId: 'a1', bpmnElementId: 'task1', activityName: 'Tarea 1',
expectedDirectCost: 300, expectedIndirectCost: 50, expectedTotalCost: 300,
percentOfTotal: 100, executionProbability: 1.0, expectedExecutions: 1.0,
executionTimeMinutes: 10, resourceCostBreakdown: [],
}],
perResource: [], warnings: [],
},
}
// ─── Tests ─────────────────────────────────────────────────────────────────────
describe('PDF orientation — Etapa 5', () => {
beforeEach(() => {
vi.clearAllMocks()
// Simular que getWidth/getHeight devuelven 210×297 por defecto (portrait)
// En landscape, jsPDF realmente cambia los valores internamente
mockDoc.internal.pageSize.getWidth.mockReturnValue(210)
mockDoc.internal.pageSize.getHeight.mockReturnValue(297)
})
describe('PDF Actual/Automatizado — mezcla portrait-landscape-portrait-portrait', () => {
it('llama addPage exactamente 3 veces para 4 páginas', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
await exportToPdf({
process: mockProcess,
simulation: mockSimulation,
resources: [],
heatmapImageData: null,
tab: 'actual',
})
expect(mockDoc.addPage).toHaveBeenCalledTimes(3)
})
it('primera addPage usa landscape (página BPMN)', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
await exportToPdf({
process: mockProcess,
simulation: mockSimulation,
resources: [],
heatmapImageData: null,
tab: 'actual',
})
const firstCall = mockDoc.addPage.mock.calls[0]
expect(firstCall[0]).toBe('a4')
expect(firstCall[1]).toBe('landscape')
})
it('segunda addPage usa portrait (análisis + tabla)', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
await exportToPdf({
process: mockProcess,
simulation: mockSimulation,
resources: [],
heatmapImageData: null,
tab: 'actual',
})
const secondCall = mockDoc.addPage.mock.calls[1]
expect(secondCall[0]).toBe('a4')
expect(secondCall[1]).toBe('portrait')
})
it('tercera addPage usa portrait (nota metodológica)', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
await exportToPdf({
process: mockProcess,
simulation: mockSimulation,
resources: [],
heatmapImageData: null,
tab: 'actual',
})
const thirdCall = mockDoc.addPage.mock.calls[2]
expect(thirdCall[0]).toBe('a4')
expect(thirdCall[1]).toBe('portrait')
})
it('tab automatizado también usa landscape en página 2', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
await exportToPdf({
process: mockProcess,
simulation: mockSimulation,
resources: [],
heatmapImageData: null,
tab: 'automatizado',
})
const firstCall = mockDoc.addPage.mock.calls[0]
expect(firstCall[1]).toBe('landscape')
})
})
describe('PDF ROI — todas portrait', () => {
it('llama addPage 4 veces para 5 páginas (todas sin landscape)', async () => {
mockDoc.internal.getNumberOfPages.mockReturnValue(5)
const { exportToPdf } = await import('@/lib/export/pdf-export')
await exportToPdf({
process: mockProcess,
simulation: mockSimulation,
resources: [],
heatmapImageData: null,
tab: 'roi',
activities: [],
})
expect(mockDoc.addPage).toHaveBeenCalledTimes(4)
// Ninguna llamada debe usar landscape
const hasLandscape = mockDoc.addPage.mock.calls.some(
(c: unknown[]) => c[1] === 'landscape'
)
expect(hasLandscape).toBe(false)
})
})
describe('drawHeatmapImage — dimensiones dinámicas', () => {
it('usa getWidth() del doc, no constante hardcodeada', async () => {
const { drawHeatmapImage } = await import('@/lib/export/pdf-sections')
// Simular página landscape (297mm wide)
mockDoc.internal.pageSize.getWidth.mockReturnValue(297)
mockDoc.internal.pageSize.getHeight.mockReturnValue(210)
const fakeDataUrl = 'data:image/jpeg;base64,/9j/test'
drawHeatmapImage(mockDoc as any, fakeDataUrl, 40)
expect(mockDoc.internal.pageSize.getWidth).toHaveBeenCalled()
// La imagen debe ser más ancha que en portrait (170mm)
const imgCallArgs = mockDoc.addImage.mock.calls[0]
// args: [dataUrl, format, x, y, width, height]
const imgWidth = imgCallArgs[4]
expect(imgWidth).toBeGreaterThan(170) // más ancho que portrait (297 - 40 = 257mm)
})
})
})

View File

@@ -0,0 +1,232 @@
/**
* Tests para la página 1 rediseñada del PDF ROI — Etapa 6 Sprint 1.5.
*
* Verifica:
* - drawRoiPage1 invoca los bloques clave (hero, top3, grid, banner)
* - exportToPdf ROI llama addPage 4 veces (5 páginas)
* - Ninguna página ROI usa landscape
* - El hero llama setFontSize(28) para la cifra principal
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
const mockDoc = {
setProperties: vi.fn(),
setFont: vi.fn(),
setFontSize: vi.fn(),
setTextColor: vi.fn(),
setFillColor: vi.fn(),
setDrawColor: vi.fn(),
setLineWidth: vi.fn(),
text: vi.fn(),
rect: vi.fn(),
roundedRect: vi.fn(),
line: vi.fn(),
addImage: vi.fn(),
addPage: vi.fn(),
setPage: vi.fn(),
save: vi.fn(),
splitTextToSize: vi.fn().mockImplementation((t: string) => [t]),
lastAutoTable: { finalY: 150 },
internal: {
getNumberOfPages: vi.fn().mockReturnValue(5),
pageSize: {
getWidth: vi.fn().mockReturnValue(210),
getHeight: vi.fn().mockReturnValue(297),
},
},
}
vi.mock('jspdf', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function MockJsPDF(this: any) { return mockDoc }
return { jsPDF: MockJsPDF }
})
vi.mock('jspdf-autotable', () => ({
default: vi.fn(),
}))
import type { Process, Simulation } from '@/domain/types'
import type { RoiResult } from '@/domain/roi'
const mockProcess: Process = {
id: 'p1', name: 'Test Process',
clientName: 'Test Client',
bpmnXml: '', currency: 'USD',
overheadPercentage: 0.2,
annualFrequency: 5000, analysisHorizonYears: 3, automationInvestment: 80000,
createdAt: 0, updatedAt: 0,
}
const mockSimulation: Simulation = {
id: 'sim1', processId: 'p1',
executedAt: new Date('2026-05-17T10:00:00Z').getTime(),
result: {
totalCost: 600, totalDirectCost: 500, totalIndirectCost: 100,
totalTimeMinutes: 90,
perActivity: [
{
activityId: 'a1', bpmnElementId: 'task1', activityName: 'Tarea Alpha',
expectedDirectCost: 400, expectedIndirectCost: 80, expectedTotalCost: 400,
percentOfTotal: 66, executionProbability: 1.0, expectedExecutions: 1.0,
executionTimeMinutes: 30, resourceCostBreakdown: [],
},
{
activityId: 'a2', bpmnElementId: 'task2', activityName: 'Tarea Beta',
expectedDirectCost: 200, expectedIndirectCost: 40, expectedTotalCost: 200,
percentOfTotal: 34, executionProbability: 1.0, expectedExecutions: 1.0,
executionTimeMinutes: 20, resourceCostBreakdown: [],
},
],
perResource: [], warnings: [],
},
resultAutomated: {
totalCost: 60, totalDirectCost: 50, totalIndirectCost: 10,
totalTimeMinutes: 10,
perActivity: [
{
activityId: 'a1', bpmnElementId: 'task1', activityName: 'Tarea Alpha',
expectedDirectCost: 40, expectedIndirectCost: 10, expectedTotalCost: 40,
percentOfTotal: 66, executionProbability: 1.0, expectedExecutions: 1.0,
executionTimeMinutes: 5, resourceCostBreakdown: [],
},
{
activityId: 'a2', bpmnElementId: 'task2', activityName: 'Tarea Beta',
expectedDirectCost: 20, expectedIndirectCost: 5, expectedTotalCost: 20,
percentOfTotal: 34, executionProbability: 1.0, expectedExecutions: 1.0,
executionTimeMinutes: 5, resourceCostBreakdown: [],
},
],
perResource: [], warnings: [],
},
}
const mockRoi: RoiResult = {
savingsPerExecution: 540,
savingsPerExecutionPercent: 90,
annualSavings: 2_700_000,
paybackMonths: 0.36,
paybackYears: 0.03,
cumulativeSavingsHorizon: 8_020_000,
breaksEvenInHorizon: true,
roiAnnualPercent: 3375,
}
describe('PDF ROI — Página 1 rediseñada (Etapa 6)', () => {
beforeEach(() => {
vi.clearAllMocks()
mockDoc.internal.pageSize.getWidth.mockReturnValue(210)
mockDoc.internal.pageSize.getHeight.mockReturnValue(297)
mockDoc.internal.getNumberOfPages.mockReturnValue(5)
})
it('drawRoiPage1 completa sin errores y llama text() múltiples veces', async () => {
const { drawRoiPage1 } = await import('@/lib/export/pdf-sections-roi')
expect(() =>
drawRoiPage1(
mockDoc as any,
mockProcess,
mockRoi,
mockSimulation.executedAt,
mockSimulation.result.perActivity,
mockSimulation.resultAutomated!.perActivity,
'USD'
)
).not.toThrow()
expect(mockDoc.text.mock.calls.length).toBeGreaterThan(5)
})
it('drawRoiPage1 incluye texto "InQ ROI" en el header denso', async () => {
const { drawRoiPage1 } = await import('@/lib/export/pdf-sections-roi')
drawRoiPage1(
mockDoc as any,
mockProcess,
mockRoi,
mockSimulation.executedAt,
mockSimulation.result.perActivity,
mockSimulation.resultAutomated!.perActivity,
'USD'
)
const textCalls = mockDoc.text.mock.calls.map((c: unknown[]) => c[0])
expect(textCalls).toContain('InQ ROI')
})
it('drawRoiPage1 incluye texto "TOP 3 ACTIVIDADES POR AHORRO"', async () => {
const { drawRoiPage1 } = await import('@/lib/export/pdf-sections-roi')
drawRoiPage1(
mockDoc as any,
mockProcess,
mockRoi,
mockSimulation.executedAt,
mockSimulation.result.perActivity,
mockSimulation.resultAutomated!.perActivity,
'USD'
)
const textCalls = mockDoc.text.mock.calls.map((c: unknown[]) => c[0])
expect(textCalls).toContain('TOP 3 ACTIVIDADES POR AHORRO')
})
it('drawRoiPage1 usa setFontSize(28) para la cifra del KPI Hero', async () => {
const { drawRoiPage1 } = await import('@/lib/export/pdf-sections-roi')
drawRoiPage1(
mockDoc as any,
mockProcess,
mockRoi,
mockSimulation.executedAt,
mockSimulation.result.perActivity,
mockSimulation.resultAutomated!.perActivity,
'USD'
)
const fontSizes = mockDoc.setFontSize.mock.calls.map((c: number[]) => c[0])
expect(fontSizes).toContain(28)
})
it('drawRoiPage1 dibuja rectángulos para la grilla 2x2 y barras top3', async () => {
const { drawRoiPage1 } = await import('@/lib/export/pdf-sections-roi')
drawRoiPage1(
mockDoc as any,
mockProcess,
mockRoi,
mockSimulation.executedAt,
mockSimulation.result.perActivity,
mockSimulation.resultAutomated!.perActivity,
'USD'
)
// roundedRect para cards de KPI secundarios (4 cards) + metadata strip
expect(mockDoc.roundedRect).toHaveBeenCalled()
// rect para elementos del banner y barras top3
expect(mockDoc.rect).toHaveBeenCalled()
})
it('exportToPdf ROI: 4 addPage calls (5 páginas) sin landscape', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
await exportToPdf({
process: mockProcess,
simulation: mockSimulation,
resources: [],
heatmapImageData: null,
tab: 'roi',
activities: [],
})
expect(mockDoc.addPage).toHaveBeenCalledTimes(4)
const hasLandscape = mockDoc.addPage.mock.calls.some(
(c: unknown[]) => c[1] === 'landscape'
)
expect(hasLandscape).toBe(false)
})
it('drawRoiPage1 dibuja nombre de actividad del top3 para actividades con ahorro', async () => {
const { drawRoiPage1 } = await import('@/lib/export/pdf-sections-roi')
drawRoiPage1(
mockDoc as any,
mockProcess,
mockRoi,
mockSimulation.executedAt,
mockSimulation.result.perActivity,
mockSimulation.resultAutomated!.perActivity,
'USD'
)
const textCalls = mockDoc.text.mock.calls.map((c: unknown[]) => c[0])
expect(textCalls).toContain('Tarea Alpha')
})
})

View File

@@ -0,0 +1,291 @@
/**
* Tests Etapa 7 — PDF ROI páginas 2-5 con identidad InQ.
*
* Verifica:
* - Tabla (p.2): headStyles con fondo naranja claro, texto #92400E
* - Análisis (p.3): títulos uppercase naranja oscuro, "COMPOSICIÓN DEL AHORRO"
* - Metodología (p.4): título uppercase naranja oscuro, caja contenedora
* - Gráfico SVG (p.5): líneas, áreas, marker payback, anotaciones
* - Coordenadas del gráfico: inicio negativo, payback en 0, final positivo
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
const mockDoc = {
setProperties: vi.fn(),
setFont: vi.fn(),
setFontSize: vi.fn(),
setTextColor: vi.fn(),
setFillColor: vi.fn(),
setDrawColor: vi.fn(),
setLineWidth: vi.fn(),
text: vi.fn(),
rect: vi.fn(),
roundedRect: vi.fn(),
line: vi.fn(),
addImage: vi.fn(),
addPage: vi.fn(),
setPage: vi.fn(),
save: vi.fn(),
splitTextToSize: vi.fn().mockImplementation((t: string) => [t]),
lastAutoTable: { finalY: 150 },
internal: {
getNumberOfPages: vi.fn().mockReturnValue(5),
pageSize: {
getWidth: vi.fn().mockReturnValue(210),
getHeight: vi.fn().mockReturnValue(297),
},
},
}
vi.mock('jspdf', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function MockJsPDF(this: any) { return mockDoc }
return { jsPDF: MockJsPDF }
})
vi.mock('jspdf-autotable', () => ({ default: vi.fn() }))
import type { Process, Simulation, Activity } from '@/domain/types'
import type { RoiResult } from '@/domain/roi'
const mockProcess: Process = {
id: 'p1', name: 'Proceso Test', clientName: 'Cliente Test',
bpmnXml: '', currency: 'USD', overheadPercentage: 0.2,
annualFrequency: 5000, analysisHorizonYears: 3, automationInvestment: 80000,
createdAt: 0, updatedAt: 0,
}
const mockRoi: RoiResult = {
savingsPerExecution: 540,
savingsPerExecutionPercent: 90,
annualSavings: 2_700_000,
paybackMonths: 0.356,
paybackYears: 0.03,
cumulativeSavingsHorizon: 8_020_000,
breaksEvenInHorizon: true,
roiAnnualPercent: 3375,
}
const mockSimulation: Simulation = {
id: 's1', processId: 'p1',
executedAt: new Date('2026-05-17T10:00:00Z').getTime(),
result: {
totalCost: 600, totalDirectCost: 500, totalIndirectCost: 100,
totalTimeMinutes: 90,
perActivity: [
{ activityId: 'a1', bpmnElementId: 't1', activityName: 'Tarea A',
expectedDirectCost: 400, expectedIndirectCost: 80, expectedTotalCost: 400,
percentOfTotal: 66, executionProbability: 1, expectedExecutions: 1,
executionTimeMinutes: 30, resourceCostBreakdown: [] },
{ activityId: 'a2', bpmnElementId: 't2', activityName: 'Tarea B',
expectedDirectCost: 200, expectedIndirectCost: 40, expectedTotalCost: 200,
percentOfTotal: 34, executionProbability: 1, expectedExecutions: 1,
executionTimeMinutes: 20, resourceCostBreakdown: [] },
],
perResource: [], warnings: [],
},
resultAutomated: {
totalCost: 60, totalDirectCost: 50, totalIndirectCost: 10,
totalTimeMinutes: 10,
perActivity: [
{ activityId: 'a1', bpmnElementId: 't1', activityName: 'Tarea A',
expectedDirectCost: 40, expectedIndirectCost: 10, expectedTotalCost: 40,
percentOfTotal: 66, executionProbability: 1, expectedExecutions: 1,
executionTimeMinutes: 5, resourceCostBreakdown: [] },
{ activityId: 'a2', bpmnElementId: 't2', activityName: 'Tarea B',
expectedDirectCost: 20, expectedIndirectCost: 5, expectedTotalCost: 20,
percentOfTotal: 34, executionProbability: 1, expectedExecutions: 1,
executionTimeMinutes: 5, resourceCostBreakdown: [] },
],
perResource: [], warnings: [],
},
}
const mockActivities: Activity[] = [
{ id: 'a1', processId: 'p1', bpmnElementId: 't1', name: 'Tarea A', type: 'task',
automatable: true, directCostFixed: 400, executionTimeMinutes: 30,
automatedCostFixed: 40, automatedTimeMinutes: 5, assignedResources: [] },
{ id: 'a2', processId: 'p1', bpmnElementId: 't2', name: 'Tarea B', type: 'task',
automatable: false, directCostFixed: 200, executionTimeMinutes: 20,
automatedCostFixed: 0, automatedTimeMinutes: 0, assignedResources: [] },
]
describe('PDF ROI — Etapa 7 páginas 2-5', () => {
beforeEach(() => {
vi.clearAllMocks()
mockDoc.internal.pageSize.getWidth.mockReturnValue(210)
mockDoc.internal.pageSize.getHeight.mockReturnValue(297)
mockDoc.internal.getNumberOfPages.mockReturnValue(5)
mockDoc.splitTextToSize.mockImplementation((t: string) => [t])
})
// ─── Página 2: tabla comparativa ────────────────────────────────────────────
describe('buildComparisonTableConfig — header paleta InQ', () => {
it('headStyles usa fondo #FFF8ED [255,248,237] (no naranja sólido)', async () => {
const { buildComparisonTableConfig } = await import('@/lib/export/pdf-sections-roi')
const config = buildComparisonTableConfig(
mockSimulation.result.perActivity,
mockSimulation.resultAutomated!.perActivity,
mockActivities, 'USD', 50
) as any
expect(config.headStyles.fillColor).toEqual([255, 248, 237])
})
it('headStyles textColor es #92400E [146,64,14]', async () => {
const { buildComparisonTableConfig } = await import('@/lib/export/pdf-sections-roi')
const config = buildComparisonTableConfig(
mockSimulation.result.perActivity,
mockSimulation.resultAutomated!.perActivity,
mockActivities, 'USD', 50
) as any
expect(config.headStyles.textColor).toEqual([146, 64, 14])
})
it('fila no-automatizable muestra "—" en columna Ahorro', async () => {
const { buildComparisonTableConfig } = await import('@/lib/export/pdf-sections-roi')
const config = buildComparisonTableConfig(
mockSimulation.result.perActivity,
mockSimulation.resultAutomated!.perActivity,
mockActivities, 'USD', 50
) as any
// Tarea B es no-automatizable — debe tener "—" en ahorro (columna índice 3)
const tareaB = (config.body as any[]).find((row: any[]) => row[0].content === 'Tarea B')
expect(tareaB).toBeDefined()
expect(tareaB[3].content).toBe('—')
expect(tareaB[4].content).toBe('—')
})
})
// ─── Página 3: análisis del ahorro ──────────────────────────────────────────
describe('drawRoiAnalysisPage — títulos InQ', () => {
it('dibuja "COMPOSICIÓN DEL AHORRO" (uppercase)', async () => {
const { drawRoiAnalysisPage } = await import('@/lib/export/pdf-sections-roi')
drawRoiAnalysisPage(mockDoc as any, mockRoi, mockProcess,
mockSimulation.result.perActivity, mockSimulation.resultAutomated!.perActivity,
mockActivities, 'USD', 50)
const textCalls = mockDoc.text.mock.calls.map((c: unknown[]) => c[0])
expect(textCalls).toContain('COMPOSICIÓN DEL AHORRO')
})
it('dibuja "TRAYECTORIA DEL AHORRO ACUMULADO" (uppercase)', async () => {
const { drawRoiAnalysisPage } = await import('@/lib/export/pdf-sections-roi')
drawRoiAnalysisPage(mockDoc as any, mockRoi, mockProcess,
mockSimulation.result.perActivity, mockSimulation.resultAutomated!.perActivity,
mockActivities, 'USD', 50)
const textCalls = mockDoc.text.mock.calls.map((c: unknown[]) => c[0])
expect(textCalls).toContain('TRAYECTORIA DEL AHORRO ACUMULADO')
})
it('dibuja nombre de actividad en bullets del top3', async () => {
const { drawRoiAnalysisPage } = await import('@/lib/export/pdf-sections-roi')
drawRoiAnalysisPage(mockDoc as any, mockRoi, mockProcess,
mockSimulation.result.perActivity, mockSimulation.resultAutomated!.perActivity,
mockActivities, 'USD', 50)
const textCalls = mockDoc.text.mock.calls.map((c: unknown[]) => String(c[0]))
const hasActivity = textCalls.some(t => t.includes('Tarea A') || t.includes('Tarea B'))
expect(hasActivity).toBe(true)
})
})
// ─── Página 4: nota metodológica ────────────────────────────────────────────
describe('drawRoiMethodologySection — paleta InQ', () => {
it('dibuja título "NOTA METODOLOGICA" (uppercase, sin caracteres Unicode)', async () => {
const { drawRoiMethodologySection } = await import('@/lib/export/pdf-sections-roi')
drawRoiMethodologySection(mockDoc as any, mockProcess, 50)
const textCalls = mockDoc.text.mock.calls.map((c: unknown[]) => c[0])
const hasTitle = textCalls.some(t => String(t).includes('NOTA METODOLOGICA'))
expect(hasTitle).toBe(true)
})
it('dibuja caja contenedora (rect con relleno slate-50)', async () => {
const { drawRoiMethodologySection } = await import('@/lib/export/pdf-sections-roi')
drawRoiMethodologySection(mockDoc as any, mockProcess, 50)
// setFillColor para [248,250,252] slate-50 debe haberse llamado
const fillCalls = mockDoc.setFillColor.mock.calls
const hasSlate50 = fillCalls.some((c: number[]) => c[0] === 248 && c[1] === 250 && c[2] === 252)
expect(hasSlate50).toBe(true)
})
it('dibuja al menos 5 secciones (text calls para títulos de fórmulas)', async () => {
const { drawRoiMethodologySection } = await import('@/lib/export/pdf-sections-roi')
drawRoiMethodologySection(mockDoc as any, mockProcess, 50)
expect(mockDoc.text.mock.calls.length).toBeGreaterThan(6)
})
})
// ─── Página 5: gráfico SVG nativo ───────────────────────────────────────────
describe('drawTrajectoryChart — coordenadas matemáticas', () => {
it('dibuja líneas (eje Y, eje X, segmentos de curva)', async () => {
const { drawTrajectoryChart } = await import('@/lib/export/pdf-sections-roi')
drawTrajectoryChart(mockDoc as any, mockRoi, mockProcess, 'USD', 20, 170, 50)
expect(mockDoc.line.mock.calls.length).toBeGreaterThan(10)
})
it('dibuja rectángulos de área (relleno para negativo y positivo)', async () => {
const { drawTrajectoryChart } = await import('@/lib/export/pdf-sections-roi')
drawTrajectoryChart(mockDoc as any, mockRoi, mockProcess, 'USD', 20, 170, 50)
expect(mockDoc.rect.mock.calls.length).toBeGreaterThan(5)
})
it('punto inicial (mes 0) tiene valor = -inversión', () => {
// Con investment=80000 y annualSavings=2700000, valueAt(0) = -80000
const investment = 80000, annualSavings = 2_700_000
const valueAt = (month: number) => -investment + (annualSavings / 12) * month
expect(valueAt(0)).toBe(-80000)
})
it('punto de payback tiene valor = 0', () => {
const investment = 80000, annualSavings = 2_700_000
const paybackMonths = investment / (annualSavings / 12) // = 0.3556
const valueAt = (month: number) => -investment + (annualSavings / 12) * month
expect(valueAt(paybackMonths)).toBeCloseTo(0, 5)
})
it('punto final (mes 36) tiene valor = cumulativeSavingsHorizon', () => {
const investment = 80000, annualSavings = 2_700_000
const horizonMonths = 36
const valueAt = (month: number) => -investment + (annualSavings / 12) * month
const finalValue = valueAt(horizonMonths)
// annualSavings * 3 - investment = 8100000 - 80000 = 8020000
expect(finalValue).toBeCloseTo(8_020_000, 0)
})
it('incluye texto de anotaciones (inversión y ahorro acumulado)', async () => {
const { drawTrajectoryChart } = await import('@/lib/export/pdf-sections-roi')
drawTrajectoryChart(mockDoc as any, mockRoi, mockProcess, 'USD', 20, 170, 50)
// splitTextToSize se llama con el texto de anotaciones
expect(mockDoc.splitTextToSize).toHaveBeenCalled()
// text() se llama para etiquetas de ejes y anotaciones
expect(mockDoc.text.mock.calls.length).toBeGreaterThan(4)
})
it('sin payback en horizonte: no dibuja marker de payback', async () => {
const { drawTrajectoryChart } = await import('@/lib/export/pdf-sections-roi')
const roiSinPayback: RoiResult = {
...mockRoi,
breaksEvenInHorizon: false,
paybackMonths: Infinity,
}
// Solo verificar que no lanza error
expect(() =>
drawTrajectoryChart(mockDoc as any, roiSinPayback, mockProcess, 'USD', 20, 170, 50)
).not.toThrow()
})
})
// ─── exportToPdf ROI integración ────────────────────────────────────────────
describe('exportToPdf ROI — integración Etapa 7', () => {
it('sigue siendo 5 páginas (4 addPage calls) sin regresión', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
await exportToPdf({
process: mockProcess, simulation: mockSimulation,
resources: [], heatmapImageData: null, tab: 'roi', activities: mockActivities,
})
expect(mockDoc.addPage).toHaveBeenCalledTimes(4)
})
})
})