Merge pull request 'Correccion de clientes y proveedores,' (#39) from fixed/clientes_provedores_sellos into development

Reviewed-on: ADUANASOFT/anexo76#39
This commit is contained in:
2026-01-02 19:51:18 +00:00
37 changed files with 516 additions and 1976 deletions

View File

@@ -61,7 +61,6 @@ async def get_clients_and_providers(
"page_size": limit,
}
@router.get("/{client_id}/basic", response_model=ClientProviderBasicDTO)
async def get_clients_and_providers_basic_info(
client_id: int,
@@ -111,6 +110,26 @@ async def update_client_provider(
return client
@router.get("/{client_id}", response_model=ClientProviderResponseDTO)
async def get_client_provider_detail(
client_id: int,
company_id: int = Query(..., description="Company ID"),
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
"""
Obtener un cliente/proveedor completo por ID.
Esta es la ruta que tu formulario necesita para cargar los datos.
"""
tenant_id = validate_access_to_resource(db, company_id, current_user)
# Usamos el servicio para buscar por ID
client = ClientProviderService.get_by_id(db, client_id, tenant_id, company_id)
if not client:
raise HTTPException(status_code=404, detail="Client/Provider not found")
return client
@router.delete("/{client_id}", response_model=bool)
async def delete_client_provider(

View File

@@ -5,14 +5,17 @@
import { api } from '$lib/api';
export interface ClientProviderAddress {
id?: number;
street?: string | null;
neighborhood?: string | null;
city?: string | null;
state?: string | null;
country?: string | null;
zip_code?: string | null;
client_id?: number;
id?: number;
streets?: string | null;
neighborhood?: string | null;
city?: string | null;
state?: string | null;
country?: string | null;
zip_code?: string | null;
client_id?: number;
interior_number?: string | null;
exterior_number?: string | null;
municipality?: string | null;
}
export interface ClientProviderPrograms {
@@ -25,7 +28,7 @@ export interface ClientProviderPrograms {
export interface ClientProvider {
id: number;
rfc: string;
name: string;
name: string;
curp?: string | null;
residence_country?: string | null;
domicile_fiscal?: string | null;

View File

@@ -1,103 +1,98 @@
<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 { ClientProvider } from "./columns.js";
import CreateEditDialog from "./create-edit-dialog.svelte";
import DetailsDialog from "./details-dialog.svelte";
import DeleteDialog from "./delete-dialog.svelte";
import { clientsProvidersApi } from "$lib/api/dashboard/a76/clients-providers";
import { companyStore } from "$lib/stores/company.svelte";
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 { ClientProvider } from "./columns.js";
import DetailsDialog from "./details-dialog.svelte";
import DeleteDialog from "./delete-dialog.svelte";
import { clientsProvidersApi } from "$lib/api/dashboard/a76/clients-providers";
import { companyStore } from "$lib/stores/company.svelte";
import { goto } from "$app/navigation";
let {
item,
onSuccess
}: {
item: ClientProvider;
onSuccess?: () => void;
} = $props();
let {
item,
onSuccess
}: {
item: ClientProvider;
onSuccess?: () => void;
} = $props();
let showDetailsDialog = $state(false);
let showEditDialog = $state(false);
let showDeleteDialog = $state(false);
let isToggling = $state(false);
let showDetailsDialog = $state(false);
let showDeleteDialog = $state(false);
let isToggling = $state(false);
function handleCopyId() {
navigator.clipboard.writeText(item.id.toString());
}
function handleCopyId() {
navigator.clipboard.writeText(item.id.toString());
}
function handleCopyRfc() {
navigator.clipboard.writeText(item.rfc);
}
function handleCopyRfc() {
navigator.clipboard.writeText(item.rfc);
}
function handleViewDetails() {
showDetailsDialog = true;
}
function handleViewDetails() {
showDetailsDialog = true;
}
function handleEdit() {
showEditDialog = true;
}
function handleDelete() {
showDeleteDialog = true;
}
function handleDelete() {
showDeleteDialog = true;
}
async function handleToggleStatus() {
if (isToggling || !companyStore.activeCompany) return;
async function handleToggleStatus() {
if (isToggling || !companyStore.activeCompany) return;
isToggling = true;
try {
const response = await clientsProvidersApi.toggleStatus(item.id, companyStore.activeCompany.id);
if (response.error) {
console.error('Error toggling status:', response.error);
alert(`Error: ${response.error}`);
} else {
// Llamar al callback de éxito para recargar datos
if (onSuccess) {
onSuccess();
}
}
} catch (error) {
console.error('Error toggling status:', error);
alert('Error cambiando el estado');
} finally {
isToggling = false;
}
}
isToggling = true;
try {
const response = await clientsProvidersApi.toggleStatus(item.id, companyStore.activeCompany.id);
if (response.error) {
console.error('Error toggling status:', response.error);
alert(`Error: ${response.error}`);
} else {
if (onSuccess) {
onSuccess();
}
}
} catch (error) {
console.error('Error toggling status:', error);
alert('Error cambiando el estado');
} finally {
isToggling = false;
}
}
</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.Item onclick={handleCopyRfc}>
Copiar RFC
</DropdownMenu.Item>
</DropdownMenu.Group>
<DropdownMenu.Separator />
<DropdownMenu.Item onclick={handleViewDetails}>Ver detalles</DropdownMenu.Item>
<DropdownMenu.Item onclick={handleEdit}>Editar</DropdownMenu.Item>
<DropdownMenu.Item onclick={handleToggleStatus} disabled={isToggling}>
{isToggling ? 'Cambiando...' : item.is_active === true ? 'Desactivar' : 'Activar'}
</DropdownMenu.Item>
<DropdownMenu.Separator />
<DropdownMenu.Item class="text-destructive" onclick={handleDelete}>Eliminar</DropdownMenu.Item>
</DropdownMenu.Content>
<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.Item onclick={handleCopyRfc}>
Copiar RFC
</DropdownMenu.Item>
</DropdownMenu.Group>
<DropdownMenu.Separator />
<DropdownMenu.Item onclick={handleViewDetails}>Ver detalles</DropdownMenu.Item>
<DropdownMenu.Item onclick={() => goto(`/dashboard/clients_and_providers/edit/${item.id}`)}>
Editar
</DropdownMenu.Item>
<DropdownMenu.Item onclick={handleToggleStatus} disabled={isToggling}>
{isToggling ? 'Cambiando...' : item.is_active === true ? 'Desactivar' : 'Activar'}
</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} />
<DeleteDialog bind:open={showDeleteDialog} {item} {onSuccess} />

View File

@@ -118,6 +118,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef<CustomsBroker>[
},
{
id: "actions",
header: "Acciones",
cell: ({ row }) => {
return renderComponent(DataTableActions, {
broker: row.original,

View File

@@ -32,6 +32,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef<Doda>[] {
},
{
id: 'actions',
Headers: 'Acciones',
cell: ({ row }) => {
return renderComponent(DataTableActions, {
item: row.original,

View File

@@ -2,6 +2,7 @@ import type { ColumnDef } from '@tanstack/table-core';
import type { ElectronicNotice } from '$lib/api/dashboard/a76/general_catalogs/electronic-notices';
import { renderComponent } from '$lib/components/ui/data-table';
import DataTableActions from './data-table-actions.svelte';
import { Head } from '$lib/components/ui/table';
export function createColumns(onSuccess?: () => void): ColumnDef<ElectronicNotice>[] {
return [
@@ -32,6 +33,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef<ElectronicNotic
},
{
id: 'actions',
Headers: 'Acciones',
cell: ({ row }) => {
return renderComponent(DataTableActions, {
item: row.original,

View File

@@ -2,6 +2,7 @@ import type { ColumnDef } from '@tanstack/table-core';
import type { Equivalency } from '$lib/api/dashboard/a76/general_catalogs/equivalencies';
import { renderComponent } from '$lib/components/ui/data-table';
import DataTableActions from './data-table-actions.svelte';
import { Header } from '$lib/components/ui/alert-dialog';
export function createColumns(onSuccess?: () => void): ColumnDef<Equivalency>[] {
return [
@@ -22,6 +23,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef<Equivalency>[]
},
{
id: 'actions',
Header: 'Acciones',
cell: ({ row }) => {
return renderComponent(DataTableActions, {
item: row.original,

View File

@@ -2,6 +2,7 @@ import type { ColumnDef } from '@tanstack/table-core';
import type { Identifier } from '$lib/api/dashboard/a76/general_catalogs/identifiers';
import { renderComponent } from '$lib/components/ui/data-table';
import DataTableActions from './data-table-actions.svelte';
import { Header } from '$lib/components/ui/alert-dialog';
export function createColumns(onSuccess?: () => void): ColumnDef<Identifier>[] {
return [
@@ -27,6 +28,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef<Identifier>[] {
},
{
id: 'actions',
Header: 'Acciones',
cell: ({ row }) => {
return renderComponent(DataTableActions, {
item: row.original,

View File

@@ -22,6 +22,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef<INPC>[] {
},
{
id: 'actions',
header: 'Acciones',
cell: ({ row }) => {
return renderComponent(DataTableActions, {
item: row.original,

View File

@@ -2,6 +2,7 @@ import type { ColumnDef } from '@tanstack/table-core';
import type { Prevalidator } from '$lib/api/dashboard/a76/general_catalogs/prevalidators';
import { renderComponent } from '$lib/components/ui/data-table';
import DataTableActions from './data-table-actions.svelte';
import { Header } from '$lib/components/ui/alert-dialog';
export function createColumns(onSuccess?: () => void): ColumnDef<Prevalidator>[] {
return [
@@ -27,6 +28,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef<Prevalidator>[]
},
{
id: 'actions',
Header: 'Acciones',
cell: ({ row }) => {
return renderComponent(DataTableActions, {
item: row.original,

View File

@@ -2,6 +2,7 @@ import type { ColumnDef } from '@tanstack/table-core';
import type { UnitConversion } from '$lib/api/dashboard/a76/general_catalogs/unit-conversions';
import { renderComponent } from '$lib/components/ui/data-table';
import DataTableActions from './data-table-actions.svelte';
import { Header } from '$lib/components/ui/alert-dialog';
export function createColumns(onSuccess?: () => void): ColumnDef<UnitConversion>[] {
return [
@@ -19,6 +20,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef<UnitConversion>
},
{
id: 'actions',
header: 'Acciones',
cell: ({ row }) =>
renderComponent(DataTableActions, {
conversion: row.original,

View File

@@ -15,6 +15,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef<UnitOfMeasureAm
},
{
id: "actions",
header: "Acciones",
cell: ({ row }) =>
renderComponent(DataTableActions, {
unit: row.original,

View File

@@ -19,6 +19,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef<UnitOfMeasureCu
},
{
id: "actions",
header: "Acciones",
cell: ({ row }) =>
renderComponent(DataTableActions, {
unit: row.original,

View File

@@ -15,6 +15,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef<UnitOfMeasureOM
},
{
id: "actions",
header: "Acciones",
cell: ({ row }) =>
renderComponent(DataTableActions, {
unit: row.original,

View File

@@ -26,6 +26,7 @@ export function createColumns(onSuccess?: () => void): ColumnDef<Identifier>[] {
},
{
id: 'actions',
header: 'Acciones',
cell: ({ row }) => {
return renderComponent(DataTableActions, {
item: row.original,

View File

@@ -1,27 +1,26 @@
/**
* Column definitions for Seal table
*/
import type { ColumnDef } from '@tanstack/table-core';
import type { Seal } from '$lib/api/dashboard/a76/general_catalogs/seal';
import { renderComponent } from '$lib/components/ui/data-table';
import DataTableActions from './data-table-actions.svelte';
export function createColumns(onSuccess?: () => void): ColumnDef<Seal>[] {
return [
{
accessorKey: 'seal',
header: 'Sello',
cell: ({ row }) => row.original.seal
},
{
id: 'actions',
header: 'Acciones',
cell: ({ row }) => {
return renderComponent(DataTableActions, {
item: row.original,
onSuccess
});
}
}
];
}
return [
{
accessorKey: 'seal',
header: 'Sello',
cell: ({ row }) => row.original.seal,
},
{
id: 'actions',
header: 'Acciones',
meta: {
class: 'w-[100px] text-right'
},
cell: ({ row }) => renderComponent(DataTableActions, {
item: row.original,
onSuccess
})
}
];
}

View File

@@ -1,27 +0,0 @@
import type { UnitOfMeasureACE } from '$lib/api/dashboard/a76/general_catalogs/units-of-measure';
import type { ColumnDef } from '@tanstack/table-core';
import { renderComponent } from '$lib/components/ui/data-table';
import DataTableActions from './data-table-actions.svelte';
export function createColumns(onSuccess?: () => void): ColumnDef<UnitOfMeasureACE>[] {
return [
{
accessorKey: 'code',
header: 'Código',
},
{
accessorKey: 'description',
header: 'Descripción',
cell: ({ row }) => row.original.description || '-'
},
{
id: 'actions',
cell: ({ row }) => {
return renderComponent(DataTableActions, {
item: row.original,
onSuccess
});
}
}
];
}

View File

@@ -1,110 +0,0 @@
<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 { createUnitOfMeasureACE, updateUnitOfMeasureACE, type UnitOfMeasureACE } from "$lib/api/dashboard/a76/general_catalogs/units-of-measure";
let {
open = $bindable(false),
mode = 'create',
item = null,
onSuccess
}: {
open: boolean;
mode?: 'create' | 'edit';
item?: UnitOfMeasureACE | null;
onSuccess?: () => void;
} = $props();
const isEdit = $derived(mode === 'edit');
const title = $derived(isEdit ? "Editar Unidad ACE" : "Nueva Unidad ACE");
let formData = $state({
code: '',
description: ''
});
let loading = $state(false);
let error = $state<string | null>(null);
$effect(() => {
if (open) {
if (isEdit && item) {
formData = {
code: item.code,
description: item.description || ''
};
} else {
formData = {
code: '',
description: ''
};
}
error = null;
}
});
async function handleSubmit() {
loading = true;
error = null;
try {
let response;
if (isEdit && item) {
response = await updateUnitOfMeasureACE(item.id, {
code: formData.code,
description: formData.description || null
});
} else {
response = await createUnitOfMeasureACE({
code: formData.code,
description: formData.description || null
});
}
if (response.error) {
error = response.error;
return;
}
open = false;
if (onSuccess) onSuccess();
} catch (e) {
error = 'Error de conexión';
console.error(e);
} finally {
loading = false;
}
}
</script>
<Dialog.Root bind:open>
<Dialog.Content class="sm:max-w-[425px]">
<Dialog.Header>
<Dialog.Title>{title}</Dialog.Title>
</Dialog.Header>
<div class="grid gap-4 py-4">
{#if error}
<div class="text-red-500 text-sm mb-2">{error}</div>
{/if}
<div class="grid grid-cols-4 items-center gap-4">
<Label for="code" class="text-right">Código</Label>
<Input id="code" bind:value={formData.code} class="col-span-3" disabled={loading} />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label for="description" class="text-right">Descripción</Label>
<Input id="description" bind:value={formData.description} class="col-span-3" disabled={loading} />
</div>
</div>
<Dialog.Footer>
<Button type="submit" onclick={handleSubmit} disabled={loading}>
{loading ? 'Guardando...' : 'Guardar'}
</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>

View File

@@ -1,79 +0,0 @@
<script lang="ts">
import { Button } from "$lib/components/ui/button";
import * as DropdownMenu from "$lib/components/ui/dropdown-menu";
import { deleteUnitOfMeasureACE, type UnitOfMeasureACE } from "$lib/api/dashboard/a76/general_catalogs/units-of-measure";
import { EllipsisVertical, Pencil, LoaderCircle, Trash2 } from 'lucide-svelte';
import CreateEditDialog from "./create-edit-dialog.svelte";
let {
item,
onSuccess
}: {
item: UnitOfMeasureACE;
onSuccess?: () => void;
} = $props();
let loading = $state(false);
let error = $state<string | null>(null);
let dialogOpen = $state(false);
async function handleDelete() {
if (!confirm(`¿Estás seguro de eliminar la unidad "${item.code}"?`)) {
return;
}
loading = true;
error = null;
try {
const response = await deleteUnitOfMeasureACE(item.id);
if (response.error) {
error = response.error;
alert(`Error al eliminar: ${response.error}`);
return;
}
if (onSuccess) onSuccess();
} catch (e) {
error = 'Error de conexión';
console.error(e);
alert('Error de conexión al eliminar');
} finally {
loading = false;
}
}
</script>
<DropdownMenu.Root>
<DropdownMenu.Trigger>
{#snippet child({ props })}
<Button {...props} variant="ghost" size="icon" class="h-8 w-8 p-0">
<span class="sr-only">Abrir menú</span>
<EllipsisVertical class="h-4 w-4" />
</Button>
{/snippet}
</DropdownMenu.Trigger>
<DropdownMenu.Content align="end">
<DropdownMenu.Label>Acciones</DropdownMenu.Label>
<DropdownMenu.Item onclick={() => dialogOpen = true}>
<Pencil class="mr-2 h-4 w-4" />
Editar
</DropdownMenu.Item>
<DropdownMenu.Item onclick={handleDelete} class="text-red-600">
{#if loading}
<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
{:else}
<Trash2 class="mr-2 h-4 w-4" />
{/if}
Eliminar
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
<CreateEditDialog
bind:open={dialogOpen}
mode="edit"
{item}
{onSuccess}
/>

View File

@@ -1,106 +0,0 @@
<script lang="ts" generics="TData, TValue">
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";
import { Button } from "$lib/components/ui/button";
import { goto } from "$app/navigation";
import { page } from "$app/stores";
type DataTableProps<TData, TValue> = {
columns: ColumnDef<TData, TValue>[];
data: TData[];
pageCount: number;
totalItems: number;
};
let {
data,
columns,
pageCount,
totalItems
}: DataTableProps<TData, TValue> = $props();
const table = createSvelteTable({
get data() {
return data;
},
columns,
getCoreRowModel: getCoreRowModel(),
manualPagination: true,
pageCount: pageCount,
});
function handlePageChange(newPage: number) {
const url = new URL($page.url);
url.searchParams.set('page', newPage.toString());
goto(url);
}
</script>
<div class="rounded-md border">
<Table.Root>
<Table.Header>
{#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}
</Table.Body>
</Table.Root>
</div>
<div class="flex items-center justify-end space-x-2 py-4">
<div class="flex-1 text-sm text-muted-foreground">
Total: {totalItems}
</div>
<div class="space-x-2">
<Button
variant="outline"
size="sm"
onclick={() => handlePageChange(Number($page.url.searchParams.get('page') || 1) - 1)}
disabled={Number($page.url.searchParams.get('page') || 1) <= 1}
>
Anterior
</Button>
<Button
variant="outline"
size="sm"
onclick={() => handlePageChange(Number($page.url.searchParams.get('page') || 1) + 1)}
disabled={Number($page.url.searchParams.get('page') || 1) >= pageCount}
>
Siguiente
</Button>
</div>
</div>

View File

@@ -1,27 +0,0 @@
import type { UnitOfMeasureAmerican } from '$lib/api/dashboard/a76/general_catalogs/units-of-measure';
import type { ColumnDef } from '@tanstack/table-core';
import { renderComponent } from '$lib/components/ui/data-table';
import DataTableActions from './data-table-actions.svelte';
export function createColumns(onSuccess?: () => void): ColumnDef<UnitOfMeasureAmerican>[] {
return [
{
accessorKey: 'code',
header: 'Código',
},
{
accessorKey: 'description',
header: 'Descripción',
cell: ({ row }) => row.original.description || '-'
},
{
id: 'actions',
cell: ({ row }) => {
return renderComponent(DataTableActions, {
item: row.original,
onSuccess
});
}
}
];
}

View File

@@ -1,110 +0,0 @@
<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 { createUnitOfMeasureAmerican, updateUnitOfMeasureAmerican, type UnitOfMeasureAmerican } from "$lib/api/dashboard/a76/general_catalogs/units-of-measure";
let {
open = $bindable(false),
mode = 'create',
item = null,
onSuccess
}: {
open: boolean;
mode?: 'create' | 'edit';
item?: UnitOfMeasureAmerican | null;
onSuccess?: () => void;
} = $props();
const isEdit = $derived(mode === 'edit');
const title = $derived(isEdit ? "Editar Unidad Americana" : "Nueva Unidad Americana");
let formData = $state({
code: '',
description: ''
});
let loading = $state(false);
let error = $state<string | null>(null);
$effect(() => {
if (open) {
if (isEdit && item) {
formData = {
code: item.code,
description: item.description || ''
};
} else {
formData = {
code: '',
description: ''
};
}
error = null;
}
});
async function handleSubmit() {
loading = true;
error = null;
try {
let response;
if (isEdit && item) {
response = await updateUnitOfMeasureAmerican(item.id, {
code: formData.code,
description: formData.description || null
});
} else {
response = await createUnitOfMeasureAmerican({
code: formData.code,
description: formData.description || null
});
}
if (response.error) {
error = response.error;
return;
}
open = false;
if (onSuccess) onSuccess();
} catch (e) {
error = 'Error de conexión';
console.error(e);
} finally {
loading = false;
}
}
</script>
<Dialog.Root bind:open>
<Dialog.Content class="sm:max-w-[425px]">
<Dialog.Header>
<Dialog.Title>{title}</Dialog.Title>
</Dialog.Header>
<div class="grid gap-4 py-4">
{#if error}
<div class="text-red-500 text-sm mb-2">{error}</div>
{/if}
<div class="grid grid-cols-4 items-center gap-4">
<Label for="code" class="text-right">Código</Label>
<Input id="code" bind:value={formData.code} class="col-span-3" disabled={loading} />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label for="description" class="text-right">Descripción</Label>
<Input id="description" bind:value={formData.description} class="col-span-3" disabled={loading} />
</div>
</div>
<Dialog.Footer>
<Button type="submit" onclick={handleSubmit} disabled={loading}>
{loading ? 'Guardando...' : 'Guardar'}
</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>

View File

@@ -1,79 +0,0 @@
<script lang="ts">
import { Button } from "$lib/components/ui/button";
import * as DropdownMenu from "$lib/components/ui/dropdown-menu";
import { deleteUnitOfMeasureAmerican, type UnitOfMeasureAmerican } from "$lib/api/dashboard/a76/general_catalogs/units-of-measure";
import { EllipsisVertical, Pencil, LoaderCircle, Trash2 } from 'lucide-svelte';
import CreateEditDialog from "./create-edit-dialog.svelte";
let {
item,
onSuccess
}: {
item: UnitOfMeasureAmerican;
onSuccess?: () => void;
} = $props();
let loading = $state(false);
let error = $state<string | null>(null);
let dialogOpen = $state(false);
async function handleDelete() {
if (!confirm(`¿Estás seguro de eliminar la unidad "${item.code}"?`)) {
return;
}
loading = true;
error = null;
try {
const response = await deleteUnitOfMeasureAmerican(item.id);
if (response.error) {
error = response.error;
alert(`Error al eliminar: ${response.error}`);
return;
}
if (onSuccess) onSuccess();
} catch (e) {
error = 'Error de conexión';
console.error(e);
alert('Error de conexión al eliminar');
} finally {
loading = false;
}
}
</script>
<DropdownMenu.Root>
<DropdownMenu.Trigger>
{#snippet child({ props })}
<Button {...props} variant="ghost" size="icon" class="h-8 w-8 p-0">
<span class="sr-only">Abrir menú</span>
<EllipsisVertical class="h-4 w-4" />
</Button>
{/snippet}
</DropdownMenu.Trigger>
<DropdownMenu.Content align="end">
<DropdownMenu.Label>Acciones</DropdownMenu.Label>
<DropdownMenu.Item onclick={() => dialogOpen = true}>
<Pencil class="mr-2 h-4 w-4" />
Editar
</DropdownMenu.Item>
<DropdownMenu.Item onclick={handleDelete} class="text-red-600">
{#if loading}
<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
{:else}
<Trash2 class="mr-2 h-4 w-4" />
{/if}
Eliminar
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
<CreateEditDialog
bind:open={dialogOpen}
mode="edit"
{item}
{onSuccess}
/>

View File

@@ -1,32 +0,0 @@
import type { ColumnDef } from '@tanstack/table-core';
import { renderComponent } from '$lib/components/ui/data-table';
import DataTableActions from './data-table-actions.svelte';
export interface UMCustomsMex {
id: number;
code: string;
description: string | null;
}
export function createColumns(onSuccess?: () => void): ColumnDef<UMCustomsMex>[] {
return [
{
accessorKey: 'code',
header: 'Código',
},
{
accessorKey: 'description',
header: 'Descripción',
cell: ({ row }) => row.original.description || '-'
},
{
id: 'actions',
cell: ({ row }) => {
return renderComponent(DataTableActions, {
item: row.original,
onSuccess
});
}
}
];
}

View File

@@ -1,113 +0,0 @@
<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 { createUMCustomsMex, updateUMCustomsMex, type UMCustomsMex } from "$lib/api/dashboard/a76/general_catalogs/um-customs-mex";
let {
open = $bindable(false),
mode = 'create',
item = null,
onSuccess
}: {
open: boolean;
mode?: 'create' | 'edit';
item?: UMCustomsMex | null;
onSuccess?: () => void;
} = $props();
const isEdit = $derived(mode === 'edit');
const title = $derived(isEdit ? "Editar Unidad Customs MEX" : "Nueva Unidad Customs MEX");
let formData = $state({
code: '',
description: ''
});
let loading = $state(false);
let error = $state<string | null>(null);
$effect(() => {
if (open) {
if (isEdit && item) {
formData = {
code: item.code,
description: item.description || ''
};
} else {
formData = {
code: '',
description: ''
};
}
error = null;
}
});
async function handleSubmit() {
loading = true;
error = null;
try {
let response;
if (isEdit && item) {
response = await updateUMCustomsMex(item.id, {
code: formData.code,
description: formData.description || null
});
} else {
response = await createUMCustomsMex({
code: formData.code,
description: formData.description || null
});
}
if (response.error) {
error = response.error;
return;
}
open = false;
if (onSuccess) onSuccess();
} catch (e) {
error = 'Error de conexión';
console.error(e);
} finally {
loading = false;
}
}
</script>
<Dialog.Root bind:open>
<Dialog.Content class="sm:max-w-[425px]">
<Dialog.Header>
<Dialog.Title>{title}</Dialog.Title>
</Dialog.Header>
<div class="grid gap-4 py-4">
{#if error}
<div class="text-red-500 text-sm mb-2">{error}</div>
{/if}
<div class="grid grid-cols-4 items-center gap-4">
<Label for="code" class="text-right">Código</Label>
<Input id="code" bind:value={formData.code} class="col-span-3" disabled={loading} />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label for="description" class="text-right">Descripción</Label>
<Input id="description" bind:value={formData.description} class="col-span-3" disabled={loading} />
</div>
</div>
<div class="flex justify-end gap-2">
<Button variant="outline" onclick={() => open = false} disabled={loading}>
Cancelar
</Button>
<Button onclick={handleSubmit} disabled={loading}>
{loading ? 'Guardando...' : 'Guardar'}
</Button>
</div>
</Dialog.Content>
</Dialog.Root>

View File

@@ -1,79 +0,0 @@
<script lang="ts">
import { Button } from "$lib/components/ui/button";
import * as DropdownMenu from "$lib/components/ui/dropdown-menu";
import { deleteUMCustomsMex, type UMCustomsMex } from "$lib/api/dashboard/a76/general_catalogs/um-customs-mex";
import { EllipsisVertical, Pencil, LoaderCircle, Trash2 } from 'lucide-svelte';
import CreateEditDialog from "./create-edit-dialog.svelte";
let {
item,
onSuccess
}: {
item: UMCustomsMex;
onSuccess?: () => void;
} = $props();
let loading = $state(false);
let error = $state<string | null>(null);
let dialogOpen = $state(false);
async function handleDelete() {
if (!confirm(`¿Estás seguro de eliminar la unidad "${item.code}"?`)) {
return;
}
loading = true;
error = null;
try {
const response = await deleteUMCustomsMex(item.id);
if (response.error) {
error = response.error;
alert(`Error al eliminar: ${response.error}`);
return;
}
if (onSuccess) onSuccess();
} catch (e) {
error = 'Error de conexión';
console.error(e);
alert('Error de conexión al eliminar');
} finally {
loading = false;
}
}
</script>
<DropdownMenu.Root>
<DropdownMenu.Trigger>
{#snippet child({ props })}
<Button {...props} variant="ghost" size="icon" class="h-8 w-8 p-0">
<span class="sr-only">Abrir menú</span>
<EllipsisVertical class="h-4 w-4" />
</Button>
{/snippet}
</DropdownMenu.Trigger>
<DropdownMenu.Content align="end">
<DropdownMenu.Label>Acciones</DropdownMenu.Label>
<DropdownMenu.Item onclick={() => dialogOpen = true}>
<Pencil class="mr-2 h-4 w-4" />
Editar
</DropdownMenu.Item>
<DropdownMenu.Item onclick={handleDelete} class="text-red-600">
{#if loading}
<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
{:else}
<Trash2 class="mr-2 h-4 w-4" />
{/if}
Eliminar
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
<CreateEditDialog
bind:open={dialogOpen}
mode="edit"
{item}
{onSuccess}
/>

View File

@@ -1,106 +0,0 @@
<script lang="ts" generics="TData, TValue">
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";
import { Button } from "$lib/components/ui/button";
import { goto } from "$app/navigation";
import { page } from "$app/stores";
type DataTableProps<TData, TValue> = {
columns: ColumnDef<TData, TValue>[];
data: TData[];
pageCount: number;
totalItems: number;
};
let {
data,
columns,
pageCount,
totalItems
}: DataTableProps<TData, TValue> = $props();
const table = createSvelteTable({
get data() {
return data;
},
columns,
getCoreRowModel: getCoreRowModel(),
manualPagination: true,
pageCount: pageCount,
});
function handlePageChange(newPage: number) {
const url = new URL($page.url);
url.searchParams.set('page', newPage.toString());
goto(url);
}
</script>
<div class="rounded-md border">
<Table.Root>
<Table.Header>
{#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}
</Table.Body>
</Table.Root>
</div>
<div class="flex items-center justify-end space-x-2 py-4">
<div class="flex-1 text-sm text-muted-foreground">
Total: {totalItems}
</div>
<div class="space-x-2">
<Button
variant="outline"
size="sm"
onclick={() => handlePageChange(Number($page.url.searchParams.get('page') || 1) - 1)}
disabled={Number($page.url.searchParams.get('page') || 1) <= 1}
>
Anterior
</Button>
<Button
variant="outline"
size="sm"
onclick={() => handlePageChange(Number($page.url.searchParams.get('page') || 1) + 1)}
disabled={Number($page.url.searchParams.get('page') || 1) >= pageCount}
>
Siguiente
</Button>
</div>
</div>

View File

@@ -1,32 +0,0 @@
import type { ColumnDef } from '@tanstack/table-core';
import { renderComponent } from '$lib/components/ui/data-table';
import DataTableActions from './data-table-actions.svelte';
export interface UnitMeasure {
id: number;
code: string;
description: string | null;
}
export function createColumns(onSuccess?: () => void): ColumnDef<UnitMeasure>[] {
return [
{
accessorKey: 'code',
header: 'Código',
},
{
accessorKey: 'description',
header: 'Descripción',
cell: ({ row }) => row.original.description || '-'
},
{
id: 'actions',
cell: ({ row }) => {
return renderComponent(DataTableActions, {
item: row.original,
onSuccess
});
}
}
];
}

View File

@@ -1,113 +0,0 @@
<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 { createUnitMeasure, updateUnitMeasure, type UnitMeasure } from "$lib/api/dashboard/a76/general_catalogs/unit-measures";
let {
open = $bindable(false),
mode = 'create',
item = null,
onSuccess
}: {
open: boolean;
mode?: 'create' | 'edit';
item?: UnitMeasure | null;
onSuccess?: () => void;
} = $props();
const isEdit = $derived(mode === 'edit');
const title = $derived(isEdit ? "Editar Unidad de Medida" : "Nueva Unidad de Medida");
let formData = $state({
code: '',
description: ''
});
let loading = $state(false);
let error = $state<string | null>(null);
$effect(() => {
if (open) {
if (isEdit && item) {
formData = {
code: item.code,
description: item.description || ''
};
} else {
formData = {
code: '',
description: ''
};
}
error = null;
}
});
async function handleSubmit() {
loading = true;
error = null;
try {
let response;
if (isEdit && item) {
response = await updateUnitMeasure(item.id, {
code: formData.code,
description: formData.description || null
});
} else {
response = await createUnitMeasure({
code: formData.code,
description: formData.description || null
});
}
if (response.error) {
error = response.error;
return;
}
open = false;
if (onSuccess) onSuccess();
} catch (e) {
error = 'Error de conexión';
console.error(e);
} finally {
loading = false;
}
}
</script>
<Dialog.Root bind:open>
<Dialog.Content class="sm:max-w-[425px]">
<Dialog.Header>
<Dialog.Title>{title}</Dialog.Title>
</Dialog.Header>
<div class="grid gap-4 py-4">
{#if error}
<div class="text-red-500 text-sm mb-2">{error}</div>
{/if}
<div class="grid grid-cols-4 items-center gap-4">
<Label for="code" class="text-right">Código</Label>
<Input id="code" bind:value={formData.code} class="col-span-3" disabled={loading} />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label for="description" class="text-right">Descripción</Label>
<Input id="description" bind:value={formData.description} class="col-span-3" disabled={loading} />
</div>
</div>
<div class="flex justify-end gap-2">
<Button variant="outline" onclick={() => open = false} disabled={loading}>
Cancelar
</Button>
<Button onclick={handleSubmit} disabled={loading}>
{loading ? 'Guardando...' : 'Guardar'}
</Button>
</div>
</Dialog.Content>
</Dialog.Root>

View File

@@ -1,79 +0,0 @@
<script lang="ts">
import { Button } from "$lib/components/ui/button";
import * as DropdownMenu from "$lib/components/ui/dropdown-menu";
import { deleteUnitMeasure, type UnitMeasure } from "$lib/api/dashboard/a76/general_catalogs/unit-measures";
import { EllipsisVertical, Pencil, LoaderCircle, Trash2 } from 'lucide-svelte';
import CreateEditDialog from "./create-edit-dialog.svelte";
let {
item,
onSuccess
}: {
item: UnitMeasure;
onSuccess?: () => void;
} = $props();
let loading = $state(false);
let error = $state<string | null>(null);
let dialogOpen = $state(false);
async function handleDelete() {
if (!confirm(`¿Estás seguro de eliminar la unidad "${item.code}"?`)) {
return;
}
loading = true;
error = null;
try {
const response = await deleteUnitMeasure(item.id);
if (response.error) {
error = response.error;
alert(`Error al eliminar: ${response.error}`);
return;
}
if (onSuccess) onSuccess();
} catch (e) {
error = 'Error de conexión';
console.error(e);
alert('Error de conexión al eliminar');
} finally {
loading = false;
}
}
</script>
<DropdownMenu.Root>
<DropdownMenu.Trigger>
{#snippet child({ props })}
<Button {...props} variant="ghost" size="icon" class="h-8 w-8 p-0">
<span class="sr-only">Abrir menú</span>
<EllipsisVertical class="h-4 w-4" />
</Button>
{/snippet}
</DropdownMenu.Trigger>
<DropdownMenu.Content align="end">
<DropdownMenu.Label>Acciones</DropdownMenu.Label>
<DropdownMenu.Item onclick={() => dialogOpen = true}>
<Pencil class="mr-2 h-4 w-4" />
Editar
</DropdownMenu.Item>
<DropdownMenu.Item onclick={handleDelete} class="text-red-600">
{#if loading}
<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
{:else}
<Trash2 class="mr-2 h-4 w-4" />
{/if}
Eliminar
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
<CreateEditDialog
bind:open={dialogOpen}
mode="edit"
{item}
{onSuccess}
/>

View File

@@ -1,106 +0,0 @@
<script lang="ts" generics="TData, TValue">
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";
import { Button } from "$lib/components/ui/button";
import { goto } from "$app/navigation";
import { page } from "$app/stores";
type DataTableProps<TData, TValue> = {
columns: ColumnDef<TData, TValue>[];
data: TData[];
pageCount: number;
totalItems: number;
};
let {
data,
columns,
pageCount,
totalItems
}: DataTableProps<TData, TValue> = $props();
const table = createSvelteTable({
get data() {
return data;
},
columns,
getCoreRowModel: getCoreRowModel(),
manualPagination: true,
pageCount: pageCount,
});
function handlePageChange(newPage: number) {
const url = new URL($page.url);
url.searchParams.set('page', newPage.toString());
goto(url);
}
</script>
<div class="rounded-md border">
<Table.Root>
<Table.Header>
{#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}
</Table.Body>
</Table.Root>
</div>
<div class="flex items-center justify-end space-x-2 py-4">
<div class="flex-1 text-sm text-muted-foreground">
Total: {totalItems}
</div>
<div class="space-x-2">
<Button
variant="outline"
size="sm"
onclick={() => handlePageChange(Number($page.url.searchParams.get('page') || 1) - 1)}
disabled={Number($page.url.searchParams.get('page') || 1) <= 1}
>
Anterior
</Button>
<Button
variant="outline"
size="sm"
onclick={() => handlePageChange(Number($page.url.searchParams.get('page') || 1) + 1)}
disabled={Number($page.url.searchParams.get('page') || 1) >= pageCount}
>
Siguiente
</Button>
</div>
</div>

View File

@@ -1,27 +0,0 @@
import type { UnitOfMeasureOMA } from '$lib/api/dashboard/a76/general_catalogs/units-of-measure';
import type { ColumnDef } from '@tanstack/table-core';
import { renderComponent } from '$lib/components/ui/data-table';
import DataTableActions from './data-table-actions.svelte';
export function createColumns(onSuccess?: () => void): ColumnDef<UnitOfMeasureOMA>[] {
return [
{
accessorKey: 'code',
header: 'Código',
},
{
accessorKey: 'description',
header: 'Descripción',
cell: ({ row }) => row.original.description || '-'
},
{
id: 'actions',
cell: ({ row }) => {
return renderComponent(DataTableActions, {
item: row.original,
onSuccess
});
}
}
];
}

View File

@@ -1,110 +0,0 @@
<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 { createUnitOfMeasureOMA, updateUnitOfMeasureOMA, type UnitOfMeasureOMA } from "$lib/api/dashboard/a76/general_catalogs/units-of-measure";
let {
open = $bindable(false),
mode = 'create',
item = null,
onSuccess
}: {
open: boolean;
mode?: 'create' | 'edit';
item?: UnitOfMeasureOMA | null;
onSuccess?: () => void;
} = $props();
const isEdit = $derived(mode === 'edit');
const title = $derived(isEdit ? "Editar Unidad OMA" : "Nueva Unidad OMA");
let formData = $state({
code: '',
description: ''
});
let loading = $state(false);
let error = $state<string | null>(null);
$effect(() => {
if (open) {
if (isEdit && item) {
formData = {
code: item.code,
description: item.description || ''
};
} else {
formData = {
code: '',
description: ''
};
}
error = null;
}
});
async function handleSubmit() {
loading = true;
error = null;
try {
let response;
if (isEdit && item) {
response = await updateUnitOfMeasureOMA(item.id, {
code: formData.code,
description: formData.description || null
});
} else {
response = await createUnitOfMeasureOMA({
code: formData.code,
description: formData.description || null
});
}
if (response.error) {
error = response.error;
return;
}
open = false;
if (onSuccess) onSuccess();
} catch (e) {
error = 'Error de conexión';
console.error(e);
} finally {
loading = false;
}
}
</script>
<Dialog.Root bind:open>
<Dialog.Content class="sm:max-w-[425px]">
<Dialog.Header>
<Dialog.Title>{title}</Dialog.Title>
</Dialog.Header>
<div class="grid gap-4 py-4">
{#if error}
<div class="text-red-500 text-sm mb-2">{error}</div>
{/if}
<div class="grid grid-cols-4 items-center gap-4">
<Label for="code" class="text-right">Código</Label>
<Input id="code" bind:value={formData.code} class="col-span-3" disabled={loading} />
</div>
<div class="grid grid-cols-4 items-center gap-4">
<Label for="description" class="text-right">Descripción</Label>
<Input id="description" bind:value={formData.description} class="col-span-3" disabled={loading} />
</div>
</div>
<Dialog.Footer>
<Button type="submit" onclick={handleSubmit} disabled={loading}>
{loading ? 'Guardando...' : 'Guardar'}
</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>

View File

@@ -1,79 +0,0 @@
<script lang="ts">
import { Button } from "$lib/components/ui/button";
import * as DropdownMenu from "$lib/components/ui/dropdown-menu";
import { deleteUnitOfMeasureOMA, type UnitOfMeasureOMA } from "$lib/api/dashboard/a76/general_catalogs/units-of-measure";
import { EllipsisVertical, Pencil, LoaderCircle, Trash2 } from 'lucide-svelte';
import CreateEditDialog from "./create-edit-dialog.svelte";
let {
item,
onSuccess
}: {
item: UnitOfMeasureOMA;
onSuccess?: () => void;
} = $props();
let loading = $state(false);
let error = $state<string | null>(null);
let dialogOpen = $state(false);
async function handleDelete() {
if (!confirm(`¿Estás seguro de eliminar la unidad "${item.code}"?`)) {
return;
}
loading = true;
error = null;
try {
const response = await deleteUnitOfMeasureOMA(item.id);
if (response.error) {
error = response.error;
alert(`Error al eliminar: ${response.error}`);
return;
}
if (onSuccess) onSuccess();
} catch (e) {
error = 'Error de conexión';
console.error(e);
alert('Error de conexión al eliminar');
} finally {
loading = false;
}
}
</script>
<DropdownMenu.Root>
<DropdownMenu.Trigger>
{#snippet child({ props })}
<Button {...props} variant="ghost" size="icon" class="h-8 w-8 p-0">
<span class="sr-only">Abrir menú</span>
<EllipsisVertical class="h-4 w-4" />
</Button>
{/snippet}
</DropdownMenu.Trigger>
<DropdownMenu.Content align="end">
<DropdownMenu.Label>Acciones</DropdownMenu.Label>
<DropdownMenu.Item onclick={() => dialogOpen = true}>
<Pencil class="mr-2 h-4 w-4" />
Editar
</DropdownMenu.Item>
<DropdownMenu.Item onclick={handleDelete} class="text-red-600">
{#if loading}
<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
{:else}
<Trash2 class="mr-2 h-4 w-4" />
{/if}
Eliminar
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
<CreateEditDialog
bind:open={dialogOpen}
mode="edit"
{item}
{onSuccess}
/>

View File

@@ -3,7 +3,6 @@
import { clientsProvidersApi, type ClientProvider } from '$lib/api/dashboard/a76/clients-providers';
import DataTable from '$lib/components/dashboard/clients_and_providers/data-table.svelte';
import { createColumns } from '$lib/components/dashboard/clients_and_providers/columns.js';
import CreateEditDialog from '$lib/components/dashboard/clients_and_providers/create-edit-dialog.svelte';
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import * as Select from '$lib/components/ui/select';
@@ -195,7 +194,7 @@
Gestiona el catálogo de clientes y proveedores de tu empresa
</p>
</div>
<Button href="/dashboard/clients_and_providers/new">
<Button href="/dashboard/clients_and_providers/edit">
<Plus class="mr-2" size={16} />
Nuevo Cliente/Proveedor
</Button>
@@ -254,6 +253,3 @@
</Card.Content>
</Card.Root>
</div>
<!-- Diálogo de crear/editar -->
<CreateEditDialog bind:open={showCreateDialog} onSuccess={handleSuccess} />

View File

@@ -0,0 +1,363 @@
<script lang="ts">
import { onMount } from 'svelte';
import { browser } from '$app/environment';
import { page } from '$app/stores';
import { goto } from "$app/navigation";
// UI Components
import { Button } from "$lib/components/ui/button";
import { Input } from "$lib/components/ui/input";
import { Label } from "$lib/components/ui/label";
import * as Card from "$lib/components/ui/card";
import * as Select from "$lib/components/ui/select";
import { LoaderCircle, ArrowLeft, Save } from 'lucide-svelte';
// API & Stores
import { clientsProvidersApi } from "$lib/api/dashboard/a76/clients-providers";
import { companyStore } from "$lib/stores/company.svelte";
// 1. DETECCIÓN DE MODO (CREAR vs EDITAR)
let id = $derived($page.params.id);
let isEditing = $derived(!!id);
let title = $derived(isEditing ? "Editar Cliente/Proveedor" : "Nuevo Cliente/Proveedor");
// Mapa para corregir la visualización del Select
const typeLabels: Record<string, string> = {
client: "Cliente",
provider: "Proveedor",
both: "Ambos"
};
// Sincronización de Cookies (Token)
onMount(() => {
if (browser) {
const getCookie = (name: string) => document.cookie.split(`; ${name}=`).pop()?.split(';').shift() || null;
const cT = getCookie('access_token');
const lT = localStorage.getItem('access_token');
if (cT && cT !== lT) localStorage.setItem('access_token', cT);
}
});
// Estado inicial del formulario
function getEmptyForm() {
return {
rfc: "", name: "", curp: "", residence_country: "",
domicile_fiscal: "", foreign_tax_id: "",
client_or_provider: "client", is_active: true,
// Dirección
street: "", neighborhood: "", city: "", state: "",
country: "", zip_code: "",
// Programas
program_code: "", authorization_date: ""
};
}
let formData = $state(getEmptyForm());
let loading = $state(false);
let error = $state<string | null>(null);
// --- UTILIDADES DE FECHA ---
const intDateToString = (dateInt?: number | null) => {
if (!dateInt) return "";
const s = dateInt.toString();
if (s.length !== 8) return "";
return `${s.substring(0, 4)}-${s.substring(4, 6)}-${s.substring(6, 8)}`;
};
const stringDateToInt = (dateStr?: string) => {
if (!dateStr) return null;
return parseInt(dateStr.replace(/-/g, '')) || null;
};
// Efecto de carga automática
$effect(() => {
if (id && companyStore.activeCompany?.id) {
loadClientById(Number(id));
} else {
// Si salimos de editar a crear, limpiamos
if (!id) {
formData = getEmptyForm();
error = null;
}
}
});
async function loadClientById(clientId: number) {
if (!companyStore.activeCompany?.id) return;
loading = true;
error = null;
try {
// Usamos el nuevo endpoint GET /{id} que agregaste al backend
const response = await clientsProvidersApi.get(clientId, companyStore.activeCompany.id);
const item = (response as any).data || response;
if (item) {
const addr = item.address || {};
const prog = item.programs || {};
formData = {
rfc: item.rfc || "",
name: item.name || "",
curp: item.curp || "",
residence_country: item.residence_country || "",
domicile_fiscal: item.domicile_fiscal || "",
foreign_tax_id: item.foreign_tax_id || "",
client_or_provider: item.client_or_provider || "client",
is_active: item.is_active ?? true,
// Mapeo de dirección
street: addr.streets || addr.street || "",
neighborhood: addr.neighborhood || "",
city: addr.city || "",
state: addr.state || "",
country: addr.country || "",
zip_code: addr.postal_code || addr.zip_code || "",
// Mapeo de programas
program_code: prog.program_number || prog.program_code || "",
authorization_date: intDateToString(prog.secon_auth_date)
};
}
} catch (e: any) {
console.error("Error al cargar:", e);
error = "No se pudieron cargar los detalles del cliente. Error: " + (e.message || "Desconocido");
} finally {
loading = false;
}
}
async function handleSubmit(e: Event) {
e.preventDefault();
if (!companyStore.activeCompany) { error = "No hay compañía seleccionada"; return; }
if (!formData.rfc.trim()) { error = "El RFC es obligatorio"; return; }
if (!formData.name.trim()) { error = "El nombre es obligatorio"; return; }
loading = true;
error = null;
try {
// Payloads para backend
const addressPayload: any = {
street: formData.street || null,
streets: formData.street || null,
postal_code: formData.zip_code || null,
zip_code: formData.zip_code || null,
neighborhood: formData.neighborhood || null,
city: formData.city || null,
state: formData.state || null,
country: formData.country || formData.residence_country || null,
};
const programsPayload: any = {
program_code: formData.program_code || null,
program_number: formData.program_code || null,
secon_auth_date: stringDateToInt(formData.authorization_date),
};
const basePayload = {
rfc: formData.rfc,
name: formData.name,
curp: formData.curp || null,
residence_country: formData.residence_country || null,
domicile_fiscal: formData.domicile_fiscal || null,
foreign_tax_id: formData.foreign_tax_id || null,
client_or_provider: formData.client_or_provider,
is_active: formData.is_active,
address: addressPayload,
programs: programsPayload
};
const companyId = companyStore.activeCompany.id;
let response;
if (isEditing) {
response = await clientsProvidersApi.update(Number(id), companyId, basePayload as any);
} else {
response = await clientsProvidersApi.create(companyId, basePayload as any);
}
if (response.error) {
if (response.status === 401) {
error = 'Sesión expirada.';
window.location.reload();
} else {
error = response.error || "Error al procesar la solicitud";
}
return;
}
goto('/dashboard/clients_and_providers');
} catch (e: any) {
console.error("Error:", e);
error = e.message || "Error desconocido";
} finally {
loading = false;
}
}
</script>
<div class="space-y-6 pb-24">
<div class="flex items-center gap-4">
<Button variant="ghost" size="icon" onclick={() => goto('/dashboard/clients_and_providers')}>
<ArrowLeft class="h-4 w-4" />
</Button>
<div>
<h1 class="text-3xl font-bold tracking-tight">{title}</h1>
<p class="text-muted-foreground">
{isEditing ? "Modifica los datos del registro existente." : "Completa los datos para el nuevo registro."}
</p>
</div>
</div>
<Card.Root>
<Card.Header>
<Card.Title>Información General</Card.Title>
<Card.Description>Los campos marcados con * son obligatorios</Card.Description>
</Card.Header>
<Card.Content>
{#if loading && isEditing && !formData.name}
<div class="flex justify-center py-10">
<LoaderCircle class="h-8 w-8 animate-spin text-primary" />
</div>
{:else}
<form id="cp-form" onsubmit={handleSubmit} class="space-y-6">
{#if error}
<div class="rounded-lg border border-destructive bg-destructive/10 p-3 text-sm text-destructive font-medium flex items-center gap-2">
<span>🚨</span> {error}
</div>
{/if}
<div class="space-y-4">
<h3 class="text-sm font-semibold border-b pb-2">Información Básica</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="space-y-2">
<Label for="rfc">RFC *</Label>
<Input id="rfc" bind:value={formData.rfc} placeholder="Ej: XAXX010101000" maxlength={13} required disabled={loading} />
</div>
<div class="space-y-2">
<Label for="client_or_provider">Tipo *</Label>
<Select.Root type="single" bind:value={formData.client_or_provider}>
<Select.Trigger id="client_or_provider">
{typeLabels[formData.client_or_provider] || "Selecciona un tipo"}
</Select.Trigger>
<Select.Content>
<Select.Item value="client" label="Cliente">Cliente</Select.Item>
<Select.Item value="provider" label="Proveedor">Proveedor</Select.Item>
<Select.Item value="both" label="Ambos">Ambos</Select.Item>
</Select.Content>
</Select.Root>
</div>
</div>
<div class="space-y-2">
<Label for="name">Nombre / Razón Social *</Label>
<Input id="name" bind:value={formData.name} placeholder="Nombre completo" maxlength={256} required disabled={loading} />
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="space-y-2">
<Label for="curp">CURP</Label>
<Input id="curp" bind:value={formData.curp} placeholder="Opcional" maxlength={18} disabled={loading} />
</div>
<div class="space-y-2">
<Label for="residence_country">País de Residencia</Label>
<Input id="residence_country" bind:value={formData.residence_country} placeholder="Ej: MEX" maxlength={64} disabled={loading} />
</div>
</div>
</div>
<div class="space-y-4">
<h3 class="text-sm font-semibold border-b pb-2">Datos Fiscales</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="space-y-2">
<Label for="domicile_fiscal">Domicilio Fiscal</Label>
<Input id="domicile_fiscal" bind:value={formData.domicile_fiscal} placeholder="Domicilio completo" maxlength={256} disabled={loading} />
</div>
<div class="space-y-2">
<Label for="foreign_tax_id">ID Fiscal Extranjero</Label>
<Input id="foreign_tax_id" bind:value={formData.foreign_tax_id} placeholder="Tax ID" maxlength={64} disabled={loading} />
</div>
</div>
</div>
<div class="space-y-4">
<h3 class="text-sm font-semibold border-b pb-2">Dirección Física</h3>
<div class="space-y-2">
<Label for="street">Calle y Número</Label>
<Input id="street" bind:value={formData.street} placeholder="Calle..." maxlength={256} disabled={loading} />
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="space-y-2">
<Label for="neighborhood">Colonia</Label>
<Input id="neighborhood" bind:value={formData.neighborhood} placeholder="Colonia..." maxlength={128} disabled={loading} />
</div>
<div class="space-y-2">
<Label for="zip_code">Código Postal</Label>
<Input id="zip_code" bind:value={formData.zip_code} placeholder="CP" maxlength={10} disabled={loading} />
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<div class="space-y-2">
<Label for="city">Ciudad</Label>
<Input id="city" bind:value={formData.city} placeholder="Ciudad" maxlength={128} disabled={loading} />
</div>
<div class="space-y-2">
<Label for="state">Estado</Label>
<Input id="state" bind:value={formData.state} placeholder="Estado" maxlength={128} disabled={loading} />
</div>
<div class="space-y-2">
<Label for="country">País</Label>
<Input id="country" bind:value={formData.country} placeholder="MEX" maxlength={64} disabled={loading} />
</div>
</div>
</div>
<div class="space-y-4">
<h3 class="text-sm font-semibold border-b pb-2">Programas de Fomento</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="space-y-2">
<Label for="program_code">Nº Programa (IMMEX)</Label>
<Input id="program_code" bind:value={formData.program_code} placeholder="Ej: 1234-56" maxlength={32} disabled={loading} />
</div>
<div class="space-y-2">
<Label for="authorization_date">Fecha Autorización</Label>
<Input id="authorization_date" type="date" bind:value={formData.authorization_date} disabled={loading} />
</div>
</div>
</div>
</form>
{/if}
</Card.Content>
</Card.Root>
</div>
<div class="fixed bottom-0 right-0 left-0 md:left-64 p-4 border-t bg-background/95 backdrop-blur z-50 flex justify-end gap-4 shadow-lg">
<Button type="button" variant="outline" onclick={() => goto('/dashboard/clients_and_providers')} disabled={loading}>
Cancelar
</Button>
{#if !isEditing}
<Button type="button" variant="ghost" onclick={() => formData = getEmptyForm()} disabled={loading}>
Limpiar
</Button>
{/if}
<Button type="submit" form="cp-form" disabled={loading}>
{#if loading}
<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
Guardando...
{:else}
<Save class="mr-2 h-4 w-4" />
{isEditing ? "Guardar Cambios" : "Crear Registro"}
{/if}
</Button>
</div>

View File

@@ -1,438 +0,0 @@
<script lang="ts">
import { onMount } from 'svelte';
import { browser } from '$app/environment';
import { Button } from "$lib/components/ui/button";
import { Input } from "$lib/components/ui/input";
import { Label } from "$lib/components/ui/label";
import * as Card from "$lib/components/ui/card";
import * as Select from "$lib/components/ui/select";
import { clientsProvidersApi, type CreateClientProviderData } from "$lib/api/dashboard/a76/clients-providers";
import { companyStore } from "$lib/stores/company.svelte";
import { goto } from "$app/navigation";
import { ArrowLeft } from "lucide-svelte";
// Sincronizar token de cookies a localStorage al montar el componente
onMount(() => {
if (browser) {
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;
};
const cookieToken = getCookie('access_token');
const localToken = localStorage.getItem('access_token');
if (cookieToken && cookieToken !== localToken) {
localStorage.setItem('access_token', cookieToken);
}
const cookieRefreshToken = getCookie('refresh_token');
const localRefreshToken = localStorage.getItem('refresh_token');
if (cookieRefreshToken && cookieRefreshToken !== localRefreshToken) {
localStorage.setItem('refresh_token', cookieRefreshToken);
}
}
});
let formData = $state({
rfc: "",
name: "",
curp: "",
residence_country: "",
domicile_fiscal: "",
foreign_tax_id: "",
client_or_provider: "client",
is_active: true,
// Address fields
street: "",
neighborhood: "",
city: "",
state: "",
country: "",
zip_code: "",
// Programs fields
program_code: "",
authorization_date: ""
});
let loading = $state(false);
let error = $state<string | null>(null);
// Formulario inicializado vacío para nuevo registro
async function handleSubmit(e: Event) {
e.preventDefault();
if (!companyStore.activeCompany) {
error = "No hay compañía seleccionada";
return;
}
// Validaciones básicas
if (!formData.rfc.trim()) {
error = "El RFC es obligatorio";
return;
}
if (!formData.name.trim()) {
error = "El nombre es obligatorio";
return;
}
loading = true;
error = null;
// Verificar que tenemos token de acceso
const token = localStorage.getItem('access_token');
if (!token) {
error = "No hay token de acceso. Recargando página...";
setTimeout(() => {
window.location.reload();
}, 1500);
loading = false;
return;
}
try {
const payload: CreateClientProviderData = {
rfc: formData.rfc,
name: formData.name,
curp: formData.curp || null,
residence_country: formData.residence_country || null,
domicile_fiscal: formData.domicile_fiscal || null,
foreign_tax_id: formData.foreign_tax_id || null,
client_or_provider: formData.client_or_provider as "client" | "provider" | "both" | null,
is_active: formData.is_active,
address: {
street: formData.street || null,
neighborhood: formData.neighborhood || null,
city: formData.city || null,
state: formData.state || null,
country: formData.country || null,
zip_code: formData.zip_code || null,
},
programs: {
program_code: formData.program_code || null,
authorization_date: formData.authorization_date || null,
}
};
const response = await clientsProvidersApi.create(companyStore.activeCompany.id, payload);
if (response.error) {
console.error('🔧 Error del API:', response);
if (response.status === 401) {
error = 'Sesión expirada. Recargando página...';
setTimeout(() => {
window.location.reload();
}, 1500);
} else if (response.status === 403) {
error = 'No tienes permisos para crear clientes/proveedores';
} else if (response.status === 500) {
error = 'Error interno del servidor. Intenta nuevamente.';
} else if (response.status === 0 || !response.status) {
error = 'Error de conexión. Verifica tu internet y que el servidor esté corriendo.';
} else {
error = response.error || 'Error desconocido al guardar';
}
return;
}
// Éxito - redirigir a la lista
goto('/dashboard/clients_and_providers');
} catch (e) {
console.error("🔧 Error en catch:", e);
if (e instanceof TypeError && e.message.includes('fetch')) {
error = "Error de conexión: No se puede conectar con el servidor";
} else {
error = e instanceof Error ? e.message : "Error al guardar";
}
} finally {
loading = false;
}
}
function resetForm() {
formData = {
rfc: "",
name: "",
curp: "",
residence_country: "",
domicile_fiscal: "",
foreign_tax_id: "",
client_or_provider: "client",
is_active: true,
street: "",
neighborhood: "",
city: "",
state: "",
country: "",
zip_code: "",
program_code: "",
authorization_date: ""
}
}
</script>
<div class="space-y-6">
<!-- Header -->
<div class="flex items-center gap-4">
<Button variant="ghost" size="icon" onclick={() => goto('/dashboard/clients_and_providers')}>
<ArrowLeft class="h-4 w-4" />
</Button>
<div>
<h1 class="text-3xl font-bold tracking-tight">Nuevo Cliente/Proveedor</h1>
<p class="text-muted-foreground">
Completa los datos para crear un nuevo cliente o proveedor
</p>
</div>
</div>
<!-- Formulario -->
<Card.Root>
<Card.Header>
<Card.Title>Información del Cliente/Proveedor</Card.Title>
<Card.Description>
Todos los campos marcados con * son obligatorios
</Card.Description>
</Card.Header>
<Card.Content>
<form id="client-provider-form" onsubmit={handleSubmit} class="space-y-6">
{#if error}
<div class="rounded-lg border border-destructive bg-destructive/10 p-3 text-sm text-destructive">
{error}
</div>
{/if}
<!-- Información básica -->
<div class="space-y-4">
<h3 class="text-sm font-semibold">Información Básica</h3>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<Label for="rfc">RFC *</Label>
<Input
id="rfc"
bind:value={formData.rfc}
placeholder="Ej: XAXX010101000"
maxlength={13}
required
disabled={loading}
/>
</div>
<div class="space-y-2">
<Label for="client_or_provider">Tipo *</Label>
<Select.Root value={formData.client_or_provider} onValueChange={(value) => (formData.client_or_provider = value || "client")}>
<Select.Trigger>
<Select.Value />
</Select.Trigger>
<Select.Content>
<Select.Item value="client">Cliente</Select.Item>
<Select.Item value="provider">Proveedor</Select.Item>
<Select.Item value="both">Ambos</Select.Item>
</Select.Content>
</Select.Root>
</div>
</div>
<div class="space-y-2">
<Label for="name">Nombre / Razón Social *</Label>
<Input
id="name"
bind:value={formData.name}
placeholder="Nombre completo o razón social"
maxlength={256}
required
disabled={loading}
/>
</div>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<Label for="curp">CURP</Label>
<Input
id="curp"
bind:value={formData.curp}
placeholder="Ej: XAXX010101HDFXXX00"
maxlength={18}
disabled={loading}
/>
</div>
<div class="space-y-2">
<Label for="residence_country">País de Residencia</Label>
<Input
id="residence_country"
bind:value={formData.residence_country}
placeholder="Ej: México"
maxlength={64}
disabled={loading}
/>
</div>
</div>
</div>
<!-- Información fiscal -->
<div class="space-y-4">
<h3 class="text-sm font-semibold">Información Fiscal</h3>
<div class="space-y-2">
<Label for="domicile_fiscal">Domicilio Fiscal</Label>
<Input
id="domicile_fiscal"
bind:value={formData.domicile_fiscal}
placeholder="Domicilio fiscal completo"
maxlength={256}
disabled={loading}
/>
</div>
<div class="space-y-2">
<Label for="foreign_tax_id">ID Fiscal Extranjero</Label>
<Input
id="foreign_tax_id"
bind:value={formData.foreign_tax_id}
placeholder="Para contribuyentes extranjeros"
maxlength={64}
disabled={loading}
/>
</div>
</div>
<!-- Dirección -->
<div class="space-y-4">
<h3 class="text-sm font-semibold">Dirección</h3>
<div class="space-y-2">
<Label for="street">Calle</Label>
<Input
id="street"
bind:value={formData.street}
placeholder="Calle y número"
maxlength={256}
disabled={loading}
/>
</div>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<Label for="neighborhood">Colonia</Label>
<Input
id="neighborhood"
bind:value={formData.neighborhood}
placeholder="Colonia o barrio"
maxlength={128}
disabled={loading}
/>
</div>
<div class="space-y-2">
<Label for="zip_code">Código Postal</Label>
<Input
id="zip_code"
bind:value={formData.zip_code}
placeholder="Ej: 12345"
maxlength={10}
disabled={loading}
/>
</div>
</div>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<Label for="city">Ciudad</Label>
<Input
id="city"
bind:value={formData.city}
placeholder="Ciudad"
maxlength={128}
disabled={loading}
/>
</div>
<div class="space-y-2">
<Label for="state">Estado</Label>
<Input
id="state"
bind:value={formData.state}
placeholder="Estado o provincia"
maxlength={128}
disabled={loading}
/>
</div>
</div>
<div class="space-y-2">
<Label for="country">País</Label>
<Input
id="country"
bind:value={formData.country}
placeholder="País"
maxlength={64}
disabled={loading}
/>
</div>
</div>
<!-- Programas -->
<div class="space-y-4">
<h3 class="text-sm font-semibold">Programas</h3>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<Label for="program_code">Código de Programa</Label>
<Input
id="program_code"
bind:value={formData.program_code}
placeholder="Código del programa"
maxlength={32}
disabled={loading}
/>
</div>
<div class="space-y-2">
<Label for="authorization_date">Fecha de Autorización</Label>
<Input
id="authorization_date"
type="date"
bind:value={formData.authorization_date}
disabled={loading}
/>
</div>
</div>
</div>
</form>
</Card.Content>
</Card.Root>
</div>
<!-- Botones fijos en la parte inferior -->
<div class="fixed bottom-0 right-0 left-0 md:left-64 p-4 border-t bg-background/95 backdrop-blur z-50 flex justify-end gap-4 shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.1)]">
<Button type="button" variant="outline" onclick={() => goto('/dashboard/clients_and_providers')} disabled={loading}>
Cancelar
</Button>
<Button type="button" variant="outline" onclick={resetForm} disabled={loading}>
Limpiar
</Button>
<Button
type="submit"
form="client-provider-form"
disabled={loading}
>
{#if loading}
<div class="flex items-center gap-2">
<div class="h-4 w-4 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent"></div>
Guardando...
</div>
{:else}
Crear Cliente/Proveedor
{/if}
</Button>
</div>
<!-- Espaciado para evitar que los botones fijos oculten contenido -->
<div class="h-20"></div>