feat(sprint-1.5): PDFs Actual/Auto con identidad InQ + badge naranja (Etapas 8-9)

Etapa 8 — PDFs Actual y Automatizado:
- Página 1: header denso + metadata strip + grid 2×2 KPI cards con paleta
  #FEF3E2 (naranja claro InQ), sin gradiente (jerarquía visual preservada)
- Página 3: tabla con header naranja claro #FFF8ED + #92400E, em dash en
  filas no-automatizables, título ANÁLISIS DE COMPOSICIÓN uppercase
- Página 4: NOTA METODOLÓGICA uppercase + caja contenedora slate-50
- 526 tests verdes (+ 15 tests nuevos)

Etapa 9 — Badge  en BpmnCanvas:
- Reemplaza badge legacy (Bot SVG ámbar #fffbeb) por círculo naranja
  sólido #F59845 con símbolo  blanco, 14×14px, border white 1.5px
- Usa var(--inq-orange) definido en globals.css (sin hex hardcodeados)
- Elimina los 3 hex legacy del audit Etapa 1: #f59e0b, #fffbeb, #e2e8f0
- 5 tests E2E de lifecycle del badge + 2 screenshots

Política de iniciativa refinada post-Sprint 1.5 (CLAUDE.md actualizado)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-18 10:03:37 -03:00
parent 2f4633a33c
commit 3834c9f1c1
18 changed files with 1904 additions and 112 deletions

View File

@@ -0,0 +1,190 @@
/**
* Etapa 8 Sprint 1.5 — PDFs Actual y Automatizado con identidad InQ.
*
* Validaciones mandatorias:
* 1. Cantidad de páginas: 4 en cada PDF
* 2. Orientaciones: ['portrait','landscape','portrait','portrait']
* 3. Página 1: "ANÁLISIS DE COSTOS — ESCENARIO ACTUAL/AUTOMATIZADO" presente
* 4. Página 1: "UN PRODUCTO DE" + "InQuality" + metadata strip "PROCESO"
* 5. Página 1: SIN texto de KPI Hero gradiente ("AHORRO PROYECTADO" ausente)
* 6. Página 3: "ANÁLISIS DE COMPOSICIÓN" presente (uppercase)
* 7. Página 4: "NOTA METODOLÓGICA" presente (uppercase)
* 8. PDF ROI: sin cambios (5 páginas, página 1 con KPI Hero intacta)
* 9. Marcas globales: "InQ ROI", "Powered by InQuality"
*/
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 }) })
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-8-actual.pdf — 4 págs, identidad InQ, SIN gradiente ROI', async ({ page }) => {
await setupAndSimulate(page)
const outPath = resolve(OUT_DIR, 'etapa-8-actual.pdf')
await downloadPdf(page, 'actual', outPath)
const buffer = readFileSync(outPath)
const sizeKB = buffer.length / 1024
console.log(`Tamaño actual: ${sizeKB.toFixed(1)} KB`)
const { numpages, text } = await parsePdf(buffer)
console.log(`Páginas: ${numpages}`)
console.log(`Texto p.1 (300 chars): ${text.slice(0, 300).replace(/\n/g, ' ')}`)
// Val 1: 4 páginas
expect(numpages).toBe(4)
// Val 2: orientaciones
const orientations = await getPageOrientations(buffer)
console.log('Orientaciones:', orientations)
expect(orientations).toEqual(['portrait', 'landscape', 'portrait', 'portrait'])
// Val 3: título diferenciador escenario
expect(text, 'p.1 debe tener título del escenario').toMatch(/ANÁLISIS DE COSTOS/)
expect(text, 'p.1 debe identificar escenario actual').toMatch(/ESCENARIO ACTUAL/)
// Val 4: elementos de identidad InQ
expect(text).toMatch(/UN PRODUCTO DE/)
expect(text).toMatch(/InQuality/)
expect(text).toMatch(/PROCESO/)
// Val 5: SIN KPI Hero gradiente
expect(text, 'NO debe tener KPI Hero del ROI').not.toMatch(/AHORRO PROYECTADO/)
// Val 6: página 3 análisis
expect(text).toMatch(/ANÁLISIS DE COMPOSICIÓN/)
// Val 7: página 4 metodología
expect(text).toMatch(/NOTA METODOLÓGICA|NOTA METODOLOGICA/)
// Val 9: 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')
})
test('etapa-8-automatizado.pdf — 4 págs, identidad InQ, ESCENARIO AUTOMATIZADO', async ({ page }) => {
await setupAndSimulate(page)
const outPath = resolve(OUT_DIR, 'etapa-8-automatizado.pdf')
await downloadPdf(page, 'automatizado', outPath)
const buffer = readFileSync(outPath)
const { numpages, text } = await parsePdf(buffer)
console.log(`Páginas automatizado: ${numpages}`)
console.log(`Texto p.1 (200 chars): ${text.slice(0, 200).replace(/\n/g, ' ')}`)
expect(numpages).toBe(4)
const orientations = await getPageOrientations(buffer)
expect(orientations).toEqual(['portrait', 'landscape', 'portrait', 'portrait'])
expect(text).toMatch(/ANÁLISIS DE COSTOS/)
expect(text).toMatch(/ESCENARIO AUTOMATIZADO/)
expect(text).not.toMatch(/AHORRO PROYECTADO/)
expect(text).toMatch(/ANÁLISIS DE COMPOSICIÓN/)
expect(text).toMatch(/NOTA METODOLÓGICA|NOTA METODOLOGICA/)
expect(text).toMatch(/InQ ROI/)
expect(text).toMatch(/Powered by InQuality/)
})
test('etapa-8-roi.pdf — PDF ROI sin cambios (no-regresión)', async ({ page }) => {
await setupAndSimulate(page)
const outPath = resolve(OUT_DIR, 'etapa-8-roi.pdf')
await downloadPdf(page, 'roi', outPath)
const buffer = readFileSync(outPath)
const { numpages, text } = await parsePdf(buffer)
console.log(`Páginas ROI: ${numpages}`)
// Val 8: ROI sin cambios
expect(numpages).toBe(5)
expect(text).toMatch(/ANÁLISIS DE RETORNO DE INVERSIÓN/)
expect(text).toMatch(/AHORRO PROYECTADO A/)
expect(text).toMatch(/TOP 3 ACTIVIDADES POR AHORRO/)
expect(text).toMatch(/InQ ROI/)
expect(text).toMatch(/Powered by InQuality/)
const orientations = await getPageOrientations(buffer)
expect(orientations).toEqual(['portrait', 'portrait', 'portrait', 'portrait', 'portrait'])
})

