fix(camera-parity-pwa): resolver parpadeo de camara, paridad funcional de acompanantes, lotes, egreso y PWA responsive
This commit is contained in:
@@ -11,6 +11,8 @@ from app.schemas.access_schema import (
|
|||||||
ActiveTicketDTO,
|
ActiveTicketDTO,
|
||||||
PersonSearchDTO,
|
PersonSearchDTO,
|
||||||
LotSearchDTO,
|
LotSearchDTO,
|
||||||
|
LotPermissionDTO,
|
||||||
|
TicketOccupantDTO,
|
||||||
)
|
)
|
||||||
from app.services.access_service import AccessService
|
from app.services.access_service import AccessService
|
||||||
from app.services.dni_parser_service import DNIParsingService, DNIParsedResult
|
from app.services.dni_parser_service import DNIParsingService, DNIParsedResult
|
||||||
@@ -105,3 +107,23 @@ def parsear_codigo_dni(
|
|||||||
detail="No se pudo interpretar el formato del código escaneado.",
|
detail="No se pudo interpretar el formato del código escaneado.",
|
||||||
)
|
)
|
||||||
return res
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/lots/{lote_id}/permission", response_model=LotPermissionDTO, summary="Validar estado y permisos de lote")
|
||||||
|
|
||||||
|
def validar_permiso_lote(
|
||||||
|
lote_id: int,
|
||||||
|
persona_id: int = Query(0, description="ID opcional de la persona a validar con el lote"),
|
||||||
|
current_user: dict = Depends(obtener_usuario_actual),
|
||||||
|
):
|
||||||
|
"""Consulta estado del lote (Cat 26) y relación de persona (LotPer)."""
|
||||||
|
return AccessService.obtener_permiso_lote(lote_id, persona_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/tickets/{ticket_id}/occupants", response_model=List[TicketOccupantDTO], summary="Listar ocupantes de un ticket")
|
||||||
|
def listar_ocupantes_ticket(
|
||||||
|
ticket_id: int,
|
||||||
|
current_user: dict = Depends(obtener_usuario_actual),
|
||||||
|
):
|
||||||
|
"""Retorna todos los integrantes que ingresaron en el vehículo correspondiente a este ticket."""
|
||||||
|
return AccessService.obtener_ocupantes_ticket(ticket_id)
|
||||||
|
|||||||
@@ -178,52 +178,237 @@ class AccessRepository:
|
|||||||
|
|
||||||
return ticket_id
|
return ticket_id
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def obtener_permiso_lote(lote_id: int, persona_id: int = 0) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Verifica restricciones del lote en LotCatVal (Categoría 26) y relación de la persona en LotPer.
|
||||||
|
Idéntico a pct_repository.py en OnEverAccess de escritorio.
|
||||||
|
"""
|
||||||
|
resultado = {
|
||||||
|
"estado": "Habilitado",
|
||||||
|
"color": "#155724",
|
||||||
|
"bg_color": "#d4edda",
|
||||||
|
"detalle": "Lote Habilitado",
|
||||||
|
"es_residente": False,
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
with db_session() as conn:
|
||||||
|
cursor = conn.cursor(as_dict=True)
|
||||||
|
|
||||||
|
# 1. Chequear estado del lote en LotCatVal (Categoría 26)
|
||||||
|
sql_lot = """
|
||||||
|
SELECT c.Nombre AS Categoria
|
||||||
|
FROM LotCatVal lc
|
||||||
|
JOIN CatVal c ON lc.CategoriaID = c.CategoriaID AND lc.ValorID = c.ValorID
|
||||||
|
WHERE lc.LoteID = %s AND lc.CategoriaID = 26
|
||||||
|
"""
|
||||||
|
cursor.execute(sql_lot, (lote_id,))
|
||||||
|
row_cat = cursor.fetchone()
|
||||||
|
if row_cat and row_cat.get("Categoria"):
|
||||||
|
cat_nombre = str(row_cat["Categoria"]).strip()
|
||||||
|
cat_lower = cat_nombre.lower()
|
||||||
|
if any(k in cat_lower for k in ["moroso", "restringido", "bloqueado", "deuda", "inhabilitado"]):
|
||||||
|
resultado["estado"] = "Restringido"
|
||||||
|
resultado["color"] = "#721c24"
|
||||||
|
resultado["bg_color"] = "#f8d7da"
|
||||||
|
resultado["detalle"] = f"Lote con Restricción ({cat_nombre})"
|
||||||
|
elif any(k in cat_lower for k in ["obra", "construc"]):
|
||||||
|
resultado["estado"] = "En Obra"
|
||||||
|
resultado["color"] = "#856404"
|
||||||
|
resultado["bg_color"] = "#fff3cd"
|
||||||
|
resultado["detalle"] = f"Lote en Obra ({cat_nombre})"
|
||||||
|
else:
|
||||||
|
resultado["detalle"] = f"Lote {cat_nombre}"
|
||||||
|
|
||||||
|
# 2. Si se especificó persona, verificar si es residente o autorizado
|
||||||
|
if persona_id > 0:
|
||||||
|
sql_per = """
|
||||||
|
SELECT lp.FechaInicio, lp.FechaFin, pr.Nombre AS Perfil, c.Nombre AS EstadoRel
|
||||||
|
FROM LotPer lp
|
||||||
|
LEFT JOIN Prf pr ON lp.PerfilID = pr.PerfilID
|
||||||
|
LEFT JOIN CatVal c ON lp.ValorID = c.ValorID AND c.CategoriaID = 18
|
||||||
|
WHERE lp.LoteID = %s AND lp.PersonaID = %s
|
||||||
|
"""
|
||||||
|
cursor.execute(sql_per, (lote_id, persona_id))
|
||||||
|
row_lp = cursor.fetchone()
|
||||||
|
if row_lp:
|
||||||
|
resultado["es_residente"] = True
|
||||||
|
f_fin = row_lp.get("FechaFin")
|
||||||
|
ahora = datetime.now()
|
||||||
|
if f_fin and f_fin < ahora:
|
||||||
|
resultado["detalle"] += f" · Permiso Vencido ({f_fin.strftime('%d/%m/%Y')})"
|
||||||
|
resultado["color"] = "#856404"
|
||||||
|
resultado["bg_color"] = "#fff3cd"
|
||||||
|
else:
|
||||||
|
perfil = row_lp.get("Perfil") or "Residente"
|
||||||
|
resultado["detalle"] += f" · {perfil}"
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error al verificar permiso del lote {lote_id}: {e}")
|
||||||
|
return resultado
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def obtener_ocupantes_ticket(ticket_id: int) -> List[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
Retorna la lista de ocupantes (titular + acompañantes) vinculados a un ticket en tckper.
|
||||||
|
"""
|
||||||
|
ocupantes = []
|
||||||
|
try:
|
||||||
|
with db_session() as conn:
|
||||||
|
cursor = conn.cursor(as_dict=True)
|
||||||
|
sql = """
|
||||||
|
SELECT tp.PersonaID,
|
||||||
|
COALESCE(p.Apellido, '') AS Apellido,
|
||||||
|
COALESCE(p.Nombre, '') AS Nombre,
|
||||||
|
COALESCE(pd.Documento, '') AS Documento,
|
||||||
|
COALESCE(tp.RolID, 2) AS RolID,
|
||||||
|
COALESCE(tp.EsMenor, 0) AS EsMenor
|
||||||
|
FROM tckper tp
|
||||||
|
LEFT JOIN Per p ON tp.PersonaID = p.PersonaID
|
||||||
|
LEFT JOIN PerDocCatVal pd ON p.PersonaID = pd.PersonaID AND pd.DocumentoID = 100000
|
||||||
|
WHERE tp.TicketID = %s
|
||||||
|
ORDER BY tp.RolID ASC, tp.PersonaID ASC
|
||||||
|
"""
|
||||||
|
cursor.execute(sql, (ticket_id,))
|
||||||
|
rows = cursor.fetchall()
|
||||||
|
for r in rows:
|
||||||
|
es_menor = bool(r.get("EsMenor") or r.get("RolID") == 3)
|
||||||
|
rol_id = int(r.get("RolID") or 2)
|
||||||
|
rol_nom = "Conductor" if rol_id == 1 else ("Menor de Edad" if es_menor else "Acompañante")
|
||||||
|
ocupantes.append({
|
||||||
|
"persona_id": int(r.get("PersonaID") or 0),
|
||||||
|
"documento": str(r.get("Documento") or ""),
|
||||||
|
"apellido": str(r.get("Apellido") or "").strip(),
|
||||||
|
"nombre": str(r.get("Nombre") or "").strip(),
|
||||||
|
"rol_id": rol_id,
|
||||||
|
"es_menor": es_menor,
|
||||||
|
"rol_nombre": rol_nom,
|
||||||
|
})
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error al obtener ocupantes de ticket {ticket_id}: {e}")
|
||||||
|
return ocupantes
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def desacoplar_acompanantes_a_peaton(ticket_id: int, personas_ids: List[int], modulo_id: int) -> bool:
|
||||||
|
"""
|
||||||
|
Desacopla acompañantes que permanecen en el predio a tickets peatonales individuales.
|
||||||
|
"""
|
||||||
|
if not personas_ids:
|
||||||
|
return True
|
||||||
|
ahora = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
try:
|
||||||
|
with db_session() as conn:
|
||||||
|
cursor = conn.cursor(as_dict=True)
|
||||||
|
|
||||||
|
# Obtener lote y entidad del ticket padre
|
||||||
|
cursor.execute("SELECT PropiedadID, Valor FROM tckprx WHERE TicketID = %s", (ticket_id,))
|
||||||
|
prx_rows = cursor.fetchall()
|
||||||
|
lote_val = None
|
||||||
|
entidad_val = None
|
||||||
|
for prx in prx_rows:
|
||||||
|
if prx.get("PropiedadID") == 7:
|
||||||
|
lote_val = prx.get("Valor")
|
||||||
|
elif prx.get("PropiedadID") == 11:
|
||||||
|
entidad_val = prx.get("Valor")
|
||||||
|
|
||||||
|
for pid in personas_ids:
|
||||||
|
# Desasociar del ticket del vehículo
|
||||||
|
cursor.execute("DELETE FROM tckper WHERE TicketID = %s AND PersonaID = %s", (ticket_id, pid))
|
||||||
|
|
||||||
|
# Generar ticket peatonal individual
|
||||||
|
cursor.execute("SELECT COALESCE(MAX(TicketID), 0) + 1 AS NextTid FROM tck")
|
||||||
|
nuevo_tid = cursor.fetchone()["NextTid"]
|
||||||
|
cursor.execute("SELECT COALESCE(MAX(Numero), 0) + 1 AS NextNro FROM tck")
|
||||||
|
nuevo_nro = cursor.fetchone()["NextNro"]
|
||||||
|
|
||||||
|
cursor.execute(
|
||||||
|
"INSERT INTO tck (TicketID, Numero, FechaHoraIngreso, ModuloIngresoID) VALUES (%s, %s, %s, %s)",
|
||||||
|
(nuevo_tid, nuevo_nro, ahora, modulo_id or 0),
|
||||||
|
)
|
||||||
|
cursor.execute(
|
||||||
|
"INSERT INTO tckper (TicketID, PersonaID, RolID, EsMenor) VALUES (%s, %s, 2, 0)",
|
||||||
|
(nuevo_tid, pid),
|
||||||
|
)
|
||||||
|
if lote_val:
|
||||||
|
cursor.execute("INSERT INTO tckprx (TicketID, PropiedadID, Valor) VALUES (%s, 7, %s)", (nuevo_tid, str(lote_val)))
|
||||||
|
if entidad_val:
|
||||||
|
cursor.execute("INSERT INTO tckprx (TicketID, PropiedadID, Valor) VALUES (%s, 11, %s)", (nuevo_tid, str(entidad_val)))
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error al desacoplar acompañantes a peatón: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def registrar_ticket_salida(
|
def registrar_ticket_salida(
|
||||||
ticket_id: int, modulo_salida_id: int, persona_id: int = 0, patente: str = ""
|
ticket_id: int,
|
||||||
|
modulo_salida_id: int,
|
||||||
|
persona_id: int = 0,
|
||||||
|
patente: str = "",
|
||||||
|
personas_ids_permanecen: Optional[List[int]] = None,
|
||||||
|
integrantes_verificados: Optional[List[Any]] = None,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""
|
"""
|
||||||
Cierra un ticket activo moviéndolo a `tckhst`, registrando el egreso en `mvthist`
|
Cierra un ticket activo moviéndolo a `tckhst`, registrando el egreso en `mvthist`
|
||||||
y liberando los registros de `tck` y `tckper`.
|
para todos los que salen, desacoplando acompañantes que permanecen, y liberando el ticket de `tck`.
|
||||||
"""
|
"""
|
||||||
ahora = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
ahora = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
|
||||||
|
# 1. Desacoplar acompañantes que permanecen
|
||||||
|
if personas_ids_permanecen:
|
||||||
|
AccessRepository.desacoplar_acompanantes_a_peaton(ticket_id, personas_ids_permanecen, modulo_salida_id)
|
||||||
|
|
||||||
with db_session() as conn:
|
with db_session() as conn:
|
||||||
cursor = conn.cursor(as_dict=True)
|
cursor = conn.cursor(as_dict=True)
|
||||||
|
|
||||||
# Leer datos de ingreso
|
# Leer datos de ingreso
|
||||||
cursor.execute("SELECT FechaHoraIngreso, ModuloIngresoID FROM tck WHERE TicketID = %s", (ticket_id,))
|
cursor.execute("SELECT Numero, FechaHoraIngreso, ModuloIngresoID FROM tck WHERE TicketID = %s", (ticket_id,))
|
||||||
tck_row = cursor.fetchone()
|
tck_row = cursor.fetchone()
|
||||||
if not tck_row:
|
if not tck_row:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
f_ing = str(tck_row["FechaHoraIngreso"])
|
f_ing = str(tck_row["FechaHoraIngreso"])
|
||||||
|
nro_tck = tck_row.get("Numero") or 0
|
||||||
mod_ing = tck_row.get("ModuloIngresoID") or 0
|
mod_ing = tck_row.get("ModuloIngresoID") or 0
|
||||||
|
|
||||||
# 1. Insertar en tckhst (histórico de tickets)
|
# 2. Insertar en tckhst (histórico de tickets)
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO tckhst (TicketID, Numero, FechaHoraIngreso, ModuloIngresoID, FechaHoraSalida, ModuloSalidaID)
|
INSERT INTO tckhst (TicketID, Numero, FechaHoraIngreso, ModuloIngresoID, FechaHoraSalida, ModuloSalidaID)
|
||||||
VALUES (%s, 0, %s, %s, %s, %s)
|
VALUES (%s, %s, %s, %s, %s, %s)
|
||||||
""",
|
""",
|
||||||
(ticket_id, f_ing, mod_ing, ahora, modulo_salida_id),
|
(ticket_id, nro_tck, f_ing, mod_ing, ahora, modulo_salida_id),
|
||||||
)
|
)
|
||||||
|
|
||||||
# 2. Registrar en mvthist
|
# 3. Registrar en mvthist para todos los que egresan con este ticket
|
||||||
try:
|
try:
|
||||||
|
# Ocupantes en tckper para este ticket
|
||||||
|
cursor.execute("""
|
||||||
|
SELECT tp.PersonaID, tp.RolID, tp.EsMenor,
|
||||||
|
(SELECT TOP 1 Valor FROM tckprx WHERE TicketID = tp.TicketID AND PropiedadID = 4) AS Patente,
|
||||||
|
(SELECT TOP 1 Valor FROM tckprx WHERE TicketID = tp.TicketID AND PropiedadID = 7) AS LoteID,
|
||||||
|
(SELECT TOP 1 Valor FROM tckprx WHERE TicketID = tp.TicketID AND PropiedadID = 11) AS Entidad
|
||||||
|
FROM tckper tp
|
||||||
|
WHERE tp.TicketID = %s
|
||||||
|
""", (ticket_id,))
|
||||||
|
ocupantes_salida = cursor.fetchall()
|
||||||
|
|
||||||
|
for oc in ocupantes_salida:
|
||||||
|
oc_pid = oc.get("PersonaID")
|
||||||
|
oc_pat = patente or oc.get("Patente") or None
|
||||||
|
oc_lote = oc.get("LoteID") or None
|
||||||
|
oc_rol = oc.get("RolID") or 1
|
||||||
|
oc_ent = oc.get("Entidad") or "EGRESO..."
|
||||||
|
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO mvthist (TicketID, PersonaID, Patente, RolID, Entidad, Sentido, ModuloID, FechaHora)
|
INSERT INTO mvthist (TicketID, PersonaID, Patente, LoteID, RolID, Entidad, Sentido, ModuloID, FechaHora)
|
||||||
VALUES (%s, %s, %s, 1, 'EGRESO...', 'Salida', %s, %s)
|
VALUES (%s, %s, %s, %s, %s, %s, 'Salida', %s, %s)
|
||||||
""",
|
""",
|
||||||
(ticket_id, persona_id or None, patente or None, modulo_salida_id, ahora),
|
(ticket_id, oc_pid, oc_pat, oc_lote, oc_rol, oc_ent, modulo_salida_id, ahora),
|
||||||
)
|
)
|
||||||
except Exception:
|
except Exception as e:
|
||||||
pass
|
print(f"Aviso registrando mvthist salida: {e}")
|
||||||
|
|
||||||
# 3. Eliminar de tablas vivas
|
# 4. Eliminar de tck (manteniendo tckper y tckprx para coherencia histórica con tckhst)
|
||||||
cursor.execute("DELETE FROM tckper WHERE TicketID = %s", (ticket_id,))
|
|
||||||
cursor.execute("DELETE FROM tckprx WHERE TicketID = %s", (ticket_id,))
|
|
||||||
cursor.execute("DELETE FROM tck WHERE TicketID = %s", (ticket_id,))
|
cursor.execute("DELETE FROM tck WHERE TicketID = %s", (ticket_id,))
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|||||||
@@ -34,6 +34,24 @@ class EntryRequest(BaseModel):
|
|||||||
integrantes: List[CompanionDTO] = Field(default_factory=list)
|
integrantes: List[CompanionDTO] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
class LotPermissionDTO(BaseModel):
|
||||||
|
estado: str = "Habilitado"
|
||||||
|
color: str = "#155724"
|
||||||
|
bg_color: str = "#d4edda"
|
||||||
|
detalle: str = "Lote Habilitado"
|
||||||
|
es_residente: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class TicketOccupantDTO(BaseModel):
|
||||||
|
persona_id: int
|
||||||
|
documento: str
|
||||||
|
apellido: str
|
||||||
|
nombre: str
|
||||||
|
rol_id: int = 2
|
||||||
|
es_menor: bool = False
|
||||||
|
rol_nombre: str = "Acompañante"
|
||||||
|
|
||||||
|
|
||||||
class ExitRequest(BaseModel):
|
class ExitRequest(BaseModel):
|
||||||
ticket_id: int = Field(..., description="ID del ticket activo a cerrar")
|
ticket_id: int = Field(..., description="ID del ticket activo a cerrar")
|
||||||
modulo_salida_id: int = Field(..., description="ID del módulo / barrera de salida")
|
modulo_salida_id: int = Field(..., description="ID del módulo / barrera de salida")
|
||||||
@@ -43,6 +61,8 @@ class ExitRequest(BaseModel):
|
|||||||
patente_salida: Optional[str] = None
|
patente_salida: Optional[str] = None
|
||||||
abrir_barrera: bool = True
|
abrir_barrera: bool = True
|
||||||
personas_ids_permanecen: List[int] = Field(default_factory=list)
|
personas_ids_permanecen: List[int] = Field(default_factory=list)
|
||||||
|
integrantes_verificados: List[CompanionDTO] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class TicketResponse(BaseModel):
|
class TicketResponse(BaseModel):
|
||||||
|
|||||||
@@ -71,14 +71,17 @@ class AccessService:
|
|||||||
"""
|
"""
|
||||||
Ejecuta la regla de negocio para registrar la salida:
|
Ejecuta la regla de negocio para registrar la salida:
|
||||||
1. Valida existencia del ticket en tck.
|
1. Valida existencia del ticket en tck.
|
||||||
2. Mueve a tckhst y mvthist, liberando tckper y tck.
|
2. Desacopla personas que permanecen a tickets peatonales independientes.
|
||||||
3. Encola la apertura de barrera en pdtmdl si corresponde.
|
3. Mueve a tckhst y mvthist, liberando el ticket de tck.
|
||||||
|
4. Encola la apertura de barrera en pdtmdl si corresponde.
|
||||||
"""
|
"""
|
||||||
ok = AccessRepository.registrar_ticket_salida(
|
ok = AccessRepository.registrar_ticket_salida(
|
||||||
ticket_id=req.ticket_id,
|
ticket_id=req.ticket_id,
|
||||||
modulo_salida_id=req.modulo_salida_id,
|
modulo_salida_id=req.modulo_salida_id,
|
||||||
persona_id=req.persona_id or 0,
|
persona_id=req.persona_id or 0,
|
||||||
patente=req.patente_salida or "",
|
patente=req.patente_salida or "",
|
||||||
|
personas_ids_permanecen=req.personas_ids_permanecen,
|
||||||
|
integrantes_verificados=req.integrantes_verificados,
|
||||||
)
|
)
|
||||||
if not ok:
|
if not ok:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
@@ -100,6 +103,17 @@ class AccessService:
|
|||||||
fecha_hora=ahora,
|
fecha_hora=ahora,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def obtener_permiso_lote(lote_id: int, persona_id: int = 0) -> dict:
|
||||||
|
"""Verifica restricciones de lote (Cat 26) y relación de persona (LotPer)."""
|
||||||
|
return AccessRepository.obtener_permiso_lote(lote_id, persona_id)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def obtener_ocupantes_ticket(ticket_id: int) -> list:
|
||||||
|
"""Obtiene la lista de ocupantes (conductor y acompañantes) vinculados a un ticket."""
|
||||||
|
return AccessRepository.obtener_ocupantes_ticket(ticket_id)
|
||||||
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def obtener_tickets_activos() -> List[ActiveTicketDTO]:
|
def obtener_tickets_activos() -> List[ActiveTicketDTO]:
|
||||||
"""Obtiene la lista de tickets que se encuentran actualmente dentro del predio."""
|
"""Obtiene la lista de tickets que se encuentran actualmente dentro del predio."""
|
||||||
|
|||||||
@@ -170,3 +170,105 @@ async def test_flujo_completo_ingreso_y_salida():
|
|||||||
cursor.execute("DELETE FROM pdtmdl WHERE ModuloID IN (100004, 100005) AND Extra = %s", (str(ticket_id),))
|
cursor.execute("DELETE FROM pdtmdl WHERE ModuloID IN (100004, 100005) AND Extra = %s", (str(ticket_id),))
|
||||||
cursor.execute("DELETE FROM mvthist WHERE TicketID = %s", (ticket_id,))
|
cursor.execute("DELETE FROM mvthist WHERE TicketID = %s", (ticket_id,))
|
||||||
cursor.execute("DELETE FROM tckhst WHERE TicketID = %s", (ticket_id,))
|
cursor.execute("DELETE FROM tckhst WHERE TicketID = %s", (ticket_id,))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_lot_permission_and_occupants_api():
|
||||||
|
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")
|
||||||
|
|
||||||
|
# 1. Validar permiso de lote
|
||||||
|
lot_res = await client.get(
|
||||||
|
"/api/v1/access/lots/1/permission",
|
||||||
|
cookies={"access_token": token},
|
||||||
|
)
|
||||||
|
assert lot_res.status_code == 200
|
||||||
|
lot_data = lot_res.json()
|
||||||
|
assert "estado" in lot_data
|
||||||
|
assert "color" in lot_data
|
||||||
|
assert "detalle" in lot_data
|
||||||
|
|
||||||
|
# 2. Registrar ingreso con acompañantes
|
||||||
|
doc_cond = "88112233"
|
||||||
|
doc_acomp1 = "88112234"
|
||||||
|
doc_acomp2 = "88112235"
|
||||||
|
|
||||||
|
entry_res = await client.post(
|
||||||
|
"/api/v1/access/entry",
|
||||||
|
json={
|
||||||
|
"modulo_ingreso_id": 100004,
|
||||||
|
"documento": doc_cond,
|
||||||
|
"apellido": "GARCIA",
|
||||||
|
"nombre": "ROBERTO",
|
||||||
|
"patente": "GRC888",
|
||||||
|
"cantidad_ocupantes": 3,
|
||||||
|
"abrir_barrera": False,
|
||||||
|
"integrantes": [
|
||||||
|
{
|
||||||
|
"documento": doc_acomp1,
|
||||||
|
"apellido": "GARCIA",
|
||||||
|
"nombre": "ANA",
|
||||||
|
"sexo": "F",
|
||||||
|
"es_menor": False,
|
||||||
|
"rol_id": 2,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"documento": doc_acomp2,
|
||||||
|
"apellido": "GARCIA",
|
||||||
|
"nombre": "LUCAS",
|
||||||
|
"sexo": "M",
|
||||||
|
"es_menor": True,
|
||||||
|
"rol_id": 3,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
cookies={"access_token": token},
|
||||||
|
)
|
||||||
|
assert entry_res.status_code == 200
|
||||||
|
tid = entry_res.json()["ticket_id"]
|
||||||
|
|
||||||
|
# 3. Consultar ocupantes del ticket
|
||||||
|
occ_res = await client.get(
|
||||||
|
f"/api/v1/access/tickets/{tid}/occupants",
|
||||||
|
cookies={"access_token": token},
|
||||||
|
)
|
||||||
|
assert occ_res.status_code == 200
|
||||||
|
ocupantes = occ_res.json()
|
||||||
|
assert len(ocupantes) >= 2
|
||||||
|
docs_cargados = [o["documento"] for o in ocupantes]
|
||||||
|
assert doc_cond in docs_cargados
|
||||||
|
|
||||||
|
# 4. Registrar salida verificando al conductor y desacoplando al acompañante que permanece
|
||||||
|
pid_permanece = next((o["persona_id"] for o in ocupantes if o["documento"] == doc_acomp1), 0)
|
||||||
|
|
||||||
|
exit_res = await client.post(
|
||||||
|
"/api/v1/access/exit",
|
||||||
|
json={
|
||||||
|
"ticket_id": tid,
|
||||||
|
"modulo_salida_id": 100005,
|
||||||
|
"patente_salida": "GRC888",
|
||||||
|
"abrir_barrera": False,
|
||||||
|
"personas_ids_permanecen": [pid_permanece] if pid_permanece else [],
|
||||||
|
"integrantes_verificados": [],
|
||||||
|
},
|
||||||
|
cookies={"access_token": token},
|
||||||
|
)
|
||||||
|
assert exit_res.status_code == 200
|
||||||
|
assert exit_res.json()["status"] == "ok"
|
||||||
|
|
||||||
|
# Limpieza
|
||||||
|
from app.core.database import db_session
|
||||||
|
with db_session() as conn:
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute("DELETE FROM PerDocCatVal WHERE Documento IN (%s, %s, %s)", (doc_cond, doc_acomp1, doc_acomp2))
|
||||||
|
cursor.execute("DELETE FROM Per WHERE Apellido = 'GARCIA'")
|
||||||
|
cursor.execute("DELETE FROM mvthist WHERE TicketID = %s", (tid,))
|
||||||
|
cursor.execute("DELETE FROM tckhst WHERE TicketID = %s", (tid,))
|
||||||
|
cursor.execute("DELETE FROM tckper WHERE TicketID = %s", (tid,))
|
||||||
|
cursor.execute("DELETE FROM tck WHERE TicketID = %s", (tid,))
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
// ==============================================================================
|
||||||
|
// Service Worker para OnEverControl PWA
|
||||||
|
// Permite instalación en Android / Windows y aceleración de carga en red local
|
||||||
|
// ==============================================================================
|
||||||
|
const CACHE_NAME = 'onevercontrol-v0.6.2';
|
||||||
|
const STATIC_ASSETS = [
|
||||||
|
'/',
|
||||||
|
'/index.html',
|
||||||
|
'/manifest.json',
|
||||||
|
'/favicon.ico',
|
||||||
|
'/logo_mini.png',
|
||||||
|
'/logo_os.png',
|
||||||
|
'/icons/puesto-control.ico',
|
||||||
|
'/icons/identificaciones.ico',
|
||||||
|
'/icons/movimientos.ico'
|
||||||
|
];
|
||||||
|
|
||||||
|
self.addEventListener('install', (event) => {
|
||||||
|
event.waitUntil(
|
||||||
|
caches.open(CACHE_NAME).then((cache) => {
|
||||||
|
return cache.addAll(STATIC_ASSETS).catch(() => {});
|
||||||
|
})
|
||||||
|
);
|
||||||
|
self.skipWaiting();
|
||||||
|
});
|
||||||
|
|
||||||
|
self.addEventListener('activate', (event) => {
|
||||||
|
event.waitUntil(
|
||||||
|
caches.keys().then((keys) => {
|
||||||
|
return Promise.all(
|
||||||
|
keys.filter((key) => key !== CACHE_NAME).map((key) => caches.delete(key))
|
||||||
|
);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
self.clients.claim();
|
||||||
|
});
|
||||||
|
|
||||||
|
self.addEventListener('fetch', (event) => {
|
||||||
|
const url = new URL(event.request.url);
|
||||||
|
|
||||||
|
// No interceptar peticiones a la API backend ni WebSockets
|
||||||
|
if (url.pathname.startsWith('/api') || url.pathname.startsWith('/ws')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
event.respondWith(
|
||||||
|
caches.match(event.request).then((cachedResponse) => {
|
||||||
|
if (cachedResponse) {
|
||||||
|
return cachedResponse;
|
||||||
|
}
|
||||||
|
return fetch(event.request).catch(() => {
|
||||||
|
// Fallback a index.html en navegación SPA
|
||||||
|
if (event.request.mode === 'navigate') {
|
||||||
|
return caches.match('/');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -57,4 +57,17 @@ export const accessApi = {
|
|||||||
method: 'GET',
|
method: 'GET',
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
|
getLotPermission: (loteId: number, personaId: number = 0) => {
|
||||||
|
return request<any>(`/access/lots/${loteId}/permission?persona_id=${personaId}`, {
|
||||||
|
method: 'GET',
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
getTicketOccupants: (ticketId: number) => {
|
||||||
|
return request<any[]>(`/access/tickets/${ticketId}/occupants`, {
|
||||||
|
method: 'GET',
|
||||||
|
});
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,467 @@
|
|||||||
|
// ==============================================================================
|
||||||
|
// Modal de Registro Secuencial de Integrantes y Acompañantes
|
||||||
|
// Paridad 1:1 con DialogoRegistroIntegrantes (OemspotPySYS / OneverAccess)
|
||||||
|
// ==============================================================================
|
||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import { Companion, DNIParsedResult } from '../../types';
|
||||||
|
import { CameraScannerModal } from '../scanner/CameraScannerModal';
|
||||||
|
|
||||||
|
interface CompanionsRegistrationModalProps {
|
||||||
|
isOpen: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
conductorNombre: string;
|
||||||
|
conductorDocumento: string;
|
||||||
|
patente: string;
|
||||||
|
cantidadAdultos: number;
|
||||||
|
cantidadMenores: number;
|
||||||
|
integrantesIniciales: Companion[];
|
||||||
|
onConfirm: (integrantes: Companion[], totalAdultos: number, totalMenores: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CompanionsRegistrationModal: React.FC<CompanionsRegistrationModalProps> = ({
|
||||||
|
isOpen,
|
||||||
|
onClose,
|
||||||
|
conductorNombre,
|
||||||
|
conductorDocumento,
|
||||||
|
patente,
|
||||||
|
cantidadAdultos,
|
||||||
|
cantidadMenores,
|
||||||
|
integrantesIniciales,
|
||||||
|
onConfirm,
|
||||||
|
}) => {
|
||||||
|
const [adultos, setAdultos] = useState<number>(cantidadAdultos);
|
||||||
|
const [menores, setMenores] = useState<number>(cantidadMenores);
|
||||||
|
const [integrantes, setIntegrantes] = useState<Companion[]>(integrantesIniciales || []);
|
||||||
|
|
||||||
|
// Formulario para carga del integrante en curso
|
||||||
|
const [doc, setDoc] = useState<string>('');
|
||||||
|
const [apellido, setApellido] = useState<string>('');
|
||||||
|
const [nombre, setNombre] = useState<string>('');
|
||||||
|
const [sexo, setSexo] = useState<string>('M');
|
||||||
|
const [esMenor, setEsMenor] = useState<boolean>(false);
|
||||||
|
|
||||||
|
// Cámara para escanear DNI de un acompañante
|
||||||
|
const [cameraOpen, setCameraOpen] = useState<boolean>(false);
|
||||||
|
const [feedback, setFeedback] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Sincronizar cantidades al abrir
|
||||||
|
useEffect(() => {
|
||||||
|
if (isOpen) {
|
||||||
|
setAdultos(Math.max(1, cantidadAdultos));
|
||||||
|
setMenores(Math.max(0, cantidadMenores));
|
||||||
|
setIntegrantes(integrantesIniciales || []);
|
||||||
|
setDoc('');
|
||||||
|
setApellido('');
|
||||||
|
setNombre('');
|
||||||
|
setSexo('M');
|
||||||
|
setEsMenor(false);
|
||||||
|
setFeedback(null);
|
||||||
|
}
|
||||||
|
}, [isOpen, cantidadAdultos, cantidadMenores, integrantesIniciales]);
|
||||||
|
|
||||||
|
if (!isOpen) return null;
|
||||||
|
|
||||||
|
// Total de acompañantes esperados (excluye al conductor)
|
||||||
|
const acompEsperados = Math.max(0, adultos - 1) + menores;
|
||||||
|
|
||||||
|
const handleAddIntegrante = (e?: React.FormEvent) => {
|
||||||
|
if (e) e.preventDefault();
|
||||||
|
if (!doc.trim()) {
|
||||||
|
setFeedback('Debe ingresar el número de documento del acompañante.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nuevo: Companion = {
|
||||||
|
documento: doc.trim(),
|
||||||
|
apellido: apellido.trim().toUpperCase(),
|
||||||
|
nombre: nombre.trim().toUpperCase(),
|
||||||
|
sexo: sexo || 'M',
|
||||||
|
es_menor: esMenor,
|
||||||
|
rol_id: esMenor ? 3 : 2,
|
||||||
|
};
|
||||||
|
|
||||||
|
const actualizados = [...integrantes, nuevo];
|
||||||
|
setIntegrantes(actualizados);
|
||||||
|
setDoc('');
|
||||||
|
setApellido('');
|
||||||
|
setNombre('');
|
||||||
|
setSexo('M');
|
||||||
|
setEsMenor(false);
|
||||||
|
setFeedback(`✓ Acompañante agregado (${nuevo.apellido || 'S/A'}, ${nuevo.nombre || 'S/N'}).`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRemoveIntegrante = (index: number) => {
|
||||||
|
setIntegrantes((prev) => prev.filter((_, idx) => idx !== index));
|
||||||
|
setFeedback('Acompañante eliminado de la lista.');
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCameraScanSuccess = (data: DNIParsedResult) => {
|
||||||
|
setDoc(data.documento);
|
||||||
|
setApellido(data.apellido);
|
||||||
|
setNombre(data.nombre);
|
||||||
|
setSexo(data.sexo || 'M');
|
||||||
|
setFeedback(`DNI escaneado: ${data.apellido}, ${data.nombre}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleConfirmAll = () => {
|
||||||
|
onConfirm(integrantes, adultos, menores);
|
||||||
|
onClose();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
position: 'fixed',
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
bottom: 0,
|
||||||
|
backgroundColor: 'rgba(2, 6, 23, 0.85)',
|
||||||
|
backdropFilter: 'blur(4px)',
|
||||||
|
zIndex: 9998,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
padding: '1rem',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="card"
|
||||||
|
style={{
|
||||||
|
width: '100%',
|
||||||
|
maxWidth: '820px',
|
||||||
|
maxHeight: '90vh',
|
||||||
|
backgroundColor: 'var(--bg-surface)',
|
||||||
|
borderRadius: '12px',
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
boxShadow: 'var(--shadow-lg)',
|
||||||
|
border: '1px solid var(--border-subtle)',
|
||||||
|
overflow: 'hidden',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* Cabecera del Modal */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
padding: '1rem 1.25rem',
|
||||||
|
backgroundColor: 'var(--bg-surface)',
|
||||||
|
borderBottom: '1px solid var(--border-subtle)',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: '0.65rem' }}>
|
||||||
|
<span style={{ fontSize: '1.4rem' }}>👥</span>
|
||||||
|
<div>
|
||||||
|
<h2 style={{ fontSize: '1.15rem', fontWeight: 700, margin: 0, color: 'var(--text-primary)' }}>
|
||||||
|
Registro de Integrantes y Acompañantes
|
||||||
|
</h2>
|
||||||
|
<span style={{ fontSize: '0.8rem', color: 'var(--text-secondary)' }}>
|
||||||
|
Vehículo: <strong>{patente || 'Peatonal'}</strong> • Conductor: <strong>{conductorNombre || 'S/D'}</strong> (DNI: {conductorDocumento || 'S/D'})
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="btn btn-secondary"
|
||||||
|
style={{ minHeight: '36px', padding: '0 0.75rem', fontSize: '1.1rem' }}
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Resumen de Cupos y Steppers */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
padding: '0.85rem 1.25rem',
|
||||||
|
backgroundColor: 'var(--bg-app)',
|
||||||
|
borderBottom: '1px solid var(--border-subtle)',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
gap: '1rem',
|
||||||
|
flexWrap: 'wrap',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* Stepper Adultos */}
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
|
||||||
|
<span style={{ fontSize: '0.85rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
||||||
|
👤 Adultos Totales:
|
||||||
|
</span>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: '0.25rem' }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-secondary"
|
||||||
|
onClick={() => setAdultos((prev) => Math.max(1, prev - 1))}
|
||||||
|
style={{ minHeight: '34px', width: '34px', padding: 0, fontSize: '1.1rem' }}
|
||||||
|
>
|
||||||
|
-
|
||||||
|
</button>
|
||||||
|
<span style={{ minWidth: '28px', textAlign: 'center', fontWeight: 700 }}>{adultos}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-secondary"
|
||||||
|
onClick={() => setAdultos((prev) => prev + 1)}
|
||||||
|
style={{ minHeight: '34px', width: '34px', padding: 0, fontSize: '1.1rem' }}
|
||||||
|
>
|
||||||
|
+
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Stepper Menores */}
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
|
||||||
|
<span style={{ fontSize: '0.85rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
||||||
|
👶 Menores de Edad:
|
||||||
|
</span>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: '0.25rem' }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-secondary"
|
||||||
|
onClick={() => setMenores((prev) => Math.max(0, prev - 1))}
|
||||||
|
style={{ minHeight: '34px', width: '34px', padding: 0, fontSize: '1.1rem' }}
|
||||||
|
>
|
||||||
|
-
|
||||||
|
</button>
|
||||||
|
<span style={{ minWidth: '28px', textAlign: 'center', fontWeight: 700 }}>{menores}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-secondary"
|
||||||
|
onClick={() => setMenores((prev) => prev + 1)}
|
||||||
|
style={{ minHeight: '34px', width: '34px', padding: 0, fontSize: '1.1rem' }}
|
||||||
|
>
|
||||||
|
+
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Badge Estado de Acompañantes */}
|
||||||
|
<div>
|
||||||
|
<span
|
||||||
|
className={`badge ${integrantes.length >= acompEsperados ? 'badge-success' : 'badge-warning'}`}
|
||||||
|
style={{ fontSize: '0.85rem', padding: '0.4rem 0.8rem' }}
|
||||||
|
>
|
||||||
|
{integrantes.length} de {acompEsperados} acompañantes cargados
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Cuerpo del Modal: Formulario + Grilla */}
|
||||||
|
<div style={{ display: 'flex', flex: 1, overflow: 'hidden', flexDirection: 'column', padding: '1.25rem', gap: '1rem' }}>
|
||||||
|
{/* Banner de Feedback */}
|
||||||
|
{feedback && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
padding: '0.5rem 1rem',
|
||||||
|
backgroundColor: 'var(--status-info-bg)',
|
||||||
|
color: 'var(--status-info)',
|
||||||
|
borderRadius: '6px',
|
||||||
|
fontSize: '0.85rem',
|
||||||
|
fontWeight: 600,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{feedback}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Formulario Rápido de Carga */}
|
||||||
|
<form
|
||||||
|
onSubmit={handleAddIntegrante}
|
||||||
|
style={{
|
||||||
|
display: 'grid',
|
||||||
|
gridTemplateColumns: '1fr 1fr 1fr 110px auto',
|
||||||
|
gap: '0.5rem',
|
||||||
|
alignItems: 'end',
|
||||||
|
backgroundColor: 'var(--bg-app)',
|
||||||
|
padding: '0.85rem',
|
||||||
|
borderRadius: '8px',
|
||||||
|
border: '1px solid var(--border-subtle)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
||||||
|
DNI ACOMPAÑANTE:
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="input-touch"
|
||||||
|
placeholder="Ej: 35123456"
|
||||||
|
value={doc}
|
||||||
|
onChange={(e) => setDoc(e.target.value)}
|
||||||
|
style={{ width: '100%', marginTop: '0.2rem' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
||||||
|
APELLIDO:
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="input-touch"
|
||||||
|
placeholder="Apellido"
|
||||||
|
value={apellido}
|
||||||
|
onChange={(e) => setApellido(e.target.value)}
|
||||||
|
style={{ width: '100%', marginTop: '0.2rem', textTransform: 'uppercase' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
||||||
|
NOMBRE:
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="input-touch"
|
||||||
|
placeholder="Nombre"
|
||||||
|
value={nombre}
|
||||||
|
onChange={(e) => setNombre(e.target.value)}
|
||||||
|
style={{ width: '100%', marginTop: '0.2rem', textTransform: 'uppercase' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
||||||
|
TIPO:
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
className="input-touch"
|
||||||
|
value={esMenor ? 'menor' : 'adulto'}
|
||||||
|
onChange={(e) => setEsMenor(e.target.value === 'menor')}
|
||||||
|
style={{ width: '100%', marginTop: '0.2rem' }}
|
||||||
|
>
|
||||||
|
<option value="adulto">Adulto</option>
|
||||||
|
<option value="menor">Menor</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ display: 'flex', gap: '0.35rem' }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-secondary"
|
||||||
|
onClick={() => setCameraOpen(true)}
|
||||||
|
title="Escanear DNI de este acompañante con la cámara"
|
||||||
|
style={{ minHeight: '44px', padding: '0 0.75rem' }}
|
||||||
|
>
|
||||||
|
📷
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="btn btn-primary"
|
||||||
|
style={{ minHeight: '44px', padding: '0 1rem', fontWeight: 600 }}
|
||||||
|
>
|
||||||
|
+ Agregar
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{/* Grilla de Acompañantes Cargados */}
|
||||||
|
<div style={{ flex: 1, overflowY: 'auto', border: '1px solid var(--border-subtle)', borderRadius: '8px' }}>
|
||||||
|
<table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', fontSize: '0.9rem' }}>
|
||||||
|
<thead>
|
||||||
|
<tr style={{ backgroundColor: 'var(--bg-app)', borderBottom: '1px solid var(--border-subtle)' }}>
|
||||||
|
<th style={{ padding: '0.65rem 0.85rem', color: 'var(--text-secondary)' }}>ROL</th>
|
||||||
|
<th style={{ padding: '0.65rem 0.85rem', color: 'var(--text-secondary)' }}>DOCUMENTO</th>
|
||||||
|
<th style={{ padding: '0.65rem 0.85rem', color: 'var(--text-secondary)' }}>APELLIDO Y NOMBRE</th>
|
||||||
|
<th style={{ padding: '0.65rem 0.85rem', color: 'var(--text-secondary)', textAlign: 'right' }}>ACCIÓN</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{/* Conductor Titular (Fila Fija Destacada) */}
|
||||||
|
<tr style={{ borderBottom: '1px solid var(--border-subtle)', backgroundColor: 'var(--status-info-bg)' }}>
|
||||||
|
<td style={{ padding: '0.65rem 0.85rem', fontWeight: 700, color: 'var(--status-info)' }}>
|
||||||
|
🚗 Conductor (Titular)
|
||||||
|
</td>
|
||||||
|
<td style={{ padding: '0.65rem 0.85rem', fontWeight: 600 }}>{conductorDocumento || '(A completar)'}</td>
|
||||||
|
<td style={{ padding: '0.65rem 0.85rem', fontWeight: 600 }}>{conductorNombre || '(A completar en formulario)'}</td>
|
||||||
|
<td style={{ padding: '0.65rem 0.85rem', textAlign: 'right', color: 'var(--text-secondary)', fontSize: '0.8rem' }}>
|
||||||
|
Fijo
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
|
||||||
|
{/* Lista de Acompañantes */}
|
||||||
|
{integrantes.map((ing, idx) => (
|
||||||
|
<tr key={`${ing.documento}-${idx}`} style={{ borderBottom: '1px solid var(--border-subtle)' }}>
|
||||||
|
<td style={{ padding: '0.65rem 0.85rem' }}>
|
||||||
|
<span className={ing.es_menor ? 'badge badge-warning' : 'badge badge-info'}>
|
||||||
|
{ing.es_menor ? '👶 Menor' : '👤 Adulto Acompañante'}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td style={{ padding: '0.65rem 0.85rem', fontWeight: 600 }}>{ing.documento}</td>
|
||||||
|
<td style={{ padding: '0.65rem 0.85rem' }}>
|
||||||
|
{ing.apellido ? `${ing.apellido}, ${ing.nombre}` : ing.nombre || '-'}
|
||||||
|
</td>
|
||||||
|
<td style={{ padding: '0.65rem 0.85rem', textAlign: 'right' }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleRemoveIntegrante(idx)}
|
||||||
|
style={{
|
||||||
|
backgroundColor: 'rgba(239, 68, 68, 0.15)',
|
||||||
|
color: 'var(--status-danger)',
|
||||||
|
border: '1px solid var(--status-danger)',
|
||||||
|
borderRadius: '4px',
|
||||||
|
padding: '0.25rem 0.5rem',
|
||||||
|
cursor: 'pointer',
|
||||||
|
fontSize: '0.8rem',
|
||||||
|
fontWeight: 600,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
✖ Quitar
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{integrantes.length === 0 && (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={4} style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-secondary)' }}>
|
||||||
|
No se han cargado acompañantes aún. Use el formulario superior o escanee sus DNI.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Footer de Acciones */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
padding: '1rem 1.25rem',
|
||||||
|
backgroundColor: 'var(--bg-surface)',
|
||||||
|
borderTop: '1px solid var(--border-subtle)',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span style={{ fontSize: '0.85rem', color: 'var(--text-secondary)' }}>
|
||||||
|
Total en vehículo: <strong>{1 + integrantes.length} persona(s)</strong> (1 Conductor + {integrantes.length} Acompañante(s))
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<div style={{ display: 'flex', gap: '0.75rem' }}>
|
||||||
|
<button type="button" className="btn btn-secondary" onClick={onClose} style={{ minHeight: '44px' }}>
|
||||||
|
Cancelar
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-primary"
|
||||||
|
onClick={handleConfirmAll}
|
||||||
|
style={{ minHeight: '44px', fontWeight: 700, padding: '0 1.5rem', backgroundColor: 'var(--status-success)' }}
|
||||||
|
>
|
||||||
|
✓ Confirmar e Incorporar al Ingreso
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Submodal para escaneo de DNI con cámara */}
|
||||||
|
<CameraScannerModal
|
||||||
|
isOpen={cameraOpen}
|
||||||
|
onClose={() => setCameraOpen(false)}
|
||||||
|
onScanSuccess={handleCameraScanSuccess}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,550 @@
|
|||||||
|
// ==============================================================================
|
||||||
|
// Modal de Verificación de Salida Vehicular e Integrantes
|
||||||
|
// Paridad 1:1 con DialogoVerificacionSalidaVehicular (OemspotPySYS / OneverAccess)
|
||||||
|
// ==============================================================================
|
||||||
|
import React, { useState, useEffect, useCallback } from 'react';
|
||||||
|
import { ActiveTicket, TicketOccupant, Companion, DNIParsedResult } from '../../types';
|
||||||
|
import { accessApi } from '../../api/accessApi';
|
||||||
|
import { CameraScannerModal } from '../scanner/CameraScannerModal';
|
||||||
|
|
||||||
|
interface ExitVerificationModalProps {
|
||||||
|
isOpen: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
ticket: ActiveTicket | null;
|
||||||
|
moduloSalidaId: number;
|
||||||
|
onExitConfirmed: (message: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ExitVerificationModal: React.FC<ExitVerificationModalProps> = ({
|
||||||
|
isOpen,
|
||||||
|
onClose,
|
||||||
|
ticket,
|
||||||
|
moduloSalidaId,
|
||||||
|
onExitConfirmed,
|
||||||
|
}) => {
|
||||||
|
const [ocupantesOriginales, setOcupantesOriginales] = useState<TicketOccupant[]>([]);
|
||||||
|
const [verificados, setVerificados] = useState<TicketOccupant[]>([]);
|
||||||
|
const [dniInput, setDniInput] = useState<string>('');
|
||||||
|
const [feedback, setFeedback] = useState<{ text: string; type: 'info' | 'success' | 'warn' | 'error' } | null>(null);
|
||||||
|
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||||
|
const [isConfirming, setIsConfirming] = useState<boolean>(false);
|
||||||
|
const [cameraOpen, setCameraOpen] = useState<boolean>(false);
|
||||||
|
|
||||||
|
// Cargar ocupantes desde la base de datos al abrir el modal
|
||||||
|
const loadOccupants = useCallback(async () => {
|
||||||
|
if (!ticket) return;
|
||||||
|
setIsLoading(true);
|
||||||
|
setFeedback(null);
|
||||||
|
try {
|
||||||
|
const data = await accessApi.getTicketOccupants(ticket.ticket_id);
|
||||||
|
setOcupantesOriginales(data);
|
||||||
|
// Por defecto, el conductor titular siempre se incluye en los que egresan
|
||||||
|
const conductor = data.find((o) => o.rol_id === 1) || {
|
||||||
|
persona_id: ticket.persona_id,
|
||||||
|
documento: ticket.documento,
|
||||||
|
apellido: ticket.apellido,
|
||||||
|
nombre: ticket.nombre,
|
||||||
|
rol_id: 1,
|
||||||
|
es_menor: false,
|
||||||
|
rol_nombre: 'Conductor',
|
||||||
|
};
|
||||||
|
setVerificados([conductor]);
|
||||||
|
} catch {
|
||||||
|
// Fallback con el conductor titular del ticket
|
||||||
|
const conductor: TicketOccupant = {
|
||||||
|
persona_id: ticket.persona_id,
|
||||||
|
documento: ticket.documento,
|
||||||
|
apellido: ticket.apellido,
|
||||||
|
nombre: ticket.nombre,
|
||||||
|
rol_id: 1,
|
||||||
|
es_menor: false,
|
||||||
|
rol_nombre: 'Conductor',
|
||||||
|
};
|
||||||
|
setOcupantesOriginales([conductor]);
|
||||||
|
setVerificados([conductor]);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
}, [ticket]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isOpen && ticket) {
|
||||||
|
loadOccupants();
|
||||||
|
}
|
||||||
|
}, [isOpen, ticket, loadOccupants]);
|
||||||
|
|
||||||
|
if (!isOpen || !ticket) return null;
|
||||||
|
|
||||||
|
const pidsVerificados = new Set(verificados.map((v) => v.persona_id));
|
||||||
|
const ocupantesQuePermanecen = ocupantesOriginales.filter((o) => !pidsVerificados.has(o.persona_id));
|
||||||
|
|
||||||
|
// Verificar persona por DNI (escaneado o tipeado)
|
||||||
|
const handleVerifyDni = (rawDni: string) => {
|
||||||
|
const cleanDni = rawDni.trim().replace(/[^0-9]/g, '');
|
||||||
|
if (!cleanDni) return;
|
||||||
|
|
||||||
|
// 1. Buscar entre los ocupantes originales del vehículo
|
||||||
|
const encontradoOriginal = ocupantesOriginales.find(
|
||||||
|
(o) => o.documento.trim() === cleanDni || o.documento.includes(cleanDni)
|
||||||
|
);
|
||||||
|
|
||||||
|
if (encontradoOriginal) {
|
||||||
|
if (pidsVerificados.has(encontradoOriginal.persona_id)) {
|
||||||
|
setFeedback({ text: `ℹ️ ${encontradoOriginal.apellido}, ${encontradoOriginal.nombre} ya fue verificado para salir.`, type: 'info' });
|
||||||
|
} else {
|
||||||
|
setVerificados((prev) => [...prev, encontradoOriginal]);
|
||||||
|
setFeedback({ text: `✓ ${encontradoOriginal.apellido}, ${encontradoOriginal.nombre} verificado correctamente.`, type: 'success' });
|
||||||
|
}
|
||||||
|
setDniInput('');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Si no es original, verificar si ya está agregado como externo
|
||||||
|
const yaAgregado = verificados.find((v) => v.documento === cleanDni);
|
||||||
|
if (yaAgregado) {
|
||||||
|
setFeedback({ text: `ℹ️ DNI ${cleanDni} ya está en la lista de salida.`, type: 'info' });
|
||||||
|
setDniInput('');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Agregar como acompañante externo que egresa en este vehículo
|
||||||
|
const nuevoExt: TicketOccupant = {
|
||||||
|
persona_id: 0,
|
||||||
|
documento: cleanDni,
|
||||||
|
apellido: 'ACOMPAÑANTE',
|
||||||
|
nombre: 'EXTERNO',
|
||||||
|
rol_id: 2,
|
||||||
|
es_menor: false,
|
||||||
|
rol_nombre: 'Externo / Peatón',
|
||||||
|
};
|
||||||
|
setVerificados((prev) => [...prev, nuevoExt]);
|
||||||
|
setFeedback({ text: `✓ DNI ${cleanDni} incorporado a la salida del vehículo.`, type: 'success' });
|
||||||
|
setDniInput('');
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleQuitarVerificado = (personaId: number, documento: string) => {
|
||||||
|
// No permitir quitar al conductor titular
|
||||||
|
const target = verificados.find((v) => v.persona_id === personaId && v.documento === documento);
|
||||||
|
if (target?.rol_id === 1) {
|
||||||
|
setFeedback({ text: '⚠️ No puede quitar al conductor titular de la salida.', type: 'warn' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setVerificados((prev) => prev.filter((v) => !(v.persona_id === personaId && v.documento === documento)));
|
||||||
|
setFeedback({ text: 'Acompañante retirado de la salida. Permanecerá dentro del predio.', type: 'info' });
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleVerificarTodos = () => {
|
||||||
|
setVerificados(ocupantesOriginales);
|
||||||
|
setFeedback({ text: '✓ Todos los ocupantes originales fueron marcados para salir.', type: 'success' });
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCameraScanSuccess = (data: DNIParsedResult) => {
|
||||||
|
handleVerifyDni(data.documento);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Confirmar la salida atómica definitiva
|
||||||
|
const handleConfirmExit = async () => {
|
||||||
|
if (!moduloSalidaId) {
|
||||||
|
setFeedback({ text: '⚠️ Debe seleccionar una barrera de salida.', type: 'warn' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsConfirming(true);
|
||||||
|
try {
|
||||||
|
const pidsPermanecen = ocupantesQuePermanecen.map((o) => o.persona_id).filter((id) => id > 0);
|
||||||
|
const acompanantesDTO: Companion[] = verificados
|
||||||
|
.filter((v) => v.rol_id !== 1)
|
||||||
|
.map((v) => ({
|
||||||
|
documento: v.documento,
|
||||||
|
apellido: v.apellido,
|
||||||
|
nombre: v.nombre,
|
||||||
|
sexo: 'M',
|
||||||
|
es_menor: v.es_menor,
|
||||||
|
rol_id: v.rol_id,
|
||||||
|
}));
|
||||||
|
|
||||||
|
await accessApi.registerExit({
|
||||||
|
ticket_id: ticket.ticket_id,
|
||||||
|
modulo_salida_id: moduloSalidaId,
|
||||||
|
persona_id: ticket.persona_id,
|
||||||
|
patente_salida: ticket.patente || '',
|
||||||
|
abrir_barrera: true,
|
||||||
|
personas_ids_permanecen: pidsPermanecen,
|
||||||
|
integrantes_verificados: acompanantesDTO,
|
||||||
|
});
|
||||||
|
|
||||||
|
let msg = `Salida registrada exitosamente para ${ticket.apellido} (${ticket.patente || 'Peatón'}) con ${verificados.length} ocupante(s).`;
|
||||||
|
if (pidsPermanecen.length > 0) {
|
||||||
|
msg += ` ${pidsPermanecen.length} acompañante(s) permanecen en el predio como peatones.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
onExitConfirmed(msg);
|
||||||
|
onClose();
|
||||||
|
} catch (err: any) {
|
||||||
|
setFeedback({ text: `Error al registrar salida: ${err.message}`, type: 'error' });
|
||||||
|
} finally {
|
||||||
|
setIsConfirming(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
position: 'fixed',
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
bottom: 0,
|
||||||
|
backgroundColor: 'rgba(2, 6, 23, 0.85)',
|
||||||
|
backdropFilter: 'blur(4px)',
|
||||||
|
zIndex: 9998,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
padding: '1rem',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="card"
|
||||||
|
style={{
|
||||||
|
width: '100%',
|
||||||
|
maxWidth: '960px',
|
||||||
|
maxHeight: '92vh',
|
||||||
|
backgroundColor: 'var(--bg-surface)',
|
||||||
|
borderRadius: '12px',
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
boxShadow: 'var(--shadow-lg)',
|
||||||
|
border: '1px solid var(--border-subtle)',
|
||||||
|
overflow: 'hidden',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* Cabecera del Modal */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
padding: '1rem 1.25rem',
|
||||||
|
backgroundColor: 'var(--bg-surface)',
|
||||||
|
borderBottom: '1px solid var(--border-subtle)',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: '0.65rem' }}>
|
||||||
|
<span style={{ fontSize: '1.4rem' }}>🚗</span>
|
||||||
|
<div>
|
||||||
|
<h2 style={{ fontSize: '1.15rem', fontWeight: 700, margin: 0, color: 'var(--text-primary)' }}>
|
||||||
|
Verificación de Salida Vehicular e Integrantes
|
||||||
|
</h2>
|
||||||
|
<span style={{ fontSize: '0.8rem', color: 'var(--text-secondary)' }}>
|
||||||
|
Ticket #{ticket.ticket_id} • Vehículo: <strong>{ticket.patente || 'Peatonal'}</strong> • Conductor:{' '}
|
||||||
|
<strong>{ticket.apellido}, {ticket.nombre}</strong> (DNI: {ticket.documento})
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="btn btn-secondary"
|
||||||
|
style={{ minHeight: '36px', padding: '0 0.75rem', fontSize: '1.1rem' }}
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Input Rápido de DNI y Escáner Activo */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
padding: '0.85rem 1.25rem',
|
||||||
|
backgroundColor: 'var(--bg-app)',
|
||||||
|
borderBottom: '1px solid var(--border-subtle)',
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
gap: '0.5rem',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: '0.65rem' }}>
|
||||||
|
<span style={{ fontSize: '1.1rem' }}>⚡</span>
|
||||||
|
<span style={{ fontSize: '0.85rem', fontWeight: 700, color: 'var(--accent)' }}>
|
||||||
|
Lector de DNI / Documento Activo — Ingrese o escanee DNI de quienes están saliendo
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
handleVerifyDni(dniInput);
|
||||||
|
}}
|
||||||
|
style={{ display: 'flex', gap: '0.5rem' }}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="input-touch"
|
||||||
|
placeholder="Esperando DNI... Escanee código PDF417 o ingrese DNI y presione ENTER"
|
||||||
|
value={dniInput}
|
||||||
|
onChange={(e) => setDniInput(e.target.value)}
|
||||||
|
autoFocus
|
||||||
|
style={{ flex: 1, minHeight: '44px', fontWeight: 600 }}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-secondary"
|
||||||
|
onClick={() => setCameraOpen(true)}
|
||||||
|
title="Escanear con cámara"
|
||||||
|
style={{ minHeight: '44px', padding: '0 1rem' }}
|
||||||
|
>
|
||||||
|
📷 Cámara
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="btn btn-primary"
|
||||||
|
style={{ minHeight: '44px', padding: '0 1.25rem', fontWeight: 600 }}
|
||||||
|
>
|
||||||
|
✔ Verificar DNI
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-secondary"
|
||||||
|
onClick={handleVerificarTodos}
|
||||||
|
title="Marcar a todos los que entraron como egresando"
|
||||||
|
style={{ minHeight: '44px', padding: '0 1rem', fontSize: '0.85rem' }}
|
||||||
|
>
|
||||||
|
👥 Salen Todos ({ocupantesOriginales.length})
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{feedback && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
padding: '0.4rem 0.85rem',
|
||||||
|
borderRadius: '6px',
|
||||||
|
fontSize: '0.825rem',
|
||||||
|
fontWeight: 600,
|
||||||
|
backgroundColor:
|
||||||
|
feedback.type === 'success'
|
||||||
|
? 'var(--status-success-bg)'
|
||||||
|
: feedback.type === 'warn'
|
||||||
|
? 'var(--status-warning-bg)'
|
||||||
|
: feedback.type === 'error'
|
||||||
|
? 'var(--status-danger-bg)'
|
||||||
|
: 'var(--status-info-bg)',
|
||||||
|
color:
|
||||||
|
feedback.type === 'success'
|
||||||
|
? 'var(--status-success)'
|
||||||
|
: feedback.type === 'warn'
|
||||||
|
? 'var(--status-warning)'
|
||||||
|
: feedback.type === 'error'
|
||||||
|
? 'var(--status-danger)'
|
||||||
|
: 'var(--status-info)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{feedback.text}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Paneles Duales: Ingresaron Originales vs Verificados para Salir */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: 'grid',
|
||||||
|
gridTemplateColumns: '1fr 1fr',
|
||||||
|
gap: '1rem',
|
||||||
|
padding: '1.25rem',
|
||||||
|
flex: 1,
|
||||||
|
overflowY: 'auto',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* Panel Izquierdo: Originales */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
backgroundColor: 'var(--bg-app)',
|
||||||
|
borderRadius: '8px',
|
||||||
|
border: '1px solid var(--border-subtle)',
|
||||||
|
overflow: 'hidden',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ padding: '0.75rem 1rem', borderBottom: '1px solid var(--border-subtle)' }}>
|
||||||
|
<h3 style={{ fontSize: '0.95rem', fontWeight: 700, margin: 0 }}>
|
||||||
|
📋 Ingresaron con este Vehículo ({ocupantesOriginales.length})
|
||||||
|
</h3>
|
||||||
|
<span style={{ fontSize: '0.75rem', color: 'var(--text-secondary)' }}>
|
||||||
|
Quienes no verifiquen permanecerán adentro con ticket peatonal.
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ flex: 1, overflowY: 'auto', padding: '0.5rem' }}>
|
||||||
|
{isLoading ? (
|
||||||
|
<div style={{ textAlign: 'center', padding: '2rem', color: 'var(--text-secondary)' }}>Cargando ocupantes...</div>
|
||||||
|
) : (
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.4rem' }}>
|
||||||
|
{ocupantesOriginales.map((oc, idx) => {
|
||||||
|
const isVerif = pidsVerificados.has(oc.persona_id);
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={`${oc.persona_id}-${idx}`}
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
padding: '0.65rem 0.85rem',
|
||||||
|
backgroundColor: 'var(--bg-surface)',
|
||||||
|
borderRadius: '6px',
|
||||||
|
border: `1px solid ${isVerif ? 'var(--status-success)' : 'var(--border-subtle)'}`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<div style={{ fontSize: '0.9rem', fontWeight: 600 }}>
|
||||||
|
{oc.apellido}, {oc.nombre || ''}{' '}
|
||||||
|
<span style={{ fontSize: '0.8rem', color: 'var(--text-secondary)', fontWeight: 400 }}>
|
||||||
|
(DNI: {oc.documento})
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span style={{ fontSize: '0.75rem', color: 'var(--text-secondary)' }}>
|
||||||
|
{oc.rol_id === 1 ? '🚗 Conductor Titular' : oc.es_menor ? '👶 Menor' : '👤 Acompañante'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<span
|
||||||
|
className={`badge ${isVerif ? 'badge-success' : 'badge-warning'}`}
|
||||||
|
style={{ fontSize: '0.75rem' }}
|
||||||
|
>
|
||||||
|
{isVerif ? '✅ Verificado' : '⏳ Permanece'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Panel Derecho: Verificados para Salir */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
backgroundColor: 'var(--bg-app)',
|
||||||
|
borderRadius: '8px',
|
||||||
|
border: '1px solid var(--border-subtle)',
|
||||||
|
overflow: 'hidden',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ padding: '0.75rem 1rem', borderBottom: '1px solid var(--border-subtle)' }}>
|
||||||
|
<h3 style={{ fontSize: '0.95rem', fontWeight: 700, margin: 0, color: 'var(--status-success)' }}>
|
||||||
|
✅ Personas Verificadas para Salir ({verificados.length})
|
||||||
|
</h3>
|
||||||
|
<span style={{ fontSize: '0.75rem', color: 'var(--text-secondary)' }}>
|
||||||
|
Egresan en este vehículo al abrir la barrera.
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ flex: 1, overflowY: 'auto', padding: '0.5rem' }}>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.4rem' }}>
|
||||||
|
{verificados.map((v, idx) => (
|
||||||
|
<div
|
||||||
|
key={`${v.persona_id}-${v.documento}-${idx}`}
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
padding: '0.65rem 0.85rem',
|
||||||
|
backgroundColor: 'var(--bg-surface)',
|
||||||
|
borderRadius: '6px',
|
||||||
|
border: '1px solid var(--status-success)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<div style={{ fontSize: '0.9rem', fontWeight: 600 }}>
|
||||||
|
{v.apellido}, {v.nombre || ''}{' '}
|
||||||
|
<span style={{ fontSize: '0.8rem', color: 'var(--text-secondary)', fontWeight: 400 }}>
|
||||||
|
(DNI: {v.documento})
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span style={{ fontSize: '0.75rem', color: 'var(--text-secondary)' }}>
|
||||||
|
{v.rol_id === 1 ? '🚗 Conductor Titular' : v.rol_nombre || 'Acompañante'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{v.rol_id !== 1 ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleQuitarVerificado(v.persona_id, v.documento)}
|
||||||
|
style={{
|
||||||
|
backgroundColor: 'rgba(239, 68, 68, 0.15)',
|
||||||
|
color: 'var(--status-danger)',
|
||||||
|
border: '1px solid var(--status-danger)',
|
||||||
|
borderRadius: '4px',
|
||||||
|
padding: '0.2rem 0.5rem',
|
||||||
|
cursor: 'pointer',
|
||||||
|
fontSize: '0.75rem',
|
||||||
|
fontWeight: 600,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
✖ Quitar
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<span className="badge badge-info" style={{ fontSize: '0.7rem' }}>
|
||||||
|
Titular
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Footer y Confirmación */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
padding: '1rem 1.25rem',
|
||||||
|
backgroundColor: 'var(--bg-surface)',
|
||||||
|
borderTop: '1px solid var(--border-subtle)',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<div style={{ fontSize: '0.95rem', fontWeight: 700 }}>
|
||||||
|
Total que egresan: {verificados.length} persona(s)
|
||||||
|
</div>
|
||||||
|
{ocupantesQuePermanecen.length > 0 && (
|
||||||
|
<div style={{ fontSize: '0.8rem', color: 'var(--status-warning)', fontWeight: 600 }}>
|
||||||
|
⚠️ {ocupantesQuePermanecen.length} acompañante(s) permanecerán en el predio como peatones.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ display: 'flex', gap: '0.75rem' }}>
|
||||||
|
<button type="button" className="btn btn-secondary" onClick={onClose} style={{ minHeight: '46px' }}>
|
||||||
|
Cancelar
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-primary"
|
||||||
|
disabled={isConfirming}
|
||||||
|
onClick={handleConfirmExit}
|
||||||
|
style={{
|
||||||
|
minHeight: '46px',
|
||||||
|
fontWeight: 700,
|
||||||
|
padding: '0 1.75rem',
|
||||||
|
backgroundColor: 'var(--status-danger)',
|
||||||
|
color: '#fff',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{isConfirming ? 'Procesando...' : `🚗 Confirmar Salida y Abrir Barrera (${verificados.length})`}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<CameraScannerModal
|
||||||
|
isOpen={cameraOpen}
|
||||||
|
onClose={() => setCameraOpen(false)}
|
||||||
|
onScanSuccess={handleCameraScanSuccess}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -44,6 +44,9 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
const [selectedDeviceId, setSelectedDeviceId] = useState<string>('');
|
const [selectedDeviceId, setSelectedDeviceId] = useState<string>('');
|
||||||
const [activeCameraLabel, setActiveCameraLabel] = useState<string>('');
|
const [activeCameraLabel, setActiveCameraLabel] = useState<string>('');
|
||||||
|
|
||||||
|
const isProcessingRef = useRef<boolean>(false);
|
||||||
|
const decodeFrameRef = useRef<(ctx: CanvasRenderingContext2D, width: number, height: number) => Promise<boolean>>(() => Promise.resolve(false));
|
||||||
|
|
||||||
// Inicializar motor ZXing configurado para DNI Argentino (PDF417 + QR + Code128)
|
// Inicializar motor ZXing configurado para DNI Argentino (PDF417 + QR + Code128)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const hints = new Map();
|
const hints = new Map();
|
||||||
@@ -61,6 +64,12 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
// Crear canvas offscreen reutilizable
|
// Crear canvas offscreen reutilizable
|
||||||
const offscreenCanvas = document.createElement('canvas');
|
const offscreenCanvas = document.createElement('canvas');
|
||||||
canvasRef.current = offscreenCanvas;
|
canvasRef.current = offscreenCanvas;
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
try {
|
||||||
|
reader.reset();
|
||||||
|
} catch {}
|
||||||
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const stopCamera = useCallback(() => {
|
const stopCamera = useCallback(() => {
|
||||||
@@ -81,11 +90,14 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
if (videoRef.current) {
|
if (videoRef.current) {
|
||||||
videoRef.current.srcObject = null;
|
videoRef.current.srcObject = null;
|
||||||
}
|
}
|
||||||
|
isProcessingRef.current = false;
|
||||||
|
setIsProcessing(false);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleDecodedString = useCallback(
|
const handleDecodedString = useCallback(
|
||||||
async (rawText: string) => {
|
async (rawText: string) => {
|
||||||
if (isProcessing || !rawText) return;
|
if (isProcessingRef.current || !rawText) return;
|
||||||
|
isProcessingRef.current = true;
|
||||||
setIsProcessing(true);
|
setIsProcessing(true);
|
||||||
setErrorMsg(null);
|
setErrorMsg(null);
|
||||||
try {
|
try {
|
||||||
@@ -100,15 +112,18 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setErrorMsg(err.message || 'Error al interpretar el código escaneado.');
|
setErrorMsg(err.message || 'Error al interpretar el código escaneado.');
|
||||||
} finally {
|
} finally {
|
||||||
|
isProcessingRef.current = false;
|
||||||
setIsProcessing(false);
|
setIsProcessing(false);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[isProcessing, stopCamera, onScanSuccess, onClose]
|
[stopCamera, onScanSuccess, onClose]
|
||||||
);
|
);
|
||||||
|
|
||||||
// Decodificar un buffer ImageData mediante ZXing y BarcodeDetector
|
// Decodificar un buffer ImageData mediante ZXing y BarcodeDetector
|
||||||
const decodeFrame = useCallback(
|
const decodeFrame = useCallback(
|
||||||
async (ctx: CanvasRenderingContext2D, width: number, height: number): Promise<boolean> => {
|
async (ctx: CanvasRenderingContext2D, width: number, height: number): Promise<boolean> => {
|
||||||
|
if (isProcessingRef.current) return false;
|
||||||
|
|
||||||
// 1. Probar BarcodeDetector nativo si está presente en el navegador (acelerado por GPU)
|
// 1. Probar BarcodeDetector nativo si está presente en el navegador (acelerado por GPU)
|
||||||
if ('BarcodeDetector' in window) {
|
if ('BarcodeDetector' in window) {
|
||||||
try {
|
try {
|
||||||
@@ -137,7 +152,11 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// NotFoundException en cada frame sin código
|
// NotFoundException en cada frame sin código (normal)
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
zxingReaderRef.current.reset();
|
||||||
|
} catch {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -146,6 +165,9 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
[handleDecodedString]
|
[handleDecodedString]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Mantener decodeFrameRef sincronizado
|
||||||
|
decodeFrameRef.current = decodeFrame;
|
||||||
|
|
||||||
const startCamera = useCallback(
|
const startCamera = useCallback(
|
||||||
async (deviceIdToUse?: string) => {
|
async (deviceIdToUse?: string) => {
|
||||||
setErrorMsg(null);
|
setErrorMsg(null);
|
||||||
@@ -172,10 +194,23 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
try {
|
try {
|
||||||
let stream: MediaStream | null = null;
|
let stream: MediaStream | null = null;
|
||||||
|
|
||||||
// Estrategia de Constraints flexible:
|
// Limpiar stream previo si hubiera
|
||||||
// Intento 1: Dispositivo seleccionado o cámara trasera
|
if (streamRef.current) {
|
||||||
const constraints1: MediaStreamConstraints = deviceIdToUse
|
streamRef.current.getTracks().forEach((t) => {
|
||||||
? { video: { deviceId: { exact: deviceIdToUse } }, audio: false }
|
try { t.stop(); } catch {}
|
||||||
|
});
|
||||||
|
streamRef.current = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const constraints: MediaStreamConstraints = deviceIdToUse
|
||||||
|
? {
|
||||||
|
video: {
|
||||||
|
deviceId: { exact: deviceIdToUse },
|
||||||
|
width: { ideal: 1280 },
|
||||||
|
height: { ideal: 720 },
|
||||||
|
},
|
||||||
|
audio: false,
|
||||||
|
}
|
||||||
: {
|
: {
|
||||||
video: {
|
video: {
|
||||||
facingMode: { ideal: 'environment' },
|
facingMode: { ideal: 'environment' },
|
||||||
@@ -186,9 +221,9 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
stream = await navigator.mediaDevices.getUserMedia(constraints1);
|
stream = await navigator.mediaDevices.getUserMedia(constraints);
|
||||||
} catch {
|
} catch {
|
||||||
// Intento 2: Fallback incondicional para webcams Windows / laptop estándar
|
// Fallback simple si fallaron los constraints ideales
|
||||||
stream = await navigator.mediaDevices.getUserMedia({
|
stream = await navigator.mediaDevices.getUserMedia({
|
||||||
video: true,
|
video: true,
|
||||||
audio: false,
|
audio: false,
|
||||||
@@ -211,11 +246,16 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Enumerar dispositivos disponibles (ahora con permisos ya otorgados)
|
// Enumerar dispositivos disponibles sin provocar re-renders cíclicos
|
||||||
try {
|
try {
|
||||||
const allDevices = await navigator.mediaDevices.enumerateDevices();
|
const allDevices = await navigator.mediaDevices.enumerateDevices();
|
||||||
const vInputs = allDevices.filter((d) => d.kind === 'videoinput');
|
const vInputs = allDevices.filter((d) => d.kind === 'videoinput');
|
||||||
setAvailableDevices(vInputs);
|
setAvailableDevices((prev) => {
|
||||||
|
if (prev.length !== vInputs.length) return vInputs;
|
||||||
|
const prevIds = prev.map((p) => p.deviceId).join(',');
|
||||||
|
const newIds = vInputs.map((p) => p.deviceId).join(',');
|
||||||
|
return prevIds === newIds ? prev : vInputs;
|
||||||
|
});
|
||||||
} catch {
|
} catch {
|
||||||
// Ignorar si falla enumeración
|
// Ignorar si falla enumeración
|
||||||
}
|
}
|
||||||
@@ -230,7 +270,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
// Iniciar loop de escaneo periódico cada 200ms
|
// Iniciar loop de escaneo periódico cada 200ms
|
||||||
if (timerRef.current) window.clearInterval(timerRef.current);
|
if (timerRef.current) window.clearInterval(timerRef.current);
|
||||||
timerRef.current = window.setInterval(async () => {
|
timerRef.current = window.setInterval(async () => {
|
||||||
if (!videoRef.current || videoRef.current.readyState < 2 || isProcessing) return;
|
if (!videoRef.current || videoRef.current.readyState < 2 || isProcessingRef.current) return;
|
||||||
|
|
||||||
const video = videoRef.current;
|
const video = videoRef.current;
|
||||||
const canvas = canvasRef.current;
|
const canvas = canvasRef.current;
|
||||||
@@ -239,13 +279,13 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
const width = video.videoWidth || 640;
|
const width = video.videoWidth || 640;
|
||||||
const height = video.videoHeight || 480;
|
const height = video.videoHeight || 480;
|
||||||
|
|
||||||
canvas.width = width;
|
if (canvas.width !== width) canvas.width = width;
|
||||||
canvas.height = height;
|
if (canvas.height !== height) canvas.height = height;
|
||||||
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
||||||
if (!ctx) return;
|
if (!ctx) return;
|
||||||
|
|
||||||
ctx.drawImage(video, 0, 0, width, height);
|
ctx.drawImage(video, 0, 0, width, height);
|
||||||
await decodeFrame(ctx, width, height);
|
await decodeFrameRef.current(ctx, width, height);
|
||||||
}, 200);
|
}, 200);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setHasCamera(false);
|
setHasCamera(false);
|
||||||
@@ -261,7 +301,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[decodeFrame, isProcessing]
|
[]
|
||||||
);
|
);
|
||||||
|
|
||||||
// Manejador de captura de foto nativa (funciona sin HTTPS en tablets Android)
|
// Manejador de captura de foto nativa (funciona sin HTTPS en tablets Android)
|
||||||
|
|||||||
@@ -2,8 +2,18 @@ import React from 'react';
|
|||||||
import ReactDOM from 'react-dom/client';
|
import ReactDOM from 'react-dom/client';
|
||||||
import App from './App';
|
import App from './App';
|
||||||
|
|
||||||
|
if ('serviceWorker' in navigator) {
|
||||||
|
window.addEventListener('load', () => {
|
||||||
|
navigator.serviceWorker
|
||||||
|
.register('/sw.js')
|
||||||
|
.then((reg) => console.log('PWA ServiceWorker registrado:', reg.scope))
|
||||||
|
.catch((err) => console.log('ServiceWorker error:', err));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
|
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
|
||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
<App />
|
<App />
|
||||||
</React.StrictMode>
|
</React.StrictMode>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -282,3 +282,34 @@ button:disabled, .btn:disabled, .touch-button:disabled {
|
|||||||
::-webkit-scrollbar-thumb:hover {
|
::-webkit-scrollbar-thumb:hover {
|
||||||
background: var(--text-3);
|
background: var(--text-3);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ==============================================================================
|
||||||
|
ADAPTABILIDAD Y MULTIORIENTACIÓN (Tablets Samsung Galaxy Tab y Móviles)
|
||||||
|
============================================================================== */
|
||||||
|
@media (max-width: 960px), (orientation: portrait) and (max-width: 1024px) {
|
||||||
|
.cockpit-grid {
|
||||||
|
display: flex !important;
|
||||||
|
flex-direction: column !important;
|
||||||
|
}
|
||||||
|
.cockpit-entry-col {
|
||||||
|
max-width: 100% !important;
|
||||||
|
border-right: none !important;
|
||||||
|
border-bottom: 1px solid var(--border-subtle) !important;
|
||||||
|
}
|
||||||
|
.portrait-tabs-bar {
|
||||||
|
display: flex !important;
|
||||||
|
}
|
||||||
|
.portrait-tab-hidden {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (min-width: 961px) and (orientation: landscape) {
|
||||||
|
.portrait-tabs-bar {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
.portrait-tab-hidden {
|
||||||
|
display: flex !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -49,12 +49,32 @@ export interface EntryFormData {
|
|||||||
integrantes: Companion[];
|
integrantes: Companion[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface LotPermission {
|
||||||
|
estado: string;
|
||||||
|
color: string;
|
||||||
|
bg_color: string;
|
||||||
|
detalle: string;
|
||||||
|
es_residente: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TicketOccupant {
|
||||||
|
persona_id: number;
|
||||||
|
documento: string;
|
||||||
|
apellido: string;
|
||||||
|
nombre: string;
|
||||||
|
rol_id: number;
|
||||||
|
es_menor: boolean;
|
||||||
|
rol_nombre: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ExitRequestData {
|
export interface ExitRequestData {
|
||||||
ticket_id: number;
|
ticket_id: number;
|
||||||
modulo_salida_id: number;
|
modulo_salida_id: number;
|
||||||
persona_id?: number;
|
persona_id?: number;
|
||||||
patente_salida?: string;
|
patente_salida?: string;
|
||||||
abrir_barrera: boolean;
|
abrir_barrera: boolean;
|
||||||
|
personas_ids_permanecen?: number[];
|
||||||
|
integrantes_verificados?: Companion[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ActiveTicket {
|
export interface ActiveTicket {
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import { hardwareApi } from '../api/hardwareApi';
|
|||||||
import { useWebSocket } from '../hooks/useWebSocket';
|
import { useWebSocket } from '../hooks/useWebSocket';
|
||||||
import { useTheme } from '../hooks/useTheme';
|
import { useTheme } from '../hooks/useTheme';
|
||||||
import { CameraScannerModal } from '../components/scanner/CameraScannerModal';
|
import { CameraScannerModal } from '../components/scanner/CameraScannerModal';
|
||||||
|
import { CompanionsRegistrationModal } from '../components/modals/CompanionsRegistrationModal';
|
||||||
|
import { ExitVerificationModal } from '../components/modals/ExitVerificationModal';
|
||||||
import { APP_VERSION, APP_BUILD } from '../version';
|
import { APP_VERSION, APP_BUILD } from '../version';
|
||||||
import {
|
import {
|
||||||
WorkstationConfig,
|
WorkstationConfig,
|
||||||
@@ -17,8 +19,10 @@ import {
|
|||||||
EntryFormData,
|
EntryFormData,
|
||||||
DNIParsedResult,
|
DNIParsedResult,
|
||||||
LotSearchItem,
|
LotSearchItem,
|
||||||
|
LotPermission,
|
||||||
} from '../types';
|
} from '../types';
|
||||||
|
|
||||||
|
|
||||||
export const ControlPostView: React.FC = () => {
|
export const ControlPostView: React.FC = () => {
|
||||||
const { user, workstation, logout } = useAuth();
|
const { user, workstation, logout } = useAuth();
|
||||||
const { theme, toggleTheme } = useTheme();
|
const { theme, toggleTheme } = useTheme();
|
||||||
@@ -53,17 +57,48 @@ export const ControlPostView: React.FC = () => {
|
|||||||
integrantes: [],
|
integrantes: [],
|
||||||
});
|
});
|
||||||
|
|
||||||
// Autocompletado de Lotes
|
// Autocompletado y validación de Lotes
|
||||||
const [lotSuggestions, setLotSuggestions] = useState<LotSearchItem[]>([]);
|
const [lotSuggestions, setLotSuggestions] = useState<LotSearchItem[]>([]);
|
||||||
const [showLotSuggestions, setShowLotSuggestions] = useState<boolean>(false);
|
const [showLotSuggestions, setShowLotSuggestions] = useState<boolean>(false);
|
||||||
|
const [lotPermission, setLotPermission] = useState<LotPermission | null>(null);
|
||||||
|
|
||||||
// Modales y Alertas
|
// Modales y Alertas
|
||||||
const [scannerOpen, setScannerOpen] = useState<boolean>(false);
|
const [scannerOpen, setScannerOpen] = useState<boolean>(false);
|
||||||
|
const [companionsModalOpen, setCompanionsModalOpen] = useState<boolean>(false);
|
||||||
|
const [exitModalOpen, setExitModalOpen] = useState<boolean>(false);
|
||||||
|
const [ticketForExit, setTicketForExit] = useState<ActiveTicket | null>(null);
|
||||||
|
|
||||||
const [actionSuccess, setActionSuccess] = useState<string | null>(null);
|
const [actionSuccess, setActionSuccess] = useState<string | null>(null);
|
||||||
const [actionError, setActionError] = useState<string | null>(null);
|
const [actionError, setActionError] = useState<string | null>(null);
|
||||||
const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
|
const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
|
||||||
const [clock, setClock] = useState<string>('');
|
const [clock, setClock] = useState<string>('');
|
||||||
|
|
||||||
|
// PWA y Adaptabilidad Multiorientación
|
||||||
|
const [deferredPrompt, setDeferredPrompt] = useState<any>(null);
|
||||||
|
const [canInstallPwa, setCanInstallPwa] = useState<boolean>(false);
|
||||||
|
const [portraitTab, setPortraitTab] = useState<'entry' | 'predio'>('entry');
|
||||||
|
|
||||||
|
// Detección de soporte PWA
|
||||||
|
useEffect(() => {
|
||||||
|
const pwaHandler = (e: any) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDeferredPrompt(e);
|
||||||
|
setCanInstallPwa(true);
|
||||||
|
};
|
||||||
|
window.addEventListener('beforeinstallprompt', pwaHandler);
|
||||||
|
return () => window.removeEventListener('beforeinstallprompt', pwaHandler);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleInstallPwa = async () => {
|
||||||
|
if (!deferredPrompt) return;
|
||||||
|
deferredPrompt.prompt();
|
||||||
|
const choice = await deferredPrompt.userChoice;
|
||||||
|
if (choice.outcome === 'accepted') {
|
||||||
|
setCanInstallPwa(false);
|
||||||
|
}
|
||||||
|
setDeferredPrompt(null);
|
||||||
|
};
|
||||||
|
|
||||||
// Reloj digital en tiempo real
|
// Reloj digital en tiempo real
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const timer = setInterval(() => {
|
const timer = setInterval(() => {
|
||||||
@@ -131,14 +166,24 @@ export const ControlPostView: React.FC = () => {
|
|||||||
onMessage: handleWsEvent,
|
onMessage: handleWsEvent,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Búsqueda autocompletada de Lotes
|
// Búsqueda autocompletada y validación de Lotes (Cat 26)
|
||||||
const handleLotSearch = async (val: string) => {
|
const handleLotSearch = async (val: string) => {
|
||||||
setForm((prev) => ({ ...prev, lote_codigo: val.toUpperCase() }));
|
const cod = val.toUpperCase();
|
||||||
if (val.trim().length >= 1) {
|
setForm((prev) => ({ ...prev, lote_codigo: cod, lote_id: null }));
|
||||||
|
setLotPermission(null);
|
||||||
|
|
||||||
|
if (cod.trim().length >= 1) {
|
||||||
try {
|
try {
|
||||||
const results = await accessApi.searchLots(val.trim());
|
const results = await accessApi.searchLots(cod.trim());
|
||||||
setLotSuggestions(results);
|
setLotSuggestions(results);
|
||||||
setShowLotSuggestions(true);
|
setShowLotSuggestions(true);
|
||||||
|
|
||||||
|
const matchExacto = results.find((r) => r.codigo.toUpperCase() === cod.trim());
|
||||||
|
if (matchExacto) {
|
||||||
|
setForm((prev) => ({ ...prev, lote_id: matchExacto.lote_id }));
|
||||||
|
const perm = await accessApi.getLotPermission(matchExacto.lote_id);
|
||||||
|
setLotPermission(perm);
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
setLotSuggestions([]);
|
setLotSuggestions([]);
|
||||||
}
|
}
|
||||||
@@ -148,13 +193,19 @@ export const ControlPostView: React.FC = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const selectLot = (lot: LotSearchItem) => {
|
const selectLot = async (lot: LotSearchItem) => {
|
||||||
setForm((prev) => ({
|
setForm((prev) => ({
|
||||||
...prev,
|
...prev,
|
||||||
lote_id: lot.lote_id,
|
lote_id: lot.lote_id,
|
||||||
lote_codigo: lot.codigo,
|
lote_codigo: lot.codigo,
|
||||||
}));
|
}));
|
||||||
setShowLotSuggestions(false);
|
setShowLotSuggestions(false);
|
||||||
|
try {
|
||||||
|
const perm = await accessApi.getLotPermission(lot.lote_id);
|
||||||
|
setLotPermission(perm);
|
||||||
|
} catch {
|
||||||
|
setLotPermission(null);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Callback al escanear DNI con cámara
|
// Callback al escanear DNI con cámara
|
||||||
@@ -217,6 +268,7 @@ export const ControlPostView: React.FC = () => {
|
|||||||
abrir_barrera: true,
|
abrir_barrera: true,
|
||||||
integrantes: [],
|
integrantes: [],
|
||||||
});
|
});
|
||||||
|
setLotPermission(null);
|
||||||
|
|
||||||
loadActiveTickets();
|
loadActiveTickets();
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
@@ -226,28 +278,14 @@ export const ControlPostView: React.FC = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Registrar salida de un ticket activo
|
// Abrir diálogo interactivo de verificación de salida
|
||||||
const handleRegisterExit = async (ticket: ActiveTicket) => {
|
const handleOpenExitModal = (ticket: ActiveTicket) => {
|
||||||
if (!selectedExitModuleId) {
|
if (!selectedExitModuleId) {
|
||||||
setActionError('Seleccione un módulo de salida para habilitar la barrera de egreso.');
|
setActionError('Seleccione un módulo de salida para habilitar la barrera de egreso.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
setTicketForExit(ticket);
|
||||||
try {
|
setExitModalOpen(true);
|
||||||
await accessApi.registerExit({
|
|
||||||
ticket_id: ticket.ticket_id,
|
|
||||||
modulo_salida_id: selectedExitModuleId,
|
|
||||||
persona_id: ticket.persona_id,
|
|
||||||
patente_salida: ticket.patente || '',
|
|
||||||
abrir_barrera: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
setActionSuccess(`Salida registrada para ${ticket.apellido} (${ticket.patente || 'Peatón'}) - Barrera Abierta`);
|
|
||||||
setTimeout(() => setActionSuccess(null), 4000);
|
|
||||||
loadActiveTickets();
|
|
||||||
} catch (err: any) {
|
|
||||||
setActionError(`Error al registrar salida: ${err.message}`);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Apertura manual forzada de barrera
|
// Apertura manual forzada de barrera
|
||||||
@@ -374,6 +412,27 @@ export const ControlPostView: React.FC = () => {
|
|||||||
👤 Operador: <strong>{user?.username}</strong>
|
👤 Operador: <strong>{user?.username}</strong>
|
||||||
</span>
|
</span>
|
||||||
|
|
||||||
|
{/* Botón de instalación PWA en Tablet / Móvil */}
|
||||||
|
{canInstallPwa && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-primary"
|
||||||
|
onClick={handleInstallPwa}
|
||||||
|
style={{
|
||||||
|
minHeight: '38px',
|
||||||
|
padding: '0 0.85rem',
|
||||||
|
fontSize: '0.85rem',
|
||||||
|
backgroundColor: 'var(--accent)',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: '0.4rem',
|
||||||
|
}}
|
||||||
|
title="Instalar OnEverControl como App en la pantalla de inicio"
|
||||||
|
>
|
||||||
|
<span>📲</span> Instalar App
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="btn btn-secondary"
|
className="btn btn-secondary"
|
||||||
@@ -454,10 +513,58 @@ export const ControlPostView: React.FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Barra de pestañas responsive para tablets en modo vertical */}
|
||||||
|
<div
|
||||||
|
className="portrait-tabs-bar"
|
||||||
|
style={{
|
||||||
|
display: 'none',
|
||||||
|
backgroundColor: 'var(--bg-surface)',
|
||||||
|
borderBottom: '1px solid var(--border-subtle)',
|
||||||
|
padding: '0.35rem 1rem',
|
||||||
|
gap: '0.5rem',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setPortraitTab('entry')}
|
||||||
|
style={{
|
||||||
|
flex: 1,
|
||||||
|
padding: '0.6rem',
|
||||||
|
border: 'none',
|
||||||
|
borderRadius: '6px',
|
||||||
|
backgroundColor: portraitTab === 'entry' ? 'var(--accent-primary)' : 'transparent',
|
||||||
|
color: portraitTab === 'entry' ? '#fff' : 'var(--text-secondary)',
|
||||||
|
fontWeight: 700,
|
||||||
|
cursor: 'pointer',
|
||||||
|
fontSize: '0.9rem',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
🚗 Registrar Ingreso
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setPortraitTab('predio')}
|
||||||
|
style={{
|
||||||
|
flex: 1,
|
||||||
|
padding: '0.6rem',
|
||||||
|
border: 'none',
|
||||||
|
borderRadius: '6px',
|
||||||
|
backgroundColor: portraitTab === 'predio' ? 'var(--accent-primary)' : 'transparent',
|
||||||
|
color: portraitTab === 'predio' ? '#fff' : 'var(--text-secondary)',
|
||||||
|
fontWeight: 700,
|
||||||
|
cursor: 'pointer',
|
||||||
|
fontSize: '0.9rem',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
📋 En Predio ({activeTickets.length})
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* =========================================================================
|
{/* =========================================================================
|
||||||
Cuerpo Principal de Garita (Layout de 2 Columnas Táctil)
|
Cuerpo Principal de Garita (Layout Cockpit con soporte Multiorientación)
|
||||||
========================================================================= */}
|
========================================================================= */}
|
||||||
<div
|
<div
|
||||||
|
className="cockpit-grid"
|
||||||
style={{
|
style={{
|
||||||
display: 'grid',
|
display: 'grid',
|
||||||
gridTemplateColumns: 'minmax(380px, 460px) 1fr',
|
gridTemplateColumns: 'minmax(380px, 460px) 1fr',
|
||||||
@@ -469,6 +576,7 @@ export const ControlPostView: React.FC = () => {
|
|||||||
COLUMNA 1: FORMULARIO DE INGRESO RÁPIDO
|
COLUMNA 1: FORMULARIO DE INGRESO RÁPIDO
|
||||||
======================================================================= */}
|
======================================================================= */}
|
||||||
<section
|
<section
|
||||||
|
className={`cockpit-entry-col ${portraitTab === 'entry' ? '' : 'portrait-tab-hidden'}`}
|
||||||
style={{
|
style={{
|
||||||
backgroundColor: 'var(--bg-surface)',
|
backgroundColor: 'var(--bg-surface)',
|
||||||
borderRight: '1px solid var(--border-subtle)',
|
borderRight: '1px solid var(--border-subtle)',
|
||||||
@@ -660,6 +768,34 @@ export const ControlPostView: React.FC = () => {
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Badge de Validación de Lote (Categoría 26: Habilitado / Moroso / En Obra) */}
|
||||||
|
{lotPermission && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
marginTop: '0.35rem',
|
||||||
|
padding: '0.35rem 0.65rem',
|
||||||
|
borderRadius: '6px',
|
||||||
|
fontSize: '0.8rem',
|
||||||
|
fontWeight: 700,
|
||||||
|
backgroundColor: lotPermission.bg_color,
|
||||||
|
color: lotPermission.color,
|
||||||
|
border: `1px solid ${lotPermission.color}`,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: '0.4rem',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span>
|
||||||
|
{lotPermission.estado === 'Habilitado'
|
||||||
|
? '✅'
|
||||||
|
: lotPermission.estado === 'Restringido'
|
||||||
|
? '⛔'
|
||||||
|
: '🚧'}
|
||||||
|
</span>
|
||||||
|
<span>{lotPermission.detalle}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -726,6 +862,51 @@ export const ControlPostView: React.FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Gestión de Acompañantes Múltiples (Paridad DialogoRegistroIntegrantes) */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
backgroundColor: 'var(--bg-app)',
|
||||||
|
padding: '0.75rem',
|
||||||
|
borderRadius: '8px',
|
||||||
|
border: '1px solid var(--border-subtle)',
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
gap: '0.45rem',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||||
|
<span style={{ fontSize: '0.8rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
||||||
|
👥 ACOMPAÑANTES ({form.integrantes.length})
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-secondary"
|
||||||
|
onClick={() => setCompanionsModalOpen(true)}
|
||||||
|
style={{ minHeight: '34px', fontSize: '0.8rem', padding: '0 0.75rem', fontWeight: 600 }}
|
||||||
|
>
|
||||||
|
{form.integrantes.length > 0 ? '✏️ Gestionar' : '+ Cargar Acompañantes'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{form.integrantes.length > 0 ? (
|
||||||
|
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.35rem' }}>
|
||||||
|
{form.integrantes.map((ing, idx) => (
|
||||||
|
<span
|
||||||
|
key={idx}
|
||||||
|
className="badge badge-info"
|
||||||
|
style={{ fontSize: '0.75rem', padding: '0.2rem 0.5rem' }}
|
||||||
|
>
|
||||||
|
{ing.es_menor ? '👶' : '👤'} {ing.apellido || ing.documento}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<span style={{ fontSize: '0.75rem', color: 'var(--text-secondary)' }}>
|
||||||
|
Solo conductor registrado. Haga clic en "+ Cargar Acompañantes" para registrar más ocupantes.
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Switch Abrir Barrera */}
|
{/* Switch Abrir Barrera */}
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
@@ -779,6 +960,7 @@ export const ControlPostView: React.FC = () => {
|
|||||||
COLUMNA 2: TICKETS ACTIVOS Y EGRESOS DEL PREDIO
|
COLUMNA 2: TICKETS ACTIVOS Y EGRESOS DEL PREDIO
|
||||||
======================================================================= */}
|
======================================================================= */}
|
||||||
<section
|
<section
|
||||||
|
className={portraitTab === 'predio' ? '' : 'portrait-tab-hidden'}
|
||||||
style={{
|
style={{
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
flexDirection: 'column',
|
flexDirection: 'column',
|
||||||
@@ -977,7 +1159,7 @@ export const ControlPostView: React.FC = () => {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="btn"
|
className="btn"
|
||||||
onClick={() => handleRegisterExit(t)}
|
onClick={() => handleOpenExitModal(t)}
|
||||||
style={{
|
style={{
|
||||||
backgroundColor: 'var(--status-danger)',
|
backgroundColor: 'var(--status-danger)',
|
||||||
color: '#fff',
|
color: '#fff',
|
||||||
@@ -1130,6 +1312,44 @@ export const ControlPostView: React.FC = () => {
|
|||||||
onClose={() => setScannerOpen(false)}
|
onClose={() => setScannerOpen(false)}
|
||||||
onScanSuccess={handleDniScanned}
|
onScanSuccess={handleDniScanned}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* Modal de Registro de Múltiples Integrantes / Acompañantes */}
|
||||||
|
<CompanionsRegistrationModal
|
||||||
|
isOpen={companionsModalOpen}
|
||||||
|
onClose={() => setCompanionsModalOpen(false)}
|
||||||
|
conductorNombre={`${form.apellido}, ${form.nombre}`.trim().replace(/^,\s*|,\s*$/g, '')}
|
||||||
|
conductorDocumento={form.documento}
|
||||||
|
patente={form.patente}
|
||||||
|
cantidadAdultos={form.cantidad_ocupantes}
|
||||||
|
cantidadMenores={form.cantidad_menores}
|
||||||
|
integrantesIniciales={form.integrantes}
|
||||||
|
onConfirm={(nuevosIntegrantes, totAdultos, totMenores) => {
|
||||||
|
setForm((prev) => ({
|
||||||
|
...prev,
|
||||||
|
integrantes: nuevosIntegrantes,
|
||||||
|
cantidad_ocupantes: totAdultos,
|
||||||
|
cantidad_menores: totMenores,
|
||||||
|
}));
|
||||||
|
setActionSuccess(`✓ Se registraron ${nuevosIntegrantes.length} acompañante(s) para este ingreso.`);
|
||||||
|
setTimeout(() => setActionSuccess(null), 4000);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Modal de Verificación de Salida Vehicular */}
|
||||||
|
<ExitVerificationModal
|
||||||
|
isOpen={exitModalOpen}
|
||||||
|
onClose={() => {
|
||||||
|
setExitModalOpen(false);
|
||||||
|
setTicketForExit(null);
|
||||||
|
}}
|
||||||
|
ticket={ticketForExit}
|
||||||
|
moduloSalidaId={selectedExitModuleId}
|
||||||
|
onExitConfirmed={(msg) => {
|
||||||
|
setActionSuccess(msg);
|
||||||
|
setTimeout(() => setActionSuccess(null), 5000);
|
||||||
|
loadActiveTickets();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user