feat(access): paridad funcional de verificacion peaton vs conductor y pulsos a barrera/molinete segun desktop pct_view
This commit is contained in:
@@ -30,7 +30,22 @@ class WorkstationRepository:
|
||||
m.GrupoModulos,
|
||||
m.ModuloEntradaID,
|
||||
m.ModuloSalidaID,
|
||||
m.duracion_pulso
|
||||
m.duracion_pulso,
|
||||
COALESCE(
|
||||
(SELECT ValorID FROM MdlCatVal WHERE ModuloID = m.ModuloID AND CategoriaID = 15),
|
||||
(SELECT ValorID FROM MdlCatVal WHERE ModuloID = m.ModuloEntradaID AND CategoriaID = 15),
|
||||
(SELECT ValorID FROM MdlCatVal WHERE ModuloID = m.ModuloSalidaID AND CategoriaID = 15),
|
||||
3
|
||||
) AS tipo_acceso_id,
|
||||
COALESCE(
|
||||
(SELECT Nombre FROM CatVal cv WHERE cv.CategoriaID = 15 AND cv.ValorID = COALESCE(
|
||||
(SELECT ValorID FROM MdlCatVal WHERE ModuloID = m.ModuloID AND CategoriaID = 15),
|
||||
(SELECT ValorID FROM MdlCatVal WHERE ModuloID = m.ModuloEntradaID AND CategoriaID = 15),
|
||||
(SELECT ValorID FROM MdlCatVal WHERE ModuloID = m.ModuloSalidaID AND CategoriaID = 15),
|
||||
3
|
||||
)),
|
||||
'Barrera'
|
||||
) AS tipo_acceso_nombre
|
||||
FROM wksmdl wm
|
||||
JOIN mdl m ON wm.ModuloID = m.ModuloID
|
||||
WHERE wm.WorkstationID = %s
|
||||
|
||||
@@ -110,6 +110,7 @@ class ExitRequest(BaseModel):
|
||||
rol_salida: Optional[int] = 1
|
||||
entidad_salida: Optional[str] = None
|
||||
patente_salida: Optional[str] = None
|
||||
tipo_salida: Optional[str] = Field(None, description="CONDUCTOR o PEATON")
|
||||
abrir_barrera: bool = True
|
||||
personas_ids_permanecen: List[int] = Field(default_factory=list)
|
||||
integrantes_verificados: List[CompanionDTO] = Field(default_factory=list)
|
||||
|
||||
@@ -15,6 +15,9 @@ class LaneModuleDTO(BaseModel):
|
||||
duracion_pulso: Optional[int] = None
|
||||
modulo_id: Optional[int] = None
|
||||
nombre: Optional[str] = None
|
||||
tipo_acceso_id: Optional[int] = 3
|
||||
tipo_acceso_nombre: Optional[str] = "Barrera"
|
||||
es_acceso_peatonal: Optional[bool] = False
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
|
||||
@@ -139,17 +139,31 @@ class AccessService:
|
||||
# 10. Registro transaccional en base de datos
|
||||
AccessRepository.registrar_ticket_ingreso(req, persona_id, ticket_id)
|
||||
|
||||
# 11. Apertura física de barrera vía pdtmdl
|
||||
# 11. Apertura física de barrera o molinete vía pdtmdl (Regla de escritorio pct_view.py:2861-2868)
|
||||
# Si es Peatón: NO debe enviar pulso a barrera vehicular. Pero si el acceso está configurado como
|
||||
# Puerta (1), Molinete (2) o Molinete Club (7), SÍ debe enviar el pulso para destrabar el paso peatonal.
|
||||
tipo_acc_mod = HardwareService.obtener_tipo_acceso(req.modulo_ingreso_id)
|
||||
es_acceso_peatonal = tipo_acc_mod in (1, 2, 7)
|
||||
es_conductor = req.tipo_ingreso.upper() == "CONDUCTOR"
|
||||
debe_abrir = es_conductor or es_acceso_peatonal
|
||||
|
||||
barrier_opened = False
|
||||
if req.abrir_barrera and req.modulo_ingreso_id:
|
||||
if req.abrir_barrera and req.modulo_ingreso_id and debe_abrir:
|
||||
ok, _ = HardwareService.encolar_apertura(req.modulo_ingreso_id, ticket_id)
|
||||
barrier_opened = ok
|
||||
|
||||
ahora = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
if es_conductor:
|
||||
msg = "Ingreso autorizado y registrado correctamente"
|
||||
elif es_acceso_peatonal:
|
||||
msg = "Ingreso peatonal registrado. Molinete/puerta habilitado."
|
||||
else:
|
||||
msg = "Ingreso peatonal registrado correctamente (barrera vehicular no accionada)."
|
||||
|
||||
return TicketResponse(
|
||||
status="ok",
|
||||
ticket_id=ticket_id,
|
||||
message="Ingreso autorizado y registrado correctamente",
|
||||
message=msg,
|
||||
barrier_opened=barrier_opened,
|
||||
fecha_hora=ahora,
|
||||
)
|
||||
@@ -161,7 +175,7 @@ class AccessService:
|
||||
1. Valida existencia del ticket en tck.
|
||||
2. Desacopla personas que permanecen a tickets peatonales independientes.
|
||||
3. Mueve a tckhst y mvthist, liberando el ticket de tck.
|
||||
4. Encola la apertura de barrera en pdtmdl si corresponde.
|
||||
4. Encola la apertura de barrera/molinete en pdtmdl si corresponde (pct_view.py:3088-3093).
|
||||
"""
|
||||
ok = AccessRepository.registrar_ticket_salida(
|
||||
ticket_id=req.ticket_id,
|
||||
@@ -177,16 +191,33 @@ class AccessService:
|
||||
detail=f"Ticket activo {req.ticket_id} no encontrado o ya fue egresado.",
|
||||
)
|
||||
|
||||
# Accionamiento de hardware para Salida (Regla de escritorio pct_view.py:3088-3093)
|
||||
# Para Molinete y Puerta (peatonal), siempre abrir; para barreras solo si es Conductor / Vehicular.
|
||||
tipo_acc_sal = HardwareService.obtener_tipo_acceso(req.modulo_salida_id)
|
||||
es_acceso_peatonal_sal = tipo_acc_sal in (1, 2, 7)
|
||||
if req.tipo_salida:
|
||||
es_conductor_sal = req.tipo_salida.upper() == "CONDUCTOR"
|
||||
else:
|
||||
es_conductor_sal = bool(req.patente_salida and req.patente_salida.strip())
|
||||
debe_abrir_sal = es_conductor_sal or es_acceso_peatonal_sal
|
||||
|
||||
barrier_opened = False
|
||||
if req.abrir_barrera and req.modulo_salida_id:
|
||||
if req.abrir_barrera and req.modulo_salida_id and debe_abrir_sal:
|
||||
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")
|
||||
if es_conductor_sal:
|
||||
salida_msg = "Salida registrada exitosamente"
|
||||
elif es_acceso_peatonal_sal:
|
||||
salida_msg = "Salida peatonal registrada. Molinete/puerta habilitado."
|
||||
else:
|
||||
salida_msg = "Salida peatonal registrada exitosamente (barrera vehicular no accionada)."
|
||||
|
||||
return TicketResponse(
|
||||
status="ok",
|
||||
ticket_id=req.ticket_id,
|
||||
message="Salida registrada exitosamente",
|
||||
message=salida_msg,
|
||||
barrier_opened=barrier_opened,
|
||||
fecha_hora=ahora,
|
||||
)
|
||||
|
||||
@@ -42,6 +42,77 @@ class HardwareService:
|
||||
cursor.execute(query, (modulo_id,))
|
||||
return cursor.fetchone()
|
||||
|
||||
@classmethod
|
||||
def obtener_tipo_acceso(cls, modulo_id: int) -> int:
|
||||
"""
|
||||
Obtiene el tipo_acceso_id (CategoriaID = 15 de MdlCatVal) resolviendo si
|
||||
es un módulo virtual hacia su módulo físico asociado (ModuloEntradaID o ModuloSalidaID).
|
||||
Valores estándar de CatVal (Cat 15):
|
||||
1: Puerta
|
||||
2: Molinete
|
||||
7: Molinete Club
|
||||
3: Barrera de Estado
|
||||
4: Controlado
|
||||
5: Barrera Pulso
|
||||
6: Barrera Doble Pulso
|
||||
"""
|
||||
if not modulo_id:
|
||||
return 0
|
||||
|
||||
mdl = cls.obtener_info_modulo(modulo_id)
|
||||
if not mdl:
|
||||
return 0
|
||||
|
||||
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
|
||||
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"]
|
||||
|
||||
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
|
||||
|
||||
tipo_acceso = target_cat_map.get(15) or cat_map.get(15, 3)
|
||||
return int(tipo_acceso)
|
||||
|
||||
@classmethod
|
||||
def es_acceso_peatonal(cls, modulo_id: int) -> bool:
|
||||
"""
|
||||
Devuelve True si el acceso está configurado como Puerta (1), Molinete (2) o Molinete Club (7).
|
||||
Idéntico a pct_view.py:2862 (`tipo_acc_mod in (1, 2, 7)`).
|
||||
"""
|
||||
tipo_acceso = cls.obtener_tipo_acceso(modulo_id)
|
||||
return tipo_acceso in (1, 2, 7)
|
||||
|
||||
@classmethod
|
||||
def encolar_apertura(
|
||||
cls, modulo_id: int, ticket_id: int = 0, sin_ticket: bool = False
|
||||
|
||||
@@ -40,6 +40,8 @@ class WorkstationService:
|
||||
es_entrada = True
|
||||
else:
|
||||
es_entrada = not bool(m.get("ModuloEntradaID"))
|
||||
tipo_acc = int(m.get("tipo_acceso_id") or 3)
|
||||
es_peatonal = tipo_acc in (1, 2, 7)
|
||||
dto = LaneModuleDTO(
|
||||
id=m["ModuloID"],
|
||||
name=nom,
|
||||
@@ -48,6 +50,9 @@ class WorkstationService:
|
||||
grupo_modulos=m.get("GrupoModulos"),
|
||||
es_entrada=es_entrada,
|
||||
duracion_pulso=m.get("duracion_pulso"),
|
||||
tipo_acceso_id=tipo_acc,
|
||||
tipo_acceso_nombre=m.get("tipo_acceso_nombre") or ("Molinete/Puerta" if es_peatonal else "Barrera"),
|
||||
es_acceso_peatonal=es_peatonal,
|
||||
)
|
||||
if es_entrada:
|
||||
entry_modules.append(dto)
|
||||
|
||||
@@ -365,3 +365,123 @@ async def test_validations_and_policies():
|
||||
assert "art" in res_art_vencida.json()["detail"].lower()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_verificaciones_peaton_vs_conductor_hardware_pulse(monkeypatch):
|
||||
"""
|
||||
Verifica la regla de negocio de escritorio (pct_view.py:2861-2868 y 3088-3093):
|
||||
1. Si es Peatón y el módulo es Barrera Vehicular (tipo_acceso=3 o 5):
|
||||
NO se envía pulso de apertura (barrier_opened == False).
|
||||
2. Si es Peatón y el módulo es Molinete o Puerta (tipo_acceso in (1, 2, 7)):
|
||||
SÍ se envía pulso de apertura (barrier_opened == True).
|
||||
3. Si es Conductor:
|
||||
SÍ se envía pulso de apertura independientemente del tipo de acceso (barrier_opened == True).
|
||||
"""
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
login_res = await client.post(
|
||||
"/api/v1/auth/login",
|
||||
json={"username": "guardia", "password": "guardia"},
|
||||
)
|
||||
token = login_res.cookies.get("access_token")
|
||||
|
||||
from app.services.hardware_service import HardwareService
|
||||
|
||||
# Caso 1: Peatón en Molinete Club (100004 -> tipo_acceso=7)
|
||||
res_peaton_molinete = await client.post(
|
||||
"/api/v1/access/entry",
|
||||
json={
|
||||
"modulo_ingreso_id": 100004,
|
||||
"documento": "88771122",
|
||||
"nombre": "PEATON MOLINETE",
|
||||
"lote_codigo": "100",
|
||||
"tipo_ingreso": "PEATON",
|
||||
"abrir_barrera": True,
|
||||
},
|
||||
cookies={"access_token": token},
|
||||
)
|
||||
assert res_peaton_molinete.status_code == 200
|
||||
data_molinete = res_peaton_molinete.json()
|
||||
assert data_molinete["barrier_opened"] is True
|
||||
assert "molinete" in data_molinete["message"].lower() or "habilitado" in data_molinete["message"].lower()
|
||||
|
||||
# Egresar para no dejar ticket bloqueante
|
||||
await client.post(
|
||||
"/api/v1/access/exit",
|
||||
json={
|
||||
"ticket_id": data_molinete["ticket_id"],
|
||||
"modulo_salida_id": 100005,
|
||||
"tipo_salida": "PEATON",
|
||||
"abrir_barrera": True,
|
||||
},
|
||||
cookies={"access_token": token},
|
||||
)
|
||||
|
||||
# Caso 2: Peatón en Barrera Vehicular (simulamos módulo tipo_acceso = 3: Barrera Estado)
|
||||
monkeypatch.setattr(HardwareService, "obtener_tipo_acceso", lambda mod_id: 3)
|
||||
res_peaton_barrera = await client.post(
|
||||
"/api/v1/access/entry",
|
||||
json={
|
||||
"modulo_ingreso_id": 100004,
|
||||
"documento": "88771133",
|
||||
"nombre": "PEATON BARRERA",
|
||||
"lote_codigo": "100",
|
||||
"tipo_ingreso": "PEATON",
|
||||
"abrir_barrera": True,
|
||||
},
|
||||
cookies={"access_token": token},
|
||||
)
|
||||
assert res_peaton_barrera.status_code == 200
|
||||
data_barrera = res_peaton_barrera.json()
|
||||
# Regla clave: NO DEBE ABRIR LA BARRERA VEHICULAR A UN PEATÓN
|
||||
assert data_barrera["barrier_opened"] is False
|
||||
assert "no accionada" in data_barrera["message"].lower()
|
||||
|
||||
# Caso 3: Salida Peatón en Barrera Vehicular -> Tampoco acciona barrera
|
||||
exit_res_barrera = await client.post(
|
||||
"/api/v1/access/exit",
|
||||
json={
|
||||
"ticket_id": data_barrera["ticket_id"],
|
||||
"modulo_salida_id": 100005,
|
||||
"tipo_salida": "PEATON",
|
||||
"abrir_barrera": True,
|
||||
},
|
||||
cookies={"access_token": token},
|
||||
)
|
||||
assert exit_res_barrera.status_code == 200
|
||||
assert exit_res_barrera.json()["barrier_opened"] is False
|
||||
|
||||
# Caso 4: Conductor en Barrera Vehicular -> SÍ acciona barrera
|
||||
res_conductor = await client.post(
|
||||
"/api/v1/access/entry",
|
||||
json={
|
||||
"modulo_ingreso_id": 100004,
|
||||
"documento": "88771144",
|
||||
"nombre": "CONDUCTOR BARRERA",
|
||||
"lote_codigo": "100",
|
||||
"tipo_ingreso": "CONDUCTOR",
|
||||
"patente": "ABC789",
|
||||
"abrir_barrera": True,
|
||||
},
|
||||
cookies={"access_token": token},
|
||||
)
|
||||
assert res_conductor.status_code == 200
|
||||
data_cond = res_conductor.json()
|
||||
assert data_cond["barrier_opened"] is True
|
||||
|
||||
# Salida Conductor -> SÍ acciona barrera
|
||||
exit_cond = await client.post(
|
||||
"/api/v1/access/exit",
|
||||
json={
|
||||
"ticket_id": data_cond["ticket_id"],
|
||||
"modulo_salida_id": 100005,
|
||||
"patente_salida": "ABC789",
|
||||
"tipo_salida": "CONDUCTOR",
|
||||
"abrir_barrera": True,
|
||||
},
|
||||
cookies={"access_token": token},
|
||||
)
|
||||
assert exit_cond.status_code == 200
|
||||
assert exit_cond.json()["barrier_opened"] is True
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -26,3 +26,18 @@ def test_encolar_apertura_virtual_module_molinete_club():
|
||||
assert res["payload"] == "O5"
|
||||
assert res["comando_trama"] == "\x0220O518\x03"
|
||||
assert res["trama_ticket"] == "\x0220T90F\x03"
|
||||
|
||||
|
||||
def test_obtener_tipo_acceso_y_es_acceso_peatonal():
|
||||
"""
|
||||
Verifica que:
|
||||
1. Modulo 100004 sea detectado como Molinete Club (7) -> es_acceso_peatonal True.
|
||||
2. Modulo inexistente o 0 retorne 0 -> es_acceso_peatonal False.
|
||||
"""
|
||||
tipo_acc = HardwareService.obtener_tipo_acceso(100004)
|
||||
assert tipo_acc == 7
|
||||
assert HardwareService.es_acceso_peatonal(100004) is True
|
||||
|
||||
assert HardwareService.obtener_tipo_acceso(0) == 0
|
||||
assert HardwareService.es_acceso_peatonal(0) is False
|
||||
|
||||
|
||||
Reference in New Issue
Block a user