feat(countries): implement CRUD operations and UI for country management, including dialogs and data table with infinite scroll

This commit is contained in:
2025-11-02 15:40:26 -06:00
parent 39365f4e83
commit 27b5880524
10 changed files with 1072 additions and 0 deletions

View File

@@ -0,0 +1,78 @@
/**
* API Client para Countries
* Gestiona las operaciones CRUD para los países
*/
import { api } from '$lib/api';
export interface Country {
m3_key: string;
mex_key: string;
ame_key: string;
description_es: string;
description_en: string;
}
export interface CountryListResponse {
items: Country[];
total: number;
page: number;
page_size: number;
}
export interface CreateCountryData {
m3_key: string;
mex_key: string;
ame_key: string;
description_es: string;
description_en: string;
}
export interface UpdateCountryData {
m3_key?: string;
mex_key?: string;
ame_key?: string;
description_es?: string;
description_en?: string;
}
/**
* API para Countries
*/
export const countriesApi = {
/**
* Lista todos los países con paginación
* @param page - Número de página (por defecto 1)
* @param pageSize - Tamaño de página (por defecto 50)
*/
list: (page = 1, pageSize = 50) =>
api.get<CountryListResponse>(
`/v1/countries?page=${page}&page_size=${pageSize}`
),
/**
* Obtiene un país por su clave M3
* @param m3_key - Clave M3 del país
*/
get: (m3_key: string) => api.get<Country>(`/v1/countries/${m3_key}`),
/**
* Crea un nuevo país
* @param data - Datos del país a crear
*/
create: (data: CreateCountryData) =>
api.post<Country>('/v1/countries', data),
/**
* Actualiza un país existente
* @param m3_key - Clave M3 del país a actualizar
* @param data - Datos a actualizar
*/
update: (m3_key: string, data: UpdateCountryData) =>
api.put<Country>(`/v1/countries/${m3_key}`, data),
/**
* Elimina un país
* @param m3_key - Clave M3 del país a eliminar
*/
delete: (m3_key: string) => api.delete(`/v1/countries/${m3_key}`)
};

View File

@@ -0,0 +1,94 @@
import type { ColumnDef } from "@tanstack/table-core";
import { renderComponent, renderSnippet } from "$lib/components/ui/data-table/index.js";
import { createRawSnippet } from "svelte";
import DataTableActions from "./data-table-actions.svelte";
export type Country = {
m3_key: string;
mex_key: string;
ame_key: string;
description_es: string;
description_en: string;
};
export function createColumns(onSuccess?: () => void): ColumnDef<Country>[] {
return [
{
accessorKey: "m3_key",
header: "Clave M3",
cell: ({ row }) => {
const codeSnippet = createRawSnippet<[{ code: string }]>((getCode) => {
const { code } = getCode();
return {
render: () =>
`<code class="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm">${code}</code>`
};
});
return renderSnippet(codeSnippet, { code: row.original.m3_key });
}
},
{
accessorKey: "mex_key",
header: "Clave MX",
cell: ({ row }) => {
const codeSnippet = createRawSnippet<[{ code: string }]>((getCode) => {
const { code } = getCode();
return {
render: () =>
`<code class="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm">${code}</code>`
};
});
return renderSnippet(codeSnippet, { code: row.original.mex_key });
}
},
{
accessorKey: "ame_key",
header: "Clave AME",
cell: ({ row }) => {
const codeSnippet = createRawSnippet<[{ code: string }]>((getCode) => {
const { code } = getCode();
return {
render: () =>
`<code class="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm">${code}</code>`
};
});
return renderSnippet(codeSnippet, { code: row.original.ame_key });
}
},
{
accessorKey: "description_es",
header: "Descripción (ES)",
cell: ({ row }) => {
const descSnippet = createRawSnippet<[{ description: string }]>((getDesc) => {
const { description } = getDesc();
return {
render: () => `<div class="max-w-[300px] truncate">${description}</div>`
};
});
return renderSnippet(descSnippet, { description: row.original.description_es });
}
},
{
accessorKey: "description_en",
header: "Descripción (EN)",
cell: ({ row }) => {
const descSnippet = createRawSnippet<[{ description: string }]>((getDesc) => {
const { description } = getDesc();
return {
render: () => `<div class="max-w-[300px] truncate">${description}</div>`
};
});
return renderSnippet(descSnippet, { description: row.original.description_en });
}
},
{
id: "actions",
cell: ({ row }) => {
return renderComponent(DataTableActions, { item: row.original, onSuccess });
}
}
];
}
// Mantener compatibilidad hacia atrás
export const columns = createColumns();

