Se termino deintegrar el crud de partes y clases

This commit is contained in:
2026-01-05 17:37:20 -06:00
parent e84a030aec
commit 8d189aaaf1
12 changed files with 1843 additions and 860 deletions

View File

@@ -1,232 +1,78 @@
"""
DTOs (Data Transfer Objects) para módulo de partes/componentes
Reemplaza schemas.py siguiendo enfoque DDD y estilo NestJS
"""
from datetime import datetime
from decimal import Decimal
from typing import Optional
from typing import List, Optional
from pydantic import BaseModel, Field
class PartCreateDTO(BaseModel):
"""DTO para crear una parte"""
client_id: int = Field(..., description="Client key")
part_number: str = Field(..., max_length=49, description="Part number")
fraction: Optional[str] = Field(None, max_length=10, description="Tariff fraction")
description_spanish: Optional[str] = Field(
None, max_length=500, description="Description in Spanish"
)
description_english: Optional[str] = Field(
None, max_length=500, description="Description in English"
)
part_class: Optional[str] = Field(None, max_length=8, description="Part class")
unit_of_measure: Optional[str] = Field(
None, max_length=5, description="Unit of measure"
)
commercial_part_number: Optional[str] = Field(
None, max_length=70, description="Commercial part number"
)
country_of_origin: Optional[str] = Field(
None, max_length=3, description="Country of origin code"
)
# Pricing and currency
unit_cost: Optional[Decimal] = Field(None, description="Unit cost")
currency_type: Optional[str] = Field(
None, max_length=2, description="Currency type"
)
currency_key: Optional[str] = Field(None, max_length=3, description="Currency key")
# Weight information
unit_weight: Optional[Decimal] = Field(None, description="Unit weight")
weight_type: Optional[str] = Field(None, max_length=6, description="Weight type")
# Classification and regulatory
us_fraction: Optional[str] = Field(
None, max_length=16, description="US tariff fraction"
)
fda_key: Optional[str] = Field(None, max_length=20, description="FDA key")
fcc_key: Optional[str] = Field(None, max_length=30, description="FCC key")
license_code: Optional[str] = Field(None, max_length=3, description="License code")
eccn: Optional[str] = Field(
None, max_length=20, description="Export Control Classification Number"
)
export_code: Optional[str] = Field(None, max_length=2, description="Export code")
exclusion_symbol: Optional[str] = Field(
None, max_length=19, description="Exclusion symbol"
)
# Additional information
supplier: Optional[str] = Field(None, max_length=14, description="Supplier")
alternate_unit_measure: Optional[str] = Field(
None, max_length=14, description="Alternate unit of measure"
)
added_value: Optional[Decimal] = Field(None, description="Added value")
# Status and media
is_active: Optional[bool] = Field(None, description="Enabled/Disabled status")
creation_date: Optional[int] = Field(None, description="Creation date")
part_photo: Optional[str] = Field(
None, max_length=255, description="Part photo URL"
)
class Config:
from_attributes = True
client_id: int
part_number: str = Field(..., max_length=50)
description_spanish: Optional[str] = None
description_english: Optional[str] = None
part_class: Optional[str] = None
unit_of_measure: Optional[str] = "PZ"
commercial_part_number: Optional[str] = None
country_of_origin: Optional[str] = "MEX"
unit_cost: Optional[Decimal] = Decimal("0.0")
currency_key: Optional[str] = "USD"
unit_weight: Optional[Decimal] = Decimal("0.0")
weight_type: Optional[str] = "KG"
fraction: Optional[str] = None
us_fraction: Optional[str] = None
supplier: Optional[str] = None
fda_key: Optional[str] = None
fcc_key: Optional[str] = None
eccn: Optional[str] = None
is_active: Optional[bool] = True
class PartUpdateDTO(BaseModel):
"""DTO para actualizar una parte"""
fraction: Optional[str] = Field(None, max_length=10, description="Tariff fraction")
description_spanish: Optional[str] = Field(
None, max_length=500, description="Description in Spanish"
)
description_english: Optional[str] = Field(
None, max_length=500, description="Description in English"
)
part_class: Optional[str] = Field(None, max_length=8, description="Part class")
unit_of_measure: Optional[str] = Field(
None, max_length=5, description="Unit of measure"
)
commercial_part_number: Optional[str] = Field(
None, max_length=70, description="Commercial part number"
)
country_of_origin: Optional[str] = Field(
None, max_length=3, description="Country of origin code"
)
# Pricing and currency
unit_cost: Optional[Decimal] = Field(None, description="Unit cost")
currency_type: Optional[str] = Field(
None, max_length=2, description="Currency type"
)
currency_key: Optional[str] = Field(None, max_length=3, description="Currency key")
# Weight information
unit_weight: Optional[Decimal] = Field(None, description="Unit weight")
weight_type: Optional[str] = Field(None, max_length=6, description="Weight type")
# Classification and regulatory
us_fraction: Optional[str] = Field(
None, max_length=16, description="US tariff fraction"
)
fda_key: Optional[str] = Field(None, max_length=20, description="FDA key")
fcc_key: Optional[str] = Field(None, max_length=30, description="FCC key")
license_code: Optional[str] = Field(None, max_length=3, description="License code")
eccn: Optional[str] = Field(
None, max_length=20, description="Export Control Classification Number"
)
export_code: Optional[str] = Field(None, max_length=2, description="Export code")
exclusion_symbol: Optional[str] = Field(
None, max_length=19, description="Exclusion symbol"
)
# Additional information
supplier: Optional[str] = Field(None, max_length=14, description="Supplier")
alternate_unit_measure: Optional[str] = Field(
None, max_length=14, description="Alternate unit of measure"
)
added_value: Optional[Decimal] = Field(None, description="Added value")
# Status and media
is_active: Optional[bool] = Field(None, description="Enabled/Disabled status")
part_photo: Optional[str] = Field(
None, max_length=255, description="Part photo URL"
)
class Config:
from_attributes = True
class PartResponseDTO(BaseModel):
"""DTO para respuesta de parte"""
client_id: int
part_number: str
fraction: Optional[str] = None
description_spanish: Optional[str] = None
description_english: Optional[str] = None
part_class: Optional[str] = None
unit_of_measure: Optional[str] = None
commercial_part_number: Optional[str] = None
country_of_origin: Optional[str] = None
# Pricing and currency
unit_cost: Optional[Decimal] = None
currency_type: Optional[str] = None
currency_key: Optional[str] = None
# Weight information
unit_weight: Optional[Decimal] = None
weight_type: Optional[str] = None
# Classification and regulatory
fraction: Optional[str] = None
us_fraction: Optional[str] = None
supplier: Optional[str] = None
fda_key: Optional[str] = None
fcc_key: Optional[str] = None
license_code: Optional[str] = None
eccn: Optional[str] = None
export_code: Optional[str] = None
exclusion_symbol: Optional[str] = None
# Additional information
supplier: Optional[str] = None
alternate_unit_measure: Optional[str] = None
added_value: Optional[Decimal] = None
# Status and dates
is_active: Optional[bool] = None
creation_date: Optional[int] = None
modification_date: Optional[int] = None
modification_date_iso: Optional[datetime] = None
# Media
part_photo: Optional[str] = None
class PartResponseDTO(PartCreateDTO):
id: int
tenant_id: int
company_id: int
creation_date: Optional[int] = None
modification_date_iso: Optional[datetime] = None
class Config:
from_attributes = True
class PartBasicDTO(BaseModel):
"""DTO para información básica de parte"""
id: int
client_id: int
part_number: str
description_spanish: Optional[str] = None
description_english: Optional[str] = None
part_class: Optional[str] = None
unit_cost: Optional[Decimal] = None
currency_key: Optional[str] = None
is_active: Optional[bool] = None
is_active: Optional[bool] = True
class Config:
from_attributes = True
class PartListDTO(BaseModel):
"""DTO para lista de partes"""
parts: list[PartBasicDTO]
parts: List[PartBasicDTO]
total: int
page: int
size: int
class Config:
from_attributes = True
class PartSearchDTO(BaseModel):
"""DTO para búsqueda de partes"""
client_id: Optional[int] = Field(None, description="Filter by client key")
part_number: Optional[str] = Field(None, description="Search by part number")
description: Optional[str] = Field(None, description="Search in descriptions")
fraction: Optional[str] = Field(None, description="Filter by tariff fraction")
supplier: Optional[str] = Field(None, description="Filter by supplier")
enabled_only: bool = Field(False, description="Show only enabled parts")
class Config:
from_attributes = True
client_id: Optional[int] = None
part_number: Optional[str] = None
description: Optional[str] = None
fraction: Optional[str] = None
supplier: Optional[str] = None
enabled_only: bool = False

