Some checks failed
/ Deploy to Cloudflare Pages (push) Has been cancelled
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.
234 lines
7.5 KiB
TypeScript
234 lines
7.5 KiB
TypeScript
/**
|
|
* 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,
|
|
groupId: null, tags: [], ownerId: 'test-user', updatedBy: 'test-user', orgId: null,
|
|
}
|
|
|
|
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(26) para la cifra del KPI Hero (Etapa 11: bajada de 28→26pt)', 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(26)
|
|
})
|
|
|
|
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')
|
|
})
|
|
})
|