Merge pull request 'feature/catalogo-pedimento' (#219) from feature/catalogo-pedimento into development

Reviewed-on: ADUANASOFT/anexo76#219
This commit is contained in:
2026-03-18 03:53:00 +00:00
16 changed files with 355 additions and 70 deletions

View File

@@ -35,7 +35,7 @@ def load_pedimentos_fk_sets(
valid_clave_regimen_tipo, # (pedimento_code, regimen_code, type_code)
valid_aduana_seccion, # customs_code
existing_pedimento_keys, # key strings para actualizar
valid_anexo22_claves, # stub vacío hasta tener catálogo
valid_anexo22_claves, # catálogo de transporte Anexo 22 (pedimento_transport_catalog.code)
valid_patentes, # CustomsBroker.license (tenant/company)
short_name_to_id, # short_name normalizado (upper) -> client id (primera aparición gana)
"""
@@ -48,6 +48,9 @@ def load_pedimentos_fk_sets(
from api.v1.modules.public.reference_data.customs_sections.models import CustomsSection
from api.v1.modules.public.reference_data.pedimento_codes.models import PedimentoCode
from api.v1.modules.public.reference_data.pedimento_regimens.models import RegimenPedimento
from api.v1.modules.public.reference_data.pedimento_transport_catalog.models import (
PedimentoTransportCatalog,
)
valid_client_ids: Set[int] = set()
valid_regimes: Set[str] = set()
@@ -96,6 +99,10 @@ def load_pedimentos_fk_sets(
for cs in session.query(CustomsSection).all():
valid_aduana_seccion.add(cs.customs_code.strip())
for tm in session.query(PedimentoTransportCatalog.code).all():
if (tm[0] or "").strip():
valid_anexo22_claves.add((tm[0] or "").strip().upper())
for cb in (
session.query(CustomsBroker)
.filter(

View File

@@ -8,6 +8,9 @@ from api.v1.modules.public.reference_data.customs_sections.models import Customs
from api.v1.modules.public.reference_data.code_pedimento_regimens.models import CodePedimentoRegimen
from api.v1.modules.public.reference_data.transport_types.models import TransportType
from api.v1.modules.public.reference_data.transport_modes.models import TransportMode
from api.v1.modules.public.reference_data.pedimento_transport_catalog.models import (
PedimentoTransportCatalog,
)
# Import A76 Services
from api.v1.modules.a76.customs_brokers.services import CustomsBrokerService
@@ -19,6 +22,9 @@ from api.v1.modules.public.reference_data.customs_sections.dto import CustomsSec
from api.v1.modules.public.reference_data.code_pedimento_regimens.dto import CodePedimentoRegimenDTO
from api.v1.modules.public.reference_data.transport_types.dto import TransportTypeDTO
from api.v1.modules.public.reference_data.transport_modes.dto import TransportModeDTO
from api.v1.modules.public.reference_data.pedimento_transport_catalog.dto import (
PedimentoTransportCatalogDTO,
)
from api.v1.modules.a76.customs_brokers.dto import CustomsBrokerResponseDTO
from api.v1.modules.a76.clients_and_providers.dto import ClientProviderResponseDTO
from .dtos.pedimentos import PedimentosResponse
@@ -71,6 +77,16 @@ class PedimentoCatalogService:
except Exception as e:
print(f"Error fetching transport_modes: {e}")
try:
response.pedimento_transport_catalog = [
PedimentoTransportCatalogDTO.model_validate(obj)
for obj in db.query(PedimentoTransportCatalog)
.order_by(PedimentoTransportCatalog.code.asc())
.all()
]
except Exception as e:
print(f"Error fetching pedimento_transport_catalog: {e}")
# Helper to fetch tenant/company specific data
def fetch_tenant_data():
# Customs Brokers

View File

@@ -10,27 +10,27 @@ class PedimentoTransportMeansBase(BaseModel):
pedimento_id: Optional[int] = Field(None, description="Pedimento ID")
tenant_id: Optional[int] = Field(None, description="Tenant ID")
destination: Optional[int] = Field(None, description="Destination")
entry_exit: Optional[str] = Field(None, max_length=2, description="Entry/exit")
arrival: str = Field(..., max_length=2, description="Arrival")
departure: str = Field(..., max_length=2, description="Departure")
entry_exit: Optional[str] = Field(None, max_length=3, description="Entry/exit")
arrival: str = Field(..., max_length=3, description="Arrival")
departure: str = Field(..., max_length=3, description="Departure")
class PedimentoTransportMeansCreate(BaseModel):
"""Schema for creating a new Pedimento Transport Means - pedimento_id and tenant_id are set by backend"""
destination: Optional[int] = Field(None, description="Destination")
entry_exit: Optional[str] = Field(None, max_length=2, description="Entry/exit")
arrival: str = Field(..., max_length=2, description="Arrival")
departure: str = Field(..., max_length=2, description="Departure")
entry_exit: Optional[str] = Field(None, max_length=3, description="Entry/exit")
arrival: str = Field(..., max_length=3, description="Arrival")
departure: str = Field(..., max_length=3, description="Departure")
class PedimentoTransportMeansUpdate(BaseModel):
"""Schema for updating a Pedimento Transport Means"""
destination: Optional[int] = None
entry_exit: Optional[str] = Field(None, max_length=2)
arrival: Optional[str] = Field(None, max_length=2)
departure: Optional[str] = Field(None, max_length=2)
entry_exit: Optional[str] = Field(None, max_length=3)
arrival: Optional[str] = Field(None, max_length=3)
departure: Optional[str] = Field(None, max_length=3)
class PedimentoTransportMeansResponse(PedimentoTransportMeansBase):

View File

@@ -39,9 +39,9 @@ class PedimentoTransportMeans(Base, TenantScopedMixin, TimestampMixin):
pedimento_id: Mapped[int] = mapped_column(Integer, nullable=False)
destination: Mapped[int] = mapped_column(SmallInteger)
entry_exit: Mapped[str] = mapped_column(String(2))
arrival: Mapped[str] = mapped_column(String(2))
departure: Mapped[str] = mapped_column(String(2))
entry_exit: Mapped[str] = mapped_column(String(3))
arrival: Mapped[str] = mapped_column(String(3))
departure: Mapped[str] = mapped_column(String(3))
pedimento: Mapped["Pedimentos"] = relationship(
"Pedimentos", back_populates="pedimento_transport_means"

View File

@@ -13,6 +13,9 @@ from api.v1.modules.a76.customs_brokers.dto import CustomsBrokerResponseDTO
from api.v1.modules.a76.clients_and_providers.dto import ClientProviderResponseDTO
from api.v1.modules.public.reference_data.transport_types.dto import TransportTypeDTO
from api.v1.modules.public.reference_data.transport_modes.dto import TransportModeDTO
from api.v1.modules.public.reference_data.pedimento_transport_catalog.dto import (
PedimentoTransportCatalogDTO,
)
from .dtos.pedimentos import PedimentosResponse
@@ -26,6 +29,7 @@ class PedimentoCatalogsResponse(BaseModel):
clients: List[ClientProviderResponseDTO] = []
transport_types: List[TransportTypeDTO] = []
transport_modes: List[TransportModeDTO] = []
pedimento_transport_catalog: List[PedimentoTransportCatalogDTO] = []
class PedimentoCreationResponse(PedimentoCatalogsResponse):

View File

@@ -227,7 +227,7 @@ BASE_SELECT = """
COALESCE(icm.vucem_operation_num,'') AS "C41",
COALESCE(cl.material_key,'') AS "C42",
CONCAT(ped.year,'-',ped.customs_office,'-',ped.license,'-',ped.pedimento_number) AS "C43",
'' AS "C44",
COALESCE(ptc.payment_date_code, 'P') AS "C44",
COALESCE(ilc.octave_fraction,'') AS "C45",
'' AS "C47",
COALESCE(ped.pedimento_code,'') AS "C48",
@@ -243,6 +243,8 @@ BASE_JOINS = """
JOIN a76.invoice_compliance_mx icm ON icm.invoice_id = ih.id
LEFT JOIN a76.pedimentos ped ON ped.id = icm.pedimento_id
LEFT JOIN a76.pedimento_dates pd ON pd.pedimento_id = ped.id
LEFT JOIN a76.pedimento_transport_means ptm ON ptm.pedimento_id = ped.id
LEFT JOIN public.pedimento_transport_catalog ptc ON ptc.code = ptm.entry_exit
LEFT JOIN a76.classes cl ON cl.id = il.class_id
LEFT JOIN a76.item_line_quantities ilq ON ilq.item_line_id = il.id
LEFT JOIN a76.item_line_financials ilf ON ilf.item_line_id = il.id
@@ -440,20 +442,21 @@ def _build_row(
peso_usado = (cant_ret * peso_neto / cant_orig) if cant_orig != 0 else Decimal(0)
peso_saldo = peso_neto - peso_usado
# TIPO DE CAMBIO — per Clarion logic:
# Si TipoPedimentoTransporteE IN ('4','1','98E') → usar Fecha_Inicio, else Fecha_Pago
# TIPO DE CAMBIO:
# C44 now carries payment_date_code from pedimento_transport_catalog:
# E => Fecha_Inicio, P => Fecha_Pago.
# If explicitly "invoice_date", we use invoice_date (C11) instead.
tc = Decimal(1)
fecha_pago = row.get("C7")
fecha_inicio = row.get("C9")
fecha_factura= row.get("C11")
transport_type = str(row.get("C44") or "")
payment_date_code = str(row.get("C44") or "").upper()
tc_fecha_display = None
# TIPO DE CAMBIO
tc_fecha = None
if use_fp:
tc_fecha = fecha_inicio if transport_type in ("1", "4", "98E") else fecha_pago
tc_fecha = fecha_inicio if payment_date_code == "E" else fecha_pago
else:
tc_fecha = fecha_factura

View File

@@ -0,0 +1,10 @@
from pydantic import BaseModel, ConfigDict, Field
class PedimentoTransportCatalogDTO(BaseModel):
code: str = Field(..., min_length=1, max_length=3)
transport_en: str
transport_es: str
payment_date_code: str = Field(..., min_length=1, max_length=1)
model_config = ConfigDict(from_attributes=True)

View File

@@ -0,0 +1,26 @@
from core.database import Base
from sqlalchemy import CheckConstraint, PrimaryKeyConstraint, String
from sqlalchemy.orm import Mapped, mapped_column
class PedimentoTransportCatalog(Base):
__tablename__ = "pedimento_transport_catalog"
__table_args__ = (
PrimaryKeyConstraint("code", name="pedimento_transport_catalog_pkey"),
CheckConstraint(
"payment_date_code IN ('E', 'P')",
name="pedimento_transport_catalog_payment_date_code_chk",
),
{"schema": "public", "extend_existing": True},
)
code: Mapped[str] = mapped_column(String(3), nullable=False)
transport_en: Mapped[str] = mapped_column(String(80), nullable=False)
transport_es: Mapped[str] = mapped_column(String(120), nullable=False)
payment_date_code: Mapped[str] = mapped_column(String(1), nullable=False)
def __repr__(self) -> str:
return (
f"<PedimentoTransportCatalog(code={self.code}, transport_en={self.transport_en}, "
f"transport_es={self.transport_es}, payment_date_code={self.payment_date_code})>"
)

View File

@@ -0,0 +1,93 @@
from typing import Any, Dict
from core.database import get_core_db
from core.security import get_current_user
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from .dto import PedimentoTransportCatalogDTO
from .models import PedimentoTransportCatalog
router = APIRouter(prefix="/pedimento-transport-catalog")
@router.get("/", response_model=Dict[str, Any])
async def list_pedimento_transport_catalog(
page: int = Query(1, ge=1, description="Numero de pagina"),
page_size: int = Query(100, ge=1, le=200, description="Tamano de pagina"),
db: Session = Depends(get_core_db),
):
skip = (page - 1) * page_size
query = db.query(PedimentoTransportCatalog).order_by(PedimentoTransportCatalog.code.asc())
items = query.offset(skip).limit(page_size).all()
total = query.count()
return {
"items": [PedimentoTransportCatalogDTO.model_validate(obj) for obj in items],
"total": total,
"page": page,
"page_size": page_size,
}
@router.get("/{code}", response_model=PedimentoTransportCatalogDTO)
async def get_pedimento_transport_catalog(code: str, db: Session = Depends(get_core_db)):
obj = (
db.query(PedimentoTransportCatalog)
.filter(PedimentoTransportCatalog.code == code)
.first()
)
if not obj:
raise HTTPException(status_code=404, detail="Not found")
return obj
@router.post("/", response_model=PedimentoTransportCatalogDTO, status_code=201)
async def create_pedimento_transport_catalog(
data: PedimentoTransportCatalogDTO,
db: Session = Depends(get_core_db),
user=Depends(get_current_user),
):
obj = PedimentoTransportCatalog(**data.model_dump())
db.add(obj)
db.commit()
db.refresh(obj)
return obj
@router.put("/{code}", response_model=PedimentoTransportCatalogDTO)
async def update_pedimento_transport_catalog(
code: str,
data: PedimentoTransportCatalogDTO,
db: Session = Depends(get_core_db),
user=Depends(get_current_user),
):
obj = (
db.query(PedimentoTransportCatalog)
.filter(PedimentoTransportCatalog.code == code)
.first()
)
if not obj:
raise HTTPException(status_code=404, detail="Not found")
for field, value in data.model_dump().items():
setattr(obj, field, value)
db.commit()
db.refresh(obj)
return obj
@router.delete("/{code}", status_code=204)
async def delete_pedimento_transport_catalog(
code: str,
db: Session = Depends(get_core_db),
user=Depends(get_current_user),
):
obj = (
db.query(PedimentoTransportCatalog)
.filter(PedimentoTransportCatalog.code == code)
.first()
)
if not obj:
raise HTTPException(status_code=404, detail="Not found")
db.delete(obj)
db.commit()
return None

View File

@@ -0,0 +1,16 @@
seed = [
("1", "MARITIME", "MARITIMO", "E"),
("2", "DOUBLE-TRACK RAIL", "FERROVIARIO DE DOBLE VIA", "P"),
("3", "ROAD-RAIL", "CARRETERO-FERROVIARIO", "P"),
("4", "AIR", "AEREO.", "E"),
("5", "POSTAL", "POSTAL.", "P"),
("6", "RAIL", "FERROVIARIO.", "P"),
("7", "ROAD", "CARRETERO.", "P"),
("8", "PIPELINE", "TUBERIA.", "P"),
("10", "CABLE", "CABLES.", "P"),
("11", "DUCT", "DUCTOS.", "P"),
("12", "PEDESTRIAN", "PEATONAL.", "P"),
("98", "NOT DECLARED TRANSPORT MODE", "NO SE DECLARA MEDIO DE TRANSPORTE", "P"),
("98E", "NOT DECLARED TRANSPORT MODE", "NO SE DECLARA MEDIO DE TRANSPORTE", "E"),
("99", "OTHERS", "OTROS.", "P"),
]

View File

@@ -15,6 +15,7 @@ from .incoterms.routes import router as incoterms_router
from .invoice_types.routes import router as invoice_types_router
from .material_types.routes import router as material_types_router
from .payment_methods.routes import router as payment_methods_router
from .pedimento_transport_catalog.routes import router as pedimento_transport_catalog_router
from .pedimento_codes.routes import router as pedimento_codes_router
from .pedimento_regimens.routes import router as pedimento_regimens_router
from .states.routes import router as states_router
@@ -27,6 +28,11 @@ from .valuation_methods.routes import router as valuation_methods_router
router = APIRouter()
# Registrar módulos
router.include_router(
pedimento_transport_catalog_router,
prefix="/reference_data",
tags=["public / reference_data / pedimento_transport_catalog"],
)
router.include_router(
pedimento_codes_router,
prefix="/reference_data",