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.
163 lines
5.0 KiB
TypeScript
163 lines
5.0 KiB
TypeScript
/**
|
|
* Tests de renderizado condicional en LibraryPage según el rol del usuario.
|
|
* Verifica que el botón "Importar BPMN" y el panel de grupos se muestran
|
|
* solo para roles internos (platform_admin / member).
|
|
*/
|
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
import { render, screen } from '@testing-library/react'
|
|
import React from 'react'
|
|
|
|
// ─── Referencias mutables para controlar el rol durante los tests ─────────────
|
|
|
|
const { authUserRef, libStoreRef } = vi.hoisted(() => {
|
|
const authUserRef = {
|
|
current: {
|
|
id: 'user-1',
|
|
email: 'test@test.com',
|
|
name: 'Test User',
|
|
platformRole: 'platform_admin' as string,
|
|
},
|
|
isProfileLoaded: true,
|
|
}
|
|
const sampleProcess = {
|
|
id: 'proc-1',
|
|
name: 'Proceso de prueba',
|
|
ownerId: 'user-1',
|
|
ownerName: 'Test User',
|
|
updaterName: 'Test User',
|
|
groupId: null,
|
|
tags: [],
|
|
updatedAt: Date.now(),
|
|
bpmnXml: '',
|
|
annualFrequency: 1,
|
|
analysisHorizonYears: 3,
|
|
automationInvestment: 0,
|
|
currency: 'USD',
|
|
clientName: null,
|
|
overhead: 0,
|
|
isShared: false,
|
|
orgId: null,
|
|
}
|
|
const sampleGroup = {
|
|
id: 'grp-1',
|
|
processId: 'proc-1',
|
|
name: 'Banca',
|
|
createdAt: Date.now(),
|
|
ownerId: 'user-1',
|
|
}
|
|
const libStoreRef = {
|
|
groups: [sampleGroup],
|
|
processes: [sampleProcess],
|
|
settings: { groupLabel: 'Área', groupLabelPlural: 'Áreas', currency: 'USD' },
|
|
isLoading: false,
|
|
error: null,
|
|
load: vi.fn(),
|
|
createGroup: vi.fn(),
|
|
getAllTags: vi.fn().mockReturnValue([]),
|
|
getLatestSimulation: vi.fn().mockResolvedValue(null),
|
|
deleteProcess: vi.fn(),
|
|
}
|
|
return { authUserRef, libStoreRef }
|
|
})
|
|
|
|
vi.mock('@/auth/AuthContext', () => ({
|
|
useAuth: () => ({ user: authUserRef.current, isProfileLoaded: authUserRef.isProfileLoaded }),
|
|
}))
|
|
|
|
vi.mock('@/store/library-store', () => ({
|
|
useLibraryStore: (selector?: (s: typeof libStoreRef) => unknown) =>
|
|
selector ? selector(libStoreRef) : libStoreRef,
|
|
}))
|
|
|
|
vi.mock('@/components/AppHeader', () => ({ AppHeader: () => null }))
|
|
|
|
vi.mock('@tanstack/react-router', () => ({
|
|
useNavigate: () => vi.fn(),
|
|
useSearch: () => ({}),
|
|
Link: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
|
}))
|
|
|
|
vi.mock('@/components/ui/use-toast', () => ({
|
|
useToast: () => ({ message: null, show: vi.fn() }),
|
|
}))
|
|
|
|
// Importar después de los mocks
|
|
import { LibraryPage } from '@/features/library/LibraryPage'
|
|
|
|
// ─── Tests ────────────────────────────────────────────────────────────────────
|
|
|
|
describe('LibraryPage — visibilidad de controles según rol', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
libStoreRef.load = vi.fn()
|
|
libStoreRef.getAllTags = vi.fn().mockReturnValue([])
|
|
libStoreRef.getLatestSimulation = vi.fn().mockResolvedValue(null)
|
|
authUserRef.isProfileLoaded = true
|
|
})
|
|
|
|
describe('isProfileLoaded = false (sync en curso)', () => {
|
|
beforeEach(() => {
|
|
authUserRef.current = { ...authUserRef.current, platformRole: 'platform_admin' }
|
|
authUserRef.isProfileLoaded = false
|
|
})
|
|
|
|
it('NO muestra el botón "Importar BPMN" mientras el perfil no está cargado', () => {
|
|
render(<LibraryPage />)
|
|
expect(screen.queryByText('Importar BPMN')).not.toBeInTheDocument()
|
|
})
|
|
|
|
it('NO muestra el panel de grupos mientras el perfil no está cargado', () => {
|
|
render(<LibraryPage />)
|
|
expect(screen.queryByTestId('groups-header')).not.toBeInTheDocument()
|
|
})
|
|
})
|
|
|
|
describe('platform_admin', () => {
|
|
beforeEach(() => {
|
|
authUserRef.current = { ...authUserRef.current, platformRole: 'platform_admin' }
|
|
})
|
|
|
|
it('muestra el botón "Importar BPMN"', () => {
|
|
render(<LibraryPage />)
|
|
expect(screen.getByText('Importar BPMN')).toBeInTheDocument()
|
|
})
|
|
|
|
it('muestra el panel de grupos (header de sección)', () => {
|
|
render(<LibraryPage />)
|
|
expect(screen.getByTestId('groups-header')).toBeInTheDocument()
|
|
})
|
|
})
|
|
|
|
describe('client_editor', () => {
|
|
beforeEach(() => {
|
|
authUserRef.current = { ...authUserRef.current, platformRole: 'client_editor' }
|
|
})
|
|
|
|
it('NO muestra el botón "Importar BPMN"', () => {
|
|
render(<LibraryPage />)
|
|
expect(screen.queryByText('Importar BPMN')).not.toBeInTheDocument()
|
|
})
|
|
|
|
it('NO muestra el panel de grupos', () => {
|
|
render(<LibraryPage />)
|
|
expect(screen.queryByTestId('groups-header')).not.toBeInTheDocument()
|
|
})
|
|
})
|
|
|
|
describe('client_viewer', () => {
|
|
beforeEach(() => {
|
|
authUserRef.current = { ...authUserRef.current, platformRole: 'client_viewer' }
|
|
})
|
|
|
|
it('NO muestra el botón "Importar BPMN"', () => {
|
|
render(<LibraryPage />)
|
|
expect(screen.queryByText('Importar BPMN')).not.toBeInTheDocument()
|
|
})
|
|
|
|
it('NO muestra el panel de grupos', () => {
|
|
render(<LibraryPage />)
|
|
expect(screen.queryByTestId('groups-header')).not.toBeInTheDocument()
|
|
})
|
|
})
|
|
})
|