Files
inq-roi-simulador-web/tests/lib/export/pdf-export-roi.test.ts
Marcos Benítez ee356e5de6
Some checks failed
/ Deploy to Cloudflare Pages (push) Has been cancelled
Etapa 7 ya estaba completamente ejecutada en esta sesión. Todo está en su lugar:
Fix A1 — isProfileLoaded en AuthContext 

useState(false) inicial
setIsProfileLoaded(true) si onAuthStateChange devuelve null (no hay usuario que sincronizar)
setIsProfileLoaded(false) en SIGNED_IN (resetea para el nuevo sync)
setIsProfileLoaded(true) en el finally del sync effect (después de syncProfileFromDB, éxito o error)
Fix A2 — Guard en LibraryPage 

if (!user || !isProfileLoaded) devuelve skeleton animado antes de cualquier contenido rol-dependiente
Fix A3 — Campo "cliente" read-only para client_editor 

GlobalSettingsPanel.tsx: <p> estático en lugar de <Input> cuando isClientRole
WorkspacePage.tsx: topbar muestra el valor sin input ni lápiz para client_editor
Fix B — Migración 016 + aplicada a DB 

Archivo supabase/migrations/016_add_simulations_update_policy.sql creado
Policy simulations_update confirmada activa en DB (pg_policies devuelve las 4 policies de simulations)
Fix adicional — 403 en POST /processes  (ejecutado en el turno inmediato anterior)

updateEditable() en process-repo.ts usa .update() en lugar de .upsert() para todos los paths de edición
Tests: 586 verdes, build limpio.

Lo que falta según el checklist del prompt es la validación visual del director (msebem@gmail.com en la app real). Eso requiere tu OK después de verificar en el navegador.

domain/types.ts — orgId: string | null agregado a Process (campo de DB ya existente, ahora mapeado en el dominio).

process-repo.ts — fromRow incluye orgId: (row.org_id as string | null) ?? null. Ambas queries (getById y getAll) usan select('*'), por lo que el campo viene gratis.

WorkspacePage.tsx:

Import supabase para el fetch de org name
Estado orgName + useEffect que hace SELECT name FROM organizations WHERE id = orgId cuando cambia currentProcess?.orgId
Variable isClientRole (solo client_editor — client_viewer ya fue redirigido)
backLabel: "Procesos" para client_editor, nombre de org (o "Volver" mientras carga) si hay orgId, "Biblioteca" si no hay
handleBack(): navega a /?org=<orgId> para admin con proceso de cliente, a / para el resto
El Home button + Tooltip fueron reemplazados por <Button variant="ghost" size="sm"> con ArrowLeft + backLabel
LibraryPage.tsx:

Import useSearch
Lee orgParam = useSearch({ from: '/' }) as { org?: string }
useEffect que, cuando orgParam está presente y la carga terminó, busca el proceso con p.orgId === orgParam, obtiene su groupId, y hace scrollIntoView al elemento group-{groupId}
Los GroupCards en el grid están ahora envueltos en <div id="group-{group.id}"> para ser alcanzables por el scroll
Tests — workspace-back-button.test.ts con 6 casos: admin+orgName, admin+orgName loading, admin sin org, member sin org, client_editor, client_viewer. Fixtures actualizados en 13 archivos con orgId: null. Mock de useSearch agregado en library-ui.test.tsx.
2026-07-07 14:12:10 -03:00

216 lines
9.6 KiB
TypeScript

