Compare commits

..

4 Commits

Author SHA1 Message Date
8b839baf77 refactor(router): guards AdminLayout + ImportPage → RequireRole wrapper (Etapa 6A)
Some checks are pending
/ Deploy to Cloudflare Pages (push) Waiting to run
- Crea RequireRole component (Approach B — router sin auth context)
- AdminLayout: elimina useEffect + spinner + null check, usa <RequireRole roles={['platform_admin']}>
- ImportPage: elimina useEffect guard + return null client_viewer, usa <RequireRole roles={['platform_admin','member','client_editor']}>

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-09 13:18:14 -03:00
1032944f8b fix import para client_editor
Some checks failed
/ Deploy to Cloudflare Pages (push) Has been cancelled
2026-07-09 12:10:36 -03:00
0257dd95ec Otro fix para el import con client_editor
Some checks failed
/ Deploy to Cloudflare Pages (push) Has been cancelled
2026-07-08 11:54:18 -03:00
fdbdc42470 El bug está en toRow() en process-repo.ts, no en el ImportPage:
Some checks failed
/ Deploy to Cloudflare Pages (push) Has been cancelled
typescript// toRow() en process-repo.ts — líneas 4-24
// NUNCA incluye org_id en el payload del upsert
const row = {
  id: process.id,
  name: process.name,
  // ... otros campos
  // ← org_id ausente completamente
}
La cadena completa del fallo:

ImportPage.tsx sí tiene orgId: user!.orgId ?? null → el Process object tiene el valor correcto
process-repo.ts llama toRow() para construir el payload de Supabase
toRow() nunca pone org_id en el payload → Supabase recibe org_id = null (default)
La RLS chequea org_id = current_org() → null ≠ '2a956076-...' → 403
El error propaga y sale como toast genérico de archivo dañado

Esto pasó desapercibido hasta ahora porque platform_admin tiene is_platform_admin() que bypasea la verificación de org_id. La inserción con org_id = null le funciona a admins, nunca a client_editor.
El fix es quirúrgico: agregar una sola línea en toRow():
typescriptorg_id: process.orgId ?? null,
Eso es todo. Una línea en process-repo.ts. La restricción "no tocar process-repo.ts" de Etapa 5 era por razón equivocada (asumíamos que el repo no necesitaba cambios) — este es un bug que impide que Etapa 5 funcione en absoluto.
2026-07-08 11:46:29 -03:00
9 changed files with 426 additions and 66 deletions

View File

@@ -7,21 +7,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
- `RequireRole` componente wrapper para guards de rol declarativos (Approach B — sin router context) (Sprint 8)
- Edge Function `delete-user`: hard delete permanente de usuario en auth.users + public.users (Sprint 8)
- Edge Function `list-users`: lista usuarios con email desde auth.users vía service_role (Sprint 8)
- UsersPage: columna "Email" entre Nombre y Rol (via Edge Function list-users) (Sprint 8)
- Migración 018: policy INSERT en `processes` extendida para `client_editor` en su org (Sprint 8)
- ImportPage: `client_editor` puede importar BPMN; proceso se crea con `orgId` de su cuenta (Sprint 8)
- LibraryPage: botón "Importar BPMN" visible para `client_editor`; empty state con call-to-action de importar (Sprint 8)
### Changed
- AdminLayout: guard useEffect + spinner → RequireRole wrapper (sin flash de contenido protegido) (Sprint 8)
- ImportPage: guard useEffect → RequireRole wrapper (Sprint 8)
- UsersPage: "Eliminar" (soft delete / revoke-user) → "Eliminar permanentemente" (hard delete / delete-user) (Sprint 8)
### Fixed
- ImportPage: texto de marca corregido — "Process Cost Platform · MVP Fase 0" → "InQ ROI" (Sprint 8)
- ImportPage: párrafo "Sin backend · Sin registro · Datos guardados localmente" eliminado (obsoleto desde Sprint 4) (Sprint 8)
### Fixed
- OrganizationsPage: InQuality visible en lista con badge naranja — quitar filtro is_provider (Sprint 8)
- WorkspacePage: back button pasa ?org=orgId para scroll contextual al volver a biblioteca (Sprint 8)
- LibraryPage: scroll automático a sección de org al recibir ?org param desde workspace (Sprint 8)
- router.tsx: redirect de settingsRoute pasa search: { org: undefined } para compatibilidad con validateSearch (Sprint 8)
### Added
### Added (Etapas 1-4)
- GlobalSettingsPanel: selector de área reemplaza campo libre "Cliente" (Sprint 8)
- WorkspacePage topbar: display de `areaName` de solo lectura reemplaza edición inline de cliente (Sprint 8)
- OrganizationDetailPage: tercer tab "Áreas" con CRUD completo — crear, renombrar, eliminar con confirmación (Sprint 8)

