Se esta disenando mejor la parte de partes

This commit is contained in:
2026-01-13 18:05:59 -06:00
parent 0c43c252a4
commit e16eafec1b
10 changed files with 1135 additions and 286 deletions

View File

@@ -1,6 +1,6 @@
from decimal import Decimal
from typing import Optional, TYPE_CHECKING
from sqlalchemy import Boolean, String, Integer, Numeric, SmallInteger, ForeignKey
from sqlalchemy import Boolean, String, Integer, Numeric, SmallInteger, ForeignKey, ForeignKeyConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from api.v1.common.base_models import TenantScopedMixin, TimestampMixin
from core.database import Base
@@ -25,9 +25,14 @@ class LineItem(Base, TenantScopedMixin, TimestampMixin):
"""
__tablename__ = "item_lines"
__table_args__ = {
"schema": "a76",
}
__table_args__ = (
ForeignKeyConstraint(
["class_code", "tenant_id", "company_id"],
["a76.classes.class_code", "a76.classes.tenant_id", "a76.classes.company_id"],
name="fk_item_lines_class"
),
{"schema": "a76"},
)
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
item_id: Mapped[int] = mapped_column(ForeignKey("a76.items.id"))
@@ -40,9 +45,7 @@ class LineItem(Base, TenantScopedMixin, TimestampMixin):
component_part_number: Mapped[Optional[str]] = mapped_column(
ForeignKey("a76.parts.id")
) # NUMPARTECOM
class_code: Mapped[Optional[str]] = mapped_column(
ForeignKey("a76.classes.class_code")
) # CLASE
class_code: Mapped[Optional[str]] = mapped_column(String(8)) # CLASE
# Unit of measure
unit_of_measure: Mapped[Optional[str]] = mapped_column(

View File

@@ -109,12 +109,14 @@
<th class="p-3 font-medium text-muted-foreground w-[130px]">RFC</th>
<th class="p-3 font-medium text-muted-foreground">Razón Social</th>
<th class="p-3 font-medium text-muted-foreground w-[100px] text-center">Estado</th>
<th class="p-3 font-medium text-muted-foreground w-[80px]">Acción</th>
</tr>
</thead>
<tbody>
{#each filteredClients as client}
<tr class="border-b hover:bg-muted/50 transition-colors group">
<tr
class="border-b hover:bg-accent/50 transition-colors cursor-pointer"
onclick={() => handleSelect(client)}
>
<td class="p-3 font-mono text-xs">{client.id}</td>
<td class="p-3 font-mono text-xs">{client.rfc}</td>
<td class="p-3 font-medium">
@@ -138,17 +140,6 @@
</span>
{/if}
</td>
<td class="p-2">
<Button
type="button"
size="sm"
variant="ghost"
class="h-8 w-full"
onclick={() => handleSelect(client)}
>
Usar
</Button>
</td>
</tr>
{/each}
</tbody>

View File

@@ -0,0 +1,145 @@
<script lang="ts">
import { Button } from "$lib/components/ui/button";
import { Input } from "$lib/components/ui/input";
import * as Dialog from "$lib/components/ui/dialog";
import * as Table from "$lib/components/ui/table";
import { Search, Loader2, Globe } from "lucide-svelte";
import { countriesApi, type Country } from "$lib/api/dashboard/refrence_data/countries";
// --- PROPS ---
let {
open = $bindable(false),
onSelect
}: {
open: boolean,
onSelect: (item: Country) => void
} = $props();
// --- ESTADO ---
let items = $state<Country[]>([]);
let loading = $state(false);
let searchTerm = $state("");
let loaded = $state(false);
// Filtro local
let filteredItems = $derived(
items.filter(i =>
(i.m3_key || "").toLowerCase().includes(searchTerm.toLowerCase()) ||
(i.mex_key || "").toLowerCase().includes(searchTerm.toLowerCase()) ||
(i.description_es || "").toLowerCase().includes(searchTerm.toLowerCase()) ||
(i.description_en || "").toLowerCase().includes(searchTerm.toLowerCase())
)
);
// Cargar datos al abrir
$effect(() => {
if (open && !loaded) {
loadCountries();
}
});
async function loadCountries() {
loading = true;
try {
const response = await countriesApi.list(1, 300);
if (response.data?.items) {
items = response.data.items;
loaded = true;
} else {
console.warn("No se encontraron países:", response);
}
} catch (e) {
console.error("Error cargando países:", e);
} finally {
loading = false;
}
}
function handleSelect(item: Country) {
if (onSelect) onSelect(item);
open = false;
}
</script>
<Dialog.Root bind:open={open}>
<Dialog.Content class="sm:max-w-[900px] max-h-[80vh] flex flex-col">
<Dialog.Header>
<Dialog.Title>Seleccionar País</Dialog.Title>
<Dialog.Description>
Seleccione el país de origen del catálogo.
</Dialog.Description>
</Dialog.Header>
<div class="relative w-full my-2">
<Search class="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
type="search"
placeholder="Buscar por clave o descripción..."
class="pl-9"
bind:value={searchTerm}
/>
</div>
<div class="flex-1 overflow-y-auto border rounded-md min-h-[300px]">
{#if loading}
<div class="flex flex-col items-center justify-center h-48 gap-2 text-muted-foreground">
<Loader2 class="h-8 w-8 animate-spin text-primary" />
<p>Cargando catálogo...</p>
</div>
{:else if filteredItems.length === 0}
<div class="flex flex-col items-center justify-center h-48 text-muted-foreground">
<p>No se encontraron países.</p>
</div>
{:else}
<Table.Root>
<Table.Header>
<Table.Row>
<Table.Head class="w-[80px]">M3</Table.Head>
<Table.Head class="w-[80px]">MEX</Table.Head>
<Table.Head class="w-[80px]">AME</Table.Head>
<Table.Head>Descripción ES</Table.Head>
<Table.Head>Description EN</Table.Head>
</Table.Row>
</Table.Header>
<Table.Body>
{#each filteredItems as item}
<Table.Row
class="cursor-pointer hover:bg-accent/50 transition-colors"
onclick={() => handleSelect(item)}
>
<Table.Cell>
<div class="flex items-center gap-1">
<Globe class="h-3 w-3 text-blue-500" />
<span class="font-mono font-bold text-xs">
{item.m3_key}
</span>
</div>
</Table.Cell>
<Table.Cell class="font-mono text-xs">
{item.mex_key}
</Table.Cell>
<Table.Cell class="font-mono text-xs">
{item.ame_key}
</Table.Cell>
<Table.Cell class="font-medium text-sm">
{item.description_es}
</Table.Cell>
<Table.Cell class="text-sm text-muted-foreground italic">
{item.description_en}
</Table.Cell>
</Table.Row>
{/each}
</Table.Body>
</Table.Root>
{/if}
</div>
<Dialog.Footer>
<div class="text-xs text-muted-foreground self-center mr-auto">
{filteredItems.length} registros encontrados
</div>
<Button variant="outline" onclick={() => open = false}>Cancelar</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>

View File

@@ -0,0 +1,138 @@
<script lang="ts">
import { Button } from "$lib/components/ui/button";
import { Input } from "$lib/components/ui/input";
import * as Dialog from "$lib/components/ui/dialog";
import * as Table from "$lib/components/ui/table";
import { Search, Loader2, DollarSign } from "lucide-svelte";
import { getMultiCurrencyTypes, type MultiCurrencyType } from "$lib/api/dashboard/a76/general_catalogs/multi-currency-types";
import { companyStore } from "$lib/stores/company.svelte";
// --- PROPS ---
let {
open = $bindable(false),
onSelect
}: {
open: boolean,
onSelect: (item: MultiCurrencyType) => void
} = $props();
// --- ESTADO ---
let items = $state<MultiCurrencyType[]>([]);
let loading = $state(false);
let searchTerm = $state("");
let loaded = $state(false);
// Filtro local
let filteredItems = $derived(
items.filter(i =>
(i.currency_type_code || "").toLowerCase().includes(searchTerm.toLowerCase()) ||
(i.country_key || "").toLowerCase().includes(searchTerm.toLowerCase())
)
);
// Cargar datos al abrir
$effect(() => {
if (open && !loaded && companyStore.activeCompany?.id) {
loadCurrencies();
}
});
async function loadCurrencies() {
if (!companyStore.activeCompany?.id) return;
loading = true;
try {
const response = await getMultiCurrencyTypes(companyStore.activeCompany.id, 1, 100);
if (response?.items) {
items = response.items;
loaded = true;
} else {
console.warn("No se encontraron monedas:", response);
}
} catch (e) {
console.error("Error cargando monedas:", e);
} finally {
loading = false;
}
}
function handleSelect(item: MultiCurrencyType) {
if (onSelect) onSelect(item);
open = false;
}
</script>
<Dialog.Root bind:open={open}>
<Dialog.Content class="sm:max-w-[700px] max-h-[80vh] flex flex-col">
<Dialog.Header>
<Dialog.Title>Seleccionar Moneda</Dialog.Title>
<Dialog.Description>
Seleccione el tipo de moneda del catálogo.
</Dialog.Description>
</Dialog.Header>
<div class="relative w-full my-2">
<Search class="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
type="search"
placeholder="Buscar por código o país..."
class="pl-9"
bind:value={searchTerm}
/>
</div>
<div class="flex-1 overflow-y-auto border rounded-md min-h-[300px]">
{#if loading}
<div class="flex flex-col items-center justify-center h-48 gap-2 text-muted-foreground">
<Loader2 class="h-8 w-8 animate-spin text-primary" />
<p>Cargando catálogo...</p>
</div>
{:else if filteredItems.length === 0}
<div class="flex flex-col items-center justify-center h-48 text-muted-foreground">
<p>No se encontraron monedas.</p>
</div>
{:else}
<Table.Root>
<Table.Header>
<Table.Row>
<Table.Head class="w-[120px]">Código</Table.Head>
<Table.Head class="w-[100px]">País</Table.Head>
<Table.Head class="text-right">Factor Conversión</Table.Head>
</Table.Row>
</Table.Header>
<Table.Body>
{#each filteredItems as item}
<Table.Row
class="cursor-pointer hover:bg-accent/50 transition-colors"
onclick={() => handleSelect(item)}
>
<Table.Cell>
<div class="flex items-center gap-2">
<DollarSign class="h-3 w-3 text-green-500" />
<span class="font-mono font-bold text-primary">
{item.currency_type_code}
</span>
</div>
</Table.Cell>
<Table.Cell class="font-medium">
{item.country_key || '-'}
</Table.Cell>
<Table.Cell class="text-right font-mono text-sm">
{item.conversion_factor?.toFixed(4) || '-'}
</Table.Cell>
</Table.Row>
{/each}
</Table.Body>
</Table.Root>
{/if}
</div>
<Dialog.Footer>
<div class="text-xs text-muted-foreground self-center mr-auto">
{filteredItems.length} registros encontrados
</div>
<Button variant="outline" onclick={() => open = false}>Cancelar</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>

View File

@@ -0,0 +1,155 @@
<script lang="ts">
import { Button } from "$lib/components/ui/button";
import { Input } from "$lib/components/ui/input";
import * as Dialog from "$lib/components/ui/dialog";
import * as Table from "$lib/components/ui/table";
import { Search, Loader2, Hash } from "lucide-svelte";
import { classesApi, type A76Class } from "$lib/api/dashboard/a76/classes";
import { companyStore } from "$lib/stores/company.svelte";
// --- PROPS ---
let {
open = $bindable(false),
onSelect
}: {
open: boolean,
onSelect: (item: { fraction: string; description: string; class_code: string }) => void
} = $props();
// --- ESTADO ---
let classes = $state<A76Class[]>([]);
let loading = $state(false);
let searchTerm = $state("");
let loaded = $state(false);
// Extraer fracciones únicas
let uniqueFractions = $derived(
Array.from(new Set(classes.map(c => c.fraction)))
.filter(f => f && f.trim())
.map(fraction => {
const cls = classes.find(c => c.fraction === fraction);
return {
fraction,
description: cls?.description_es || '',
class_code: cls?.class_code || ''
};
})
.filter(item =>
item.fraction.toLowerCase().includes(searchTerm.toLowerCase()) ||
item.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
item.class_code.toLowerCase().includes(searchTerm.toLowerCase())
)
);
// Cargar datos al abrir
$effect(() => {
if (open && !loaded && companyStore.activeCompany?.id) {
loadFractions();
}
});
async function loadFractions() {
if (!companyStore.activeCompany?.id) return;
loading = true;
try {
const response = await classesApi.list({
company_id: companyStore.activeCompany.id,
page: 1,
page_size: 1000
});
if (response.data?.items) {
classes = response.data.items;
loaded = true;
} else {
console.warn("No se encontraron clases:", response);
}
} catch (e) {
console.error("Error cargando fracciones:", e);
} finally {
loading = false;
}
}
function handleSelect(item: { fraction: string; description: string; class_code: string }) {
if (onSelect) onSelect(item);
open = false;
}
</script>
<Dialog.Root bind:open={open}>
<Dialog.Content class="sm:max-w-[800px] max-h-[80vh] flex flex-col">
<Dialog.Header>
<Dialog.Title>Seleccionar Fracción Arancelaria</Dialog.Title>
<Dialog.Description>
Seleccione la fracción arancelaria del catálogo de clases.
</Dialog.Description>
</Dialog.Header>
<div class="relative w-full my-2">
<Search class="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
type="search"
placeholder="Buscar por fracción, clase o descripción..."
class="pl-9"
bind:value={searchTerm}
/>
</div>
<div class="flex-1 overflow-y-auto border rounded-md min-h-[300px]">
{#if loading}
<div class="flex flex-col items-center justify-center h-48 gap-2 text-muted-foreground">
<Loader2 class="h-8 w-8 animate-spin text-primary" />
<p>Cargando catálogo...</p>
</div>
{:else if uniqueFractions.length === 0}
<div class="flex flex-col items-center justify-center h-48 text-muted-foreground">
<p>No se encontraron fracciones.</p>
</div>
{:else}
<Table.Root>
<Table.Header>
<Table.Row>
<Table.Head class="w-[150px]">Fracción</Table.Head>
<Table.Head>Descripción</Table.Head>
<Table.Head class="w-[120px]">Clase</Table.Head>
</Table.Row>
</Table.Header>
<Table.Body>
{#each uniqueFractions as item}
<Table.Row
class="cursor-pointer hover:bg-accent/50 transition-colors"
onclick={() => handleSelect(item)}
>
<Table.Cell>
<div class="flex items-center gap-2">
<Hash class="h-3 w-3 text-orange-500" />
<span class="font-mono font-bold text-orange-600 dark:text-orange-400">
{item.fraction}
</span>
</div>
</Table.Cell>
<Table.Cell class="font-medium text-sm">
{item.description || '-'}
</Table.Cell>
<Table.Cell>
<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">
{item.class_code}
</span>
</Table.Cell>
</Table.Row>
{/each}
</Table.Body>
</Table.Root>
{/if}
</div>
<Dialog.Footer>
<div class="text-xs text-muted-foreground self-center mr-auto">
{uniqueFractions.length} fracciones únicas encontradas
</div>
<Button variant="outline" onclick={() => open = false}>Cancelar</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>

View File

@@ -116,7 +116,6 @@
<Table.Row>
<Table.Head class="w-[80px]">Código</Table.Head>
<Table.Head>Descripción</Table.Head>
<Table.Head class="text-right w-[50px]"></Table.Head>
</Table.Row>
</Table.Header>
<Table.Body>
@@ -129,7 +128,7 @@
{:else}
{#each items as item}
<Table.Row
class="cursor-pointer hover:bg-muted/50"
class="cursor-pointer hover:bg-accent/50 transition-colors"
onclick={() => handleSelect(item)}
>
<Table.Cell class="font-mono font-bold">{item.code}</Table.Cell>
@@ -141,11 +140,6 @@
{/if}
</div>
</Table.Cell>
<Table.Cell class="text-right">
<Button variant="ghost" size="icon" class="h-6 w-6">
<Check class="h-4 w-4" />
</Button>
</Table.Cell>
</Table.Row>
{/each}
{/if}

View File

@@ -110,12 +110,14 @@
<th class="p-3 font-medium text-muted-foreground w-[100px]">Clave</th>
<th class="p-3 font-medium text-muted-foreground">Descripción</th>
<th class="p-3 font-medium text-muted-foreground w-[80px]">UM</th>
<th class="p-3 font-medium text-muted-foreground w-[80px]">Acción</th>
</tr>
</thead>
<tbody>
{#each filteredItems as item}
<tr class="border-b hover:bg-muted/50 transition-colors">
<tr
class="border-b hover:bg-accent/50 transition-colors cursor-pointer"
onclick={() => handleSelect(item)}
>
<td class="p-3">
<span class="font-mono font-bold text-primary bg-primary/10 px-2 py-1 rounded text-xs">
{item.class_code}
@@ -137,18 +139,6 @@
{item.unit_of_measure || '-'}
</div>
</td>
<td class="p-2">
<Button
type="button"
size="sm"
variant="ghost"
class="h-8 w-full"
onclick={() => handleSelect(item)}
>
Usar
</Button>
</td>
</tr>
{/each}
</tbody>

View File

@@ -9,7 +9,9 @@
import * as Tabs from '$lib/components/ui/tabs';
import * as Card from '$lib/components/ui/card';
import * as Select from "$lib/components/ui/select";
import { Switch } from "$lib/components/ui/switch";
import { Switch } from "$lib/components/ui/switch";
import { Separator } from '$lib/components/ui/separator';
import { Badge } from '$lib/components/ui/badge';
// Iconos
import {
@@ -30,6 +32,9 @@
import ClassSelectorDialog from '$lib/components/dashboard/goods/parts/class-selector-dialog.svelte';
import MaterialTypeSelectorDialog from '$lib/components/dashboard/goods/modales/material-type-selector-dialog.svelte';
import UnitMeasureSelectorDialog from '$lib/components/dashboard/goods/modales/unit-measure-dialog.svelte';
import CurrencySelectorDialog from '$lib/components/dashboard/goods/modales/currency-selector-dialog.svelte';
import CountrySelectorDialog from '$lib/components/dashboard/goods/modales/country-selector-dialog.svelte';
import FractionSelectorDialog from '$lib/components/dashboard/goods/modales/fraction-selector-dialog.svelte';
// --- PROPS ---
let { partId = null, formType = 'inv' }: { partId?: number | null, formType?: 'inv' | 'fa' } = $props();
@@ -40,6 +45,7 @@
let loading = $state(false);
let error = $state<string | null>(null);
let activeTab = $state('general');
// Estado Modales
let showClientModal = $state(false);
@@ -47,11 +53,16 @@
let showMaterialModal = $state(false);
let showUOMModal = $state(false);
let showAltUOMModal = $state(false);
let showCurrencyModal = $state(false);
let showCountryModal = $state(false);
let showFractionModal = $state(false);
// Descripciones Visuales
let selectedClientName = $state("");
let selectedClientStatus = $state(true);
let selectedClassDesc = $state("");
let selectedCurrencyName = $state("");
let selectedCountryName = $state("");
let selectedMaterialDesc = $state("");
// Estado Formulario
@@ -60,13 +71,14 @@
part_number: '',
description_spanish: '',
description_english: '',
part_class: '',
part_class: '',
material_type: '',
unit_of_measure: 'PZ',
unit_weight: 0,
weight_type: 'KG',
unit_cost: 0,
currency_key: 'USD',
currency_type: '',
currency_key: null,
added_value: 0,
value_added_type: 'USD',
us_fraction: '',
@@ -180,6 +192,13 @@
function handleMaterialSelect(item: any) { formData.material_type = item.key; selectedMaterialDesc = item.description; }
function handleUOMSelect(item: any) { formData.unit_of_measure = item.code; }
function handleAltUOMSelect(item: any) { formData.alternate_unit_measure = item.code; }
function handleCurrencySelect(currency: any) {
formData.currency_type = ''; // Catálogo no usa currency_type
formData.currency_key = currency.currency_type_code;
selectedCurrencyName = currency.currency_type_code;
}
function handleCountrySelect(country: any) { formData.origin_country = country.m3_key; selectedCountryName = country.description_es; }
function handleFractionSelect(item: any) { formData.fraction = item.fraction; }
// --- SUBMIT ---
async function handleSubmit() {
@@ -192,51 +211,83 @@
loading = true;
try {
// Construimos el payload.
// Si es FA, inyectamos el objeto fa_data anidado.
let commonData: any = { ...formData };
// Si currency_key está vacío o es el default, ponerlo en null
if (!commonData.currency_key || commonData.currency_key === 'USD') {
commonData.currency_key = null;
}
if (formType === 'fa') {
// Crear fa_data con los campos específicos de FA
commonData.fa_data = {
sector: formData.sector,
fraction_type: formData.fraction_type,
origin_country: formData.origin_country
};
// IMPORTANTE: Eliminar estos campos del nivel raíz para evitar duplicados
delete commonData.sector;
delete commonData.fraction_type;
delete commonData.origin_country;
}
// DEBUG: Ver qué se está enviando
console.log('Payload que se enviará:', JSON.stringify(commonData, null, 2));
console.log('client_id:', formData.client_id);
console.log('selectedClientName:', selectedClientName);
if (isEdit && partId) {
await partsApi.update(partId, commonData, activeCompanyId);
} else {
await partsApi.create({ ...commonData, company_id: activeCompanyId }, activeCompanyId);
const result = await partsApi.create({ ...commonData, company_id: activeCompanyId }, activeCompanyId);
console.log('Resultado de creación:', result);
if (result.error) {
console.error('Error del backend:', result.error);
error = result.error;
return;
}
}
goto('/dashboard/goods/parts');
} catch (e: any) { error = e.message || 'Error al guardar'; } finally { loading = false; }
} catch (e: any) {
console.error('Error completo:', e);
error = e.message || 'Error al guardar';
} finally { loading = false; }
}
</script>
<div class="w-full mx-auto max-w-6xl py-6 px-4 space-y-6 pb-48">
<div class="flex items-center gap-4">
<Button variant="outline" size="icon" href="/dashboard/goods/parts">
<ArrowLeft class="h-4 w-4" />
</Button>
<div>
<h1 class="text-2xl font-bold tracking-tight">{title}</h1>
<div class="space-y-3">
<div class="flex items-center justify-between">
<div class="space-y-1">
<div class="flex items-center gap-3">
<Button variant="ghost" size="icon" href="/dashboard/goods/parts">
<ArrowLeft size={20} />
</Button>
<h1 class="text-3xl font-bold tracking-tight">{title}</h1>
<Badge variant={isEdit ? "secondary" : "default"}>
{isEdit ? "Editar" : "Nueva"}
</Badge>
</div>
<p class="text-muted-foreground">
{formType === 'fa' ? 'Gestión de Activos Fijos (Q-Partes)' : 'Gestión detallada de números de parte (S-Partes).'}
{formType === 'fa' ? 'Activo Fijo' : 'Inventario'}
</p>
</div>
</div>
<Separator />
{#if error}
<div class="p-4 rounded-md bg-destructive/10 text-destructive border border-destructive/20 text-sm font-medium">
⚠️ {error}
</div>
{/if}
<div class="pb-48">
{#if formType === 'fa'}
<form onsubmit={(e) => { e.preventDefault(); handleSubmit(); }} class="space-y-6">
<Card.Root>
<Card.Content class="p-6">
<Tabs.Root value="general" class="w-full">
<Tabs.Root bind:value={activeTab} class="w-full">
<div class="min-h-[500px]">
@@ -250,10 +301,9 @@
<div class="grid gap-2">
<Label for="fa_client" class="required">Cliente Asignado</Label>
<div class="flex gap-2">
<Input id="fa_client" bind:value={formData.client_id} readonly onclick={() => showClientModal = true} class="cursor-pointer font-mono" placeholder="Seleccione..."/>
<Input id="fa_client" bind:value={selectedClientName} readonly onclick={() => showClientModal = true} class="cursor-pointer" placeholder="Seleccione..."/>
<Button variant="outline" size="icon" type="button" onclick={() => showClientModal = true}><FolderSearch class="h-4 w-4" /></Button>
</div>
{#if selectedClientName}<div class="text-xs font-semibold text-primary">{selectedClientName}</div>{/if}
</div>
</div>
@@ -288,7 +338,10 @@
<div class="grid gap-2">
<Label for="fa_origin">País Origen (ISO)</Label>
<Input id="fa_origin" bind:value={formData.origin_country} maxlength={3} placeholder="MEX"/>
<div class="flex gap-2">
<Input id="fa_origin" bind:value={selectedCountryName} readonly onclick={() => showCountryModal = true} class="cursor-pointer" placeholder="Seleccione..."/>
<Button variant="outline" size="icon" type="button" onclick={() => showCountryModal = true}><FolderSearch class="h-4 w-4" /></Button>
</div>
</div>
</div>
@@ -303,15 +356,23 @@
</div>
</div>
<div class="grid gap-2">
<Label for="fa_currency">Moneda</Label>
<Select.Root type="single" bind:value={formData.currency_key}>
<Select.Trigger id="fa_currency">{formData.currency_key}</Select.Trigger>
<Select.Content>
<Select.Item value="USD">Extranjera (USD)</Select.Item>
<Select.Item value="MXN">Nacional (MXN)</Select.Item>
<Select.Item value="EUR">Euros (EUR)</Select.Item>
</Select.Content>
</Select.Root>
<Label>Moneda</Label>
<div class="flex flex-col gap-2">
<div class="flex items-center gap-4">
<label class="flex items-center gap-2 cursor-pointer">
<input type="radio" name="fa_currency_type" value="NA" bind:group={formData.currency_type} class="h-4 w-4" />
<span class="text-sm">Nacional</span>
</label>
<label class="flex items-center gap-2 cursor-pointer">
<input type="radio" name="fa_currency_type" value="EX" bind:group={formData.currency_type} class="h-4 w-4" />
<span class="text-sm">Extranjera</span>
</label>
</div>
<Button variant="outline" size="sm" type="button" onclick={() => { formData.currency_type = 'CATALOG'; showCurrencyModal = true; }} class="w-full">
<FolderSearch class="h-4 w-4 mr-2" />
{selectedCurrencyName || 'Seleccionar del Catálogo'}
</Button>
</div>
</div>
<div class="grid gap-2">
<Label for="fa_weight">Peso Unitario</Label>
@@ -334,7 +395,10 @@
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="grid gap-2">
<Label for="fa_fraction">Fracción UMT (MX)</Label>
<Input id="fa_fraction" bind:value={formData.fraction} maxlength={10} />
<div class="flex gap-2">
<Input id="fa_fraction" bind:value={formData.fraction} readonly onclick={() => showFractionModal = true} class="cursor-pointer" placeholder="Seleccione..."/>
<Button variant="outline" size="icon" type="button" onclick={() => showFractionModal = true}><FolderSearch class="h-4 w-4" /></Button>
</div>
</div>
<div class="grid gap-2">
<Label for="fa_sector">Sector</Label>
@@ -408,32 +472,16 @@
</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">Generales</Tabs.Trigger>
<Tabs.Trigger value="cont1" class="flex gap-2 items-center justify-center">Continuación 1</Tabs.Trigger>
<Tabs.Trigger value="cont2" class="flex gap-2 items-center justify-center">Continuación 2</Tabs.Trigger>
</Tabs.List>
</Tabs.Root>
</Card.Content>
</Card.Root>
<div class="fixed bottom-0 right-0 left-0 md:left-64 p-4 border-t bg-background/95 backdrop-blur z-50">
<div class="max-w-6xl mx-auto flex justify-end gap-4">
<Button variant="ghost" href="/dashboard/goods/parts" disabled={loading}>Cancelar</Button>
<Button type="submit" disabled={loading} class="min-w-[140px] bg-amber-600 hover:bg-amber-700">
{#if loading}<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />{:else}<Save class="mr-2 h-4 w-4" />{/if}
{isEdit ? 'Actualizar Activo' : 'Guardar Activo'}
</Button>
</div>
</div>
</form>
{:else}
<form onsubmit={(e) => { e.preventDefault(); handleSubmit(); }} class="space-y-6">
<Card.Root>
<Card.Content class="p-6">
<Tabs.Root value="general" class="w-full">
<Tabs.Root bind:value={activeTab} class="w-full">
<div class="min-h-[500px]">
@@ -492,7 +540,10 @@
<div class="grid gap-2">
<Label for="country">País Origen (ISO)</Label>
<Input id="country" bind:value={formData.origin_country} maxlength={3} placeholder="MEX"/>
<div class="flex gap-2">
<Input id="country" bind:value={selectedCountryName} readonly onclick={() => showCountryModal = true} class="cursor-pointer" placeholder="Seleccione..."/>
<Button variant="outline" size="icon" type="button" onclick={() => showCountryModal = true}><FolderSearch class="h-4 w-4" /></Button>
</div>
</div>
<div class="grid gap-2">
@@ -513,15 +564,23 @@
<h3 class="font-medium text-sm text-green-800 dark:text-green-300 flex items-center gap-2"><DollarSign class="h-4 w-4"/> Costos, valores y peso unitario</h3>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<div class="grid gap-2">
<Label for="currency">Tipos de Moneda</Label>
<Select.Root type="single" bind:value={formData.currency_key}>
<Select.Trigger id="currency">{formData.currency_key}</Select.Trigger>
<Select.Content>
<Select.Item value="USD">Dólares (USD)</Select.Item>
<Select.Item value="MXN">Pesos (MXN)</Select.Item>
<Select.Item value="EUR">Euros (EUR)</Select.Item>
</Select.Content>
</Select.Root>
<Label>Tipos de Moneda</Label>
<div class="flex flex-col gap-2">
<div class="flex items-center gap-4">
<label class="flex items-center gap-2 cursor-pointer">
<input type="radio" name="inv_currency_type" value="NA" bind:group={formData.currency_type} class="h-4 w-4" />
<span class="text-sm">Nacional</span>
</label>
<label class="flex items-center gap-2 cursor-pointer">
<input type="radio" name="inv_currency_type" value="EX" bind:group={formData.currency_type} class="h-4 w-4" />
<span class="text-sm">Extranjera</span>
</label>
</div>
<Button variant="outline" size="sm" type="button" onclick={() => { formData.currency_type = 'CATALOG'; showCurrencyModal = true; }} class="w-full">
<FolderSearch class="h-4 w-4 mr-2" />
{selectedCurrencyName || 'Seleccionar del Catálogo'}
</Button>
</div>
</div>
<div class="grid gap-2">
<Label for="unit_cost">Costo Unitario</Label>
@@ -617,14 +676,13 @@
<div class="flex gap-2">
<div class="relative flex-1">
<UserCheck class="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
<Input type="number" id="client_id" bind:value={formData.client_id} class="pl-9 font-mono" placeholder="Seleccione un cliente..." readonly onclick={() => showClientModal = true}/>
<Input id="client_id" bind:value={selectedClientName} class="pl-9" placeholder="Seleccione un cliente..." readonly onclick={() => showClientModal = true}/>
</div>
<Button variant="outline" class="shrink-0" type="button" onclick={() => showClientModal = true}><FolderSearch class="h-4 w-4 mr-2" /> Buscar</Button>
</div>
{#if selectedClientName}
<div class="flex items-center gap-2 mt-1 px-3 py-2 bg-slate-50 dark:bg-slate-900/50 border rounded-md text-sm">
<span class="font-semibold text-primary">{selectedClientName}</span>
{#if selectedClientStatus}<span class="text-green-600 flex items-center gap-1 text-xs font-medium"><CheckCircle2 class="h-3 w-3"/> Activo</span>{:else}<span class="text-red-600 flex items-center gap-1 text-xs font-medium"><XCircle class="h-3 w-3"/> Inactivo</span>{/if}
<div class="flex items-center gap-2 text-xs">
{#if selectedClientStatus}<span class="text-green-600 flex items-center gap-1 font-medium"><CheckCircle2 class="h-3 w-3"/> Activo</span>{:else}<span class="text-red-600 flex items-center gap-1 font-medium"><XCircle class="h-3 w-3"/> Inactivo</span>{/if}
</div>
{/if}
</div>
@@ -647,7 +705,10 @@
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="grid gap-2">
<Label for="fraction_mx" class="required">Fracción Arancelaria (MX)</Label>
<Input id="fraction_mx" bind:value={formData.fraction} maxlength={10} />
<div class="flex gap-2">
<Input id="fraction_mx" bind:value={formData.fraction} readonly onclick={() => showFractionModal = true} class="cursor-pointer" placeholder="Seleccione..."/>
<Button variant="outline" size="icon" type="button" onclick={() => showFractionModal = true}><FolderSearch class="h-4 w-4" /></Button>
</div>
</div>
<div class="grid gap-2">
<Label for="eccn">ECCN</Label>
@@ -674,27 +735,71 @@
</Tabs.Content>
</div>
<Tabs.List class="grid grid-cols-4 fixed bottom-24 left-1/2 -translate-x-1/2 w-[95%] max-w-2xl z-40 shadow-2xl bg-background border p-1 rounded-xl">
<Tabs.Trigger value="general" class="flex gap-2 items-center justify-center"><Package class="h-4 w-4 hidden sm:block" /> General</Tabs.Trigger>
<Tabs.Trigger value="opciones" class="flex gap-2 items-center justify-center"><Settings class="h-4 w-4 hidden sm:block" /> Opciones</Tabs.Trigger>
<Tabs.Trigger value="opcionales2" class="flex gap-2 items-center justify-center"><FileText class="h-4 w-4 hidden sm:block" /> Opcionales 2</Tabs.Trigger>
<Tabs.Trigger value="otros" class="flex gap-2 items-center justify-center"><Settings 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">
<div class="max-w-6xl mx-auto flex justify-end gap-4">
<Button variant="ghost" href="/dashboard/goods/parts" 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" />{:else}<Save class="mr-2 h-4 w-4" />{/if}
{isEdit ? 'Actualizar' : 'Guardar'}
</Button>
</div>
</div>
</form>
{/if}
</div>
</div>
<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] group-has-data-[state=collapsed]/sidebar-wrapper:ml-[calc(var(--sidebar-width-icon))] ml-[calc(var(--sidebar-width))]">
<div class="px-4 py-4 space-y-4 max-w-[1400px] mx-auto">
<Tabs.Root bind:value={activeTab}>
<div class="w-full overflow-x-auto pb-2">
{#if formType === 'fa'}
<Tabs.List class="inline-flex md:grid md:w-full md:grid-cols-3">
<Tabs.Trigger value="general" class="whitespace-nowrap">
<Package size={16} class="mr-2" />
General
</Tabs.Trigger>
<Tabs.Trigger value="cont1" class="whitespace-nowrap">
<FileText size={16} class="mr-2" />
Continuación 1
</Tabs.Trigger>
<Tabs.Trigger value="cont2" class="whitespace-nowrap">
<Settings size={16} class="mr-2" />
Continuación 2
</Tabs.Trigger>
</Tabs.List>
{:else}
<Tabs.List class="inline-flex md:grid md:w-full md:grid-cols-4">
<Tabs.Trigger value="general" class="whitespace-nowrap">
<Package size={16} class="mr-2" />
General
</Tabs.Trigger>
<Tabs.Trigger value="opciones" class="whitespace-nowrap">
<Settings size={16} class="mr-2" />
Opciones
</Tabs.Trigger>
<Tabs.Trigger value="opcionales2" class="whitespace-nowrap">
<FileText size={16} class="mr-2" />
Opcionales 2
</Tabs.Trigger>
<Tabs.Trigger value="otros" class="whitespace-nowrap">
<DollarSign size={16} class="mr-2" />
Otros
</Tabs.Trigger>
</Tabs.List>
{/if}
</div>
</Tabs.Root>
<div class="flex justify-end gap-3">
<Button type="button" variant="outline" href="/dashboard/goods/parts" disabled={loading}>
Cancelar
</Button>
<Button type="button" onclick={handleSubmit} disabled={loading}>
{#if loading}
<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
Guardando...
{:else}
<Save size={16} class="mr-2" />
{isEdit ? 'Actualizar' : 'Guardar'}
{/if}
</Button>
</div>
</div>
</div>
<ClientSelectorDialog bind:open={showClientModal} onSelect={handleClientSelect} />
@@ -702,6 +807,9 @@
<MaterialTypeSelectorDialog bind:open={showMaterialModal} onSelect={handleMaterialSelect} />
<UnitMeasureSelectorDialog bind:open={showUOMModal} onSelect={handleUOMSelect} />
<UnitMeasureSelectorDialog bind:open={showAltUOMModal} onSelect={handleAltUOMSelect} />
<CurrencySelectorDialog bind:open={showCurrencyModal} onSelect={handleCurrencySelect} />
<CountrySelectorDialog bind:open={showCountryModal} onSelect={handleCountrySelect} />
<FractionSelectorDialog bind:open={showFractionModal} onSelect={handleFractionSelect} />
<style>
:global(.required::after) {

View File

@@ -1,184 +1,325 @@
<script lang="ts">
import { onMount } from 'svelte';
import { partsApi, type Part } from '$lib/api/dashboard/a76/parts';
import DataTable from '$lib/components/dashboard/goods/parts/data-table.svelte';
import { createColumns } from '$lib/components/dashboard/goods/parts/columns.js';
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';
import { companyStore } from '$lib/stores/company.svelte';
import { Plus, Search, RefreshCw, Loader2, Trash2 } from 'lucide-svelte';
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';
import { Label } from '$lib/components/ui/label';
import { Plus, RefreshCw, Package } from 'lucide-svelte';
import { toast } from 'svelte-sonner';
import { partsApi, type Part } from '$lib/api/dashboard/a76/parts';
import { companyStore } from '$lib/stores/company.svelte';
// 1. ESTADOS
let partsList = $state<Part[]>([]);
let listLoading = $state(false);
let listError = $state<string | null>(null);
// Estado de la lista de partes
let parts = $state<Part[]>([]);
let selectedPart = $state<Part | null>(null);
let isLoading = $state(false);
let searchPartNumber = $state('');
let searchDescription = $state('');
let searchClient = $state('');
let searchClass = $state('');
// Estado Búsqueda
let searchCode = $state('');
let searchResults = $state<Part[]>([]); // Array para guardar los resultados
let searchLoading = $state(false);
let isSearching = $state(false); // Para saber si estamos viendo resultados de búsqueda
// Partes filtradas según búsqueda
const filteredParts = $derived(
parts.filter((p) => {
// Filtro por número de parte
const matchesPartNumber = !searchPartNumber ||
p.part_number.toLowerCase().includes(searchPartNumber.toLowerCase());
// Filtro por descripción (español o inglés)
const matchesDescription = !searchDescription ||
(p.description_spanish?.toLowerCase().includes(searchDescription.toLowerCase()) ?? false) ||
(p.description_english?.toLowerCase().includes(searchDescription.toLowerCase()) ?? false);
// Filtro por cliente
const matchesClient = !searchClient ||
(p.client_id?.toString().includes(searchClient) ?? false);
// Filtro por clase
const matchesClass = !searchClass ||
(p.part_class?.toLowerCase().includes(searchClass.toLowerCase()) ?? false);
return matchesPartNumber && matchesDescription && matchesClient && matchesClass;
})
);
// 2. CARGA DE DATOS (Lista Completa)
async function loadParts() {
const companyId = companyStore.activeCompany?.id;
if (!companyId) return;
// Reactively load parts when company changes
$effect(() => {
const companyId = companyStore.activeCompany?.id;
if (companyId) {
loadParts();
}
});
listLoading = true;
listError = null;
isSearching = false; // Reseteamos modo búsqueda
searchResults = [];
async function loadParts() {
const companyId = companyStore.activeCompany?.id;
if (!companyId) {
return;
}
try {
const response = await partsApi.list({
company_id: companyId,
page: 1,
page_size: 100
});
isLoading = true;
try {
const response = await partsApi.list({
company_id: companyId,
page: 1,
page_size: 1000
});
if (response.data) {
partsList = response.data.items || [];
} else if (response.error) {
listError = response.error;
}
} catch (e) {
listError = 'Error de conexión con el servidor';
} finally {
listLoading = false;
}
}
if (response.data) {
parts = response.data.items || [];
}
} catch (error) {
console.error('Error cargando partes:', error);
toast.error('Error al cargar las partes');
} finally {
isLoading = false;
}
}
// 3. REACTIVIDAD DE COMPAÑÍA
$effect(() => {
if (companyStore.activeCompany) {
loadParts();
}
});
function selectPart(part: Part) {
selectedPart = part;
}
// 4. BÚSQUEDA MANUAL
async function handleSearch() {
if (!searchCode.trim()) return;
searchLoading = true;
listError = null; // Limpiamos errores previos
const companyId = companyStore.activeCompany?.id;
if (!companyId) return;
async function handleRefresh() {
await loadParts();
toast.success('Partes actualizadas');
}
try {
const response = await partsApi.list({
company_id: companyId,
q: searchCode.trim()
});
const results = response.data?.items || [];
if (results.length > 0) {
searchResults = results; // Guardamos TODOS los resultados
isSearching = true; // Activamos modo búsqueda
} else {
listError = "No se encontraron partes con ese criterio";
searchResults = [];
isSearching = true; // Aún en modo búsqueda, pero vacía
}
} catch (e) {
listError = "Error en la búsqueda";
} finally {
searchLoading = false;
}
}
function clearSearch() {
searchCode = '';
searchResults = [];
isSearching = false;
listError = null;
loadParts(); // Recargamos la lista completa
}
const columns = createColumns(loadParts);
// Si estamos buscando, mostramos searchResults, si no, la lista completa
const tableData = $derived(isSearching ? searchResults : partsList);
function handleDelete() {
if (!selectedPart) {
toast.error('Selecciona una parte para borrar');
return;
}
// TODO: Implementar eliminación
toast.info('Función de eliminación pendiente');
}
</script>
<div class="space-y-6 p-4">
<div class="flex items-center justify-between">
<div>
<h1 class="text-3xl font-bold tracking-tight">Catálogo de Partes</h1>
<p class="text-muted-foreground">Gestiona las partes y componentes del sistema.</p>
</div>
<div class="flex gap-2">
<Button variant="outline" onclick={loadParts} disabled={listLoading}>
<RefreshCw class="mr-2 h-4 w-4 {listLoading ? 'animate-spin' : ''}" />
Actualizar
</Button>
<Button href="/dashboard/goods/parts/edit">
<Plus class="mr-2 h-4 w-4" />
Nueva Parte
</Button>
</div>
</div>
<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">CATÁLOGO DE PARTES</h1>
<p class="text-sm text-muted-foreground">
Gestiona y consulta las partes de inventario y activo fijo
</p>
</div>
<Card.Root>
<Card.Header>
<Card.Title>Búsqueda Rápida</Card.Title>
<Card.Description>Ingresa el número de parte o descripción para filtrar.</Card.Description>
</Card.Header>
<Card.Content>
<div class="flex gap-4">
<div class="flex-1 max-w-xl">
<Input
bind:value={searchCode}
placeholder="Buscar por número de parte o descripción..."
onkeydown={(e) => e.key === 'Enter' && handleSearch()}
/>
</div>
<Button onclick={handleSearch} disabled={searchLoading}>
{#if searchLoading}
<Loader2 class="mr-2 h-4 w-4 animate-spin" />
Buscando...
{:else}
<Search class="mr-2 h-4 w-4" />
Buscar
{/if}
</Button>
{#if isSearching || searchCode}
<Button variant="ghost" onclick={clearSearch}>
<Trash2 class="mr-2 h-4 w-4" />
Limpiar
</Button>
{/if}
</div>
</Card.Content>
</Card.Root>
<!-- Contenedor principal con grid y detalles -->
<div class="flex-1 flex gap-4 overflow-hidden">
<!-- Panel izquierdo: Grid/Tabla de partes -->
<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 partes 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">Número de Parte</Label>
<Input
bind:value={searchPartNumber}
placeholder="Ej: PART-001"
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">Cliente</Label>
<Input
bind:value={searchClient}
placeholder="ID de cliente..."
class="h-9"
/>
</div>
<div class="space-y-2">
<Label class="text-xs">Clase</Label>
<Input
bind:value={searchClass}
placeholder="Clase..."
class="h-9"
/>
</div>
</div>
</div>
</div>
<Card.Root>
<Card.Header>
<Card.Title>
{#if isSearching}
Resultados de la búsqueda ({searchResults.length})
{:else}
Listado General ({partsList.length} registros)
{/if}
</Card.Title>
</Card.Header>
<Card.Content>
{#if listError}
<div class="bg-destructive/10 text-destructive p-4 rounded-lg border border-destructive/20 mb-4">
{listError}
</div>
{/if}
<DataTable
data={tableData}
{columns}
loading={listLoading || searchLoading}
hasMore={false}
loadMore={() => {}}
/>
</Card.Content>
</Card.Root>
<!-- Tabla de partes -->
<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 Partes</h2>
<div class="flex items-center gap-2">
<span class="text-xs text-muted-foreground">
Mostrando {filteredParts.length} registros
</span>
<Button variant="outline" size="sm" onclick={handleRefresh}>
<RefreshCw class="h-4 w-4 mr-2" />
Actualizar
</Button>
</div>
</div>
<!-- Tabla de partes -->
<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">Número de Parte</th>
<th class="px-2 py-2 text-left">Descripción</th>
<th class="px-2 py-2 text-left">Cliente</th>
<th class="px-2 py-2 text-left">Clase</th>
<th class="px-2 py-2 text-left">U.M.</th>
<th class="px-2 py-2 text-left">Fracción</th>
</tr>
</thead>
<tbody>
{#if isLoading}
<tr>
<td colspan="7" class="text-center py-8 text-muted-foreground">Cargando...</td>
</tr>
{:else if filteredParts.length === 0}
<tr>
<td colspan="7" class="text-center py-8 text-muted-foreground">
No hay partes registradas
</td>
</tr>
{:else}
{#each filteredParts as part (part.id)}
<tr
class="border-b cursor-pointer transition-colors {selectedPart?.id ===
part.id
? 'bg-gray-300 dark:bg-gray-600'
: 'hover:bg-gray-100 dark:hover:bg-gray-700'}"
onclick={() => selectPart(part)}
>
<td class="px-2 py-1">
<input
type="checkbox"
checked={selectedPart?.id === part.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">
{part.part_number}
</span>
</td>
<td class="px-2 py-1 font-medium text-sm">{part.description_spanish || ''}</td>
<td class="px-2 py-1 text-muted-foreground">{part.client_id || '-'}</td>
<td class="px-2 py-1">
{#if part.part_class}
<span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-400">
{part.part_class}
</span>
{:else}
<span class="text-muted-foreground">-</span>
{/if}
</td>
<td class="px-2 py-1 text-muted-foreground">{part.unit_of_measure || '-'}</td>
<td class="px-2 py-1 font-mono text-xs text-orange-600 dark:text-orange-400">{part.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">Número de Parte</p>
<h2 class="text-3xl font-black font-mono tracking-tighter">
{selectedPart?.part_number || '---'}
</h2>
</div>
<div class="flex-1 overflow-auto p-5 space-y-6 bg-card">
{#if selectedPart}
<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">{selectedPart.description_spanish || '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">{selectedPart.description_english || '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">Cliente</Label>
<div class="flex items-center gap-2">
<Package class="h-3 w-3 text-blue-500" />
<span class="text-sm font-bold">{selectedPart.client_id || '-'}</span>
</div>
</div>
<div class="space-y-1">
<Label class="text-[10px] uppercase text-muted-foreground font-bold">Clase</Label>
<span class="text-sm font-bold">{selectedPart.part_class || '-'}</span>
</div>
</div>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-1">
<Label class="text-[10px] uppercase text-muted-foreground font-bold">U.M.</Label>
<span class="text-sm font-bold">{selectedPart.unit_of_measure || '-'}</span>
</div>
<div class="space-y-1">
<Label class="text-[10px] uppercase text-muted-foreground font-bold">Peso Unit.</Label>
<span class="text-sm font-bold">{selectedPart.unit_weight || '-'}</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">
{selectedPart.fraction || '0000.00.00'}
</p>
</div>
{#if selectedPart.unit_cost}
<div class="p-3 bg-green-50 dark:bg-green-950/20 rounded-lg border border-green-100 dark:border-green-900">
<Label class="text-[10px] uppercase text-green-600 dark:text-green-400 font-bold">Costo Unitario</Label>
<p class="text-lg font-bold text-green-700 dark:text-green-300">
${selectedPart.unit_cost} {selectedPart.currency_key || 'USD'}
</p>
</div>
{/if}
{:else}
<div class="flex flex-col items-center justify-center h-full text-center text-muted-foreground">
<Package class="h-12 w-12 mb-3 opacity-20" />
<p class="text-sm">Selecciona una parte para ver sus detalles</p>
</div>
{/if}
</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] group-has-data-[state=collapsed]/sidebar-wrapper:ml-[calc(var(--sidebar-width-icon))] ml-[calc(var(--sidebar-width))]">
<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" href="/dashboard/goods/parts/edit">
<Plus class="h-4 w-4 mr-1" />
Nueva Parte
</Button>
<Button variant="outline" size="sm" href="/dashboard/goods/parts/edit/{selectedPart?.id}" disabled={!selectedPart}>Editar</Button>
<Button variant="outline" size="sm" onclick={handleDelete} disabled={!selectedPart}>Borrar</Button>
</div>
</div>
</div>

View File

@@ -0,0 +1,184 @@
<script lang="ts">
import { onMount } from 'svelte';
import { partsApi, type Part } from '$lib/api/dashboard/a76/parts';
import DataTable from '$lib/components/dashboard/goods/parts/data-table.svelte';
import { createColumns } from '$lib/components/dashboard/goods/parts/columns.js';
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';
import { companyStore } from '$lib/stores/company.svelte';
import { Plus, Search, RefreshCw, Loader2, Trash2 } from 'lucide-svelte';
// 1. ESTADOS
let partsList = $state<Part[]>([]);
let listLoading = $state(false);
let listError = $state<string | null>(null);
// Estado Búsqueda
let searchCode = $state('');
let searchResults = $state<Part[]>([]); // Array para guardar los resultados
let searchLoading = $state(false);
let isSearching = $state(false); // Para saber si estamos viendo resultados de búsqueda
// 2. CARGA DE DATOS (Lista Completa)
async function loadParts() {
const companyId = companyStore.activeCompany?.id;
if (!companyId) return;
listLoading = true;
listError = null;
isSearching = false; // Reseteamos modo búsqueda
searchResults = [];
try {
const response = await partsApi.list({
company_id: companyId,
page: 1,
page_size: 100
});
if (response.data) {
partsList = response.data.items || [];
} else if (response.error) {
listError = response.error;
}
} catch (e) {
listError = 'Error de conexión con el servidor';
} finally {
listLoading = false;
}
}
// 3. REACTIVIDAD DE COMPAÑÍA
$effect(() => {
if (companyStore.activeCompany) {
loadParts();
}
});
// 4. BÚSQUEDA MANUAL
async function handleSearch() {
if (!searchCode.trim()) return;
searchLoading = true;
listError = null; // Limpiamos errores previos
const companyId = companyStore.activeCompany?.id;
if (!companyId) return;
try {
const response = await partsApi.list({
company_id: companyId,
q: searchCode.trim()
});
const results = response.data?.items || [];
if (results.length > 0) {
searchResults = results; // Guardamos TODOS los resultados
isSearching = true; // Activamos modo búsqueda
} else {
listError = "No se encontraron partes con ese criterio";
searchResults = [];
isSearching = true; // Aún en modo búsqueda, pero vacía
}
} catch (e) {
listError = "Error en la búsqueda";
} finally {
searchLoading = false;
}
}
function clearSearch() {
searchCode = '';
searchResults = [];
isSearching = false;
listError = null;
loadParts(); // Recargamos la lista completa
}
const columns = createColumns(loadParts);
// Si estamos buscando, mostramos searchResults, si no, la lista completa
const tableData = $derived(isSearching ? searchResults : partsList);
</script>
<div class="space-y-6 p-4">
<div class="flex items-center justify-between">
<div>
<h1 class="text-3xl font-bold tracking-tight">Catálogo de Partes</h1>
<p class="text-muted-foreground">Gestiona las partes y componentes del sistema.</p>
</div>
<div class="flex gap-2">
<Button variant="outline" onclick={loadParts} disabled={listLoading}>
<RefreshCw class="mr-2 h-4 w-4 {listLoading ? 'animate-spin' : ''}" />
Actualizar
</Button>
<Button href="/dashboard/goods/parts/edit">
<Plus class="mr-2 h-4 w-4" />
Nueva Parte
</Button>
</div>
</div>
<Card.Root>
<Card.Header>
<Card.Title>Búsqueda Rápida</Card.Title>
<Card.Description>Ingresa el número de parte o descripción para filtrar.</Card.Description>
</Card.Header>
<Card.Content>
<div class="flex gap-4">
<div class="flex-1 max-w-xl">
<Input
bind:value={searchCode}
placeholder="Buscar por número de parte o descripción..."
onkeydown={(e) => e.key === 'Enter' && handleSearch()}
/>
</div>
<Button onclick={handleSearch} disabled={searchLoading}>
{#if searchLoading}
<Loader2 class="mr-2 h-4 w-4 animate-spin" />
Buscando...
{:else}
<Search class="mr-2 h-4 w-4" />
Buscar
{/if}
</Button>
{#if isSearching || searchCode}
<Button variant="ghost" onclick={clearSearch}>
<Trash2 class="mr-2 h-4 w-4" />
Limpiar
</Button>
{/if}
</div>
</Card.Content>
</Card.Root>
<Card.Root>
<Card.Header>
<Card.Title>
{#if isSearching}
Resultados de la búsqueda ({searchResults.length})
{:else}
Listado General ({partsList.length} registros)
{/if}
</Card.Title>
</Card.Header>
<Card.Content>
{#if listError}
<div class="bg-destructive/10 text-destructive p-4 rounded-lg border border-destructive/20 mb-4">
{listError}
</div>
{/if}
<DataTable
data={tableData}
{columns}
loading={listLoading || searchLoading}
hasMore={false}
loadMore={() => {}}
/>
</Card.Content>
</Card.Root>
</div>