Refactor and enhance CRUD operations for Seal, Trailer, Transporter, Vehicle, and Customs Broker modules

- Updated SealService to support tenant and company filtering with pagination and enhanced CRUD methods.
- Refactored TrailerService to include tenant and company support, added filtering capabilities, and improved CRUD methods.
- Introduced TenantCRUDRoutes for Trailer and Transporter routes to streamline API endpoint creation and management.
- Enhanced TransporterService with tenant and company filtering, pagination, and improved CRUD operations.
- Added Customs Broker module with DTOs, models, services, and routes for managing customs broker data.
- Implemented CRUD operations for Customs Broker, including personnel and VU management.
- Improved data validation and descriptions in DTOs for better API documentation.
This commit is contained in:
2025-11-11 18:20:39 -06:00
parent b68c4316ff
commit 962f43fe62
39 changed files with 1488 additions and 1366 deletions

View File

@@ -1,40 +1,40 @@
"""
DTOs for GBultos.
DTOs for Packages (GBultos).
"""
from typing import Optional
from pydantic import BaseModel
from pydantic import BaseModel, Field
class GBultoBaseDTO(BaseModel):
CODE: str
DESCRIPTION: Optional[str]
DESCRIPTIONI: Optional[str]
WEIGHT_UNIT: Optional[float]
PLURALS: Optional[str]
PLURAL_IN: Optional[str]
CODE_ACE: Optional[str]
CODE_AAMEX: Optional[str]
class PackageBaseDTO(BaseModel):
key: str = Field(..., description="Package key (primary identifier)", max_length=5)
description_es: Optional[str] = Field(None, description="Description in Spanish", max_length=40)
description_en: Optional[str] = Field(None, description="Description in English", max_length=40)
weight_unit: Optional[float] = Field(None, description="Weight unit")
plurals: Optional[str] = Field(None, max_length=4)
plural_in: Optional[str] = Field(None, max_length=4)
code_ace: Optional[str] = Field(None, max_length=4)
code_aamex: Optional[str] = Field(None, max_length=9)
class GBultoCreateDTO(GBultoBaseDTO):
class PackageCreateDTO(PackageBaseDTO):
"""Schema for creating a package"""
pass
class GBultoUpdateDTO(BaseModel):
DESCRIPTION: Optional[str]
DESCRIPTIONI: Optional[str]
WEIGHT_UNIT: Optional[float]
PLURALS: Optional[str]
PLURAL_IN: Optional[str]
CODE_ACE: Optional[str]
CODE_AAMEX: Optional[str]
class PackageUpdateDTO(PackageBaseDTO):
"""Schema for updating a package"""
key: Optional[str] = Field(None, description="Package key (cannot be modified)", max_length=5)
class GBultoResponseDTO(GBultoBaseDTO):
CREATED_AT: Optional[str]
UPDATED_AT: Optional[str]
class PackageResponseDTO(PackageBaseDTO):
"""Schema for package response"""
id: int
company_id: int
tenant_id: int
created_at: Optional[str] = None
updated_at: Optional[str] = None
class Config:
from_attributes = True

View File

