Se puso los modales de catalogos en el formulario de clases

This commit is contained in:
2026-01-07 12:41:03 -06:00
parent c57ddada6e
commit adbaa0fd18
17 changed files with 236 additions and 110 deletions

View File

@@ -1,6 +1,8 @@
import { api } from '$lib/api';
import type { ApiResponse } from '$lib/api';
// --- INTERFACES ---
export interface A76Class {
id: number;
tenant_id: number;
@@ -16,10 +18,31 @@ export interface A76Class {
sub_key: string;
physical_review: number;
iva_exempt_fraction: string;
is_active?: boolean; // Agregado para el switch del formulario
created_at: string;
updated_at: string;
}
// DTO para crear (match con tu formulario)
export interface A76ClassCreate {
company_id: number;
client_id: number;
class_code: string;
description_es?: string | null;
description_en?: string | null;
material_key?: string | null;
unit_of_measure?: string | null;
fraction?: string | null;
us_fraction?: string | null;
sub_key?: string | null;
physical_review?: number | null;
iva_exempt_fraction?: string | null;
is_active?: boolean;
}
// DTO para actualizar (Partial del create)
export interface A76ClassUpdate extends Partial<A76ClassCreate> {}
export interface A76ClassListResponse {
items: A76Class[];
classes?: A76Class[];
@@ -35,18 +58,33 @@ export interface A76ClassListParams {
page_size?: number;
class_code?: string;
description?: string;
q?: string; // Agregado por si usas búsqueda general
}
// --- API OBJECT ---
export const classesApi = {
list: (params: A76ClassListParams): Promise<ApiResponse<A76ClassListResponse>> => {
const query = new URLSearchParams();
Object.entries(params).forEach(([key, value]) => {
if (value) query.append(key, value.toString());
if (value !== undefined && value !== null) query.append(key, value.toString());
});
return api.get(`/v1/a76/classes/?${query.toString()}`);
},
get: (id: number, company_id: number): Promise<ApiResponse<A76Class>> => {
return api.get(`/v1/a76/classes/${id}?company_id=${company_id}`);
},
create: (data: A76ClassCreate, company_id: number): Promise<ApiResponse<A76Class>> => {
return api.post(`/v1/a76/classes/?company_id=${company_id}`, data);
},
update: (id: number, data: A76ClassUpdate, company_id: number): Promise<ApiResponse<A76Class>> => {
return api.put(`/v1/a76/classes/${id}?company_id=${company_id}`, data);
},
delete: (id: number, company_id: number): Promise<ApiResponse<void>> => {
return api.delete(`/v1/a76/classes/${id}?company_id=${company_id}`);
}
};

View File

@@ -1,8 +1,8 @@
<script lang="ts">
import { onMount } from 'svelte';
// import { classesApi } from '$lib/api/dashboard/a76/classes'; // <--- TODO: Descomentar cuando crees el archivo API
import DataTable from '$lib/components/dashboard/classes/data-table.svelte';
import { createColumns } from '$lib/components/dashboard/classes/columns.js';
import DataTable from '$lib/components/dashboard/goods/classes/data-table.svelte';
import { createColumns } from '$lib/components/dashboard/goods/classes/columns.js';
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';

View File

@@ -10,7 +10,10 @@
import { Textarea } from '$lib/components/ui/textarea';
import * as Tabs from '$lib/components/ui/tabs';
import * as Card from '$lib/components/ui/card';
import { ArrowLeft, LoaderCircle, Save } from 'lucide-svelte';
import {
ArrowLeft, LoaderCircle, Save, Search,
User, Package, Scale, BookOpen, Layers, Tag, CheckCircle2
} from 'lucide-svelte';
// Stores y APIs
import { companyStore } from '$lib/stores/company.svelte';
@@ -19,8 +22,18 @@
type A76ClassCreate,
type A76ClassUpdate
} from '$lib/api/dashboard/a76/classes';
import { materialTypesApi, type MaterialType } from "$lib/api/dashboard/refrence_data/material_types";
// APIs para recuperar nombres al editar
import { materialTypesApi } from "$lib/api/dashboard/a76/material-types";
import { clientsProvidersApi } from '$lib/api/dashboard/a76/clients-providers';
// Nota: Asumo que tienes una API para obtener una unidad por código o lista,
// si no, usaremos la descripción del modal.
// --- MODALES IMPORTADOS ---
import MaterialTypeSelectorDialog from '$lib/components/dashboard/goods/modales/material-type-selector-dialog.svelte';
import UnitMeasureSelectorDialog from '$lib/components/dashboard/goods/modales/unit-measure-dialog.svelte';
import ClientSelectorDialog from '$lib/components/dashboard/goods/modales/client-selector-dialog.svelte';
// --- 1. LÓGICA DE IDENTIFICACIÓN ---
let id = $derived($page.params.id === 'new' ? null : Number($page.params.id));
let isEdit = $derived(!!id);
@@ -29,21 +42,27 @@
// --- 2. ESTADOS ---
let loading = $state(false);
let error = $state<string | null>(null);
// Catálogos
let materialTypes = $state<MaterialType[]>([]);
let loadingCatalogs = $state(false);
// Estados de Modales
let showClientModal = $state(false);
let showMaterialModal = $state(false);
let showUnitModal = $state(false);
// Descripciones Visuales (Para que el usuario sepa qué seleccionó)
let selectedClientName = $state("");
let selectedMaterialDesc = $state("");
let selectedUnitDesc = $state("");
// Formulario Inicial
function getEmptyForm(): A76ClassCreate {
return {
company_id: 0,
client_id: 0, // Se llenará manual
client_id: 0,
class_code: '',
description_es: '',
description_en: '',
material_key: '',
unit_of_measure: 'KG',
unit_of_measure: '', // Ahora vacío para obligar selección
fraction: '',
us_fraction: '',
sub_key: '',
@@ -59,28 +78,12 @@
const companyId = companyStore.activeCompany?.id;
if (!companyId) return;
loadingCatalogs = true;
// Ejecutamos las cargas en paralelo
await Promise.all([
loadMaterialTypes(companyId),
id ? loadClassData(id, companyId) : Promise.resolve()
]);
loadingCatalogs = false;
if (id) {
await loadClassData(id, companyId);
}
});
// Carga de Catálogos
async function loadMaterialTypes(companyId: number) {
try {
const response = await materialTypesApi.list(1, 100);
if (response.data) materialTypes = response.data.items;
} catch (e) {
console.error('Error loading material types:', e);
}
}
// Carga del Registro a Editar
// Carga del Registro a Editar y sus descripciones visuales
async function loadClassData(classId: number, companyId: number) {
loading = true;
try {
@@ -107,6 +110,11 @@
physical_review: data.physical_review,
iva_exempt_fraction: data.iva_exempt_fraction
};
// Recuperar descripciones visuales para que no se vean solo códigos
if (data.client_id) await fetchClientName(data.client_id, companyId);
if (data.material_key) await fetchMaterialName(data.material_key);
if (data.unit_of_measure) selectedUnitDesc = data.unit_of_measure; // O buscar descripción si tienes API
}
} catch (e) {
error = "No se pudo cargar la información de la Clase";
@@ -116,6 +124,45 @@
}
}
// --- HELPERS PARA RECUPERAR NOMBRES (Solo visual) ---
async function fetchClientName(clientId: number, companyId: number) {
try {
const res = await clientsProvidersApi.get(clientId, companyId);
const data = (res as any).data || res;
if (data) selectedClientName = data.name;
} catch (e) { console.log("Error visual cliente", e); }
}
async function fetchMaterialName(key: string) {
try {
// Asumiendo que list devuelve items y podemos buscar ahí,
// o si tienes un get(key) mejor.
const res = await materialTypesApi.list(1, 100);
const list = (res as any).data?.items || [];
const found = list.find((m: any) => m.key === key);
if (found) selectedMaterialDesc = found.description;
else selectedMaterialDesc = key;
} catch (e) { console.log("Error visual material", e); }
}
// --- HANDLERS DE SELECCIÓN DE MODALES ---
function handleClientSelect(client: any) {
formData.client_id = client.id;
selectedClientName = client.name;
}
function handleMaterialSelect(item: any) {
formData.material_key = item.key;
selectedMaterialDesc = item.description || item.name;
}
function handleUnitSelect(item: any) {
// Asumiendo que el modal devuelve { code: 'KG', description: 'Kilogramos' }
formData.unit_of_measure = item.code;
selectedUnitDesc = item.description || item.code;
}
// --- 4. GUARDADO ---
async function handleSubmit() {
error = null;
@@ -123,7 +170,7 @@
// Validaciones
if (!activeCompanyId) { error = 'Selecciona una compañía'; return; }
if (!formData.client_id) { error = 'Debes ingresar un ID de Cliente válido'; return; } // Validación manual
if (!formData.client_id) { error = 'Debes seleccionar un Cliente'; return; }
if (!formData.class_code?.trim()) { error = 'La Clave de Clase es requerida'; return; }
if (!formData.fraction?.trim()) { error = 'La Fracción es requerida'; return; }
@@ -154,20 +201,6 @@
loading = false;
}
}
// Opciones estáticas para Unidades
const unitOptions = [
{ value: 'KG', label: 'Kilogramos (KG)' },
{ value: 'LB', label: 'Libras (LB)' },
{ value: 'MT', label: 'Metros (MT)' },
{ value: 'PZ', label: 'Piezas (PZ)' },
{ value: 'LT', label: 'Litros (LT)' },
{ value: 'M3', label: 'Metros Cúbicos (M3)' },
{ value: 'TON', label: 'Toneladas (TON)' },
{ value: 'KGM', label: 'Kilogramo (KGM)' },
{ value: 'H87', label: 'Pieza (H87)' },
{ value: 'EA', label: 'Elemento (EA)' }
];
</script>
<div class="w-full mx-auto max-w-6xl py-6 px-4 space-y-6 pb-48">
@@ -177,11 +210,12 @@
</Button>
<div>
<h1 class="text-2xl font-bold tracking-tight">{title}</h1>
<p class="text-muted-foreground">Gestión de catálogo de clases (Anexo 24).</p>
</div>
</div>
{#if error}
<div class="p-4 rounded-md bg-destructive/10 text-destructive border border-destructive/20 text-sm font-medium">
<div class="p-4 rounded-md bg-destructive/10 text-destructive border border-destructive/20 text-sm font-medium animate-in slide-in-from-top-2">
⚠️ {error}
</div>
{/if}
@@ -193,93 +227,132 @@
<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 md:grid-cols-2 gap-4">
<Tabs.Content value="general" class="space-y-6 pt-4 animate-in fade-in duration-300">
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div class="grid gap-2">
<Label for="class_code" class="required">Clave de Clase</Label>
<Input id="class_code" bind:value={formData.class_code} maxlength={8} placeholder="Ej. ACERO" />
<p class="text-xs text-muted-foreground">Máximo 8 caracteres.</p>
<Input id="class_code" bind:value={formData.class_code} maxlength={8} class="font-mono text-lg" placeholder="Ej. ACERO" />
</div>
<div class="grid gap-2">
<Label for="client_id" class="required">ID Cliente</Label>
<Input
type="number"
id="client_id"
bind:value={formData.client_id}
placeholder="Ingresa el ID del cliente"
/>
<Label for="client_id" class="required">Cliente Asignado</Label>
<div class="flex gap-2">
<div class="relative flex-1">
<User class="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
type="text"
id="client_id"
value={formData.client_id ? `ID: ${formData.client_id}` : ''}
placeholder="Seleccione un cliente..."
class="pl-9 cursor-pointer"
readonly
onclick={() => showClientModal = true}
/>
</div>
<Button variant="outline" size="icon" type="button" onclick={() => showClientModal = true}>
<Search class="h-4 w-4" />
</Button>
</div>
{#if selectedClientName}
<div class="text-xs text-primary font-medium px-1 flex items-center gap-1 animate-in fade-in">
<CheckCircle2 class="h-3 w-3" /> {selectedClientName}
</div>
{/if}
</div>
</div>
<div class="grid gap-2">
<Label for="desc_es">Descripción (Español)</Label>
<Textarea id="desc_es" bind:value={formData.description_es} class="min-h-[80px]" maxlength={500} />
</div>
<div class="grid gap-2">
<Label for="desc_en">Descripción (Inglés)</Label>
<Textarea id="desc_en" bind:value={formData.description_en} class="min-h-[80px]" maxlength={500} />
<div class="grid gap-4 p-4 bg-slate-50 dark:bg-slate-900/30 rounded-lg border">
<h3 class="font-medium text-sm text-muted-foreground flex items-center gap-2">
<BookOpen class="h-4 w-4"/> Descripciones
</h3>
<div class="grid gap-4">
<div class="grid gap-2">
<Label for="desc_es">Descripción (Español)</Label>
<Textarea id="desc_es" bind:value={formData.description_es} class="min-h-[80px]" maxlength={500} />
</div>
<div class="grid gap-2">
<Label for="desc_en">Descripción (Inglés)</Label>
<Textarea id="desc_en" bind:value={formData.description_en} class="min-h-[80px]" maxlength={500} />
</div>
</div>
</div>
</Tabs.Content>
<Tabs.Content value="technical" class="space-y-4 pt-4">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<Tabs.Content value="technical" class="space-y-6 pt-4 animate-in fade-in duration-300">
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div class="grid gap-2">
<Label for="material_key">Tipo de Material</Label>
{#if loadingCatalogs}
<div class="h-9 w-full animate-pulse rounded-md bg-muted"></div>
{:else}
<select
id="material_key"
bind:value={formData.material_key}
class="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
>
<option value="">Sin tipo específico</option>
{#each materialTypes as mt}
<option value={mt.key}>
{mt.key} - {mt.description}
</option>
{/each}
</select>
<div class="flex gap-2">
<div class="relative flex-1">
<Layers class="h-4 w-4 absolute left-3 top-2.5 text-muted-foreground" />
<Input
id="material_key"
value={formData.material_key}
placeholder="Seleccione material..."
class="pl-9 font-mono cursor-pointer"
readonly
onclick={() => showMaterialModal = true}
/>
</div>
<Button variant="outline" size="icon" type="button" onclick={() => showMaterialModal = true}>
<Search class="h-4 w-4" />
</Button>
</div>
{#if selectedMaterialDesc}
<div class="text-xs text-blue-600 font-medium px-1 flex items-center gap-1 animate-in fade-in">
<Tag class="h-3 w-3" /> {selectedMaterialDesc}
</div>
{/if}
</div>
<div class="grid gap-2">
<Label for="uom" class="required">Unidad de Medida</Label>
<select
id="uom"
bind:value={formData.unit_of_measure}
class="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
>
{#each unitOptions as unit}
<option value={unit.value}>{unit.label}</option>
{/each}
</select>
<Label for="uom" class="required">Unidad de Medida (TIGIE)</Label>
<div class="flex gap-2">
<div class="relative flex-1">
<Scale class="h-4 w-4 absolute left-3 top-2.5 text-muted-foreground" />
<Input
id="uom"
value={formData.unit_of_measure}
placeholder="Seleccione unidad..."
class="pl-9 font-mono cursor-pointer"
readonly
onclick={() => showUnitModal = true}
/>
</div>
<Button variant="outline" size="icon" type="button" onclick={() => showUnitModal = true}>
<Search class="h-4 w-4" />
</Button>
</div>
{#if selectedUnitDesc}
<div class="text-xs text-muted-foreground px-1 animate-in fade-in">
{selectedUnitDesc}
</div>
{/if}
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 pt-4 border-t">
<div class="grid gap-2">
<Label for="fraction" class="required">Fracción Arancelaria (MX)</Label>
<Input id="fraction" bind:value={formData.fraction} maxlength={10} placeholder="Ej: 12345678" />
</div>
<div class="grid gap-2">
<Label for="us_fraction" class="required">Fracción Arancelaria (US)</Label>
<Label for="us_fraction">Fracción Arancelaria (US)</Label>
<Input id="us_fraction" bind:value={formData.us_fraction} maxlength={16} placeholder="Ej: 12345678" />
</div>
</div>
</Tabs.Content>
<Tabs.Content value="others" class="space-y-4 pt-4">
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<Tabs.Content value="others" class="space-y-4 pt-4 animate-in fade-in duration-300">
<div class="p-4 border rounded-lg bg-card grid grid-cols-1 md:grid-cols-3 gap-6">
<div class="grid gap-2">
<Label for="sub_key" class="required">Subclave</Label>
<Label for="sub_key">Subclave</Label>
<Input id="sub_key" bind:value={formData.sub_key} maxlength={5} />
</div>
<div class="grid gap-2">
<Label for="iva_exempt" class="required">Fracción Exenta IVA</Label>
<Label for="iva_exempt">Fracción Exenta IVA</Label>
<Input id="iva_exempt" bind:value={formData.iva_exempt_fraction} maxlength={4} />
</div>
@@ -288,7 +361,7 @@
<select
id="phys_rev"
bind:value={formData.physical_review}
class="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
class="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
>
<option value={0}>No</option>
<option value={1}>Sí</option>
@@ -299,9 +372,9 @@
</div>
<Tabs.List class="grid grid-cols-3 fixed bottom-24 left-1/2 -translate-x-1/2 w-[95%] max-w-xl z-40 shadow-2xl bg-background border p-1 rounded-xl">
<Tabs.Trigger value="general">General</Tabs.Trigger>
<Tabs.Trigger value="technical">Clasificación</Tabs.Trigger>
<Tabs.Trigger value="others">Otros</Tabs.Trigger>
<Tabs.Trigger value="general" class="flex gap-2 items-center justify-center"><Package class="h-4 w-4 hidden sm:block"/> General</Tabs.Trigger>
<Tabs.Trigger value="technical" class="flex gap-2 items-center justify-center"><Layers class="h-4 w-4 hidden sm:block"/> Clasificación</Tabs.Trigger>
<Tabs.Trigger value="others" class="flex gap-2 items-center justify-center"><BookOpen class="h-4 w-4 hidden sm:block"/> Otros</Tabs.Trigger>
</Tabs.List>
</Tabs.Root>
</Card.Content>
@@ -312,7 +385,7 @@
<Button type="button" variant="ghost" href="/dashboard/goods/classes" disabled={loading}>
Cancelar
</Button>
<Button type="submit" disabled={loading || loadingCatalogs} class="min-w-[140px]">
<Button type="submit" disabled={loading} class="min-w-[140px]">
{#if loading}
<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
Guardando...
@@ -327,6 +400,21 @@
{/key}
</div>
<ClientSelectorDialog
bind:open={showClientModal}
onSelect={handleClientSelect}
/>
<MaterialTypeSelectorDialog
bind:open={showMaterialModal}
onSelect={handleMaterialSelect}
/>
<UnitMeasureSelectorDialog
bind:open={showUnitModal}
onSelect={handleUnitSelect}
/>
<style>
:global(.required::after) {
content: " *";

View File

@@ -1,8 +1,8 @@
<script lang="ts">
import { onMount } from 'svelte';
import { partsApi, type Part } from '$lib/api/dashboard/a76/parts';
import DataTable from '$lib/components/dashboard/classes/data-table.svelte';
import { createColumns } from '$lib/components/dashboard/parts/columns.js';
import DataTable from '$lib/components/dashboard/goods/classes/data-table.svelte';
import { createColumns } from '$lib/components/dashboard/goods/parts/columns.js';
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';

View File

@@ -28,10 +28,10 @@
import { materialTypesApi } from '$lib/api/dashboard/a76/material-types';
// Modales
import ClientSelectorDialog from '$lib/components/dashboard/parts/client-selector-dialog.svelte';
import ClassSelectorDialog from '$lib/components/dashboard/parts/class-selector-dialog.svelte';
import MaterialTypeSelectorDialog from '$lib/components/dashboard/parts/material-type-selector-dialog.svelte';
import UnitMeasureSelectorDialog from '$lib/components/dashboard/parts/unit-measure-dialog.svelte';
import ClientSelectorDialog from '$lib/components/dashboard/goods/modales/client-selector-dialog.svelte';
import ClassSelectorDialog from '$lib/components/dashboard/goods/parts/class-selector-dialog.svelte';
import MaterialTypeSelectorDialog from '$lib/components/dashboard/goods/modales/material-type-selector-dialog.svelte';
import UnitMeasureSelectorDialog from '$lib/components/dashboard/goods/modales/unit-measure-dialog.svelte';
// --- 1. IDENTIFICACIÓN ---
let id = $derived($page.params.id === 'new' ? null : Number($page.params.id));