# Reporte de Trabajo - 5 de Noviembre de 2025

## Cambios Realizados

### 1. **Modelos**
- Se actualizaron los modelos para incluir el esquema  en las tablas:
  -
  -
  -
  -
- Ajustes en relaciones y claves foráneas para garantizar consistencia con el esquema .
- Se añadieron anotaciones de tipo y mejoras en la documentación de los modelos.

### 2. **Servicios**
- Implementación de lógica de negocio en  para el módulo :
  - Creación, actualización, eliminación y búsqueda de partes.
  - Métodos para estadísticas y manejo de estados habilitado/deshabilitado.

### 3. **Migraciones**
- Creación de nuevas migraciones de Alembic para las tablas:
  -
  -
  -
  -
  - Tablas relacionadas con direcciones y programas de clientes/proveedores.

### 4. **Documentación**
- Actualización de :
  - Detalles de las nuevas funcionalidades implementadas.
  - Endpoints REST API agregados para los módulos.
  - Relaciones principales entre tablas.
- Actualización de :
  - Cambios realizados en los modelos para usar el esquema .
  - Beneficios de la separación de esquemas.
  - Próximos pasos para completar la integración.

## Próximos Pasos
1. Verificar las migraciones generadas y aplicarlas en el entorno de desarrollo.
2. Implementar pruebas unitarias para los nuevos servicios y modelos.

---

*Documento generado automáticamente el 5 de noviembre de 2025.*
This commit is contained in:
2025-11-05 22:38:58 -06:00
parent 38d86531e8
commit c1dee97092
13 changed files with 1130 additions and 14 deletions

View File

@@ -1,5 +1,5 @@
"""
Módulo de Tenants
Módulo de GClass
"""
from .routes import router

View File

