184 lines
7.2 KiB
Python
184 lines
7.2 KiB
Python
# ==============================================================================
|
|
# Servicio de Negocio de Control de Accesos (Ingreso, Salida y Búsquedas)
|
|
# ==============================================================================
|
|
from datetime import datetime
|
|
from typing import List, Dict, Any, Optional
|
|
from fastapi import HTTPException, status
|
|
from app.schemas.access_schema import (
|
|
EntryRequest,
|
|
ExitRequest,
|
|
TicketResponse,
|
|
ActiveTicketDTO,
|
|
PersonSearchDTO,
|
|
LotSearchDTO,
|
|
)
|
|
from app.repositories.access_repository import AccessRepository
|
|
from app.services.hardware_service import HardwareService
|
|
|
|
|
|
class AccessService:
|
|
@staticmethod
|
|
def procesar_ingreso(req: EntryRequest) -> TicketResponse:
|
|
"""
|
|
Ejecuta la regla de negocio para registrar el ingreso:
|
|
1. Verifica antipassback del titular.
|
|
2. Obtiene o crea la entidad Per / PerDocCatVal.
|
|
3. Genera el TicketID canónico.
|
|
4. Persiste en tck, tckprx, tckper, mvthist de forma atómica.
|
|
5. Encola la apertura de barrera en pdtmdl si fue solicitada.
|
|
"""
|
|
# 1. Búsqueda preliminar para verificación de antipassback
|
|
persona_existente = AccessRepository.buscar_persona_por_documento(req.documento)
|
|
if persona_existente:
|
|
pid = persona_existente["PersonaID"]
|
|
if AccessRepository.verificar_antipassback(pid):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_409_CONFLICT,
|
|
detail=f"Antipassback detectado: La persona con DNI {req.documento} ya posee un ingreso activo en el predio.",
|
|
)
|
|
|
|
# 2. Búsqueda o creación de la persona
|
|
persona_id = AccessRepository.buscar_o_crear_persona(
|
|
documento=req.documento,
|
|
apellido=req.apellido or "",
|
|
nombre=req.nombre or "",
|
|
sexo=req.sexo or "M",
|
|
)
|
|
|
|
# 3. Generación del TicketID
|
|
ticket_id = AccessRepository.generar_ticket_id()
|
|
|
|
# 4. Registro transaccional en base de datos
|
|
AccessRepository.registrar_ticket_ingreso(req, persona_id, ticket_id)
|
|
|
|
# 5. Apertura física de barrera vía pdtmdl
|
|
barrier_opened = False
|
|
if req.abrir_barrera and req.modulo_ingreso_id:
|
|
ok, _ = HardwareService.encolar_apertura(req.modulo_ingreso_id, ticket_id)
|
|
barrier_opened = ok
|
|
|
|
ahora = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
return TicketResponse(
|
|
status="ok",
|
|
ticket_id=ticket_id,
|
|
message="Ingreso autorizado y registrado correctamente",
|
|
barrier_opened=barrier_opened,
|
|
fecha_hora=ahora,
|
|
)
|
|
|
|
@staticmethod
|
|
def procesar_salida(req: ExitRequest) -> TicketResponse:
|
|
"""
|
|
Ejecuta la regla de negocio para registrar la salida:
|
|
1. Valida existencia del ticket en tck.
|
|
2. Mueve a tckhst y mvthist, liberando tckper y tck.
|
|
3. Encola la apertura de barrera en pdtmdl si corresponde.
|
|
"""
|
|
ok = AccessRepository.registrar_ticket_salida(
|
|
ticket_id=req.ticket_id,
|
|
modulo_salida_id=req.modulo_salida_id,
|
|
persona_id=req.persona_id or 0,
|
|
patente=req.patente_salida or "",
|
|
)
|
|
if not ok:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Ticket activo {req.ticket_id} no encontrado o ya fue egresado.",
|
|
)
|
|
|
|
barrier_opened = False
|
|
if req.abrir_barrera and req.modulo_salida_id:
|
|
hw_ok, _ = HardwareService.encolar_apertura(req.modulo_salida_id, req.ticket_id)
|
|
barrier_opened = hw_ok
|
|
|
|
ahora = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
return TicketResponse(
|
|
status="ok",
|
|
ticket_id=req.ticket_id,
|
|
message="Salida registrada exitosamente",
|
|
barrier_opened=barrier_opened,
|
|
fecha_hora=ahora,
|
|
)
|
|
|
|
@staticmethod
|
|
def obtener_tickets_activos() -> List[ActiveTicketDTO]:
|
|
"""Obtiene la lista de tickets que se encuentran actualmente dentro del predio."""
|
|
filas = AccessRepository.listar_tickets_activos()
|
|
resultado = []
|
|
for f in filas:
|
|
f_ing = f["FechaHoraIngreso"]
|
|
f_ing_str = f_ing.strftime("%Y-%m-%d %H:%M:%S") if isinstance(f_ing, datetime) else str(f_ing)
|
|
resultado.append(
|
|
ActiveTicketDTO(
|
|
ticket_id=f["TicketID"],
|
|
persona_id=f["PersonaID"],
|
|
documento=str(f.get("Documento") or ""),
|
|
apellido=str(f.get("Apellido") or ""),
|
|
nombre=str(f.get("Nombre") or ""),
|
|
patente=f.get("Patente"),
|
|
lote_codigo=f.get("LoteCodigo"),
|
|
modulo_ingreso=str(f.get("ModuloIngreso") or "Módulo Desconocido"),
|
|
fecha_ingreso=f_ing_str,
|
|
ocupantes=1,
|
|
)
|
|
)
|
|
return resultado
|
|
|
|
@staticmethod
|
|
def buscar_personas(term: str) -> List[PersonSearchDTO]:
|
|
"""Búsqueda predictiva con autocompletado de personas."""
|
|
if not term or len(term.strip()) < 2:
|
|
return []
|
|
filas = AccessRepository.buscar_personas_predictivo(term)
|
|
return [
|
|
PersonSearchDTO(
|
|
persona_id=f["PersonaID"],
|
|
documento=str(f.get("Documento") or ""),
|
|
apellido=str(f.get("Apellido") or ""),
|
|
nombre=str(f.get("Nombre") or ""),
|
|
sexo=str(f.get("Sexo") or "M"),
|
|
)
|
|
for f in filas
|
|
]
|
|
|
|
@staticmethod
|
|
def buscar_lotes(term: str) -> List[LotSearchDTO]:
|
|
"""Búsqueda predictiva con autocompletado de lotes."""
|
|
if not term or len(term.strip()) < 1:
|
|
return []
|
|
filas = AccessRepository.buscar_lotes_predictivo(term)
|
|
return [
|
|
LotSearchDTO(
|
|
lote_id=f["LoteID"],
|
|
codigo=str(f["Codigo"]),
|
|
propietario=None,
|
|
)
|
|
for f in filas
|
|
]
|
|
|
|
@staticmethod
|
|
def obtener_ultimos_movimientos(limite: int = 50) -> List[dict]:
|
|
"""Retorna los últimos movimientos reales registrados en SQL Server mvthist."""
|
|
from app.schemas.access_schema import MovementHistoryDTO
|
|
filas = AccessRepository.listar_ultimos_movimientos(limite)
|
|
resultado = []
|
|
for f in filas:
|
|
fh = f["FechaHora"]
|
|
fh_str = fh.strftime("%Y-%m-%d %H:%M:%S") if isinstance(fh, datetime) else str(fh)
|
|
resultado.append(
|
|
MovementHistoryDTO(
|
|
mvt_hist_id=f["MvtHistID"],
|
|
ticket_id=f["TicketID"] or 0,
|
|
sentido=str(f["Sentido"] or "Ingreso"),
|
|
patente=f.get("Patente"),
|
|
apellido=f.get("Apellido"),
|
|
nombre=f.get("Nombre"),
|
|
documento=f.get("Documento"),
|
|
lote_codigo=None,
|
|
modulo_nombre=f.get("ModuloNombre"),
|
|
fecha_hora=fh_str,
|
|
entidad=f.get("Entidad"),
|
|
)
|
|
)
|
|
return resultado
|