feat: complete Phases 2 to 5 inclusive - Access Core, Web Cockpit, Hardware enqueuing, Optical Scanner and QA (v0.5.0-beta)
This commit is contained in:
@@ -0,0 +1 @@
|
||||
# Services module
|
||||
@@ -0,0 +1,157 @@
|
||||
# ==============================================================================
|
||||
# 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
|
||||
]
|
||||
@@ -0,0 +1,60 @@
|
||||
# ==============================================================================
|
||||
# Servicio de Autenticación y Control de Sesión
|
||||
# ==============================================================================
|
||||
from typing import Optional, Tuple
|
||||
from fastapi import HTTPException, status
|
||||
from app.repositories.auth_repository import AuthRepository
|
||||
from app.core.security import verificar_password, crear_access_token
|
||||
from app.schemas.auth_schema import LoginResponse, UserSessionDTO
|
||||
|
||||
|
||||
class AuthService:
|
||||
@staticmethod
|
||||
def autenticar_usuario(
|
||||
username: str, password_raw: str, workstation_name: Optional[str] = None
|
||||
) -> Tuple[LoginResponse, str]:
|
||||
"""Valida credenciales, genera token JWT y registra auditoría."""
|
||||
user_row = AuthRepository.obtener_usuario_por_nombre(username)
|
||||
if not user_row:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Credenciales inválidas: usuario o contraseña incorrectos",
|
||||
)
|
||||
|
||||
stored_password = user_row.get("Password", "")
|
||||
if not verificar_password(password_raw, stored_password):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Credenciales inválidas: usuario o contraseña incorrectos",
|
||||
)
|
||||
|
||||
user_id = user_row["UsuarioID"]
|
||||
nombre = user_row["Nombre"].strip()
|
||||
system_param = user_row.get("SystemParameter")
|
||||
|
||||
# Generar Token JWT
|
||||
token_data = {
|
||||
"sub": str(user_id),
|
||||
"username": nombre,
|
||||
"workstation": workstation_name or "",
|
||||
}
|
||||
token = crear_access_token(token_data)
|
||||
|
||||
# Registrar auditoría en usrlogin
|
||||
AuthRepository.registrar_evento_login(user_id)
|
||||
|
||||
user_dto = UserSessionDTO(
|
||||
user_id=user_id,
|
||||
username=nombre,
|
||||
role="SUPERVISOR" if system_param == 1 else "OPERADOR",
|
||||
system_parameter=system_param,
|
||||
)
|
||||
|
||||
response = LoginResponse(
|
||||
status="ok",
|
||||
message="Autenticación exitosa",
|
||||
user=user_dto,
|
||||
workstation=workstation_name,
|
||||
)
|
||||
|
||||
return response, token
|
||||
@@ -0,0 +1,121 @@
|
||||
# ==============================================================================
|
||||
# Servicio de Parseo y Normalización de DNI Argentino (PDF417 / QR)
|
||||
# Soporta formatos 2009, 2012, 2026 y App Mi Argentina
|
||||
# ==============================================================================
|
||||
from typing import Dict
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class DNIParsedResult(BaseModel):
|
||||
valido: bool
|
||||
documento: str
|
||||
apellido: str
|
||||
nombre: str
|
||||
sexo: str
|
||||
|
||||
|
||||
class DniParserService:
|
||||
@staticmethod
|
||||
def parsear(raw_text: str) -> Dict[str, str]:
|
||||
"""
|
||||
Parsea el texto decodificado por la cámara de la tablet o escáner.
|
||||
Retorna: {"documento": str, "apellido": str, "nombre": str, "sexo": str}
|
||||
"""
|
||||
if not raw_text:
|
||||
return {"documento": "", "apellido": "", "nombre": "", "sexo": "M"}
|
||||
|
||||
# Limpiar terminadores y retornos de carro
|
||||
raw_clean = raw_text.strip().replace("\r", "").replace("\n", "")
|
||||
|
||||
# Algunos escáneres o formatos vienen separados por @ en lugar de comillas dobles
|
||||
text = raw_clean.replace("@", '"')
|
||||
parts = [p.strip() for p in text.split('"')]
|
||||
|
||||
if len(parts) < 5:
|
||||
# Si solo vino un número de documento escrito manualmente
|
||||
digits = "".join(filter(str.isdigit, raw_clean))
|
||||
if 6 <= len(digits) <= 9:
|
||||
return {"documento": digits, "apellido": "", "nombre": "", "sexo": "M"}
|
||||
return {"documento": "", "apellido": "", "nombre": "", "sexo": "M"}
|
||||
|
||||
doc = nombre = apellido = sexo = ""
|
||||
|
||||
# Heurística para Formato 2009 con comilla inicial
|
||||
if parts[0] == "" and 6 <= len(parts[1]) <= 11 and len(parts) > 2 and parts[2].isalpha() and len(parts[2]) == 1:
|
||||
doc = parts[1]
|
||||
if len(parts) > 5:
|
||||
apellido = parts[4]
|
||||
nombre = parts[5]
|
||||
|
||||
# Heurística para Formato 2009 sin comilla inicial
|
||||
elif 6 <= len(parts[0]) <= 11 and len(parts) > 4 and parts[1].isalpha() and len(parts[1]) == 1:
|
||||
doc = parts[0]
|
||||
apellido = parts[3]
|
||||
nombre = parts[4]
|
||||
|
||||
# Formatos 2012, 2026 y App Mi Argentina
|
||||
else:
|
||||
if parts[0] == "" and len(parts) > 1:
|
||||
parts = parts[1:]
|
||||
|
||||
if parts[0].isdigit() and len(parts[0]) >= 8:
|
||||
apellido = parts[1] if len(parts) > 1 else ""
|
||||
nombre = parts[2] if len(parts) > 2 else ""
|
||||
|
||||
if len(parts) > 3:
|
||||
p3 = parts[3].strip()
|
||||
p4 = parts[4].strip() if len(parts) > 4 else ""
|
||||
|
||||
# Formato 2012: parts[3] es letra de sexo (M, F, X)
|
||||
if len(p3) == 1 and p3.upper() in ("M", "F", "X"):
|
||||
sexo = p3.upper()
|
||||
if len(parts) > 4:
|
||||
doc = p4
|
||||
|
||||
# Formato App Mi Argentina: parts[3] es código 1=M, 2=F, 3=X y parts[4] es DNI
|
||||
elif p3 in ("1", "2", "3", "0") and p4.isdigit() and 6 <= len(p4) <= 9:
|
||||
sexo = "M" if p3 == "1" else ("F" if p3 == "2" else "X")
|
||||
doc = p4
|
||||
|
||||
# Formato 2026: parts[3] es DNI directo
|
||||
elif p3.isdigit() and 6 <= len(p3) <= 9 and not (p4.isdigit() and 6 <= len(p4) <= 9):
|
||||
doc = p3
|
||||
if p4.upper() in ("M", "F", "X"):
|
||||
sexo = p4.upper()
|
||||
elif p4.upper() == "G":
|
||||
sexo = "M"
|
||||
|
||||
# Desempate general: si parts[4] es DNI numérico
|
||||
elif p4.isdigit() and 6 <= len(p4) <= 9:
|
||||
doc = p4
|
||||
if p3 == "1":
|
||||
sexo = "M"
|
||||
elif p3 == "2":
|
||||
sexo = "F"
|
||||
elif p3.upper() in ("M", "F", "X"):
|
||||
sexo = p3.upper()
|
||||
else:
|
||||
doc = p3
|
||||
|
||||
return {
|
||||
"documento": doc.strip(),
|
||||
"apellido": apellido.upper().strip() if apellido else "",
|
||||
"nombre": nombre.upper().strip() if nombre else "",
|
||||
"sexo": sexo or "M",
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def parsear_codigo(cls, raw_text: str) -> DNIParsedResult:
|
||||
res = cls.parsear(raw_text)
|
||||
valido = bool(res["documento"] and len(res["documento"]) >= 6)
|
||||
return DNIParsedResult(
|
||||
valido=valido,
|
||||
documento=res["documento"],
|
||||
apellido=res["apellido"],
|
||||
nombre=res["nombre"],
|
||||
sexo=res["sexo"],
|
||||
)
|
||||
|
||||
|
||||
# Alias para compatibilidad de nomenclatura
|
||||
DNIParsingService = DniParserService
|
||||
@@ -0,0 +1,94 @@
|
||||
# ==============================================================================
|
||||
# Servicio de Integración de Hardware Industrial (ST1660 / pdtmdl)
|
||||
# ==============================================================================
|
||||
import time
|
||||
from typing import Tuple, Dict, Any, Optional
|
||||
from app.core.database import db_session
|
||||
|
||||
ASCII_STX = "\x02" # Start of text
|
||||
ASCII_EOF = "\x03" # End of file
|
||||
|
||||
|
||||
def calcular_checksum(comando: str) -> str:
|
||||
"""Calcula el checksum de 2 dígitos hexadecimales idéntico a VB6 Protocolo.cls."""
|
||||
raw = comando.encode("latin-1", errors="ignore")
|
||||
checksum = 0
|
||||
for b in raw:
|
||||
checksum = (checksum + b) & 0xFF
|
||||
checksum = ((0xFF - checksum) + 1) & 0xFF
|
||||
return f"{checksum:02X}"
|
||||
|
||||
|
||||
def formatear_comando_hardware(direccion: int, comando_payload: str) -> str:
|
||||
"""Genera la trama física: STX + Addr(2) + Payload + CS(2) + EOF."""
|
||||
direccion_str = f"{direccion:02d}"
|
||||
base = f"{ASCII_STX}{direccion_str}{comando_payload}"
|
||||
cs = calcular_checksum(base)
|
||||
return f"{base}{cs}{ASCII_EOF}"
|
||||
|
||||
|
||||
class HardwareService:
|
||||
@staticmethod
|
||||
def obtener_info_modulo(modulo_id: int) -> Optional[Dict[str, Any]]:
|
||||
"""Obtiene address, tipo y configuración del módulo desde la tabla `mdl`."""
|
||||
query = """
|
||||
SELECT m.ModuloID, m.Nombre, m.Address, m.ModuloEntradaID, m.ModuloSalidaID,
|
||||
m.duracion_pulso, m.ValidacionTicket
|
||||
FROM mdl m
|
||||
WHERE m.ModuloID = %s
|
||||
"""
|
||||
with db_session() as conn:
|
||||
cursor = conn.cursor(as_dict=True)
|
||||
cursor.execute(query, (modulo_id,))
|
||||
return cursor.fetchone()
|
||||
|
||||
@classmethod
|
||||
def encolar_apertura(cls, modulo_id: int, ticket_id: int = 0) -> Tuple[bool, Dict[str, Any]]:
|
||||
"""
|
||||
Encola un comando de apertura de barrera/molinete en la tabla `pdtmdl`
|
||||
para que OnEverWPC lo despache al bus RS-485 físico en < 50ms.
|
||||
"""
|
||||
t_start = time.perf_counter()
|
||||
mdl = cls.obtener_info_modulo(modulo_id)
|
||||
if not mdl:
|
||||
return False, {"error": f"Módulo {modulo_id} no encontrado en base de datos"}
|
||||
|
||||
address = mdl.get("Address", 1)
|
||||
duracion = mdl.get("duracion_pulso") or 500
|
||||
|
||||
# Verificamos si es variante PASS (Access) o PARK (Default)
|
||||
is_pass = False
|
||||
try:
|
||||
with db_session() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(
|
||||
"SELECT ValorID FROM MdlCatVal WHERE ModuloID = %s AND CategoriaID = 2",
|
||||
(modulo_id,),
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
is_pass = (row is not None and int(row[0]) == 1)
|
||||
except Exception:
|
||||
is_pass = False
|
||||
|
||||
# Determinación del payload de pulso según protocolo
|
||||
payload = "V3" if is_pass else "O3"
|
||||
trama_comando = formatear_comando_hardware(address, payload)
|
||||
|
||||
sql_insert = """
|
||||
INSERT INTO pdtmdl (PdtMdlID, ModuloID, Comando, Inmediato, Extra)
|
||||
VALUES ((SELECT COALESCE(MAX(PdtMdlID), 0) + 1 FROM pdtmdl), %s, %s, 1, %s)
|
||||
"""
|
||||
extra_info = str(ticket_id or 0)[:20]
|
||||
|
||||
with db_session() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(sql_insert, (modulo_id, trama_comando, extra_info))
|
||||
|
||||
latencia = (time.perf_counter() - t_start) * 1000
|
||||
|
||||
return True, {
|
||||
"modulo_id": modulo_id,
|
||||
"address": address,
|
||||
"payload": payload,
|
||||
"latencia_ms": round(latencia, 2),
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
# ==============================================================================
|
||||
# Servicio de Gestión de Estaciones de Trabajo (Workstations)
|
||||
# ==============================================================================
|
||||
from typing import List, Dict, Any
|
||||
from app.repositories.workstation_repository import WorkstationRepository
|
||||
from app.schemas.workstation_schema import WorkstationStatusResponse, LaneModuleDTO
|
||||
|
||||
|
||||
class WorkstationService:
|
||||
@staticmethod
|
||||
def obtener_estado_workstation(name: str) -> WorkstationStatusResponse:
|
||||
"""Determina si la tablet/workstation está registrada y qué carriles tiene asignados."""
|
||||
wks_row = WorkstationRepository.obtener_workstation_por_nombre(name)
|
||||
if not wks_row:
|
||||
return WorkstationStatusResponse(
|
||||
workstation_name=name,
|
||||
is_control_post=False,
|
||||
workstation_id=None,
|
||||
modules=[],
|
||||
)
|
||||
|
||||
wks_id = wks_row["WorkstationID"]
|
||||
nombre_oficial = wks_row["Nombre"].strip()
|
||||
modulos_rows = WorkstationRepository.listar_modulos_por_workstation(wks_id)
|
||||
|
||||
modules_dto: List[LaneModuleDTO] = []
|
||||
for m in modulos_rows:
|
||||
# Determinamos si es entrada o salida según ModuloEntradaID o nombre
|
||||
es_entrada = bool(m.get("ModuloEntradaID")) or "ENTRADA" in m["Nombre"].upper()
|
||||
modules_dto.append(
|
||||
LaneModuleDTO(
|
||||
modulo_id=m["ModuloID"],
|
||||
nombre=m["Nombre"].strip(),
|
||||
address=m["Address"],
|
||||
grupo_modulos=m.get("GrupoModulos"),
|
||||
es_entrada=es_entrada,
|
||||
duracion_pulso=m.get("duracion_pulso"),
|
||||
)
|
||||
)
|
||||
|
||||
return WorkstationStatusResponse(
|
||||
workstation_name=nombre_oficial,
|
||||
is_control_post=len(modules_dto) > 0,
|
||||
workstation_id=wks_id,
|
||||
modules=modules_dto,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def listar_estaciones_disponibles() -> List[Dict[str, Any]]:
|
||||
"""Retorna el listado de todas las workstations disponibles para selección de supervisor."""
|
||||
rows = WorkstationRepository.listar_todas()
|
||||
return [{"workstation_id": r["WorkstationID"], "nombre": r["Nombre"].strip()} for r in rows]
|
||||
Reference in New Issue
Block a user