View File

@@ -0,0 +1,239 @@
<script lang="ts">
import { Button } from "$lib/components/ui/button";
import * as Dialog from "$lib/components/ui/dialog";
import { Input } from "$lib/components/ui/input";
import { Label } from "$lib/components/ui/label";
import { countriesApi, type Country, type CreateCountryData, type UpdateCountryData } from "$lib/api/dashboard/refrence_data/countries";
let {
open = $bindable(false),
item = $bindable<Country | null>(null),
onSuccess
}: {
open: boolean;
item?: Country | null;
onSuccess?: () => void;
} = $props();
let formData = $state({
m3_key: "",
mex_key: "",
ame_key: "",
description_es: "",
description_en: ""
});
let loading = $state(false);
let error = $state<string | null>(null);
// Actualizar formData cuando item cambia
$effect(() => {
if (item) {
formData = {
m3_key: item.m3_key,
mex_key: item.mex_key,
ame_key: item.ame_key,
description_es: item.description_es,
description_en: item.description_en,
};
} else {
formData = {
m3_key: "",
mex_key: "",
ame_key: "",
description_es: "",
description_en: "",
};
}
});
const isEditing = $derived(!!item);
async function handleSubmit(e: Event) {
e.preventDefault();
loading = true;
error = null;
try {
let response;
if (isEditing && item) {
const payload: UpdateCountryData = {
m3_key: formData.m3_key,
mex_key: formData.mex_key,
ame_key: formData.ame_key,
description_es: formData.description_es,
description_en: formData.description_en
};
response = await countriesApi.update(item.m3_key, payload);
} else {
const payload: CreateCountryData = {
m3_key: formData.m3_key,
mex_key: formData.mex_key,
ame_key: formData.ame_key,
description_es: formData.description_es,
description_en: formData.description_en
};
response = await countriesApi.create(payload);
}
if (response.error) {
// Si es error de autenticación y ya se intentó refrescar, el API lo manejará
// pero mostramos un mensaje más claro
if (response.status === 401) {
error = 'Sesión expirada. Recargando página...';
setTimeout(() => {
window.location.reload();
}, 1500);
} else {
error = response.error;
}
return;
}
// Éxito
open = false;
if (onSuccess) {
onSuccess();
}
} catch (e) {
error = e instanceof Error ? e.message : "Error al guardar";
console.error("Error saving:", e);
} finally {
loading = false;
}
}
function handleOpenChange(newOpen: boolean) {
if (!newOpen) {
// Limpiar form al cerrar
formData = {
m3_key: "",
mex_key: "",
ame_key: "",
description_es: "",
description_en: "",
};
error = null;
}
open = newOpen;
}
</script>
<Dialog.Root bind:open onOpenChange={handleOpenChange}>
<Dialog.Content class="sm:max-w-[600px]">
<Dialog.Header>
<Dialog.Title>
{isEditing ? "Editar" : "Nuevo"} País
</Dialog.Title>
<Dialog.Description>
{isEditing
? "Modifica los datos del país."
: "Completa los datos para crear un nuevo país."}
</Dialog.Description>
</Dialog.Header>
<form onsubmit={handleSubmit} class="space-y-4">
{#if error}
<div class="rounded-lg border border-destructive bg-destructive/10 p-3 text-sm text-destructive">
{error}
</div>
{/if}
<div class="grid grid-cols-3 gap-4">
<div class="space-y-2">
<Label for="m3_key">Clave M3 *</Label>
<Input
id="m3_key"
bind:value={formData.m3_key}
placeholder="Ej: MEX"
maxlength={3}
required
disabled={loading || isEditing}
/>
</div>
<div class="space-y-2">
<Label for="mex_key">Clave MX *</Label>
<Input
id="mex_key"
bind:value={formData.mex_key}
placeholder="Ej: MX"
maxlength={2}
required
disabled={loading}
/>
</div>
<div class="space-y-2">
<Label for="ame_key">Clave AME *</Label>
<Input
id="ame_key"
bind:value={formData.ame_key}
placeholder="Ej: MX"
maxlength={2}
required
disabled={loading}
/>
</div>
</div>
<div class="space-y-2">
<Label for="description_es">Descripción en Español *</Label>
<Input
id="description_es"
bind:value={formData.description_es}
placeholder="Ej: México"
required
disabled={loading}
/>
</div>
<div class="space-y-2">
<Label for="description_en">Descripción en Inglés *</Label>
<Input
id="description_en"
bind:value={formData.description_en}
placeholder="Ej: Mexico"
required
disabled={loading}
/>
</div>
<Dialog.Footer>
<Button
type="button"
variant="outline"
onclick={() => (open = false)}
disabled={loading}
>
Cancelar
</Button>
<Button type="submit" disabled={loading}>
{#if loading}
<svg
class="mr-2 h-4 w-4 animate-spin"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
class="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
stroke-width="4"
></circle>
<path
class="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
{/if}
{isEditing ? "Guardar cambios" : "Crear"}
</Button>
</Dialog.Footer>
</form>
</Dialog.Content>
</Dialog.Root>

View File

@@ -0,0 +1,66 @@
<script lang="ts">
import EllipsisIcon from "@lucide/svelte/icons/ellipsis";
import { Button } from "$lib/components/ui/button/index.js";
import * as DropdownMenu from "$lib/components/ui/dropdown-menu/index.js";
import type { Country } from "./columns.js";
import CreateEditDialog from "./create-edit-dialog.svelte";
import DetailsDialog from "./details-dialog.svelte";
import DeleteDialog from "./delete-dialog.svelte";
let {
item,
onSuccess
}: {
item: Country;
onSuccess?: () => void;
} = $props();
let showDetailsDialog = $state(false);
let showEditDialog = $state(false);
let showDeleteDialog = $state(false);
function handleCopyId() {
navigator.clipboard.writeText(item.m3_key.toString());
}
function handleViewDetails() {
showDetailsDialog = true;
}
function handleEdit() {
showEditDialog = true;
}
function handleDelete() {
showDeleteDialog = true;
}
</script>
<DropdownMenu.Root>
<DropdownMenu.Trigger>
{#snippet child({ props })}
<Button {...props} variant="ghost" size="icon" class="relative size-8 p-0">
<span class="sr-only">Abrir menú</span>
<EllipsisIcon class="size-4" />
</Button>
{/snippet}
</DropdownMenu.Trigger>
<DropdownMenu.Content align="end">
<DropdownMenu.Group>
<DropdownMenu.Label>Acciones</DropdownMenu.Label>
<DropdownMenu.Item onclick={handleCopyId}>
Copiar ID
</DropdownMenu.Item>
</DropdownMenu.Group>
<DropdownMenu.Separator />
<DropdownMenu.Item onclick={handleViewDetails}>Ver detalles</DropdownMenu.Item>
<DropdownMenu.Item onclick={handleEdit}>Editar</DropdownMenu.Item>
<DropdownMenu.Separator />
<DropdownMenu.Item class="text-destructive" onclick={handleDelete}>Eliminar</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
<!-- Dialogs -->
<DetailsDialog bind:open={showDetailsDialog} {item} />
<CreateEditDialog bind:open={showEditDialog} bind:item {onSuccess} />
<DeleteDialog bind:open={showDeleteDialog} {item} {onSuccess} />

View File

@@ -0,0 +1,123 @@
<script lang="ts" generics="TData, TValue">
import { onMount } from 'svelte';
import {
type ColumnDef,
getCoreRowModel
} from "@tanstack/table-core";
import { createSvelteTable, FlexRender } from "$lib/components/ui/data-table/index.js";
import * as Table from "$lib/components/ui/table/index.js";
type DataTableProps<TData, TValue> = {
columns: ColumnDef<TData, TValue>[];
data: TData[];
loading: boolean;
hasMore: boolean;
loadMore: () => void;
};
let {
data,
columns,
loading,
hasMore,
loadMore
}: DataTableProps<TData, TValue> = $props();
const table = createSvelteTable({
get data() {
return data;
},
columns,
getCoreRowModel: getCoreRowModel()
});
let scrollContainer = $state<HTMLDivElement>();
let loadingTrigger = $state<HTMLDivElement>();
// Intersection Observer para detectar cuando el usuario llega al final
onMount(() => {
const observer = new IntersectionObserver(
(entries) => {
const [entry] = entries;
if (entry.isIntersecting && hasMore && !loading) {
loadMore();
}
},
{
root: scrollContainer,
threshold: 0.1
}
);
if (loadingTrigger) {
observer.observe(loadingTrigger);
}
return () => {
observer.disconnect();
};
});
</script>
<div class="w-full">
<div class="rounded-md border max-h-[600px] overflow-y-auto" bind:this={scrollContainer}>
<Table.Root>
<Table.Header class="sticky top-0 bg-background z-10">
{#each table.getHeaderGroups() as headerGroup (headerGroup.id)}
<Table.Row>
{#each headerGroup.headers as header (header.id)}
<Table.Head>
{#if !header.isPlaceholder}
<FlexRender
content={header.column.columnDef.header}
context={header.getContext()}
/>
{/if}
</Table.Head>
{/each}
</Table.Row>
{/each}
</Table.Header>
<Table.Body>
{#each table.getRowModel().rows as row (row.id)}
<Table.Row data-state={row.getIsSelected() && "selected"}>
{#each row.getVisibleCells() as cell (cell.id)}
<Table.Cell>
<FlexRender
content={cell.column.columnDef.cell}
context={cell.getContext()}
/>
</Table.Cell>
{/each}
</Table.Row>
{:else}
<Table.Row>
<Table.Cell colspan={columns.length} class="h-24 text-center">
No hay resultados.
</Table.Cell>
</Table.Row>
{/each}
<!-- Loading Trigger - Se activa cuando es visible -->
{#if hasMore}
<Table.Row>
<Table.Cell colspan={columns.length} class="h-20 text-center">
<div bind:this={loadingTrigger}>
{#if loading}
<div class="flex items-center justify-center gap-2">
<div class="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
<span class="text-muted-foreground text-sm">Cargando más...</span>
</div>
{:else}
<div class="text-muted-foreground text-sm">
Desplázate para cargar más
</div>
{/if}
</div>
</Table.Cell>
</Table.Row>
{/if}
</Table.Body>
</Table.Root>
</div>
</div>

View File

@@ -0,0 +1,116 @@
<script lang="ts">
import { Button } from "$lib/components/ui/button";
import * as AlertDialog from "$lib/components/ui/alert-dialog";
import { countriesApi, type Country } from "$lib/api/dashboard/refrence_data/countries";
let {
open = $bindable(false),
item,
onSuccess
}: {
open: boolean;
item: Country | null;
onSuccess?: () => void;
} = $props();
let loading = $state(false);
let error = $state<string | null>(null);
async function handleDelete() {
if (!item) return;
loading = true;
error = null;
try {
const response = await countriesApi.delete(item.m3_key);
if (response.error) {
error = response.error;
return;
}
// Éxito
open = false;
if (onSuccess) {
onSuccess();
}
} catch (e) {
error = e instanceof Error ? e.message : "Error al eliminar";
console.error("Error deleting:", e);
} finally {
loading = false;
}
}
function handleOpenChange(newOpen: boolean) {
if (!newOpen) {
error = null;
}
open = newOpen;
}
</script>
<AlertDialog.Root bind:open onOpenChange={handleOpenChange}>
<AlertDialog.Content>
<AlertDialog.Header>
<AlertDialog.Title>¿Estás seguro?</AlertDialog.Title>
<AlertDialog.Description class="space-y-2">
<p>Esta acción no se puede deshacer. Se eliminará permanentemente este país:</p>
{#if item}
<div class="mt-2 rounded-lg bg-muted p-3 space-y-1">
<div class="flex items-center justify-between text-sm">
<span class="font-medium">Clave M3:</span>
<code class="font-mono">{item.m3_key}</code>
</div>
<div class="flex items-center justify-between text-sm">
<span class="font-medium">Clave MX:</span>
<code class="font-mono">{item.mex_key}</code>
</div>
<div class="flex items-center justify-between text-sm">
<span class="font-medium">Descripción:</span>
<span class="truncate max-w-[200px]">{item.description_es}</span>
</div>
</div>
{/if}
{#if error}
<div class="mt-2 rounded-lg border border-destructive bg-destructive/10 p-3 text-sm text-destructive">
{error}
</div>
{/if}
</AlertDialog.Description>
</AlertDialog.Header>
<AlertDialog.Footer>
<AlertDialog.Cancel disabled={loading}>Cancelar</AlertDialog.Cancel>
<AlertDialog.Action
onclick={handleDelete}
disabled={loading}
class="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{#if loading}
<svg
class="mr-2 h-4 w-4 animate-spin"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
class="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
stroke-width="4"
></circle>
<path
class="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
{/if}
Eliminar
</AlertDialog.Action>
</AlertDialog.Footer>
</AlertDialog.Content>
</AlertDialog.Root>

View File

@@ -0,0 +1,79 @@
<script lang="ts">
import { Button } from "$lib/components/ui/button";
import * as Dialog from "$lib/components/ui/dialog";
import { Separator } from "$lib/components/ui/separator";
import type { Country } from "$lib/api/dashboard/refrence_data/countries";
let {
open = $bindable(false),
item
}: {
open: boolean;
item: Country | null;
} = $props();
function handleOpenChange(newOpen: boolean) {
open = newOpen;
}
</script>
<Dialog.Root bind:open onOpenChange={handleOpenChange}>
<Dialog.Content class="sm:max-w-[600px]">
<Dialog.Header>
<Dialog.Title>Detalles del País</Dialog.Title>
<Dialog.Description>
Información completa del país
</Dialog.Description>
</Dialog.Header>
{#if item}
<div class="space-y-4 py-4">
<div class="grid grid-cols-3 gap-4">
<div class="space-y-2">
<span class="text-sm font-medium text-muted-foreground">Clave M3</span>
<code class="block relative rounded bg-muted px-2 py-1 font-mono text-sm">
{item.m3_key}
</code>
</div>
<div class="space-y-2">
<span class="text-sm font-medium text-muted-foreground">Clave MX</span>
<code class="block relative rounded bg-muted px-2 py-1 font-mono text-sm">
{item.mex_key}
</code>
</div>
<div class="space-y-2">
<span class="text-sm font-medium text-muted-foreground">Clave AME</span>
<code class="block relative rounded bg-muted px-2 py-1 font-mono text-sm">
{item.ame_key}
</code>
</div>
</div>
<Separator />
<div class="space-y-2">
<div class="flex flex-col gap-2">
<span class="text-sm font-medium text-muted-foreground">Descripción en Español</span>
<p class="text-sm">{item.description_es}</p>
</div>
<Separator />
</div>
<div class="space-y-2">
<div class="flex flex-col gap-2">
<span class="text-sm font-medium text-muted-foreground">Descripción en Inglés</span>
<p class="text-sm">{item.description_en}</p>
</div>
<Separator />
</div>
</div>
{/if}
<Dialog.Footer>
<Button variant="outline" onclick={() => (open = false)}>
Cerrar
</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>

View File

@@ -0,0 +1,81 @@
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ cookies, fetch, url, parent }) => {
// Esperar a que el layout padre valide/refresque el token
await parent();
const token = cookies.get('access_token');
if (!token) {
return {
error: 'No authenticated',
items: [],
total: 0,
page: 1,
page_size: 50
};
}
try {
// Obtener parámetros de paginación de la URL
const page = parseInt(url.searchParams.get('page') || '1');
const pageSize = parseInt(url.searchParams.get('page_size') || '50');
// Configurar la URL de la API para SSR
let apiUrl = process.env.INTERNAL_API_URL;
if (!apiUrl) {
apiUrl = import.meta.env.VITE_API_URL;
// Reemplazar 'localhost' con 'backend' para llamadas desde el servidor (SSR)
apiUrl = apiUrl?.replace('localhost', 'backend').replace('127.0.0.1', 'backend');
}
// Normalizar la URL
const baseUrl = apiUrl?.endsWith('/') ? apiUrl : `${apiUrl}/`;
const response = await fetch(
`${baseUrl}v1/countries?page=${page}&page_size=${pageSize}`,
{
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
}
);
if (!response.ok) {
const errorText = await response.text();
console.error('📊 [Countries] API Error:', {
status: response.status,
statusText: response.statusText,
error: errorText
});
return {
error: `Error ${response.status}: ${response.statusText}`,
items: [],
total: 0,
page: page,
page_size: pageSize
};
}
const data = await response.json();
return {
items: data.items || [],
total: data.total || 0,
page: data.page || page,
page_size: data.page_size || pageSize,
error: null
};
} catch (error) {
console.error('📊 [Countries] Load error:', error);
return {
error: 'Error loading data',
items: [],
total: 0,
page: 1,
page_size: 50
};
}
};

View File

@@ -0,0 +1,196 @@
<script lang="ts">
import { onMount } from 'svelte';
import { countriesApi, type Country } from '$lib/api/dashboard/refrence_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 CreateEditDialog from '$lib/components/dashboard/reference_data/countries/create-edit-dialog.svelte';
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import type { PageData } from './$types';
import { browser } from '$app/environment';
// Los datos iniciales vienen del servidor
let { data }: { data: PageData } = $props();
// Estado para el diálogo de crear
let showCreateDialog = $state(false);
// 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}=`);
if (parts.length === 2) return parts.pop()?.split(';').shift() || null;
return null;
};
// Verificar si hay token en las cookies
const cookieToken = getCookie('access_token');
const localToken = localStorage.getItem('access_token');
if (cookieToken && cookieToken !== localToken) {
localStorage.setItem('access_token', cookieToken);
}
// También sincronizar refresh_token si existe
const cookieRefreshToken = getCookie('refresh_token');
const localRefreshToken = localStorage.getItem('refresh_token');
if (cookieRefreshToken && cookieRefreshToken !== localRefreshToken) {
localStorage.setItem('refresh_token', cookieRefreshToken);
}
}
});
// Estado para infinite scroll
let allItems = $state<Country[]>(data.items || []);
let currentPage = $state(data.page || 1);
let pageSize = $state(50);
let totalItems = $state(data.total || 0);
let loading = $state(false);
let hasMore = $derived(allItems.length < totalItems);
let error = $state<string | null>(data.error || null);
async function loadMore() {
if (loading || !hasMore) return;
loading = true;
error = null;
try {
const response = await countriesApi.list(currentPage + 1, pageSize);
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);
} else {
error = response.error;
}
return;
}
if (response.data?.items) {
// Agregar los nuevos items al array existente
allItems = [...allItems, ...response.data.items];
currentPage++;
totalItems = response.data.total;
}
} catch (e) {
error = 'Error cargando más datos';
console.error('📊 [Page] Error loading more:', e);
} finally {
loading = false;
}
}
function reloadData() {
// Reset y recargar desde el principio
window.location.reload();
}
function handleCreateClick() {
showCreateDialog = true;
}
function handleSuccess() {
// Recargar datos después de crear/editar/eliminar
reloadData();
}
// Crear columnas con el callback onSuccess
const columns = createColumns(handleSuccess);
</script>
<div class="space-y-6">
<!-- Header -->
<div class="flex items-center justify-between">
<div>
<h1 class="text-3xl font-bold tracking-tight">Países</h1>
<p class="text-muted-foreground">
Gestiona los países disponibles en el sistema
</p>
</div>
<Button onclick={handleCreateClick}>
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="mr-2"
>
<path d="M5 12h14" />
<path d="M12 5v14" />
</svg>
Nuevo País
</Button>
</div>
<!-- Error Message -->
{#if error}
<Card.Root class="border-destructive">
<Card.Header>
<Card.Title class="text-destructive">Error</Card.Title>
<Card.Description>{error}</Card.Description>
</Card.Header>
</Card.Root>
{/if}
<!-- Data Table -->
<Card.Root>
<Card.Header>
<div class="flex items-center justify-between">
<div>
<Card.Title>Listado de Países</Card.Title>
<Card.Description>
Mostrando {allItems.length} de {totalItems} registros
</Card.Description>
</div>
<Button variant="outline" onclick={reloadData}>
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="mr-2"
>
<path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8" />
<path d="M21 3v5h-5" />
</svg>
Actualizar
</Button>
</div>
</Card.Header>
<Card.Content>
<!-- TanStack DataTable con Infinite Scroll -->
<DataTable
data={allItems}
{columns}
{loading}
{hasMore}
{loadMore}
/>
</Card.Content>
</Card.Root>
</div>
<!-- Diálogo de crear/editar -->
<CreateEditDialog bind:open={showCreateDialog} onSuccess={handleSuccess} />