feat(crm): catálogos Clientes/Prospectos (enriquecido) y Proveedores + direcciones/documentos

Alinea el dominio al spec de catálogos:
- accounts (Clientes/Prospectos): tipo registro/persona, CURP, clasificación
  comercial, bloque fiscal (régimen, CFDI, pago, crédito), auditoría, notas internas
- suppliers (Proveedores): clasificación múltiple, cobertura, países/puertos/
  aeropuertos/aduanas (JSON), fiscal
- addresses y documents: tablas compartidas con FK a cliente o proveedor
- contacts enriquecidos (extensión, whatsapp, área, flags "recibe…", supplier_id)
- migración a7b8c9d0e1f2 (ALTER + CREATE) con downgrade completo
- permisos supplier/address/document; seed de datos actualizado
- 39 tests pytest en verde

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Aduanasoft
2026-07-14 16:19:13 -06:00
parent 2ed6247f1e
commit b12af1a561
31 changed files with 1599 additions and 101 deletions

View File

@@ -0,0 +1,88 @@
from datetime import datetime
from decimal import Decimal
from pydantic import BaseModel, ConfigDict, EmailStr, Field
class SupplierBase(BaseModel):
# Datos generales
name: str = Field(..., min_length=1, max_length=255)
trade_name: str | None = Field(None, max_length=255)
rfc: str | None = Field(None, max_length=13)
curp: str | None = Field(None, max_length=18)
person_type: str | None = Field(None, max_length=10)
status: str = Field("active", max_length=20)
classifications: list[str] = Field(default_factory=list)
# Comercial
services_offered: str | None = None
coverage: str | None = Field(None, max_length=20)
countries: list[str] = Field(default_factory=list)
ports: list[str] = Field(default_factory=list)
airports: list[str] = Field(default_factory=list)
customs: list[str] = Field(default_factory=list)
business_hours: str | None = Field(None, max_length=255)
quote_currency: str | None = Field(None, max_length=3)
avg_response_time: str | None = Field(None, max_length=120)
commercial_notes: str | None = None
email: EmailStr | None = None
phone: str | None = Field(None, max_length=40)
website: str | None = Field(None, max_length=255)
# Fiscal
tax_regime: str | None = Field(None, max_length=120)
payment_method: str | None = Field(None, max_length=60)
payment_form: str | None = Field(None, max_length=60)
credit_limit: Decimal | None = Field(None, ge=0, max_digits=14, decimal_places=2)
credit_days: int | None = Field(None, ge=0)
commercial_terms: str | None = None
# Observaciones
notes: str | None = None
internal_notes: str | None = None
owner_user_id: str | None = Field(None, max_length=64)
class SupplierCreate(SupplierBase):
pass
class SupplierUpdate(BaseModel):
name: str | None = Field(None, min_length=1, max_length=255)
trade_name: str | None = Field(None, max_length=255)
rfc: str | None = Field(None, max_length=13)
curp: str | None = Field(None, max_length=18)
person_type: str | None = Field(None, max_length=10)
status: str | None = Field(None, max_length=20)
classifications: list[str] | None = None
services_offered: str | None = None
coverage: str | None = Field(None, max_length=20)
countries: list[str] | None = None
ports: list[str] | None = None
airports: list[str] | None = None
customs: list[str] | None = None
business_hours: str | None = Field(None, max_length=255)
quote_currency: str | None = Field(None, max_length=3)
avg_response_time: str | None = Field(None, max_length=120)
commercial_notes: str | None = None
email: EmailStr | None = None
phone: str | None = Field(None, max_length=40)
website: str | None = Field(None, max_length=255)
tax_regime: str | None = Field(None, max_length=120)
payment_method: str | None = Field(None, max_length=60)
payment_form: str | None = Field(None, max_length=60)
credit_limit: Decimal | None = Field(None, ge=0, max_digits=14, decimal_places=2)
credit_days: int | None = Field(None, ge=0)
commercial_terms: str | None = None
notes: str | None = None
internal_notes: str | None = None
owner_user_id: str | None = Field(None, max_length=64)
class SupplierResponse(SupplierBase):
model_config = ConfigDict(from_attributes=True)
id: int
tenant_id: int
company_id: int
created_by: str | None = None
updated_by: str | None = None
created_at: datetime
updated_at: datetime