View File

@@ -1,393 +1,22 @@
"""
Endpoints API para gestión de partes/componentes
Endpoints API para gestión de partes (SCAII)
"""
# ESTA ES LA LÍNEA QUE FALTA:
from api.v1.common.tenant_crud_routes import TenantCRUDRoutes
from typing import List, Optional
from core.database import get_core_db
from core.security import get_current_user
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from .dto import (
PartBasicDTO,
PartCreateDTO,
PartListDTO,
PartResponseDTO,
PartSearchDTO,
PartUpdateDTO,
)
from .dto import PartCreateDTO, PartResponseDTO, PartUpdateDTO
from .service import PartService
router = APIRouter(prefix="/parts")
@router.post("/", response_model=PartResponseDTO, status_code=status.HTTP_201_CREATED)
async def create_part(
part_data: PartCreateDTO,
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
"""
Create a new part in the system
"""
# Validate access to the tenant and company
tenant_id = current_user.get("tenant_id")
company_id = current_user.get("company_id")
if not tenant_id or not company_id:
raise HTTPException(
status_code=403, detail="Access denied: Tenant or Company not found"
)
service = PartService(db)
return service.create_part(part_data)
@router.get("/", response_model=PartListDTO)
async def list_parts(
skip: int = Query(0, ge=0, description="Number of records to skip"),
limit: int = Query(
100, ge=1, le=1000, description="Maximum number of records to return"
),
client_id: Optional[int] = Query(None, description="Filter by client key"),
part_number: Optional[str] = Query(None, description="Search by part number"),
description: Optional[str] = Query(None, description="Search in descriptions"),
fraction: Optional[str] = Query(None, description="Filter by tariff fraction"),
supplier: Optional[str] = Query(None, description="Filter by supplier"),
enabled_only: bool = Query(False, description="Show only enabled parts"),
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
"""
List parts with optional filters and pagination
"""
# Validate access to the tenant and company
tenant_id = current_user.get("tenant_id")
company_id = current_user.get("company_id")
if not tenant_id or not company_id:
raise HTTPException(
status_code=403, detail="Access denied: Tenant or Company not found"
)
service = PartService(db)
search_params = PartSearchDTO(
client_id=client_id,
part_number=part_number,
description=description,
fraction=fraction,
supplier=supplier,
enabled_only=enabled_only,
)
return service.list_parts(skip, limit, search_params)
@router.get("/client/{client_id}", response_model=List[PartBasicDTO])
async def get_parts_by_client(
client_id: int,
skip: int = Query(0, ge=0),
limit: int = Query(100, ge=1, le=1000),
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
"""
Get all parts for a specific client
"""
# Validate access to the tenant and company
tenant_id = current_user.get("tenant_id")
company_id = current_user.get("company_id")
if not tenant_id or not company_id:
raise HTTPException(
status_code=403, detail="Access denied: Tenant or Company not found"
)
service = PartService(db)
return service.search_by_client(client_id, skip, limit)
@router.get("/search/fraction/{fraction}", response_model=List[PartBasicDTO])
async def search_by_fraction(
fraction: str,
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
"""
Search parts by tariff fraction
"""
# Validate access to the tenant and company
tenant_id = current_user.get("tenant_id")
company_id = current_user.get("company_id")
if not tenant_id or not company_id:
raise HTTPException(
status_code=403, detail="Access denied: Tenant or Company not found"
)
service = PartService(db)
return service.search_by_fraction(fraction)
@router.get("/search/supplier/{supplier}", response_model=List[PartBasicDTO])
async def search_by_supplier(
supplier: str,
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
"""
Search parts by supplier
"""
# Validate access to the tenant and company
tenant_id = current_user.get("tenant_id")
company_id = current_user.get("company_id")
if not tenant_id or not company_id:
raise HTTPException(
status_code=403, detail="Access denied: Tenant or Company not found"
)
service = PartService(db)
return service.search_by_supplier(supplier)
@router.get("/search/country/{country_code}", response_model=List[PartBasicDTO])
async def get_parts_by_country(
country_code: str,
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
"""
Get parts by country of origin
"""
# Validate access to the tenant and company
tenant_id = current_user.get("tenant_id")
company_id = current_user.get("company_id")
if not tenant_id or not company_id:
raise HTTPException(
status_code=403, detail="Access denied: Tenant or Company not found"
)
service = PartService(db)
return service.get_parts_by_country(country_code)
@router.get("/statistics", response_model=dict)
async def get_parts_statistics(
db: Session = Depends(get_core_db), current_user: dict = Depends(get_current_user)
):
"""
Get basic parts statistics
"""
# Validate access to the tenant and company
tenant_id = current_user.get("tenant_id")
company_id = current_user.get("company_id")
if not tenant_id or not company_id:
raise HTTPException(
status_code=403, detail="Access denied: Tenant or Company not found"
)
service = PartService(db)
return service.get_parts_statistics()
@router.get("/{client_id}/{part_number}", response_model=PartResponseDTO)
async def get_part(
client_id: int,
part_number: str,
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
"""
Get part by composite key (client_id + part_number)
"""
# Validate access to the tenant and company
tenant_id = current_user.get("tenant_id")
company_id = current_user.get("company_id")
if not tenant_id or not company_id:
raise HTTPException(
status_code=403, detail="Access denied: Tenant or Company not found"
)
service = PartService(db)
part = service.get_part(client_id, part_number)
if not part:
raise HTTPException(
status_code=404,
detail=f"Part with client_id '{client_id}' and part_number '{part_number}' not found",
)
return part
@router.put("/{client_id}/{part_number}", response_model=PartResponseDTO)
async def update_part(
client_id: int,
part_number: str,
part_data: PartUpdateDTO,
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
"""
Update part information
"""
# Validate access to the tenant and company
tenant_id = current_user.get("tenant_id")
company_id = current_user.get("company_id")
if not tenant_id or not company_id:
raise HTTPException(
status_code=403, detail="Access denied: Tenant or Company not found"
)
service = PartService(db)
part = service.update_part(client_id, part_number, part_data)
if not part:
raise HTTPException(
status_code=404,
detail=f"Part with client_id '{client_id}' and part_number '{part_number}' not found",
)
return part
@router.delete("/{client_id}/{part_number}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_part(
client_id: int,
part_number: str,
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
"""
Delete part from the system
Note: This will completely remove the part from the system.
"""
# Validate access to the tenant and company
tenant_id = current_user.get("tenant_id")
company_id = current_user.get("company_id")
if not tenant_id or not company_id:
raise HTTPException(
status_code=403, detail="Access denied: Tenant or Company not found"
)
service = PartService(db)
if not service.delete_part(client_id, part_number):
raise HTTPException(
status_code=404,
detail=f"Part with client_id '{client_id}' and part_number '{part_number}' not found",
)
@router.patch(
"/{client_id}/{part_number}/toggle-status", response_model=PartResponseDTO
)
async def toggle_part_status(
client_id: int,
part_number: str,
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
"""
Toggle part enabled/disabled status
"""
# Validate access to the tenant and company
tenant_id = current_user.get("tenant_id")
company_id = current_user.get("company_id")
if not tenant_id or not company_id:
raise HTTPException(
status_code=403, detail="Access denied: Tenant or Company not found"
)
service = PartService(db)
part = service.toggle_status(client_id, part_number)
if not part:
raise HTTPException(
status_code=404,
detail=f"Part with client_id '{client_id}' and part_number '{part_number}' not found",
)
return part
# Endpoints específicos para información detallada
@router.get("/{client_id}/{part_number}/basic", response_model=PartBasicDTO)
async def get_part_basic_info(
client_id: int,
part_number: str,
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
"""
Get basic information for a part
"""
# Validate access to the tenant and company
tenant_id = current_user.get("tenant_id")
company_id = current_user.get("company_id")
if not tenant_id or not company_id:
raise HTTPException(
status_code=403, detail="Access denied: Tenant or Company not found"
)
service = PartService(db)
part = service.get_part(client_id, part_number)
if not part:
raise HTTPException(
status_code=404,
detail=f"Part with client_id '{client_id}' and part_number '{part_number}' not found",
)
return PartBasicDTO(
client_id=part.client_id,
part_number=part.part_number,
description_spanish=part.description_spanish,
description_english=part.description_english,
part_class=part.part_class,
unit_cost=part.unit_cost,
currency_key=part.currency_key,
is_active=part.is_active,
)
@router.get("/{client_id}/{part_number}/regulatory", response_model=dict)
async def get_part_regulatory_info(
client_id: int,
part_number: str,
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
"""
Get regulatory information for a part (FDA, FCC, ECCN, etc.)
"""
# Validate access to the tenant and company
tenant_id = current_user.get("tenant_id")
company_id = current_user.get("company_id")
if not tenant_id or not company_id:
raise HTTPException(
status_code=403, detail="Access denied: Tenant or Company not found"
)
service = PartService(db)
part = service.get_part(client_id, part_number)
if not part:
raise HTTPException(
status_code=404,
detail=f"Part with client_id '{client_id}' and part_number '{part_number}' not found",
)
return {
"client_id": part.client_id,
"part_number": part.part_number,
"fraction": part.fraction,
"us_fraction": part.us_fraction,
"fda_key": part.fda_key,
"fcc_key": part.fcc_key,
"license_code": part.license_code,
"eccn": part.eccn,
"export_code": part.export_code,
"exclusion_symbol": part.exclusion_symbol,
}
# Ahora ya no dará error aquí
router = TenantCRUDRoutes(
service=PartService,
create_schema=PartCreateDTO,
update_schema=PartUpdateDTO,
response_schema=PartResponseDTO,
prefix="/parts",
tags=["a76 / parts"],
resource_name="Part",
id_name="part_id",
enable_list=True,
enable_filters=True,
).router

View File

@@ -1,309 +1,128 @@
"""
Capa de servicio para lógica de negocio de partes/componentes
"""
import logging
from typing import List, Optional
from typing import List, Optional, Any, Dict
from fastapi import HTTPException
from sqlalchemy import and_, func, or_
from sqlalchemy import and_, or_
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from .dto import PartCreateDTO, PartUpdateDTO
from .models import Part
from .dto import PartCreateDTO, PartUpdateDTO, PartSearchDTO
logger = logging.getLogger(__name__)
class PartService:
"""
Servicio para gestión de partes/componentes
Servicio de Partes compatible con TenantCRUDRoutes
"""
@staticmethod
def create_part(db: Session, part_data: PartCreateDTO) -> Part:
"""
Crear una nueva parte
"""
def get_all(
db: Session,
tenant_id: int,
company_id: int,
skip: int = 0,
limit: int = 100,
filters: Optional[Dict[str, Any]] = None, # Agregamos este argumento explícito
) -> tuple[List[Part], int]:
"""Obtener todas las partes con paginación y filtros"""
try:
db_part = Part(**part_data.model_dump())
query = db.query(Part).filter(
Part.tenant_id == tenant_id,
Part.company_id == company_id
)
if filters:
if filters.get("part_number"):
query = query.filter(Part.part_number.ilike(f"%{filters['part_number']}%"))
if filters.get("description"):
pattern = f"%{filters['description']}%"
query = query.filter(or_(
Part.description_spanish.ilike(pattern),
Part.description_english.ilike(pattern)
))
if filters.get("client_id"):
query = query.filter(Part.client_id == filters["client_id"])
total = query.count()
items = query.offset(skip).limit(limit).all()
return items, total
except Exception as e:
logger.error(f"Error en get_all partes: {e}")
raise HTTPException(status_code=500, detail="Error al listar partes")
@staticmethod
def get_by_id(db: Session, part_id: int, tenant_id: int, company_id: int) -> Optional[Part]:
"""Obtener una parte por su ID numérico (Reemplaza a get_part)"""
return db.query(Part).filter(
Part.id == part_id,
Part.tenant_id == tenant_id,
Part.company_id == company_id
).first()
@staticmethod
def create(db: Session, part_data: PartCreateDTO, tenant_id: int, company_id: int) -> Part:
"""Crear parte (Reemplaza a create_part)"""
try:
data = part_data.model_dump()
data['company_id'] = company_id
data['tenant_id'] = tenant_id
db_part = Part(**data)
db.add(db_part)
db.commit()
db.refresh(db_part)
return db_part
except IntegrityError as e:
db.rollback()
logger.error(f"Error creating part: {e}")
raise HTTPException(
status_code=400,
detail="Part with this client_id and part_number already exists",
)
except Exception as e:
db.rollback()
logger.error(f"Unexpected error creating part: {e}")
raise HTTPException(status_code=500, detail="Error creating part")
msg = str(e.orig)
if "client_part_ukey" in msg:
raise HTTPException(status_code=400, detail="El número de parte ya existe para este cliente.")
raise HTTPException(status_code=400, detail=f"Error de integridad: {msg}")
@staticmethod
def get_part(db: Session, client_id: int, part_number: str) -> Optional[Part]:
"""
Obtener una parte por clave de cliente y número de parte
"""
try:
return (
db.query(Part)
.filter(
and_(Part.client_id == client_id, Part.part_number == part_number)
)
.first()
)
except Exception as e:
logger.error(f"Error getting part: {e}")
raise HTTPException(status_code=500, detail="Error retrieving part")
@staticmethod
def get_parts_paginated(
db: Session,
skip: int = 0,
limit: int = 100,
search: Optional[str] = None,
client_id: Optional[int] = None,
fraction: Optional[str] = None,
country_of_origin: Optional[str] = None,
) -> tuple[List[Part], int]:
"""
Obtener partes con paginación y filtros
"""
try:
query = db.query(Part)
# Aplicar filtros
if search:
query = query.filter(
or_(
Part.description_spanish.ilike(f"%{search}%"),
Part.description_english.ilike(f"%{search}%"),
Part.part_number.ilike(f"%{search}%"),
)
)
if client_id is not None:
query = query.filter(Part.client_id == client_id)
if fraction:
query = query.filter(Part.fraction == fraction)
if country_of_origin:
query = query.filter(Part.country_of_origin == country_of_origin)
# Contar total
total = query.count()
# Aplicar paginación
parts = query.offset(skip).limit(limit).all()
return parts, total
except Exception as e:
logger.error(f"Error getting paginated parts: {e}")
raise HTTPException(status_code=500, detail="Error retrieving parts")
@staticmethod
def get_parts_by_client(db: Session, client_id: int) -> List[Part]:
"""
Obtener todas las partes de un cliente específico
"""
try:
return db.query(Part).filter(Part.client_id == client_id).all()
except Exception as e:
logger.error(f"Error getting parts by client: {e}")
raise HTTPException(status_code=500, detail="Error retrieving client parts")
@staticmethod
def search_parts_by_fraction(db: Session, fraction: str) -> List[Part]:
"""
Buscar partes por fracción arancelaria
"""
try:
return (
db.query(Part)
.filter(
or_(
Part.fraction.ilike(f"%{fraction}%"),
Part.us_fraction.ilike(f"%{fraction}%"),
)
)
.all()
)
except Exception as e:
logger.error(f"Error searching parts by fraction: {e}")
raise HTTPException(
status_code=500, detail="Error searching parts by fraction"
)
@staticmethod
def search_parts_by_supplier(db: Session, supplier: str) -> List[Part]:
"""
Buscar partes por proveedor
"""
try:
return db.query(Part).filter(Part.supplier.ilike(f"%{supplier}%")).all()
except Exception as e:
logger.error(f"Error searching parts by supplier: {e}")
raise HTTPException(
status_code=500, detail="Error searching parts by supplier"
)
@staticmethod
def search_parts_by_country(db: Session, country_code: str) -> List[Part]:
"""
Buscar partes por país de origen
"""
try:
return db.query(Part).filter(Part.country_of_origin == country_code).all()
except Exception as e:
logger.error(f"Error searching parts by country: {e}")
raise HTTPException(
status_code=500, detail="Error searching parts by country"
)
@staticmethod
def update_part(
db: Session, client_id: int, part_number: str, part_data: PartUpdateDTO
def update(
db: Session,
part_id: int,
tenant_id: int,
part_data: PartUpdateDTO,
company_id: int
) -> Optional[Part]:
"""
Actualizar una parte existente
"""
"""Actualizar parte por ID (Reemplaza a update_part)"""
db_part = PartService.get_by_id(db, part_id, tenant_id, company_id)
if not db_part:
return None
update_data = part_data.model_dump(exclude_unset=True)
# Evitar que se intente actualizar el ID o las llaves de seguridad
for key in ["id", "tenant_id", "company_id"]:
update_data.pop(key, None)
for key, value in update_data.items():
setattr(db_part, key, value)
try:
db_part = PartService.get_part(db, client_id, part_number)
if not db_part:
return None
# Actualizar campos
for field, value in part_data.model_dump(exclude_unset=True).items():
setattr(db_part, field, value)
db.commit()
db.refresh(db_part)
return db_part
except Exception as e:
db.rollback()
logger.error(f"Error updating part: {e}")
raise HTTPException(status_code=500, detail="Error updating part")
logger.error(f"Error actualizando parte {part_id}: {e}")
raise HTTPException(status_code=500, detail="Error al actualizar parte")
@staticmethod
def delete_part(db: Session, client_id: int, part_number: str) -> bool:
"""
Eliminar una parte
"""
def delete(db: Session, part_id: int, tenant_id: int, company_id: int) -> bool:
"""Eliminar parte"""
db_part = PartService.get_by_id(db, part_id, tenant_id, company_id)
if not db_part:
return False
try:
db_part = PartService.get_part(db, client_id, part_number)
if not db_part:
return False
db.delete(db_part)
db.commit()
return True
except Exception as e:
db.rollback()
logger.error(f"Error deleting part: {e}")
raise HTTPException(status_code=500, detail="Error deleting part")
@staticmethod
def toggle_part_status(
db: Session, client_id: int, part_number: str
) -> Optional[Part]:
"""
Cambiar el estado habilitado/deshabilitado de una parte
"""
try:
db_part = PartService.get_part(db, client_id, part_number)
if not db_part:
return None
# Toggle status (assuming 1 = enabled, 0 = disabled)
db_part.is_active = 1 if db_part.is_active == 0 else 0
db.commit()
db.refresh(db_part)
return db_part
except Exception as e:
db.rollback()
logger.error(f"Error toggling part status: {e}")
raise HTTPException(status_code=500, detail="Error toggling part status")
@staticmethod
def get_parts_statistics(db: Session) -> dict:
"""
Obtener estadísticas de partes
"""
try:
total_parts = db.query(Part).count()
# Partes por cliente
parts_by_client = (
db.query(Part.client_id, func.count(Part.part_number).label("count"))
.group_by(Part.client_id)
.all()
)
# Partes por país de origen
parts_by_country = (
db.query(
Part.country_of_origin, func.count(Part.part_number).label("count")
)
.filter(Part.country_of_origin.isnot(None))
.group_by(Part.country_of_origin)
.all()
)
# Partes habilitadas vs deshabilitadas
enabled_parts = db.query(Part).filter(Part.is_active == 1).count()
disabled_parts = db.query(Part).filter(Part.is_active == 0).count()
return {
"total_parts": total_parts,
"enabled_parts": enabled_parts,
"disabled_parts": disabled_parts,
"parts_by_client": [
{"client_id": item[0], "count": item[1]} for item in parts_by_client
],
"parts_by_country": [
{"country": item[0], "count": item[1]} for item in parts_by_country
],
}
except Exception as e:
logger.error(f"Error getting parts statistics: {e}")
raise HTTPException(
status_code=500, detail="Error retrieving parts statistics"
)
@staticmethod
def get_part_regulatory_info(
db: Session, client_id: int, part_number: str
) -> Optional[dict]:
"""
Obtener información regulatoria específica de una parte
"""
try:
db_part = PartService.get_part(db, client_id, part_number)
if not db_part:
return None
return {
"client_id": db_part.client_id,
"part_number": db_part.part_number,
"fraction": db_part.fraction,
"us_fraction": db_part.us_fraction,
"fda_key": db_part.fda_key,
"fcc_key": db_part.fcc_key,
"license_code": db_part.license_code,
"eccn": db_part.eccn,
"export_code": db_part.export_code,
"exclusion_symbol": db_part.exclusion_symbol,
"country_of_origin": db_part.country_of_origin,
}
except Exception as e:
logger.error(f"Error getting part regulatory info: {e}")
raise HTTPException(
status_code=500, detail="Error retrieving part regulatory information"
)
logger.error(f"Error eliminando parte {part_id}: {e}")
raise HTTPException(status_code=500, detail="Error al eliminar parte")

View File

@@ -0,0 +1,122 @@
import { api } from '$lib/api';
import type { ApiResponse } from '$lib/api';
export interface Part {
id: number;
// Llaves foráneas y IDs
tenant_id: number;
company_id: number;
client_id: number;
// Identificación
part_number: string;
commercial_part_number: string | null;
part_class: string | null;
// Descripciones
description_spanish: string | null;
description_english: string | null;
// Físico y Origen
unit_of_measure: string;
alternate_unit_measure: string | null;
country_of_origin: string;
unit_weight: number | null;
weight_type: string | null;
part_photo: string | null;
// Clasificación Arancelaria
fraction: string | null;
us_fraction: string | null;
// Costos y Valores
unit_cost: number | null;
currency_key: string | null; // currency_type en DB a veces es redundante, usamos key
added_value: number | null;
// Regulatorio y Proveedores
supplier: string | null;
fda_key: string | null;
fcc_key: string | null;
eccn: string | null;
license_code: string | null;
export_code: string | null;
exclusion_symbol: string | null;
// Estado
is_active: boolean;
created_at?: string;
updated_at?: string;
}
export interface PartCreate {
company_id: number;
client_id: number;
part_number: string;
// Opcionales
description_spanish?: string | null;
description_english?: string | null;
commercial_part_number?: string | null;
part_class?: string | null;
unit_of_measure: string;
alternate_unit_measure?: string | null;
country_of_origin?: string;
unit_weight?: number | null;
weight_type?: string | null;
fraction?: string | null;
us_fraction?: string | null;
unit_cost?: number | null;
currency_key?: string | null;
added_value?: number | null;
supplier?: string | null;
fda_key?: string | null;
fcc_key?: string | null;
eccn?: string | null;
license_code?: string | null;
export_code?: string | null;
exclusion_symbol?: string | null;
part_photo?: string | null;
is_active?: boolean;
}
export interface PartUpdate extends Partial<PartCreate> {}
export interface PartListResponse {
items: Part[];
total: number;
page: number;
page_size: number;
}
export const partsApi = {
list: (params: { company_id: number; page?: number; page_size?: number; q?: string }) => {
const { company_id, page = 1, page_size = 50, q = '' } = params;
const skip = (page - 1) * page_size;
return api.get<PartListResponse>(
`/v1/a76/parts/?company_id=${company_id}&skip=${skip}&limit=${page_size}&description=${q}`
);
},
get: (id: number, company_id: number) => {
return api.get<Part>(`/v1/a76/parts/${id}?company_id=${company_id}`);
},
create: (data: PartCreate, company_id: number) => {
return api.post<Part>(`/v1/a76/parts/?company_id=${company_id}`, data);
},
update: (id: number, data: PartUpdate, company_id: number) => {
return api.put<Part>(`/v1/a76/parts/${id}?company_id=${company_id}`, data);
},
delete: (id: number, company_id: number) => {
return api.delete<void>(`/v1/a76/parts/${id}?company_id=${company_id}`);
}
};

View File

@@ -0,0 +1,178 @@
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 { Part } from "$lib/api/dashboard/a76/parts";
/**
* Formatea moneda (USD/MXN)
*/
function formatCurrency(amount: number | null, currency: string | null): string {
if (amount === null || amount === undefined) return '-';
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: currency || 'USD',
minimumFractionDigits: 4
}).format(amount);
}
export function createColumns(onSuccess?: () => void): ColumnDef<Part>[] {
return [
// 1. STATUS (Corregido a Texto)
{
accessorKey: "is_active",
header: "Status",
cell: ({ row }) => {
const statusSnippet = createRawSnippet<[{ active: boolean }]>((getStatus) => {
const { active } = getStatus();
return {
render: () => active
? `<span class="inline-flex items-center rounded-full bg-green-50 px-2 py-1 text-xs font-medium text-green-700 ring-1 ring-inset ring-green-600/20">Activo</span>`
: `<span class="inline-flex items-center rounded-full bg-red-50 px-2 py-1 text-xs font-medium text-red-700 ring-1 ring-inset ring-red-600/10">Inactivo</span>`
};
});
return renderSnippet(statusSnippet, { active: row.original.is_active });
}
},
// 2. NUMERO PARTE
{
accessorKey: "part_number",
header: "No. Parte",
cell: ({ row }) => {
const pnSnippet = createRawSnippet<[{ pn: string }]>((getPn) => {
const { pn } = getPn();
return {
render: () =>
`<div class="font-mono text-sm font-semibold text-foreground whitespace-nowrap">${pn}</div>`
};
});
return renderSnippet(pnSnippet, { pn: row.original.part_number });
}
},
// 3. DESCRIPCION (Español)
{
accessorKey: "description_spanish",
header: "Descripción",
cell: ({ row }) => {
const descSnippet = createRawSnippet<[{ desc: string }]>((getDesc) => {
const { desc } = getDesc();
return {
render: () =>
`<div class="max-w-[250px] truncate text-xs font-medium uppercase text-muted-foreground" title="${desc}">${desc || '-'}</div>`
};
});
return renderSnippet(descSnippet, { desc: row.original.description_spanish || '' });
}
},
// 4. DESCRIPCION INGLES
{
accessorKey: "description_english",
header: "Desc. Inglés",
cell: ({ row }) => {
const descEnSnippet = createRawSnippet<[{ desc: string }]>((getDesc) => {
const { desc } = getDesc();
return {
render: () =>
`<div class="max-w-[200px] truncate text-xs text-muted-foreground/70" title="${desc}">${desc || '-'}</div>`
};
});
return renderSnippet(descEnSnippet, { desc: row.original.description_english || '' });
}
},
// 5. CLASE
{
accessorKey: "part_class",
header: "Clase",
cell: ({ row }) => {
const classSnippet = createRawSnippet<[{ cls: string }]>((getCls) => {
const { cls } = getCls();
return {
render: () => `<div class="text-xs font-mono">${cls || '-'}</div>`
};
});
return renderSnippet(classSnippet, { cls: row.original.part_class || '' });
}
},
// 6. TIPO (Commercial Part Number)
{
accessorKey: "commercial_part_number",
header: "Tipo",
cell: ({ row }) => {
const typeSnippet = createRawSnippet<[{ val: string }]>((getType) => {
const { val } = getType();
return {
render: () => `<div class="text-xs text-muted-foreground">${val || '-'}</div>`
};
});
return renderSnippet(typeSnippet, { val: row.original.commercial_part_number || '' });
}
},
// 7. FRACCION
{
accessorKey: "fraction",
header: "Fracción",
cell: ({ row }) => {
const fracSnippet = createRawSnippet<[{ fr: string }]>((getFrac) => {
const { fr } = getFrac();
return {
render: () => `<span class="font-mono text-xs bg-slate-100 dark:bg-slate-800 px-1.5 py-0.5 rounded">${fr || '-'}</span>`
};
});
return renderSnippet(fracSnippet, { fr: row.original.fraction || '' });
}
},
// 8. UMT (Unidad de Medida)
{
accessorKey: "unit_of_measure",
header: "UMT",
cell: ({ row }) => {
const umtSnippet = createRawSnippet<[{ um: string }]>((getUm) => {
const { um } = getUm();
return {
render: () =>
`<span class="inline-flex items-center rounded-sm bg-blue-50 text-blue-700 px-1.5 py-0.5 text-[10px] font-bold ring-1 ring-inset ring-blue-700/10">
${um}
</span>`
};
});
return renderSnippet(umtSnippet, { um: row.original.unit_of_measure });
}
},
// 9. COSTO
{
accessorKey: "unit_cost",
header: "Costo",
cell: ({ row }) => {
const costSnippet = createRawSnippet<[{ amount: number | null, curr: string | null }]>((getCost) => {
const { amount, curr } = getCost();
return {
render: () => `<div class="font-mono text-xs font-medium">${formatCurrency(amount, curr)}</div>`
};
});
return renderSnippet(costSnippet, {
amount: row.original.unit_cost,
curr: row.original.currency_key
});
}
},
// ACCIONES
{
id: "actions",
header: "",
cell: ({ row }) => {
return renderComponent(DataTableActions, { item: row.original, onSuccess });
}
}
];
}
export const columns = createColumns();

View File

@@ -0,0 +1,520 @@
<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 ClientProviderBasic } 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<ClientProviderBasic[]>([]);
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.listClients(companyId, 0, 500);
if (response.data) {
clients = response.data;
}
} 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>

View File

@@ -0,0 +1,101 @@
<script lang="ts">
import { Button } from "$lib/components/ui/button";
import * as DropdownMenu from "$lib/components/ui/dropdown-menu";
// 1. Cambiamos la API y el Tipo a Part
import { partsApi, type Part } from "$lib/api/dashboard/a76/parts";
import { companyStore } from "$lib/stores/company.svelte";
import { EllipsisVertical, Pencil, LoaderCircle, Trash2 } from 'lucide-svelte';
import { goto } from "$app/navigation";
let {
item,
onSuccess
}: {
item: Part; // Cambiado a Part
onSuccess?: () => void;
} = $props();
let loading = $state(false);
let error = $state<string | null>(null);
async function handleDelete() {
// 2. Ajustamos el mensaje de confirmación para que muestre el No. Parte
if (!confirm(`¿Estás seguro de eliminar la parte "${item.part_number}"?`)) {
return;
}
const companyId = companyStore.activeCompany?.id;
if (!companyId) {
alert('No hay compañía seleccionada');
return;
}
loading = true;
error = null;
try {
// 3. Llamamos a la API de PARTES
const response = await partsApi.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() {
// Redirigimos a la página de edición usando el ID
goto(`/dashboard/goods/parts/edit/${item.id}`);
}
</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={handleEdit} >
<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>

View File

@@ -0,0 +1,123 @@
<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>

View File

@@ -6,7 +6,6 @@ export const load: PageServerLoad = async ({ cookies, fetch, url, parent }) => {
const { accessToken } = getAuthTokens(cookies);
if (!accessToken) {
// Cambiamos el objeto de retorno vacío a "classes"
return { error: 'No authenticated', classes: { items: [], total: 0, page: 1, page_size: 50, pages: 0 } };
}
@@ -14,16 +13,16 @@ export const load: PageServerLoad = async ({ cookies, fetch, url, parent }) => {
const page = Number(url.searchParams.get('page')) || 1;
const pageSize = Number(url.searchParams.get('pageSize')) || 50;
// --- ZONA DE CAMBIOS DE FILTROS ---
const filters: Record<string, string> = {};
// En tu modelo el campo se llama "class_code", así que buscamos eso o 'code'
const classCode = url.searchParams.get('class_code') || url.searchParams.get('code');
const description = url.searchParams.get('description'); // Este sirve para description_es o description_en
const description = url.searchParams.get('description');
if (classCode) filters.class_code = classCode; // Ajustado al modelo
if (classCode) filters.class_code = classCode;
if (description) filters.description = description;
// ----------------------------------
const parentData = await parent();
const cookieCompanyId = cookies.get('active_company_id');
@@ -46,14 +45,14 @@ export const load: PageServerLoad = async ({ cookies, fetch, url, parent }) => {
});
// --- ZONA DE CAMBIO DE ENDPOINT ---
// Asumiendo que tu endpoint sigue el estándar REST y se llama 'classes'
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 } };
}
// Retornamos "classes" para que coincida con lo que espera tu frontend
return { classes: await response.json() };
} catch (error) {

View File

@@ -0,0 +1,60 @@
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/parts?${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 } };
}
};

View File

@@ -1 +1,146 @@
<h1>Pagina de partes</h1>
<script lang="ts">
import { onMount } from 'svelte';
import { partsApi, type Part } from '$lib/api/dashboard/a76/parts';
import DataTable from '$lib/components/dashboard/classes/data-table.svelte';
import { createColumns } from '$lib/components/dashboard/parts/columns.js';
import * 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 { companyStore } from '$lib/stores/company.svelte';
import { Plus, Search, Trash2, RefreshCw } from 'lucide-svelte';
// 1. ESTADOS
let partsList = $state<Part[]>([]);
let listLoading = $state(false);
let listError = $state<string | null>(null);
let searchCode = $state('');
let searchedPart = $state<Part | null>(null);
let searchLoading = $state(false);
// 2. CARGA DE DATOS
async function loadParts() {
const companyId = companyStore.activeCompany?.id;
if (!companyId) return;
listLoading = true;
listError = null;
try {
const response = await partsApi.list({
company_id: companyId,
page: 1,
page_size: 100
});
if (response.data) {
partsList = response.data.items || response.data.parts || [];
console.log("Datos recibidos:", response.data);
} 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();
}
});
async function handleSearch() {
if (!searchCode.trim()) return;
searchLoading = true;
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 || response.data.parts || [];
if (results.length > 0) {
searchedPart = results[0];
} else {
listError = "No se encontró la parte";
}
} catch (e) {
listError = "Error en la búsqueda";
} finally {
searchLoading = false;
}
}
function clearSearch() {
searchCode = '';
searchedPart = null;
loadParts();
}
const columns = createColumns(loadParts);
const tableData = $derived(searchedPart ? [searchedPart] : 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.Content class="pt-6">
<div class="flex gap-4">
<div class="flex-1">
<Input bind:value={searchCode} placeholder="Buscar por número de parte o descripción..." />
</div>
<Button onclick={handleSearch} disabled={searchLoading}>
<Search class="mr-2 h-4 w-4" />
Buscar
</Button>
{#if searchedPart || searchCode}
<Button variant="ghost" onclick={clearSearch}>
Limpiar
</Button>
{/if}
</div>
</Card.Content>
</Card.Root>
<Card.Root>
<Card.Header>
<Card.Title>{searchedPart ? 'Resultado' : 'Listado General'}</Card.Title>
</Card.Header>
<Card.Content>
{#if listError}
<div class="bg-destructive/10 text-destructive p-4 rounded-lg border border-destructive/20">
{listError}
</div>
{:else}
<DataTable data={tableData} {columns} />
{/if}
</Card.Content>
</Card.Root>
</div>

View File

@@ -0,0 +1,441 @@
<script lang="ts">
import { page } from '$app/stores';
import { goto } from '$app/navigation';
import { onMount } from 'svelte';
// UI Components
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 { Switch } from "$lib/components/ui/switch";
import { ArrowLeft, LoaderCircle, Save, CheckCircle2, XCircle, Package, DollarSign } from 'lucide-svelte';
import { companyStore } from '$lib/stores/company.svelte';
import { partsApi, type PartCreate } from '$lib/api/dashboard/a76/parts';
// --- 1. IDENTIFICACIÓN ---
let id = $derived($page.params.id === 'new' ? null : Number($page.params.id));
let isEdit = $derived(!!id);
let title = $derived(isEdit ? "Editar Parte" : "Nueva Parte");
// --- 2. ESTADOS ---
let loading = $state(false);
let error = $state<string | null>(null);
// Estado del Formulario
let formData = $state({
client_id: 0,
part_number: '',
// General
description_spanish: '',
description_english: '',
part_class: '',
country_of_origin: 'MEX',
unit_of_measure: 'PZ',
// Opcionales 1
fraction: '',
us_fraction: '',
unit_weight: 0,
weight_type: 'KG',
// Opcionales 2
supplier: '',
fda_key: '',
fcc_key: '',
eccn: '',
license_code: '',
export_code: '',
exclusion_symbol: '',
// Costos
unit_cost: 0,
currency_key: 'USD',
added_value: 0,
commercial_part_number: '',
// Otros
alternate_unit_measure: '',
part_photo: '',
is_active: true
});
// --- 3. CARGA ---
onMount(async () => {
const companyId = companyStore.activeCompany?.id;
if (!companyId) return;
if (id) {
await loadPartData(id, companyId);
}
});
async function loadPartData(partId: number, companyId: number) {
loading = true;
try {
const response = await partsApi.get(partId, companyId);
if (response.error) {
error = response.error;
return;
}
if (response.data) {
const d = response.data;
formData = {
client_id: d.client_id,
part_number: d.part_number,
description_spanish: d.description_spanish || '',
description_english: d.description_english || '',
part_class: d.part_class || '',
country_of_origin: d.country_of_origin || 'MEX',
unit_of_measure: d.unit_of_measure || 'PZ',
fraction: d.fraction || '',
us_fraction: d.us_fraction || '',
unit_weight: Number(d.unit_weight) || 0,
weight_type: d.weight_type || 'KG',
supplier: d.supplier || '',
fda_key: d.fda_key || '',
fcc_key: d.fcc_key || '',
eccn: d.eccn || '',
license_code: d.license_code || '',
export_code: d.export_code || '',
exclusion_symbol: d.exclusion_symbol || '',
unit_cost: Number(d.unit_cost) || 0,
currency_key: d.currency_key || 'USD',
added_value: Number(d.added_value) || 0,
commercial_part_number: d.commercial_part_number || '',
alternate_unit_measure: d.alternate_unit_measure || '',
part_photo: d.part_photo || '',
is_active: d.is_active ?? true
};
}
} catch (e) {
error = "Error al cargar la parte";
console.error(e);
} finally {
loading = false;
}
}
async function handleSubmit() {
error = null;
const activeCompanyId = companyStore.activeCompany?.id;
if (!activeCompanyId) { error = 'No hay una compañía activa seleccionada'; return; }
if (!formData.client_id) { error = 'ID Cliente requerido'; return; }
if (!formData.part_number.trim()) { error = 'Número de Parte requerido'; return; }
if (!formData.fraction.trim()) { error = 'Fracción MX requerida'; return; }
loading = true;
try {
const commonData = {
description_spanish: formData.description_spanish || null,
description_english: formData.description_english || null,
part_class: formData.part_class || null,
country_of_origin: formData.country_of_origin || 'MEX',
unit_of_measure: formData.unit_of_measure,
fraction: formData.fraction || null,
us_fraction: formData.us_fraction || null,
unit_weight: Number(formData.unit_weight) || 0,
weight_type: formData.weight_type || 'KG',
supplier: formData.supplier || null,
fda_key: formData.fda_key || null,
fcc_key: formData.fcc_key || null,
eccn: formData.eccn || null,
license_code: formData.license_code || null,
export_code: formData.export_code || null,
exclusion_symbol: formData.exclusion_symbol || null,
unit_cost: Number(formData.unit_cost) || 0,
currency_key: formData.currency_key || 'USD',
added_value: Number(formData.added_value) || 0,
commercial_part_number: formData.commercial_part_number || null,
alternate_unit_measure: formData.alternate_unit_measure || null,
part_photo: formData.part_photo || null,
is_active: formData.is_active
};
if (isEdit && id) {
const response = await partsApi.update(id, commonData, activeCompanyId);
if (response.error) throw new Error(response.error);
console.log("Registro actualizado con éxito");
} else {
const createData: PartCreate = {
...commonData,
company_id: activeCompanyId,
client_id: Number(formData.client_id),
part_number: formData.part_number
};
const response = await partsApi.create(createData, activeCompanyId);
if (response.error) throw new Error(response.error);
console.log("Registro creado con éxito");
}
goto('/dashboard/goods/parts');
} catch (e: any) {
console.error("Error en el guardado:", e);
if (e.message?.includes('already exists')) {
error = `El número de parte ${formData.part_number} ya existe para este cliente.`;
} else if (e.message?.includes('foreign key constraint')) {
error = `Error: Uno de los datos (País, Moneda o Unidad) no existe en el sistema.`;
} else {
error = e.message || 'Ocurrió un error inesperado 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 justify-between">
<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>
<p class="text-xs text-muted-foreground">{isEdit ? 'Modificando registro existente' : 'Creando nuevo registro'}</p>
</div>
</div>
{#if isEdit}
<div class="flex items-center gap-2 px-3 py-1 rounded-full border text-xs font-medium {formData.is_active ? 'bg-green-100 text-green-700 border-green-200' : 'bg-red-100 text-red-700 border-red-200'}">
{#if formData.is_active} <CheckCircle2 class="w-3 h-3 mr-1"/> Activo {:else} <XCircle class="w-3 h-3 mr-1"/> Inactivo {/if}
</div>
{/if}
</div>
{#if error}
<div class="p-4 rounded-md bg-destructive/10 text-destructive border border-destructive/20 text-sm font-medium">
⚠️ {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-[450px]">
<Tabs.Content value="general" class="space-y-4 pt-4 animate-in fade-in slide-in-from-bottom-2 duration-300">
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div class="space-y-4">
<div class="grid gap-2">
<Label for="client_id" class="required">ID Cliente</Label>
<Input type="number" id="client_id" bind:value={formData.client_id} placeholder="Ej. 11" />
</div>
<div class="grid gap-2">
<Label for="part_number" class="required">Número de Parte</Label>
<Input id="part_number" bind:value={formData.part_number} disabled={isEdit} maxlength={50} class="font-mono" />
</div>
<div class="grid gap-2">
<Label for="part_class">Clase / Familia</Label>
<Input id="part_class" bind:value={formData.part_class} maxlength={8} />
</div>
</div>
<div class="space-y-4">
<div class="grid gap-2">
<Label for="country">País de Origen</Label>
<Input id="country" bind:value={formData.country_of_origin} maxlength={3} placeholder="MEX" />
</div>
<div class="grid gap-2">
<Label for="uom" class="required">Unidad Medida (UM)</Label>
<select id="uom" bind:value={formData.unit_of_measure} class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm">
<option value="PZ">Pieza (PZ)</option>
<option value="KG">Kilogramo (KG)</option>
<option value="EA">Elemento (EA)</option>
<option value="L">Litro (L)</option>
</select>
</div>
</div>
</div>
<div class="grid gap-2">
<Label for="desc_es">Descripción (Español)</Label>
<Textarea id="desc_es" bind:value={formData.description_spanish} 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_english} maxlength={500} />
</div>
</Tabs.Content>
<Tabs.Content value="opt1" class="space-y-4 pt-4 animate-in fade-in slide-in-from-bottom-2 duration-300">
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div class="p-4 border rounded-lg bg-slate-50 dark:bg-slate-900/50 space-y-4">
<h3 class="font-semibold text-sm">Clasificación Arancelaria</h3>
<div class="grid gap-2">
<Label for="frac_mx" class="required">Fracción MX</Label>
<Input id="frac_mx" bind:value={formData.fraction} maxlength={10} placeholder="Ej: 85011001" />
</div>
<div class="grid gap-2">
<Label for="frac_us">Fracción US (HTS)</Label>
<Input id="frac_us" bind:value={formData.us_fraction} maxlength={16} placeholder="Ej: 8501.10.00" />
</div>
</div>
<div class="p-4 border rounded-lg bg-slate-50 dark:bg-slate-900/50 space-y-4">
<h3 class="font-semibold text-sm flex items-center gap-2">
<Package class="h-4 w-4"/> Dimensiones Físicas
</h3>
<div class="grid gap-2">
<Label for="weight">Peso Unitario</Label>
<Input type="number" step="0.0001" id="weight" bind:value={formData.unit_weight} />
</div>
<div class="grid gap-2">
<Label for="weight_type">Tipo Peso</Label>
<select id="weight_type" bind:value={formData.weight_type} class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm">
<option value="KG">Kilogramos (KG)</option>
<option value="LB">Libras (LB)</option>
</select>
</div>
</div>
</div>
</Tabs.Content>
<Tabs.Content value="opt2" class="space-y-4 pt-4 animate-in fade-in slide-in-from-bottom-2 duration-300">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="grid gap-2">
<Label for="supplier">Proveedor</Label>
<Input id="supplier" bind:value={formData.supplier} maxlength={14} />
</div>
<div class="grid gap-2">
<Label for="eccn">ECCN (Export Control)</Label>
<Input id="eccn" bind:value={formData.eccn} maxlength={20} />
</div>
<div class="grid gap-2">
<Label for="fda">FDA Key</Label>
<Input id="fda" bind:value={formData.fda_key} maxlength={20} />
</div>
<div class="grid gap-2">
<Label for="fcc">FCC Key</Label>
<Input id="fcc" bind:value={formData.fcc_key} maxlength={30} />
</div>
<div class="grid gap-2">
<Label for="lic_code">License Code</Label>
<Input id="lic_code" bind:value={formData.license_code} maxlength={3} />
</div>
<div class="grid gap-2">
<Label for="exp_code">Export Code</Label>
<Input id="exp_code" bind:value={formData.export_code} maxlength={2} />
</div>
<div class="grid gap-2 md:col-span-2">
<Label for="exc_sym">Exclusion Symbol</Label>
<Input id="exc_sym" bind:value={formData.exclusion_symbol} maxlength={19} />
</div>
</div>
</Tabs.Content>
<Tabs.Content value="costs" class="space-y-4 pt-4 animate-in fade-in slide-in-from-bottom-2 duration-300">
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div class="p-4 border rounded-lg bg-green-50/50 dark:bg-green-900/10 space-y-4">
<h3 class="font-semibold text-sm text-green-800 dark:text-green-300 flex items-center gap-2">
<DollarSign class="h-4 w-4"/> Costos y Moneda
</h3>
<div class="grid gap-2">
<Label for="unit_cost">Costo Unitario</Label>
<div class="relative">
<span class="absolute left-3 top-2.5 text-muted-foreground">$</span>
<Input type="number" step="0.0001" id="unit_cost" bind:value={formData.unit_cost} class="pl-7" />
</div>
</div>
<div class="grid gap-2">
<Label for="currency">Moneda</Label>
<select id="currency" bind:value={formData.currency_key} class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm">
<option value="USD">USD - Dólar Americano</option>
<option value="MXP">MXP - Peso Mexicano</option>
<option value="EUR">EUR - Euro</option>
</select>
</div>
<div class="grid gap-2">
<Label for="added_value">Valor Agregado</Label>
<Input type="number" step="0.0001" id="added_value" bind:value={formData.added_value} />
</div>
</div>
<div class="space-y-4">
<div class="grid gap-2">
<Label for="comm_pn">No. Parte Comercial</Label>
<Input id="comm_pn" bind:value={formData.commercial_part_number} maxlength={70} placeholder="Código usado en factura..." />
<p class="text-xs text-muted-foreground">Si difiere del número de parte interno.</p>
</div>
</div>
</div>
</Tabs.Content>
<Tabs.Content value="others" class="space-y-4 pt-4 animate-in fade-in slide-in-from-bottom-2 duration-300">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="grid gap-2">
<Label for="alt_um">UM Alterna</Label>
<Input id="alt_um" bind:value={formData.alternate_unit_measure} maxlength={14} />
</div>
<div class="grid gap-2">
<Label for="photo">URL Foto</Label>
<Input id="photo" bind:value={formData.part_photo} maxlength={255} />
</div>
<div class="flex items-center space-x-2 pt-4">
<Switch id="active-mode" bind:checked={formData.is_active} />
<Label for="active-mode">Parte Activa en Sistema</Label>
</div>
</div>
</Tabs.Content>
</div>
<div class="fixed bottom-20 left-0 right-0 z-40 flex justify-center pointer-events-none">
<Tabs.List class="pointer-events-auto grid grid-cols-5 w-[95%] max-w-4xl shadow-2xl bg-background border p-1 rounded-xl">
<Tabs.Trigger value="general" class="text-xs md:text-sm">General</Tabs.Trigger>
<Tabs.Trigger value="opt1" class="text-xs md:text-sm">Op. 1</Tabs.Trigger>
<Tabs.Trigger value="opt2" class="text-xs md:text-sm">Op. 2</Tabs.Trigger>
<Tabs.Trigger value="costs" class="text-xs md:text-sm">Costos</Tabs.Trigger>
<Tabs.Trigger value="others" class="text-xs md:text-sm">Otros</Tabs.Trigger>
</Tabs.List>
</div>
</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/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" />
Guardando...
{:else}
<Save class="mr-2 h-4 w-4" />
{isEdit ? 'Actualizar' : 'Guardar'}
{/if}
</Button>
</div>
</div>
</form>
{/key}
</div>
<style>
:global(.required::after) {
content: " *";
color: hsl(var(--destructive));
}
</style>