Files
collina-pld/app/routers/carga.py
T

256 lines
10 KiB
Python

"""Router `carga`: módulo 1, carga de información (Pieza K; sustituye a `/operaciones/cargas`).
- `GET /carga`: plantilla, subir archivo e historial de lotes.
- `GET /carga/plantilla?formato=xlsx|csv`: la plantilla del giro de la empresa (`tenant.giro`),
en Excel o como `.zip` con un CSV por tipo de registro.
- `POST /carga`: guarda el original en disco y prepara el lote (validación por fila; no carga).
- `GET /carga/lotes/<id>`: aceptadas, rechazadas (con cascada), existentes, advertencias y el
primer tramo de rechazos; «Cargar las aceptadas» o «Cancelar y corregir».
- `POST /carga/lotes/<id>/confirmar` (carga las aceptadas y lanza en segundo plano el screening,
la reevaluación y las reglas), `/cancelar` y `/reanudar` (un lote interrumpido).
- `GET /carga/lotes/<id>/rechazos`: el reporte completo en el formato que subió el usuario.
- `GET /carga/lotes/<id>/original`: el archivo tal cual se subió, solo si su huella SHA-256
coincide con la registrada; cada descarga (y cada intento bloqueado) queda en el audit trail.
Sube y confirma el oficial; el analista descarga la plantilla y ve el historial; el auditor ve
todo y no sube. El original lo descargan los tres; el administrador de plataforma no entra a
ninguna ruta de empresa (403): el archivo trae datos de clientes.
"""
from typing import Annotated
from fastapi import APIRouter, Depends, File, HTTPException, Query, Request, UploadFile, status
from sqlalchemy.orm import Session
from starlette.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response
from app.auth import requiere_rol
from app.db import get_db
from app.importers import plantillas
from app.importers.operations import TAMANO_MAXIMO_MB
from app.models import LoteCarga, Usuario
from app.models.usuario import Rol
from app.routers import render
from app.services import operaciones as servicio
from app.services import screening as servicio_screening
from app.services.alertas import tenant_de_sesion
from app.services.expediente import nombres_para_mostrar
router = APIRouter(tags=["carga"])
ROLES_CARGA = (Rol.OFICIAL,)
ROLES_ORIGINAL = (Rol.OFICIAL, Rol.ANALISTA, Rol.AUDITOR)
CABECERA_HUELLA = "X-Huella-Verificada"
TIPOS_ORIGINAL = {
"xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"csv": "text/csv",
}
MAXIMO_RECHAZOS_EN_PANTALLA = 200
TIPOS_CONTENIDO = {
"xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"csv": "application/zip",
}
def _lote(db: Session, lote_id: int) -> LoteCarga:
lote = servicio.lote_de_carga(db, lote_id)
if lote is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "Carga no encontrada.")
return lote
def _ir(destino: str) -> Response:
return RedirectResponse(destino, status_code=status.HTTP_303_SEE_OTHER)
@router.get("/carga", include_in_schema=False)
def modulo(request: Request, db: Annotated[Session, Depends(get_db)]) -> HTMLResponse:
tenant = tenant_de_sesion(db)
return render(
request,
"carga/index.html",
{
"giro": plantillas.giro(tenant.giro),
"ultima": servicio.ultima_carga(db, tenant),
"vencida": servicio.carga_vencida(db, tenant),
"periodo_meses": tenant.periodo_carga_meses,
"historial": (historial := servicio.historial_cargas(db)),
"puede_descargar_original": request.state.usuario.rol in ROLES_ORIGINAL,
"estados": {
lote.id: servicio.estado_visible(lote)
for lote in [*historial, servicio.ultima_carga(db, tenant)]
if lote is not None
},
"puede_cargar": request.state.usuario.rol in ROLES_CARGA,
"tamano_maximo_mb": TAMANO_MAXIMO_MB,
"error": request.query_params.get("error"),
},
)
@router.get("/carga/plantilla", include_in_schema=False)
def descargar_plantilla(
db: Annotated[Session, Depends(get_db)],
formato: Annotated[str, Query(max_length=4)] = "xlsx",
) -> Response:
if formato not in TIPOS_CONTENIDO:
raise HTTPException(status.HTTP_400_BAD_REQUEST, "El formato debe ser xlsx o csv.")
tenant = tenant_de_sesion(db)
try:
giro = plantillas.giro(tenant.giro)
except LookupError as exc:
raise HTTPException(status.HTTP_404_NOT_FOUND, str(exc)) from None
contenido = (
plantillas.plantilla_xlsx(giro) if formato == "xlsx" else plantillas.plantilla_csv_zip(giro)
)
nombre = plantillas.nombre_descarga(giro, formato)
return Response(
contenido,
media_type=TIPOS_CONTENIDO[formato],
headers={"Content-Disposition": f'attachment; filename="{nombre}"'},
)
@router.post("/carga", include_in_schema=False)
def subir(
db: Annotated[Session, Depends(get_db)],
usuario: Annotated[Usuario, Depends(requiere_rol(*ROLES_CARGA))],
archivo: Annotated[UploadFile, File()],
) -> Response:
try:
ruta, _ = servicio.guardar_archivo(archivo.file, archivo.filename or "")
except servicio.CargaError as exc:
from urllib.parse import quote
return _ir(f"/carga?error={quote(str(exc))}")
with db.begin_nested():
lote, ya_cargado = servicio.preparar_carga(
db, ruta, archivo.filename or "", usuario.usuario
)
db.commit()
return _ir(f"/carga/lotes/{lote.id}" + ("?ya_cargado=1" if ya_cargado else ""))
@router.get("/carga/lotes/{lote_id:int}", include_in_schema=False)
def ver_lote(
request: Request, lote_id: int, db: Annotated[Session, Depends(get_db)]
) -> HTMLResponse:
lote = _lote(db, lote_id)
rechazos = []
for i, fila in enumerate(servicio.rechazos(db, lote)):
if i >= MAXIMO_RECHAZOS_EN_PANTALLA:
break
rechazos.append(dict(zip(servicio.COLUMNAS_REPORTE, fila, strict=True)))
return render(
request,
"carga/lote.html",
{
"lote": lote,
"estado": servicio.estado_visible(lote),
"datos": lote.filas or {},
"rechazos": rechazos,
"maximo_rechazos": MAXIMO_RECHAZOS_EN_PANTALLA,
"puede_cargar": request.state.usuario.rol in ROLES_CARGA,
"puede_descargar_original": bool(lote.ruta_archivo)
and request.state.usuario.rol in ROLES_ORIGINAL,
"ya_cargado": request.query_params.get("ya_cargado") == "1",
"error": request.query_params.get("error"),
"sin_listas": not servicio_screening.listas_vigentes(db, tenant_de_sesion(db)),
# Cambios de nivel: el nombre o el RFC del cliente, no su identificador interno.
"nombres": nombres_para_mostrar(
db,
tenant_de_sesion(db),
[c["cliente_id"] for c in (lote.filas or {}).get("cambios_nivel", [])[:20]],
),
},
)
@router.post("/carga/lotes/{lote_id:int}/confirmar", include_in_schema=False)
def confirmar(
lote_id: int,
db: Annotated[Session, Depends(get_db)],
usuario: Annotated[Usuario, Depends(requiere_rol(*ROLES_CARGA))],
) -> Response:
from urllib.parse import quote
try:
with db.begin_nested():
servicio.confirmar_carga(db, lote_id, usuario.usuario)
except servicio.CargaError as exc:
return _ir(f"/carga/lotes/{lote_id}?error={quote(str(exc))}")
db.commit()
# Screening, reevaluación y reglas, en segundo plano: la página muestra el avance.
servicio.lanzar_procesamiento(lote_id, usuario.usuario)
return _ir(f"/carga/lotes/{lote_id}")
@router.post("/carga/lotes/{lote_id:int}/reanudar", include_in_schema=False)
def reanudar(
lote_id: int,
db: Annotated[Session, Depends(get_db)],
usuario: Annotated[Usuario, Depends(requiere_rol(*ROLES_CARGA))],
) -> Response:
from urllib.parse import quote
try:
servicio.reanudar_carga(db, lote_id, usuario.usuario)
except servicio.CargaError as exc:
return _ir(f"/carga/lotes/{lote_id}?error={quote(str(exc))}")
db.commit()
servicio.lanzar_procesamiento(lote_id, usuario.usuario)
return _ir(f"/carga/lotes/{lote_id}")
@router.post("/carga/lotes/{lote_id:int}/cancelar", include_in_schema=False)
def cancelar(
lote_id: int,
db: Annotated[Session, Depends(get_db)],
usuario: Annotated[Usuario, Depends(requiere_rol(*ROLES_CARGA))],
) -> Response:
from urllib.parse import quote
try:
servicio.cancelar_carga(db, lote_id, usuario.usuario)
except servicio.CargaError as exc:
return _ir(f"/carga/lotes/{lote_id}?error={quote(str(exc))}")
db.commit()
return _ir(f"/carga/lotes/{lote_id}")
@router.get("/carga/lotes/{lote_id:int}/rechazos", include_in_schema=False)
def descargar_rechazos(lote_id: int, db: Annotated[Session, Depends(get_db)]) -> Response:
contenido, nombre, tipo = servicio.reporte_rechazos(db, _lote(db, lote_id))
return Response(
contenido,
media_type=tipo,
headers={"Content-Disposition": f'attachment; filename="{nombre}"'},
)
@router.get("/carga/lotes/{lote_id:int}/original", include_in_schema=False)
def descargar_original(
request: Request,
lote_id: int,
db: Annotated[Session, Depends(get_db)],
usuario: Annotated[Usuario, Depends(requiere_rol(*ROLES_ORIGINAL))],
) -> Response:
"""El original, con la huella recalculada. Si no coincide, no se entrega: la página del lote
muestra el error (o, pedido desde la página con `fetch`, un 409 con el mensaje)."""
from urllib.parse import quote
lote = _lote(db, lote_id)
try:
ruta = servicio.original_verificado(db, lote)
except servicio.CargaError as exc:
db.commit() # el intento bloqueado queda en el audit trail
if request.headers.get("X-Solicitud") == "fetch":
return JSONResponse({"error": str(exc)}, status_code=status.HTTP_409_CONFLICT)
return _ir(f"/carga/lotes/{lote_id}?error={quote(str(exc))}")
db.commit()
return FileResponse(
ruta,
filename=lote.nombre_archivo or ruta.name,
media_type=TIPOS_ORIGINAL.get(lote.formato or "", "application/octet-stream"),
headers={CABECERA_HUELLA: lote.archivo_hash},
)