feat: Implement customs brokers management interface

- Added a data table for displaying customs brokers with columns for key, name, type, license, RFC, email, phone, city, and actions.
- Created a dialog for adding new customs brokers with a form for inputting necessary details.
- Implemented actions for viewing details and deleting customs brokers with confirmation dialogs.
- Integrated search functionality to find customs brokers by their key.
- Established server-side loading for the customs brokers page to handle authentication and data retrieval.
This commit is contained in:
2025-11-12 16:57:15 -06:00
parent 6225122832
commit aa35635397
47 changed files with 1381 additions and 10 deletions

View File

@@ -22,7 +22,7 @@ class Company(Base, TimestampMixin):
Modelo para la tabla Company - Información de la empresa
"""
__tablename__ = "company"
__tablename__ = "company" #GEmpresa
__table_args__ = (
PrimaryKeyConstraint("id", name="company_pkey"),
ForeignKeyConstraint(

View File

@@ -9,7 +9,7 @@ from sqlalchemy.orm import Session
from core.database import get_core_db
from core.security import get_current_user, validate_access_to_resource
from ....common.tenant_crud_routes import TenantCRUDRoutes
from .....common.tenant_crud_routes import TenantCRUDRoutes
from .dto import CompanyCreateDTO, CompanyResponseDTO, CompanyUpdateDTO
from .models import Company
from .service import CompanyService

View File

@@ -11,22 +11,22 @@ from .customs_brokers.routes import router as customs_broker_router
from .auth import router as auth_router
from .classes import router as classes_router
from .clients_and_providers import router as client_and_provider_router
from .company import router as company_router
from .general_catalogs.company import router as company_router
from .country_rule_oct.routes import router as country_rule_oct_router
from .drivers.routes import router as drivers_router
from .exchange_rate.routes import router as exchange_rate_router
from .transportation.drivers.routes import router as drivers_router
from .general_catalogs.exchange_rate.routes import router as exchange_rate_router
from .fraction_rule_octave.routes import router as fraction_rule_octave_router
from .licenses import router as licenses_router
from .package.routes import router as package_router
from .general_catalogs.packages.routes import router as package_router
from .parts import router as parts_router
from .pedmientos.router import router as pedimentos_router
from .permission_rule_oct.routes import router as permission_rule_oct_router
from .seal.routes import router as seal_router
from .general_catalogs.seal.routes import router as seal_router
from .tenants import router as tenants_router
from .trailers.routes import router as trailers_router
from .transporters.routes import router as transporters_router
from .transportation.trailers.routes import router as trailers_router
from .transportation.transporters.routes import router as transporters_router
from .user_tenant.routes import router as user_tenant_router
from .vehicles.routes import router as vehicles_router
from .transportation.vehicles.routes import router as vehicles_router
# Router principal
router = APIRouter()

View File

@@ -0,0 +1,128 @@
/**
* API Client para Agentes Aduanales (Customs Brokers)
* Gestiona las operaciones CRUD para agentes aduanales
*/
import { api } from '$lib/api';
export interface CustomsBroker {
type?: string | null;
broker_key: string;
name?: string | null;
address?: string | null;
postal_code?: string | null;
city?: string | null;
state?: string | null;
phone?: string | null;
fax?: string | null;
email?: string | null;
country?: string | null;
tax_id?: string | null;
personal_id?: string | null;
position?: string | null;
license?: string | null;
company?: string | null;
contact?: string | null;
tenant_id: string;
company_id: string;
}
export interface CustomsBrokerVU {
certificate_path?: string | null;
key_path?: string | null;
access_key?: string | null;
fiel_format?: string | null;
signature_read_path?: string | null;
archive_path?: string | null;
fiel_access_key?: string | null;
web_service_user?: string | null;
web_service_access_key?: string | null;
vu_email?: string | null;
vu_figure_type?: string | null;
xml_files_path?: string | null;
query_tax_id?: string | null;
doda_certificate_path?: string | null;
doda_key_path?: string | null;
doda_web_service_user?: string | null;
doda_web_service_access_key?: string | null;
doda_fiel_access_key?: string | null;
doda_xml_files_path?: string | null;
}
export interface CustomsBrokerPersonnel {
broker_key: string;
line: number;
name?: string | null;
tax_id?: string | null;
personal_id?: string | null;
position?: string | null;
license?: string | null;
first_name?: string | null;
last_name?: string | null;
middle_name?: string | null;
email?: string | null;
}
export interface CreateCustomsBrokerData {
type?: string | null;
broker_key: string;
name?: string | null;
address?: string | null;
postal_code?: string | null;
city?: string | null;
state?: string | null;
phone?: string | null;
fax?: string | null;
email?: string | null;
country?: string | null;
tax_id?: string | null;
personal_id?: string | null;
position?: string | null;
license?: string | null;
company?: string | null;
contact?: string | null;
tenant_id: string;
company_id: string;
}
/**
* API para Agentes Aduanales
*/
export const customsBrokersApi = {
/**
* Obtiene un agente aduanal por su clave
*/
get: (brokerKey: string) => {
return api.get<CustomsBroker>(`/api/v1/a76/customs-broker/${brokerKey}`);
},
/**
* Crea un nuevo agente aduanal
*/
create: (data: CreateCustomsBrokerData) => {
return api.post<CustomsBroker>('/api/v1/a76/customs-broker', data);
},
/**
* Elimina un agente aduanal
*/
delete: (brokerKey: string) => {
return api.delete<CustomsBroker>(`/api/v1/a76/customs-broker/${brokerKey}`);
},
/**
* Actualiza la información de VU de un agente aduanal
*/
updateVU: (brokerKey: string, data: CustomsBrokerVU) => {
return api.put<CustomsBrokerVU>(`/api/v1/a76/customs-broker-vu/${brokerKey}`, data);
},
/**
* Actualiza el personal de un agente aduanal
*/
updatePersonnel: (brokerKey: string, line: number, data: CustomsBrokerPersonnel) => {
return api.put<CustomsBrokerPersonnel>(
`/api/v1/a76/customs-broker-personnel/${brokerKey}/${line}`,
data
);
}
};

View File

@@ -0,0 +1,129 @@
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 { CustomsBroker } from "$lib/api/dashboard/a76/customs-brokers";
export type { CustomsBroker };
export function createColumns(onSuccess?: () => void): ColumnDef<CustomsBroker>[] {
return [
{
accessorKey: "broker_key",
header: "Clave",
cell: ({ row }) => {
const keySnippet = createRawSnippet<[{ key: string }]>((getKey) => {
const { key } = getKey();
return {
render: () =>
`<code class="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold">${key}</code>`
};
});
return renderSnippet(keySnippet, { key: row.original.broker_key });
}
},
{
accessorKey: "name",
header: "Nombre",
cell: ({ row }) => {
const nameSnippet = createRawSnippet<[{ name: string | null | undefined }]>((getName) => {
const { name } = getName();
return {
render: () => `<div class="max-w-[300px] truncate font-medium">${name || '-'}</div>`
};
});
return renderSnippet(nameSnippet, { name: row.original.name });
}
},
{
accessorKey: "type",
header: "Tipo",
cell: ({ row }) => {
const typeSnippet = createRawSnippet<[{ type: string | null | undefined }]>((getType) => {
const { type } = getType();
return {
render: () => `<div class="max-w-[120px] truncate">${type || '-'}</div>`
};
});
return renderSnippet(typeSnippet, { type: row.original.type });
}
},
{
accessorKey: "license",
header: "Patente",
cell: ({ row }) => {
const licenseSnippet = createRawSnippet<[{ license: string | null | undefined }]>((getLicense) => {
const { license } = getLicense();
return {
render: () =>
license
? `<code class="relative rounded bg-blue-100 dark:bg-blue-900 px-[0.3rem] py-[0.2rem] font-mono text-xs font-semibold">${license}</code>`
: `<span class="text-muted-foreground">-</span>`
};
});
return renderSnippet(licenseSnippet, { license: row.original.license });
}
},
{
accessorKey: "tax_id",
header: "RFC",
cell: ({ row }) => {
const taxIdSnippet = createRawSnippet<[{ taxId: string | null | undefined }]>((getTaxId) => {
const { taxId } = getTaxId();
return {
render: () => `<div class="max-w-[140px] truncate font-mono text-sm">${taxId || '-'}</div>`
};
});
return renderSnippet(taxIdSnippet, { taxId: row.original.tax_id });
}
},
{
accessorKey: "email",
header: "Email",
cell: ({ row }) => {
const emailSnippet = createRawSnippet<[{ email: string | null | undefined }]>((getEmail) => {
const { email } = getEmail();
return {
render: () => `<div class="max-w-[200px] truncate text-sm">${email || '-'}</div>`
};
});
return renderSnippet(emailSnippet, { email: row.original.email });
}
},
{
accessorKey: "phone",
header: "Teléfono",
cell: ({ row }) => {
const phoneSnippet = createRawSnippet<[{ phone: string | null | undefined }]>((getPhone) => {
const { phone } = getPhone();
return {
render: () => `<div class="max-w-[140px] truncate text-sm">${phone || '-'}</div>`
};
});
return renderSnippet(phoneSnippet, { phone: row.original.phone });
}
},
{
accessorKey: "city",
header: "Ciudad",
cell: ({ row }) => {
const citySnippet = createRawSnippet<[{ city: string | null | undefined }]>((getCity) => {
const { city } = getCity();
return {
render: () => `<div class="max-w-[150px] truncate">${city || '-'}</div>`
};
});
return renderSnippet(citySnippet, { city: row.original.city });
}
},
{
id: "actions",
cell: ({ row }) => {
return renderComponent(DataTableActions, {
broker: row.original,
onSuccess
});
}
}
];
}

View File

@@ -0,0 +1,381 @@
<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 { customsBrokersApi, type CreateCustomsBrokerData } from "$lib/api/dashboard/a76/customs-brokers";
import { companyStore } from "$lib/stores/company.svelte";
let {
open = $bindable(false),
onSuccess
}: {
open: boolean;
onSuccess?: () => void;
} = $props();
let formData = $state({
broker_key: "",
name: "",
type: "",
address: "",
postal_code: "",
city: "",
state: "",
phone: "",
fax: "",
email: "",
country: "",
tax_id: "",
personal_id: "",
position: "",
license: "",
company: "",
contact: ""
});
let loading = $state(false);
let error = $state<string | null>(null);
async function handleSubmit(e: Event) {
e.preventDefault();
if (!companyStore.activeCompany) {
error = "No hay compañía seleccionada";
return;
}
loading = true;
error = null;
try {
const payload: CreateCustomsBrokerData = {
broker_key: formData.broker_key,
name: formData.name || null,
type: formData.type || null,
address: formData.address || null,
postal_code: formData.postal_code || null,
city: formData.city || null,
state: formData.state || null,
phone: formData.phone || null,
fax: formData.fax || null,
email: formData.email || null,
country: formData.country || null,
tax_id: formData.tax_id || null,
personal_id: formData.personal_id || null,
position: formData.position || null,
license: formData.license || null,
company: formData.company || null,
contact: formData.contact || null,
tenant_id: "1", // TODO: Get from user context
company_id: companyStore.activeCompany.id.toString()
};
const response = await customsBrokersApi.create(payload);
if (response.error) {
if (response.status === 401) {
error = 'Sesión expirada. Recargando página...';
setTimeout(() => {
window.location.reload();
}, 1500);
} else {
error = response.error;
}
return;
}
// Éxito
open = false;
if (onSuccess) {
onSuccess();
}
} catch (e) {
error = e instanceof Error ? e.message : "Error al guardar";
console.error("Error saving:", e);
} finally {
loading = false;
}
}
function handleOpenChange(newOpen: boolean) {
if (!newOpen) {
// Limpiar form al cerrar
formData = {
broker_key: "",
name: "",
type: "",
address: "",
postal_code: "",
city: "",
state: "",
phone: "",
fax: "",
email: "",
country: "",
tax_id: "",
personal_id: "",
position: "",
license: "",
company: "",
contact: ""
};
error = null;
}
open = newOpen;
}
</script>
<Dialog.Root bind:open onOpenChange={handleOpenChange}>
<Dialog.Content class="sm:max-w-[700px] max-h-[90vh] overflow-y-auto">
<Dialog.Header>
<Dialog.Title>Nuevo Agente Aduanal</Dialog.Title>
<Dialog.Description>
Completa los datos para crear un nuevo agente aduanal.
</Dialog.Description>
</Dialog.Header>
<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="broker_key">Clave *</Label>
<Input
id="broker_key"
bind:value={formData.broker_key}
placeholder="Ej: 12345"
maxlength={5}
required
disabled={loading}
/>
</div>
<div class="space-y-2">
<Label for="type">Tipo</Label>
<Input
id="type"
bind:value={formData.type}
placeholder="Tipo de agente"
maxlength={9}
disabled={loading}
/>
</div>
</div>
<div class="space-y-2">
<Label for="name">Nombre</Label>
<Input
id="name"
bind:value={formData.name}
placeholder="Nombre del agente aduanal"
maxlength={80}
disabled={loading}
/>
</div>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<Label for="license">Patente</Label>
<Input
id="license"
bind:value={formData.license}
placeholder="Número de patente"
maxlength={4}
disabled={loading}
/>
</div>
<div class="space-y-2">
<Label for="company">Empresa</Label>
<Input
id="company"
bind:value={formData.company}
placeholder="Empresa del agente"
maxlength={200}
disabled={loading}
/>
</div>
</div>
</div>
<!-- Información de contacto -->
<div class="space-y-4">
<h3 class="text-sm font-semibold">Información de Contacto</h3>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<Label for="phone">Teléfono</Label>
<Input
id="phone"
bind:value={formData.phone}
placeholder="Número telefónico"
maxlength={30}
disabled={loading}
/>
</div>
<div class="space-y-2">
<Label for="fax">Fax</Label>
<Input
id="fax"
bind:value={formData.fax}
placeholder="Número de fax"
maxlength={30}
disabled={loading}
/>
</div>
</div>
<div class="space-y-2">
<Label for="email">Email</Label>
<Input
id="email"
type="email"
bind:value={formData.email}
placeholder="correo@ejemplo.com"
maxlength={100}
disabled={loading}
/>
</div>
<div class="space-y-2">
<Label for="contact">Contacto</Label>
<Input
id="contact"
bind:value={formData.contact}
placeholder="Nombre del contacto"
maxlength={80}
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="address">Dirección</Label>
<Input
id="address"
bind:value={formData.address}
placeholder="Calle y número"
maxlength={1500}
disabled={loading}
/>
</div>
<div class="grid grid-cols-3 gap-4">
<div class="space-y-2">
<Label for="postal_code">Código Postal</Label>
<Input
id="postal_code"
bind:value={formData.postal_code}
placeholder="C.P."
maxlength={15}
disabled={loading}
/>
</div>
<div class="space-y-2">
<Label for="city">Ciudad</Label>
<Input
id="city"
bind:value={formData.city}
placeholder="Ciudad"
maxlength={30}
disabled={loading}
/>
</div>
<div class="space-y-2">
<Label for="state">Estado</Label>
<Input
id="state"
bind:value={formData.state}
placeholder="Estado"
maxlength={30}
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={3}
disabled={loading}
/>
</div>
</div>
<!-- Información fiscal -->
<div class="space-y-4">
<h3 class="text-sm font-semibold">Información Fiscal</h3>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<Label for="tax_id">RFC</Label>
<Input
id="tax_id"
bind:value={formData.tax_id}
placeholder="RFC"
maxlength={30}
disabled={loading}
/>
</div>
<div class="space-y-2">
<Label for="personal_id">CURP</Label>
<Input
id="personal_id"
bind:value={formData.personal_id}
placeholder="CURP"
maxlength={20}
disabled={loading}
/>
</div>
</div>
<div class="space-y-2">
<Label for="position">Posición</Label>
<Input
id="position"
bind:value={formData.position}
placeholder="Cargo o posición"
maxlength={30}
disabled={loading}
/>
</div>
</div>
<Dialog.Footer>
<Button type="button" variant="outline" onclick={() => (open = false)} disabled={loading}>
Cancelar
</Button>
<Button type="submit" 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 Agente Aduanal
{/if}
</Button>
</Dialog.Footer>
</form>
</Dialog.Content>
</Dialog.Root>

View File

@@ -0,0 +1,75 @@
<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 { CustomsBroker } from "./columns.js";
import DetailsDialog from "./details-dialog.svelte";
import DeleteDialog from "./delete-dialog.svelte";
let {
broker,
onSuccess
}: {
broker: CustomsBroker;
onSuccess?: () => void;
} = $props();
let showDetailsDialog = $state(false);
let showDeleteDialog = $state(false);
function handleCopyKey() {
navigator.clipboard.writeText(broker.broker_key);
}
function handleCopyTaxId() {
if (broker.tax_id) {
navigator.clipboard.writeText(broker.tax_id);
}
}
function handleViewDetails() {
showDetailsDialog = true;
}
function handleDelete() {
showDeleteDialog = true;
}
</script>
<DropdownMenu.Root>
<DropdownMenu.Trigger>
<Button
variant="ghost"
size="icon"
class="relative h-8 w-8 p-0"
>
<span class="sr-only">Abrir menú</span>
<EllipsisIcon class="h-4 w-4" />
</Button>
</DropdownMenu.Trigger>
<DropdownMenu.Content>
<DropdownMenu.Group>
<DropdownMenu.Label>Acciones</DropdownMenu.Label>
<DropdownMenu.Item onclick={handleCopyKey}>
Copiar clave
</DropdownMenu.Item>
{#if broker.tax_id}
<DropdownMenu.Item onclick={handleCopyTaxId}>
Copiar RFC
</DropdownMenu.Item>
{/if}
</DropdownMenu.Group>
<DropdownMenu.Separator />
<DropdownMenu.Group>
<DropdownMenu.Item onclick={handleViewDetails}>
Ver detalles
</DropdownMenu.Item>
<DropdownMenu.Item onclick={handleDelete} class="text-destructive">
Eliminar
</DropdownMenu.Item>
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
<DetailsDialog bind:open={showDetailsDialog} {broker} />
<DeleteDialog bind:open={showDeleteDialog} {broker} {onSuccess} />

View File

@@ -0,0 +1,70 @@
<script lang="ts" generics="TData, TValue">
import { onMount } from 'svelte';
import {
type ColumnDef,
getCoreRowModel
} from "@tanstack/table-core";
import { createSvelteTable, FlexRender } from "$lib/components/ui/data-table/index.js";
import * as Table from "$lib/components/ui/table/index.js";
type DataTableProps<TData, TValue> = {
columns: ColumnDef<TData, TValue>[];
data: TData[];
};
let {
data,
columns
}: DataTableProps<TData, TValue> = $props();
const table = createSvelteTable({
get data() {
return data;
},
columns,
getCoreRowModel: getCoreRowModel()
});
</script>
<div class="w-full">
<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>

View File

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

View File

@@ -0,0 +1,192 @@
<script lang="ts">
import { Button } from "$lib/components/ui/button";
import * as Dialog from "$lib/components/ui/dialog";
import { Separator } from "$lib/components/ui/separator";
import type { CustomsBroker } from "$lib/api/dashboard/a76/customs-brokers";
let {
open = $bindable(false),
broker
}: {
open: boolean;
broker: CustomsBroker | null;
} = $props();
function handleOpenChange(newOpen: boolean) {
open = newOpen;
}
</script>
<Dialog.Root bind:open onOpenChange={handleOpenChange}>
<Dialog.Content class="sm:max-w-[700px] max-h-[80vh] overflow-y-auto">
<Dialog.Header>
<Dialog.Title>Detalles del Agente Aduanal</Dialog.Title>
<Dialog.Description>
Información completa del agente aduanal
</Dialog.Description>
</Dialog.Header>
{#if broker}
<div class="space-y-4 py-4">
<!-- Información básica -->
<div class="space-y-2">
<h3 class="text-sm font-semibold">Información Básica</h3>
<div class="grid grid-cols-2 gap-2">
<div class="flex flex-col gap-1">
<span class="text-xs font-medium text-muted-foreground">Clave</span>
<code class="text-sm font-mono font-semibold">{broker.broker_key}</code>
</div>
{#if broker.license}
<div class="flex flex-col gap-1">
<span class="text-xs font-medium text-muted-foreground">Patente</span>
<code class="text-sm font-mono font-semibold">{broker.license}</code>
</div>
{/if}
</div>
{#if broker.name}
<div class="flex flex-col gap-1">
<span class="text-xs font-medium text-muted-foreground">Nombre</span>
<span class="text-sm">{broker.name}</span>
</div>
{/if}
{#if broker.type}
<div class="flex flex-col gap-1">
<span class="text-xs font-medium text-muted-foreground">Tipo</span>
<span class="text-sm">{broker.type}</span>
</div>
{/if}
{#if broker.company}
<div class="flex flex-col gap-1">
<span class="text-xs font-medium text-muted-foreground">Empresa</span>
<span class="text-sm">{broker.company}</span>
</div>
{/if}
<Separator />
</div>
<!-- Información de contacto -->
<div class="space-y-2">
<h3 class="text-sm font-semibold">Información de Contacto</h3>
{#if broker.contact}
<div class="flex flex-col gap-1">
<span class="text-xs font-medium text-muted-foreground">Contacto</span>
<span class="text-sm">{broker.contact}</span>
</div>
{/if}
<div class="grid grid-cols-2 gap-2">
{#if broker.phone}
<div class="flex flex-col gap-1">
<span class="text-xs font-medium text-muted-foreground">Teléfono</span>
<span class="text-sm">{broker.phone}</span>
</div>
{/if}
{#if broker.fax}
<div class="flex flex-col gap-1">
<span class="text-xs font-medium text-muted-foreground">Fax</span>
<span class="text-sm">{broker.fax}</span>
</div>
{/if}
</div>
{#if broker.email}
<div class="flex flex-col gap-1">
<span class="text-xs font-medium text-muted-foreground">Email</span>
<a href="mailto:{broker.email}" class="text-sm text-blue-600 hover:underline">
{broker.email}
</a>
</div>
{/if}
<Separator />
</div>
<!-- Dirección -->
<div class="space-y-2">
<h3 class="text-sm font-semibold">Dirección</h3>
{#if broker.address}
<div class="flex flex-col gap-1">
<span class="text-xs font-medium text-muted-foreground">Dirección</span>
<span class="text-sm">{broker.address}</span>
</div>
{/if}
<div class="grid grid-cols-3 gap-2">
{#if broker.postal_code}
<div class="flex flex-col gap-1">
<span class="text-xs font-medium text-muted-foreground">C.P.</span>
<span class="text-sm">{broker.postal_code}</span>
</div>
{/if}
{#if broker.city}
<div class="flex flex-col gap-1">
<span class="text-xs font-medium text-muted-foreground">Ciudad</span>
<span class="text-sm">{broker.city}</span>
</div>
{/if}
{#if broker.state}
<div class="flex flex-col gap-1">
<span class="text-xs font-medium text-muted-foreground">Estado</span>
<span class="text-sm">{broker.state}</span>
</div>
{/if}
</div>
{#if broker.country}
<div class="flex flex-col gap-1">
<span class="text-xs font-medium text-muted-foreground">País</span>
<span class="text-sm">{broker.country}</span>
</div>
{/if}
<Separator />
</div>
<!-- Información fiscal -->
<div class="space-y-2">
<h3 class="text-sm font-semibold">Información Fiscal</h3>
{#if broker.tax_id}
<div class="flex flex-col gap-1">
<span class="text-xs font-medium text-muted-foreground">RFC</span>
<code class="text-sm font-mono">{broker.tax_id}</code>
</div>
{/if}
{#if broker.personal_id}
<div class="flex flex-col gap-1">
<span class="text-xs font-medium text-muted-foreground">CURP</span>
<code class="text-sm font-mono">{broker.personal_id}</code>
</div>
{/if}
{#if broker.position}
<div class="flex flex-col gap-1">
<span class="text-xs font-medium text-muted-foreground">Posición</span>
<span class="text-sm">{broker.position}</span>
</div>
{/if}
</div>
</div>
{:else}
<div class="py-8 text-center text-sm text-muted-foreground">
No hay información disponible
</div>
{/if}
<Dialog.Footer>
<Button onclick={() => (open = false)}>Cerrar</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>

View File

@@ -0,0 +1,21 @@
import type { PageServerLoad } from './$types';
import { getAuthTokens } from '$lib/server/api';
export const load: PageServerLoad = async ({ cookies, parent }) => {
// Esperar a que el layout padre valide/refresque el token
const parentData = await parent();
const { accessToken } = getAuthTokens(cookies);
if (!accessToken) {
return {
error: 'No authenticated',
companies: parentData.companies || []
};
}
return {
companies: parentData.companies || [],
error: null
};
};

View File

@@ -0,0 +1,253 @@
<script lang="ts">
import { onMount } from 'svelte';
import { customsBrokersApi, type CustomsBroker } from '$lib/api/dashboard/a76/customs-brokers';
import DataTable from '$lib/components/dashboard/customs_brokers/data-table.svelte';
import { createColumns } from '$lib/components/dashboard/customs_brokers/columns.js';
import CreateDialog from '$lib/components/dashboard/customs_brokers/create-dialog.svelte';
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';
import { Label } from '$lib/components/ui/label';
import type { PageData } from './$types';
import { browser } from '$app/environment';
import { companyStore } from '$lib/stores/company.svelte';
// Los datos iniciales vienen del servidor
let { data }: { data: PageData } = $props();
// Estado para el diálogo de crear
let showCreateDialog = $state(false);
// Estado para búsqueda
let searchKey = $state('');
let searchedBroker = $state<CustomsBroker | null>(null);
let searchLoading = $state(false);
let searchError = $state<string | null>(null);
// Sincronizar token de cookies a localStorage al montar el componente
onMount(() => {
if (browser) {
// Función para obtener el valor de una cookie
const getCookie = (name: string): string | null => {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop()?.split(';').shift() || null;
return null;
};
// Verificar si hay token en las cookies
const cookieToken = getCookie('access_token');
const localToken = localStorage.getItem('access_token');
if (cookieToken && cookieToken !== localToken) {
localStorage.setItem('access_token', cookieToken);
}
// También sincronizar refresh_token si existe
const cookieRefreshToken = getCookie('refresh_token');
const localRefreshToken = localStorage.getItem('refresh_token');
if (cookieRefreshToken && cookieRefreshToken !== localRefreshToken) {
localStorage.setItem('refresh_token', cookieRefreshToken);
}
}
});
async function handleSearch() {
if (!searchKey.trim()) {
searchError = 'Por favor ingresa una clave de agente aduanal';
return;
}
searchLoading = true;
searchError = null;
searchedBroker = null;
try {
const response = await customsBrokersApi.get(searchKey.trim());
if (response.error) {
if (response.status === 404) {
searchError = 'No se encontró un agente aduanal con esta clave';
} else if (response.status === 401 || response.status === 403) {
searchError = 'Sesión expirada. Recargando página...';
setTimeout(() => {
window.location.reload();
}, 2000);
} else {
searchError = response.error;
}
return;
}
if (response.data) {
searchedBroker = response.data;
}
} catch (e) {
searchError = 'Error al buscar agente aduanal';
console.error('Error searching broker:', e);
} finally {
searchLoading = false;
}
}
function reloadData() {
// Limpiar búsqueda
searchKey = '';
searchedBroker = null;
searchError = null;
}
function handleCreateClick() {
showCreateDialog = true;
}
function handleSuccess() {
// Recargar datos después de crear/eliminar
reloadData();
}
// Crear columnas con el callback onSuccess
const columns = createColumns(handleSuccess);
// Array para mostrar en la tabla (vacío o con el broker buscado)
const brokers = $derived(searchedBroker ? [searchedBroker] : []);
</script>
<div class="space-y-6">
<!-- Header -->
<div class="flex items-center justify-between">
<div>
<h1 class="text-3xl font-bold tracking-tight">Agentes Aduanales</h1>
<p class="text-muted-foreground">
Gestiona el catálogo de agentes aduanales
</p>
</div>
<Button onclick={handleCreateClick}>
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="mr-2"
>
<path d="M5 12h14" />
<path d="M12 5v14" />
</svg>
Nuevo Agente Aduanal
</Button>
</div>
<!-- Búsqueda -->
<Card.Root>
<Card.Header>
<Card.Title>Buscar Agente Aduanal</Card.Title>
<Card.Description>
Ingresa la clave del agente aduanal para buscarlo
{#if companyStore.activeCompany}
- Compañía: {companyStore.activeCompany.name}
{/if}
</Card.Description>
</Card.Header>
<Card.Content>
<form onsubmit={(e) => { e.preventDefault(); handleSearch(); }} class="space-y-4">
<div class="flex gap-4">
<div class="flex-1 space-y-2">
<Label for="search-key">Clave del Agente Aduanal</Label>
<Input
id="search-key"
bind:value={searchKey}
placeholder="Ej: 12345"
maxlength={5}
disabled={searchLoading}
/>
</div>
<div class="flex items-end gap-2">
<Button type="submit" disabled={searchLoading}>
{#if searchLoading}
<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>
Buscando...
</div>
{:else}
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="mr-2"
>
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
</svg>
Buscar
{/if}
</Button>
{#if searchedBroker}
<Button type="button" variant="outline" onclick={reloadData}>
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="mr-2"
>
<path d="M3 6h18" />
<path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6" />
<path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2" />
</svg>
Limpiar
</Button>
{/if}
</div>
</div>
{#if searchError}
<div class="rounded-lg border border-destructive bg-destructive/10 p-3 text-sm text-destructive">
{searchError}
</div>
{/if}
</form>
</Card.Content>
</Card.Root>
<!-- Resultados -->
{#if searchedBroker}
<Card.Root>
<Card.Header>
<div class="flex items-center justify-between">
<div>
<Card.Title>Resultado de la Búsqueda</Card.Title>
<Card.Description>
Se encontró 1 agente aduanal
</Card.Description>
</div>
</div>
</Card.Header>
<Card.Content>
<DataTable
data={brokers}
{columns}
/>
</Card.Content>
</Card.Root>
{/if}
</div>
<!-- Diálogo de crear -->
<CreateDialog bind:open={showCreateDialog} onSuccess={handleSuccess} />