feat: MVP Fase 0 — Process Cost Platform v0.1.0

Plataforma completa de análisis de costos operativos basada en BPMN 2.0.

Funcionalidades incluidas:
- Import de archivos BPMN 2.0 por drag & drop + 3 procesos de ejemplo
- Visualización read-only del diagrama (bpmn-js)
- Configuración de actividades (costo, tiempo, recursos asignados)
- CRUD de recursos (rol, persona, sistema, equipo, insumo)
- Configuración global (moneda, overhead %, nombre, cliente)
- Motor de simulación determinístico agregado con propagación de gateways XOR/AND
- Reporte visual con mapa de calor en dos modos (relativo/absoluto)
- Gráficos: KPIs, top actividades, composición, costo por recurso
- Export PDF (jsPDF + html2canvas) y CSV (papaparse)
- Persistencia en IndexedDB (Dexie)
- 268 tests unitarios/integración + 6 E2E con Playwright
- Deploy: https://process-cost-platform.pages.dev

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-14 01:58:40 -03:00
commit bed161c92a
97 changed files with 19638 additions and 0 deletions

View File

@@ -0,0 +1,251 @@
/**
* Tests permanentes del parser BPMN.
* Protegen contra regresiones cuando se modifique parseBpmnXml,
* extractActivityElements o extractGatewayElements.
*
* Conteos esperados (fijos, derivados del XML de los sample BPMNs):
*
* simple-linear.bpmn
* nodes total : 7 (1 startEvent + 5 tasks + 1 endEvent)
* flows total : 6
* tasks : 5
* gateways : 0
* events : 2
* divergentes : 0
*
* medium-with-gateways.bpmn
* nodes total : 17 (1 start + 11 tasks + 4 gateways + 1 end)
* flows total : 19
* tasks : 11
* gateways : 4 (gw_datos XOR, gw_parallel_split AND, gw_parallel_join AND, gw_decision XOR)
* events : 2
* divergentes : 3 (gw_datos:2, gw_parallel_split:2, gw_decision:2)
*
* complex-with-loop.bpmn
* nodes total : 13 (1 start + 9 tasks + 2 gateways + 1 end)
* flows total : 14
* tasks : 9
* gateways : 2 (gw_resultado XOR 3-salidas, gw_merge XOR convergente)
* events : 2
* divergentes : 1 (gw_resultado:3)
*/
import { describe, it, expect } from 'vitest'
import { readFileSync } from 'fs'
import { resolve } from 'path'
import {
parseBpmnXml,
extractActivityElements,
extractGatewayElements,
BpmnParseError,
} from '@/domain/bpmn-parser'
import { isTaskNode, isGatewayNode } from '@/domain/types'
function loadSample(name: string): string {
return readFileSync(resolve(__dirname, '../../public/sample-processes', name), 'utf-8')
}
function countByCategory(graph: ReturnType<typeof parseBpmnXml>) {
let tasks = 0, gateways = 0, events = 0, unknown = 0
for (const node of graph.nodes.values()) {
if (isTaskNode(node.type)) tasks++
else if (isGatewayNode(node.type)) gateways++
else if (['startEvent', 'endEvent', 'intermediateThrowEvent', 'intermediateCatchEvent'].includes(node.type)) events++
else unknown++
}
return { tasks, gateways, events, unknown }
}
// ─── simple-linear.bpmn ──────────────────────────────────────────────────────
describe('parser / simple-linear.bpmn', () => {
const xml = loadSample('simple-linear.bpmn')
it('parsea sin lanzar error', () => {
expect(() => parseBpmnXml(xml)).not.toThrow()
})
it('grafo: 7 nodos y 6 flujos de secuencia', () => {
const g = parseBpmnXml(xml)
expect(g.nodes.size).toBe(7)
expect(g.flows.size).toBe(6)
})
it('grafo: 5 tasks | 0 gateways | 2 eventos', () => {
const g = parseBpmnXml(xml)
const { tasks, gateways, events, unknown } = countByCategory(g)
expect(tasks).toBe(5)
expect(gateways).toBe(0)
expect(events).toBe(2)
expect(unknown).toBe(0)
})
it('1 startEvent detectado como punto de entrada', () => {
const g = parseBpmnXml(xml)
expect(g.startEventIds).toHaveLength(1)
expect(g.startEventIds[0]).toBe('start')
})
it('extractActivityElements: 5 actividades con nombres correctos', () => {
const g = parseBpmnXml(xml)
const acts = extractActivityElements(g)
expect(acts).toHaveLength(5)
const names = acts.map((a) => a.name)
expect(names).toContain('Recibir solicitud')
expect(names).toContain('Verificar documentación')
expect(names).toContain('Procesar pedido')
expect(names).toContain('Notificar al cliente')
expect(names).toContain('Archivar expediente')
acts.forEach((a) => expect(a.type).toBe('task'))
})
it('extractGatewayElements: 0 gateways divergentes (proceso lineal)', () => {
const g = parseBpmnXml(xml)
const gws = extractGatewayElements(g)
expect(gws).toHaveLength(0)
})
})
// ─── medium-with-gateways.bpmn ───────────────────────────────────────────────
describe('parser / medium-with-gateways.bpmn', () => {
const xml = loadSample('medium-with-gateways.bpmn')
it('parsea sin lanzar error', () => {
expect(() => parseBpmnXml(xml)).not.toThrow()
})
it('grafo: 17 nodos y 19 flujos de secuencia', () => {
const g = parseBpmnXml(xml)
expect(g.nodes.size).toBe(17)
expect(g.flows.size).toBe(19)
})
it('grafo: 11 tasks | 4 gateways | 2 eventos', () => {
const g = parseBpmnXml(xml)
const { tasks, gateways, events, unknown } = countByCategory(g)
expect(tasks).toBe(11)
expect(gateways).toBe(4)
expect(events).toBe(2)
expect(unknown).toBe(0)
})
it('extractActivityElements: exactamente 11 actividades', () => {
const g = parseBpmnXml(xml)
const acts = extractActivityElements(g)
expect(acts).toHaveLength(11)
const ids = acts.map((a) => a.bpmnElementId)
expect(ids).toContain('task_recv')
expect(ids).toContain('task_valid')
expect(ids).toContain('task_pedir_docs')
expect(ids).toContain('task_score')
expect(ids).toContain('task_bureau')
expect(ids).toContain('task_empleador')
expect(ids).toContain('task_analisis')
expect(ids).toContain('task_aprobar')
expect(ids).toContain('task_rechazar')
expect(ids).toContain('task_desembolso')
expect(ids).toContain('task_archivo')
})
it('extractGatewayElements: 3 gateways divergentes con salidas correctas', () => {
const g = parseBpmnXml(xml)
const gws = extractGatewayElements(g)
expect(gws).toHaveLength(3)
const byId = Object.fromEntries(gws.map((gw) => [gw.bpmnElementId, gw]))
// gw_datos: XOR con 2 salidas
expect(byId['gw_datos']).toBeDefined()
expect(byId['gw_datos'].outgoing).toHaveLength(2)
expect(byId['gw_datos'].gatewayType).toBe('exclusiveGateway')
// gw_parallel_split: AND con 2 salidas
expect(byId['gw_parallel_split']).toBeDefined()
expect(byId['gw_parallel_split'].outgoing).toHaveLength(2)
expect(byId['gw_parallel_split'].gatewayType).toBe('parallelGateway')
// gw_decision: XOR con 2 salidas
expect(byId['gw_decision']).toBeDefined()
expect(byId['gw_decision'].outgoing).toHaveLength(2)
expect(byId['gw_decision'].gatewayType).toBe('exclusiveGateway')
// gw_parallel_join NO debe estar (convergente: 1 salida)
expect(byId['gw_parallel_join']).toBeUndefined()
})
})
// ─── complex-with-loop.bpmn ───────────────────────────────────────────────────
describe('parser / complex-with-loop.bpmn', () => {
const xml = loadSample('complex-with-loop.bpmn')
it('parsea sin lanzar error', () => {
expect(() => parseBpmnXml(xml)).not.toThrow()
})
it('grafo: 13 nodos y 14 flujos de secuencia', () => {
const g = parseBpmnXml(xml)
expect(g.nodes.size).toBe(13)
expect(g.flows.size).toBe(14)
})
it('grafo: 9 tasks | 2 gateways | 2 eventos', () => {
const g = parseBpmnXml(xml)
const { tasks, gateways, events, unknown } = countByCategory(g)
expect(tasks).toBe(9)
expect(gateways).toBe(2)
expect(events).toBe(2)
expect(unknown).toBe(0)
})
it('extractActivityElements: exactamente 9 actividades', () => {
const g = parseBpmnXml(xml)
const acts = extractActivityElements(g)
expect(acts).toHaveLength(9)
const ids = acts.map((a) => a.bpmnElementId)
expect(ids).toContain('task_preparar')
expect(ids).toContain('task_inspeccion')
expect(ids).toContain('task_documentar')
expect(ids).toContain('task_correcciones')
expect(ids).toContain('task_rechazo')
expect(ids).toContain('task_informe_rechazo')
expect(ids).toContain('task_entrega')
expect(ids).toContain('task_certificado')
expect(ids).toContain('task_registro')
})
it('extractGatewayElements: 1 gateway divergente (gw_resultado con 3 salidas)', () => {
const g = parseBpmnXml(xml)
const gws = extractGatewayElements(g)
expect(gws).toHaveLength(1)
expect(gws[0].bpmnElementId).toBe('gw_resultado')
expect(gws[0].outgoing).toHaveLength(3)
expect(gws[0].gatewayType).toBe('exclusiveGateway')
// gw_merge es convergente (1 salida) — no debe aparecer
})
it('el flujo de loop existe en el grafo (correc_inspeccion apunta a task_inspeccion)', () => {
const g = parseBpmnXml(xml)
const loopFlow = g.flows.get('flow_correc_inspeccion')
expect(loopFlow).toBeDefined()
expect(loopFlow!.sourceRef).toBe('task_correcciones')
expect(loopFlow!.targetRef).toBe('task_inspeccion')
})
})
// ─── Casos de error del parser ────────────────────────────────────────────────
describe('parser / manejo de errores', () => {
it('lanza BpmnParseError si el XML no tiene elemento <process>', () => {
expect(() => parseBpmnXml('<definitions><notAProcess/></definitions>')).toThrow(BpmnParseError)
})
it('lanza BpmnParseError si el XML está malformado', () => {
expect(() => parseBpmnXml('<definitions><process id="p"><unclosed')).toThrow(BpmnParseError)
})
it('lanza BpmnParseError si el proceso no tiene startEvent', () => {
const xml = `<?xml version="1.0"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL">
<process id="p"><task id="t1" name="Solo tarea"/></process>
</definitions>`
expect(() => parseBpmnXml(xml)).toThrow(BpmnParseError)
})
})