/**
* Tests del export PDF para el tab "Comparación + ROI" (Sprint 1 — Etapa 4).
* También verifica sufijos de nombre de archivo para los 3 tabs.
* jsPDF y autotable se mockean.
*/
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((text: string) => [text]),
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 }
})
const mockAutoTable = vi.fn()
vi.mock('jspdf-autotable', () => ({ default: mockAutoTable }))
// ─── Fixtures ─────────────────────────────────────────────────────────────────
import type { Process, Simulation, Activity } from '@/domain/types'
const mockProcess: Process = {
id: 'p1', name: 'Proceso de Aprobación de Crédito', clientName: 'Banco XYZ',
bpmnXml: '', currency: 'USD', overheadPercentage: 0.2,
annualFrequency: 1200, analysisHorizonYears: 3, automationInvestment: 50_000,
createdAt: 0, updatedAt: 0,
groupId: null, tags: [], ownerId: 'test-user', updatedBy: 'test-user', orgId: null,
}
const perActivityActual = [
{
activityId: 'a1', bpmnElementId: 'task_recv', activityName: 'Recibir solicitud',
expectedDirectCost: 200, expectedIndirectCost: 40, expectedTotalCost: 240,
percentOfTotal: 60, executionProbability: 1.0, expectedExecutions: 1.0,
executionTimeMinutes: 60, resourceCostBreakdown: [],
},
{
activityId: 'a2', bpmnElementId: 'task_valid', activityName: 'Validar datos',
expectedDirectCost: 100, expectedIndirectCost: 20, expectedTotalCost: 120,
percentOfTotal: 40, executionProbability: 0.8, expectedExecutions: 0.8,
executionTimeMinutes: 30, resourceCostBreakdown: [],
},
]
const perActivityAutomated = [
{
activityId: 'a1', bpmnElementId: 'task_recv', activityName: 'Recibir solicitud',
expectedDirectCost: 20, expectedIndirectCost: 4, expectedTotalCost: 24,
percentOfTotal: 40, executionProbability: 1.0, expectedExecutions: 1.0,
executionTimeMinutes: 5, resourceCostBreakdown: [],
},
{
activityId: 'a2', bpmnElementId: 'task_valid', activityName: 'Validar datos',
expectedDirectCost: 100, expectedIndirectCost: 20, expectedTotalCost: 120,
percentOfTotal: 60, executionProbability: 0.8, expectedExecutions: 0.8,
executionTimeMinutes: 30, resourceCostBreakdown: [],
},
]
const mockSimulation: Simulation = {
id: 'sim1', processId: 'p1',
executedAt: new Date('2026-05-13T10:00:00Z').getTime(),
result: {
totalCost: 360, totalDirectCost: 300, totalIndirectCost: 60, totalTimeMinutes: 84,
perActivity: perActivityActual, perResource: [], warnings: [],
},
resultAutomated: {
totalCost: 144, totalDirectCost: 120, totalIndirectCost: 24, totalTimeMinutes: 8,
perActivity: perActivityAutomated, perResource: [], warnings: [],
},
}
const mockActivities: Activity[] = [
{
id: 'a1', processId: 'p1', bpmnElementId: 'task_recv', name: 'Recibir solicitud', type: 'task',
directCostFixed: 200, executionTimeMinutes: 60, assignedResources: [],
automatable: true, automatedCostFixed: 20, automatedTimeMinutes: 5,
automatedAssignedResources: [],
},
{
id: 'a2', processId: 'p1', bpmnElementId: 'task_valid', name: 'Validar datos', type: 'task',
directCostFixed: 100, executionTimeMinutes: 30, assignedResources: [],
automatable: false, automatedCostFixed: 0, automatedTimeMinutes: 0,
automatedAssignedResources: [],
},
]
// ─── Tests ────────────────────────────────────────────────────────────────────
describe('exportToPdf — tab=roi', () => {
beforeEach(() => { vi.clearAllMocks() })
it('no lanza error con tab=roi y parámetros válidos', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
await expect(
exportToPdf({ process: mockProcess, simulation: mockSimulation, resources: [], heatmapImageData: null, tab: 'roi', activities: mockActivities })
).resolves.not.toThrow()
})
it('tab=roi: llama a addPage al menos 3 veces (4 páginas)', 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.mock.calls.length).toBeGreaterThanOrEqual(3)
})
it('tab=roi: autoTable llamado con 6 columnas en el head (tabla comparativa)', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
await exportToPdf({ process: mockProcess, simulation: mockSimulation, resources: [], heatmapImageData: null, tab: 'roi', activities: mockActivities })
// autoTable puede llamarse múltiples veces; la tabla de comparación tiene 6 cols en head
const roiTableCall = mockAutoTable.mock.calls.find((call) => {
const head = call[1]?.head
return Array.isArray(head) && Array.isArray(head[0]) && head[0].length === 6
})
expect(roiTableCall).toBeDefined()
})
it('tab=roi: nombre de archivo termina en _roi.pdf', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
await exportToPdf({ process: mockProcess, simulation: mockSimulation, resources: [], heatmapImageData: null, tab: 'roi', activities: mockActivities })
const saveName = mockDoc.save.mock.calls[0][0] as string
expect(saveName).toMatch(/_roi\.pdf$/)
})
it('tab=roi: setProperties incluye "retorno de inversión" en subject', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
await exportToPdf({ process: mockProcess, simulation: mockSimulation, resources: [], heatmapImageData: null, tab: 'roi', activities: mockActivities })
expect(mockDoc.setProperties).toHaveBeenCalledWith(
expect.objectContaining({ subject: expect.stringContaining('retorno') })
)
})
it('tab=roi: NO llama a addImage (el tab ROI no tiene heatmap)', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
const fakeDataUrl = 'data:image/jpeg;base64,/9j/fake'
await exportToPdf({ process: mockProcess, simulation: mockSimulation, resources: [], heatmapImageData: fakeDataUrl, tab: 'roi', activities: mockActivities })
// El ROI PDF no embebe heatmap aunque se pase imageData
expect(mockDoc.addImage).not.toHaveBeenCalled()
})
it('tab=roi sin resultAutomated: no lanza error (usa result como fallback)', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
const simSinAuto = { ...mockSimulation, resultAutomated: undefined }
await expect(
exportToPdf({ process: mockProcess, simulation: simSinAuto, resources: [], heatmapImageData: null, tab: 'roi', activities: mockActivities })
).resolves.not.toThrow()
})
})
describe('exportToPdf — tab=actual', () => {
beforeEach(() => { vi.clearAllMocks() })
it('tab=actual: nombre de archivo termina en _actual.pdf', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
await exportToPdf({ process: mockProcess, simulation: mockSimulation, resources: [], heatmapImageData: null, tab: 'actual' })
expect(mockDoc.save.mock.calls[0][0]).toMatch(/_actual\.pdf$/)
})
it('tab=actual: contiene el proceso en el título (setProperties)', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
await exportToPdf({ process: mockProcess, simulation: mockSimulation, resources: [], heatmapImageData: null, tab: 'actual' })
expect(mockDoc.setProperties).toHaveBeenCalledWith(
expect.objectContaining({ title: expect.stringContaining('Proceso de Aprobación de Crédito') })
)
})
it('tab=undefined (default): se comporta como actual', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
await exportToPdf({ process: mockProcess, simulation: mockSimulation, resources: [], heatmapImageData: null })
expect(mockDoc.save.mock.calls[0][0]).toMatch(/_actual\.pdf$/)
})
})
describe('exportToPdf — tab=automatizado', () => {
beforeEach(() => { vi.clearAllMocks() })
it('tab=automatizado: nombre de archivo termina en _automatizado.pdf', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
await exportToPdf({ process: mockProcess, simulation: mockSimulation, resources: [], heatmapImageData: null, tab: 'automatizado' })
expect(mockDoc.save.mock.calls[0][0]).toMatch(/_automatizado\.pdf$/)
})
it('tab=automatizado: no lanza error', async () => {
const { exportToPdf } = await import('@/lib/export/pdf-export')
await expect(
exportToPdf({ process: mockProcess, simulation: mockSimulation, resources: [], heatmapImageData: null, tab: 'automatizado' })
).resolves.not.toThrow()
})
})