feat(crm): ampliar solicitud de servicio y encadenar el ciclo comercial
Solicitud de servicio:
- Campos del documento maestro de cotización (ruta estructurada por país,
mercancía, dimensiones/bultos, FCL/LCL, servicios adicionales, notas).
- Origen/Destino seleccionables por catálogo de país (seed ya poblado).
- Validación de contacto asociado (422 si no existe).
Ciclo Oportunidad -> Solicitud -> Cotización -> Operación:
- Dirección impo/expo se captura en la Oportunidad y se hereda al ciclo.
- Conversión Oportunidad->Solicitud idempotente con back-link.
- Endpoint Solicitud->Cotización; "Ambas" genera 2 cotizaciones (FCL/LCL).
- Liberación a Operaciones confirma IMPO/EXPO (prefijado) y siembra los hitos.
- Fecha de la cotización (issue_date) por defecto hoy, editable y en el PDF.
Folios auto-generados {LETRA}{AAAA}-{MM}-{NNN}-{DIR} para Oportunidad (O),
Solicitud (S), Cotización (C) y Operación (OP); consecutivo mensual por
compañía y entidad (crm.folio_counters + helper next_folio con bloqueo de fila).
Catálogos: 9 nuevos (tipo_operacion, medio_transporte, tipo_servicio, prioridad,
tipo_mercancia, unidad_medida, tipo_embalaje, servicio_adicional, tipo_documento).
Migración b1c2d3e4f5a6 reversible (upgrade->downgrade->upgrade verificado en PG).
25 pruebas unitarias nuevas (folios, catálogos, solicitudes, cotizaciones,
embarques); suite completa en verde (101 pruebas).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -56,6 +56,7 @@ class QuoteBase(BaseModel):
|
||||
service_request_id: int | None = None
|
||||
account_id: int | None = None
|
||||
currency: str = Field("USD", max_length=3)
|
||||
load_type: str | None = Field(None, max_length=10) # FCL | LCL (variante de la comparación "Ambas")
|
||||
issue_date: date | None = None
|
||||
valid_until: date | None = None
|
||||
notes: str | None = None
|
||||
@@ -72,6 +73,7 @@ class QuoteUpdate(BaseModel):
|
||||
service_request_id: int | None = None
|
||||
account_id: int | None = None
|
||||
currency: str | None = Field(None, max_length=3)
|
||||
load_type: str | None = Field(None, max_length=10)
|
||||
issue_date: date | None = None
|
||||
valid_until: date | None = None
|
||||
notes: str | None = None
|
||||
|
||||
@@ -22,6 +22,8 @@ class Quote(Base, TenantScopedMixin, TimestampMixin):
|
||||
Integer, ForeignKey("crm.accounts.id"), nullable=True, index=True
|
||||
)
|
||||
currency: Mapped[str] = mapped_column(String(3), nullable=False, server_default=text("'USD'"))
|
||||
# Variante de carga cuando la solicitud es "Ambas": FCL | LCL (NULL si no aplica)
|
||||
load_type: Mapped[str | None] = mapped_column(String(10), nullable=True)
|
||||
# borrador | enviada | aceptada | rechazada
|
||||
status: Mapped[str] = mapped_column(String(20), nullable=False, server_default=text("'borrador'"), index=True)
|
||||
issue_date: Mapped[date | None] = mapped_column(Date, nullable=True)
|
||||
|
||||
@@ -59,6 +59,14 @@ def set_logo_key(db: Session, tenant_id: int, company_id: int, file_key: str) ->
|
||||
return obj
|
||||
|
||||
|
||||
def _compose_place(city: str | None, country: str | None, port: str | None) -> str | None:
|
||||
"""Arma 'Ciudad, PAÍS (Puerto)' con las partes que existan (ruta estructurada)."""
|
||||
head = ", ".join(p for p in (city, country) if p)
|
||||
if port:
|
||||
head = f"{head} ({port})" if head else port
|
||||
return head or None
|
||||
|
||||
|
||||
def _company_row(db: Session, company_id: int) -> dict:
|
||||
try:
|
||||
row = db.execute(
|
||||
@@ -139,7 +147,8 @@ def build_pdf_bytes(db: Session, quote: Quote, tenant_id: int, company_id: int)
|
||||
route = [
|
||||
("Operación", sr.operation_type), ("Modo", sr.transport_mode),
|
||||
("Servicio", sr.service_type), ("Incoterm", sr.incoterm),
|
||||
("Origen", sr.origin), ("Destino", sr.destination),
|
||||
("Origen", sr.origin or _compose_place(sr.origin_city, sr.origin_country, sr.origin_port)),
|
||||
("Destino", sr.destination or _compose_place(sr.destination_city, sr.destination_country, sr.destination_port)),
|
||||
("Fecha requerida", sr.required_date.isoformat() if sr.required_date else None),
|
||||
]
|
||||
|
||||
|
||||
@@ -110,6 +110,24 @@ def create_quote(
|
||||
return service.create_quote(db, payload, tenant_id, company_id, _user_id(current_user))
|
||||
|
||||
|
||||
@router.post(
|
||||
"/quotes/from-service-request",
|
||||
response_model=list[QuoteResponse],
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
def create_quotes_from_service_request(
|
||||
service_request_id: int = Query(..., description="Solicitud de servicio a cotizar"),
|
||||
company_id: int = Query(..., description="Company ID"),
|
||||
current_user: dict = Depends(get_current_user),
|
||||
db: Session = Depends(get_core_db),
|
||||
):
|
||||
"""Genera la(s) cotización(es) desde una solicitud. Si es 'Ambas' devuelve 2 (FCL/LCL)."""
|
||||
tenant_id = current_user["tenant_id"]
|
||||
return service.create_quotes_from_service_request(
|
||||
db, service_request_id, tenant_id, company_id, _user_id(current_user)
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/quotes/{quote_id}", response_model=QuoteResponse)
|
||||
def update_quote(
|
||||
quote_id: int,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, timezone
|
||||
from datetime import date, datetime, timezone
|
||||
from decimal import Decimal
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
@@ -6,7 +6,8 @@ from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..accounts.models import Account
|
||||
from ..service_requests.models import ServiceRequest
|
||||
from ..common.folios import next_folio
|
||||
from ..service_requests.models import RateRequest, ServiceRequest
|
||||
from ..suppliers.models import Supplier
|
||||
from .dto import QuoteCreate, QuoteItemCreate, QuoteItemUpdate, QuoteUpdate
|
||||
from .models import Quote, QuoteItem
|
||||
@@ -89,18 +90,104 @@ def get_quote(db: Session, quote_id: int, tenant_id: int, company_id: int) -> Qu
|
||||
return obj
|
||||
|
||||
|
||||
def _sr_direction(db: Session, service_request_id: int | None) -> str | None:
|
||||
"""Dirección impo/expo heredada de la solicitud asociada (para el folio)."""
|
||||
if not service_request_id:
|
||||
return None
|
||||
sr = db.query(ServiceRequest).filter(ServiceRequest.id == service_request_id).first()
|
||||
return sr.operation_type if sr else None
|
||||
|
||||
|
||||
def create_quote(
|
||||
db: Session, payload: QuoteCreate, tenant_id: int, company_id: int, user_id: str | None = None
|
||||
) -> Quote:
|
||||
data = payload.model_dump()
|
||||
_validate_refs(db, data, tenant_id, company_id)
|
||||
obj = Quote(**data, tenant_id=tenant_id, company_id=company_id, created_by=user_id, updated_by=user_id)
|
||||
# Fecha de la cotización: por defecto hoy si no se capturó
|
||||
if obj.issue_date is None:
|
||||
obj.issue_date = date.today()
|
||||
# Folio C... auto-generado (mensual), con la dirección heredada de la solicitud
|
||||
if not obj.reference:
|
||||
obj.reference = next_folio(db, tenant_id, company_id, "C", _sr_direction(db, obj.service_request_id))
|
||||
db.add(obj)
|
||||
db.commit()
|
||||
db.refresh(obj)
|
||||
return obj
|
||||
|
||||
|
||||
def create_quotes_from_service_request(
|
||||
db: Session, service_request_id: int, tenant_id: int, company_id: int, user_id: str | None = None
|
||||
) -> list[Quote]:
|
||||
"""Genera cotización(es) a partir de una solicitud de servicio.
|
||||
|
||||
Si la solicitud es "Ambas" (FCL y LCL), genera **dos** cotizaciones (una por
|
||||
variante) para comparar. Cada cotización toma su propio folio C... y hereda la
|
||||
dirección impo/expo de la solicitud. Los conceptos se siembran desde las
|
||||
solicitudes de tarifa (RateRequest) capturadas en la solicitud.
|
||||
"""
|
||||
sr = (
|
||||
db.query(ServiceRequest)
|
||||
.filter(
|
||||
ServiceRequest.id == service_request_id,
|
||||
ServiceRequest.tenant_id == tenant_id,
|
||||
ServiceRequest.company_id == company_id,
|
||||
ServiceRequest.deleted_at.is_(None),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not sr:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Solicitud no encontrada")
|
||||
|
||||
variants = ["FCL", "LCL"] if (sr.load_type or "").upper() == "AMBAS" else [sr.load_type or None]
|
||||
rate_requests = (
|
||||
db.query(RateRequest)
|
||||
.filter(
|
||||
RateRequest.service_request_id == sr.id,
|
||||
RateRequest.tenant_id == tenant_id,
|
||||
RateRequest.company_id == company_id,
|
||||
RateRequest.deleted_at.is_(None),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
|
||||
created: list[Quote] = []
|
||||
for variant in variants:
|
||||
quote = Quote(
|
||||
account_id=sr.account_id,
|
||||
service_request_id=sr.id,
|
||||
currency=sr.currency or "USD",
|
||||
load_type=variant,
|
||||
status="borrador",
|
||||
issue_date=date.today(),
|
||||
notes=sr.client_notes or sr.notes,
|
||||
owner_user_id=sr.owner_user_id,
|
||||
reference=next_folio(db, tenant_id, company_id, "C", sr.operation_type),
|
||||
tenant_id=tenant_id,
|
||||
company_id=company_id,
|
||||
created_by=user_id,
|
||||
updated_by=user_id,
|
||||
)
|
||||
db.add(quote)
|
||||
db.flush()
|
||||
for rr in rate_requests:
|
||||
amount = rr.rate_amount if rr.rate_amount is not None else Decimal(0)
|
||||
db.add(QuoteItem(
|
||||
quote_id=quote.id, concept=rr.concept, description=rr.description,
|
||||
supplier_id=rr.supplier_id, quantity=Decimal(1),
|
||||
unit_cost=amount, unit_sale=amount, currency=rr.currency,
|
||||
tenant_id=tenant_id, company_id=company_id,
|
||||
))
|
||||
db.flush()
|
||||
_recompute_totals(db, quote)
|
||||
created.append(quote)
|
||||
|
||||
db.commit()
|
||||
for quote in created:
|
||||
db.refresh(quote)
|
||||
return created
|
||||
|
||||
|
||||
def update_quote(
|
||||
db: Session, quote_id: int, payload: QuoteUpdate, tenant_id: int, company_id: int, user_id: str | None = None
|
||||
) -> Quote:
|
||||
|
||||
Reference in New Issue
Block a user