Files
inq-roi-simulador-web/tests/lib/export/measure-sizes.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

92 lines
3.6 KiB
TypeScript

/**
* Medición de tamaños de CSV para los 3 sample BPMNs.
* Este test calcula el tamaño en bytes del CSV generado para cada BPMN.
*/
import { describe, it } from 'vitest'
import { readFileSync } from 'fs'
import { resolve } from 'path'
import { v4 as uuidv4 } from 'uuid'
import { parseBpmnXml, extractActivityElements, extractGatewayElements } from '@/domain/bpmn-parser'
import { runSimulation } from '@/domain/simulation'
import { generateCsvContent } from '@/lib/export/csv-export'
import { bpmnTypeToGatewayType } from '@/domain/types'
import type { Activity, GatewayConfig, SimulationInput, Process, Simulation } from '@/domain/types'
function loadBpmn(name: string): string {
return readFileSync(resolve(__dirname, '../../../public/sample-processes', name), 'utf-8')
}
function buildInput(xml: string, directCost: number): SimulationInput {
const graph = parseBpmnXml(xml)
const actEls = extractActivityElements(graph)
const gwEls = extractGatewayElements(graph)
const processId = 'measure-proc'
const activities = new Map<string, Activity>(
actEls.map((el) => [el.bpmnElementId, {
id: uuidv4(), processId, bpmnElementId: el.bpmnElementId, name: el.name,
type: el.type, directCostFixed: directCost, executionTimeMinutes: 30, assignedResources: [],
automatable: false, automatedCostFixed: 0, automatedTimeMinutes: 0, automatedAssignedResources: [],
}])
)
const gateways = new Map<string, GatewayConfig>(
gwEls.map((el) => {
const gwType = bpmnTypeToGatewayType(el.gatewayType as any)
return [el.bpmnElementId, {
id: uuidv4(), processId, bpmnElementId: el.bpmnElementId, gatewayType: gwType,
branches: el.outgoing.map((flowId) => ({
flowId, targetElementId: graph.flows.get(flowId)?.targetRef ?? '',
probability: gwType === 'parallel' ? 1.0 : 1 / el.outgoing.length,
})),
}]
})
)
return {
processXml: xml, activities, gateways, resources: new Map(),
globalSettings: { currency: 'USD', overheadPercentage: 0.2 },
}
}
describe('Medición de tamaños de CSV — 3 sample BPMNs', () => {
const BPMNS = [
{ file: 'simple-linear.bpmn', name: 'Proceso Lineal Simple', client: 'Demo' },
{ file: 'medium-with-gateways.bpmn', name: 'Aprobación de Crédito', client: 'Banco ABC' },
{ file: 'complex-with-loop.bpmn', name: 'Control de Calidad', client: 'Empresa XYZ' },
]
for (const bpmn of BPMNS) {
it(`${bpmn.file}: mide tamaño del CSV`, () => {
const xml = loadBpmn(bpmn.file)
const result = runSimulation(buildInput(xml, 1000))
const process: Process = {
id: 'p1', name: bpmn.name, clientName: bpmn.client,
bpmnXml: xml, currency: 'USD', overheadPercentage: 0.2,
annualFrequency: 1000, analysisHorizonYears: 3, automationInvestment: 0,
createdAt: 0, updatedAt: 0,
groupId: null, tags: [], ownerId: 'test-user', updatedBy: 'test-user', orgId: null,
}
const simulation: Simulation = {
id: 's1', processId: 'p1',
executedAt: new Date('2026-05-13T12:00:00Z').getTime(),
result,
}
const csv = generateCsvContent({ process, simulation, resources: [] })
const bytes = new TextEncoder().encode(csv).length
console.log(`\n📊 ${bpmn.file}`)
console.log(` Actividades: ${result.perActivity.length}`)
console.log(` CSV size: ${bytes} bytes (${(bytes / 1024).toFixed(1)} KB)`)
console.log(` CSV líneas de datos: ${result.perActivity.length} + 1 header + 7 meta`)
console.log(` Costo total: $${result.totalCost.toFixed(2)}`)
// El CSV no debe ser vacío
expect(bytes).toBeGreaterThan(100)
})
}
})