View File

@@ -0,0 +1,157 @@
/**
* Tests permanentes de validación de gateways.
* Protegen las reglas de negocio: XOR debe sumar 1, AND no tiene probs editables.
*/
import { describe, it, expect } from 'vitest'
import { isXorSumValid } from '@/features/workspace/GatewayPanel'
import { runSimulation } from '@/domain/simulation'
import type { GatewayConfig, SimulationInput, Activity } from '@/domain/types'
import { v4 as uuidv4 } from 'uuid'
import { readFileSync } from 'fs'
import { resolve } from 'path'
function makeBranches(probs: number[]): GatewayConfig['branches'] {
return probs.map((p, i) => ({ flowId: `f${i}`, targetElementId: `t${i}`, probability: p }))
}
function makeXorGateway(probs: number[]): GatewayConfig {
return {
id: uuidv4(), processId: 'p', bpmnElementId: 'gw1',
gatewayType: 'exclusive',
branches: makeBranches(probs),
}
}
function makeParallelGateway(n: number): GatewayConfig {
return {
id: uuidv4(), processId: 'p', bpmnElementId: 'gw1',
gatewayType: 'parallel',
branches: makeBranches(Array(n).fill(1.0)),
}
}
// ─── isXorSumValid ────────────────────────────────────────────────────────────
describe('isXorSumValid', () => {
it('válido: suma exactamente 1.0', () => {
expect(isXorSumValid(makeXorGateway([0.6, 0.4]))).toBe(true)
})
it('válido: suma = 1.0 con 3 ramas (0.5 + 0.3 + 0.2)', () => {
expect(isXorSumValid(makeXorGateway([0.5, 0.3, 0.2]))).toBe(true)
})
it('válido: tolerancia de 0.5% — 0.999 se acepta como 1.0', () => {
expect(isXorSumValid(makeXorGateway([0.499, 0.501]))).toBe(true)
})
it('inválido: suma = 0.5 (faltan 50%)', () => {
expect(isXorSumValid(makeXorGateway([0.3, 0.2]))).toBe(false)
})
it('inválido: suma = 1.5 (excede 100%)', () => {
expect(isXorSumValid(makeXorGateway([0.8, 0.7]))).toBe(false)
})
it('inválido: suma = 0 (gateways sin configurar)', () => {
expect(isXorSumValid(makeXorGateway([0, 0]))).toBe(false)
})
it('gateway paralelo siempre válido (no aplica regla de suma)', () => {
expect(isXorSumValid(makeParallelGateway(2))).toBe(true)
expect(isXorSumValid(makeParallelGateway(3))).toBe(true)
})
it('gateway inclusivo tratado como exclusivo — aplica regla de suma', () => {
const gw: GatewayConfig = { ...makeXorGateway([0.6, 0.4]), gatewayType: 'inclusive' }
// inclusive usa isXorSumValid solo para el display; el motor lo trata igual
// Aquí verificamos que la función no lanza para gateways inclusive
expect(() => isXorSumValid(gw)).not.toThrow()
})
})
// ─── Motor: gateways con distribución 70/30 sobre medium BPMN ────────────────
describe('motor / propagación con GatewayConfig correcta', () => {
const xml = readFileSync(resolve(__dirname, '../../public/sample-processes/medium-with-gateways.bpmn'), 'utf-8')
function buildSimInput(datosProbs: [number, number], decisionProbs: [number, number]): SimulationInput {
const processId = 'gv-test'
const actIds = ['task_recv', 'task_valid', 'task_pedir_docs', 'task_score',
'task_bureau', 'task_empleador', 'task_analisis',
'task_aprobar', 'task_rechazar', 'task_desembolso', 'task_archivo']
const activities = new Map<string, Activity>(
actIds.map((id) => [id, {
id: uuidv4(), processId, bpmnElementId: id, name: id,
type: 'task', directCostFixed: 100, executionTimeMinutes: 30, assignedResources: [],
}])
)
const gateways = new Map<string, GatewayConfig>([
['gw_datos', {
id: uuidv4(), processId, bpmnElementId: 'gw_datos', gatewayType: 'exclusive',
branches: [
{ flowId: 'flow_gw1_completo', targetElementId: 'task_score', probability: datosProbs[0] },
{ flowId: 'flow_gw1_incompleto', targetElementId: 'task_pedir_docs', probability: datosProbs[1] },
],
}],
['gw_parallel_split', {
id: uuidv4(), processId, bpmnElementId: 'gw_parallel_split', gatewayType: 'parallel',
branches: [
{ flowId: 'flow_para_bureau', targetElementId: 'task_bureau', probability: 1.0 },
{ flowId: 'flow_para_empleador', targetElementId: 'task_empleador', probability: 1.0 },
],
}],
['gw_decision', {
id: uuidv4(), processId, bpmnElementId: 'gw_decision', gatewayType: 'exclusive',
branches: [
{ flowId: 'flow_dec_aprobado', targetElementId: 'task_aprobar', probability: decisionProbs[0] },
{ flowId: 'flow_dec_rechazado', targetElementId: 'task_rechazar', probability: decisionProbs[1] },
],
}],
])
return { processXml: xml, activities, gateways, resources: new Map(), globalSettings: { currency: 'USD', overheadPercentage: 0 } }
}
it('rama "completo" 70% → task_score tiene prob ≈ 0.7', () => {
const result = runSimulation(buildSimInput([0.7, 0.3], [0.8, 0.2]))
const score = result.perActivity.find((a) => a.bpmnElementId === 'task_score')
expect(score?.executionProbability).toBeCloseTo(0.7, 2)
})
it('rama "incompleto" 30% → task_pedir_docs tiene prob ≈ 0.3', () => {
const result = runSimulation(buildSimInput([0.7, 0.3], [0.8, 0.2]))
const pedir = result.perActivity.find((a) => a.bpmnElementId === 'task_pedir_docs')
expect(pedir?.executionProbability).toBeCloseTo(0.3, 2)
})
it('task_aprobar tiene prob = 0.8 (task_analisis converge ambos caminos a 1.0, luego 80% decision)', () => {
// task_analisis recibe:
// - camino completo (70%): AND join correcto → 0.7
// - camino incompleto (30%): task_pedir_docs → 0.3
// - suma XOR: 0.7 + 0.3 = 1.0
// gw_decision → task_aprobar: 1.0 × 0.8 = 0.8
const result = runSimulation(buildSimInput([0.7, 0.3], [0.8, 0.2]))
const analisis = result.perActivity.find((a) => a.bpmnElementId === 'task_analisis')
const aprobar = result.perActivity.find((a) => a.bpmnElementId === 'task_aprobar')
const rechazar = result.perActivity.find((a) => a.bpmnElementId === 'task_rechazar')
expect(analisis?.executionProbability).toBeCloseTo(1.0, 2)
expect(aprobar?.executionProbability).toBeCloseTo(0.8, 2)
expect(rechazar?.executionProbability).toBeCloseTo(0.2, 2)
})
it('gateway AND: bureau y empleador tienen la misma prob que score', () => {
const result = runSimulation(buildSimInput([1.0, 0.0], [0.5, 0.5]))
const bureau = result.perActivity.find((a) => a.bpmnElementId === 'task_bureau')
const empleador = result.perActivity.find((a) => a.bpmnElementId === 'task_empleador')
// Ambos deben tener la misma probabilidad (AND paralelo)
expect(bureau?.executionProbability).toBeCloseTo(empleador?.executionProbability ?? -1, 2)
})
it('con probs que no suman 1 el motor no explota, solo produce resultados parciales', () => {
// Esto valida que el motor es robusto aunque la UI deba prevenirlo
expect(() => runSimulation(buildSimInput([0.3, 0.3], [0.5, 0.5]))).not.toThrow()
})
})

