feat(crm): Expediente — referencia única de trazabilidad del trámite (Fase D)
- Tabla crm.cases (expediente) con folio EXP2026-08-001 (next_folio entidad EXP,
sin dirección). Nace al crear la Oportunidad y se hereda vía case_id a
solicitud → cotización → operación → factura. advance_stage solo avanza.
- case_id (FK a crm.cases) en crm.opportunities/service_requests/quotes,
ops.shipments y fin.invoices; propagación en sus create_*. Migración
d4e5f6a7b8c9 reversible.
- Endpoints GET /v1/crm/cases, /cases/{id}, /cases/by-ref/{ref} con timeline
(historia completa para UI y otros sistemas).
- Frontend: casesAPI, ruta /dashboard/crm/expedientes (lista + timeline vertical),
chip "📁 Expediente" en solicitud/cotización, "Expedientes" en el sidebar.
- Consecutivo de folios sin tope (soporta >10,000,000/mes).
- 4 pruebas de expediente (minteo, propagación, timeline, no-retroceso). Suite en verde (113).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
0
backend/api/v1/modules/crm/cases/__init__.py
Normal file
0
backend/api/v1/modules/crm/cases/__init__.py
Normal file
31
backend/api/v1/modules/crm/cases/dto.py
Normal file
31
backend/api/v1/modules/crm/cases/dto.py
Normal file
@@ -0,0 +1,31 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class CaseResponse(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
reference: str | None
|
||||
account_id: int | None
|
||||
title: str | None
|
||||
stage: str
|
||||
status: str
|
||||
tenant_id: int
|
||||
company_id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
class CaseTimelineEvent(BaseModel):
|
||||
kind: str # oportunidad | solicitud | cotizacion | operacion | factura
|
||||
id: int
|
||||
reference: str | None = None
|
||||
status: str | None = None
|
||||
created_at: datetime
|
||||
url: str
|
||||
|
||||
|
||||
class CaseWithTimeline(CaseResponse):
|
||||
timeline: list[CaseTimelineEvent] = []
|
||||
28
backend/api/v1/modules/crm/cases/models.py
Normal file
28
backend/api/v1/modules/crm/cases/models.py
Normal file
@@ -0,0 +1,28 @@
|
||||
from sqlalchemy import ForeignKey, Integer, String, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from api.v1.common.base_models import TenantScopedMixin, TimestampMixin
|
||||
from core.database import Base
|
||||
|
||||
|
||||
class Case(Base, TenantScopedMixin, TimestampMixin):
|
||||
"""Expediente: hilo maestro de un trámite (Oportunidad → Solicitud → Cotización →
|
||||
Operación → Factura). Una sola referencia (``EXP…``) que agrupa toda la historia.
|
||||
Nace al crear la Oportunidad y se hereda a las entidades siguientes vía ``case_id``.
|
||||
"""
|
||||
|
||||
__tablename__ = "cases"
|
||||
__table_args__ = {"schema": "crm"}
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
|
||||
reference: Mapped[str | None] = mapped_column(String(40), nullable=True, index=True) # folio EXP...
|
||||
account_id: Mapped[int | None] = mapped_column(
|
||||
Integer, ForeignKey("crm.accounts.id"), nullable=True, index=True
|
||||
)
|
||||
title: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
# Etapa más avanzada alcanzada: oportunidad|solicitud|cotizacion|operacion|facturacion|cerrado
|
||||
stage: Mapped[str] = mapped_column(String(20), nullable=False, server_default=text("'oportunidad'"))
|
||||
# abierto | cerrado
|
||||
status: Mapped[str] = mapped_column(String(20), nullable=False, server_default=text("'abierto'"), index=True)
|
||||
created_by: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
updated_by: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
51
backend/api/v1/modules/crm/cases/routes.py
Normal file
51
backend/api/v1/modules/crm/cases/routes.py
Normal file
@@ -0,0 +1,51 @@
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
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 CaseResponse, CaseWithTimeline
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _with_timeline(db, case) -> CaseWithTimeline:
|
||||
data = CaseWithTimeline.model_validate(case)
|
||||
data.timeline = service.build_timeline(db, case) # type: ignore[assignment]
|
||||
return data
|
||||
|
||||
|
||||
@router.get("/cases", response_model=list[CaseResponse])
|
||||
def list_cases(
|
||||
company_id: int = Query(..., description="Company ID"),
|
||||
search: str | None = Query(None),
|
||||
account_id: int | None = Query(None),
|
||||
stage: str | None = Query(None),
|
||||
current_user: dict = Depends(get_current_user),
|
||||
db: Session = Depends(get_core_db),
|
||||
):
|
||||
return service.get_cases(db, current_user["tenant_id"], company_id, search, account_id, stage)
|
||||
|
||||
|
||||
@router.get("/cases/by-ref/{reference}", response_model=CaseWithTimeline)
|
||||
def get_case_by_ref(
|
||||
reference: str,
|
||||
company_id: int = Query(..., description="Company ID"),
|
||||
current_user: dict = Depends(get_current_user),
|
||||
db: Session = Depends(get_core_db),
|
||||
):
|
||||
"""Expediente + historia completa por su referencia (para UI y otros sistemas)."""
|
||||
case = service.get_case_by_reference(db, reference, current_user["tenant_id"], company_id)
|
||||
return _with_timeline(db, case)
|
||||
|
||||
|
||||
@router.get("/cases/{case_id}", response_model=CaseWithTimeline)
|
||||
def get_case(
|
||||
case_id: int,
|
||||
company_id: int = Query(..., description="Company ID"),
|
||||
current_user: dict = Depends(get_current_user),
|
||||
db: Session = Depends(get_core_db),
|
||||
):
|
||||
case = service.get_case(db, case_id, current_user["tenant_id"], company_id)
|
||||
return _with_timeline(db, case)
|
||||
109
backend/api/v1/modules/crm/cases/service.py
Normal file
109
backend/api/v1/modules/crm/cases/service.py
Normal file
@@ -0,0 +1,109 @@
|
||||
"""Lógica del Expediente: minteo del folio, avance de etapa y armado del timeline."""
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..common.folios import next_folio
|
||||
from .models import Case
|
||||
|
||||
# Orden de etapas (solo se avanza, nunca retrocede)
|
||||
STAGE_ORDER = ["oportunidad", "solicitud", "cotizacion", "operacion", "facturacion", "cerrado"]
|
||||
|
||||
|
||||
def create_case(
|
||||
db: Session, tenant_id: int, company_id: int, *, account_id: int | None = None,
|
||||
title: str | None = None, stage: str = "oportunidad", user_id: str | None = None,
|
||||
) -> Case:
|
||||
"""Mintea un expediente con folio EXP... (sin commit; lo confirma quien lo invoca)."""
|
||||
case = Case(
|
||||
reference=next_folio(db, tenant_id, company_id, "EXP", None, with_direction=False),
|
||||
account_id=account_id, title=title, stage=stage, status="abierto",
|
||||
tenant_id=tenant_id, company_id=company_id, created_by=user_id, updated_by=user_id,
|
||||
)
|
||||
db.add(case)
|
||||
db.flush()
|
||||
return case
|
||||
|
||||
|
||||
def advance_stage(db: Session, case_id: int | None, stage: str) -> None:
|
||||
"""Avanza la etapa del expediente si la nueva es posterior a la actual."""
|
||||
if not case_id or stage not in STAGE_ORDER:
|
||||
return
|
||||
case = db.query(Case).filter(Case.id == case_id).first()
|
||||
if not case:
|
||||
return
|
||||
current = case.stage if case.stage in STAGE_ORDER else "oportunidad"
|
||||
if STAGE_ORDER.index(stage) > STAGE_ORDER.index(current):
|
||||
case.stage = stage
|
||||
|
||||
|
||||
def get_cases(
|
||||
db: Session, tenant_id: int, company_id: int, search: str | None = None,
|
||||
account_id: int | None = None, stage: str | None = None,
|
||||
) -> list[Case]:
|
||||
q = db.query(Case).filter(
|
||||
Case.tenant_id == tenant_id, Case.company_id == company_id, Case.deleted_at.is_(None),
|
||||
)
|
||||
if account_id is not None:
|
||||
q = q.filter(Case.account_id == account_id)
|
||||
if stage:
|
||||
q = q.filter(Case.stage == stage)
|
||||
if search:
|
||||
q = q.filter(Case.reference.ilike(f"%{search}%"))
|
||||
return q.order_by(Case.created_at.desc()).all()
|
||||
|
||||
|
||||
def get_case(db: Session, case_id: int, tenant_id: int, company_id: int) -> Case:
|
||||
obj = (
|
||||
db.query(Case)
|
||||
.filter(Case.id == case_id, Case.tenant_id == tenant_id, Case.company_id == company_id, Case.deleted_at.is_(None))
|
||||
.first()
|
||||
)
|
||||
if not obj:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Expediente no encontrado")
|
||||
return obj
|
||||
|
||||
|
||||
def get_case_by_reference(db: Session, reference: str, tenant_id: int, company_id: int) -> Case:
|
||||
obj = (
|
||||
db.query(Case)
|
||||
.filter(Case.reference == reference, Case.tenant_id == tenant_id, Case.company_id == company_id,
|
||||
Case.deleted_at.is_(None))
|
||||
.first()
|
||||
)
|
||||
if not obj:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Expediente no encontrado")
|
||||
return obj
|
||||
|
||||
|
||||
def build_timeline(db: Session, case: Case) -> list[dict]:
|
||||
"""Devuelve la historia del expediente: todas las entidades ligadas por case_id,
|
||||
en orden cronológico. Un único lookup para la UI y para otros sistemas."""
|
||||
# Import local para evitar ciclos de importación entre módulos.
|
||||
from ..opportunities.models import Opportunity
|
||||
from ..quotes.models import Quote
|
||||
from ..service_requests.models import ServiceRequest
|
||||
from api.v1.modules.fin.invoices.models import Invoice
|
||||
from api.v1.modules.ops.shipments.models import Shipment
|
||||
|
||||
events: list[dict] = []
|
||||
specs = [
|
||||
("oportunidad", Opportunity, "/dashboard/crm/oportunidades"),
|
||||
("solicitud", ServiceRequest, "/dashboard/crm/solicitudes"),
|
||||
("cotizacion", Quote, "/dashboard/crm/cotizaciones"),
|
||||
("operacion", Shipment, "/dashboard/ops/embarques"),
|
||||
("factura", Invoice, "/dashboard/fin/facturas"),
|
||||
]
|
||||
for kind, model, base_url in specs:
|
||||
rows = db.query(model).filter(model.case_id == case.id, model.deleted_at.is_(None)).all()
|
||||
for r in rows:
|
||||
events.append({
|
||||
"kind": kind,
|
||||
"id": r.id,
|
||||
"reference": getattr(r, "reference", None),
|
||||
"status": getattr(r, "status", None),
|
||||
"created_at": r.created_at,
|
||||
"url": f"{base_url}/{r.id}",
|
||||
})
|
||||
events.sort(key=lambda e: e["created_at"])
|
||||
return events
|
||||
Reference in New Issue
Block a user