View File

@@ -0,0 +1,62 @@
from decimal import Decimal
from sqlalchemy import JSON, Integer, Numeric, String, Text, text
from sqlalchemy.orm import Mapped, mapped_column
from api.v1.common.base_models import TenantScopedMixin, TimestampMixin
from core.database import Base
class Supplier(Base, TenantScopedMixin, TimestampMixin):
"""Catálogo de Proveedores (navieras, aerolíneas, transportistas, agentes, etc.).
Los campos multi-valor (clasificaciones, cobertura por país/puerto/aduana) se
guardan como listas JSON. Direcciones, contactos y documentos viven en tablas
relacionadas (crm.addresses, crm.contacts, crm.documents).
"""
__tablename__ = "suppliers"
__table_args__ = {"schema": "crm"}
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
# ----- Datos generales -----
name: Mapped[str] = mapped_column(String(255), nullable=False) # razón social
trade_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
rfc: Mapped[str | None] = mapped_column(String(13), nullable=True, index=True)
curp: Mapped[str | None] = mapped_column(String(18), nullable=True)
person_type: Mapped[str | None] = mapped_column(String(10), nullable=True) # fisica | moral
status: Mapped[str] = mapped_column(String(20), nullable=False, server_default=text("'active'"))
# Clasificación (múltiple): naviera, aerolinea, transportista_terrestre, ferrocarril,
# agente_aduanal, agente_carga, agente_corresponsal, almacen, aseguradora, paqueteria, otro
classifications: Mapped[list | None] = mapped_column(JSON, nullable=True, default=list)
# ----- Información comercial -----
services_offered: Mapped[str | None] = mapped_column(Text, nullable=True)
coverage: Mapped[str | None] = mapped_column(String(20), nullable=True) # nacional | internacional | ambos
countries: Mapped[list | None] = mapped_column(JSON, nullable=True, default=list)
ports: Mapped[list | None] = mapped_column(JSON, nullable=True, default=list)
airports: Mapped[list | None] = mapped_column(JSON, nullable=True, default=list)
customs: Mapped[list | None] = mapped_column(JSON, nullable=True, default=list) # aduanas
business_hours: Mapped[str | None] = mapped_column(String(255), nullable=True)
quote_currency: Mapped[str | None] = mapped_column(String(3), nullable=True)
avg_response_time: Mapped[str | None] = mapped_column(String(120), nullable=True)
commercial_notes: Mapped[str | None] = mapped_column(Text, nullable=True)
email: Mapped[str | None] = mapped_column(String(255), nullable=True)
phone: Mapped[str | None] = mapped_column(String(40), nullable=True)
website: Mapped[str | None] = mapped_column(String(255), nullable=True)
# ----- Información fiscal -----
tax_regime: Mapped[str | None] = mapped_column(String(120), nullable=True)
payment_method: Mapped[str | None] = mapped_column(String(60), nullable=True)
payment_form: Mapped[str | None] = mapped_column(String(60), nullable=True)
credit_limit: Mapped[Decimal | None] = mapped_column(Numeric(14, 2), nullable=True)
credit_days: Mapped[int | None] = mapped_column(Integer, nullable=True)
commercial_terms: Mapped[str | None] = mapped_column(Text, nullable=True)
# ----- Observaciones y auditoría -----
notes: Mapped[str | None] = mapped_column(Text, nullable=True) # comentarios generales
internal_notes: Mapped[str | None] = mapped_column(Text, nullable=True)
owner_user_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
created_by: Mapped[str | None] = mapped_column(String(64), nullable=True)
updated_by: Mapped[str | None] = mapped_column(String(64), nullable=True)

View File

