feat: Implement reference data management for states, transport modes, transport types, and valuation methods

- Added server-side loading logic for states, transport modes, transport types, and valuation methods with pagination support.
- Created Svelte components for displaying and managing states, transport modes, transport types, and valuation methods.
- Implemented infinite scroll functionality for loading more data as the user scrolls.
- Added error handling and user feedback for API interactions.
- Included dialogs for creating and editing entries in each reference data category.
This commit is contained in:
2025-11-02 16:54:27 -06:00
parent 27b5880524
commit ab57c6cd79
141 changed files with 13989 additions and 2 deletions

View File

@@ -0,0 +1,67 @@
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 Sector = {
key: string;
description: string;
authorized: number;
};
export function createColumns(onSuccess?: () => void): ColumnDef<Sector>[] {
return [
{
accessorKey: "key",
header: "Clave",
cell: ({ row }) => {
const keySnippet = createRawSnippet<[{ key: string }]>((getKey) => {
const { key } = getKey();
return {
render: () =>
`<code class="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold">${key}</code>`
};
});
return renderSnippet(keySnippet, { key: row.original.key });
}
},
{
accessorKey: "description",
header: "Descripción",
cell: ({ row }) => {
const descSnippet = createRawSnippet<[{ description: string }]>((getDesc) => {
const { description } = getDesc();
return {
render: () => `<div class="max-w-[500px] truncate">${description}</div>`
};
});
return renderSnippet(descSnippet, { description: row.original.description });
}
},
{
accessorKey: "authorized",
header: "Autorizado",
cell: ({ row }) => {
const authSnippet = createRawSnippet<[{ authorized: number }]>((getAuth) => {
const { authorized } = getAuth();
const badge = authorized === 1
? '<span class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200">Sí</span>'
: '<span class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200">No</span>';
return {
render: () => badge
};
});
return renderSnippet(authSnippet, { authorized: row.original.authorized });
}
},
{
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,223 @@
<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 { sectorsApi, type Sector, type CreateSectorData, type UpdateSectorData } from "$lib/api/dashboard/refrence_data/sectors";
let {
open = $bindable(false),
item = $bindable<Sector | null>(null),
onSuccess
}: {
open: boolean;
item?: Sector | null;
onSuccess?: () => void;
} = $props();
let formData = $state({
key: "",
description: "",
authorized: 0
});
let loading = $state(false);
let error = $state<string | null>(null);
// Actualizar formData cuando item cambia
$effect(() => {
if (item) {
formData = {
key: item.key,
description: item.description,
authorized: item.authorized
};
} else {
formData = {
key: "",
description: "",
authorized: 0
};
}
});
const isEditing = $derived(!!item);
async function handleSubmit(e: Event) {
e.preventDefault();
loading = true;
error = null;
try {
let response;
if (isEditing && item) {
const payload: UpdateSectorData = {
key: formData.key,
description: formData.description,
authorized: formData.authorized
};
response = await sectorsApi.update(item.key, payload);
} else {
const payload: CreateSectorData = {
key: formData.key,
description: formData.description,
authorized: formData.authorized
};
response = await sectorsApi.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 = {
key: "",
description: "",
authorized: 0
};
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"} Sector
</Dialog.Title>
<Dialog.Description>
{isEditing
? "Modifica los datos del sector."
: "Completa los datos para crear un nuevo sector."}
</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="space-y-2">
<Label for="key">Clave *</Label>
<Input
id="key"
bind:value={formData.key}
placeholder="Ej: 01"
maxlength={8}
required
disabled={loading || isEditing}
/>
<p class="text-sm text-muted-foreground">Clave de hasta 8 caracteres</p>
</div>
<div class="space-y-2">
<Label for="description">Descripción *</Label>
<Input
id="description"
bind:value={formData.description}
placeholder="Ej: Sector automotriz"
maxlength={150}
required
disabled={loading}
/>
</div>
<div class="space-y-2">
<Label>Autorizado *</Label>
<div class="flex gap-4">
<label class="flex items-center gap-2 cursor-pointer">
<input
type="radio"
name="authorized"
value="1"
checked={formData.authorized === 1}
onchange={() => (formData.authorized = 1)}
disabled={loading}
class="h-4 w-4 border-gray-300 text-primary focus:ring-primary"
/>
<span class="text-sm"></span>
</label>
<label class="flex items-center gap-2 cursor-pointer">
<input
type="radio"
name="authorized"
value="0"
checked={formData.authorized === 0}
onchange={() => (formData.authorized = 0)}
disabled={loading}
class="h-4 w-4 border-gray-300 text-primary focus:ring-primary"
/>
<span class="text-sm">No</span>
</label>
</div>
<p class="text-sm text-muted-foreground">1 = Autorizado, 0 = No autorizado</p>
</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 { Sector } 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: Sector;
onSuccess?: () => void;
} = $props();
let showDetailsDialog = $state(false);
let showEditDialog = $state(false);
let showDeleteDialog = $state(false);
function handleCopyId() {
navigator.clipboard.writeText(item.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 Clave
</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,119 @@
<script lang="ts">
import { Button } from "$lib/components/ui/button";
import * as AlertDialog from "$lib/components/ui/alert-dialog";
import { Badge } from "$lib/components/ui/badge";
import { sectorsApi, type Sector } from "$lib/api/dashboard/refrence_data/sectors";
let {
open = $bindable(false),
item,
onSuccess
}: {
open: boolean;
item: Sector | 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 sectorsApi.delete(item.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 sector:</p>
{#if item}
<div class="mt-2 rounded-lg bg-muted p-3 space-y-2">
<div class="flex items-center justify-between text-sm">
<span class="font-medium">Clave:</span>
<code class="font-mono font-semibold">{item.key}</code>
</div>
<div class="flex items-center justify-between text-sm">
<span class="font-medium">Descripción:</span>
<span>{item.description}</span>
</div>
<div class="flex items-center justify-between text-sm">
<span class="font-medium">Autorizado:</span>
<Badge variant={item.authorized === 1 ? "default" : "destructive"}>
{item.authorized === 1 ? "Sí" : "No"}
</Badge>
</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,68 @@
<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 { Badge } from "$lib/components/ui/badge";
import type { Sector } from "$lib/api/dashboard/refrence_data/sectors";
let {
open = $bindable(false),
item
}: {
open: boolean;
item: Sector | 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 Sector</Dialog.Title>
<Dialog.Description>
Información completa del sector
</Dialog.Description>
</Dialog.Header>
{#if item}
<div class="space-y-4 py-4">
<div class="space-y-2">
<div class="flex items-center justify-between">
<span class="text-sm font-medium text-muted-foreground">Clave</span>
<code class="relative rounded bg-muted px-2 py-1 font-mono text-sm font-semibold">
{item.key}
</code>
</div>
<Separator />
</div>
<div class="space-y-2">
<div class="flex items-center justify-between">
<span class="text-sm font-medium text-muted-foreground">Descripción</span>
<span class="text-sm">{item.description}</span>
</div>
<Separator />
</div>
<div class="space-y-2">
<div class="flex items-center justify-between">
<span class="text-sm font-medium text-muted-foreground">Autorizado</span>
<Badge variant={item.authorized === 1 ? "default" : "destructive"}>
{item.authorized === 1 ? "Sí" : "No"}
</Badge>
</div>
<Separator />
</div>
</div>
{/if}
<Dialog.Footer>
<Button variant="outline" onclick={() => (open = false)}>
Cerrar
</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>