From cfb24d81c4c3282f199e7394052079956b18aac7 Mon Sep 17 00:00:00 2001 From: Carlos Tello Date: Wed, 14 Oct 2026 07:46:25 -0300 Subject: [PATCH] fix(camera-parity-pwa): resolver parpadeo de camara, paridad funcional de acompanantes, lotes, egreso y PWA responsive --- backend/app/api/v1/access.py | 22 + backend/app/repositories/access_repository.py | 223 ++++++- backend/app/schemas/access_schema.py | 20 + backend/app/services/access_service.py | 18 +- backend/tests/test_access.py | 102 ++++ frontend/public/sw.js | 59 ++ frontend/src/api/accessApi.ts | 13 + .../modals/CompanionsRegistrationModal.tsx | 467 +++++++++++++++ .../modals/ExitVerificationModal.tsx | 550 ++++++++++++++++++ .../components/scanner/CameraScannerModal.tsx | 72 ++- frontend/src/main.tsx | 10 + frontend/src/styles/base.css | 31 + frontend/src/types/index.ts | 20 + frontend/src/views/ControlPostView.tsx | 272 ++++++++- 14 files changed, 1816 insertions(+), 63 deletions(-) create mode 100644 frontend/public/sw.js create mode 100644 frontend/src/components/modals/CompanionsRegistrationModal.tsx create mode 100644 frontend/src/components/modals/ExitVerificationModal.tsx diff --git a/backend/app/api/v1/access.py b/backend/app/api/v1/access.py index 527cc71..9cf00d7 100644 --- a/backend/app/api/v1/access.py +++ b/backend/app/api/v1/access.py @@ -11,6 +11,8 @@ from app.schemas.access_schema import ( ActiveTicketDTO, PersonSearchDTO, LotSearchDTO, + LotPermissionDTO, + TicketOccupantDTO, ) from app.services.access_service import AccessService 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.", ) 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) diff --git a/backend/app/repositories/access_repository.py b/backend/app/repositories/access_repository.py index de03fa8..869147b 100644 --- a/backend/app/repositories/access_repository.py +++ b/backend/app/repositories/access_repository.py @@ -178,52 +178,237 @@ class AccessRepository: 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 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: """ 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") + # 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: cursor = conn.cursor(as_dict=True) # 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() if not tck_row: return False f_ing = str(tck_row["FechaHoraIngreso"]) + nro_tck = tck_row.get("Numero") 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( """ 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: - cursor.execute( - """ - INSERT INTO mvthist (TicketID, PersonaID, Patente, RolID, Entidad, Sentido, ModuloID, FechaHora) - VALUES (%s, %s, %s, 1, 'EGRESO...', 'Salida', %s, %s) - """, - (ticket_id, persona_id or None, patente or None, modulo_salida_id, ahora), - ) - except Exception: - pass + # 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() - # 3. Eliminar de tablas vivas - cursor.execute("DELETE FROM tckper WHERE TicketID = %s", (ticket_id,)) - cursor.execute("DELETE FROM tckprx WHERE TicketID = %s", (ticket_id,)) + 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( + """ + INSERT INTO mvthist (TicketID, PersonaID, Patente, LoteID, RolID, Entidad, Sentido, ModuloID, FechaHora) + VALUES (%s, %s, %s, %s, %s, %s, 'Salida', %s, %s) + """, + (ticket_id, oc_pid, oc_pat, oc_lote, oc_rol, oc_ent, modulo_salida_id, ahora), + ) + except Exception as e: + print(f"Aviso registrando mvthist salida: {e}") + + # 4. Eliminar de tck (manteniendo tckper y tckprx para coherencia histórica con tckhst) cursor.execute("DELETE FROM tck WHERE TicketID = %s", (ticket_id,)) return True diff --git a/backend/app/schemas/access_schema.py b/backend/app/schemas/access_schema.py index 037c7f4..a7c5603 100644 --- a/backend/app/schemas/access_schema.py +++ b/backend/app/schemas/access_schema.py @@ -34,6 +34,24 @@ class EntryRequest(BaseModel): 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): ticket_id: int = Field(..., description="ID del ticket activo a cerrar") 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 abrir_barrera: bool = True personas_ids_permanecen: List[int] = Field(default_factory=list) + integrantes_verificados: List[CompanionDTO] = Field(default_factory=list) + class TicketResponse(BaseModel): diff --git a/backend/app/services/access_service.py b/backend/app/services/access_service.py index 6b7a585..f9ebb7e 100644 --- a/backend/app/services/access_service.py +++ b/backend/app/services/access_service.py @@ -71,14 +71,17 @@ class AccessService: """ Ejecuta la regla de negocio para registrar la salida: 1. Valida existencia del ticket en tck. - 2. Mueve a tckhst y mvthist, liberando tckper y tck. - 3. Encola la apertura de barrera en pdtmdl si corresponde. + 2. Desacopla personas que permanecen a tickets peatonales independientes. + 3. Mueve a tckhst y mvthist, liberando el ticket de tck. + 4. Encola la apertura de barrera en pdtmdl si corresponde. """ ok = AccessRepository.registrar_ticket_salida( ticket_id=req.ticket_id, modulo_salida_id=req.modulo_salida_id, persona_id=req.persona_id or 0, patente=req.patente_salida or "", + personas_ids_permanecen=req.personas_ids_permanecen, + integrantes_verificados=req.integrantes_verificados, ) if not ok: raise HTTPException( @@ -100,6 +103,17 @@ class AccessService: 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 def obtener_tickets_activos() -> List[ActiveTicketDTO]: """Obtiene la lista de tickets que se encuentran actualmente dentro del predio.""" diff --git a/backend/tests/test_access.py b/backend/tests/test_access.py index 3ace6bc..e6e5a49 100644 --- a/backend/tests/test_access.py +++ b/backend/tests/test_access.py @@ -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 mvthist 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,)) + diff --git a/frontend/public/sw.js b/frontend/public/sw.js new file mode 100644 index 0000000..468772d --- /dev/null +++ b/frontend/public/sw.js @@ -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('/'); + } + }); + }) + ); +}); diff --git a/frontend/src/api/accessApi.ts b/frontend/src/api/accessApi.ts index bfb734d..b6807ee 100644 --- a/frontend/src/api/accessApi.ts +++ b/frontend/src/api/accessApi.ts @@ -57,4 +57,17 @@ export const accessApi = { method: 'GET', }); }, + + getLotPermission: (loteId: number, personaId: number = 0) => { + return request(`/access/lots/${loteId}/permission?persona_id=${personaId}`, { + method: 'GET', + }); + }, + + getTicketOccupants: (ticketId: number) => { + return request(`/access/tickets/${ticketId}/occupants`, { + method: 'GET', + }); + }, }; + diff --git a/frontend/src/components/modals/CompanionsRegistrationModal.tsx b/frontend/src/components/modals/CompanionsRegistrationModal.tsx new file mode 100644 index 0000000..0adef6c --- /dev/null +++ b/frontend/src/components/modals/CompanionsRegistrationModal.tsx @@ -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 = ({ + isOpen, + onClose, + conductorNombre, + conductorDocumento, + patente, + cantidadAdultos, + cantidadMenores, + integrantesIniciales, + onConfirm, +}) => { + const [adultos, setAdultos] = useState(cantidadAdultos); + const [menores, setMenores] = useState(cantidadMenores); + const [integrantes, setIntegrantes] = useState(integrantesIniciales || []); + + // Formulario para carga del integrante en curso + const [doc, setDoc] = useState(''); + const [apellido, setApellido] = useState(''); + const [nombre, setNombre] = useState(''); + const [sexo, setSexo] = useState('M'); + const [esMenor, setEsMenor] = useState(false); + + // Cámara para escanear DNI de un acompañante + const [cameraOpen, setCameraOpen] = useState(false); + const [feedback, setFeedback] = useState(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 ( +
+
+ {/* Cabecera del Modal */} +
+
+ 👥 +
+

