Remove embedded page for fixed asset classes from the dashboard
This commit is contained in:
@@ -1,520 +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 { Textarea } from "$lib/components/ui/textarea";
|
||||
import * as Select from "$lib/components/ui/select";
|
||||
import { classesApi, type A76Class, type A76ClassCreate, type A76ClassUpdate } from "$lib/api/dashboard/a76/classes";
|
||||
import { materialTypesApi, type MaterialType } from "$lib/api/dashboard/refrence_data/material_types";
|
||||
import { clientsProvidersApi, type ClientProvider } from "$lib/api/dashboard/a76/clients-providers";
|
||||
import { companyStore } from "$lib/stores/company.svelte";
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
let {
|
||||
open = $bindable(false),
|
||||
item = null,
|
||||
onSuccess
|
||||
}: {
|
||||
open: boolean;
|
||||
item?: A76Class | null;
|
||||
onSuccess?: () => void;
|
||||
} = $props();
|
||||
|
||||
// Determinar si es modo edición o creación
|
||||
const isEdit = $derived(!!item);
|
||||
const title = $derived(isEdit ? "Editar Clase" : "Nueva Clase");
|
||||
|
||||
// Estado del formulario
|
||||
let formData = $state({
|
||||
client_id: item?.client_id || null,
|
||||
class_code: item?.class_code || '',
|
||||
description_es: item?.description_es || '',
|
||||
description_en: item?.description_en || '',
|
||||
material_key: item?.material_key || '',
|
||||
unit_of_measure: item?.unit_of_measure || 'KG',
|
||||
fraction: item?.fraction || '',
|
||||
us_fraction: item?.us_fraction || '',
|
||||
sub_key: item?.sub_key || '',
|
||||
physical_review: item?.physical_review || 0,
|
||||
iva_exempt_fraction: item?.iva_exempt_fraction || ''
|
||||
});
|
||||
|
||||
let loading = $state(false);
|
||||
let error = $state<string | null>(null);
|
||||
let materialTypes = $state<MaterialType[]>([]);
|
||||
let loadingMaterialTypes = $state(false);
|
||||
let clients = $state<ClientProvider[]>([]);
|
||||
let loadingClients = $state(false);
|
||||
|
||||
// Variables para controlar los selects
|
||||
let selectedUnitValue = $state<string>('KG');
|
||||
let selectedMaterialValue = $state<string>('');
|
||||
let selectedPhysicalReviewValue = $state<number>(0);
|
||||
|
||||
// Cargar tipos de materiales y clientes al montar
|
||||
onMount(async () => {
|
||||
const companyId = companyStore.activeCompany?.id;
|
||||
if (!companyId) return;
|
||||
|
||||
// Cargar tipos de materiales
|
||||
loadingMaterialTypes = true;
|
||||
try {
|
||||
const response = await materialTypesApi.list(1, 100);
|
||||
if (response.data) {
|
||||
materialTypes = response.data.items;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error loading material types:', e);
|
||||
} finally {
|
||||
loadingMaterialTypes = false;
|
||||
}
|
||||
|
||||
// Cargar clientes
|
||||
loadingClients = true;
|
||||
try {
|
||||
const response = await clientsProvidersApi.list(companyId, 1, 500);
|
||||
if (response.data) {
|
||||
clients = response.data.items;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error loading clients:', e);
|
||||
} finally {
|
||||
loadingClients = false;
|
||||
}
|
||||
});
|
||||
|
||||
// Resetear formulario cuando cambia el item
|
||||
$effect(() => {
|
||||
if (item) {
|
||||
formData = {
|
||||
client_id: item.client_id,
|
||||
class_code: item.class_code,
|
||||
description_es: item.description_es || '',
|
||||
description_en: item.description_en || '',
|
||||
material_key: item.material_key || '',
|
||||
unit_of_measure: item.unit_of_measure,
|
||||
fraction: item.fraction,
|
||||
us_fraction: item.us_fraction,
|
||||
sub_key: item.sub_key,
|
||||
physical_review: item.physical_review,
|
||||
iva_exempt_fraction: item.iva_exempt_fraction
|
||||
};
|
||||
// Actualizar valores de los selects
|
||||
selectedUnitValue = item.unit_of_measure;
|
||||
selectedMaterialValue = item.material_key || '';
|
||||
selectedPhysicalReviewValue = item.physical_review;
|
||||
} else {
|
||||
// Reset para modo crear
|
||||
formData = {
|
||||
client_id: null,
|
||||
class_code: '',
|
||||
description_es: '',
|
||||
description_en: '',
|
||||
material_key: '',
|
||||
unit_of_measure: 'KG',
|
||||
fraction: '',
|
||||
us_fraction: '',
|
||||
sub_key: '',
|
||||
physical_review: 0,
|
||||
iva_exempt_fraction: ''
|
||||
};
|
||||
// Resetear valores de los selects
|
||||
selectedUnitValue = 'KG';
|
||||
selectedMaterialValue = '';
|
||||
selectedPhysicalReviewValue = 0;
|
||||
}
|
||||
error = null;
|
||||
});
|
||||
|
||||
function handleOpenChange(newOpen: boolean) {
|
||||
open = newOpen;
|
||||
if (!newOpen) {
|
||||
error = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSubmit(e: Event) {
|
||||
e.preventDefault();
|
||||
|
||||
const companyId = companyStore.activeCompany?.id;
|
||||
if (!companyId) {
|
||||
error = 'No hay compañía seleccionada';
|
||||
return;
|
||||
}
|
||||
|
||||
// Validaciones básicas
|
||||
if (!formData.client_id) {
|
||||
error = 'Debes seleccionar un cliente';
|
||||
return;
|
||||
}
|
||||
if (!formData.class_code.trim()) {
|
||||
error = 'El código de clase es requerido';
|
||||
return;
|
||||
}
|
||||
if (!formData.fraction.trim()) {
|
||||
error = 'La fracción es requerida';
|
||||
return;
|
||||
}
|
||||
if (!formData.us_fraction.trim()) {
|
||||
error = 'La fracción US es requerida';
|
||||
return;
|
||||
}
|
||||
if (!formData.sub_key.trim()) {
|
||||
error = 'La subclave es requerida';
|
||||
return;
|
||||
}
|
||||
if (!formData.iva_exempt_fraction.trim()) {
|
||||
error = 'La fracción exenta de IVA es requerida';
|
||||
return;
|
||||
}
|
||||
|
||||
loading = true;
|
||||
error = null;
|
||||
|
||||
try {
|
||||
let response;
|
||||
|
||||
if (isEdit && item) {
|
||||
// Actualizar
|
||||
const updateData: A76ClassUpdate = {
|
||||
client_id: formData.client_id!,
|
||||
class_code: formData.class_code,
|
||||
description_es: formData.description_es || null,
|
||||
description_en: formData.description_en || null,
|
||||
material_key: formData.material_key || null,
|
||||
unit_of_measure: formData.unit_of_measure,
|
||||
fraction: formData.fraction,
|
||||
us_fraction: formData.us_fraction,
|
||||
sub_key: formData.sub_key,
|
||||
physical_review: formData.physical_review,
|
||||
iva_exempt_fraction: formData.iva_exempt_fraction
|
||||
};
|
||||
response = await classesApi.update(item.id, updateData, companyId);
|
||||
} else {
|
||||
// Crear con el client_id seleccionado
|
||||
const createData: A76ClassCreate = {
|
||||
company_id: companyId,
|
||||
client_id: formData.client_id!,
|
||||
class_code: formData.class_code,
|
||||
description_es: formData.description_es || null,
|
||||
description_en: formData.description_en || null,
|
||||
material_key: formData.material_key || null,
|
||||
unit_of_measure: formData.unit_of_measure,
|
||||
fraction: formData.fraction,
|
||||
us_fraction: formData.us_fraction,
|
||||
sub_key: formData.sub_key,
|
||||
physical_review: formData.physical_review,
|
||||
iva_exempt_fraction: formData.iva_exempt_fraction
|
||||
};
|
||||
response = await classesApi.create(createData, companyId);
|
||||
}
|
||||
|
||||
if (response.error) {
|
||||
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 class:', e);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Opciones de unidades de medida (puedes expandir esto)
|
||||
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)' }
|
||||
];
|
||||
|
||||
// Funciones para obtener valores seleccionados
|
||||
function getSelectedMaterialType() {
|
||||
if (!formData.material_key) return null;
|
||||
const found = materialTypes.find(mt => mt.key === formData.material_key);
|
||||
return found ? { value: found.key, label: `${found.key} - ${found.description}` } : null;
|
||||
}
|
||||
|
||||
function getSelectedUnit() {
|
||||
return unitOptions.find(opt => opt.value === formData.unit_of_measure) || unitOptions[0];
|
||||
}
|
||||
|
||||
function getSelectedPhysicalReview() {
|
||||
return { value: formData.physical_review, label: formData.physical_review === 1 ? 'Sí' : 'No' };
|
||||
}
|
||||
</script>
|
||||
|
||||
<Dialog.Root bind:open onOpenChange={handleOpenChange}>
|
||||
<Dialog.Content class="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
|
||||
<Dialog.Header>
|
||||
<Dialog.Title>{title}</Dialog.Title>
|
||||
<Dialog.Description>
|
||||
{isEdit ? 'Modifica los datos de la clase' : 'Completa los datos para crear una nueva clase'}
|
||||
</Dialog.Description>
|
||||
</Dialog.Header>
|
||||
|
||||
<form onsubmit={handleSubmit} class="space-y-4 py-4">
|
||||
<!-- Error Message -->
|
||||
{#if error}
|
||||
<div class="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Información de la compañía (solo lectura) -->
|
||||
{#if companyStore.activeCompany}
|
||||
<div class="rounded-md bg-blue-50 border border-blue-200 p-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<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="text-blue-600"
|
||||
>
|
||||
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
|
||||
<polyline points="9 22 9 12 15 12 15 22" />
|
||||
</svg>
|
||||
<div>
|
||||
<p class="text-sm font-medium text-blue-900">
|
||||
{companyStore.activeCompany.name}
|
||||
</p>
|
||||
<p class="text-xs text-blue-600">
|
||||
ID: {companyStore.activeCompany.id}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Cliente -->
|
||||
<div class="space-y-2">
|
||||
<Label for="client_id" class="required">Cliente</Label>
|
||||
{#if loadingClients}
|
||||
<div class="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<div class="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
|
||||
Cargando clientes...
|
||||
</div>
|
||||
{:else if clients.length > 0}
|
||||
<select
|
||||
bind:value={formData.client_id}
|
||||
disabled={loading}
|
||||
class="border-input bg-background selection:bg-primary dark:bg-input/30 selection:text-primary-foreground ring-offset-background placeholder:text-muted-foreground shadow-xs flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base outline-none transition-[color,box-shadow] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive"
|
||||
>
|
||||
<option value="">Selecciona un cliente</option>
|
||||
{#each clients as client}
|
||||
<option value={client.id}>
|
||||
{client.name} ({client.rfc})
|
||||
</option>
|
||||
{/each}
|
||||
</select>
|
||||
{:else}
|
||||
<div class="text-sm text-muted-foreground">
|
||||
No hay clientes disponibles
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Código de Clase -->
|
||||
<div class="space-y-2">
|
||||
<Label for="class_code" class="required">Código de Clase</Label>
|
||||
<Input
|
||||
id="class_code"
|
||||
bind:value={formData.class_code}
|
||||
placeholder="Ej: A76"
|
||||
required
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Descripciones -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div class="space-y-2">
|
||||
<Label for="description_es">Descripción (Español)</Label>
|
||||
<Textarea
|
||||
id="description_es"
|
||||
bind:value={formData.description_es}
|
||||
placeholder="Descripción en español"
|
||||
disabled={loading}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<Label for="description_en">Descripción (Inglés)</Label>
|
||||
<Textarea
|
||||
id="description_en"
|
||||
bind:value={formData.description_en}
|
||||
placeholder="English description"
|
||||
disabled={loading}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Material Type -->
|
||||
<div class="space-y-2">
|
||||
<Label for="material_key">Tipo de Material</Label>
|
||||
{#if loadingMaterialTypes}
|
||||
<div class="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<div class="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
|
||||
Cargando tipos de material...
|
||||
</div>
|
||||
{:else if materialTypes.length > 0}
|
||||
<select
|
||||
bind:value={formData.material_key}
|
||||
disabled={loading}
|
||||
class="border-input bg-background selection:bg-primary dark:bg-input/30 selection:text-primary-foreground ring-offset-background placeholder:text-muted-foreground shadow-xs flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base outline-none transition-[color,box-shadow] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive"
|
||||
>
|
||||
<option value="">Sin tipo de material</option>
|
||||
{#each materialTypes as materialType}
|
||||
<option value={materialType.key}>
|
||||
{materialType.key} - {materialType.description}
|
||||
</option>
|
||||
{/each}
|
||||
</select>
|
||||
{:else}
|
||||
<Input
|
||||
id="material_key"
|
||||
bind:value={formData.material_key}
|
||||
placeholder="No hay tipos de material disponibles"
|
||||
disabled={true}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Fracciones -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div class="space-y-2">
|
||||
<Label for="fraction" class="required">Fracción</Label>
|
||||
<Input
|
||||
id="fraction"
|
||||
bind:value={formData.fraction}
|
||||
placeholder="Ej: 123123"
|
||||
required
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<Label for="us_fraction" class="required">Fracción US</Label>
|
||||
<Input
|
||||
id="us_fraction"
|
||||
bind:value={formData.us_fraction}
|
||||
placeholder="Ej: 123123"
|
||||
required
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Sub Key e IVA Exempt -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div class="space-y-2">
|
||||
<Label for="sub_key" class="required">Subclave</Label>
|
||||
<Input
|
||||
id="sub_key"
|
||||
bind:value={formData.sub_key}
|
||||
placeholder="Ej: 123"
|
||||
required
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<Label for="iva_exempt_fraction" class="required">Fracción Exenta IVA</Label>
|
||||
<Input
|
||||
id="iva_exempt_fraction"
|
||||
bind:value={formData.iva_exempt_fraction}
|
||||
placeholder="Ej: 123"
|
||||
required
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Unidad de Medida -->
|
||||
<div class="space-y-2">
|
||||
<Label for="unit_of_measure" class="required">Unidad de Medida</Label>
|
||||
<select
|
||||
bind:value={formData.unit_of_measure}
|
||||
disabled={loading}
|
||||
class="border-input bg-background selection:bg-primary dark:bg-input/30 selection:text-primary-foreground ring-offset-background placeholder:text-muted-foreground shadow-xs flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base outline-none transition-[color,box-shadow] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive"
|
||||
>
|
||||
{#each unitOptions as unit}
|
||||
<option value={unit.value}>{unit.label}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Revisión Física -->
|
||||
<div class="space-y-2">
|
||||
<Label for="physical_review">Revisión Física</Label>
|
||||
<select
|
||||
bind:value={formData.physical_review}
|
||||
disabled={loading}
|
||||
class="border-input bg-background selection:bg-primary dark:bg-input/30 selection:text-primary-foreground ring-offset-background placeholder:text-muted-foreground shadow-xs flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base outline-none transition-[color,box-shadow] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive"
|
||||
>
|
||||
<option value={0}>No</option>
|
||||
<option value={1}>Sí</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<Dialog.Footer>
|
||||
<Button type="button" variant="outline" onclick={() => (open = false)} disabled={loading}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{#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>
|
||||
Guardando...
|
||||
{:else}
|
||||
{isEdit ? 'Actualizar' : 'Crear'}
|
||||
{/if}
|
||||
</Button>
|
||||
</Dialog.Footer>
|
||||
</form>
|
||||
</Dialog.Content>
|
||||
</Dialog.Root>
|
||||
|
||||
<style>
|
||||
:global(.required::after) {
|
||||
content: " *";
|
||||
color: hsl(var(--destructive));
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,178 +0,0 @@
|
||||
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 { A76Class } from "$lib/api/dashboard/a76/classes";
|
||||
|
||||
/**
|
||||
* Formatea una fecha
|
||||
*/
|
||||
function formatDate(date?: string | null): string {
|
||||
if (!date) return '-';
|
||||
return new Date(date).toLocaleDateString('es-MX', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtiene el color del badge según el tipo de revisión física
|
||||
*/
|
||||
function getReviewColor(physicalReview: number): string {
|
||||
return physicalReview === 1
|
||||
? 'bg-yellow-100 text-yellow-800'
|
||||
: 'bg-green-100 text-green-800';
|
||||
}
|
||||
|
||||
export function createColumns(onSuccess?: () => void): ColumnDef<A76Class>[] {
|
||||
return [
|
||||
{
|
||||
accessorKey: "id",
|
||||
header: "ID",
|
||||
cell: ({ row }) => {
|
||||
const idSnippet = createRawSnippet<[{ id: number }]>((getId) => {
|
||||
const { id } = getId();
|
||||
return {
|
||||
render: () =>
|
||||
`<div class="font-medium">#${id}</div>`
|
||||
};
|
||||
});
|
||||
return renderSnippet(idSnippet, { id: row.original.id });
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "class_code",
|
||||
header: "Código de Clase",
|
||||
cell: ({ row }) => {
|
||||
const codeSnippet = createRawSnippet<[{ code: string }]>((getCode) => {
|
||||
const { code } = getCode();
|
||||
return {
|
||||
render: () =>
|
||||
`<code class="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold">${code}</code>`
|
||||
};
|
||||
});
|
||||
return renderSnippet(codeSnippet, { code: row.original.class_code });
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "description_es",
|
||||
header: "Descripción",
|
||||
cell: ({ row }) => {
|
||||
const description = row.original.description_es || row.original.description_en || '-';
|
||||
const descSnippet = createRawSnippet<[{ desc: string }]>((getDesc) => {
|
||||
const { desc } = getDesc();
|
||||
return {
|
||||
render: () =>
|
||||
`<div class="max-w-xs truncate" title="${desc}">${desc}</div>`
|
||||
};
|
||||
});
|
||||
return renderSnippet(descSnippet, { desc: description });
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "fraction",
|
||||
header: "Fracción",
|
||||
cell: ({ row }) => {
|
||||
const fractionSnippet = createRawSnippet<[{ fraction: string }]>((getFraction) => {
|
||||
const { fraction } = getFraction();
|
||||
return {
|
||||
render: () =>
|
||||
`<div class="font-mono text-sm">${fraction}</div>`
|
||||
};
|
||||
});
|
||||
return renderSnippet(fractionSnippet, { fraction: row.original.fraction });
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "us_fraction",
|
||||
header: "Fracción US",
|
||||
cell: ({ row }) => {
|
||||
const usFractionSnippet = createRawSnippet<[{ usFraction: string }]>((getUsFraction) => {
|
||||
const { usFraction } = getUsFraction();
|
||||
return {
|
||||
render: () =>
|
||||
`<div class="font-mono text-sm">${usFraction}</div>`
|
||||
};
|
||||
});
|
||||
return renderSnippet(usFractionSnippet, { usFraction: row.original.us_fraction });
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "unit_of_measure",
|
||||
header: "Unidad",
|
||||
cell: ({ row }) => {
|
||||
const unitSnippet = createRawSnippet<[{ unit: string }]>((getUnit) => {
|
||||
const { unit } = getUnit();
|
||||
return {
|
||||
render: () =>
|
||||
`<span class="inline-flex items-center rounded-full bg-blue-100 text-blue-800 px-2.5 py-0.5 text-xs font-medium">
|
||||
${unit}
|
||||
</span>`
|
||||
};
|
||||
});
|
||||
return renderSnippet(unitSnippet, { unit: row.original.unit_of_measure });
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "physical_review",
|
||||
header: "Rev. Física",
|
||||
cell: ({ row }) => {
|
||||
const review = row.original.physical_review;
|
||||
const colorClass = getReviewColor(review);
|
||||
const label = review === 1 ? 'Sí' : 'No';
|
||||
|
||||
const reviewSnippet = createRawSnippet<[{ label: string; colorClass: string }]>((getReview) => {
|
||||
const { label, colorClass } = getReview();
|
||||
return {
|
||||
render: () =>
|
||||
`<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${colorClass}">
|
||||
${label}
|
||||
</span>`
|
||||
};
|
||||
});
|
||||
return renderSnippet(reviewSnippet, { label, colorClass });
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "client_id",
|
||||
header: "Cliente",
|
||||
cell: ({ row }) => {
|
||||
const clientSnippet = createRawSnippet<[{ clientId: number }]>((getClient) => {
|
||||
const { clientId } = getClient();
|
||||
return {
|
||||
render: () =>
|
||||
`<div class="text-sm">Cliente #${clientId}</div>`
|
||||
};
|
||||
});
|
||||
return renderSnippet(clientSnippet, { clientId: row.original.client_id });
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: "Fecha de Creación",
|
||||
cell: ({ row }) => {
|
||||
const dateSnippet = createRawSnippet<[{ date: string }]>((getDate) => {
|
||||
const { date } = getDate();
|
||||
return {
|
||||
render: () =>
|
||||
`<div class="text-sm text-muted-foreground">${date}</div>`
|
||||
};
|
||||
});
|
||||
return renderSnippet(dateSnippet, { date: formatDate(row.original.created_at) });
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "Acciones",
|
||||
cell: ({ row }) => {
|
||||
return renderComponent(DataTableActions, { item: row.original, onSuccess });
|
||||
}
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
// Mantener compatibilidad hacia atrás
|
||||
export const columns = createColumns();
|
||||
@@ -1,109 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { Button } from "$lib/components/ui/button";
|
||||
import * as DropdownMenu from "$lib/components/ui/dropdown-menu";
|
||||
import { classesApi, type A76Class } from "$lib/api/dashboard/a76/classes";
|
||||
import { companyStore } from "$lib/stores/company.svelte";
|
||||
import { EllipsisVertical, Pencil, LoaderCircle, Trash2 } from 'lucide-svelte';
|
||||
import CreateEditDialog from "./create-edit-dialog.svelte";
|
||||
import { goto } from "$app/navigation";
|
||||
|
||||
let {
|
||||
item,
|
||||
onSuccess
|
||||
}: {
|
||||
item: A76Class;
|
||||
onSuccess?: () => void;
|
||||
} = $props();
|
||||
|
||||
let loading = $state(false);
|
||||
let error = $state<string | null>(null);
|
||||
let dialogOpen = $state(false);
|
||||
let selectedItem = $state<A76Class | null>(null);
|
||||
|
||||
async function handleDelete() {
|
||||
if (!confirm(`¿Estás seguro de eliminar la clase "${item.class_code}"?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const companyId = companyStore.activeCompany?.id;
|
||||
if (!companyId) {
|
||||
alert('No hay compañía seleccionada');
|
||||
return;
|
||||
}
|
||||
|
||||
loading = true;
|
||||
error = null;
|
||||
|
||||
try {
|
||||
const response = await classesApi.delete(item.id, companyId);
|
||||
|
||||
if (response.error) {
|
||||
if (response.status === 401) {
|
||||
error = 'Sesión expirada. Recargando página...';
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 1500);
|
||||
} else {
|
||||
error = response.error;
|
||||
alert(`Error al eliminar: ${response.error}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Éxito
|
||||
if (onSuccess) {
|
||||
onSuccess();
|
||||
}
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : "Error al eliminar";
|
||||
alert(`Error: ${error}`);
|
||||
console.error("Error deleting:", e);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleEdit() {
|
||||
selectedItem = item;
|
||||
dialogOpen = true;
|
||||
}
|
||||
|
||||
function handleDialogSuccess() {
|
||||
dialogOpen = false;
|
||||
selectedItem = null;
|
||||
if (onSuccess) {
|
||||
onSuccess();
|
||||
}
|
||||
}
|
||||
</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>
|
||||
<EllipsisVertical size={16} />
|
||||
</Button>
|
||||
{/snippet}
|
||||
</DropdownMenu.Trigger>
|
||||
<DropdownMenu.Content align="end" class="w-[160px]">
|
||||
<DropdownMenu.Label>Acciones</DropdownMenu.Label>
|
||||
<DropdownMenu.Separator />
|
||||
<DropdownMenu.Item onclick={() => { goto(`/dashboard/goods/classes/edit/${item.id}`); }} >
|
||||
<Pencil size={16} class="mr-2" />
|
||||
Editar
|
||||
</DropdownMenu.Item>
|
||||
<DropdownMenu.Separator />
|
||||
<DropdownMenu.Item onclick={handleDelete} class="text-destructive" disabled={loading}>
|
||||
{#if loading}
|
||||
<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
|
||||
{:else}
|
||||
<Trash2 size={16} class="mr-2" />
|
||||
{/if}
|
||||
Eliminar
|
||||
</DropdownMenu.Item>
|
||||
</DropdownMenu.Content>
|
||||
</DropdownMenu.Root>
|
||||
|
||||
<!-- Dialog de edición -->
|
||||
<CreateEditDialog bind:open={dialogOpen} item={selectedItem} onSuccess={handleDialogSuccess} />
|
||||
@@ -1,123 +0,0 @@
|
||||
<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[];
|
||||
loading: boolean;
|
||||
hasMore: boolean;
|
||||
loadMore: () => void;
|
||||
};
|
||||
|
||||
let {
|
||||
data,
|
||||
columns,
|
||||
loading,
|
||||
hasMore,
|
||||
loadMore
|
||||
}: DataTableProps<TData, TValue> = $props();
|
||||
|
||||
const table = createSvelteTable({
|
||||
get data() {
|
||||
return data;
|
||||
},
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel()
|
||||
});
|
||||
|
||||
let scrollContainer = $state<HTMLDivElement>();
|
||||
let loadingTrigger = $state<HTMLDivElement>();
|
||||
|
||||
// Intersection Observer para detectar cuando el usuario llega al final
|
||||
onMount(() => {
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
const [entry] = entries;
|
||||
if (entry.isIntersecting && hasMore && !loading) {
|
||||
loadMore();
|
||||
}
|
||||
},
|
||||
{
|
||||
root: scrollContainer,
|
||||
threshold: 0.1
|
||||
}
|
||||
);
|
||||
|
||||
if (loadingTrigger) {
|
||||
observer.observe(loadingTrigger);
|
||||
}
|
||||
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="w-full">
|
||||
<div class="rounded-md border max-h-[600px] overflow-y-auto" bind:this={scrollContainer}>
|
||||
<Table.Root>
|
||||
<Table.Header class="sticky top-0 bg-background z-10">
|
||||
{#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}
|
||||
|
||||
<!-- Loading Trigger - Se activa cuando es visible -->
|
||||
{#if hasMore}
|
||||
<Table.Row>
|
||||
<Table.Cell colspan={columns.length} class="h-20 text-center">
|
||||
<div bind:this={loadingTrigger}>
|
||||
{#if loading}
|
||||
<div class="flex items-center justify-center gap-2">
|
||||
<div class="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
|
||||
<span class="text-muted-foreground text-sm">Cargando más...</span>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="text-muted-foreground text-sm">
|
||||
Desplázate para cargar más
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</Table.Cell>
|
||||
</Table.Row>
|
||||
{/if}
|
||||
</Table.Body>
|
||||
</Table.Root>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,914 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import { Input } from '$lib/components/ui/input';
|
||||
import { Label } from '$lib/components/ui/label';
|
||||
import * as Dialog from '$lib/components/ui/dialog';
|
||||
import FixedAssetClassForm from '$lib/components/dashboard/classes/forms/FixedAssetClassForm.svelte';
|
||||
import { Folder, Save, Plus, RefreshCw } from 'lucide-svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { classesApi, type A76Class } from '$lib/api/dashboard/a76/classes';
|
||||
import { faClassesApi, type FAClass } from '$lib/api/dashboard/a24/fa_classes';
|
||||
import { companyStore } from '$lib/stores/company.svelte';
|
||||
import { getToken } from '$lib/auth';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
// Tipo extendido que combina A76Class y FAClass
|
||||
interface FixedAssetClassExtended extends A76Class {
|
||||
fa_class_id?: number;
|
||||
depreciation_rate?: number | null;
|
||||
fda_code?: string | null;
|
||||
class_enabled?: boolean | null;
|
||||
}
|
||||
|
||||
// Estado de la lista de clases
|
||||
let classes = $state<FixedAssetClassExtended[]>([]);
|
||||
let selectedClass = $state<FixedAssetClassExtended | null>(null);
|
||||
let isLoading = $state(false);
|
||||
let searchTerm = $state('');
|
||||
let searchDescription = $state('');
|
||||
let searchType = $state('');
|
||||
let searchFraction = $state('');
|
||||
let showInsertDialog = $state(false);
|
||||
let showDeleteDialog = $state(false);
|
||||
let validationError = $state<string>('');
|
||||
let isSaving = $state(false);
|
||||
|
||||
// Estado del formulario
|
||||
let formData = $state({
|
||||
class_code: '',
|
||||
description_es: '',
|
||||
description_en: '',
|
||||
material_key: '',
|
||||
unit_of_measure: '',
|
||||
fraction: '',
|
||||
us_fraction: '',
|
||||
unit_measure_trade: '',
|
||||
bom: ''
|
||||
});
|
||||
|
||||
// Clases filtradas según búsqueda
|
||||
const filteredClasses = $derived(
|
||||
classes.filter((c) => {
|
||||
// Filtro por código de clase
|
||||
const matchesCode = !searchTerm ||
|
||||
c.class_code.toLowerCase().includes(searchTerm.toLowerCase());
|
||||
|
||||
// Filtro por descripción (español o inglés)
|
||||
const matchesDescription = !searchDescription ||
|
||||
(c.description_es?.toLowerCase().includes(searchDescription.toLowerCase()) ?? false) ||
|
||||
(c.description_en?.toLowerCase().includes(searchDescription.toLowerCase()) ?? false);
|
||||
|
||||
// Filtro por tipo de material
|
||||
const matchesType = !searchType ||
|
||||
(c.material_key?.toLowerCase().includes(searchType.toLowerCase()) ?? false);
|
||||
|
||||
// Filtro por fracción arancelaria
|
||||
const matchesFraction = !searchFraction ||
|
||||
(c.fraction?.toLowerCase().includes(searchFraction.toLowerCase()) ?? false);
|
||||
|
||||
return matchesCode && matchesDescription && matchesType && matchesFraction;
|
||||
})
|
||||
);
|
||||
|
||||
// Reactively load classes when company changes
|
||||
$effect(() => {
|
||||
const companyId = companyStore.activeCompany?.id;
|
||||
if (companyId) {
|
||||
loadClasses();
|
||||
}
|
||||
});
|
||||
|
||||
async function loadClasses() {
|
||||
const companyId = companyStore.activeCompany?.id;
|
||||
if (!companyId) {
|
||||
console.log('No company selected, skipping load');
|
||||
return;
|
||||
}
|
||||
|
||||
isLoading = true;
|
||||
try {
|
||||
console.log('Cargando clases para company:', companyId);
|
||||
const response = await classesApi.list({
|
||||
company_id: companyId,
|
||||
page: 1,
|
||||
page_size: 1000
|
||||
});
|
||||
|
||||
if (!response.data) return;
|
||||
|
||||
// Para cada clase base, intentar cargar sus datos de activo fijo
|
||||
const classesWithFA = await Promise.all(
|
||||
response.data.items.map(async (baseClass) => {
|
||||
try {
|
||||
const faResponse = await faClassesApi.list({
|
||||
company_id: companyId,
|
||||
class_id: baseClass.id,
|
||||
page: 1,
|
||||
page_size: 1
|
||||
});
|
||||
|
||||
const faData = faResponse.data?.items[0];
|
||||
|
||||
return {
|
||||
...baseClass,
|
||||
fa_class_id: faData?.id,
|
||||
depreciation_rate: faData?.depreciation_rate,
|
||||
fda_code: faData?.fda_code,
|
||||
class_enabled: faData?.class_enabled
|
||||
} as FixedAssetClassExtended;
|
||||
} catch (error) {
|
||||
// Si no tiene FA class, solo retornar la clase base
|
||||
return baseClass as FixedAssetClassExtended;
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
classes = classesWithFA;
|
||||
console.log('Clases cargadas:', classes.length);
|
||||
} catch (error) {
|
||||
console.error('Error cargando clases:', error);
|
||||
toast.error('Error al cargar las clases de activo fijo');
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function selectClass(cls: A76Class) {
|
||||
selectedClass = cls;
|
||||
formData = {
|
||||
class_code: cls.class_code,
|
||||
description_es: cls.description_es || '',
|
||||
description_en: cls.description_en || '',
|
||||
material_key: cls.material_key || '',
|
||||
unit_of_measure: cls.unit_of_measure || '',
|
||||
fraction: cls.fraction || '',
|
||||
us_fraction: cls.us_fraction || '',
|
||||
unit_measure_trade: '',
|
||||
bom: ''
|
||||
};
|
||||
}
|
||||
|
||||
async function saveFixedAssetClass(formData: any) {
|
||||
console.log('=== INICIO saveFixedAssetClass ===');
|
||||
const companyId = companyStore.activeCompany?.id;
|
||||
const clientId = 2; // Cliente demo creado en la base de datos
|
||||
|
||||
// CAMBIO: Usar $state.snapshot para obtener una copia real, no reactiva
|
||||
const data = $state.snapshot(formData);
|
||||
console.log('saveFixedAssetClass called with data:', data);
|
||||
|
||||
if (!companyId) {
|
||||
toast.error('No hay empresa seleccionada');
|
||||
throw new Error('No hay empresa seleccionada');
|
||||
}
|
||||
|
||||
// Validar campos obligatorios
|
||||
const missingFields: string[] = [];
|
||||
|
||||
if (!data.class_code?.trim()) {
|
||||
missingFields.push('Código de clase');
|
||||
}
|
||||
if (!data.description_es?.trim()) {
|
||||
missingFields.push('Descripción en español');
|
||||
}
|
||||
if (!data.material_key?.trim()) {
|
||||
missingFields.push('Tipo de activo fijo');
|
||||
}
|
||||
if (!data.unit_of_measure?.trim()) {
|
||||
missingFields.push('Unidad de medida comercial');
|
||||
}
|
||||
if (!data.fraction?.trim()) {
|
||||
missingFields.push('Fracción arancelaria');
|
||||
}
|
||||
|
||||
if (missingFields.length > 0) {
|
||||
const fieldsList = missingFields.join(', ');
|
||||
validationError = `Debe completar los siguientes campos obligatorios: ${fieldsList}`;
|
||||
toast.error(validationError, {
|
||||
duration: 8000
|
||||
});
|
||||
throw new Error(`Campos obligatorios faltantes: ${fieldsList}`);
|
||||
}
|
||||
|
||||
// Limpiar error de validación si todo está bien
|
||||
validationError = '';
|
||||
|
||||
try {
|
||||
// Usar el endpoint combinado /fa que crea ambos registros en una transacción
|
||||
const token = await getToken();
|
||||
if (!token) {
|
||||
toast.error('No estás autenticado');
|
||||
throw new Error('No estás autenticado');
|
||||
}
|
||||
|
||||
const payload = {
|
||||
client_id: clientId,
|
||||
class_code: data.class_code.trim(),
|
||||
description_es: data.description_es.trim(),
|
||||
description_en: data.description_en?.trim() || '',
|
||||
material_key: data.material_key.trim(),
|
||||
unit_of_measure: data.unit_of_measure.trim(),
|
||||
fraction: data.fraction.trim(),
|
||||
us_fraction: data.us_fraction?.trim() || '',
|
||||
sub_key: data.sub_key || '',
|
||||
physical_review: data.physical_review ? 1 : 0,
|
||||
iva_exempt_fraction: data.iva_exempt_fraction || '',
|
||||
// FA-specific fields
|
||||
import_tariff_code: data.import_tariff_code || null,
|
||||
import_tariff_type: data.import_tariff_type || null,
|
||||
export_tariff_code: data.export_tariff_code || null,
|
||||
export_tariff_type: data.export_tariff_type || null,
|
||||
depreciation_rate: data.annual_depreciation_rate || null,
|
||||
fda_code: data.fda_key || null,
|
||||
eccn_code: data.eccn_code || null,
|
||||
class_enabled: true
|
||||
};
|
||||
|
||||
console.log('Sending payload:', payload);
|
||||
|
||||
const response = await fetch(`http://localhost:8000/api/v1/a76/classes/fa?company_id=${companyId}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json();
|
||||
console.error('Server error:', error);
|
||||
|
||||
// Manejar diferentes formatos de error
|
||||
let errorMessage = 'Error al crear la clase';
|
||||
let isDuplicateError = false;
|
||||
|
||||
if (error.detail) {
|
||||
if (Array.isArray(error.detail)) {
|
||||
// Si detail es un array (errores de validación de Pydantic)
|
||||
errorMessage = error.detail.map((e: any) =>
|
||||
`${e.loc ? e.loc.join(' → ') : ''}: ${e.msg || e}`
|
||||
).join(', ');
|
||||
} else if (typeof error.detail === 'string') {
|
||||
errorMessage = error.detail;
|
||||
// Detectar si es un error de código duplicado
|
||||
if (errorMessage.includes('código') && errorMessage.includes('ya está en uso')) {
|
||||
isDuplicateError = true;
|
||||
}
|
||||
} else {
|
||||
errorMessage = JSON.stringify(error.detail);
|
||||
}
|
||||
}
|
||||
|
||||
// Mensaje más específico para errores de duplicado
|
||||
console.log('isDuplicateError:', isDuplicateError);
|
||||
if (isDuplicateError) {
|
||||
validationError = `⚠️ ${errorMessage}\n\nPor favor, cambie el código de clase a uno diferente.`;
|
||||
} else {
|
||||
validationError = `⚠️ ${errorMessage}`;
|
||||
}
|
||||
|
||||
console.log('MENSAJE ASIGNADO (save):', validationError);
|
||||
toast.error(errorMessage, { duration: 8000 });
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
const responseData = await response.json();
|
||||
validationError = '';
|
||||
toast.success('✅ Clase de activo fijo creada correctamente');
|
||||
return responseData;
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('Error saving fixed asset class:', error);
|
||||
// El toast ya se mostró arriba, solo re-lanzar el error
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function updateFixedAssetClass(formData: any) {
|
||||
console.log('=== INICIO updateFixedAssetClass ===');
|
||||
const companyId = companyStore.activeCompany?.id;
|
||||
|
||||
// CAMBIO 1: Usar $state.snapshot para obtener una copia real, no reactiva
|
||||
// Esto garantiza que aunque el hijo borre el formulario, 'data' mantenga los valores
|
||||
const data = $state.snapshot(formData);
|
||||
|
||||
console.log('updateFixedAssetClass called with snapshot data:', data);
|
||||
|
||||
if (!companyId || !selectedClass) {
|
||||
toast.error('No hay empresa o clase seleccionada');
|
||||
return;
|
||||
}
|
||||
|
||||
// CAMBIO 2: Validar sobre 'data' (la copia muerta)
|
||||
const missingFields: string[] = [];
|
||||
if (!data.class_code?.trim()) missingFields.push('Código de clase');
|
||||
if (!data.description_es?.trim()) missingFields.push('Descripción en español');
|
||||
if (!data.material_key?.trim()) missingFields.push('Tipo de activo fijo');
|
||||
if (!data.unit_of_measure?.trim()) missingFields.push('Unidad de medida comercial');
|
||||
if (!data.fraction?.trim()) missingFields.push('Fracción arancelaria');
|
||||
|
||||
if (missingFields.length > 0) {
|
||||
const errorMsg = `Campos obligatorios faltantes: ${missingFields.join(', ')}`;
|
||||
validationError = `⚠️ ${errorMsg}`;
|
||||
toast.error(errorMsg);
|
||||
// Lanzamos el error para que el 'onSave' del Dialog no cierre la ventana
|
||||
throw new Error(errorMsg);
|
||||
}
|
||||
|
||||
validationError = '';
|
||||
|
||||
try {
|
||||
// CAMBIO 3: Usar siempre 'data' para los payloads
|
||||
const a76Response = await classesApi.update(selectedClass.id, {
|
||||
class_code: data.class_code.trim(),
|
||||
description_es: data.description_es.trim(),
|
||||
description_en: data.description_en?.trim() || '',
|
||||
material_key: data.material_key.trim(),
|
||||
unit_of_measure: data.unit_of_measure.trim(),
|
||||
fraction: data.fraction.trim(),
|
||||
us_fraction: data.us_fraction || '',
|
||||
physical_review: data.physical_review ? 1 : 0,
|
||||
iva_exempt_fraction: data.iva_exempt_fraction || ''
|
||||
}, companyId);
|
||||
|
||||
if (selectedClass.fa_class_id) {
|
||||
await faClassesApi.update(selectedClass.fa_class_id, {
|
||||
depreciation_rate: data.annual_depreciation_rate || null,
|
||||
fda_code: data.fda_key || null
|
||||
}, companyId);
|
||||
} else {
|
||||
await faClassesApi.create({
|
||||
class_id: selectedClass.id,
|
||||
depreciation_rate: data.annual_depreciation_rate || null,
|
||||
fda_code: data.fda_key || null,
|
||||
class_enabled: true
|
||||
}, companyId);
|
||||
}
|
||||
|
||||
toast.success('Clase actualizada correctamente');
|
||||
return { a76: a76Response.data };
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('Error updating fixed asset class:', error);
|
||||
console.error('Error response:', error?.response);
|
||||
console.error('Error response data:', error?.response?.data);
|
||||
console.error('Error response detail:', error?.response?.data?.detail);
|
||||
console.error('Error type:', typeof error?.response?.data?.detail);
|
||||
|
||||
let errorMessage = 'Error al actualizar la clase';
|
||||
let isDuplicateError = false;
|
||||
|
||||
// Extract error message from response
|
||||
if (error?.response?.data?.detail) {
|
||||
if (Array.isArray(error.response.data.detail)) {
|
||||
errorMessage = error.response.data.detail.map((e: any) =>
|
||||
`${e.loc ? e.loc.join(' → ') : ''}: ${e.msg || e}`
|
||||
).join(', ');
|
||||
} else if (typeof error.response.data.detail === 'string') {
|
||||
errorMessage = error.response.data.detail;
|
||||
// Detectar si es un error de código duplicado
|
||||
if (errorMessage.includes('código') && errorMessage.includes('ya está en uso')) {
|
||||
isDuplicateError = true;
|
||||
}
|
||||
} else {
|
||||
errorMessage = JSON.stringify(error.response.data.detail);
|
||||
}
|
||||
} else if (error?.message) {
|
||||
errorMessage = error.message;
|
||||
}
|
||||
|
||||
console.error('Final error message:', errorMessage);
|
||||
console.error('Is duplicate error:', isDuplicateError);
|
||||
|
||||
// Mensaje más específico para errores de duplicado
|
||||
console.log('isDuplicateError:', isDuplicateError);
|
||||
if (isDuplicateError) {
|
||||
validationError = `⚠️ ${errorMessage}\n\nPor favor, cambie el código de clase a uno diferente.`;
|
||||
} else {
|
||||
validationError = `⚠️ ${errorMessage}`;
|
||||
}
|
||||
|
||||
console.log('MENSAJE ASIGNADO (update):', validationError);
|
||||
toast.error(errorMessage, { duration: 8000 });
|
||||
|
||||
console.error('Toast shown, about to throw error');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
function handleNew() {
|
||||
selectedClass = null;
|
||||
formData = {
|
||||
class_code: '',
|
||||
description_es: '',
|
||||
description_en: '',
|
||||
material_key: '',
|
||||
unit_of_measure: '',
|
||||
fraction: '',
|
||||
us_fraction: '',
|
||||
unit_measure_trade: '',
|
||||
bom: ''
|
||||
};
|
||||
}
|
||||
|
||||
async function handleRefresh() {
|
||||
await loadClasses();
|
||||
toast.success('Clases actualizadas');
|
||||
}
|
||||
|
||||
function handleDelete() {
|
||||
if (!selectedClass) {
|
||||
toast.error('Selecciona una clase para borrar');
|
||||
return;
|
||||
}
|
||||
showDeleteDialog = true;
|
||||
}
|
||||
|
||||
async function confirmDelete() {
|
||||
if (!selectedClass) return;
|
||||
|
||||
const companyId = companyStore.activeCompany?.id;
|
||||
if (!companyId) {
|
||||
toast.error('No hay empresa seleccionada');
|
||||
return;
|
||||
}
|
||||
|
||||
const classToDelete = selectedClass;
|
||||
|
||||
try {
|
||||
// El backend ahora elimina automáticamente la extensión FA si existe
|
||||
await classesApi.delete(classToDelete.id, companyId);
|
||||
|
||||
toast.success(`Clase ${classToDelete.class_code} eliminada correctamente`);
|
||||
|
||||
// Recargar lista
|
||||
await loadClasses();
|
||||
|
||||
selectedClass = null;
|
||||
showDeleteDialog = false;
|
||||
formData = {
|
||||
class_code: '',
|
||||
description_es: '',
|
||||
description_en: '',
|
||||
material_key: '',
|
||||
unit_of_measure: '',
|
||||
fraction: '',
|
||||
us_fraction: '',
|
||||
unit_measure_trade: '',
|
||||
bom: ''
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error deleting class:', error);
|
||||
toast.error('Error al eliminar la clase');
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col h-[calc(100vh-4rem)] p-4 gap-4 pb-15">
|
||||
<!-- Título -->
|
||||
<div class="flex flex-col gap-1">
|
||||
<h1 class="text-2xl font-bold">CATALOGO DE CLASES DE ACTIVO FIJO</h1>
|
||||
<p class="text-sm text-muted-foreground">
|
||||
Gestiona y consulta las clases de activo fijo
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Contenedor principal con grid y detalles -->
|
||||
<div class="flex-1 flex gap-4 overflow-hidden">
|
||||
<!-- Panel izquierdo: Grid/Tabla de clases -->
|
||||
<div class="flex-1 flex flex-col gap-4 overflow-hidden">
|
||||
<!-- Sección de Filtros -->
|
||||
<div class="border rounded-lg bg-card">
|
||||
<div class="p-4 space-y-4">
|
||||
<div class="flex items-center justify-between">
|
||||
<h2 class="text-sm font-semibold">Filtros</h2>
|
||||
<span class="text-xs text-muted-foreground">
|
||||
Filtra las clases por diferentes criterios (los filtros se aplican automáticamente)
|
||||
</span>
|
||||
</div>
|
||||
<div class="grid grid-cols-4 gap-4">
|
||||
<div class="space-y-2">
|
||||
<Label class="text-xs">Clase</Label>
|
||||
<Input
|
||||
bind:value={searchTerm}
|
||||
placeholder="Ej: AF001"
|
||||
class="h-9"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<Label class="text-xs">Descripción</Label>
|
||||
<Input
|
||||
bind:value={searchDescription}
|
||||
placeholder="Buscar descripción..."
|
||||
class="h-9"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<Label class="text-xs">Tipo</Label>
|
||||
<Input
|
||||
bind:value={searchType}
|
||||
placeholder="MP, SC, DESP..."
|
||||
class="h-9"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<Label class="text-xs">Fracción</Label>
|
||||
<Input
|
||||
bind:value={searchFraction}
|
||||
placeholder="Fracción arancelaria"
|
||||
class="h-9"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tabla de clases -->
|
||||
<div class="flex-1 flex flex-col border rounded-lg overflow-hidden">
|
||||
<div class="flex items-center justify-between p-3 border-b bg-white dark:bg-muted/50">
|
||||
<h2 class="text-sm font-semibold">Listado de Clases</h2>
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-xs text-muted-foreground">
|
||||
Mostrando de {filteredClasses.length} registros
|
||||
</span>
|
||||
<Button variant="outline" size="sm" onclick={handleRefresh}>
|
||||
<RefreshCw class="h-4 w-4 mr-2" />
|
||||
Actualizar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tabla de clases -->
|
||||
<div class="flex-1 overflow-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead class="bg-white dark:bg-black text-gray-900 dark:text-white sticky top-0 z-10 border-b">
|
||||
<tr>
|
||||
<th class="px-2 py-2 text-left w-8">
|
||||
<input type="checkbox" class="h-4 w-4" />
|
||||
</th>
|
||||
<th class="px-2 py-2 text-left">Clase</th>
|
||||
<th class="px-2 py-2 text-left">Descripción Español</th>
|
||||
<th class="px-2 py-2 text-left">Descripción Inglés</th>
|
||||
<th class="px-2 py-2 text-left">Tipo</th>
|
||||
<th class="px-2 py-2 text-left">U.M</th>
|
||||
<th class="px-2 py-2 text-left">Fracción</th> <th class="px-2 py-2 text-left">U.M.T.</th> <th class="px-2 py-2 text-left">Fracción US</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#if isLoading}
|
||||
<tr>
|
||||
<td colspan="10" class="text-center py-8 text-muted-foreground">Cargando...</td>
|
||||
</tr>
|
||||
{:else if filteredClasses.length === 0}
|
||||
<tr>
|
||||
<td colspan="10" class="text-center py-8 text-muted-foreground">
|
||||
No hay clases de activo fijo registradas
|
||||
</td>
|
||||
</tr>
|
||||
{:else}
|
||||
{#each filteredClasses as cls (cls.id)}
|
||||
<tr
|
||||
class="border-b cursor-pointer transition-colors {selectedClass?.id ===
|
||||
cls.id
|
||||
? 'bg-gray-300 dark:bg-gray-600'
|
||||
: 'hover:bg-gray-100 dark:hover:bg-gray-700'}"
|
||||
onclick={() => selectClass(cls)}
|
||||
>
|
||||
<td class="px-2 py-1">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedClass?.id === cls.id}
|
||||
class="h-4 w-4"
|
||||
/>
|
||||
</td>
|
||||
<td class="px-2 py-1">
|
||||
<span class="inline-flex items-center rounded-md bg-blue-50 dark:bg-blue-900/30 px-2 py-1 text-xs font-mono font-bold text-blue-700 dark:text-blue-400 border border-blue-200 dark:border-blue-800">
|
||||
{cls.class_code}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-2 py-1 font-medium text-sm">{cls.description_es || ''}</td>
|
||||
<td class="px-2 py-1">{cls.description_en || ''}</td>
|
||||
<td class="px-2 py-1">
|
||||
<span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider {cls.material_key === 'MP' ? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400' : cls.material_key === 'SC' ? 'bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-400' : cls.material_key === 'DESP' ? 'bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400' : 'bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-400'}">
|
||||
{cls.material_key || ''}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-2 py-1 text-muted-foreground">{cls.unit_of_measure || ''}</td>
|
||||
<td class="px-2 py-1 font-mono text-xs text-orange-600 dark:text-orange-400">{cls.fraction || ''}</td> <td class="px-2 py-1 text-xs text-muted-foreground">-</td> <td class="px-2 py-1">{cls.us_fraction || '-'}</td>
|
||||
</tr>
|
||||
{/each}
|
||||
{/if}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Panel derecho: Detalles y edición -->
|
||||
<div class="w-96 flex-none flex flex-col border rounded-xl bg-muted/30 shadow-sm overflow-hidden">
|
||||
<div class="p-4 border-b">
|
||||
<p class="text-[10px] uppercase tracking-widest opacity-80 text-muted-foreground">Código de Clase</p>
|
||||
<h2 class="text-3xl font-black font-mono tracking-tighter">
|
||||
{formData.class_code || '---'}
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 overflow-auto p-5 space-y-6 bg-card">
|
||||
<div class="space-y-3">
|
||||
<div>
|
||||
<Label class="text-[10px] uppercase text-muted-foreground font-bold">Descripción ES</Label>
|
||||
<p class="text-sm font-semibold leading-tight">{formData.description_es || 'Sin descripción'}</p>
|
||||
</div>
|
||||
<div class="pt-2 border-t border-dashed">
|
||||
<Label class="text-[10px] uppercase text-muted-foreground font-bold">Description EN</Label>
|
||||
<p class="text-sm italic text-muted-foreground">{formData.description_en || 'No translation available'}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-4 pt-4 border-t">
|
||||
<div class="space-y-1">
|
||||
<Label class="text-[10px] uppercase text-muted-foreground font-bold">Tipo Activo</Label>
|
||||
<div class="flex items-center gap-2">
|
||||
<Folder class="h-3 w-3 text-blue-500" />
|
||||
<span class="text-sm font-bold">{formData.material_key || '-'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="space-y-1">
|
||||
<Label class="text-[10px] uppercase text-muted-foreground font-bold">U.M. Com.</Label>
|
||||
<span class="text-sm font-bold">{formData.unit_of_measure || '-'}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="p-3 bg-orange-50 dark:bg-orange-950/20 rounded-lg border border-orange-100 dark:border-orange-900">
|
||||
<Label class="text-[10px] uppercase text-orange-600 dark:text-orange-400 font-bold">Fracción Arancelaria</Label>
|
||||
<p class="text-lg font-mono font-bold text-orange-700 dark:text-orange-300">
|
||||
{formData.fraction || '0000.00.00'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Footer fijo con botones de acción -->
|
||||
<div class="fixed bottom-0 left-0 right-0 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 border-t shadow-lg z-[5]">
|
||||
<div class="px-4 py-4 max-w-[1400px] mx-auto">
|
||||
<!-- Botones de acción -->
|
||||
<div class="flex justify-end gap-2">
|
||||
<Button size="sm" onclick={() => {
|
||||
selectedClass = null;
|
||||
validationError = '';
|
||||
showInsertDialog = true;
|
||||
}}>
|
||||
<Plus class="h-4 w-4 mr-1" />
|
||||
Insertar
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onclick={() => {
|
||||
if (!selectedClass) {
|
||||
toast.error('Selecciona una clase para editar');
|
||||
return;
|
||||
}
|
||||
validationError = '';
|
||||
showInsertDialog = true;
|
||||
}} disabled={!selectedClass}>Editar</Button>
|
||||
<Button variant="outline" size="sm" onclick={handleDelete} disabled={!selectedClass}>Borrar</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Dialog para Insertar/Editar Clase de Activo Fijo -->
|
||||
<Dialog.Root bind:open={showInsertDialog}>
|
||||
<Dialog.Content class="!max-w-[1600px] !w-[1600px] !h-[90vh] p-0 overflow-hidden flex flex-col">
|
||||
<Dialog.Header class="p-6 pb-4 border-b">
|
||||
<Dialog.Title>{selectedClass ? 'Editar' : 'Nueva'} Clase de Activo Fijo</Dialog.Title>
|
||||
</Dialog.Header>
|
||||
|
||||
<!-- Mensaje de error de validación -->
|
||||
{#if validationError}
|
||||
<div class="mx-6 mt-4 p-4 bg-red-50 border border-red-200 rounded-lg">
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="flex-shrink-0 w-5 h-5 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold mt-0.5">
|
||||
!
|
||||
</div>
|
||||
<div class="flex-1">
|
||||
<h3 class="text-sm font-semibold text-red-800 mb-1">Error de Validación</h3>
|
||||
<p class="text-sm text-red-700 whitespace-pre-line">{validationError}</p>
|
||||
</div>
|
||||
<button
|
||||
onclick={() => validationError = ''}
|
||||
class="flex-shrink-0 text-red-400 hover:text-red-600"
|
||||
aria-label="Cerrar mensaje de error">
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="flex-1 overflow-auto p-6">
|
||||
<FixedAssetClassForm
|
||||
initialData={selectedClass}
|
||||
externalError={validationError}
|
||||
onClearError={() => validationError = ''}
|
||||
onSave={async (data: Partial<FixedAssetClassExtended>) => {
|
||||
// Evitar múltiples clics
|
||||
if (isSaving) {
|
||||
console.log('⚠️ Ya está guardando, ignorando clic');
|
||||
return;
|
||||
}
|
||||
isSaving = true;
|
||||
validationError = '';
|
||||
|
||||
console.log('========================================');
|
||||
console.log('=== INICIO ONSAVE ===');
|
||||
console.log('Datos recibidos:', data);
|
||||
console.log('selectedClass:', selectedClass);
|
||||
console.log('========================================');
|
||||
|
||||
try {
|
||||
const cleanData = $state.snapshot(data);
|
||||
const companyId = companyStore.activeCompany?.id;
|
||||
const token = await getToken();
|
||||
|
||||
if (!companyId) {
|
||||
throw new Error('No hay empresa seleccionada');
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
throw new Error('No estás autenticado');
|
||||
}
|
||||
|
||||
let response;
|
||||
|
||||
if (selectedClass?.id) {
|
||||
// === ACTUALIZACIÓN ===
|
||||
console.log('🔄 MODO: ACTUALIZACIÓN');
|
||||
console.log('ID de clase:', selectedClass.id);
|
||||
|
||||
response = await classesApi.update(selectedClass.id, {
|
||||
class_code: cleanData.class_code?.trim() || '',
|
||||
description_es: cleanData.description_es?.trim() || '',
|
||||
description_en: cleanData.description_en?.trim() || '',
|
||||
material_key: cleanData.material_key?.trim() || '',
|
||||
unit_of_measure: cleanData.unit_of_measure?.trim() || '',
|
||||
fraction: cleanData.fraction?.trim() || '',
|
||||
us_fraction: cleanData.us_fraction || '',
|
||||
physical_review: cleanData.physical_review ? 1 : 0,
|
||||
iva_exempt_fraction: cleanData.iva_exempt_fraction || ''
|
||||
}, companyId);
|
||||
|
||||
// ¡IMPORTANTE! fetchApi NO lanza excepciones, retorna { error, status }
|
||||
if (response.error) {
|
||||
console.error('❌ Error en respuesta de actualización:', response);
|
||||
throw new Error(response.error);
|
||||
}
|
||||
|
||||
console.log('✅ Actualización exitosa');
|
||||
} else {
|
||||
// === CREACIÓN ===
|
||||
console.log('➕ MODO: CREACIÓN');
|
||||
|
||||
const payload = {
|
||||
client_id: 2,
|
||||
class_code: cleanData.class_code?.trim() || '',
|
||||
description_es: cleanData.description_es?.trim() || '',
|
||||
description_en: cleanData.description_en?.trim() || '',
|
||||
material_key: cleanData.material_key?.trim() || '',
|
||||
unit_of_measure: cleanData.unit_of_measure?.trim() || '',
|
||||
fraction: cleanData.fraction?.trim() || '',
|
||||
us_fraction: cleanData.us_fraction?.trim() || '',
|
||||
sub_key: cleanData.sub_key || '',
|
||||
physical_review: cleanData.physical_review ? 1 : 0,
|
||||
iva_exempt_fraction: cleanData.iva_exempt_fraction || '',
|
||||
depreciation_rate: cleanData.depreciation_rate || null,
|
||||
fda_code: cleanData.fda_code || null,
|
||||
class_enabled: true
|
||||
};
|
||||
|
||||
console.log('Payload:', payload);
|
||||
|
||||
const fetchResponse = await fetch(`http://localhost:8000/api/v1/a76/classes/fa?company_id=${companyId}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
if (!fetchResponse.ok) {
|
||||
const errorData = await fetchResponse.json();
|
||||
console.error('❌ Error del servidor:', errorData);
|
||||
throw errorData;
|
||||
}
|
||||
|
||||
response = await fetchResponse.json();
|
||||
console.log('✅ Creación exitosa');
|
||||
}
|
||||
|
||||
// === ÉXITO TOTAL ===
|
||||
console.log('✅ GUARDADO EXITOSO - Cerrando diálogo');
|
||||
const wasUpdate = !!selectedClass?.id;
|
||||
await loadClasses();
|
||||
showInsertDialog = false;
|
||||
selectedClass = null;
|
||||
validationError = '';
|
||||
toast.success(wasUpdate ? 'Clase actualizada correctamente' : 'Clase creada correctamente');
|
||||
|
||||
} catch (error: any) {
|
||||
// === ERROR ===
|
||||
console.error('========================================');
|
||||
console.error('❌ ERROR CAPTURADO');
|
||||
console.error('Error:', error);
|
||||
console.error('Error.response:', error?.response);
|
||||
console.error('Error.response.data:', error?.response?.data);
|
||||
console.error('Error.detail:', error?.detail);
|
||||
console.error('========================================');
|
||||
|
||||
let errorMsg = 'Error al guardar';
|
||||
|
||||
// Primero intentar con error.detail (fetch directo)
|
||||
if (error?.detail) {
|
||||
if (typeof error.detail === 'string') {
|
||||
errorMsg = error.detail;
|
||||
} else if (Array.isArray(error.detail)) {
|
||||
errorMsg = error.detail.map((e: any) => e.msg || e).join(', ');
|
||||
}
|
||||
}
|
||||
// Luego con error.response.data.detail (axios)
|
||||
else if (error?.response?.data?.detail) {
|
||||
if (typeof error.response.data.detail === 'string') {
|
||||
errorMsg = error.response.data.detail;
|
||||
} else if (Array.isArray(error.response.data.detail)) {
|
||||
errorMsg = error.response.data.detail.map((e: any) => e.msg || e).join(', ');
|
||||
}
|
||||
}
|
||||
// Por último el mensaje genérico
|
||||
else if (error?.message) {
|
||||
errorMsg = error.message;
|
||||
}
|
||||
|
||||
console.error('📝 Mensaje de error extraído:', errorMsg);
|
||||
|
||||
validationError = errorMsg;
|
||||
console.error('🔴 validationError asignado:', validationError);
|
||||
console.error('🔴 showInsertDialog permanece:', showInsertDialog);
|
||||
console.error('========================================');
|
||||
|
||||
// NO cerramos el diálogo, permanece abierto
|
||||
} finally {
|
||||
isSaving = false;
|
||||
console.log('✅ isSaving = false');
|
||||
}
|
||||
}}
|
||||
onCancel={() => {
|
||||
showInsertDialog = false;
|
||||
selectedClass = null;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Dialog.Footer class="p-6 pt-4 border-t">
|
||||
<Button variant="outline" onclick={() => { validationError = ''; showInsertDialog = false;
|
||||
selectedClass = null;
|
||||
}}>Cancelar</Button>
|
||||
<Button type="button" disabled={isSaving} onclick={() => {
|
||||
// Trigger the form's handleSave by getting a reference via DOM
|
||||
const saveEvent = new CustomEvent('save-form');
|
||||
document.dispatchEvent(saveEvent);
|
||||
}}>
|
||||
{#if isSaving}
|
||||
<RefreshCw class="h-4 w-4 mr-2 animate-spin" />
|
||||
Guardando...
|
||||
{:else}
|
||||
<Save class="h-4 w-4 mr-2" />
|
||||
Guardar
|
||||
{/if}
|
||||
</Button>
|
||||
</Dialog.Footer>
|
||||
</Dialog.Content>
|
||||
</Dialog.Root>
|
||||
|
||||
<!-- Dialog de confirmación para borrar -->
|
||||
<Dialog.Root bind:open={showDeleteDialog}>
|
||||
<Dialog.Content class="max-w-md">
|
||||
<Dialog.Header>
|
||||
<Dialog.Title>¿Confirmar eliminación?</Dialog.Title>
|
||||
</Dialog.Header>
|
||||
<div class="py-4">
|
||||
<p class="text-sm text-muted-foreground">
|
||||
¿Estás seguro que deseas eliminar la clase <strong class="text-foreground">{selectedClass?.class_code}</strong>?
|
||||
</p>
|
||||
<p class="text-sm text-muted-foreground mt-2">
|
||||
{selectedClass?.description_es}
|
||||
</p>
|
||||
<p class="text-sm text-destructive mt-4">
|
||||
Esta acción no se puede deshacer.
|
||||
</p>
|
||||
</div>
|
||||
<Dialog.Footer>
|
||||
<Button variant="outline" onclick={() => showDeleteDialog = false}>Cancelar</Button>
|
||||
<Button variant="destructive" onclick={confirmDelete}>Eliminar</Button>
|
||||
</Dialog.Footer>
|
||||
</Dialog.Content>
|
||||
</Dialog.Root>
|
||||
@@ -1,211 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import { Input } from '$lib/components/ui/input';
|
||||
import * as Card from '$lib/components/ui/card';
|
||||
import * as Table from '$lib/components/ui/table';
|
||||
import { Search, Loader2, Download } from 'lucide-svelte';
|
||||
import { getTariffFractions, type TariffFraction } from '$lib/api/dashboard/a76/general_catalogs/tariff-fractions';
|
||||
import { companyStore } from '$lib/stores/company.svelte';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
let tariffFractions = $state<TariffFraction[]>([]);
|
||||
let filteredFractions = $state<TariffFraction[]>([]);
|
||||
let searchQuery = $state('');
|
||||
let isLoading = $state(false);
|
||||
let currentPage = $state(1);
|
||||
let totalPages = $state(1);
|
||||
let totalRecords = $state(0);
|
||||
const pageSize = 50;
|
||||
|
||||
onMount(() => {
|
||||
loadTariffFractions();
|
||||
});
|
||||
|
||||
// Filtrar fracciones cuando cambia la búsqueda
|
||||
$effect(() => {
|
||||
if (searchQuery.trim() === '') {
|
||||
filteredFractions = tariffFractions;
|
||||
} else {
|
||||
const query = searchQuery.toLowerCase();
|
||||
filteredFractions = tariffFractions.filter(
|
||||
(fraction) =>
|
||||
fraction.code.toLowerCase().includes(query) ||
|
||||
fraction.fraction.toLowerCase().includes(query) ||
|
||||
(fraction.description ?? '').toLowerCase().includes(query) ||
|
||||
(fraction.nico ?? '').toLowerCase().includes(query) ||
|
||||
(fraction.umt ?? '').toLowerCase().includes(query)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
async function loadTariffFractions(page: number = 1) {
|
||||
const companyId = companyStore.activeCompany?.id;
|
||||
if (!companyId) {
|
||||
console.error('No hay compañía activa');
|
||||
return;
|
||||
}
|
||||
|
||||
isLoading = true;
|
||||
try {
|
||||
const response = await getTariffFractions(page, pageSize, companyId);
|
||||
if (response.data) {
|
||||
tariffFractions = response.data.items;
|
||||
filteredFractions = response.data.items;
|
||||
totalPages = response.data.pages;
|
||||
totalRecords = response.data.total;
|
||||
currentPage = response.data.page;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error cargando fracciones arancelarias:', error);
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function goToPage(page: number) {
|
||||
if (page >= 1 && page <= totalPages && page !== currentPage) {
|
||||
await loadTariffFractions(page);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="container mx-auto p-6">
|
||||
<Card.Root>
|
||||
<Card.Header class="text-center border-b">
|
||||
<Card.Title class="text-2xl font-bold uppercase">
|
||||
Catálogo de Fracciones SITAR - SCAII
|
||||
</Card.Title>
|
||||
<p class="text-muted-foreground mt-2">
|
||||
Nomenclatura arancelaria mexicana completa
|
||||
</p>
|
||||
</Card.Header>
|
||||
|
||||
<Card.Content class="pt-6">
|
||||
<div class="space-y-6">
|
||||
<!-- Barra de búsqueda y acciones -->
|
||||
<div class="flex gap-4 items-center">
|
||||
<div class="flex-1 relative">
|
||||
<Search class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
bind:value={searchQuery}
|
||||
placeholder="Buscar por código, fracción, descripción, NICO o UMT..."
|
||||
class="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<Button variant="outline" size="icon" title="Exportar a CSV">
|
||||
<Download class="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- Información de registros -->
|
||||
<div class="flex items-center justify-between text-sm text-muted-foreground">
|
||||
<div>
|
||||
{#if isLoading}
|
||||
<div class="flex items-center gap-2">
|
||||
<Loader2 class="h-4 w-4 animate-spin" />
|
||||
<span>Cargando...</span>
|
||||
</div>
|
||||
{:else}
|
||||
Mostrando {filteredFractions.length} de {totalRecords} fracciones arancelarias
|
||||
{#if searchQuery}
|
||||
(filtrado)
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
{#if !searchQuery && totalPages > 1}
|
||||
<div class="flex items-center gap-2">
|
||||
<span>Página {currentPage} de {totalPages}</span>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Tabla de fracciones -->
|
||||
<div class="border rounded-md overflow-auto max-h-[600px]">
|
||||
<Table.Root>
|
||||
<Table.Header class="sticky top-0 bg-background z-10">
|
||||
<Table.Row>
|
||||
<Table.Head class="w-[100px]">Código</Table.Head>
|
||||
<Table.Head class="w-[120px]">Fracción</Table.Head>
|
||||
<Table.Head class="min-w-[350px]">Descripción</Table.Head>
|
||||
<Table.Head class="w-[80px]">NICO</Table.Head>
|
||||
<Table.Head class="w-[80px]">UMT</Table.Head>
|
||||
<Table.Head class="w-[100px]">Adv. Impo</Table.Head>
|
||||
<Table.Head class="w-[100px]">Adv. Expo</Table.Head>
|
||||
</Table.Row>
|
||||
</Table.Header>
|
||||
<Table.Body>
|
||||
{#if filteredFractions.length === 0}
|
||||
<Table.Row>
|
||||
<Table.Cell colspan={7} class="text-center py-8 text-muted-foreground">
|
||||
{#if isLoading}
|
||||
Cargando fracciones arancelarias...
|
||||
{:else if searchQuery}
|
||||
No se encontraron fracciones que coincidan con la búsqueda
|
||||
{:else}
|
||||
No hay fracciones arancelarias disponibles
|
||||
{/if}
|
||||
</Table.Cell>
|
||||
</Table.Row>
|
||||
{:else}
|
||||
{#each filteredFractions as fraction (fraction.id)}
|
||||
<Table.Row class="hover:bg-muted/50">
|
||||
<Table.Cell class="font-mono text-sm">{fraction.code}</Table.Cell>
|
||||
<Table.Cell class="font-mono text-sm font-medium">{fraction.fraction}</Table.Cell>
|
||||
<Table.Cell class="text-sm">
|
||||
{fraction.description || '-'}
|
||||
</Table.Cell>
|
||||
<Table.Cell class="text-sm">{fraction.nico || '-'}</Table.Cell>
|
||||
<Table.Cell class="text-sm">{fraction.umt || '-'}</Table.Cell>
|
||||
<Table.Cell class="text-sm">{fraction.adv_impo || '-'}</Table.Cell>
|
||||
<Table.Cell class="text-sm">{fraction.adv_expo || '-'}</Table.Cell>
|
||||
</Table.Row>
|
||||
{/each}
|
||||
{/if}
|
||||
</Table.Body>
|
||||
</Table.Root>
|
||||
</div>
|
||||
|
||||
<!-- Paginación -->
|
||||
{#if !searchQuery && totalPages > 1}
|
||||
<div class="flex items-center justify-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={currentPage === 1 || isLoading}
|
||||
onclick={() => goToPage(1)}
|
||||
>
|
||||
Primera
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={currentPage === 1 || isLoading}
|
||||
onclick={() => goToPage(currentPage - 1)}
|
||||
>
|
||||
Anterior
|
||||
</Button>
|
||||
<span class="px-4 text-sm">
|
||||
Página {currentPage} de {totalPages}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={currentPage === totalPages || isLoading}
|
||||
onclick={() => goToPage(currentPage + 1)}
|
||||
>
|
||||
Siguiente
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={currentPage === totalPages || isLoading}
|
||||
onclick={() => goToPage(totalPages)}
|
||||
>
|
||||
Última
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
</div>
|
||||
@@ -1,62 +0,0 @@
|
||||
import type { PageServerLoad } from './$types';
|
||||
import { getAuthTokens, authenticatedFetch } from '$lib/server/api';
|
||||
|
||||
export const load: PageServerLoad = async ({ cookies, fetch, url, parent }) => {
|
||||
await parent();
|
||||
const { accessToken } = getAuthTokens(cookies);
|
||||
|
||||
if (!accessToken) {
|
||||
return { error: 'No authenticated', classes: { items: [], total: 0, page: 1, page_size: 50, pages: 0 } };
|
||||
}
|
||||
|
||||
try {
|
||||
const page = Number(url.searchParams.get('page')) || 1;
|
||||
const pageSize = Number(url.searchParams.get('pageSize')) || 50;
|
||||
|
||||
|
||||
const filters: Record<string, string> = {};
|
||||
|
||||
|
||||
const classCode = url.searchParams.get('class_code') || url.searchParams.get('code');
|
||||
const description = url.searchParams.get('description');
|
||||
|
||||
if (classCode) filters.class_code = classCode;
|
||||
if (description) filters.description = description;
|
||||
|
||||
|
||||
const parentData = await parent();
|
||||
const cookieCompanyId = cookies.get('active_company_id');
|
||||
const companyId = cookieCompanyId
|
||||
? parseInt(cookieCompanyId)
|
||||
: parentData.companies?.[0]?.id;
|
||||
|
||||
if (!companyId) {
|
||||
return {
|
||||
error: 'No se encontró una compañía seleccionada',
|
||||
classes: { items: [], total: 0, page: 1, page_size: 50, pages: 0 }
|
||||
};
|
||||
}
|
||||
|
||||
const queryParams = new URLSearchParams({
|
||||
company_id: companyId.toString(),
|
||||
page: page.toString(),
|
||||
page_size: pageSize.toString(),
|
||||
...filters
|
||||
});
|
||||
|
||||
// --- ZONA DE CAMBIO DE ENDPOINT ---
|
||||
|
||||
const response = await authenticatedFetch(`v1/a76/classes?${queryParams.toString()}`, { method: 'GET' }, cookies, fetch);
|
||||
|
||||
if (!response.ok) {
|
||||
return { error: 'Failed to load', classes: { items: [], total: 0, page, page_size: pageSize, pages: 0 } };
|
||||
}
|
||||
|
||||
|
||||
return { classes: await response.json() };
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error loading classes:', error);
|
||||
return { error: 'Error loading', classes: { items: [], total: 0, page: 1, page_size: 50, pages: 0 } };
|
||||
}
|
||||
};
|
||||
@@ -1,239 +0,0 @@
|
||||
<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/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';
|
||||
import { Label } from '$lib/components/ui/label';
|
||||
import type { PageData } from './$types';
|
||||
import { browser } from '$app/environment';
|
||||
import { companyStore } from '$lib/stores/company.svelte';
|
||||
import { Plus, Search, Trash2 } from 'lucide-svelte';
|
||||
|
||||
// 1. Recibimos la data del servidor (+page.server.ts)
|
||||
let { data }: { data: PageData } = $props();
|
||||
|
||||
// 2. Ajustamos el estado para Clases
|
||||
let classesList = $state(data.classes?.items || []);
|
||||
let listLoading = $state(false);
|
||||
let listError = $state<string | null>(data.error || null);
|
||||
|
||||
// Estado para búsqueda
|
||||
let searchCode = $state('');
|
||||
let searchedClass = $state<any | null>(null);
|
||||
let searchLoading = $state(false);
|
||||
let searchError = $state<string | null>(null);
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
// Escuchar cambios de compañía
|
||||
const handleCompanyChange = (event: CustomEvent) => {
|
||||
reloadData();
|
||||
};
|
||||
|
||||
window.addEventListener('companyChanged', handleCompanyChange as EventListener);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('companyChanged', handleCompanyChange as EventListener);
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
async function handleSearch() {
|
||||
if (!searchCode.trim()) {
|
||||
searchError = 'Por favor ingresa un código de clase';
|
||||
return;
|
||||
}
|
||||
|
||||
searchLoading = true;
|
||||
searchError = null;
|
||||
searchedClass = null;
|
||||
|
||||
try {
|
||||
// TODO: Usar tu API real aquí: const response = await classesApi.get(searchCode.trim());
|
||||
console.log("Buscando clase:", searchCode);
|
||||
|
||||
// MOCK TEMPORAL (Borrar esto cuando tengas el API):
|
||||
const response = { error: null, data: null, status: 200 };
|
||||
|
||||
if (response.error) {
|
||||
searchError = response.error;
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.data) {
|
||||
searchedClass = response.data;
|
||||
} else {
|
||||
// Simular no encontrado si usas el mock
|
||||
// searchError = 'No encontrado (Mock)';
|
||||
}
|
||||
} catch (e) {
|
||||
searchError = 'Error al buscar la clase';
|
||||
console.error('Error searching class:', e);
|
||||
} finally {
|
||||
searchLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function reloadData() {
|
||||
searchCode = '';
|
||||
searchedClass = null;
|
||||
searchError = null;
|
||||
|
||||
if (!companyStore.activeCompany) return;
|
||||
|
||||
listLoading = true;
|
||||
listError = null;
|
||||
|
||||
try {
|
||||
// TODO: Usar tu API real aquí: await classesApi.list(...)
|
||||
// Por ahora recargamos la página completa para traer datos frescos del server
|
||||
window.location.reload();
|
||||
|
||||
} catch (e) {
|
||||
listError = 'Error recargando datos';
|
||||
console.error('Error reloading:', e);
|
||||
} finally {
|
||||
listLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleSuccess() {
|
||||
reloadData();
|
||||
}
|
||||
|
||||
// Asegúrate de que columns.js tenga los campos correctos (class_code, description, etc)
|
||||
const columns = createColumns(handleSuccess);
|
||||
|
||||
// Array reactivo
|
||||
const classesData = $derived(searchedClass ? [searchedClass] : classesList);
|
||||
</script>
|
||||
|
||||
<div class="space-y-6">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold tracking-tight">Catálogo de Clases</h1>
|
||||
<p class="text-muted-foreground">
|
||||
Gestiona las clases de material (SCAII / SCAF)
|
||||
</p>
|
||||
</div>
|
||||
<Button href="/dashboard/goods/classes/edit" >
|
||||
<Plus class="mr-2" size={16} />
|
||||
Nueva Clase
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<Card.Title>Buscar Clase</Card.Title>
|
||||
</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">Código de Clase</Label>
|
||||
<Input
|
||||
id="search-key"
|
||||
bind:value={searchCode}
|
||||
placeholder="Ej: ACERO"
|
||||
maxlength={10}
|
||||
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}
|
||||
<Search class="mr-2" size={16} />
|
||||
Buscar
|
||||
{/if}
|
||||
</Button>
|
||||
{#if searchedClass}
|
||||
<Button type="button" variant="outline" onclick={reloadData}>
|
||||
<Trash2 class="mr-2" size={16} />
|
||||
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>
|
||||
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<Card.Title>
|
||||
{#if searchedClass}
|
||||
Resultado de la Búsqueda
|
||||
{:else}
|
||||
Listado de Clases
|
||||
{/if}
|
||||
</Card.Title>
|
||||
<Card.Description>
|
||||
{#if searchedClass}
|
||||
Se encontró 1 Clase
|
||||
{:else if listLoading}
|
||||
Cargando Clases...
|
||||
{:else}
|
||||
Total: {classesList.length} registro{classesList.length !== 1 ? 's' : ''}
|
||||
{/if}
|
||||
</Card.Description>
|
||||
</div>
|
||||
</div>
|
||||
</Card.Header>
|
||||
<Card.Content>
|
||||
{#if listError}
|
||||
<div class="rounded-lg border border-destructive bg-destructive/10 p-4 text-sm text-destructive">
|
||||
{listError}
|
||||
</div>
|
||||
{:else if listLoading}
|
||||
<div class="flex items-center justify-center py-8">
|
||||
<div class="flex items-center gap-2 text-muted-foreground">
|
||||
<div class="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
|
||||
Cargando Clases...
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<DataTable
|
||||
data={classesData}
|
||||
{columns}
|
||||
/>
|
||||
{/if}
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
</div>
|
||||
@@ -1,413 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/stores';
|
||||
import { goto } from '$app/navigation';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
// Componentes UI
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import { Input } from '$lib/components/ui/input';
|
||||
import { Label } from '$lib/components/ui/label';
|
||||
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, Search,
|
||||
User, Package, Scale, BookOpen, Layers, Tag, CheckCircle2
|
||||
} from 'lucide-svelte';
|
||||
|
||||
// Stores y APIs
|
||||
import { companyStore } from '$lib/stores/company.svelte';
|
||||
import {
|
||||
classesApi,
|
||||
type A76ClassCreate,
|
||||
type A76ClassUpdate
|
||||
} from '$lib/api/dashboard/a76/classes';
|
||||
import { materialTypesApi } from "$lib/api/dashboard/a76/material-types";
|
||||
import { clientsProvidersApi } from '$lib/api/dashboard/a76/clients-providers';
|
||||
|
||||
// --- 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);
|
||||
let title = $derived(isEdit ? "Editar Clase" : "Nueva Clase");
|
||||
|
||||
// --- 2. ESTADOS ---
|
||||
let loading = $state(false);
|
||||
let error = $state<string | null>(null);
|
||||
|
||||
let showClientModal = $state(false);
|
||||
let showMaterialModal = $state(false);
|
||||
let showUnitModal = $state(false);
|
||||
|
||||
let selectedClientName = $state("");
|
||||
let selectedMaterialDesc = $state("");
|
||||
let selectedUnitDesc = $state("");
|
||||
|
||||
// Formulario Inicial
|
||||
function getEmptyForm(): A76ClassCreate {
|
||||
return {
|
||||
company_id: 0,
|
||||
client_id: 0,
|
||||
class_code: '',
|
||||
description_es: '',
|
||||
description_en: '',
|
||||
material_key: '',
|
||||
unit_of_measure: '',
|
||||
fraction: '',
|
||||
us_fraction: '',
|
||||
sub_key: '',
|
||||
physical_review: 0,
|
||||
iva_exempt_fraction: ''
|
||||
};
|
||||
}
|
||||
|
||||
let formData = $state<A76ClassCreate>(getEmptyForm());
|
||||
|
||||
// --- 3. CARGA DE DATOS (Mount) ---
|
||||
onMount(async () => {
|
||||
const companyId = companyStore.activeCompany?.id;
|
||||
if (!companyId) return;
|
||||
|
||||
if (id) {
|
||||
await loadClassData(id, companyId);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
async function loadClassData(classId: number, companyId: number) {
|
||||
loading = true;
|
||||
try {
|
||||
const response = await classesApi.get(classId, companyId);
|
||||
|
||||
if (response.error) {
|
||||
error = response.error;
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.data) {
|
||||
const data = response.data;
|
||||
formData = {
|
||||
company_id: data.company_id,
|
||||
client_id: data.client_id,
|
||||
class_code: data.class_code,
|
||||
description_es: data.description_es || '',
|
||||
description_en: data.description_en || '',
|
||||
material_key: data.material_key || '',
|
||||
unit_of_measure: data.unit_of_measure,
|
||||
fraction: data.fraction,
|
||||
us_fraction: data.us_fraction,
|
||||
sub_key: data.sub_key,
|
||||
physical_review: data.physical_review,
|
||||
iva_exempt_fraction: data.iva_exempt_fraction
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
} catch (e) {
|
||||
error = "No se pudo cargar la información de la Clase";
|
||||
console.error(e);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
// --- 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 {
|
||||
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) {
|
||||
formData.unit_of_measure = item.code;
|
||||
selectedUnitDesc = item.description || item.code;
|
||||
}
|
||||
|
||||
// --- 4. GUARDADO ---
|
||||
async function handleSubmit() {
|
||||
error = null;
|
||||
const activeCompanyId = companyStore.activeCompany?.id;
|
||||
|
||||
// Validaciones
|
||||
if (!activeCompanyId) { error = 'Selecciona una compañía'; return; }
|
||||
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; }
|
||||
|
||||
loading = true;
|
||||
try {
|
||||
formData.company_id = activeCompanyId;
|
||||
|
||||
const cleanData = {
|
||||
...formData,
|
||||
description_es: formData.description_es || null,
|
||||
description_en: formData.description_en || null,
|
||||
material_key: formData.material_key || null,
|
||||
};
|
||||
|
||||
if (isEdit && id) {
|
||||
const updatePayload: A76ClassUpdate = cleanData;
|
||||
const response = await classesApi.update(id, updatePayload, activeCompanyId);
|
||||
if (response.error) throw new Error(response.error);
|
||||
} else {
|
||||
const response = await classesApi.create(cleanData, activeCompanyId);
|
||||
if (response.error) throw new Error(response.error);
|
||||
}
|
||||
|
||||
goto('/dashboard/goods/classes');
|
||||
} catch (e: any) {
|
||||
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/goods/classes">
|
||||
<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 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 animate-in slide-in-from-top-2">
|
||||
⚠️ {error}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#key id}
|
||||
<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-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} class="font-mono text-lg" placeholder="Ej. ACERO" />
|
||||
</div>
|
||||
|
||||
<div class="grid gap-2">
|
||||
<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-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-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>
|
||||
<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 (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 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">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 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">Subclave</Label>
|
||||
<Input id="sub_key" bind:value={formData.sub_key} maxlength={5} />
|
||||
</div>
|
||||
<div class="grid gap-2">
|
||||
<Label for="iva_exempt">Fracción Exenta IVA</Label>
|
||||
<Input id="iva_exempt" bind:value={formData.iva_exempt_fraction} maxlength={4} />
|
||||
</div>
|
||||
|
||||
<div class="grid gap-2">
|
||||
<Label for="phys_rev">Revisión Física</Label>
|
||||
<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 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||
>
|
||||
<option value={0}>No</option>
|
||||
<option value={1}>Sí</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</Tabs.Content>
|
||||
</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" 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>
|
||||
</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 flex justify-end gap-4 shadow-inner">
|
||||
<div class="max-w-6xl mx-auto flex justify-end gap-4 px-4 w-full">
|
||||
<Button type="button" variant="ghost" href="/dashboard/goods/classes" disabled={loading}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button type="submit" disabled={loading} class="min-w-[140px]">
|
||||
{#if loading}
|
||||
<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
|
||||
Guardando...
|
||||
{:else}
|
||||
<Save class="mr-2 h-4 w-4" />
|
||||
{isEdit ? 'Actualizar' : 'Guardar'}
|
||||
{/if}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
{/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: " *";
|
||||
color: hsl(var(--destructive));
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,17 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
|
||||
// Redirigir a la página principal después de guardar
|
||||
function handleSaveAndClose() {
|
||||
// Aquí se guardarían los datos
|
||||
window.parent.postMessage({ type: 'close' }, '*');
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="p-4">
|
||||
<iframe
|
||||
src="/dashboard/merchandise/fixed_asset_classes"
|
||||
class="w-full h-[80vh] border-0"
|
||||
title="Clase de Activo Fijo"
|
||||
></iframe>
|
||||
</div>
|
||||
Reference in New Issue
Block a user