View File

@@ -0,0 +1,30 @@
import { useEffect } from 'react'
import { useNavigate } from '@tanstack/react-router'
import { useAuth } from '@/auth/AuthContext'
export function RequireRole({
roles,
redirectTo = '/',
children,
}: {
roles: string[]
redirectTo?: '/' | '/library'
children: React.ReactNode
}) {
const { user, isProfileLoaded } = useAuth()
const navigate = useNavigate()
useEffect(() => {
if (!isProfileLoaded) return
if (!user || !roles.includes(user.platformRole)) {
void navigate({ to: redirectTo })
}
// roles y redirectTo son constantes en cada call site — excluidos intencionalmente
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [user?.platformRole, isProfileLoaded, navigate])
if (!isProfileLoaded || !user) return null
if (!roles.includes(user.platformRole)) return null
return <>{children}</>
}

View File

@@ -1,47 +1,28 @@
import { useEffect } from 'react'
import { Outlet, Link, useNavigate, useRouterState } from '@tanstack/react-router'
import { Loader2 } from 'lucide-react'
import { useAuth } from '@/auth/AuthContext'
import { Outlet, Link, useRouterState } from '@tanstack/react-router'
import { AppHeader } from '@/components/AppHeader'
import { RequireRole } from '@/components/RequireRole'
import { cn } from '@/lib/utils'
export function AdminLayout() {
const { user, loading } = useAuth()
const navigate = useNavigate()
const pathname = useRouterState({ select: (s) => s.location.pathname })
useEffect(() => {
if (loading) return
if (!user || user.platformRole !== 'platform_admin') {
void navigate({ to: '/' })
}
}, [user, loading, navigate])
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin" style={{ color: '#F59845' }} />
</div>
)
}
if (!user || user.platformRole !== 'platform_admin') return null
return (
<div className="min-h-screen flex flex-col bg-slate-50">
<AppHeader />
<div className="flex-1 max-w-6xl mx-auto w-full px-6 py-8">
<nav className="flex gap-1 border-b border-slate-200 mb-6">
<AdminNavTab to="/admin/organizations" active={pathname.startsWith('/admin/organizations')}>
Organizaciones
</AdminNavTab>
<AdminNavTab to="/admin/users" active={pathname.startsWith('/admin/users')}>
Usuarios
</AdminNavTab>
</nav>
<Outlet />
<RequireRole roles={['platform_admin']}>
<div className="min-h-screen flex flex-col bg-slate-50">
<AppHeader />
<div className="flex-1 max-w-6xl mx-auto w-full px-6 py-8">
<nav className="flex gap-1 border-b border-slate-200 mb-6">
<AdminNavTab to="/admin/organizations" active={pathname.startsWith('/admin/organizations')}>
Organizaciones
</AdminNavTab>
<AdminNavTab to="/admin/users" active={pathname.startsWith('/admin/users')}>
Usuarios
</AdminNavTab>
</nav>
<Outlet />
</div>
</div>
</div>
</RequireRole>
)
}

View File