+ Registro de Integrantes y Acompañantes +

+ + Vehículo: {patente || 'Peatonal'} • Conductor: {conductorNombre || 'S/D'} (DNI: {conductorDocumento || 'S/D'}) + +
+
+ +
+ + {/* Resumen de Cupos y Steppers */} +
+ {/* Stepper Adultos */} +
+ + 👤 Adultos Totales: + +
+ + {adultos} + +
+
+ + {/* Stepper Menores */} +
+ + 👶 Menores de Edad: + +
+ + {menores} + +
+
+ + {/* Badge Estado de Acompañantes */} +
+ = acompEsperados ? 'badge-success' : 'badge-warning'}`} + style={{ fontSize: '0.85rem', padding: '0.4rem 0.8rem' }} + > + {integrantes.length} de {acompEsperados} acompañantes cargados + +
+
+ + {/* Cuerpo del Modal: Formulario + Grilla */} +
+ {/* Banner de Feedback */} + {feedback && ( +
+ {feedback} +
+ )} + + {/* Formulario Rápido de Carga */} +
+
+ + setDoc(e.target.value)} + style={{ width: '100%', marginTop: '0.2rem' }} + /> +
+ +
+ + setApellido(e.target.value)} + style={{ width: '100%', marginTop: '0.2rem', textTransform: 'uppercase' }} + /> +
+ +
+ + setNombre(e.target.value)} + style={{ width: '100%', marginTop: '0.2rem', textTransform: 'uppercase' }} + /> +
+ +
+ + +
+ +
+ + +
+
+ + {/* Grilla de Acompañantes Cargados */} +
+ + + + + + + + + + + {/* Conductor Titular (Fila Fija Destacada) */} + + + + + + + + {/* Lista de Acompañantes */} + {integrantes.map((ing, idx) => ( + + + + + + + ))} + + {integrantes.length === 0 && ( + + + + )} + +
ROLDOCUMENTOAPELLIDO Y NOMBREACCIÓN
+ 🚗 Conductor (Titular) + {conductorDocumento || '(A completar)'}{conductorNombre || '(A completar en formulario)'} + Fijo +
+ + {ing.es_menor ? '👶 Menor' : '👤 Adulto Acompañante'} + + {ing.documento} + {ing.apellido ? `${ing.apellido}, ${ing.nombre}` : ing.nombre || '-'} + + +
+ No se han cargado acompañantes aún. Use el formulario superior o escanee sus DNI. +
+
+
+ + {/* Footer de Acciones */} +
+ + Total en vehículo: {1 + integrantes.length} persona(s) (1 Conductor + {integrantes.length} Acompañante(s)) + + +
+ + +
+
+
+ + {/* Submodal para escaneo de DNI con cámara */} + setCameraOpen(false)} + onScanSuccess={handleCameraScanSuccess} + /> +
+ ); +}; diff --git a/frontend/src/components/modals/ExitVerificationModal.tsx b/frontend/src/components/modals/ExitVerificationModal.tsx new file mode 100644 index 0000000..d55e282 --- /dev/null +++ b/frontend/src/components/modals/ExitVerificationModal.tsx @@ -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 = ({ + isOpen, + onClose, + ticket, + moduloSalidaId, + onExitConfirmed, +}) => { + const [ocupantesOriginales, setOcupantesOriginales] = useState([]); + const [verificados, setVerificados] = useState([]); + const [dniInput, setDniInput] = useState(''); + const [feedback, setFeedback] = useState<{ text: string; type: 'info' | 'success' | 'warn' | 'error' } | null>(null); + const [isLoading, setIsLoading] = useState(false); + const [isConfirming, setIsConfirming] = useState(false); + const [cameraOpen, setCameraOpen] = useState(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 ( +
+
+ {/* Cabecera del Modal */} +
+
+ 🚗 +
+

+ Verificación de Salida Vehicular e Integrantes +

+ + Ticket #{ticket.ticket_id} • Vehículo: {ticket.patente || 'Peatonal'} • Conductor:{' '} + {ticket.apellido}, {ticket.nombre} (DNI: {ticket.documento}) + +
+
+ +
+ + {/* Input Rápido de DNI y Escáner Activo */} +
+
+ ⚡ + + Lector de DNI / Documento Activo — Ingrese o escanee DNI de quienes están saliendo + +
+ +
{ + e.preventDefault(); + handleVerifyDni(dniInput); + }} + style={{ display: 'flex', gap: '0.5rem' }} + > + setDniInput(e.target.value)} + autoFocus + style={{ flex: 1, minHeight: '44px', fontWeight: 600 }} + /> + + + +
+ + {feedback && ( +
+ {feedback.text} +
+ )} +
+ + {/* Paneles Duales: Ingresaron Originales vs Verificados para Salir */} +
+ {/* Panel Izquierdo: Originales */} +
+
+

+ 📋 Ingresaron con este Vehículo ({ocupantesOriginales.length}) +

+ + Quienes no verifiquen permanecerán adentro con ticket peatonal. + +
+ +
+ {isLoading ? ( +
Cargando ocupantes...
+ ) : ( +
+ {ocupantesOriginales.map((oc, idx) => { + const isVerif = pidsVerificados.has(oc.persona_id); + return ( +
+
+
+ {oc.apellido}, {oc.nombre || ''}{' '} + + (DNI: {oc.documento}) + +
+ + {oc.rol_id === 1 ? '🚗 Conductor Titular' : oc.es_menor ? '👶 Menor' : '👤 Acompañante'} + +
+ + + {isVerif ? '✅ Verificado' : '⏳ Permanece'} + +
+ ); + })} +
+ )} +
+
+ + {/* Panel Derecho: Verificados para Salir */} +
+
+

+ ✅ Personas Verificadas para Salir ({verificados.length}) +

+ + Egresan en este vehículo al abrir la barrera. + +
+ +
+
+ {verificados.map((v, idx) => ( +
+
+
+ {v.apellido}, {v.nombre || ''}{' '} + + (DNI: {v.documento}) + +
+ + {v.rol_id === 1 ? '🚗 Conductor Titular' : v.rol_nombre || 'Acompañante'} + +
+ + {v.rol_id !== 1 ? ( + + ) : ( + + Titular + + )} +
+ ))} +
+
+
+
+ + {/* Footer y Confirmación */} +
+
+
+ Total que egresan: {verificados.length} persona(s) +
+ {ocupantesQuePermanecen.length > 0 && ( +
+ ⚠️ {ocupantesQuePermanecen.length} acompañante(s) permanecerán en el predio como peatones. +
+ )} +
+ +
+ + +
+
+
+ + setCameraOpen(false)} + onScanSuccess={handleCameraScanSuccess} + /> +
+ ); +}; diff --git a/frontend/src/components/scanner/CameraScannerModal.tsx b/frontend/src/components/scanner/CameraScannerModal.tsx index dda3548..3f962ea 100644 --- a/frontend/src/components/scanner/CameraScannerModal.tsx +++ b/frontend/src/components/scanner/CameraScannerModal.tsx @@ -44,6 +44,9 @@ export const CameraScannerModal: React.FC = ({ const [selectedDeviceId, setSelectedDeviceId] = useState(''); const [activeCameraLabel, setActiveCameraLabel] = useState(''); + const isProcessingRef = useRef(false); + const decodeFrameRef = useRef<(ctx: CanvasRenderingContext2D, width: number, height: number) => Promise>(() => Promise.resolve(false)); + // Inicializar motor ZXing configurado para DNI Argentino (PDF417 + QR + Code128) useEffect(() => { const hints = new Map(); @@ -61,6 +64,12 @@ export const CameraScannerModal: React.FC = ({ // Crear canvas offscreen reutilizable const offscreenCanvas = document.createElement('canvas'); canvasRef.current = offscreenCanvas; + + return () => { + try { + reader.reset(); + } catch {} + }; }, []); const stopCamera = useCallback(() => { @@ -81,11 +90,14 @@ export const CameraScannerModal: React.FC = ({ if (videoRef.current) { videoRef.current.srcObject = null; } + isProcessingRef.current = false; + setIsProcessing(false); }, []); const handleDecodedString = useCallback( async (rawText: string) => { - if (isProcessing || !rawText) return; + if (isProcessingRef.current || !rawText) return; + isProcessingRef.current = true; setIsProcessing(true); setErrorMsg(null); try { @@ -100,15 +112,18 @@ export const CameraScannerModal: React.FC = ({ } catch (err: any) { setErrorMsg(err.message || 'Error al interpretar el código escaneado.'); } finally { + isProcessingRef.current = false; setIsProcessing(false); } }, - [isProcessing, stopCamera, onScanSuccess, onClose] + [stopCamera, onScanSuccess, onClose] ); // Decodificar un buffer ImageData mediante ZXing y BarcodeDetector const decodeFrame = useCallback( async (ctx: CanvasRenderingContext2D, width: number, height: number): Promise => { + if (isProcessingRef.current) return false; + // 1. Probar BarcodeDetector nativo si está presente en el navegador (acelerado por GPU) if ('BarcodeDetector' in window) { try { @@ -137,7 +152,11 @@ export const CameraScannerModal: React.FC = ({ return true; } } 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 = ({ [handleDecodedString] ); + // Mantener decodeFrameRef sincronizado + decodeFrameRef.current = decodeFrame; + const startCamera = useCallback( async (deviceIdToUse?: string) => { setErrorMsg(null); @@ -172,10 +194,23 @@ export const CameraScannerModal: React.FC = ({ try { let stream: MediaStream | null = null; - // Estrategia de Constraints flexible: - // Intento 1: Dispositivo seleccionado o cámara trasera - const constraints1: MediaStreamConstraints = deviceIdToUse - ? { video: { deviceId: { exact: deviceIdToUse } }, audio: false } + // Limpiar stream previo si hubiera + if (streamRef.current) { + streamRef.current.getTracks().forEach((t) => { + try { t.stop(); } catch {} + }); + streamRef.current = null; + } + + const constraints: MediaStreamConstraints = deviceIdToUse + ? { + video: { + deviceId: { exact: deviceIdToUse }, + width: { ideal: 1280 }, + height: { ideal: 720 }, + }, + audio: false, + } : { video: { facingMode: { ideal: 'environment' }, @@ -186,9 +221,9 @@ export const CameraScannerModal: React.FC = ({ }; try { - stream = await navigator.mediaDevices.getUserMedia(constraints1); + stream = await navigator.mediaDevices.getUserMedia(constraints); } catch { - // Intento 2: Fallback incondicional para webcams Windows / laptop estándar + // Fallback simple si fallaron los constraints ideales stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false, @@ -211,11 +246,16 @@ export const CameraScannerModal: React.FC = ({ } } - // Enumerar dispositivos disponibles (ahora con permisos ya otorgados) + // Enumerar dispositivos disponibles sin provocar re-renders cíclicos try { const allDevices = await navigator.mediaDevices.enumerateDevices(); 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 { // Ignorar si falla enumeración } @@ -230,7 +270,7 @@ export const CameraScannerModal: React.FC = ({ // Iniciar loop de escaneo periódico cada 200ms if (timerRef.current) window.clearInterval(timerRef.current); 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 canvas = canvasRef.current; @@ -239,13 +279,13 @@ export const CameraScannerModal: React.FC = ({ const width = video.videoWidth || 640; const height = video.videoHeight || 480; - canvas.width = width; - canvas.height = height; + if (canvas.width !== width) canvas.width = width; + if (canvas.height !== height) canvas.height = height; const ctx = canvas.getContext('2d', { willReadFrequently: true }); if (!ctx) return; ctx.drawImage(video, 0, 0, width, height); - await decodeFrame(ctx, width, height); + await decodeFrameRef.current(ctx, width, height); }, 200); } catch (err: any) { setHasCamera(false); @@ -261,7 +301,7 @@ export const CameraScannerModal: React.FC = ({ } } }, - [decodeFrame, isProcessing] + [] ); // Manejador de captura de foto nativa (funciona sin HTTPS en tablets Android) diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index abd10b8..cc412c0 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -2,8 +2,18 @@ import React from 'react'; import ReactDOM from 'react-dom/client'; 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( ); + diff --git a/frontend/src/styles/base.css b/frontend/src/styles/base.css index f8c31b6..8cda522 100644 --- a/frontend/src/styles/base.css +++ b/frontend/src/styles/base.css @@ -282,3 +282,34 @@ button:disabled, .btn:disabled, .touch-button:disabled { ::-webkit-scrollbar-thumb:hover { 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; + } +} + diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 5a192c3..2a58c27 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -49,12 +49,32 @@ export interface EntryFormData { 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 { ticket_id: number; modulo_salida_id: number; persona_id?: number; patente_salida?: string; abrir_barrera: boolean; + personas_ids_permanecen?: number[]; + integrantes_verificados?: Companion[]; } export interface ActiveTicket { diff --git a/frontend/src/views/ControlPostView.tsx b/frontend/src/views/ControlPostView.tsx index 153f80a..5f97232 100644 --- a/frontend/src/views/ControlPostView.tsx +++ b/frontend/src/views/ControlPostView.tsx @@ -10,6 +10,8 @@ import { hardwareApi } from '../api/hardwareApi'; import { useWebSocket } from '../hooks/useWebSocket'; import { useTheme } from '../hooks/useTheme'; 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 { WorkstationConfig, @@ -17,8 +19,10 @@ import { EntryFormData, DNIParsedResult, LotSearchItem, + LotPermission, } from '../types'; + export const ControlPostView: React.FC = () => { const { user, workstation, logout } = useAuth(); const { theme, toggleTheme } = useTheme(); @@ -53,17 +57,48 @@ export const ControlPostView: React.FC = () => { integrantes: [], }); - // Autocompletado de Lotes + // Autocompletado y validación de Lotes const [lotSuggestions, setLotSuggestions] = useState([]); const [showLotSuggestions, setShowLotSuggestions] = useState(false); + const [lotPermission, setLotPermission] = useState(null); // Modales y Alertas const [scannerOpen, setScannerOpen] = useState(false); + const [companionsModalOpen, setCompanionsModalOpen] = useState(false); + const [exitModalOpen, setExitModalOpen] = useState(false); + const [ticketForExit, setTicketForExit] = useState(null); + const [actionSuccess, setActionSuccess] = useState(null); const [actionError, setActionError] = useState(null); const [isSubmitting, setIsSubmitting] = useState(false); const [clock, setClock] = useState(''); + // PWA y Adaptabilidad Multiorientación + const [deferredPrompt, setDeferredPrompt] = useState(null); + const [canInstallPwa, setCanInstallPwa] = useState(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 useEffect(() => { const timer = setInterval(() => { @@ -131,14 +166,24 @@ export const ControlPostView: React.FC = () => { onMessage: handleWsEvent, }); - // Búsqueda autocompletada de Lotes + // Búsqueda autocompletada y validación de Lotes (Cat 26) const handleLotSearch = async (val: string) => { - setForm((prev) => ({ ...prev, lote_codigo: val.toUpperCase() })); - if (val.trim().length >= 1) { + const cod = val.toUpperCase(); + setForm((prev) => ({ ...prev, lote_codigo: cod, lote_id: null })); + setLotPermission(null); + + if (cod.trim().length >= 1) { try { - const results = await accessApi.searchLots(val.trim()); + const results = await accessApi.searchLots(cod.trim()); setLotSuggestions(results); 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 { setLotSuggestions([]); } @@ -148,13 +193,19 @@ export const ControlPostView: React.FC = () => { } }; - const selectLot = (lot: LotSearchItem) => { + const selectLot = async (lot: LotSearchItem) => { setForm((prev) => ({ ...prev, lote_id: lot.lote_id, lote_codigo: lot.codigo, })); setShowLotSuggestions(false); + try { + const perm = await accessApi.getLotPermission(lot.lote_id); + setLotPermission(perm); + } catch { + setLotPermission(null); + } }; // Callback al escanear DNI con cámara @@ -217,6 +268,7 @@ export const ControlPostView: React.FC = () => { abrir_barrera: true, integrantes: [], }); + setLotPermission(null); loadActiveTickets(); } catch (err: any) { @@ -226,28 +278,14 @@ export const ControlPostView: React.FC = () => { } }; - // Registrar salida de un ticket activo - const handleRegisterExit = async (ticket: ActiveTicket) => { + // Abrir diálogo interactivo de verificación de salida + const handleOpenExitModal = (ticket: ActiveTicket) => { if (!selectedExitModuleId) { setActionError('Seleccione un módulo de salida para habilitar la barrera de egreso.'); return; } - - try { - 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}`); - } + setTicketForExit(ticket); + setExitModalOpen(true); }; // Apertura manual forzada de barrera @@ -374,6 +412,27 @@ export const ControlPostView: React.FC = () => { 👤 Operador: {user?.username} + {/* Botón de instalación PWA en Tablet / Móvil */} + {canInstallPwa && ( + + )} + + + + {/* ========================================================================= - Cuerpo Principal de Garita (Layout de 2 Columnas Táctil) + Cuerpo Principal de Garita (Layout Cockpit con soporte Multiorientación) ========================================================================= */}
{ COLUMNA 1: FORMULARIO DE INGRESO RÁPIDO ======================================================================= */}
{ ))}
)} + + {/* Badge de Validación de Lote (Categoría 26: Habilitado / Moroso / En Obra) */} + {lotPermission && ( +
+ + {lotPermission.estado === 'Habilitado' + ? '✅' + : lotPermission.estado === 'Restringido' + ? '⛔' + : '🚧'} + + {lotPermission.detalle} +
+ )} @@ -726,6 +862,51 @@ export const ControlPostView: React.FC = () => { + {/* Gestión de Acompañantes Múltiples (Paridad DialogoRegistroIntegrantes) */} +
+
+ + 👥 ACOMPAÑANTES ({form.integrantes.length}) + + +
+ + {form.integrantes.length > 0 ? ( +
+ {form.integrantes.map((ing, idx) => ( + + {ing.es_menor ? '👶' : '👤'} {ing.apellido || ing.documento} + + ))} +
+ ) : ( + + Solo conductor registrado. Haga clic en "+ Cargar Acompañantes" para registrar más ocupantes. + + )} +
+ {/* Switch Abrir Barrera */}
{ COLUMNA 2: TICKETS ACTIVOS Y EGRESOS DEL PREDIO ======================================================================= */}
{
); };