@@ -0,0 +1,71 @@
from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.orm import Session
from core.database import get_core_db
from core.security import get_current_user
from . import service
from .dto import SupplierCreate, SupplierResponse, SupplierUpdate
router = APIRouter()
def _user_id(current_user: dict) -> str | None:
return current_user.get("sub") or current_user.get("id")
@router.get("/suppliers", response_model=list[SupplierResponse])
def list_suppliers(
company_id: int = Query(..., description="Company ID"),
search: str | None = Query(None, description="Búsqueda por nombre o RFC"),
supplier_status: str | None = Query(None, alias="status", description="Filtrar por estatus"),
current_user: dict = Depends(get_current_user),
db: Session = Depends(get_core_db),
):
tenant_id = current_user["tenant_id"]
return service.get_suppliers(db, tenant_id, company_id, search, supplier_status)
@router.get("/suppliers/{supplier_id}", response_model=SupplierResponse)
def get_supplier(
supplier_id: int,
company_id: int = Query(..., description="Company ID"),
current_user: dict = Depends(get_current_user),
db: Session = Depends(get_core_db),
):
tenant_id = current_user["tenant_id"]
return service.get_supplier(db, supplier_id, tenant_id, company_id)
@router.post("/suppliers", response_model=SupplierResponse, status_code=status.HTTP_201_CREATED)
def create_supplier(
payload: SupplierCreate,
company_id: int = Query(..., description="Company ID"),
current_user: dict = Depends(get_current_user),
db: Session = Depends(get_core_db),
):
tenant_id = current_user["tenant_id"]
return service.create_supplier(db, payload, tenant_id, company_id, _user_id(current_user))
@router.patch("/suppliers/{supplier_id}", response_model=SupplierResponse)
def update_supplier(
supplier_id: int,
payload: SupplierUpdate,
company_id: int = Query(..., description="Company ID"),
current_user: dict = Depends(get_current_user),
db: Session = Depends(get_core_db),
):
tenant_id = current_user["tenant_id"]
return service.update_supplier(db, supplier_id, payload, tenant_id, company_id, _user_id(current_user))
@router.delete("/suppliers/{supplier_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_supplier(
supplier_id: int,
company_id: int = Query(..., description="Company ID"),
current_user: dict = Depends(get_current_user),
db: Session = Depends(get_core_db),
):
tenant_id = current_user["tenant_id"]
service.delete_supplier(db, supplier_id, tenant_id, company_id)

View File

@@ -0,0 +1,86 @@
from datetime import datetime, timezone
from fastapi import HTTPException, status
from sqlalchemy.orm import Session
from .dto import SupplierCreate, SupplierUpdate
from .models import Supplier
def get_suppliers(
db: Session,
tenant_id: int,
company_id: int,
search: str | None = None,
supplier_status: str | None = None,
) -> list[Supplier]:
query = db.query(Supplier).filter(
Supplier.tenant_id == tenant_id,
Supplier.company_id == company_id,
Supplier.deleted_at.is_(None),
)
if search:
pattern = f"%{search}%"
query = query.filter(
Supplier.name.ilike(pattern)
| Supplier.trade_name.ilike(pattern)
| Supplier.rfc.ilike(pattern)
)
if supplier_status:
query = query.filter(Supplier.status == supplier_status)
return query.order_by(Supplier.name.asc()).all()
def get_supplier(db: Session, supplier_id: int, tenant_id: int, company_id: int) -> Supplier:
supplier = (
db.query(Supplier)
.filter(
Supplier.id == supplier_id,
Supplier.tenant_id == tenant_id,
Supplier.company_id == company_id,
Supplier.deleted_at.is_(None),
)
.first()
)
if not supplier:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Proveedor no encontrado")
return supplier
def create_supplier(
db: Session, payload: SupplierCreate, tenant_id: int, company_id: int, user_id: str | None = None
) -> Supplier:
supplier = Supplier(
**payload.model_dump(),
tenant_id=tenant_id,
company_id=company_id,
created_by=user_id,
updated_by=user_id,
)
db.add(supplier)
db.commit()
db.refresh(supplier)
return supplier
def update_supplier(
db: Session,
supplier_id: int,
payload: SupplierUpdate,
tenant_id: int,
company_id: int,
user_id: str | None = None,
) -> Supplier:
supplier = get_supplier(db, supplier_id, tenant_id, company_id)
for field, value in payload.model_dump(exclude_unset=True).items():
setattr(supplier, field, value)
supplier.updated_by = user_id
db.commit()
db.refresh(supplier)
return supplier
def delete_supplier(db: Session, supplier_id: int, tenant_id: int, company_id: int) -> None:
supplier = get_supplier(db, supplier_id, tenant_id, company_id)
supplier.deleted_at = datetime.now(timezone.utc)
db.commit()