Se arreglo la actualizacion de clientes y proveedores, ademas de integrarlo en una misma ruta URL

This commit is contained in:
2026-01-02 09:17:32 -06:00
parent a8b8dd95aa
commit b9066880b0
6 changed files with 482 additions and 536 deletions

View File

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

View File

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

View File

@@ -1,103 +1,102 @@
<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 CreateEditDialog from "./create-edit-dialog.svelte"; // <-- Ya no lo necesitas aquí
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"; // <-- Importación importante
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 showEditDialog = $state(false); // <-- Eliminado
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 handleEdit() { showEditDialog = true; } // <-- Eliminado
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

@@ -195,7 +195,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>

View File

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

View File

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