feat: Convertir módulo de clases para usar TenantCRUDRoutes

Cambios en backend:
- Actualizado ClassResponseDTO con campos de tenant y timestamps
- Agregados métodos estáticos en servicio (get_all, get_by_id, create, update, delete)
- Reemplazados endpoints de rutas con inicialización de TenantCRUDRoutes
- Corregida ruta de importación del modelo Company en security.py
- Actualizados nombres de campos en DTO para coincidir con modelo (description_es/en)
- Agregada validación para constraint de foreign key de material_key
- Agregada validación de class_code duplicado en método create
- Agregado TimestampMixin al modelo Class
- Creada migración de Alembic para agregar columnas timestamp a tabla classes
- Corregido orden de parámetros en firma del método update

Cambios en frontend:
- Actualizados componentes de UI para módulo de clases
This commit is contained in:
KevinMrkz3221
2025-11-15 20:05:29 -06:00
parent 836083b428
commit 99aff32eea
15 changed files with 1703 additions and 295 deletions

View File

@@ -0,0 +1,177 @@
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";
import type { A76Class } from "$lib/api/dashboard/a76/classes";
/**
* Formatea una fecha
*/
function formatDate(date?: string | null): string {
if (!date) return '-';
return new Date(date).toLocaleDateString('es-MX', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
});
}
/**
* Obtiene el color del badge según el tipo de revisión física
*/
function getReviewColor(physicalReview: number): string {
return physicalReview === 1
? 'bg-yellow-100 text-yellow-800'
: 'bg-green-100 text-green-800';
}
export function createColumns(onSuccess?: () => void): ColumnDef<A76Class>[] {
return [
{
accessorKey: "id",
header: "ID",
cell: ({ row }) => {
const idSnippet = createRawSnippet<[{ id: number }]>((getId) => {
const { id } = getId();
return {
render: () =>
`<div class="font-medium">#${id}</div>`
};
});
return renderSnippet(idSnippet, { id: row.original.id });
}
},
{
accessorKey: "class_code",
header: "Código de Clase",
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 font-semibold">${code}</code>`
};
});
return renderSnippet(codeSnippet, { code: row.original.class_code });
}
},
{
accessorKey: "description_es",
header: "Descripción",
cell: ({ row }) => {
const description = row.original.description_es || row.original.description_en || '-';
const descSnippet = createRawSnippet<[{ desc: string }]>((getDesc) => {
const { desc } = getDesc();
return {
render: () =>
`<div class="max-w-xs truncate" title="${desc}">${desc}</div>`
};
});
return renderSnippet(descSnippet, { desc: description });
}
},
{
accessorKey: "fraction",
header: "Fracción",
cell: ({ row }) => {
const fractionSnippet = createRawSnippet<[{ fraction: string }]>((getFraction) => {
const { fraction } = getFraction();
return {
render: () =>
`<div class="font-mono text-sm">${fraction}</div>`
};
});
return renderSnippet(fractionSnippet, { fraction: row.original.fraction });
}
},
{
accessorKey: "us_fraction",
header: "Fracción US",
cell: ({ row }) => {
const usFractionSnippet = createRawSnippet<[{ usFraction: string }]>((getUsFraction) => {
const { usFraction } = getUsFraction();
return {
render: () =>
`<div class="font-mono text-sm">${usFraction}</div>`
};
});
return renderSnippet(usFractionSnippet, { usFraction: row.original.us_fraction });
}
},
{
accessorKey: "unit_of_measure",
header: "Unidad",
cell: ({ row }) => {
const unitSnippet = createRawSnippet<[{ unit: string }]>((getUnit) => {
const { unit } = getUnit();
return {
render: () =>
`<span class="inline-flex items-center rounded-full bg-blue-100 text-blue-800 px-2.5 py-0.5 text-xs font-medium">
${unit}
</span>`
};
});
return renderSnippet(unitSnippet, { unit: row.original.unit_of_measure });
}
},
{
accessorKey: "physical_review",
header: "Rev. Física",
cell: ({ row }) => {
const review = row.original.physical_review;
const colorClass = getReviewColor(review);
const label = review === 1 ? 'Sí' : 'No';
const reviewSnippet = createRawSnippet<[{ label: string; colorClass: string }]>((getReview) => {
const { label, colorClass } = getReview();
return {
render: () =>
`<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${colorClass}">
${label}
</span>`
};
});
return renderSnippet(reviewSnippet, { label, colorClass });
}
},
{
accessorKey: "client_id",
header: "Cliente",
cell: ({ row }) => {
const clientSnippet = createRawSnippet<[{ clientId: number }]>((getClient) => {
const { clientId } = getClient();
return {
render: () =>
`<div class="text-sm">Cliente #${clientId}</div>`
};
});
return renderSnippet(clientSnippet, { clientId: row.original.client_id });
}
},
{
accessorKey: "created_at",
header: "Fecha de Creación",
cell: ({ row }) => {
const dateSnippet = createRawSnippet<[{ date: string }]>((getDate) => {
const { date } = getDate();
return {
render: () =>
`<div class="text-sm text-muted-foreground">${date}</div>`
};
});
return renderSnippet(dateSnippet, { date: formatDate(row.original.created_at) });
}
},
{
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,464 @@
<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 { Textarea } from "$lib/components/ui/textarea";
import * as Select from "$lib/components/ui/select";
import { classesApi, type A76Class, type A76ClassCreate, type A76ClassUpdate } from "$lib/api/dashboard/a76/classes";
import { materialTypesApi, type MaterialType } from "$lib/api/dashboard/refrence_data/material_types";
import { companyStore } from "$lib/stores/company.svelte";
import { onMount } from 'svelte';
let {
open = $bindable(false),
item = null,
onSuccess
}: {
open: boolean;
item?: A76Class | null;
onSuccess?: () => void;
} = $props();
// Determinar si es modo edición o creación
const isEdit = $derived(!!item);
const title = $derived(isEdit ? "Editar Clase" : "Nueva Clase");
// Estado del formulario
let formData = $state({
class_code: item?.class_code || '',
description_es: item?.description_es || '',
description_en: item?.description_en || '',
material_key: item?.material_key || '',
unit_of_measure: item?.unit_of_measure || 'KG',
fraction: item?.fraction || '',
us_fraction: item?.us_fraction || '',
sub_key: item?.sub_key || '',
physical_review: item?.physical_review || 0,
iva_exempt_fraction: item?.iva_exempt_fraction || ''
});
let loading = $state(false);
let error = $state<string | null>(null);
let materialTypes = $state<MaterialType[]>([]);
let loadingMaterialTypes = $state(false);
// Variables para controlar los selects
let selectedUnitValue = $state<string>('KG');
let selectedMaterialValue = $state<string>('');
let selectedPhysicalReviewValue = $state<number>(0);
// Cargar tipos de materiales al montar
onMount(async () => {
loadingMaterialTypes = true;
try {
const response = await materialTypesApi.list(1, 100); // Cargar los primeros 100
if (response.data) {
materialTypes = response.data.items;
}
} catch (e) {
console.error('Error loading material types:', e);
} finally {
loadingMaterialTypes = false;
}
});
// Resetear formulario cuando cambia el item
$effect(() => {
if (item) {
formData = {
class_code: item.class_code,
description_es: item.description_es || '',
description_en: item.description_en || '',
material_key: item.material_key || '',
unit_of_measure: item.unit_of_measure,
fraction: item.fraction,
us_fraction: item.us_fraction,
sub_key: item.sub_key,
physical_review: item.physical_review,
iva_exempt_fraction: item.iva_exempt_fraction
};
// Actualizar valores de los selects
selectedUnitValue = item.unit_of_measure;
selectedMaterialValue = item.material_key || '';
selectedPhysicalReviewValue = item.physical_review;
} else {
// Reset para modo crear
formData = {
class_code: '',
description_es: '',
description_en: '',
material_key: '',
unit_of_measure: 'KG',
fraction: '',
us_fraction: '',
sub_key: '',
physical_review: 0,
iva_exempt_fraction: ''
};
// Resetear valores de los selects
selectedUnitValue = 'KG';
selectedMaterialValue = '';
selectedPhysicalReviewValue = 0;
}
error = null;
});
function handleOpenChange(newOpen: boolean) {
open = newOpen;
if (!newOpen) {
error = null;
}
}
async function handleSubmit(e: Event) {
e.preventDefault();
const companyId = companyStore.activeCompany?.id;
if (!companyId) {
error = 'No hay compañía seleccionada';
return;
}
// Validaciones básicas
if (!formData.class_code.trim()) {
error = 'El código de clase es requerido';
return;
}
if (!formData.fraction.trim()) {
error = 'La fracción es requerida';
return;
}
if (!formData.us_fraction.trim()) {
error = 'La fracción US es requerida';
return;
}
if (!formData.sub_key.trim()) {
error = 'La subclave es requerida';
return;
}
if (!formData.iva_exempt_fraction.trim()) {
error = 'La fracción exenta de IVA es requerida';
return;
}
loading = true;
error = null;
try {
let response;
if (isEdit && item) {
// Actualizar
const updateData: A76ClassUpdate = {
class_code: formData.class_code,
description_es: formData.description_es || null,
description_en: formData.description_en || null,
material_key: formData.material_key || null,
unit_of_measure: formData.unit_of_measure,
fraction: formData.fraction,
us_fraction: formData.us_fraction,
sub_key: formData.sub_key,
physical_review: formData.physical_review,
iva_exempt_fraction: formData.iva_exempt_fraction
};
response = await classesApi.update(item.id, updateData, companyId);
} else {
// Crear - usa el company_id como client_id
const createData: A76ClassCreate = {
company_id: companyId,
client_id: companyId, // Usa el mismo company_id como client_id
class_code: formData.class_code,
description_es: formData.description_es || null,
description_en: formData.description_en || null,
material_key: formData.material_key || null,
unit_of_measure: formData.unit_of_measure,
fraction: formData.fraction,
us_fraction: formData.us_fraction,
sub_key: formData.sub_key,
physical_review: formData.physical_review,
iva_exempt_fraction: formData.iva_exempt_fraction
};
response = await classesApi.create(createData, companyId);
}
if (response.error) {
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 class:', e);
} finally {
loading = false;
}
}
// Opciones de unidades de medida (puedes expandir esto)
const unitOptions = [
{ value: 'KG', label: 'Kilogramos (KG)' },
{ value: 'LB', label: 'Libras (LB)' },
{ value: 'MT', label: 'Metros (MT)' },
{ value: 'PZ', label: 'Piezas (PZ)' },
{ value: 'LT', label: 'Litros (LT)' },
{ value: 'M3', label: 'Metros Cúbicos (M3)' },
{ value: 'TON', label: 'Toneladas (TON)' }
];
// Funciones para obtener valores seleccionados
function getSelectedMaterialType() {
if (!formData.material_key) return null;
const found = materialTypes.find(mt => mt.key === formData.material_key);
return found ? { value: found.key, label: `${found.key} - ${found.description}` } : null;
}
function getSelectedUnit() {
return unitOptions.find(opt => opt.value === formData.unit_of_measure) || unitOptions[0];
}
function getSelectedPhysicalReview() {
return { value: formData.physical_review, label: formData.physical_review === 1 ? 'Sí' : 'No' };
}
</script>
<Dialog.Root bind:open onOpenChange={handleOpenChange}>
<Dialog.Content class="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
<Dialog.Header>
<Dialog.Title>{title}</Dialog.Title>
<Dialog.Description>
{isEdit ? 'Modifica los datos de la clase' : 'Completa los datos para crear una nueva clase'}
</Dialog.Description>
</Dialog.Header>
<form onsubmit={handleSubmit} class="space-y-4 py-4">
<!-- Error Message -->
{#if error}
<div class="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
{error}
</div>
{/if}
<!-- Información de la compañía (solo lectura) -->
{#if companyStore.activeCompany}
<div class="rounded-md bg-blue-50 border border-blue-200 p-3">
<div class="flex items-center gap-2">
<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="text-blue-600"
>
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
<polyline points="9 22 9 12 15 12 15 22" />
</svg>
<div>
<p class="text-sm font-medium text-blue-900">
{companyStore.activeCompany.name}
</p>
<p class="text-xs text-blue-600">
ID: {companyStore.activeCompany.id}
</p>
</div>
</div>
</div>
{/if}
<!-- Código de Clase -->
<div class="space-y-2">
<Label for="class_code" class="required">Código de Clase</Label>
<Input
id="class_code"
bind:value={formData.class_code}
placeholder="Ej: A76"
required
disabled={loading}
/>
</div>
<!-- Descripciones -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="space-y-2">
<Label for="description_es">Descripción (Español)</Label>
<Textarea
id="description_es"
bind:value={formData.description_es}
placeholder="Descripción en español"
disabled={loading}
rows={3}
/>
</div>
<div class="space-y-2">
<Label for="description_en">Descripción (Inglés)</Label>
<Textarea
id="description_en"
bind:value={formData.description_en}
placeholder="English description"
disabled={loading}
rows={3}
/>
</div>
</div>
<!-- Material Type -->
<div class="space-y-2">
<Label for="material_key">Tipo de Material</Label>
{#if loadingMaterialTypes}
<div class="flex items-center gap-2 text-sm text-muted-foreground">
<div class="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
Cargando tipos de material...
</div>
{:else if materialTypes.length > 0}
<select
bind:value={formData.material_key}
disabled={loading}
class="border-input bg-background selection:bg-primary dark:bg-input/30 selection:text-primary-foreground ring-offset-background placeholder:text-muted-foreground shadow-xs flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base outline-none transition-[color,box-shadow] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive"
>
<option value="">Sin tipo de material</option>
{#each materialTypes as materialType}
<option value={materialType.key}>
{materialType.key} - {materialType.description}
</option>
{/each}
</select>
{:else}
<Input
id="material_key"
bind:value={formData.material_key}
placeholder="No hay tipos de material disponibles"
disabled={true}
/>
{/if}
</div>
<!-- Fracciones -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="space-y-2">
<Label for="fraction" class="required">Fracción</Label>
<Input
id="fraction"
bind:value={formData.fraction}
placeholder="Ej: 123123"
required
disabled={loading}
/>
</div>
<div class="space-y-2">
<Label for="us_fraction" class="required">Fracción US</Label>
<Input
id="us_fraction"
bind:value={formData.us_fraction}
placeholder="Ej: 123123"
required
disabled={loading}
/>
</div>
</div>
<!-- Sub Key e IVA Exempt -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="space-y-2">
<Label for="sub_key" class="required">Subclave</Label>
<Input
id="sub_key"
bind:value={formData.sub_key}
placeholder="Ej: 123"
required
disabled={loading}
/>
</div>
<div class="space-y-2">
<Label for="iva_exempt_fraction" class="required">Fracción Exenta IVA</Label>
<Input
id="iva_exempt_fraction"
bind:value={formData.iva_exempt_fraction}
placeholder="Ej: 123"
required
disabled={loading}
/>
</div>
</div>
<!-- Unidad de Medida -->
<div class="space-y-2">
<Label for="unit_of_measure" class="required">Unidad de Medida</Label>
<select
bind:value={formData.unit_of_measure}
disabled={loading}
class="border-input bg-background selection:bg-primary dark:bg-input/30 selection:text-primary-foreground ring-offset-background placeholder:text-muted-foreground shadow-xs flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base outline-none transition-[color,box-shadow] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive"
>
{#each unitOptions as unit}
<option value={unit.value}>{unit.label}</option>
{/each}
</select>
</div>
<!-- Revisión Física -->
<div class="space-y-2">
<Label for="physical_review">Revisión Física</Label>
<select
bind:value={formData.physical_review}
disabled={loading}
class="border-input bg-background selection:bg-primary dark:bg-input/30 selection:text-primary-foreground ring-offset-background placeholder:text-muted-foreground shadow-xs flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base outline-none transition-[color,box-shadow] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive"
>
<option value={0}>No</option>
<option value={1}>Sí</option>
</select>
</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>
Guardando...
{:else}
{isEdit ? 'Actualizar' : 'Crear'}
{/if}
</Button>
</Dialog.Footer>
</form>
</Dialog.Content>
</Dialog.Root>
<style>
:global(.required::after) {
content: " *";
color: hsl(var(--destructive));
}
</style>

View File

@@ -0,0 +1,169 @@
<script lang="ts">
import { Button } from "$lib/components/ui/button";
import * as DropdownMenu from "$lib/components/ui/dropdown-menu";
import { classesApi, type A76Class } from "$lib/api/dashboard/a76/classes";
import { companyStore } from "$lib/stores/company.svelte";
import CreateEditDialog from "./create-edit-dialog.svelte";
let {
item,
onSuccess
}: {
item: A76Class;
onSuccess?: () => void;
} = $props();
let loading = $state(false);
let error = $state<string | null>(null);
let dialogOpen = $state(false);
let selectedItem = $state<A76Class | null>(null);
async function handleDelete() {
if (!confirm(`¿Estás seguro de eliminar la clase "${item.class_code}"?`)) {
return;
}
const companyId = companyStore.activeCompany?.id;
if (!companyId) {
alert('No hay compañía seleccionada');
return;
}
loading = true;
error = null;
try {
const response = await classesApi.delete(item.id, companyId);
if (response.error) {
if (response.status === 401) {
error = 'Sesión expirada. Recargando página...';
setTimeout(() => {
window.location.reload();
}, 1500);
} else {
error = response.error;
alert(`Error al eliminar: ${response.error}`);
}
return;
}
// Éxito
if (onSuccess) {
onSuccess();
}
} catch (e) {
error = e instanceof Error ? e.message : "Error al eliminar";
alert(`Error: ${error}`);
console.error("Error deleting:", e);
} finally {
loading = false;
}
}
function handleEdit() {
selectedItem = item;
dialogOpen = true;
}
function handleDialogSuccess() {
dialogOpen = false;
selectedItem = null;
if (onSuccess) {
onSuccess();
}
}
</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>
<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"
>
<circle cx="12" cy="12" r="1" />
<circle cx="12" cy="5" r="1" />
<circle cx="12" cy="19" r="1" />
</svg>
</Button>
{/snippet}
</DropdownMenu.Trigger>
<DropdownMenu.Content align="end" class="w-[160px]">
<DropdownMenu.Label>Acciones</DropdownMenu.Label>
<DropdownMenu.Separator />
<DropdownMenu.Item onclick={handleEdit}>
<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="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />
<path d="m15 5 4 4" />
</svg>
Editar
</DropdownMenu.Item>
<DropdownMenu.Separator />
<DropdownMenu.Item onclick={handleDelete} class="text-destructive" 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>
{:else}
<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="M3 6h18" />
<path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6" />
<path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2" />
</svg>
{/if}
Eliminar
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
<!-- Dialog de edición -->
<CreateEditDialog bind:open={dialogOpen} item={selectedItem} onSuccess={handleDialogSuccess} />

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

@@ -167,7 +167,7 @@ export function getSidebarData(): SidebarData {
},
{
title: m["sidebar.general_catalogs.classification"](),
url: "#",
url: "/dashboard/general_catalogs/classes",
},
{
title: m["sidebar.general_catalogs.identifiers"](),