@@ -1,127 +1,24 @@
from typing import List
"""
Routes for managing Packages (GBultos).
"""
from core.database import get_core_db
from core.security import get_current_user
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from api.v1.common.tenant_crud_routes import TenantCRUDRoutes
from .dto import GBultoCreateDTO, GBultoResponseDTO, GBultoUpdateDTO
from .models import Package
from .services import GBultoService
from .dto import PackageCreateDTO, PackageResponseDTO, PackageUpdateDTO
from .services import PackageService
router = APIRouter(prefix="/bultos", tags=["GBultos"])
@router.get("/", response_model=List[GBultoResponseDTO])
async def list_bultos(
skip: int = 0,
limit: int = 100,
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
"""
List all GBultos with 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"
)
return db.query(Package).offset(skip).limit(limit).all()
@router.get("/{code}", response_model=GBultoResponseDTO)
async def read_bulto(
code: str,
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
"""
Get a specific Package by its CODE.
"""
# 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"
)
bulto = GBultoService.get_bulto_by_code(db, code)
if not bulto:
raise HTTPException(status_code=404, detail="Package not found")
return bulto
@router.post("/", response_model=GBultoResponseDTO, status_code=status.HTTP_201_CREATED)
async def create_gbulto(
bulto_data: GBultoCreateDTO,
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
"""
Create a new Package.
"""
# 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"
)
return GBultoService.create_gbulto(db, bulto_data)
@router.put("/{code}", response_model=GBultoResponseDTO)
async def update_bulto(
code: str,
bulto_data: GBultoUpdateDTO,
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
"""
Update an existing Package.
"""
# 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"
)
bulto = GBultoService.update_bulto(db, code, bulto_data)
if not bulto:
raise HTTPException(status_code=404, detail="Package not found")
return bulto
@router.delete("/{code}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_bulto(
code: str,
db: Session = Depends(get_core_db),
current_user: dict = Depends(get_current_user),
):
"""
Delete a Package by its CODE.
"""
# 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"
)
bulto = GBultoService.delete_bulto(db, code)
if not bulto:
raise HTTPException(status_code=404, detail="Package not found")
# Create router using TenantCRUDRoutes factory
router = TenantCRUDRoutes(
service=PackageService,
create_schema=PackageCreateDTO,
update_schema=PackageUpdateDTO,
response_schema=PackageResponseDTO,
prefix="/package",
tags=[],
resource_name="Package",
id_name="id", # Using numeric ID
enable_list=True, # Enable GET /package with pagination
enable_filters=True, # Enable filtering by key and description_es
default_page_size=50,
max_page_size=100,
).router

View File

@@ -1,39 +1,110 @@
"""
Service layer for Packages (GBultos).
"""
from typing import Optional, Tuple, List, Dict, Any
from sqlalchemy.orm import Session
from . import dto, models
class GBultoService:
"""
Service layer for GBultos.
"""
class PackageService:
"""Service for Package CRUD operations with tenant support"""
@staticmethod
def get_bulto_by_code(db: Session, code: str):
return db.query(models.Package).filter(models.Package.CODE == code).first()
def get_all(
db: Session,
tenant_id: int,
company_id: int,
skip: int = 0,
limit: int = 50,
filters: Optional[Dict[str, Any]] = None,
) -> Tuple[List[models.Package], int]:
"""Get all packages for a tenant/company with pagination"""
query = db.query(models.Package).filter(
models.Package.tenant_id == tenant_id,
models.Package.company_id == company_id,
)
# Apply filters if provided
if filters:
if filters.get("key"):
query = query.filter(
models.Package.key.ilike(f"%{filters['key']}%")
)
if filters.get("description_es"):
query = query.filter(
models.Package.description_es.ilike(f"%{filters['description_es']}%")
)
total = query.count()
packages = query.offset(skip).limit(limit).all()
return packages, total
@staticmethod
def create_gbulto(db: Session, gbulto_data: dto.GBultoCreateDTO):
new_gbulto = models.Package(**gbulto_data.dict())
db.add(new_gbulto)
def get_by_id(
db: Session, package_id: int, tenant_id: int, company_id: int
) -> Optional[models.Package]:
"""Get package by ID"""
return (
db.query(models.Package)
.filter(
models.Package.id == package_id,
models.Package.tenant_id == tenant_id,
models.Package.company_id == company_id,
)
.first()
)
@staticmethod
def create(
db: Session,
package_data: dto.PackageCreateDTO,
tenant_id: int,
company_id: int,
) -> models.Package:
"""Create a new package"""
new_package = models.Package(
**package_data.model_dump(), tenant_id=tenant_id, company_id=company_id
)
db.add(new_package)
db.commit()
db.refresh(new_gbulto)
return new_gbulto
db.refresh(new_package)
return new_package
@staticmethod
def update_bulto(db: Session, code: str, bulto_data: dto.GBultoUpdateDTO):
bulto = GBultoService.get_bulto_by_code(db, code)
if bulto:
for key, value in bulto_data.dict(exclude_unset=True).items():
setattr(bulto, key, value)
db.commit()
db.refresh(bulto)
return bulto
def update(
db: Session,
package_id: int,
tenant_id: int,
company_id: int,
package_data: dto.PackageUpdateDTO,
) -> Optional[models.Package]:
"""Update a package"""
package = PackageService.get_by_id(db, package_id, tenant_id, company_id)
if not package:
return None
# Update fields (excluding key if it's meant to be immutable)
update_data = package_data.model_dump(exclude_unset=True, exclude={"key"})
for field, value in update_data.items():
setattr(package, field, value)
db.commit()
db.refresh(package)
return package
@staticmethod
def delete_bulto(db: Session, code: str):
bulto = GBultoService.get_bulto_by_code(db, code)
if bulto:
db.delete(bulto)
db.commit()
return bulto
def delete(
db: Session, package_id: int, tenant_id: int, company_id: int
) -> bool:
"""Delete a package"""
package = PackageService.get_by_id(db, package_id, tenant_id, company_id)
if not package:
return False
db.delete(package)
db.commit()
return True