feat(crm): dominio backend (cuentas, contactos, prospectos, embudos, oportunidades, actividades)
- Nuevo schema `crm` con 7 tablas multi-tenant (TenantScopedMixin + soft delete) - Módulos FastAPI por dominio: models/dto/service/routes (patrón example) - Métricas del dashboard (KPIs + embudo por etapa) - Conversión de prospecto → cuenta/contacto/oportunidad (idempotente) - Movimiento de oportunidad entre etapas (Kanban) con estado/probabilidad derivados - 25 permisos registrados en PermissionRegistry - Migración Alembic con upgrade/downgrade completos - 24 tests de servicios (pytest) en verde Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
0
backend/api/v1/modules/crm/accounts/__init__.py
Normal file
0
backend/api/v1/modules/crm/accounts/__init__.py
Normal file
67
backend/api/v1/modules/crm/accounts/dto.py
Normal file
67
backend/api/v1/modules/crm/accounts/dto.py
Normal file
@@ -0,0 +1,67 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, EmailStr, Field
|
||||
|
||||
|
||||
class AccountCreate(BaseModel):
|
||||
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)
|
||||
account_type: str | None = Field(None, max_length=40)
|
||||
industry: str | None = Field(None, max_length=120)
|
||||
email: EmailStr | None = None
|
||||
phone: str | None = Field(None, max_length=40)
|
||||
website: str | None = Field(None, max_length=255)
|
||||
address: str | None = None
|
||||
city: str | None = Field(None, max_length=120)
|
||||
state: str | None = Field(None, max_length=120)
|
||||
country: str | None = Field(None, max_length=2)
|
||||
patente_aduanal: str | None = Field(None, max_length=20)
|
||||
status: str = Field("active", max_length=20)
|
||||
owner_user_id: str | None = Field(None, max_length=64)
|
||||
notes: str | None = None
|
||||
|
||||
|
||||
class AccountUpdate(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)
|
||||
account_type: str | None = Field(None, max_length=40)
|
||||
industry: str | None = Field(None, max_length=120)
|
||||
email: EmailStr | None = None
|
||||
phone: str | None = Field(None, max_length=40)
|
||||
website: str | None = Field(None, max_length=255)
|
||||
address: str | None = None
|
||||
city: str | None = Field(None, max_length=120)
|
||||
state: str | None = Field(None, max_length=120)
|
||||
country: str | None = Field(None, max_length=2)
|
||||
patente_aduanal: str | None = Field(None, max_length=20)
|
||||
status: str | None = Field(None, max_length=20)
|
||||
owner_user_id: str | None = Field(None, max_length=64)
|
||||
notes: str | None = None
|
||||
|
||||
|
||||
class AccountResponse(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
name: str
|
||||
trade_name: str | None
|
||||
rfc: str | None
|
||||
account_type: str | None
|
||||
industry: str | None
|
||||
email: str | None
|
||||
phone: str | None
|
||||
website: str | None
|
||||
address: str | None
|
||||
city: str | None
|
||||
state: str | None
|
||||
country: str | None
|
||||
patente_aduanal: str | None
|
||||
status: str
|
||||
owner_user_id: str | None
|
||||
notes: str | None
|
||||
tenant_id: int
|
||||
company_id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
40
backend/api/v1/modules/crm/accounts/models.py
Normal file
40
backend/api/v1/modules/crm/accounts/models.py
Normal file
@@ -0,0 +1,40 @@
|
||||
from sqlalchemy import Integer, 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 Account(Base, TenantScopedMixin, TimestampMixin):
|
||||
"""Cuenta CRM: empresa cliente o prospecto.
|
||||
|
||||
Modela importadores, IMMEX, agencias aduanales, transportistas, etc.
|
||||
Los campos aduaneros (RFC, patente) son opcionales para no forzar datos
|
||||
en prospectos que aún no comparten información fiscal.
|
||||
"""
|
||||
|
||||
__tablename__ = "accounts"
|
||||
__table_args__ = {"schema": "crm"}
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
|
||||
# Razón social (nombre legal) y nombre comercial
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
trade_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
rfc: Mapped[str | None] = mapped_column(String(13), nullable=True, index=True)
|
||||
# Tipo de cuenta: immex | agencia_aduanal | importador | exportador | transportista | otro
|
||||
account_type: Mapped[str | None] = mapped_column(String(40), nullable=True)
|
||||
industry: Mapped[str | None] = mapped_column(String(120), 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)
|
||||
address: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
city: Mapped[str | None] = mapped_column(String(120), nullable=True)
|
||||
state: Mapped[str | None] = mapped_column(String(120), nullable=True)
|
||||
country: Mapped[str | None] = mapped_column(String(2), nullable=True, server_default=text("'MX'"))
|
||||
# Patente del agente aduanal (dato aduanero, no se traduce)
|
||||
patente_aduanal: Mapped[str | None] = mapped_column(String(20), nullable=True)
|
||||
# Estado comercial: active | inactive | prospect
|
||||
status: Mapped[str] = mapped_column(String(20), nullable=False, server_default=text("'active'"))
|
||||
# Vendedor responsable (id de usuario Keycloak / sub)
|
||||
owner_user_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
|
||||
notes: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
67
backend/api/v1/modules/crm/accounts/routes.py
Normal file
67
backend/api/v1/modules/crm/accounts/routes.py
Normal file
@@ -0,0 +1,67 @@
|
||||
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 AccountCreate, AccountResponse, AccountUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/accounts", response_model=list[AccountResponse])
|
||||
def list_accounts(
|
||||
company_id: int = Query(..., description="Company ID"),
|
||||
search: str | None = Query(None, description="Búsqueda por nombre, nombre comercial o RFC"),
|
||||
account_status: str | None = Query(None, alias="status", description="Filtrar por estado"),
|
||||
current_user: dict = Depends(get_current_user),
|
||||
db: Session = Depends(get_core_db),
|
||||
):
|
||||
tenant_id = current_user["tenant_id"]
|
||||
return service.get_accounts(db, tenant_id, company_id, search, account_status)
|
||||
|
||||
|
||||
@router.get("/accounts/{account_id}", response_model=AccountResponse)
|
||||
def get_account(
|
||||
account_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_account(db, account_id, tenant_id, company_id)
|
||||
|
||||
|
||||
@router.post("/accounts", response_model=AccountResponse, status_code=status.HTTP_201_CREATED)
|
||||
def create_account(
|
||||
payload: AccountCreate,
|
||||
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_account(db, payload, tenant_id, company_id)
|
||||
|
||||
|
||||
@router.patch("/accounts/{account_id}", response_model=AccountResponse)
|
||||
def update_account(
|
||||
account_id: int,
|
||||
payload: AccountUpdate,
|
||||
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_account(db, account_id, payload, tenant_id, company_id)
|
||||
|
||||
|
||||
@router.delete("/accounts/{account_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_account(
|
||||
account_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_account(db, account_id, tenant_id, company_id)
|
||||
73
backend/api/v1/modules/crm/accounts/service.py
Normal file
73
backend/api/v1/modules/crm/accounts/service.py
Normal file
@@ -0,0 +1,73 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .dto import AccountCreate, AccountUpdate
|
||||
from .models import Account
|
||||
|
||||
|
||||
def get_accounts(
|
||||
db: Session,
|
||||
tenant_id: int,
|
||||
company_id: int,
|
||||
search: str | None = None,
|
||||
account_status: str | None = None,
|
||||
) -> list[Account]:
|
||||
query = db.query(Account).filter(
|
||||
Account.tenant_id == tenant_id,
|
||||
Account.company_id == company_id,
|
||||
Account.deleted_at.is_(None),
|
||||
)
|
||||
if search:
|
||||
pattern = f"%{search}%"
|
||||
query = query.filter(
|
||||
Account.name.ilike(pattern)
|
||||
| Account.trade_name.ilike(pattern)
|
||||
| Account.rfc.ilike(pattern)
|
||||
)
|
||||
if account_status:
|
||||
query = query.filter(Account.status == account_status)
|
||||
return query.order_by(Account.name.asc()).all()
|
||||
|
||||
|
||||
def get_account(db: Session, account_id: int, tenant_id: int, company_id: int) -> Account:
|
||||
account = (
|
||||
db.query(Account)
|
||||
.filter(
|
||||
Account.id == account_id,
|
||||
Account.tenant_id == tenant_id,
|
||||
Account.company_id == company_id,
|
||||
Account.deleted_at.is_(None),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not account:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Cuenta no encontrada")
|
||||
return account
|
||||
|
||||
|
||||
def create_account(db: Session, payload: AccountCreate, tenant_id: int, company_id: int) -> Account:
|
||||
account = Account(**payload.model_dump(), tenant_id=tenant_id, company_id=company_id)
|
||||
db.add(account)
|
||||
db.commit()
|
||||
db.refresh(account)
|
||||
return account
|
||||
|
||||
|
||||
def update_account(
|
||||
db: Session, account_id: int, payload: AccountUpdate, tenant_id: int, company_id: int
|
||||
) -> Account:
|
||||
account = get_account(db, account_id, tenant_id, company_id)
|
||||
for field, value in payload.model_dump(exclude_unset=True).items():
|
||||
setattr(account, field, value)
|
||||
db.commit()
|
||||
db.refresh(account)
|
||||
return account
|
||||
|
||||
|
||||
def delete_account(db: Session, account_id: int, tenant_id: int, company_id: int) -> None:
|
||||
account = get_account(db, account_id, tenant_id, company_id)
|
||||
# Soft delete: conserva el histórico comercial de la cuenta
|
||||
account.deleted_at = datetime.now(timezone.utc)
|
||||
db.commit()
|
||||
Reference in New Issue
Block a user