feat(parity): implement Bloques 1, 2 y 3 complete feature parity v0.7.0-beta
This commit is contained in:
@@ -14,6 +14,10 @@ from app.schemas.access_schema import (
|
||||
PersonPoliciesDTO,
|
||||
VehicleDetailsDTO,
|
||||
LotResidentDTO,
|
||||
PreauthorizationDTO,
|
||||
VehicleSearchResultDTO,
|
||||
MassExitRequestDTO,
|
||||
MassExitResultDTO,
|
||||
)
|
||||
from app.repositories.access_repository import AccessRepository
|
||||
from app.services.hardware_service import HardwareService
|
||||
@@ -362,3 +366,43 @@ class AccessService:
|
||||
return None
|
||||
return VehicleDetailsDTO(**datos)
|
||||
|
||||
@staticmethod
|
||||
def listar_preautorizados(busqueda: str = "", solo_vigentes: bool = True) -> List[PreauthorizationDTO]:
|
||||
filas = AccessRepository.obtener_preautorizados_activos(busqueda=busqueda, solo_vigentes=solo_vigentes)
|
||||
return [PreauthorizationDTO(**f) for f in filas]
|
||||
|
||||
@staticmethod
|
||||
def consumir_preautorizado(preautorizado_id: int) -> bool:
|
||||
return AccessRepository.consumir_preautorizacion(preautorizado_id)
|
||||
|
||||
@staticmethod
|
||||
def buscar_personas_avanzado(texto: str, limite: int = 50) -> List[Dict[str, Any]]:
|
||||
return AccessRepository.buscar_personas_avanzado(texto=texto, limite=limite)
|
||||
|
||||
@staticmethod
|
||||
def buscar_vehiculos(termino: str, es_salida: bool = False, limite: int = 50) -> List[VehicleSearchResultDTO]:
|
||||
filas = AccessRepository.buscar_vehiculos_coincidencias(termino=termino, es_salida=es_salida, limite=limite)
|
||||
return [VehicleSearchResultDTO(**f) for f in filas]
|
||||
|
||||
@staticmethod
|
||||
def procesar_salida_masiva(req: MassExitRequestDTO, usuario_id: int, operador: str) -> MassExitResultDTO:
|
||||
ok, msg, salida_id = AccessRepository.ejecutar_salida_masiva(
|
||||
ticket_ids=req.ticket_ids,
|
||||
usuario_id=usuario_id,
|
||||
operador=operador,
|
||||
modulo_salida_id=req.modulo_salida_id,
|
||||
motivo=req.motivo,
|
||||
observaciones=req.observaciones or "",
|
||||
)
|
||||
if not ok:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=msg,
|
||||
)
|
||||
return MassExitResultDTO(
|
||||
status="ok",
|
||||
egresados_count=len(req.ticket_ids),
|
||||
message=msg,
|
||||
salida_masiva_id=salida_id,
|
||||
)
|
||||
|
||||
|
||||
@@ -2,10 +2,37 @@
|
||||
# Servicio de Parseo y Normalización de DNI Argentino (PDF417 / QR)
|
||||
# Soporta formatos 2009, 2012, 2026 y App Mi Argentina
|
||||
# ==============================================================================
|
||||
from typing import Dict
|
||||
import re
|
||||
from typing import Dict, Tuple, Optional
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
def limpiar_numero_documento(doc_raw: str) -> Tuple[str, Optional[str]]:
|
||||
"""
|
||||
Limpia y normaliza un número de documento DNI argentino.
|
||||
En formatos antiguos (Libreta Cívica, Libreta de Enrolamiento o Formato 2009),
|
||||
el documento suele estar precedido por 'F' (Femenino) o 'M' (Masculino),
|
||||
por ejemplo: 'F5592570' -> ('5592570', 'F'), 'M34247025' -> ('34247025', 'M').
|
||||
Retorna (documento_numerico, sexo_inferido).
|
||||
"""
|
||||
if not doc_raw:
|
||||
return "", None
|
||||
doc_clean = str(doc_raw).strip()
|
||||
doc_sin_puntos = doc_clean.replace(".", "").replace(",", "").replace(" ", "")
|
||||
|
||||
# Patrón: Prefijo F o M seguido de 5 a 9 dígitos
|
||||
m = re.match(r"^([FMfm])(\d{5,9})$", doc_sin_puntos)
|
||||
if m:
|
||||
return m.group(2), m.group(1).upper()
|
||||
|
||||
# Si contiene dígitos precedidos por F/M con posibles espacios o puntos
|
||||
m2 = re.match(r"^([FMfm])[\s\.]*(\d{5,9})$", doc_clean)
|
||||
if m2:
|
||||
return m2.group(2), m2.group(1).upper()
|
||||
|
||||
return doc_sin_puntos if doc_sin_puntos.isdigit() else doc_clean, None
|
||||
|
||||
|
||||
class DNIParsedResult(BaseModel):
|
||||
valido: bool
|
||||
documento: str
|
||||
@@ -27,28 +54,32 @@ class DniParserService:
|
||||
# Limpiar terminadores y retornos de carro
|
||||
raw_clean = raw_text.strip().replace("\r", "").replace("\n", "")
|
||||
|
||||
# Si solo vino un número de documento escrito manualmente (o escaneado directamente)
|
||||
doc_limpio, sexo_directo = limpiar_numero_documento(raw_clean)
|
||||
if 5 <= len(doc_limpio) <= 9 and doc_limpio.isdigit() and '"' not in raw_clean and '@' not in raw_clean:
|
||||
return {"documento": doc_limpio, "apellido": "", "nombre": "", "sexo": sexo_directo or "M"}
|
||||
|
||||
# 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"}
|
||||
if 5 <= len(digits) <= 9:
|
||||
return {"documento": digits, "apellido": "", "nombre": "", "sexo": sexo_directo or "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:
|
||||
if parts[0] == "" and 5 <= 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:
|
||||
elif 5 <= 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]
|
||||
@@ -73,12 +104,12 @@ class DniParserService:
|
||||
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:
|
||||
elif p3 in ("1", "2", "3", "0") and p4.isdigit() and 5 <= 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):
|
||||
elif p3.isdigit() and 5 <= len(p3) <= 9 and not (p4.isdigit() and 5 <= len(p4) <= 9):
|
||||
doc = p3
|
||||
if p4.upper() in ("M", "F", "X"):
|
||||
sexo = p4.upper()
|
||||
@@ -86,7 +117,7 @@ class DniParserService:
|
||||
sexo = "M"
|
||||
|
||||
# Desempate general: si parts[4] es DNI numérico
|
||||
elif p4.isdigit() and 6 <= len(p4) <= 9:
|
||||
elif p4.isdigit() and 5 <= len(p4) <= 9:
|
||||
doc = p4
|
||||
if p3 == "1":
|
||||
sexo = "M"
|
||||
@@ -97,6 +128,13 @@ class DniParserService:
|
||||
else:
|
||||
doc = p3
|
||||
|
||||
# Normalizar DNI por si trajo prefijo F/M en Formato 2009 o Libreta Cívica
|
||||
num_limpio, sexo_inf = limpiar_numero_documento(doc)
|
||||
if num_limpio:
|
||||
doc = num_limpio
|
||||
if not sexo and sexo_inf:
|
||||
sexo = sexo_inf
|
||||
|
||||
return {
|
||||
"documento": doc.strip(),
|
||||
"apellido": apellido.upper().strip() if apellido else "",
|
||||
|
||||
@@ -252,3 +252,116 @@ class HardwareService:
|
||||
"trama_ticket": trama_ticket,
|
||||
"latencia_ms": round(latencia, 2),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def encolar_cierre(cls, modulo_id: int, ticket_id: int = 0) -> Tuple[bool, Dict[str, Any]]:
|
||||
"""
|
||||
Encola un comando de cierre forzado de barrera/molinete en la tabla `pdtmdl`
|
||||
con tramas C0..C6 según tipo_acceso y firmware (PASS vs PARK).
|
||||
Paridad 1:1 con pct_repository.py:encolar_comando_cierre_modulo (v1.2.3).
|
||||
"""
|
||||
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"}
|
||||
|
||||
cat_map = {}
|
||||
try:
|
||||
with db_session() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(
|
||||
"SELECT CategoriaID, ValorID FROM MdlCatVal WHERE ModuloID = %s",
|
||||
(modulo_id,),
|
||||
)
|
||||
cat_map = {row[0]: row[1] for row in cursor.fetchall()}
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
tipo_modulo_id = cat_map.get(2, 0)
|
||||
sentido_id = cat_map.get(4, 0)
|
||||
nombre_upper = (mdl.get("Nombre") or "").upper()
|
||||
|
||||
target_id = modulo_id
|
||||
target_mdl = mdl
|
||||
|
||||
if tipo_modulo_id == 6 or mdl.get("Address", 0) >= 90:
|
||||
if (sentido_id == 1 or "ENTRADA" in nombre_upper or "INGRESO" in nombre_upper) and mdl.get("ModuloEntradaID"):
|
||||
target_id = mdl["ModuloEntradaID"]
|
||||
elif (sentido_id == 2 or "SALIDA" in nombre_upper or "EGRESO" in nombre_upper) and mdl.get("ModuloSalidaID"):
|
||||
target_id = mdl["ModuloSalidaID"]
|
||||
|
||||
if target_id != modulo_id:
|
||||
fisico = cls.obtener_info_modulo(target_id)
|
||||
if fisico:
|
||||
target_mdl = fisico
|
||||
|
||||
target_cat_map = {}
|
||||
if target_id != modulo_id:
|
||||
try:
|
||||
with db_session() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(
|
||||
"SELECT CategoriaID, ValorID FROM MdlCatVal WHERE ModuloID = %s",
|
||||
(target_id,),
|
||||
)
|
||||
target_cat_map = {row[0]: row[1] for row in cursor.fetchall()}
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
target_cat_map = cat_map
|
||||
|
||||
address = target_mdl.get("Address", 1)
|
||||
is_pass = (target_cat_map.get(2, 0) == 1)
|
||||
tipo_acceso = target_cat_map.get(15) or cat_map.get(15, 3)
|
||||
|
||||
if is_pass:
|
||||
if tipo_acceso == 1:
|
||||
payload = "C4"
|
||||
elif tipo_acceso in (2, 7):
|
||||
payload = "C2"
|
||||
elif tipo_acceso in (3, 4):
|
||||
payload = "C1"
|
||||
elif tipo_acceso == 6:
|
||||
payload = "C0"
|
||||
else:
|
||||
payload = "C3"
|
||||
else:
|
||||
if tipo_acceso == 1:
|
||||
payload = "C6"
|
||||
elif tipo_acceso in (2, 7):
|
||||
payload = "C5"
|
||||
elif tipo_acceso in (3, 4):
|
||||
payload = "C1"
|
||||
elif tipo_acceso == 6:
|
||||
payload = "C0"
|
||||
else:
|
||||
payload = "C3"
|
||||
|
||||
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, (target_id, trama_comando, extra_info))
|
||||
if target_id != modulo_id:
|
||||
cursor.execute(sql_insert, (modulo_id, trama_comando, extra_info))
|
||||
|
||||
latencia = (time.perf_counter() - t_start) * 1000
|
||||
|
||||
return True, {
|
||||
"modulo_id": modulo_id,
|
||||
"modulo_solicitado": modulo_id,
|
||||
"modulo_fisico_target": target_id,
|
||||
"address": address,
|
||||
"address_fisico": address,
|
||||
"tipo_acceso": tipo_acceso,
|
||||
"is_pass": is_pass,
|
||||
"payload": payload,
|
||||
"comando_trama": trama_comando,
|
||||
"latencia_ms": round(latencia, 2),
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user