View File

@@ -0,0 +1,331 @@
/**
* Tests permanentes de persistencia en IndexedDB vía Dexie.
* Usan fake-indexeddb (parcheado en tests/setup.ts) para correr en Node.
*
* Cada test limpia las tablas en beforeEach para garantizar aislamiento.
* Verifican que los repositorios escriben y recuperan datos correctamente.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { db } from '@/persistence/db'
import {
processRepo,
activityRepo,
gatewayRepo,
resourceRepo,
simulationRepo,
} from '@/persistence/repositories'
import type { Process, Activity, GatewayConfig, Resource, Simulation, SimulationResult } from '@/domain/types'
// ─── Fixtures ─────────────────────────────────────────────────────────────────
function makeProcess(id = 'proc-1'): Process {
return {
id,
name: 'Proceso de prueba',
clientName: 'Cliente Test',
bpmnXml: '<definitions/>',
currency: 'USD',
overheadPercentage: 0.2,
createdAt: 1000,
updatedAt: 2000,
}
}
function makeActivity(id: string, processId: string, bpmnElementId: string): Activity {
return {
id,
processId,
bpmnElementId,
name: `Tarea ${bpmnElementId}`,
type: 'task',
directCostFixed: 100,
executionTimeMinutes: 30,
assignedResources: [{ resourceId: 'res-1', utilizationPercent: 0.5 }],
}
}
function makeGateway(id: string, processId: string, bpmnElementId: string): GatewayConfig {
return {
id,
processId,
bpmnElementId,
gatewayType: 'exclusive',
branches: [
{ flowId: 'f1', targetElementId: 'taskA', probability: 0.7 },
{ flowId: 'f2', targetElementId: 'taskB', probability: 0.3 },
],
}
}
function makeResource(id: string, processId: string): Resource {
return {
id,
processId,
name: 'Analista',
type: 'role',
costPerHour: 60,
}
}
function makeSimulation(id: string, processId: string): Simulation {
const result: SimulationResult = {
totalCost: 1200,
totalDirectCost: 1000,
totalIndirectCost: 200,
totalTimeMinutes: 90,
perActivity: [],
perResource: [],
warnings: [],
}
return { id, processId, executedAt: 3000, result }
}
// ─── Setup / Teardown ─────────────────────────────────────────────────────────
beforeEach(async () => {
await db.open()
await db.transaction(
'rw',
[db.processes, db.activities, db.gateways, db.resources, db.simulations],
async () => {
await Promise.all([
db.processes.clear(),
db.activities.clear(),
db.gateways.clear(),
db.resources.clear(),
db.simulations.clear(),
])
}
)
})
afterEach(async () => {
await db.close()
})
// ─── Process ─────────────────────────────────────────────────────────────────
describe('IndexedDB / processRepo', () => {
it('guarda un proceso y lo recupera por id', async () => {
const proc = makeProcess()
await processRepo.save(proc)
const retrieved = await processRepo.getById('proc-1')
expect(retrieved).toBeDefined()
expect(retrieved!.name).toBe('Proceso de prueba')
expect(retrieved!.currency).toBe('USD')
expect(retrieved!.overheadPercentage).toBe(0.2)
})
it('getById devuelve undefined para id inexistente', async () => {
const result = await processRepo.getById('no-existe')
expect(result).toBeUndefined()
})
it('getAll devuelve todos los procesos guardados', async () => {
await processRepo.save(makeProcess('p1'))
await processRepo.save(makeProcess('p2'))
await processRepo.save(makeProcess('p3'))
const all = await processRepo.getAll()
expect(all).toHaveLength(3)
})
it('save sobrescribe (put) un proceso existente', async () => {
const proc = makeProcess()
await processRepo.save(proc)
await processRepo.save({ ...proc, name: 'Nombre actualizado', updatedAt: 9999 })
const updated = await processRepo.getById('proc-1')
expect(updated!.name).toBe('Nombre actualizado')
expect(updated!.updatedAt).toBe(9999)
})
it('delete elimina el proceso y sus entidades relacionadas en cascada', async () => {
const proc = makeProcess('proc-del')
await processRepo.save(proc)
await activityRepo.saveMany([makeActivity('a1', 'proc-del', 'task1')])
await gatewayRepo.saveMany([makeGateway('g1', 'proc-del', 'gw1')])
await resourceRepo.save(makeResource('r1', 'proc-del'))
await processRepo.delete('proc-del')
expect(await processRepo.getById('proc-del')).toBeUndefined()
expect(await activityRepo.getByProcess('proc-del')).toHaveLength(0)
expect(await gatewayRepo.getByProcess('proc-del')).toHaveLength(0)
expect(await resourceRepo.getByProcess('proc-del')).toHaveLength(0)
})
})
// ─── Activity ─────────────────────────────────────────────────────────────────
describe('IndexedDB / activityRepo', () => {
const processId = 'proc-act'
it('saveMany y getByProcess devuelven las mismas actividades', async () => {
const acts = [
makeActivity('a1', processId, 'task1'),
makeActivity('a2', processId, 'task2'),
makeActivity('a3', processId, 'task3'),
]
await activityRepo.saveMany(acts)
const retrieved = await activityRepo.getByProcess(processId)
expect(retrieved).toHaveLength(3)
const ids = retrieved.map((a) => a.id).sort()
expect(ids).toEqual(['a1', 'a2', 'a3'])
})
it('persiste assignedResources (array anidado) correctamente', async () => {
const act = makeActivity('a1', processId, 'task1')
await activityRepo.save(act)
const [retrieved] = await activityRepo.getByProcess(processId)
expect(retrieved.assignedResources).toHaveLength(1)
expect(retrieved.assignedResources[0].resourceId).toBe('res-1')
expect(retrieved.assignedResources[0].utilizationPercent).toBe(0.5)
})
it('no devuelve actividades de otro proceso', async () => {
await activityRepo.save(makeActivity('a-other', 'otro-proc', 'task1'))
const result = await activityRepo.getByProcess(processId)
expect(result).toHaveLength(0)
})
})
// ─── GatewayConfig ────────────────────────────────────────────────────────────
describe('IndexedDB / gatewayRepo', () => {
const processId = 'proc-gw'
it('saveMany y getByProcess devuelven la config con branches correctas', async () => {
const gw = makeGateway('g1', processId, 'gw_decision')
await gatewayRepo.saveMany([gw])
const [retrieved] = await gatewayRepo.getByProcess(processId)
expect(retrieved.bpmnElementId).toBe('gw_decision')
expect(retrieved.gatewayType).toBe('exclusive')
expect(retrieved.branches).toHaveLength(2)
expect(retrieved.branches[0].probability).toBe(0.7)
expect(retrieved.branches[1].probability).toBe(0.3)
})
it('save individual actualiza la config existente', async () => {
const gw = makeGateway('g1', processId, 'gw1')
await gatewayRepo.save(gw)
const updated: GatewayConfig = {
...gw,
branches: [
{ flowId: 'f1', targetElementId: 'taskA', probability: 0.6 },
{ flowId: 'f2', targetElementId: 'taskB', probability: 0.4 },
],
}
await gatewayRepo.save(updated)
const [retrieved] = await gatewayRepo.getByProcess(processId)
expect(retrieved.branches[0].probability).toBe(0.6)
})
})
// ─── Resource ─────────────────────────────────────────────────────────────────
describe('IndexedDB / resourceRepo', () => {
const processId = 'proc-res'
it('save y getByProcess recupera el recurso correctamente', async () => {
await resourceRepo.save(makeResource('r1', processId))
const [retrieved] = await resourceRepo.getByProcess(processId)
expect(retrieved.name).toBe('Analista')
expect(retrieved.costPerHour).toBe(60)
expect(retrieved.type).toBe('role')
})
it('delete elimina un recurso por id', async () => {
await resourceRepo.save(makeResource('r1', processId))
await resourceRepo.save(makeResource('r2', processId))
await resourceRepo.delete('r1')
const remaining = await resourceRepo.getByProcess(processId)
expect(remaining).toHaveLength(1)
expect(remaining[0].id).toBe('r2')
})
it('múltiples recursos para el mismo proceso', async () => {
const types = ['role', 'system', 'equipment'] as const
for (const [i, type] of types.entries()) {
await resourceRepo.save({ ...makeResource(`r${i}`, processId), type })
}
const all = await resourceRepo.getByProcess(processId)
expect(all).toHaveLength(3)
const typeSet = new Set(all.map((r) => r.type))
expect(typeSet.has('role')).toBe(true)
expect(typeSet.has('system')).toBe(true)
expect(typeSet.has('equipment')).toBe(true)
})
})
// ─── Simulation ───────────────────────────────────────────────────────────────
describe('IndexedDB / simulationRepo', () => {
const processId = 'proc-sim'
it('save y getLatestByProcess recuperan el snapshot de resultado', async () => {
const sim = makeSimulation('sim-1', processId)
await simulationRepo.save(sim)
const retrieved = await simulationRepo.getLatestByProcess(processId)
expect(retrieved).toBeDefined()
expect(retrieved!.result.totalCost).toBe(1200)
expect(retrieved!.result.totalDirectCost).toBe(1000)
expect(retrieved!.result.totalIndirectCost).toBe(200)
})
it('getLatestByProcess devuelve undefined si no hay simulaciones', async () => {
const result = await simulationRepo.getLatestByProcess('proc-sin-sim')
expect(result).toBeUndefined()
})
it('múltiples simulaciones: getByProcess las recupera todas', async () => {
await simulationRepo.save({ ...makeSimulation('s1', processId), executedAt: 1000 })
await simulationRepo.save({ ...makeSimulation('s2', processId), executedAt: 2000 })
await simulationRepo.save({ ...makeSimulation('s3', processId), executedAt: 3000 })
const all = await simulationRepo.getByProcess(processId)
expect(all).toHaveLength(3)
})
it('persiste warnings en el resultado (campo libre)', async () => {
const sim: Simulation = {
...makeSimulation('s-warn', processId),
result: {
...makeSimulation('s-warn', processId).result,
warnings: ['Loop detectado en taskX'],
},
}
await simulationRepo.save(sim)
const retrieved = await simulationRepo.getLatestByProcess(processId)
expect(retrieved!.result.warnings).toHaveLength(1)
expect(retrieved!.result.warnings[0]).toContain('Loop detectado')
})
})
// ─── Round-trip completo (simula el flujo de ImportPage) ─────────────────────
describe('IndexedDB / round-trip proceso completo', () => {
it('guarda proceso + actividades + gateways + recursos, luego los recupera íntegros', async () => {
const proc = makeProcess('rt-proc')
const acts = [
makeActivity('rt-a1', 'rt-proc', 'taskA'),
makeActivity('rt-a2', 'rt-proc', 'taskB'),
]
const gws = [makeGateway('rt-g1', 'rt-proc', 'gw1')]
const resources = [makeResource('rt-r1', 'rt-proc')]
await Promise.all([
processRepo.save(proc),
activityRepo.saveMany(acts),
gatewayRepo.saveMany(gws),
resourceRepo.save(resources[0]),
])
// Simular recarga de página
const [retrievedProc, retrievedActs, retrievedGws, retrievedRes] = await Promise.all([
processRepo.getById('rt-proc'),
activityRepo.getByProcess('rt-proc'),
gatewayRepo.getByProcess('rt-proc'),
resourceRepo.getByProcess('rt-proc'),
])
expect(retrievedProc!.id).toBe('rt-proc')
expect(retrievedActs).toHaveLength(2)
expect(retrievedGws).toHaveLength(1)
expect(retrievedGws[0].branches).toHaveLength(2)
expect(retrievedRes).toHaveLength(1)
expect(retrievedRes[0].costPerHour).toBe(60)
})
})

View File

@@ -0,0 +1,278 @@
/**
* Tests permanentes del motor de simulación corriendo sobre los 3 sample BPMNs.
* Protegen contra regresiones en runSimulation, la propagación de probabilidades
* y la detección de loops.
*
* Costos dummy predecibles para que las aserciones sean deterministas.
*/
import { describe, it, expect } 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 { bpmnTypeToGatewayType } from '@/domain/types'
import type { Activity, GatewayConfig, Resource, SimulationInput } from '@/domain/types'
function loadSample(name: string): string {
return readFileSync(resolve(__dirname, '../../public/sample-processes', name), 'utf-8')
}
// Construye un SimulationInput con costos fijos iguales para todas las actividades
function buildInput(
xml: string,
opts: {
directCostFixed?: number
executionTimeMinutes?: number
overheadPercentage?: number
gatewayProbsOverride?: Record<string, number[]>
} = {}
): SimulationInput {
const {
directCostFixed = 100,
executionTimeMinutes = 30,
overheadPercentage = 0.2,
gatewayProbsOverride = {},
} = opts
const processId = 'sim-test'
const graph = parseBpmnXml(xml)
const actEls = extractActivityElements(graph)
const gwEls = extractGatewayElements(graph)
const activities = new Map<string, Activity>(
actEls.map((el) => [
el.bpmnElementId,
{
id: uuidv4(),
processId,
bpmnElementId: el.bpmnElementId,
name: el.name,
type: el.type,
directCostFixed,
executionTimeMinutes,
assignedResources: [],
},
])
)
const gateways = new Map<string, GatewayConfig>(
gwEls.map((el) => {
const gwType = bpmnTypeToGatewayType(el.gatewayType as any)
const n = el.outgoing.length
const probsOverride = gatewayProbsOverride[el.bpmnElementId]
return [
el.bpmnElementId,
{
id: uuidv4(),
processId,
bpmnElementId: el.bpmnElementId,
gatewayType: gwType,
branches: el.outgoing.map((flowId, i) => ({
flowId,
targetElementId: graph.flows.get(flowId)?.targetRef ?? '',
probability:
probsOverride?.[i] ??
(gwType === 'parallel' ? 1.0 : parseFloat((1 / n).toFixed(6))),
})),
},
]
})
)
return {
processXml: xml,
activities,
gateways,
resources: new Map<string, Resource>(),
globalSettings: { currency: 'USD', overheadPercentage },
}
}
// ─── simple-linear.bpmn ──────────────────────────────────────────────────────
describe('simulación / simple-linear.bpmn', () => {
const xml = loadSample('simple-linear.bpmn')
it('corre sin lanzar error con costos dummy', () => {
expect(() => runSimulation(buildInput(xml))).not.toThrow()
})
it('no genera warnings (proceso sin loops ni gateways)', () => {
const result = runSimulation(buildInput(xml))
expect(result.warnings).toHaveLength(0)
})
it('costo total = 5 × 100 × 1.2 = 600 (5 tareas, prob=1, overhead=20%)', () => {
const result = runSimulation(buildInput(xml, { directCostFixed: 100, overheadPercentage: 0.2 }))
expect(result.totalDirectCost).toBe(500)
expect(result.totalIndirectCost).toBeCloseTo(100)
expect(result.totalCost).toBeCloseTo(600)
})
it('perActivity tiene 5 entradas, todas con executionProbability = 1', () => {
const result = runSimulation(buildInput(xml))
expect(result.perActivity).toHaveLength(5)
result.perActivity.forEach((a) => {
expect(a.executionProbability).toBeCloseTo(1.0)
})
})
it('perActivity ordenado descendente por expectedTotalCost', () => {
const result = runSimulation(buildInput(xml, { directCostFixed: 100 }))
for (let i = 0; i < result.perActivity.length - 1; i++) {
expect(result.perActivity[i].expectedTotalCost).toBeGreaterThanOrEqual(
result.perActivity[i + 1].expectedTotalCost
)
}
})
it('percentOfTotal suma exactamente 100%', () => {
const result = runSimulation(buildInput(xml))
const sum = result.perActivity.reduce((acc, a) => acc + a.percentOfTotal, 0)
expect(sum).toBeCloseTo(100, 1)
})
it('tiempo total = 5 × 30 min = 150 min', () => {
const result = runSimulation(buildInput(xml, { executionTimeMinutes: 30 }))
expect(result.totalTimeMinutes).toBeCloseTo(150)
})
})
// ─── medium-with-gateways.bpmn ───────────────────────────────────────────────
describe('simulación / medium-with-gateways.bpmn', () => {
const xml = loadSample('medium-with-gateways.bpmn')
it('corre sin lanzar error con costos dummy', () => {
expect(() => runSimulation(buildInput(xml))).not.toThrow()
})
it('no genera warnings (sin loops)', () => {
const result = runSimulation(buildInput(xml))
expect(result.warnings).toHaveLength(0)
})
it('perActivity tiene exactamente 11 entradas', () => {
const result = runSimulation(buildInput(xml))
expect(result.perActivity).toHaveLength(11)
})
it('actividades antes de cualquier gateway tienen prob = 1.0', () => {
const result = runSimulation(buildInput(xml))
const recv = result.perActivity.find((a) => a.bpmnElementId === 'task_recv')
const valid = result.perActivity.find((a) => a.bpmnElementId === 'task_valid')
expect(recv?.executionProbability).toBeCloseTo(1.0)
expect(valid?.executionProbability).toBeCloseTo(1.0)
})
it('gateway XOR con probs 0.7/0.3 propaga correctamente', () => {
// gw_datos: completo(idx 0)=0.7, incompleto(idx 1)=0.3
const result = runSimulation(
buildInput(xml, {
gatewayProbsOverride: { gw_datos: [0.7, 0.3] },
})
)
const score = result.perActivity.find((a) => a.bpmnElementId === 'task_score')
const pedirDocs = result.perActivity.find((a) => a.bpmnElementId === 'task_pedir_docs')
expect(score?.executionProbability).toBeCloseTo(0.7, 1)
expect(pedirDocs?.executionProbability).toBeCloseTo(0.3, 1)
})
it('gateway paralelo AND: ambas ramas tienen prob igual a la entrada', () => {
// gw_datos completo=1.0 para simplificar, gw_parallel_split AND ambas =1
const result = runSimulation(
buildInput(xml, {
gatewayProbsOverride: {
gw_datos: [1.0, 0.0], // siempre el camino completo
gw_decision: [0.5, 0.5],
},
})
)
const bureau = result.perActivity.find((a) => a.bpmnElementId === 'task_bureau')
const empleador = result.perActivity.find((a) => a.bpmnElementId === 'task_empleador')
// Ambas ramas del AND deben tener prob similar (≈ prob del score)
expect(bureau?.executionProbability).toBeGreaterThan(0)
expect(empleador?.executionProbability).toBeGreaterThan(0)
expect(Math.abs((bureau?.executionProbability ?? 0) - (empleador?.executionProbability ?? 0))).toBeLessThan(0.01)
})
it('perActivity ordenado descendente por costo', () => {
const result = runSimulation(buildInput(xml))
for (let i = 0; i < result.perActivity.length - 1; i++) {
expect(result.perActivity[i].expectedTotalCost).toBeGreaterThanOrEqual(
result.perActivity[i + 1].expectedTotalCost
)
}
})
})
// ─── complex-with-loop.bpmn ───────────────────────────────────────────────────
describe('simulación / complex-with-loop.bpmn', () => {
const xml = loadSample('complex-with-loop.bpmn')
it('corre sin lanzar error (a pesar del loop)', () => {
expect(() => runSimulation(buildInput(xml))).not.toThrow()
})
it('🚨 genera al menos un warning de loop detectado', () => {
const result = runSimulation(buildInput(xml))
expect(result.warnings.length).toBeGreaterThan(0)
const hasLoopWarning = result.warnings.some(
(w) => w.toLowerCase().includes('loop') || w.toLowerCase().includes('ciclo')
)
expect(hasLoopWarning).toBe(true)
})
it('el warning menciona el nodo "Inspección visual y funcional"', () => {
const result = runSimulation(buildInput(xml))
const loopWarning = result.warnings.find(
(w) => w.toLowerCase().includes('loop') || w.toLowerCase().includes('ciclo')
)
expect(loopWarning).toContain('Inspección visual y funcional')
})
it('resultado es válido a pesar del loop: costo > 0 y 9 actividades', () => {
const result = runSimulation(buildInput(xml, { directCostFixed: 100 }))
expect(result.totalCost).toBeGreaterThan(0)
expect(result.perActivity).toHaveLength(9)
})
it('con probabilidades reales (60% aprobado, 30% correcciones, 10% rechazo)', () => {
const result = runSimulation(
buildInput(xml, {
directCostFixed: 200,
overheadPercentage: 0.15,
gatewayProbsOverride: {
// gw_resultado: 3 salidas — aprobado 0.6, obs_menores 0.3, rechazo 0.1
gw_resultado: [0.6, 0.3, 0.1],
},
})
)
expect(result.totalCost).toBeGreaterThan(0)
expect(result.warnings.length).toBeGreaterThan(0)
// task_inspeccion tiene prob alta (es el nodo más costoso del proceso con loop)
const inspeccion = result.perActivity.find((a) => a.bpmnElementId === 'task_inspeccion')
expect(inspeccion).toBeDefined()
expect(inspeccion!.executionProbability).toBeGreaterThan(0)
// task_correcciones tiene prob = prob del camino de correcciones ≈ 0.3
const correcciones = result.perActivity.find((a) => a.bpmnElementId === 'task_correcciones')
expect(correcciones).toBeDefined()
expect(correcciones!.executionProbability).toBeCloseTo(0.3, 1)
// task_rechazo tiene prob ≈ 0.1
const rechazo = result.perActivity.find((a) => a.bpmnElementId === 'task_rechazo')
expect(rechazo).toBeDefined()
expect(rechazo!.executionProbability).toBeCloseTo(0.1, 1)
})
it('percentOfTotal suma ≈ 100%', () => {
const result = runSimulation(buildInput(xml))
if (result.perActivity.length > 0) {
const sum = result.perActivity.reduce((acc, a) => acc + a.percentOfTotal, 0)
expect(sum).toBeCloseTo(100, 0)
}
})
})