@@ -1,12 +1,10 @@
/**
* Limitaciones conocidas documentadas:
* 1. email no está en public.users (vive en auth.users, requiere service_role) → solo se muestra name.
* 2. "Eliminar" llama revoke-user que baja platform_role a 'guest'. Eliminación real requiere Edge Function futura.
* 3. "Reactivar" restaura siempre a 'client_editor' — no se guarda el rol previo a la suspensión.
* Limitaciones conocidas:
* - "Reactivar" restaura siempre a 'client_editor' — no se guarda el rol previo a la suspensión.
*/
import { useEffect, useState } from 'react'
import * as DialogPrimitive from '@radix-ui/react-dialog'
import { UserX, UserPlus, MoreVertical } from 'lucide-react'
import { UserX, UserPlus, MoreVertical, Trash2 } from 'lucide-react'
import { supabase } from '@/lib/supabase'
import { useAuth } from '@/auth/AuthContext'
import { Button } from '@/components/ui/button'
@@ -34,6 +32,7 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { useToast } from '@/components/ui/use-toast'
import { RoleBadge } from './RoleBadge'
interface AdminUser {
@@ -44,6 +43,7 @@ interface AdminUser {
org_id: string | null
avatar_url: string | null
organization: { name: string; is_provider: boolean } | null
email?: string | null
}
interface OrgOption {
@@ -116,6 +116,7 @@ const CHANGE_ROLES = ['platform_admin', 'member', 'client_editor', 'client_viewe
export function UsersPage() {
const { user: adminUser } = useAuth()
const { toast } = useToast()
const [users, setUsers] = useState<AdminUser[]>([])
const [orgs, setOrgs] = useState<OrgOption[]>([])
@@ -155,8 +156,25 @@ export function UsersPage() {
const finalQuery = filterOrgId !== 'all'
? query.eq('org_id', filterOrgId)
: query
const { data } = await finalQuery
setUsers((data as AdminUser[] | null) ?? [])
const [{ data }, { data: emailData }] = await Promise.all([
finalQuery,
supabase.functions.invoke('list-users'),
])
const emailMap = new Map<string, string | null>()
if (emailData) {
for (const u of (emailData as Array<{ id: string; email: string | null }>) ?? []) {
emailMap.set(u.id, u.email ?? null)
}
}
const usersWithEmail = ((data as AdminUser[] | null) ?? []).map((u) => ({
...u,
email: emailMap.get(u.id) ?? null,
}))
setUsers(usersWithEmail)
setLoadingUsers(false)
}
@@ -260,16 +278,24 @@ export function UsersPage() {
void fetchUsers()
}
// ── Delete (también usa revoke-user — baja a guest, eliminación real futura)
// ── Hard delete vía Edge Function delete-user ────────────────────────────
const handleDelete = async () => {
if (!deleteTarget) return
setDeleting(true)
const { error } = await supabase.functions.invoke('revoke-user', {
const { error } = await supabase.functions.invoke('delete-user', {
body: { userId: deleteTarget.id },
})
if (error) {
console.error('Error al eliminar usuario:', error)
toast({
title: 'Error al eliminar usuario',
description: typeof error === 'object' && 'message' in error
? String(error.message)
: 'Ocurrió un error inesperado.',
variant: 'destructive',
})
} else {
toast({ title: 'Usuario eliminado permanentemente' })
}
setDeleteTarget(null)
setDeleting(false)
@@ -334,6 +360,7 @@ export function UsersPage() {
<thead className="bg-slate-50 border-b border-slate-200">
<tr>
<th className="text-left py-2.5 px-4 font-medium text-slate-600">Nombre</th>
<th className="text-left py-2.5 px-4 font-medium text-slate-600">Email</th>
<th className="text-left py-2.5 px-4 font-medium text-slate-600">Rol</th>
<th className="text-left py-2.5 px-4 font-medium text-slate-600">Organización</th>
<th className="py-2.5 px-4" />
@@ -363,6 +390,9 @@ export function UsersPage() {
)}
</div>
</td>
<td className="py-3 px-4 text-slate-500 text-xs font-mono">
{u.email ?? '—'}
</td>
<td className="py-3 px-4">
<RoleBadge role={u.platform_role} />
</td>
@@ -403,7 +433,8 @@ export function UsersPage() {
className="text-destructive focus:text-destructive"
onClick={() => setDeleteTarget(u)}
>
Eliminar
<Trash2 className="h-3.5 w-3.5 mr-2" />
Eliminar permanentemente
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -537,13 +568,13 @@ export function UsersPage() {
destructive
/>
{/* ─── ConfirmDialog: Eliminar ─────────────────────────────────────── */}
{/* ─── ConfirmDialog: Eliminar permanentemente ────────────────────── */}
<ConfirmDialog
open={!!deleteTarget}
onOpenChange={(open) => !open && setDeleteTarget(null)}
title={`¿Eliminar a ${deleteTarget?.name ?? 'este usuario'}?`}
description="El usuario quedará suspendido permanentemente. (Nota: la eliminación real de la cuenta estará disponible en una versión futura.)"
confirmLabel="Eliminar"
title={`¿Eliminar permanentemente a ${deleteTarget?.name ?? 'este usuario'}?`}
description="Esta acción no puede deshacerse. El usuario perderá acceso inmediatamente y sus datos de autenticación serán eliminados de forma permanente."
confirmLabel="Eliminar permanentemente"
onConfirm={handleDelete}
loading={deleting}
destructive
@@ -580,6 +611,7 @@ function TableSkeleton({ rows }: { rows: number }) {
{Array.from({ length: rows }).map((_, i) => (
<div key={i} className="flex gap-4 px-4 py-3 bg-white items-center">
<Skeleton className="h-4 flex-1" />
<Skeleton className="h-4 w-40" />
<Skeleton className="h-5 w-20 rounded" />
<Skeleton className="h-4 w-28" />
<Skeleton className="h-6 w-6 rounded" />

View File

@@ -1,5 +1,5 @@
import { useNavigate, useSearch } from '@tanstack/react-router'
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useState } from 'react'
import { UploadCloud, FileText, Loader2, FlaskConical } from 'lucide-react'
import { v4 as uuidv4 } from 'uuid'
import { Card, CardContent } from '@/components/ui/card'
@@ -13,6 +13,7 @@ import { useToast } from '@/components/ui/use-toast'
import { useAuth } from '@/auth/AuthContext'
import { AppFooter } from '@/components/AppFooter'
import { AppHeader } from '@/components/AppHeader'
import { RequireRole } from '@/components/RequireRole'
const SAMPLE_PROCESSES = [
{
@@ -43,14 +44,6 @@ export function ImportPage() {
const [isProcessing, setIsProcessing] = useState(false)
const [loadingSampleId, setLoadingSampleId] = useState<string | null>(null)
useEffect(() => {
if (!user) return
const allowed = ['platform_admin', 'member', 'client_editor']
if (!allowed.includes(user.platformRole)) {
void navigate({ to: '/' })
}
}, [user, navigate])
// groupId viene de la URL cuando el usuario importa desde dentro de un grupo
const search = useSearch({ from: '/import' })
const targetGroupId = (search as { groupId?: string }).groupId ?? null
@@ -166,7 +159,7 @@ export function ImportPage() {
console.error(err)
}
}
}, [navigate, toast])
}, [navigate, toast, user])
const onDrop = useCallback((e: React.DragEvent) => {
e.preventDefault()
@@ -200,9 +193,8 @@ export function ImportPage() {
}
}
if (user?.platformRole === 'client_viewer') return null
return (
<RequireRole roles={['platform_admin', 'member', 'client_editor']}>
<div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex flex-col">
<AppHeader />
<div className="flex-1 flex flex-col items-center justify-center p-6">
@@ -314,5 +306,6 @@ export function ImportPage() {
<AppFooter />
</div>
</div>
</RequireRole>
)
}

View File

@@ -14,6 +14,7 @@ function toRow(process: Process, userId: string) {
automation_investment: process.automationInvestment,
group_id: process.groupId,
area_id: process.areaId,
org_id: process.orgId ?? null,
tags: process.tags,
// owner_id se preserva del valor existente en el proceso; solo se inicializa con userId en creates
owner_id: process.ownerId || userId,

View File

@@ -0,0 +1,99 @@
/**
* Edge Function: delete-user
* Propósito: eliminación permanente de un usuario (hard delete de auth.users + public.users).
* Solo accesible por platform_admin. No reversible.
* Variables de entorno: SUPABASE_URL y SUPABASE_SERVICE_ROLE_KEY (auto-disponibles en Edge Functions).
* Deploy: supabase functions deploy delete-user
*/
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
interface DeleteUserRequest {
userId: string
}
Deno.serve(async (req: Request) => {
const headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}
if (req.method === 'OPTIONS') {
return new Response('ok', { headers })
}
if (req.method !== 'POST') {
return new Response(JSON.stringify({ error: 'Método no permitido' }), { status: 405, headers })
}
const adminClient = createClient(
Deno.env.get('SUPABASE_URL')!,
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
)
// ── 1. Autenticar al llamador ──────────────────────────────────────────────
const callerToken = req.headers.get('Authorization')?.replace('Bearer ', '')
if (!callerToken) {
return new Response(JSON.stringify({ error: 'Authorization header requerido' }), { status: 401, headers })
}
const { data: { user: caller }, error: authError } = await adminClient.auth.getUser(callerToken)
if (authError || !caller) {
return new Response(JSON.stringify({ error: 'Token inválido o expirado' }), { status: 401, headers })
}
const { data: callerProfile, error: profileError } = await adminClient
.from('users')
.select('platform_role')
.eq('id', caller.id)
.single()
if (profileError || callerProfile?.platform_role !== 'platform_admin') {
return new Response(
JSON.stringify({ error: 'Forbidden: solo platform_admin puede eliminar usuarios' }),
{ status: 403, headers },
)
}
// ── 2. Parsear body ────────────────────────────────────────────────────────
let body: DeleteUserRequest
try {
body = await req.json() as DeleteUserRequest
} catch {
return new Response(JSON.stringify({ error: 'Body JSON inválido' }), { status: 400, headers })
}
const { userId } = body
if (!userId?.trim()) {
return new Response(JSON.stringify({ error: 'El campo userId es requerido' }), { status: 400, headers })
}
// ── 3. Prevenir auto-eliminación ──────────────────────────────────────────
if (userId === caller.id) {
return new Response(
JSON.stringify({ error: 'No puedes eliminar tu propia cuenta' }),
{ status: 400, headers },
)
}
// ── 4. Eliminar de public.users primero (CASCADE, pero por seguridad explícita) ─
await adminClient.from('users').delete().eq('id', userId)
// ── 5. Hard delete de auth.users ─────────────────────────────────────────
const { error: deleteError } = await adminClient.auth.admin.deleteUser(userId)
if (deleteError) {
return new Response(
JSON.stringify({ error: `Error al eliminar usuario: ${deleteError.message}` }),
{ status: 500, headers },
)
}
return new Response(JSON.stringify({ success: true }), { status: 200, headers })
})

View File

@@ -0,0 +1,74 @@
/**
* Edge Function: list-users
* Propósito: devuelve usuarios de public.users con email de auth.users (requiere service_role).
* Solo accesible por platform_admin.
* Deploy: supabase functions deploy list-users
*/
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
Deno.serve(async (req: Request) => {
const headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}
if (req.method === 'OPTIONS') {
return new Response('ok', { headers })
}
const adminClient = createClient(
Deno.env.get('SUPABASE_URL')!,
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
)
// ── 1. Autenticar al llamador ──────────────────────────────────────────────
const callerToken = req.headers.get('Authorization')?.replace('Bearer ', '')
if (!callerToken) {
return new Response(JSON.stringify({ error: 'Authorization header requerido' }), { status: 401, headers })
}
const { data: { user: caller }, error: authError } = await adminClient.auth.getUser(callerToken)
if (authError || !caller) {
return new Response(JSON.stringify({ error: 'Token inválido o expirado' }), { status: 401, headers })
}
const { data: callerProfile, error: profileError } = await adminClient
.from('users')
.select('platform_role')
.eq('id', caller.id)
.single()
if (profileError || callerProfile?.platform_role !== 'platform_admin') {
return new Response(
JSON.stringify({ error: 'Forbidden: solo platform_admin puede listar usuarios con email' }),
{ status: 403, headers },
)
}
// ── 2. Obtener emails de auth.users ───────────────────────────────────────
const { data: authData, error: listError } = await adminClient.auth.admin.listUsers({
page: 1,
perPage: 1000,
})
if (listError) {
return new Response(
JSON.stringify({ error: `Error al listar usuarios: ${listError.message}` }),
{ status: 500, headers },
)
}
// ── 3. Devolver mapa id → email ───────────────────────────────────────────
const result = (authData?.users ?? []).map((u) => ({
id: u.id,
email: u.email ?? null,
}))
return new Response(JSON.stringify(result), { status: 200, headers })
})

View File

@@ -0,0 +1,143 @@
-- seed_client_processes.sql
-- Distribuye procesos de InQuality a los demás clientes para testing.
-- Duplica entre 5 y 10 procesos aleatorios por org (deep copy: proceso + actividades + gateways + resource assignments).
-- Los procesos de InQuality NO se modifican ni eliminan.
-- Ejecutar desde el SQL Editor de Supabase (o psql con service_role).
DO $$
DECLARE
inquality_org_id uuid;
client_org record;
source_proc record;
new_proc_id uuid;
source_act record;
new_act_id uuid;
proc_count int := 0;
BEGIN
-- Obtener InQuality (is_provider = true)
SELECT id INTO inquality_org_id
FROM organizations
WHERE is_provider = true
LIMIT 1;
IF inquality_org_id IS NULL THEN
RAISE EXCEPTION 'No se encontró una organización con is_provider = true';
END IF;
RAISE NOTICE 'InQuality org_id: %', inquality_org_id;
-- Para cada org cliente
FOR client_org IN
SELECT id, name
FROM organizations
WHERE is_provider = false
ORDER BY name
LOOP
proc_count := 0;
RAISE NOTICE '→ Distribuyendo a: %', client_org.name;
-- Seleccionar entre 5 y 10 procesos aleatorios de InQuality
FOR source_proc IN
SELECT *
FROM processes
WHERE org_id = inquality_org_id
ORDER BY RANDOM()
LIMIT 5 + FLOOR(RANDOM() * 6)::int -- 5..10 inclusive
LOOP
new_proc_id := gen_random_uuid();
-- 1. Duplicar proceso
INSERT INTO processes (
id, name, client, bpmn_xml, currency,
overhead_percentage, annual_frequency, analysis_horizon_years,
automation_investment, group_id, area_id, org_id, tags,
owner_id, created_by, updated_by, updated_at
) VALUES (
new_proc_id,
source_proc.name,
source_proc.client,
source_proc.bpmn_xml,
source_proc.currency,
source_proc.overhead_percentage,
source_proc.annual_frequency,
source_proc.analysis_horizon_years,
source_proc.automation_investment,
NULL, -- group_id: columna legacy, no asignar
NULL, -- area_id: sin área; asignar manualmente si aplica
client_org.id, -- org destino
source_proc.tags,
source_proc.owner_id,
source_proc.created_by,
source_proc.updated_by,
NOW()
);
-- 2. Duplicar actividades + sus resource assignments
FOR source_act IN
SELECT * FROM activities WHERE process_id = source_proc.id
LOOP
new_act_id := gen_random_uuid();
INSERT INTO activities (
id, process_id, bpmn_element_id, name, type,
direct_cost_fixed, execution_time_minutes,
automatable, automated_cost_fixed, automated_time_minutes,
created_by, updated_by, created_at, updated_at
) VALUES (
new_act_id,
new_proc_id,
source_act.bpmn_element_id,
source_act.name,
source_act.type,
source_act.direct_cost_fixed,
source_act.execution_time_minutes,
source_act.automatable,
source_act.automated_cost_fixed,
source_act.automated_time_minutes,
source_act.created_by,
source_act.updated_by,
NOW(),
NOW()
);
-- Copiar resource assignments para esta actividad (si los hay)
INSERT INTO activity_resource_assignments (
id, activity_id, resource_id, utilization_minutes, units, scenario
)
SELECT
gen_random_uuid(),
new_act_id,
resource_id,
utilization_minutes,
units,
scenario
FROM activity_resource_assignments
WHERE activity_id = source_act.id;
END LOOP;
-- 3. Duplicar gateways
INSERT INTO gateways (
id, process_id, bpmn_element_id, gateway_type, branches,
created_at, updated_at
)
SELECT
gen_random_uuid(),
new_proc_id,
bpmn_element_id,
gateway_type,
branches,
NOW(),
NOW()
FROM gateways
WHERE process_id = source_proc.id;
proc_count := proc_count + 1;
RAISE NOTICE ' ✓ %', source_proc.name;
END LOOP;
RAISE NOTICE ' → % procesos duplicados para %', proc_count, client_org.name;
END LOOP;
RAISE NOTICE 'Script completado.';
END $$;