fix: solución de bloqueos y estandarización de permisos

This commit is contained in:
2026-04-27 10:47:30 -05:00
parent fa3cbb4d0a
commit 5c2a84e95d
312 changed files with 13889 additions and 7911 deletions

View File

@@ -22,9 +22,25 @@ export const load: PageServerLoad = async ({ cookies, fetch, url, parent }) => {
const page = parseInt(url.searchParams.get('page') || '1');
const pageSize = parseInt(url.searchParams.get('page_size') || '50');
const parentData = await parent();
const cookieCompanyId = cookies.get('active_company_id');
const companyId = cookieCompanyId
? parseInt(cookieCompanyId)
: parentData.companies?.[0]?.id;
if (!companyId) {
return {
error: 'No se encontró una compañía seleccionada',
items: [],
total: 0,
page,
page_size: pageSize
};
}
// Usar authenticatedFetch para manejar automáticamente el refresh de tokens
const response = await authenticatedFetch(
`v1/public/reference_data/countries?page=${page}&page_size=${pageSize}`,
`v1/public/reference_data/countries/?page=${page}&page_size=${pageSize}&company_id=${companyId}`,
{},
cookies,
fetch
@@ -39,6 +55,7 @@ export const load: PageServerLoad = async ({ cookies, fetch, url, parent }) => {
});
return {
status: response.status,
error: `Error ${response.status}: ${response.statusText}`,
items: [],
total: 0,
@@ -54,6 +71,7 @@ export const load: PageServerLoad = async ({ cookies, fetch, url, parent }) => {
total: data.total || 0,
page: data.page || page,
page_size: data.page_size || pageSize,
status: response.status,
error: null
};
} catch (error) {

View File

@@ -2,16 +2,18 @@
import { onMount } from 'svelte';
import { countriesApi, type Country } from '$lib/api/dashboard/reference_data/countries';
import DataTable from '$lib/components/dashboard/reference_data/countries/data-table.svelte';
import { createColumns } from '$lib/components/dashboard/reference_data/countries/columns.js';
import { createColumns } from '$lib/components/dashboard/reference_data/countries/columns';
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';
import { RefreshCw } from 'lucide-svelte';
import { RefreshCw, Plus } from 'lucide-svelte';
import { page } from '$app/stores';
import type { PageData } from './$types';
import { useShortcuts } from '$lib/hooks/use-shortcuts';
import { obtenerAtajosLista } from '$lib/config/shortcuts/dashboard/reference_data/countries/list';
import { browser } from '$app/environment';
import { currentUser, userHasPermission } from '$lib/auth';
import ErrorState from '$lib/components/dashboard/common/error-state.svelte';
// Los datos iniciales vienen del servidor
let { data }: { data: PageData } = $props();
@@ -27,7 +29,6 @@
// Sincronizar token de cookies a localStorage al montar el componente
onMount(() => {
if (browser) {
// Función para obtener el valor de una cookie
const getCookie = (name: string): string | null => {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
@@ -35,7 +36,6 @@
return null;
};
// Verificar si hay token en las cookies
const cookieToken = getCookie('access_token');
const localToken = localStorage.getItem('access_token');
@@ -43,7 +43,6 @@
localStorage.setItem('access_token', cookieToken);
}
// También sincronizar refresh_token si existe
const cookieRefreshToken = getCookie('refresh_token');
const localRefreshToken = localStorage.getItem('refresh_token');
@@ -61,6 +60,15 @@
let loading = $state(false);
let hasMore = $derived(allItems.length < totalItems);
let error = $state<string | null>(data.error || null);
let status = $state<number>(data.status || 200);
// Permisos
const canView = $derived(userHasPermission($currentUser, 'ref_countries.view') || userHasPermission($currentUser, 'cat_countries.view'));
const canCreate = $derived(userHasPermission($currentUser, 'ref_countries.create'));
const canEdit = $derived(userHasPermission($currentUser, 'ref_countries.edit'));
const canDelete = $derived(userHasPermission($currentUser, 'ref_countries.delete'));
const isError = $derived(!canView || status >= 400 || error);
// Filtros
let searchQuery = $state($page.url.searchParams.get('search') || '');
@@ -71,6 +79,7 @@
clearTimeout(timeout);
timeout = setTimeout(async () => {
loading = true;
error = null;
try {
const response = await countriesApi.list(1, pageSize, searchQuery);
if (!response.error && response.data) {
@@ -84,7 +93,6 @@
loading = false;
}
// Actualizar URL silenciosamente para mantener estado
const url = new URL($page.url);
if (searchQuery) url.searchParams.set('search', searchQuery);
else url.searchParams.delete('search');
@@ -101,14 +109,10 @@
try {
const response = await countriesApi.list(currentPage + 1, pageSize, searchQuery);
if (response.error) {
console.error('📊 [Page] Error en loadMore:', response.error, 'Status:', response.status);
// Si es un error de autenticación (401 o 403) y no se pudo refrescar, mostrar mensaje específico
if (response.status === 401 || response.status === 403) {
error = 'Sesión expirada. Recargando página...';
// Recargar automáticamente después de 2 segundos
setTimeout(() => {
window.location.reload();
}, 2000);
@@ -119,7 +123,6 @@
}
if (response.data?.items) {
// Agregar los nuevos items al array existente
allItems = [...allItems, ...response.data.items];
currentPage++;
totalItems = response.data.total;
@@ -133,48 +136,71 @@
}
function reloadData() {
// Reset y recargar desde el principio
window.location.reload();
if (browser) window.location.reload();
}
function handleSuccess() {
// Recargar datos después de crear/editar/eliminar
reloadData();
}
// Crear columnas con el callback onSuccess
const columns = createColumns(handleSuccess);
// Crear columnas con el callback onSuccess y permisos
const columns = $derived(createColumns(handleSuccess, { canEdit, canDelete }));
</script>
<div class="flex flex-col gap-6 p-6 h-[calc(100svh-4rem)] group-has-data-[collapsible=icon]/sidebar-wrapper:h-[calc(100svh-3rem)] overflow-hidden">
<!-- Header Section -->
<div class="flex-none flex items-center justify-between">
<div class="space-y-1">
<h1 class="text-2xl font-bold tracking-tight">
Países
</h1>
<p class="text-muted-foreground">
Gestiona los países disponibles en el sistema
</p>
{#if isError}
<ErrorState
status={!canView ? 403 : status}
error={!canView ? 'Permission denied: ref_countries.view' : (error || '')}
onRetry={reloadData}
/>
{:else}
<!-- Header Section -->
<div class="flex-none flex items-center justify-between">
<div class="space-y-1">
<h1 class="text-2xl font-bold tracking-tight">
Países
</h1>
<p class="text-muted-foreground">
Gestiona los países disponibles en el sistema
</p>
</div>
<div class="flex items-center gap-3">
<Button variant="outline" size="sm" class="h-9" onclick={reloadData}>
<RefreshCw class="mr-2 h-4 w-4 {loading ? 'animate-spin' : ''}" />
Actualizar
</Button>
{#if canCreate}
<Button class="h-9" onclick={() => (alert('Módulo de creación no disponible para Catálogos Públicos'))}>
<Plus class="mr-2 h-4 w-4" />
Nuevo País
</Button>
{/if}
</div>
</div>
<div class="flex items-center gap-3">
<Button variant="outline" size="sm" class="h-9" onclick={reloadData}>
<RefreshCw class="mr-2 h-4 w-4" />
Actualizar
</Button>
</div>
</div>
{#if error}
<div class="flex-none rounded-md border border-destructive px-4 py-3 text-sm text-destructive">
{error}
</div>
{#if error}
<div class="flex-none rounded-md border border-destructive px-4 py-3 text-sm text-destructive">
{error}
</div>
{/if}
<Card.Root class="border bg-background flex min-h-0 flex-1 flex-col overflow-hidden">
<Card.Header>
<div class="flex flex-wrap items-center justify-between gap-3">
<Card.Title>Listado de Países</Card.Title>
<div class="flex flex-wrap items-center gap-2">
<Input placeholder="Buscar" bind:value={searchQuery} oninput={handleSearch} class="h-9 w-44 bg-card lg:w-64" />
</div>
</div>
</Card.Header>
<Card.Content class="min-h-0 p-0 flex-1 overflow-hidden flex flex-col">
<div class="rounded-md border bg-background overflow-hidden flex-1 h-full">
<DataTable data={allItems} {columns} {loading} {hasMore} {loadMore} />
</div>
</Card.Content>
</Card.Root>
<div class="flex-none text-sm text-muted-foreground">Mostrando {allItems.length} de {totalItems} registros</div>
{/if}
<Card.Root class="border bg-background flex min-h-0 flex-1 flex-col">
<Card.Header><div class="flex flex-wrap items-center justify-between gap-3"><Card.Title>Listado de Países</Card.Title><div class="flex flex-wrap items-center gap-2"><Input placeholder="Buscar" bind:value={searchQuery} oninput={handleSearch} class="h-9 w-44 bg-card lg:w-64" /></div></div></Card.Header>
<Card.Content class="min-h-0 p-0"><div class="rounded-md border bg-background overflow-hidden flex min-h-0 flex-1 flex-col"><DataTable data={allItems} {columns} {loading} {hasMore} {loadMore} /></div></Card.Content>
</Card.Root>
<div class="flex-none text-sm text-muted-foreground">Mostrando {allItems.length} de {totalItems} registros</div>
</div>