chore(sprint-5/etapa-6): limpieza técnica — E2E Supabase, fix flakiness guardar, docs cierre sprint
Some checks failed
/ Deploy to Cloudflare Pages (push) Has been cancelled

This commit is contained in:
2026-06-23 22:33:01 -03:00
parent 485cc91d73
commit 5ca5d7ea31
10 changed files with 269 additions and 135 deletions

View File

@@ -15,19 +15,44 @@
* Ejecutar: npx playwright test tests/e2e/validate-dod-etapa4.spec.ts
*/
import { test, expect } from '@playwright/test'
import { readFileSync, mkdirSync, writeFileSync } from 'fs'
import { readFileSync, mkdirSync, writeFileSync, existsSync } from 'fs'
import { resolve } from 'path'
import { fileURLToPath } from 'url'
import { PDFParse } from 'pdf-parse'
import sharp from 'sharp'
import { PDFDocument, PDFName, PDFRawStream } from 'pdf-lib'
import { createClient } from '@supabase/supabase-js'
test.use({ storageState: 'tests/e2e/setup/auth-state.json' })
const __dirname = fileURLToPath(new URL('.', import.meta.url))
const ROOT = resolve(__dirname, '../..')
const BPMN_DIR = resolve(__dirname, '../../public/sample-processes')
const OUTPUT_DIR = resolve(__dirname, '__output__')
// ─── Cliente Supabase con service_role_key para inyección directa de datos ────
// Reemplaza la inyección vía IndexedDB (Dexie, eliminado en Sprint 4) por escritura
// directa en Supabase, bypaseando RLS con el service_role_key. Ver .env.example.
function loadEnvFile(filename: string): Record<string, string> {
const path = resolve(ROOT, filename)
if (!existsSync(path)) return {}
const out: Record<string, string> = {}
for (const line of readFileSync(path, 'utf-8').split('\n')) {
const trimmed = line.trim()
if (!trimmed || trimmed.startsWith('#')) continue
const idx = trimmed.indexOf('=')
if (idx === -1) continue
out[trimmed.slice(0, idx)] = trimmed.slice(idx + 1)
}
return out
}
const localEnv = loadEnvFile('.env.local')
const testEnv = loadEnvFile('.env.test')
const SUPABASE_URL = localEnv.VITE_SUPABASE_URL
const SERVICE_ROLE_KEY = testEnv.SUPABASE_SERVICE_ROLE_KEY
test.beforeAll(() => {
mkdirSync(OUTPUT_DIR, { recursive: true })
})
@@ -134,73 +159,67 @@ const AUTO_TIME = 5
// ─── Test único que genera y valida los 6 archivos ───────────────────────────
test('DoD Etapa 4 — genera y valida los 6 archivos de export para medium-with-gateways', async ({ page }) => {
test.describe('DoD Etapa 4', () => {
let createdProcessId: string | null = null
// ── Fase 1: importar BPMN e inyectar configuración en IndexedDB ─────────────
test.afterAll(async () => {
if (createdProcessId && SUPABASE_URL && SERVICE_ROLE_KEY) {
const supabaseAdmin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY)
await supabaseAdmin.from('processes').delete().eq('id', createdProcessId)
}
})
test('DoD Etapa 4 — genera y valida los 6 archivos de export para medium-with-gateways', async ({ page }) => {
test.skip(
!SUPABASE_URL || !SERVICE_ROLE_KEY,
'SUPABASE_SERVICE_ROLE_KEY no configurada en .env.test — ver .env.example para el formato esperado'
)
// ── Fase 1: importar BPMN e inyectar configuración en Supabase ──────────────
await page.goto('/import')
await page.locator('#bpmn-file-input').setInputFiles(resolve(BPMN_DIR, 'medium-with-gateways.bpmn'))
await page.waitForURL(/\/workspace\//, { timeout: 15_000 })
const processId = page.url().split('/workspace/')[1]
createdProcessId = processId
await page.waitForTimeout(1_500)
// Inyectar costos de actividades y flags de automatización en IndexedDB
await page.evaluate(async ({ procId, actualCosts, automatable, autoCost, autoTime }) => {
const DB_NAME = 'ProcessCostPlatform'
const db = await new Promise<IDBDatabase>((res, rej) => {
const req = indexedDB.open(DB_NAME)
req.onsuccess = () => res(req.result)
req.onerror = () => rej(req.error)
})
const acts = await new Promise<any[]>((res, rej) => {
const tx = db.transaction('activities', 'readonly')
const req = tx.objectStore('activities').index('processId').getAll(procId)
req.onsuccess = () => res(req.result)
req.onerror = () => rej(req.error)
})
await new Promise<void>((res, rej) => {
const tx = db.transaction('activities', 'readwrite')
const store = tx.objectStore('activities')
let pending = acts.length
if (pending === 0) { res(); return }
for (const act of acts) {
const isAuto = (automatable as string[]).includes(act.bpmnElementId)
const req = store.put({
...act,
directCostFixed: (actualCosts as Record<string, number>)[act.bpmnElementId] ?? 200,
executionTimeMinutes: 60,
automatable: isAuto,
automatedCostFixed: isAuto ? autoCost : 0,
automatedTimeMinutes: isAuto ? autoTime : 0,
})
req.onsuccess = () => { if (--pending === 0) res() }
req.onerror = () => rej(req.error)
// Inyectar costos de actividades y flags de automatización directamente en Supabase
// (service_role_key bypasa RLS — equivalente al patrón antiguo de escritura en IndexedDB)
const supabaseAdmin = createClient(SUPABASE_URL!, SERVICE_ROLE_KEY!)
const { data: acts, error: actsErr } = await supabaseAdmin
.from('activities')
.select('id, bpmn_element_id')
.eq('process_id', processId)
if (actsErr) throw actsErr
const { error: upsertActsErr } = await supabaseAdmin.from('activities').upsert(
(acts ?? []).map((act) => {
const isAuto = AUTOMATABLE.has(act.bpmn_element_id as string)
return {
id: act.id,
direct_cost_fixed: ACTUAL_COST[act.bpmn_element_id as string] ?? 200,
execution_time_minutes: 60,
automatable: isAuto,
automated_cost_fixed: isAuto ? AUTO_COST : 0,
automated_time_minutes: isAuto ? AUTO_TIME : 0,
}
})
)
if (upsertActsErr) throw upsertActsErr
// Inyectar volumetría en el proceso
const proc = await new Promise<any>((res, rej) => {
const tx = db.transaction('processes', 'readonly')
const req = tx.objectStore('processes').get(procId)
req.onsuccess = () => res(req.result)
req.onerror = () => rej(req.error)
// Inyectar volumetría en el proceso
const { error: procErr } = await supabaseAdmin
.from('processes')
.update({
annual_frequency: 12_000,
analysis_horizon_years: 3,
automation_investment: 50_000,
})
if (proc) {
await new Promise<void>((res, rej) => {
const tx = db.transaction('processes', 'readwrite')
const req = tx.objectStore('processes').put({
...proc,
annualFrequency: 12_000,
analysisHorizonYears: 3,
automationInvestment: 50_000,
})
req.onsuccess = () => res()
req.onerror = () => rej(req.error)
})
}
db.close()
}, { procId: processId, actualCosts: ACTUAL_COST, automatable: [...AUTOMATABLE], autoCost: AUTO_COST, autoTime: AUTO_TIME })
.eq('id', processId)
if (procErr) throw procErr
// Recargar para que el store de Zustand relea desde Dexie
// Recargar para que el store de Zustand relea desde Supabase
await page.reload()
await page.waitForSelector('button:has-text("Simular")', { timeout: 15_000 })
await page.waitForTimeout(1_500)
@@ -442,4 +461,5 @@ test('DoD Etapa 4 — genera y valida los 6 archivos de export para medium-with-
expect(roiHasROI, 'roi.csv debe tener metadata de ROI anualizado').toBe(true)
expect(roiHasFreq, 'roi.csv debe tener frecuencia anual 12000').toBe(true)
expect(roiHasAutomatable, 'roi.csv debe tener columna Automatizable').toBe(true)
})
})