@@ -8,7 +8,7 @@ from core.database import Base
import enum
# Importar modelos relacionados para type hints y relationships
from typing import TYPE_CHECKING, List
from typing import TYPE_CHECKING, List, Optional
if TYPE_CHECKING:
from api.v1.modules.a76.GParts.models import GPart
@@ -20,6 +20,7 @@ class GClass(Base):
Modelo para la tabla GClases - Información de clases en sistemas SCAII y SCAF
"""
__tablename__ = "gclasses"
__table_args__ = {"schema": "a76"}
# Primary key compuesta
client_key = Column(Integer, primary_key=True, nullable=False)
@@ -43,10 +44,10 @@ class GClass(Base):
iva_exempt_fraction = Column(String(4), nullable=True) # FRACCIONEXENTAIVA
# Relationships
material_type: "MaterialType" = relationship("MaterialType", foreign_keys=[material_key])
material_type = relationship("MaterialType", foreign_keys=[material_key])
# Inverse relationship with GParts that have this class
parts: List["GPart"] = relationship(
parts = relationship(
"GPart",
primaryjoin="and_(GClass.client_key == GPart.client_key, GClass.class_code == GPart.part_class)",
foreign_keys="[GPart.client_key, GPart.part_class]",

View File

@@ -1,5 +1,5 @@
"""
Módulo de Tenants
Módulo de GParts
"""
from .routes import router

View File

@@ -8,7 +8,7 @@ from core.database import Base
import enum
# Importar modelos relacionados para type hints y relationships
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Optional
if TYPE_CHECKING:
from api.v1.modules.public.reference_data.countries.models import Country
@@ -21,6 +21,7 @@ class GPart(Base):
Modelo para la tabla GPartes - Información de partes en los sistemas SCAII (N), SCAF (S) Y WINSAAI (W)
"""
__tablename__ = "gparts"
__table_args__ = {"schema": "a76"}
# Primary key compuesta
client_key = Column(Integer, primary_key=True, nullable=False)
@@ -68,12 +69,12 @@ class GPart(Base):
part_photo = Column(String(255), nullable=True)
# Relationships
country: "Country" = relationship("Country", foreign_keys=[country_of_origin])
currency: "CurrencyType" = relationship("CurrencyType", foreign_keys=[currency_key])
country = relationship("Country", foreign_keys=[country_of_origin])
currency = relationship("CurrencyType", foreign_keys=[currency_key])
# Relationship with GClass through composite foreign key
# Note: This requires both client_key and part_class to match client_key and class_code in GClass
part_class_info: "GClass" = relationship(
part_class_info = relationship(
"GClass",
primaryjoin="and_(GPart.client_key == GClass.client_key, GPart.part_class == GClass.class_code)",
foreign_keys="[GPart.client_key, GPart.part_class]",

View File

@@ -9,7 +9,267 @@ from typing import List, Optional
import logging
from datetime import datetime
from .models import GPart
from .dto import PartCreateDTO, PartUpdateDTO
logger = logging.getLogger(__name__)
class PartService:
"""
Servicio para gestión de partes/componentes
"""
@staticmethod
def create_part(db: Session, part_data: PartCreateDTO) -> GPart:
"""
Crear una nueva parte
"""
try:
db_part = GPart(**part_data.model_dump())
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_key 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")
@staticmethod
def get_part(db: Session, client_key: int, part_number: str) -> Optional[GPart]:
"""
Obtener una parte por clave de cliente y número de parte
"""
try:
return db.query(GPart).filter(
and_(
GPart.client_key == client_key,
GPart.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_key: Optional[int] = None,
fraction: Optional[str] = None,
country_of_origin: Optional[str] = None
) -> tuple[List[GPart], int]:
"""
Obtener partes con paginación y filtros
"""
try:
query = db.query(GPart)
# Aplicar filtros
if search:
query = query.filter(or_(
GPart.description_spanish.ilike(f"%{search}%"),
GPart.description_english.ilike(f"%{search}%"),
GPart.part_number.ilike(f"%{search}%")
))
if client_key is not None:
query = query.filter(GPart.client_key == client_key)
if fraction:
query = query.filter(GPart.fraction == fraction)
if country_of_origin:
query = query.filter(GPart.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_key: int) -> List[GPart]:
"""
Obtener todas las partes de un cliente específico
"""
try:
return db.query(GPart).filter(GPart.client_key == client_key).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[GPart]:
"""
Buscar partes por fracción arancelaria
"""
try:
return db.query(GPart).filter(
or_(
GPart.fraction.ilike(f"%{fraction}%"),
GPart.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[GPart]:
"""
Buscar partes por proveedor
"""
try:
return db.query(GPart).filter(GPart.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[GPart]:
"""
Buscar partes por país de origen
"""
try:
return db.query(GPart).filter(GPart.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_key: int, part_number: str, part_data: PartUpdateDTO) -> Optional[GPart]:
"""
Actualizar una parte existente
"""
try:
db_part = PartService.get_part(db, client_key, 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")
@staticmethod
def delete_part(db: Session, client_key: int, part_number: str) -> bool:
"""
Eliminar una parte
"""
try:
db_part = PartService.get_part(db, client_key, 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_key: int, part_number: str) -> Optional[GPart]:
"""
Cambiar el estado habilitado/deshabilitado de una parte
"""
try:
db_part = PartService.get_part(db, client_key, part_number)
if not db_part:
return None
# Toggle status (assuming 1 = enabled, 0 = disabled)
db_part.enabled_disabled = 1 if db_part.enabled_disabled == 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(GPart).count()
# Partes por cliente
parts_by_client = db.query(
GPart.client_key,
func.count(GPart.part_number).label('count')
).group_by(GPart.client_key).all()
# Partes por país de origen
parts_by_country = db.query(
GPart.country_of_origin,
func.count(GPart.part_number).label('count')
).filter(GPart.country_of_origin.isnot(None))\
.group_by(GPart.country_of_origin).all()
# Partes habilitadas vs deshabilitadas
enabled_parts = db.query(GPart).filter(GPart.enabled_disabled == 1).count()
disabled_parts = db.query(GPart).filter(GPart.enabled_disabled == 0).count()
return {
"total_parts": total_parts,
"enabled_parts": enabled_parts,
"disabled_parts": disabled_parts,
"parts_by_client": [{"client_key": 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_key: int, part_number: str) -> Optional[dict]:
"""
Obtener información regulatoria específica de una parte
"""
try:
db_part = PartService.get_part(db, client_key, part_number)
if not db_part:
return None
return {
"client_key": db_part.client_key,
"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")

View File

@@ -1,5 +1,5 @@
"""
Módulo de Tenants
Módulo de Client & Provider
"""
from .routes import router

View File

@@ -13,6 +13,7 @@ class GClientProvider(Base):
Modelo para la tabla GClientesPro - Información de clientes y proveedores
"""
__tablename__ = "gclient_provider"
__table_args__ = {"schema": "a76"}
# Primary key
client_id = Column(String(8), primary_key=True, nullable=False)
@@ -44,9 +45,10 @@ class GClientProviderAddress(Base):
Modelo para la tabla GClientesPro_Direccion - Dirección de clientes y proveedores
"""
__tablename__ = "gclient_provider_address"
__table_args__ = {"schema": "a76"}
# Primary key (foreign key)
client_id = Column(String(8), ForeignKey('gclient_provider.client_id', ondelete='CASCADE'), primary_key=True, nullable=False)
client_id = Column(String(8), ForeignKey('a76.gclient_provider.client_id', ondelete='CASCADE'), primary_key=True, nullable=False)
# Address information
municipality = Column(String(150), nullable=True)
@@ -73,9 +75,10 @@ class GClientProviderPrograms(Base):
Modelo para la tabla GClientesPro_Programas - Programas de clientes y proveedores
"""
__tablename__ = "gclient_provider_programs"
__table_args__ = {"schema": "a76"}
# Primary key (foreign key)
client_id = Column(String(8), ForeignKey('gclient_provider.client_id', ondelete='CASCADE'), primary_key=True, nullable=False)
client_id = Column(String(8), ForeignKey('a76.gclient_provider.client_id', ondelete='CASCADE'), primary_key=True, nullable=False)
# Program information
program = Column(String(7), nullable=True)

View File

@@ -1,5 +1,5 @@
"""
Módulo de Tenants
Módulo de Company
"""
from .routes import router

View File

@@ -12,6 +12,7 @@ class GCompany(Base):
Modelo para la tabla GCompany - Información de la empresa
"""
__tablename__ = "gcompany"
__table_args__ = {"schema": "a76"}
# Primary key
id = Column(String(3), primary_key=True, default='EMP', nullable=False)