feat(crm): ajustes de la sesión doc 2 (catálogos, bugs, oportunidades, facturación, UI)
Catálogos y selects:
- Incoterm como catálogo (nuevo catálogo global 'incoterm') en solicitud y modal
de conversión de oportunidad.
- Moneda como catálogo en Cotizaciones (nuevo/detalle) y Facturación.
- "Tipo de transporte" desde catálogo medio_transporte (antes lista fija).
- Cotizador: origen/destino como selects alineados a las rutas de los tarifarios
activos (endpoint /rate-locations), para que el costeo siempre encuentre ruta.
Bugs de la sesión:
- Direcciones no guardaban: DTO country String(2)→String(3) (ISO alfa-3); se
amplía accounts.country y se normaliza 'MX'→'MEX' (migración).
- Contacto de proveedor mal filtrado: contacts.ts ahora envía supplier_id.
- Selects ilegibles en modo oscuro: regla global select option en app.css.
- Formas de pago SAT a 2 dígitos (01/04/08) en catálogo y valores guardados.
- RelatedManager: editar direcciones/contactos/documentos (antes solo eliminar).
Oportunidades:
- Se quitan etapas Prospecto/Contactado del embudo semilla.
- Fechas separadas won_date/lost_date + motivo de pérdida, con modal al mover a
Ganada/Perdida (migración).
Facturación:
- Folio automático F{AAAA}-{MM}-{NNN} (next_folio entidad F, sin dirección).
- Moneda como catálogo.
UI:
- Giro "otro" habilita campo para especificar (accounts.industry_other, migración).
- Lista de contactos muestra a quién pertenece (cliente/prospecto/proveedor).
- Proveedores: países/puertos/aeropuertos/aduanas por catálogo (select + chips).
Migraciones reversibles (c2d3e4f5a6b7 ya existía; d3e4f5a6b7c8, e4f5a6b7c8d9).
Suite backend en verde (109). svelte-check sin errores nuevos.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -13,6 +13,7 @@ class AccountBase(BaseModel):
|
||||
record_type: str = Field("cliente", max_length=20) # cliente | prospecto
|
||||
person_type: str | None = Field(None, max_length=10) # fisica | moral
|
||||
industry: str | None = Field(None, max_length=120)
|
||||
industry_other: str | None = Field(None, max_length=120)
|
||||
account_type: str | None = Field(None, max_length=40)
|
||||
status: str = Field("active", max_length=20) # active | inactive
|
||||
# Comercial
|
||||
@@ -38,7 +39,7 @@ class AccountBase(BaseModel):
|
||||
address: str | None = None
|
||||
city: str | None = Field(None, max_length=120)
|
||||
state: str | None = Field(None, max_length=120)
|
||||
country: str | None = Field("MX", max_length=2)
|
||||
country: str | None = Field("MEX", max_length=3)
|
||||
# Observaciones
|
||||
notes: str | None = None
|
||||
internal_notes: str | None = None
|
||||
@@ -57,6 +58,7 @@ class AccountUpdate(BaseModel):
|
||||
record_type: str | None = Field(None, max_length=20)
|
||||
person_type: str | None = Field(None, max_length=10)
|
||||
industry: str | None = Field(None, max_length=120)
|
||||
industry_other: str | None = Field(None, max_length=120)
|
||||
account_type: str | None = Field(None, max_length=40)
|
||||
status: str | None = Field(None, max_length=20)
|
||||
commercial_classification: str | None = Field(None, max_length=20)
|
||||
@@ -79,7 +81,7 @@ class AccountUpdate(BaseModel):
|
||||
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)
|
||||
country: str | None = Field(None, max_length=3)
|
||||
notes: str | None = None
|
||||
internal_notes: str | None = None
|
||||
owner_user_id: str | None = Field(None, max_length=64)
|
||||
|
||||
@@ -31,6 +31,7 @@ class Account(Base, TenantScopedMixin, TimestampMixin):
|
||||
# Tipo de persona: fisica | moral
|
||||
person_type: Mapped[str | None] = mapped_column(String(10), nullable=True)
|
||||
industry: Mapped[str | None] = mapped_column(String(120), nullable=True) # giro / industria
|
||||
industry_other: Mapped[str | None] = mapped_column(String(120), nullable=True) # especificar cuando giro = "otro"
|
||||
# Tipo operativo (immex | agencia_aduanal | importador | exportador | transportista | otro)
|
||||
account_type: Mapped[str | None] = mapped_column(String(40), nullable=True)
|
||||
# Estatus: active | inactive
|
||||
@@ -65,7 +66,7 @@ class Account(Base, TenantScopedMixin, TimestampMixin):
|
||||
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'"))
|
||||
country: Mapped[str | None] = mapped_column(String(3), nullable=True, server_default=text("'MEX'"))
|
||||
|
||||
# ----- Observaciones y auditoría -----
|
||||
notes: Mapped[str | None] = mapped_column(Text, nullable=True) # comentarios generales
|
||||
|
||||
@@ -14,7 +14,7 @@ class AddressBase(BaseModel):
|
||||
postal_code: str | None = Field(None, max_length=10)
|
||||
city: str | None = Field(None, max_length=120)
|
||||
state: str | None = Field(None, max_length=120)
|
||||
country: str | None = Field("MX", max_length=2)
|
||||
country: str | None = Field("MEX", max_length=3) # ISO 3166-1 alfa-3 (alineado a catálogo pais)
|
||||
reference_notes: str | None = None
|
||||
is_primary: bool = False
|
||||
|
||||
@@ -32,7 +32,7 @@ class AddressUpdate(BaseModel):
|
||||
postal_code: str | None = Field(None, max_length=10)
|
||||
city: str | None = Field(None, max_length=120)
|
||||
state: str | None = Field(None, max_length=120)
|
||||
country: str | None = Field(None, max_length=2)
|
||||
country: str | None = Field(None, max_length=3)
|
||||
reference_notes: str | None = None
|
||||
is_primary: bool | None = None
|
||||
|
||||
|
||||
@@ -847,4 +847,23 @@ GLOBAL_CATALOGS.update({
|
||||
{'code': 'ficha_tecnica', 'label': 'Ficha técnica'},
|
||||
{'code': 'carta_instrucciones', 'label': 'Carta de instrucciones'},
|
||||
{'code': 'otro', 'label': 'Otro'}]},
|
||||
'incoterm': {'label': 'Incoterm (2020)',
|
||||
'is_system': True,
|
||||
'items': [{'code': 'EXW', 'label': 'EXW — Ex Works (en fábrica)'},
|
||||
{'code': 'FCA', 'label': 'FCA — Free Carrier (franco transportista)'},
|
||||
{'code': 'FAS', 'label': 'FAS — Free Alongside Ship (franco al costado del buque)'},
|
||||
{'code': 'FOB', 'label': 'FOB — Free On Board (franco a bordo)'},
|
||||
{'code': 'CFR', 'label': 'CFR — Cost and Freight (costo y flete)'},
|
||||
{'code': 'CIF', 'label': 'CIF — Cost, Insurance and Freight (costo, seguro y flete)'},
|
||||
{'code': 'CPT', 'label': 'CPT — Carriage Paid To (transporte pagado hasta)'},
|
||||
{'code': 'CIP', 'label': 'CIP — Carriage and Insurance Paid To (transporte y seguro pagados hasta)'},
|
||||
{'code': 'DAP', 'label': 'DAP — Delivered At Place (entregado en lugar)'},
|
||||
{'code': 'DPU', 'label': 'DPU — Delivered At Place Unloaded (entregado en lugar descargado)'},
|
||||
{'code': 'DDP', 'label': 'DDP — Delivered Duty Paid (entregado con derechos pagados)'}]},
|
||||
})
|
||||
|
||||
# Formas de pago SAT de un dígito → dos dígitos (01, 02, 03, 04, 05, 06, 08).
|
||||
# El SAT exige dos posiciones; se corrige el catálogo base.
|
||||
for _fp in GLOBAL_CATALOGS.get('forma_pago', {}).get('items', []):
|
||||
if len(_fp['code']) == 1:
|
||||
_fp['code'] = _fp['code'].zfill(2)
|
||||
|
||||
@@ -21,8 +21,8 @@ from sqlalchemy.orm import Mapped, mapped_column
|
||||
from api.v1.common.base_models import BaseTimestampMixin, TenantScopedMixin
|
||||
from core.database import Base
|
||||
|
||||
# Entidades válidas y su letra de folio.
|
||||
ENTITIES = ("O", "S", "C", "OP")
|
||||
# Entidades válidas y su letra de folio (F = factura, sin dirección impo/expo).
|
||||
ENTITIES = ("O", "S", "C", "OP", "F")
|
||||
# Mapa dirección de operación → sufijo del folio.
|
||||
_DIRECTION_SUFFIX = {"importacion": "I", "exportacion": "E"}
|
||||
|
||||
@@ -56,11 +56,13 @@ def next_folio(
|
||||
entity: str,
|
||||
direction: str | None,
|
||||
on_date: date | None = None,
|
||||
with_direction: bool = True,
|
||||
) -> str:
|
||||
"""Genera el siguiente folio de una entidad, incrementando su consecutivo mensual.
|
||||
|
||||
Reserva el número dentro de la transacción activa (no hace commit): el ``create_*``
|
||||
que lo invoca es quien confirma junto con la fila recién creada.
|
||||
que lo invoca es quien confirma junto con la fila recién creada. ``with_direction=False``
|
||||
omite el sufijo I/E (p. ej. facturas → ``F2026-08-001``).
|
||||
"""
|
||||
if entity not in ENTITIES:
|
||||
raise ValueError(f"Entidad de folio inválida: {entity!r}")
|
||||
@@ -89,4 +91,6 @@ def next_folio(
|
||||
db.flush()
|
||||
|
||||
sequence = f"{counter.last_number:03d}"
|
||||
if not with_direction:
|
||||
return f"{entity}{period}-{sequence}"
|
||||
return f"{entity}{period}-{sequence}-{direction_suffix(direction)}"
|
||||
|
||||
@@ -31,6 +31,8 @@ class OpportunityUpdate(BaseModel):
|
||||
probability: int | None = Field(None, ge=0, le=100)
|
||||
status: str | None = Field(None, max_length=20)
|
||||
expected_close_date: date | None = None
|
||||
won_date: date | None = None
|
||||
lost_date: date | None = None
|
||||
lost_reason: str | None = Field(None, max_length=255)
|
||||
source: str | None = Field(None, max_length=60)
|
||||
owner_user_id: str | None = Field(None, max_length=64)
|
||||
@@ -59,6 +61,8 @@ class OpportunityResponse(BaseModel):
|
||||
status: str
|
||||
expected_close_date: date | None
|
||||
closed_at: datetime | None
|
||||
won_date: date | None = None
|
||||
lost_date: date | None = None
|
||||
lost_reason: str | None
|
||||
source: str | None
|
||||
owner_user_id: str | None
|
||||
|
||||
@@ -34,6 +34,8 @@ class Opportunity(Base, TenantScopedMixin, TimestampMixin):
|
||||
status: Mapped[str] = mapped_column(String(20), nullable=False, server_default=text("'open'"), index=True)
|
||||
expected_close_date: Mapped[date | None] = mapped_column(Date, nullable=True)
|
||||
closed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
won_date: Mapped[date | None] = mapped_column(Date, nullable=True) # fecha en que se ganó
|
||||
lost_date: Mapped[date | None] = mapped_column(Date, nullable=True) # fecha en que se perdió
|
||||
lost_reason: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
source: Mapped[str | None] = mapped_column(String(60), nullable=True)
|
||||
owner_user_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, timezone
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -47,14 +47,20 @@ def _apply_stage_state(opportunity: Opportunity, stage: PipelineStage) -> None:
|
||||
opportunity.status = "won"
|
||||
opportunity.probability = 100
|
||||
opportunity.closed_at = datetime.now(timezone.utc)
|
||||
opportunity.won_date = opportunity.won_date or date.today()
|
||||
opportunity.lost_date = None
|
||||
elif stage.is_lost:
|
||||
opportunity.status = "lost"
|
||||
opportunity.probability = 0
|
||||
opportunity.closed_at = datetime.now(timezone.utc)
|
||||
opportunity.lost_date = opportunity.lost_date or date.today()
|
||||
opportunity.won_date = None
|
||||
else:
|
||||
opportunity.status = "open"
|
||||
opportunity.probability = stage.probability
|
||||
opportunity.closed_at = None
|
||||
opportunity.won_date = None
|
||||
opportunity.lost_date = None
|
||||
|
||||
|
||||
def _validate_refs(db: Session, data: dict, tenant_id: int, company_id: int) -> None:
|
||||
|
||||
@@ -255,3 +255,15 @@ def rate_quote(
|
||||
tenant_id, _ = _ctx(current_user)
|
||||
options = service.quote_cost(db, tenant_id, company_id, req)
|
||||
return CostResult(request=req, options=options)
|
||||
|
||||
|
||||
@cost_router.get("/rate-locations")
|
||||
def rate_locations(
|
||||
mode: str = Query(...),
|
||||
company_id: int = Query(...),
|
||||
current_user: dict = Depends(get_current_user),
|
||||
db: Session = Depends(get_core_db),
|
||||
):
|
||||
"""Orígenes/destinos cotizables (de los tarifarios activos) para alinear el cotizador."""
|
||||
tenant_id, _ = _ctx(current_user)
|
||||
return service.lane_locations(db, tenant_id, company_id, mode)
|
||||
|
||||
@@ -479,6 +479,30 @@ def _apply_charges(db: Session, sheet: RateSheet, lane: RateLane, base: Decimal,
|
||||
return lines
|
||||
|
||||
|
||||
def lane_locations(db: Session, tenant_id: int, company_id: int, mode: str) -> dict[str, list[str]]:
|
||||
"""Orígenes/destinos existentes en los tarifarios activos de un modo.
|
||||
|
||||
Alinea el cotizador con las rutas realmente cotizables (los códigos provienen
|
||||
de las lanes, por lo que el costeo siempre encontrará ruta).
|
||||
"""
|
||||
sheets = _sheet_query(db, tenant_id, company_id).filter(
|
||||
RateSheet.mode == mode, RateSheet.status == "activo",
|
||||
).all()
|
||||
origins: set[str] = set()
|
||||
destinations: set[str] = set()
|
||||
for sheet in sheets:
|
||||
lanes = db.query(RateLane).filter(
|
||||
RateLane.rate_sheet_id == sheet.id, RateLane.deleted_at.is_(None),
|
||||
).all()
|
||||
for lane in lanes:
|
||||
origin = lane.origin or sheet.default_origin
|
||||
if origin:
|
||||
origins.add(origin)
|
||||
if lane.destination:
|
||||
destinations.add(lane.destination)
|
||||
return {"origins": sorted(origins), "destinations": sorted(destinations)}
|
||||
|
||||
|
||||
def quote_cost(db: Session, tenant_id: int, company_id: int, req: CostRequest) -> list[CostOption]:
|
||||
on_date = req.on_date or date.today()
|
||||
sheets = _sheet_query(db, tenant_id, company_id).filter(
|
||||
|
||||
Reference in New Issue
Block a user