La barra lateral y el recorrido quedan en el orden nuevo: 1 Carga de información, 2 Cartera, 3 Expediente, 4 Beneficiario controlador, 5 Créditos y operaciones (solo consulta), 6 Screening, 7 Clasificación de riesgo, 8 Alertas y casos, 9 Evidencia, 10 Laboratorio. El número de paso de cada pantalla sale de NAVEGACION (ceja_paso), no de las plantillas. El módulo muestra la última carga (fecha, quién, conteos y resultado), la plantilla, la subida (solo oficial), el historial con su reporte de rechazos y un aviso cuando la empresa lleva más de su periodo de carga sin cargar. Inicio muestra primero la tarjeta de carga.
207 lines
7.6 KiB
Python
207 lines
7.6 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.
|
|
|
|
Sube y confirma el oficial; el analista descarga la plantilla y ve el historial; el auditor ve
|
|
todo y no sube.
|
|
"""
|
|
|
|
from typing import Annotated
|
|
|
|
from fastapi import APIRouter, Depends, File, HTTPException, Query, Request, UploadFile, status
|
|
from sqlalchemy.orm import Session
|
|
from starlette.responses import HTMLResponse, 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.alertas import tenant_de_sesion
|
|
|
|
router = APIRouter(tags=["carga"])
|
|
|
|
ROLES_CARGA = (Rol.OFICIAL,)
|
|
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)),
|
|
"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,
|
|
"ya_cargado": request.query_params.get("ya_cargado") == "1",
|
|
"error": request.query_params.get("error"),
|
|
},
|
|
)
|
|
|
|
|
|
@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}"'},
|
|
)
|