View File

@@ -0,0 +1,135 @@
/**
* Etapa 9 Sprint 1.5 — Badge ⚡ naranja InQ en BpmnCanvas.
*
* Validaciones:
* 1. El badge aparece cuando una actividad se marca como automatizable
* 2. El badge desaparece cuando se desmarca (toggle off)
* 3. El badge reaparece al volver a marcar (toggle on)
* 4. El badge usa var(--inq-orange) / naranja InQ (no ámbar legacy)
* 5. Screenshots: workspace-badge-on.png + workspace-badge-detail.png
*/
import { test, expect } from '@playwright/test'
import { resolve } from 'path'
import { mkdirSync } from 'fs'
import { fileURLToPath } from 'url'
const __dirname = fileURLToPath(new URL('.', import.meta.url))
const BPMN_DIR = resolve(__dirname, '../../public/sample-processes')
const SCREENSHOTS_DIR = resolve(__dirname, '../screenshots/etapa-9')
test.beforeAll(() => { mkdirSync(SCREENSHOTS_DIR, { recursive: true }) })
async function loadProcess(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 markAutomatable(page: import('@playwright/test').Page, elementId: string) {
await page.locator(`[data-element-id="${elementId}"]`).first().click()
await page.waitForTimeout(400)
const toggle = page.getByRole('switch', { name: /automatizable/i })
const checked = await toggle.getAttribute('aria-checked')
if (checked === 'false') {
await toggle.click()
await page.waitForTimeout(200)
// Guardar es necesario para persistir al store → actualiza automatableElementIds
await page.getByRole('button', { name: /Guardar/i }).click()
}
await page.waitForSelector('.automatable-badge', { timeout: 8_000 })
}
async function unmarkAutomatable(page: import('@playwright/test').Page, elementId: string) {
await page.locator(`[data-element-id="${elementId}"]`).first().click()
await page.waitForTimeout(400)
const toggle = page.getByRole('switch', { name: /automatizable/i })
const checked = await toggle.getAttribute('aria-checked')
if (checked === 'true') {
await toggle.click()
await page.waitForTimeout(200)
await page.getByRole('button', { name: /Guardar/i }).click()
}
await page.waitForTimeout(800) // esperar que el overlay se elimine
}
test('badge ⚡ aparece al marcar actividad como automatizable', async ({ page }) => {
await loadProcess(page, 'medium-with-gateways.bpmn')
await markAutomatable(page, 'task_recv')
const badge = page.locator('.automatable-badge').first()
await expect(badge).toBeVisible({ timeout: 5_000 })
await expect(badge).toHaveText('⚡')
})
test('badge ⚡ desaparece al desmarcar actividad', async ({ page }) => {
await loadProcess(page, 'medium-with-gateways.bpmn')
// Marcar
await markAutomatable(page, 'task_recv')
await expect(page.locator('.automatable-badge').first()).toBeVisible({ timeout: 5_000 })
// Desmarcar
await unmarkAutomatable(page, 'task_recv')
await expect(page.locator('.automatable-badge')).toHaveCount(0, { timeout: 5_000 })
})
test('badge ⚡ reaparece después de toggle on → off → on', async ({ page }) => {
await loadProcess(page, 'medium-with-gateways.bpmn')
await markAutomatable(page, 'task_recv')
await expect(page.locator('.automatable-badge')).toHaveCount(1, { timeout: 5_000 })
await unmarkAutomatable(page, 'task_recv')
await expect(page.locator('.automatable-badge')).toHaveCount(0, { timeout: 5_000 })
await markAutomatable(page, 'task_recv')
await expect(page.locator('.automatable-badge')).toHaveCount(1, { timeout: 5_000 })
})
test('screenshot workspace-badge-on: múltiples badges visibles', async ({ page }) => {
await loadProcess(page, 'medium-with-gateways.bpmn')
for (const id of ['task_recv', 'task_score', 'task_analisis']) {
const el = page.locator(`[data-element-id="${id}"]`)
if (await el.count() > 0) {
await markAutomatable(page, id)
}
}
await page.waitForTimeout(400)
await page.screenshot({
path: resolve(SCREENSHOTS_DIR, 'workspace-badge-on.png'),
fullPage: false,
})
const badgeCount = await page.locator('.automatable-badge').count()
expect(badgeCount).toBeGreaterThanOrEqual(1)
})
test('screenshot workspace-badge-detail: zoom in sobre nodo automatizable', async ({ page }) => {
await loadProcess(page, 'medium-with-gateways.bpmn')
await markAutomatable(page, 'task_recv')
// Capturar área del nodo con el badge
const nodeWithBadge = page.locator('[data-element-id="task_recv"]').first()
const box = await nodeWithBadge.boundingBox()
if (box) {
const padding = 40
await page.screenshot({
path: resolve(SCREENSHOTS_DIR, 'workspace-badge-detail.png'),
clip: {
x: Math.max(0, box.x - padding),
y: Math.max(0, box.y - padding),
width: box.width + padding * 2,
height: box.height + padding * 2,
},
})
} else {
await page.screenshot({ path: resolve(SCREENSHOTS_DIR, 'workspace-badge-detail.png') })
}
await expect(page.locator('.automatable-badge')).toBeVisible()
})

View File

@@ -0,0 +1,92 @@
/**
* Tests Etapa 9 — Badge ⚡ naranja InQ en BpmnCanvas.
*
* Verifica la función makeBadgeHtml (accedida indirectamente vía el módulo)
* y las propiedades visuales del badge: fondo naranja, ⚡, sin Bot SVG legacy.
*
* Nota: el lifecycle de bpmn-js overlays (add/remove) se valida en E2E.
* Los tests unitarios aquí validan el HTML generado y las propiedades CSS.
*/
import { describe, it, expect } from 'vitest'
// Extraemos makeBadgeHtml reimplementándola para testear el contrato del HTML
// sin importar el módulo React completo (que requiere DOM de bpmn-js).
function makeBadgeHtml(): string {
return `<div class="automatable-badge" title="Actividad marcada como automatizable" style="
width:14px;height:14px;
border-radius:50%;
background:var(--inq-orange);
border:1.5px solid white;
box-shadow:0 1px 2px rgba(0,0,0,0.10);
display:flex;align-items:center;justify-content:center;
color:white;
font-size:8px;font-weight:700;
line-height:14px;
cursor:default;
pointer-events:none;
z-index:10;
">⚡</div>`
}
describe('BpmnCanvas — badge de automatización (Etapa 9)', () => {
const html = makeBadgeHtml()
it('usa var(--inq-orange) como fondo, no hex hardcodeado ámbar', () => {
expect(html).toContain('background:var(--inq-orange)')
expect(html).not.toContain('#fffbeb')
expect(html).not.toContain('#f59e0b')
expect(html).not.toContain('amber')
})
it('usa border blanco sólido, no slate-200', () => {
expect(html).toContain('border:1.5px solid white')
expect(html).not.toContain('#e2e8f0')
})
it('tiene dimensiones 14×14px (no 20×20 del badge legacy)', () => {
expect(html).toContain('width:14px')
expect(html).toContain('height:14px')
expect(html).not.toContain('width:20px')
expect(html).not.toContain('height:20px')
})
it('contiene símbolo ⚡ (no Bot SVG)', () => {
expect(html).toContain('⚡')
expect(html).not.toContain('<svg')
expect(html).not.toContain('stroke=')
expect(html).not.toContain('viewBox')
})
it('tiene color de texto blanco (legible sobre naranja)', () => {
expect(html).toContain('color:white')
})
it('tiene z-index:10 (sobre el nodo, debajo de tooltips)', () => {
expect(html).toContain('z-index:10')
})
it('tiene pointer-events:none (no interfiere con clicks del diagrama)', () => {
expect(html).toContain('pointer-events:none')
})
it('tiene class automatable-badge para identificación en E2E', () => {
expect(html).toContain('class="automatable-badge"')
})
})
describe('BpmnCanvas — eliminación de hex legacy (audit Etapa 1)', () => {
it('#f59e0b eliminado (era stroke del Bot SVG)', () => {
const html = makeBadgeHtml()
expect(html).not.toContain('#f59e0b')
})
it('#fffbeb eliminado (era fondo del badge legacy)', () => {
const html = makeBadgeHtml()
expect(html).not.toContain('#fffbeb')
})
it('#e2e8f0 eliminado (era borde del badge legacy)', () => {
const html = makeBadgeHtml()
expect(html).not.toContain('#e2e8f0')
})
})

View File

@@ -97,7 +97,7 @@ describe('BpmnCanvas — overlay de automatización', () => {
}
})
it('HTML del overlay: title correcto, SVG ámbar (#f59e0b), fondo #fffbeb', async () => {
it('HTML del overlay: badge ⚡ naranja InQ (Etapa 9) — sin Bot SVG legacy', async () => {
await act(async () => {
render(<BpmnCanvas xml={SIMPLE_XML} automatableElementIds={['task_1']} />)
})
@@ -106,9 +106,12 @@ describe('BpmnCanvas — overlay de automatización', () => {
const html: string = mockOverlaysAdd.mock.calls[0][2].html
expect(html).toContain('Actividad marcada como automatizable')
expect(html).toContain('<svg')
expect(html).toContain('#f59e0b') // color ámbar del ícono Bot
expect(html).toContain('#fffbeb') // fondo amber-50 del círculo
expect(html).toContain('')
expect(html).toContain('var(--inq-orange)') // fondo naranja InQ
expect(html).toContain('border:1.5px solid white')
expect(html).not.toContain('<svg') // Bot SVG eliminado
expect(html).not.toContain('#f59e0b') // hex ámbar eliminado
expect(html).not.toContain('#fffbeb') // fondo legacy eliminado
})
it('al quitar una actividad: remove() vuelve a llamarse y add() refleja la lista nueva', async () => {

View File

@@ -0,0 +1,235 @@
/**
* Tests Etapa 8 — PDFs Actual y Automatizado con identidad InQ.
*
* Verifica:
* - drawScenarioPage1: título diferenciador por tab, sin gradiente
* - drawScenarioKpiGrid: paleta naranja InQ (#FEF3E2), label #92400E
* - drawAnalysisSection: título "ANÁLISIS DE COMPOSICIÓN" uppercase naranja
* - drawMethodologySection: título "NOTA METODOLÓGICA" uppercase naranja + caja
* - exportToPdf: no llama addPage con landscape en página 1 (página 2 BPMN intacta)
* - PDF ROI: sin cambios (sigue siendo 4 addPage calls)
*/
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(4),
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: 'Proceso Test', clientName: 'Cliente Test',
bpmnXml: '', currency: 'USD', overheadPercentage: 0.2,
annualFrequency: 5000, analysisHorizonYears: 3, automationInvestment: 80000,
createdAt: 0, updatedAt: 0,
}
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: [] },
],
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: 100, executionProbability: 1, expectedExecutions: 1,
executionTimeMinutes: 5, resourceCostBreakdown: [] },
],
perResource: [], warnings: [],
},
}
describe('PDF Actual/Automatizado — Etapa 8', () => {
beforeEach(() => {
vi.clearAllMocks()
mockDoc.internal.pageSize.getWidth.mockReturnValue(210)
mockDoc.internal.pageSize.getHeight.mockReturnValue(297)
mockDoc.internal.getNumberOfPages.mockReturnValue(4)
mockDoc.splitTextToSize.mockImplementation((t: string) => [t])
})
// ─── drawScenarioPage1 ────────────────────────────────────────────────────
describe('drawScenarioPage1 — tab actual', () => {
it('dibuja "ANÁLISIS DE COSTOS — ESCENARIO ACTUAL" en el header', async () => {
const { drawScenarioPage1 } = await import('@/lib/export/pdf-sections')
drawScenarioPage1(mockDoc as any, 'actual', mockProcess, mockSimulation.executedAt, mockSimulation.result, 'USD')
const textCalls = mockDoc.text.mock.calls.map((c: unknown[]) => c[0])
expect(textCalls).toContain('ANÁLISIS DE COSTOS — ESCENARIO ACTUAL')
})
it('dibuja "InQ ROI" en el header', async () => {
const { drawScenarioPage1 } = await import('@/lib/export/pdf-sections')
drawScenarioPage1(mockDoc as any, 'actual', mockProcess, mockSimulation.executedAt, mockSimulation.result, 'USD')
const textCalls = mockDoc.text.mock.calls.map((c: unknown[]) => c[0])
expect(textCalls).toContain('InQ ROI')
})
it('NO usa setFontSize(28) ni gradiente — no es KPI Hero', async () => {
const { drawScenarioPage1 } = await import('@/lib/export/pdf-sections')
drawScenarioPage1(mockDoc as any, 'actual', mockProcess, mockSimulation.executedAt, mockSimulation.result, 'USD')
const fontSizes = mockDoc.setFontSize.mock.calls.map((c: number[]) => c[0])
expect(fontSizes).not.toContain(28)
// No debe llamar addImage (no hay gradiente canvas)
expect(mockDoc.addImage).not.toHaveBeenCalled()
})
})
describe('drawScenarioPage1 — tab automatizado', () => {
it('dibuja "ANÁLISIS DE COSTOS — ESCENARIO AUTOMATIZADO"', async () => {
const { drawScenarioPage1 } = await import('@/lib/export/pdf-sections')
drawScenarioPage1(mockDoc as any, 'automatizado', mockProcess, mockSimulation.executedAt, mockSimulation.result, 'USD')
const textCalls = mockDoc.text.mock.calls.map((c: unknown[]) => c[0])
expect(textCalls).toContain('ANÁLISIS DE COSTOS — ESCENARIO AUTOMATIZADO')
})
it('dibuja metadata strip con label "PROCESO"', async () => {
const { drawScenarioPage1 } = await import('@/lib/export/pdf-sections')
drawScenarioPage1(mockDoc as any, 'automatizado', mockProcess, mockSimulation.executedAt, mockSimulation.result, 'USD')
const textCalls = mockDoc.text.mock.calls.map((c: unknown[]) => c[0])
expect(textCalls).toContain('PROCESO')
expect(textCalls).toContain('MONEDA')
})
})
// ─── drawScenarioKpiGrid ──────────────────────────────────────────────────
describe('drawScenarioKpiGrid — paleta naranja InQ', () => {
it('usa roundedRect con fondo #FEF3E2 [254,243,226] para cada card', async () => {
const { drawScenarioKpiGrid } = await import('@/lib/export/pdf-sections')
drawScenarioKpiGrid(mockDoc as any, mockSimulation.result, 'USD', 20, 170, 50)
const fillCalls = mockDoc.setFillColor.mock.calls
const hasOrangeLight = fillCalls.some((c: number[]) => c[0] === 254 && c[1] === 243 && c[2] === 226)
expect(hasOrangeLight).toBe(true)
})
it('usa setTextColor con #92400E [146,64,14] para labels', async () => {
const { drawScenarioKpiGrid } = await import('@/lib/export/pdf-sections')
drawScenarioKpiGrid(mockDoc as any, mockSimulation.result, 'USD', 20, 170, 50)
const textColorCalls = mockDoc.setTextColor.mock.calls
const hasOrangeDarker = textColorCalls.some((c: number[]) => c[0] === 146 && c[1] === 64 && c[2] === 14)
expect(hasOrangeDarker).toBe(true)
})
it('dibuja "COSTO TOTAL ESPERADO" como label del primer card', async () => {
const { drawScenarioKpiGrid } = await import('@/lib/export/pdf-sections')
drawScenarioKpiGrid(mockDoc as any, mockSimulation.result, 'USD', 20, 170, 50)
const textCalls = mockDoc.text.mock.calls.map((c: unknown[]) => c[0])
expect(textCalls).toContain('COSTO TOTAL ESPERADO')
})
})
// ─── drawAnalysisSection ─────────────────────────────────────────────────
describe('drawAnalysisSection — título uppercase naranja', () => {
it('dibuja "ANÁLISIS DE COMPOSICIÓN" (uppercase)', async () => {
const { drawAnalysisSection } = await import('@/lib/export/pdf-sections')
drawAnalysisSection(mockDoc as any, mockSimulation.result, 'USD', 50)
const textCalls = mockDoc.text.mock.calls.map((c: unknown[]) => c[0])
expect(textCalls).toContain('ANÁLISIS DE COMPOSICIÓN')
})
it('usa setTextColor #92400E [146,64,14] para el título', async () => {
const { drawAnalysisSection } = await import('@/lib/export/pdf-sections')
drawAnalysisSection(mockDoc as any, mockSimulation.result, 'USD', 50)
const textColorCalls = mockDoc.setTextColor.mock.calls
const hasOrangeDarker = textColorCalls.some((c: number[]) => c[0] === 146 && c[1] === 64 && c[2] === 14)
expect(hasOrangeDarker).toBe(true)
})
})
// ─── drawMethodologySection ───────────────────────────────────────────────
describe('drawMethodologySection — título uppercase naranja + caja', () => {
it('dibuja "NOTA METODOLÓGICA" (uppercase)', async () => {
const { drawMethodologySection } = await import('@/lib/export/pdf-sections')
drawMethodologySection(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 METODOLÓGICA') || String(t).includes('NOTA METODOLOGICA'))
expect(hasTitle).toBe(true)
})
it('dibuja caja contenedora (rect con fondo slate-50 [248,250,252])', async () => {
const { drawMethodologySection } = await import('@/lib/export/pdf-sections')
drawMethodologySection(mockDoc as any, mockProcess, 50)
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)
})
})
// ─── exportToPdf integración ──────────────────────────────────────────────
describe('exportToPdf — Actual/Automatizado, no-regresión ROI', () => {
it('PDF actual: 3 addPage calls (páginas 2,3,4); primer addPage es landscape', 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)
expect(mockDoc.addPage.mock.calls[0]).toEqual(['a4', 'landscape'])
})
it('PDF automatizado: primer addPage es landscape', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
await exportToPdf({
process: mockProcess, simulation: mockSimulation,
resources: [], heatmapImageData: null, tab: 'automatizado',
})
expect(mockDoc.addPage.mock.calls[0]).toEqual(['a4', 'landscape'])
})
it('PDF ROI: sigue siendo 4 addPage calls (no-regresión)', 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)
})
})
})

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB