Merge branch 'feature/creacion_modulo_mercancias' of https://git.aduanasoft.com/ADUANASOFT/anexo76 into feature/creacion_modulo_mercancias

This commit is contained in:
2026-01-06 14:37:34 -06:00
39 changed files with 770 additions and 2230 deletions

View File

@@ -1,170 +1,97 @@
/**
* API Client para Clientes y Proveedores
* Gestiona las operaciones CRUD para clientes y proveedores
*/
import { api } from '$lib/api';
// --- Interfaces para Tablas Hijas ---
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;
exterior_number?: string | null;
interior_number?: string | null;
neighborhood?: string | null;
municipality?: string | null;
city?: string | null;
state?: string | null;
country?: string | null;
postal_code?: string | null;
email?: string | null;
phone?: string | null;
contact?: string | null;
}
export interface ClientProviderPrograms {
id?: number;
program_code?: string | null;
authorization_date?: string | null;
client_id?: number;
id?: number;
program?: string | null;
program_number?: string | null;
secon_auth_date?: number | null; // YYYYMMDD
prosec?: number | null;
manufacturer_id?: string | null;
tax_id?: string | null;
ctpat_svi?: string | null;
is_certified_company?: string | null;
}
// --- Interfaz Principal ---
export interface ClientProvider {
id: number;
rfc: string;
name: string;
curp?: string | null;
residence_country?: string | null;
domicile_fiscal?: string | null;
foreign_tax_id?: string | null;
client_or_provider?: string | null;
is_active?: boolean;
tenant_id: number;
address?: ClientProviderAddress | null;
programs?: ClientProviderPrograms | null;
}
export interface ClientProviderBasic {
id: number;
rfc: string;
name: string;
curp?: string | null;
residence_country?: string | null;
domicile_fiscal?: string | null;
foreign_tax_id?: string | null;
client_or_provider?: string | null;
is_active?: boolean;
tenant_id: number;
id: number;
rfc: string;
name: string;
short_name?: string | null;
curp?: string | null;
client_or_provider: 'client' | 'provider' | 'both';
// Campos planos de la tabla principal
type_nat_foreign?: string | null;
responsible?: string | null;
position?: string | null;
// Booleanos (Coincidiendo con la BD)
is_national_provider?: boolean | null;
is_active?: boolean;
// Relaciones Anidadas
address?: ClientProviderAddress | null;
programs?: ClientProviderPrograms | null;
}
export interface ClientProviderListResponse {
items: ClientProvider[];
total: number;
page: number;
page_size: number;
items: ClientProvider[];
total: number;
page: number;
page_size: number;
}
export interface CreateClientProviderData {
rfc: string;
name: string;
curp?: string | null;
residence_country?: string | null;
domicile_fiscal?: string | null;
foreign_tax_id?: string | null;
client_or_provider?: string | null;
is_active?: boolean;
address?: Omit<ClientProviderAddress, 'id' | 'client_id'> | null;
programs?: Omit<ClientProviderPrograms, 'id' | 'client_id'> | null;
// DTOs de Envío (excluyendo IDs automáticos)
export interface CreateClientProviderData extends Omit<ClientProvider, 'id' | 'address' | 'programs'> {
address?: ClientProviderAddress | null;
programs?: ClientProviderPrograms | null;
}
export interface UpdateClientProviderData {
rfc?: string;
name?: string;
curp?: string | null;
residence_country?: string | null;
domicile_fiscal?: string | null;
foreign_tax_id?: string | null;
client_or_provider?: string | null;
is_active?: boolean;
address?: Partial<ClientProviderAddress> | null;
programs?: Partial<ClientProviderPrograms> | null;
}
export interface UpdateClientProviderData extends Partial<CreateClientProviderData> {}
/**
* API para Clientes y Proveedores
*/
export const clientsProvidersApi = {
/**
* Lista todos los clientes y proveedores con paginación
* @param companyId - ID de la compañía
* @param page - Número de página (por defecto 1)
* @param pageSize - Tamaño de página (por defecto 50)
* @param filters - Filtros opcionales
*/
list: (companyId: number, page = 1, pageSize = 50, filters?: Record<string, any>) => {
const params = new URLSearchParams({
company_id: companyId.toString(),
page: page.toString(),
page_size: pageSize.toString()
});
list: (companyId: number, page = 1, pageSize = 50, filters?: Record<string, any>) => {
const params = new URLSearchParams({
company_id: companyId.toString(),
page: page.toString(),
page_size: pageSize.toString()
});
if (filters) {
Object.entries(filters).forEach(([key, value]) => {
if (value) params.append(key, value.toString());
});
}
return api.get<ClientProviderListResponse>(`/v1/a76/clients-providers?${params.toString()}`);
},
get: (id: number, companyId: number) =>
api.get<ClientProvider>(`/v1/a76/clients-providers/${id}?company_id=${companyId}`),
create: (companyId: number, data: any) =>
api.post<ClientProvider>(`/v1/a76/clients-providers?company_id=${companyId}`, data),
if (filters) {
Object.entries(filters).forEach(([key, value]) => {
if (value !== undefined && value !== null && value !== '') {
params.append(key, value.toString());
}
});
}
update: (id: number, companyId: number, data: any) =>
api.patch<ClientProvider>(`/v1/a76/clients-providers/${id}?company_id=${companyId}`, data),
return api.get<ClientProviderListResponse>(
`/v1/a76/clients-providers?${params.toString()}`
);
},
/**
* Obtiene un cliente/proveedor por ID
* @param id - ID del cliente/proveedor
* @param companyId - ID de la compañía
*/
get: (id: number, companyId: number) =>
api.get<ClientProvider>(`/v1/a76/clients-providers/${id}?company_id=${companyId}`),
/**
* Obtiene información básica de un cliente/proveedor
* @param id - ID del cliente/proveedor
* @param companyId - ID de la compañía
*/
getBasic: (id: number, companyId: number) =>
api.get<ClientProviderBasic>(
`/v1/a76/clients-providers/${id}/basic?company_id=${companyId}`
),
/**
* Crea un nuevo cliente/proveedor
* @param companyId - ID de la compañía
* @param data - Datos del cliente/proveedor a crear
*/
create: (companyId: number, data: CreateClientProviderData) =>
api.post<ClientProvider>(`/v1/a76/clients-providers?company_id=${companyId}`, data),
/**
* Actualiza un cliente/proveedor existente
* @param id - ID del cliente/proveedor a actualizar
* @param companyId - ID de la compañía
* @param data - Datos a actualizar
*/
update: (id: number, companyId: number, data: UpdateClientProviderData) =>
api.patch<ClientProvider>(`/v1/a76/clients-providers/${id}?company_id=${companyId}`, data),
/**
* Alterna el estado activo/inactivo de un cliente/proveedor
* @param id - ID del cliente/proveedor
* @param companyId - ID de la compañía
*/
toggleStatus: (id: number, companyId: number) =>
api.put<ClientProvider>(
`/v1/a76/clients-providers/${id}/toggle-status?company_id=${companyId}`,
{}
),
/**
* Elimina un cliente/proveedor
* @param id - ID del cliente/proveedor a eliminar
* @param companyId - ID de la compañía
*/
delete: (id: number, companyId: number) =>
api.delete(`/v1/a76/clients-providers/${id}?company_id=${companyId}`)
};
delete: (id: number, companyId: number) =>
api.delete(`/v1/a76/clients-providers/${id}?company_id=${companyId}`)
};

View File

@@ -1,111 +1,101 @@
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 { ClientProvider } from "$lib/api/dashboard/a76/clients-providers";
export type { ClientProvider };
export function createColumns(onSuccess) {
return [
{
accessorKey: "id",
header: "ID",
cell: ({ row }) => {
const snippet = createRawSnippet((getData) => {
const { val } = getData();
return { render: () => `<span class="font-medium">${val}</span>` };
});
return renderSnippet(snippet, { val: row.original.id });
}
},
{
accessorKey: "rfc",
header: "RFC",
cell: ({ row }) => {
const snippet = createRawSnippet((getData) => {
const { val } = getData();
return { render: () => `<code class="bg-muted px-1 py-0.5 rounded font-mono text-sm">${val}</code>` };
});
return renderSnippet(snippet, { val: row.original.rfc });
}
},
{
accessorKey: "name",
header: "Nombre",
cell: ({ row }) => {
const snippet = createRawSnippet((getData) => {
const { val } = getData();
return { render: () => `<div class="max-w-[250px] truncate font-medium" title="${val}">${val}</div>` };
});
return renderSnippet(snippet, { val: row.original.name });
}
},
{
id: "country",
header: "País",
cell: ({ row }) => {
const snippet = createRawSnippet((getData) => {
const { val } = getData();
return { render: () => `<div>${val || '-'}</div>` };
});
// Busca en address.country, si no existe pone null
const country = row.original.address?.country;
return renderSnippet(snippet, { val: country });
}
},
{
accessorKey: "client_or_provider",
header: "Tipo",
cell: ({ row }) => {
const snippet = createRawSnippet((getData) => {
const { val } = getData();
const map = { client: 'Cliente', provider: 'Proveedor', both: 'Ambos' };
const colors = {
client: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300',
provider: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300',
both: 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300'
};
return {
render: () => `<span class="px-2 py-0.5 rounded-full text-xs font-medium ${colors[val] || 'bg-gray-100'}">${map[val] || val}</span>`
};
});
return renderSnippet(snippet, { val: row.original.client_or_provider });
}
},
// --- CORRECCIÓN AQUÍ ---
{
accessorKey: "is_active",
header: "Estado",
cell: ({ row }) => {
const snippet = createRawSnippet((getData) => {
const { val } = getData();
const isActive = !!val;
export function createColumns(onSuccess?: () => void): ColumnDef<ClientProvider>[] {
return [
{
accessorKey: "id",
header: "ID",
cell: ({ row }) => {
const idSnippet = createRawSnippet<[{ id: number }]>((getId) => {
const { id } = getId();
return {
render: () =>
`<span class="font-medium">${id}</span>`
};
});
return renderSnippet(idSnippet, { id: row.original.id });
}
},
{
accessorKey: "rfc",
header: "RFC",
cell: ({ row }) => {
const rfcSnippet = createRawSnippet<[{ rfc: string }]>((getRfc) => {
const { rfc } = getRfc();
return {
render: () =>
`<code class="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold">${rfc}</code>`
};
});
return renderSnippet(rfcSnippet, { rfc: row.original.rfc });
}
},
{
accessorKey: "name",
header: "Nombre",
cell: ({ row }) => {
const nameSnippet = createRawSnippet<[{ name: string }]>((getName) => {
const { name } = getName();
return {
render: () => `<div class="max-w-[300px] truncate font-medium">${name}</div>`
};
});
return renderSnippet(nameSnippet, { name: row.original.name });
}
},
{
accessorKey: "client_or_provider",
header: "Tipo",
cell: ({ row }) => {
const typeSnippet = createRawSnippet<[{ type: string | null | undefined }]>((getType) => {
const { type } = getType();
const displayType = type === 'client' ? 'Cliente' : type === 'provider' ? 'Proveedor' : type === 'both' ? 'Ambos' : 'N/A';
const colorClass = type === 'client' ? 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300'
: type === 'provider' ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300'
: type === 'both' ? 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300'
: 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-300';
return {
render: () => `<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${colorClass}">${displayType}</span>`
};
});
return renderSnippet(typeSnippet, { type: row.original.client_or_provider });
}
},
{
accessorKey: "residence_country",
header: "País",
cell: ({ row }) => {
const countrySnippet = createRawSnippet<[{ country: string | null | undefined }]>((getCountry) => {
const { country } = getCountry();
return {
render: () => `<div class="max-w-[120px] truncate">${country || '-'}</div>`
};
});
return renderSnippet(countrySnippet, { country: row.original.residence_country });
}
},
{
accessorKey: "is_active",
header: "Estado",
cell: ({ row }) => {
const statusSnippet = createRawSnippet<[{ status: number | undefined }]>((getStatus) => {
const { status } = getStatus();
const isEnabled = status === 1;
const statusText = isEnabled ? 'Activo' : 'Inactivo';
const colorClass = isEnabled
? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300'
: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300';
return {
render: () => `<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${colorClass}">${statusText}</span>`
};
});
return renderSnippet(statusSnippet, { status: row.original.is_active });
}
},
{
id: "actions",
cell: ({ row }) => {
return renderComponent(DataTableActions, { item: row.original, onSuccess });
}
}
];
}
// Mantener compatibilidad hacia atrás
export const columns = createColumns();
const text = isActive ? 'Activo' : 'Inactivo';
const color = isActive
? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300'
: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300';
return {
render: () => `<span class="px-2 py-0.5 rounded-full text-xs font-medium ${color}">${text}</span>`
};
});
return renderSnippet(snippet, { val: row.original.is_active });
}
},
{
id: "actions",
header: "Acciones",
cell: ({ row }) => renderComponent(DataTableActions, { item: row.original, onSuccess })
}
];
}

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,453 @@
<script lang="ts">
import { onMount } from 'svelte';
import { page } from '$app/stores';
import { goto } from "$app/navigation";
// Componentes UI
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 * as Tabs from "$lib/components/ui/tabs";
import { Switch } from "$lib/components/ui/switch";
import { LoaderCircle, ArrowLeft, Save, Building2, MapPin, FileText, Settings } from 'lucide-svelte';
// API & Stores
import { clientsProvidersApi } from "$lib/api/dashboard/a76/clients-providers";
import { companyStore } from "$lib/stores/company.svelte";
// --- CONFIGURACIÓN ---
let id = $derived($page.params.id);
let isEditing = $derived(!!id);
let title = $derived(isEditing ? "Editar Socio Comercial" : "Nuevo Socio Comercial");
const typeLabels: Record<string, string> = {
client: "Cliente",
provider: "Proveedor",
both: "Ambos"
};
// --- ESTADO INICIAL (PLANO) ---
const getEmptyForm = () => ({
rfc: "",
name: "",
short_name: "",
curp: "",
client_or_provider: "client",
type_nat_foreign: "N",
responsible: "",
position: "",
is_active: true,
is_national_provider: false,
streets: "",
exterior_number: "",
interior_number: "",
neighborhood: "",
municipality: "",
city: "",
state: "",
country: "",
postal_code: "",
email: "",
phone: "",
contact: "",
// Tabla Programas (Programs)
program: "",
program_number: "",
authorization_date_str: "", // String para input date
prosec: 0,
manufacturer_id: "",
tax_id: "",
ctpat_svi: "",
is_certified_company: "0"
});
let formData = $state(getEmptyForm());
let loading = $state(false);
let error = $state<string | null>(null);
// --- UTILIDADES ---
const intDateToString = (d?: number | null) => d ? `${d.toString().substring(0, 4)}-${d.toString().substring(4, 6)}-${d.toString().substring(6, 8)}` : "";
const stringDateToInt = (d?: string) => d ? parseInt(d.replace(/-/g, '')) : null;
const clean = (v: any) => (typeof v === 'string' && !v.trim() ? null : v);
// --- CARGA DE DATOS ---
$effect(() => {
if (id && companyStore.activeCompany?.id) loadData(Number(id));
else if (!id) formData = getEmptyForm();
});
async function loadData(clientId: number) {
if (!companyStore.activeCompany?.id) return;
loading = true;
try {
const res = await clientsProvidersApi.get(clientId, companyStore.activeCompany.id);
const item = (res as any).data || res;
if (item) {
const addr = item.address || {};
const prog = item.programs || {};
// Mapear respuesta anidada -> formulario plano
formData = {
rfc: item.rfc || "",
name: item.name || "",
short_name: item.short_name || "",
curp: item.curp || "",
client_or_provider: item.client_or_provider || "client",
type_nat_foreign: item.type_nat_foreign || "N",
responsible: item.responsible || "",
position: item.position || "",
is_active: !!item.is_active,
is_national_provider: !!item.is_national_provider,
streets: addr.streets || "",
exterior_number: addr.exterior_number || "",
interior_number: addr.interior_number || "",
neighborhood: addr.neighborhood || "",
municipality: addr.municipality || "",
city: addr.city || "",
state: addr.state || "",
country: addr.country || "",
postal_code: addr.postal_code || "",
email: addr.email || "",
phone: addr.phone || "",
contact: addr.contact || "",
program: prog.program || "",
program_number: prog.program_number || "",
authorization_date_str: intDateToString(prog.secon_auth_date),
prosec: prog.prosec || 0,
manufacturer_id: prog.manufacturer_id || "",
tax_id: prog.tax_id || "",
ctpat_svi: prog.ctpat_svi || "",
is_certified_company: prog.is_certified_company || "0"
};
}
} catch (e: any) {
error = "Error al cargar: " + e.message;
} finally {
loading = false;
}
}
// --- ENVÍO DE DATOS ---
async function handleSubmit() {
if (!companyStore.activeCompany) { error = "Selecciona una compañía"; return; }
if (!formData.rfc.trim() || !formData.name.trim()) { error = "RFC y Nombre obligatorios"; return; }
loading = true;
error = null;
try {
// Reconstruir objeto anidado para el backend
const payload = {
rfc: clean(formData.rfc),
name: clean(formData.name),
short_name: clean(formData.short_name),
curp: clean(formData.curp),
client_or_provider: formData.client_or_provider,
type_nat_foreign: clean(formData.type_nat_foreign),
responsible: clean(formData.responsible),
position: clean(formData.position),
is_active: formData.is_active,
is_national_provider: formData.is_national_provider,
address: {
streets: clean(formData.streets),
exterior_number: clean(formData.exterior_number),
interior_number: clean(formData.interior_number),
neighborhood: clean(formData.neighborhood),
municipality: clean(formData.municipality),
city: clean(formData.city),
state: clean(formData.state),
country: clean(formData.country),
postal_code: clean(formData.postal_code),
email: clean(formData.email),
phone: clean(formData.phone),
contact: clean(formData.contact)
},
programs: {
program: clean(formData.program),
program_number: clean(formData.program_number),
secon_auth_date: stringDateToInt(formData.authorization_date_str),
prosec: Number(formData.prosec) || null,
manufacturer_id: clean(formData.manufacturer_id),
tax_id: clean(formData.tax_id),
ctpat_svi: clean(formData.ctpat_svi),
is_certified_company: clean(formData.is_certified_company)
}
};
const companyId = companyStore.activeCompany.id;
const response = isEditing
? await clientsProvidersApi.update(Number(id), companyId, payload as any)
: await clientsProvidersApi.create(companyId, payload as any);
if (response.error) throw new Error(response.error);
goto('/dashboard/clients_and_providers');
} catch (e: any) {
console.error(e);
error = e.message || "Error al guardar";
} finally {
loading = false;
}
}
</script>
<div class="w-full mx-auto max-w-6xl py-6 px-4 space-y-6 pb-48">
<div class="flex items-center gap-4">
<Button variant="outline" size="icon" href="/dashboard/clients_and_providers">
<ArrowLeft class="h-4 w-4" />
</Button>
<div>
<h1 class="text-2xl font-bold tracking-tight">{title}</h1>
<p class="text-muted-foreground">Gestión integral del catálogo de socios comerciales.</p>
</div>
</div>
{#if error}
<div class="p-4 rounded-md bg-destructive/10 text-destructive border border-destructive/20 text-sm font-medium">
⚠️ {error}
</div>
{/if}
<form onsubmit={(e) => { e.preventDefault(); handleSubmit(); }} class="space-y-6">
<Card.Root>
<Card.Content class="p-6">
<Tabs.Root value="general" class="w-full">
<div class="min-h-[400px]">
<Tabs.Content value="general" class="space-y-4 pt-4">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="grid gap-2">
<Label for="rfc">RFC <span class="text-destructive">*</span></Label>
<Input id="rfc" bind:value={formData.rfc} placeholder="XAXX010101000" maxlength={13} disabled={loading} />
</div>
<div class="grid gap-2">
<Label for="type">Tipo de Relación <span class="text-destructive">*</span></Label>
<Select.Root type="single" bind:value={formData.client_or_provider}>
<Select.Trigger id="type">
{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="grid grid-cols-1 md:grid-cols-4 gap-4">
<div class="md:col-span-3 grid gap-2">
<Label for="name">Razón Social <span class="text-destructive">*</span></Label>
<Input id="name" bind:value={formData.name} placeholder="Nombre completo" maxlength={256} disabled={loading} />
</div>
<div class="grid gap-2">
<Label for="short_name">Nombre Corto</Label>
<Input id="short_name" bind:value={formData.short_name} placeholder="Alias" maxlength={10} disabled={loading} />
</div>
</div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="grid gap-2">
<Label for="curp">CURP (Opcional)</Label>
<Input id="curp" bind:value={formData.curp} maxlength={18} disabled={loading} />
</div>
<div class="grid gap-2">
<Label for="type_nat">Tipo Origen</Label>
<Select.Root type="single" bind:value={formData.type_nat_foreign}>
<Select.Trigger id="type_nat">
{formData.type_nat_foreign === 'N' ? 'Nacional' : formData.type_nat_foreign === 'E' ? 'Extranjero' : 'Seleccione'}
</Select.Trigger>
<Select.Content>
<Select.Item value="N" label="Nacional">Nacional</Select.Item>
<Select.Item value="E" label="Extranjero">Extranjero</Select.Item>
</Select.Content>
</Select.Root>
</div>
</div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="grid gap-2">
<Label for="responsible">Responsable</Label>
<Input id="responsible" bind:value={formData.responsible} disabled={loading} />
</div>
<div class="grid gap-2">
<Label for="position">Puesto</Label>
<Input id="position" bind:value={formData.position} disabled={loading} />
</div>
</div>
</Tabs.Content>
<Tabs.Content value="address" class="space-y-4 pt-4">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="grid gap-2">
<Label for="street">Calle</Label>
<Input id="street" bind:value={formData.streets} maxlength={100} disabled={loading} />
</div>
<div class="grid grid-cols-2 gap-4">
<div class="grid gap-2">
<Label for="ext">No. Exterior</Label>
<Input id="ext" bind:value={formData.exterior_number} maxlength={20} disabled={loading} />
</div>
<div class="grid gap-2">
<Label for="int">No. Interior</Label>
<Input id="int" bind:value={formData.interior_number} maxlength={20} disabled={loading} />
</div>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<div class="grid gap-2">
<Label for="col">Colonia</Label>
<Input id="col" bind:value={formData.neighborhood} maxlength={40} disabled={loading} />
</div>
<div class="grid gap-2">
<Label for="cp">C.P.</Label>
<Input id="cp" bind:value={formData.postal_code} maxlength={15} disabled={loading} />
</div>
<div class="grid gap-2">
<Label for="mun">Municipio</Label>
<Input id="mun" bind:value={formData.municipality} maxlength={150} disabled={loading} />
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<div class="grid gap-2">
<Label for="city">Ciudad</Label>
<Input id="city" bind:value={formData.city} maxlength={30} disabled={loading} />
</div>
<div class="grid gap-2">
<Label for="state">Estado</Label>
<Input id="state" bind:value={formData.state} maxlength={30} disabled={loading} />
</div>
<div class="grid gap-2">
<Label for="country">País (ISO)</Label>
<Input id="country" bind:value={formData.country} placeholder="MEX" maxlength={3} disabled={loading} />
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 pt-4 border-t">
<div class="grid gap-2">
<Label for="email">Email de Contacto</Label>
<Input id="email" type="email" bind:value={formData.email} disabled={loading} />
</div>
<div class="grid gap-2">
<Label for="phone">Teléfono</Label>
<Input id="phone" bind:value={formData.phone} disabled={loading} />
</div>
</div>
</Tabs.Content>
<Tabs.Content value="programs" class="space-y-4 pt-4">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="grid gap-2">
<Label for="program">Programa</Label>
<Input id="program" bind:value={formData.program} placeholder="IMMEX" maxlength={7} disabled={loading} />
</div>
<div class="grid gap-2">
<Label for="program_num">Número de Programa</Label>
<Input id="program_num" bind:value={formData.program_number} maxlength={40} disabled={loading} />
</div>
</div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-3">
<div class="grid gap-2">
<Label for="auth_date">Fecha Autorización</Label>
<Input id="auth_date" type="date" bind:value={formData.authorization_date_str} disabled={loading} />
</div>
<div class="grid gap-2">
<Label for="tax_id">Tax ID (Extranjero)</Label>
<Input id="tax_id" bind:value={formData.tax_id} maxlength={30} disabled={loading} />
</div>
<div class="grid gap-2">
<Label for="man_id">Manufacturer ID</Label>
<Input id="man_id" bind:value={formData.manufacturer_id} maxlength={25} disabled={loading} />
</div>
</div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="grid gap-2">
<Label for="ctpat">C-TPAT / SVI</Label>
<Input id="ctpat" bind:value={formData.ctpat_svi} maxlength={100} disabled={loading} />
</div>
<div class="grid gap-2">
<Label for="prosec">PROSEC (Sector)</Label>
<Input id="prosec" type="number" bind:value={formData.prosec} disabled={loading} />
</div>
</div>
</Tabs.Content>
<Tabs.Content value="config" class="space-y-4 pt-4">
<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
<div class="flex items-center gap-3 p-4 border rounded-lg bg-card">
<Switch id="is_active" bind:checked={formData.is_active} disabled={loading} />
<div class="grid gap-0.5">
<Label for="is_active">Registro Activo</Label>
<p class="text-xs text-muted-foreground">Habilitar o deshabilitar este socio comercial</p>
</div>
</div>
<div class="flex items-center gap-3 p-4 border rounded-lg bg-card">
<Switch id="is_national" bind:checked={formData.is_national_provider} disabled={loading} />
<div class="grid gap-0.5">
<Label for="is_national">Proveedor Nacional</Label>
<p class="text-xs text-muted-foreground">Marcar si es un proveedor nacional</p>
</div>
</div>
</div>
</Tabs.Content>
</div>
<Tabs.List class="grid grid-cols-4 fixed bottom-24 left-1/2 -translate-x-1/2 w-[95%] max-w-2xl z-40 shadow-2xl bg-background border p-1 rounded-xl">
<Tabs.Trigger value="general" class="flex gap-2 items-center justify-center">
<Building2 class="h-4 w-4 hidden sm:block" /> General
</Tabs.Trigger>
<Tabs.Trigger value="address" class="flex gap-2 items-center justify-center">
<MapPin class="h-4 w-4 hidden sm:block" /> Dirección
</Tabs.Trigger>
<Tabs.Trigger value="programs" class="flex gap-2 items-center justify-center">
<FileText class="h-4 w-4 hidden sm:block" /> Programas
</Tabs.Trigger>
<Tabs.Trigger value="config" class="flex gap-2 items-center justify-center">
<Settings class="h-4 w-4 hidden sm:block" /> Config
</Tabs.Trigger>
</Tabs.List>
</Tabs.Root>
</Card.Content>
</Card.Root>
<div class="fixed bottom-0 right-0 left-0 md:left-64 p-4 border-t bg-background/95 backdrop-blur z-50">
<div class="max-w-6xl mx-auto flex justify-end gap-4">
<Button type="button" variant="ghost" onclick={() => goto('/dashboard/clients_and_providers')} disabled={loading}>
Cancelar
</Button>
{#if !isEditing}
<Button type="button" variant="outline" onclick={() => formData = getEmptyForm()} disabled={loading}>
Limpiar
</Button>
{/if}
<Button type="submit" disabled={loading} class="min-w-[140px]">
{#if loading}
<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
{:else}
<Save class="mr-2 h-4 w-4" />
{/if}
{isEditing ? 'Actualizar' : 'Guardar'}
</Button>
</div>
</div>
</form>
</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>