feat(puesto-control): paridad completa de busqueda/seleccion de lote, validaciones estrictas y control de cacheo de garita
This commit is contained in:
@@ -11,6 +11,7 @@ from app.schemas.access_schema import (
|
||||
ActiveTicketDTO,
|
||||
PersonSearchDTO,
|
||||
LotSearchDTO,
|
||||
LotResidentDTO,
|
||||
LotPermissionDTO,
|
||||
TicketOccupantDTO,
|
||||
PersonPoliciesDTO,
|
||||
@@ -122,6 +123,15 @@ def validar_permiso_lote(
|
||||
return AccessService.obtener_permiso_lote(lote_id, persona_id)
|
||||
|
||||
|
||||
@router.get("/lots/{lote_id}/residents", response_model=List[LotResidentDTO], summary="Listar padrón de residentes de un lote")
|
||||
def listar_residentes_lote(
|
||||
lote_id: int,
|
||||
current_user: dict = Depends(obtener_usuario_actual),
|
||||
):
|
||||
"""Retorna el padrón de residentes y teléfonos asignados al lote (LotPer JOIN Per)."""
|
||||
return AccessService.obtener_residentes_lote(lote_id)
|
||||
|
||||
|
||||
@router.get("/tickets/{ticket_id}/occupants", response_model=List[TicketOccupantDTO], summary="Listar ocupantes de un ticket")
|
||||
def listar_ocupantes_ticket(
|
||||
ticket_id: int,
|
||||
|
||||
@@ -435,7 +435,8 @@ class AccessRepository:
|
||||
COALESCE(p.Nombre, '') AS Nombre,
|
||||
COALESCE(d.Documento, '') AS Documento,
|
||||
pat.Valor AS Patente,
|
||||
lot.Valor AS LoteCodigo
|
||||
lot.Valor AS LoteCodigo,
|
||||
COALESCE(cch.Valor, '0') AS CacheoSalida
|
||||
FROM tck t
|
||||
LEFT JOIN mdl m ON t.ModuloIngresoID = m.ModuloID
|
||||
LEFT JOIN tckper tp ON t.TicketID = tp.TicketID
|
||||
@@ -443,6 +444,7 @@ class AccessRepository:
|
||||
LEFT JOIN PerDocCatVal d ON p.PersonaID = d.PersonaID
|
||||
LEFT JOIN tckprx pat ON t.TicketID = pat.TicketID AND pat.PropiedadID = 4
|
||||
LEFT JOIN tckprx lot ON t.TicketID = lot.TicketID AND lot.PropiedadID = 7
|
||||
LEFT JOIN tckprx cch ON t.TicketID = cch.TicketID AND cch.PropiedadID = 6
|
||||
ORDER BY t.FechaHoraIngreso DESC
|
||||
"""
|
||||
with db_session() as conn:
|
||||
@@ -503,18 +505,136 @@ class AccessRepository:
|
||||
return cursor.fetchall()
|
||||
|
||||
@staticmethod
|
||||
def buscar_lotes_predictivo(term: str) -> List[Dict[str, Any]]:
|
||||
"""Búsqueda predictiva de lotes por código."""
|
||||
patron = f"%{term.strip()}%"
|
||||
def buscar_lote_por_codigo(codigo: str) -> Optional[Dict[str, Any]]:
|
||||
"""Busca un lote por coincidencia exacta o normalizada de código/número o LoteID."""
|
||||
query = """
|
||||
SELECT TOP 15 l.LoteID, l.Lote AS Codigo
|
||||
SELECT TOP 1 l.LoteID, l.Lote AS Codigo
|
||||
FROM lot l
|
||||
WHERE l.Lote LIKE %s
|
||||
ORDER BY l.Lote
|
||||
WHERE UPPER(LTRIM(RTRIM(l.Lote))) = UPPER(%s)
|
||||
OR (ISNUMERIC(%s) = 1 AND l.LoteID = CAST(%s AS INT))
|
||||
"""
|
||||
with db_session() as conn:
|
||||
cursor = conn.cursor(as_dict=True)
|
||||
cursor.execute(query, (patron,))
|
||||
cod_clean = codigo.strip()
|
||||
cursor.execute(query, (cod_clean, cod_clean, cod_clean))
|
||||
return cursor.fetchone()
|
||||
|
||||
@staticmethod
|
||||
def buscar_lotes_predictivo(term: str) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Búsqueda completa de lotes por número, UF, calle o residentes asociados.
|
||||
Padrón enriquecido y ponderado idéntico a DialogoBuscarLote (pct_dialogs.py).
|
||||
"""
|
||||
f_clean = term.strip() if term else ""
|
||||
if not f_clean:
|
||||
query = """
|
||||
SELECT TOP 50
|
||||
l.LoteID,
|
||||
l.Lote AS Codigo,
|
||||
l.UF,
|
||||
l.Calle,
|
||||
l.Numero,
|
||||
COALESCE(
|
||||
(SELECT TOP 1 cv.Nombre FROM LotCatVal lcv JOIN CatVal cv ON lcv.ValorID = cv.ValorID AND cv.CategoriaID = 26 WHERE lcv.LoteID = l.LoteID),
|
||||
'Habilitado'
|
||||
) AS Estado,
|
||||
(
|
||||
SELECT TOP 1 CONCAT(p.Apellido, ', ', p.Nombre)
|
||||
FROM LotPer lp
|
||||
JOIN Per p ON lp.PersonaID = p.PersonaID
|
||||
WHERE lp.LoteID = l.LoteID
|
||||
ORDER BY lp.PerfilID
|
||||
) AS Propietario
|
||||
FROM lot l
|
||||
ORDER BY
|
||||
CASE WHEN ISNUMERIC(l.Lote) = 1 THEN 1 ELSE 2 END,
|
||||
CASE WHEN ISNUMERIC(l.Lote) = 1 THEN CAST(l.Lote AS INT) ELSE 0 END,
|
||||
l.Lote
|
||||
"""
|
||||
params = ()
|
||||
else:
|
||||
f_exact = f_clean
|
||||
f_start = f"{f_clean}%"
|
||||
f_contains = f"%{f_clean}%"
|
||||
query = """
|
||||
SELECT TOP 50
|
||||
l.LoteID,
|
||||
l.Lote AS Codigo,
|
||||
l.UF,
|
||||
l.Calle,
|
||||
l.Numero,
|
||||
COALESCE(
|
||||
(SELECT TOP 1 cv.Nombre FROM LotCatVal lcv JOIN CatVal cv ON lcv.ValorID = cv.ValorID AND cv.CategoriaID = 26 WHERE lcv.LoteID = l.LoteID),
|
||||
'Habilitado'
|
||||
) AS Estado,
|
||||
(
|
||||
SELECT TOP 1 CONCAT(p.Apellido, ', ', p.Nombre)
|
||||
FROM LotPer lp
|
||||
JOIN Per p ON lp.PersonaID = p.PersonaID
|
||||
WHERE lp.LoteID = l.LoteID
|
||||
ORDER BY lp.PerfilID
|
||||
) AS Propietario
|
||||
FROM lot l
|
||||
WHERE l.Lote LIKE %s OR l.Calle LIKE %s OR l.UF LIKE %s
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM LotPer lp
|
||||
JOIN Per p ON lp.PersonaID = p.PersonaID
|
||||
WHERE lp.LoteID = l.LoteID
|
||||
AND (p.Nombre LIKE %s OR p.Apellido LIKE %s)
|
||||
)
|
||||
ORDER BY
|
||||
CASE
|
||||
WHEN UPPER(LTRIM(RTRIM(l.Lote))) = UPPER(%s) THEN 1
|
||||
WHEN UPPER(LTRIM(RTRIM(l.UF))) = UPPER(%s) THEN 2
|
||||
WHEN UPPER(l.Lote) LIKE UPPER(%s) THEN 3
|
||||
WHEN UPPER(l.UF) LIKE UPPER(%s) THEN 4
|
||||
WHEN UPPER(l.Lote) LIKE UPPER(%s) THEN 5
|
||||
WHEN UPPER(l.Calle) LIKE UPPER(%s) THEN 6
|
||||
ELSE 7
|
||||
END,
|
||||
CASE WHEN ISNUMERIC(l.Lote) = 1 THEN 1 ELSE 2 END,
|
||||
CASE WHEN ISNUMERIC(l.Lote) = 1 THEN CAST(l.Lote AS INT) ELSE 0 END,
|
||||
l.Lote
|
||||
"""
|
||||
params = (
|
||||
f_contains, f_contains, f_contains, f_contains, f_contains,
|
||||
f_exact, f_exact, f_start, f_start, f_contains, f_contains
|
||||
)
|
||||
|
||||
with db_session() as conn:
|
||||
cursor = conn.cursor(as_dict=True)
|
||||
cursor.execute(query, params)
|
||||
return cursor.fetchall()
|
||||
|
||||
@staticmethod
|
||||
def obtener_residentes_lote(lote_id: int) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Obtiene el padrón de residentes y teléfonos vinculados a un lote (LotPer JOIN Per).
|
||||
Paridad exacta con pct_repository.py:1752.
|
||||
"""
|
||||
query = """
|
||||
SELECT TOP 100
|
||||
p.PersonaID,
|
||||
p.Apellido,
|
||||
p.Nombre,
|
||||
(SELECT TOP 1 pd.Documento FROM PerDocCatVal pd WHERE pd.PersonaID = p.PersonaID) AS Documento,
|
||||
COALESCE(pr.Nombre, 'Residente') AS Perfil,
|
||||
COALESCE(c.Nombre, 'Activo') AS Estado,
|
||||
(
|
||||
SELECT STRING_AGG(pt.Telefono, ' / ')
|
||||
FROM PerTelCatVal pt
|
||||
WHERE pt.PersonaID = p.PersonaID
|
||||
) AS Telefonos
|
||||
FROM LotPer lp
|
||||
JOIN Per p ON lp.PersonaID = p.PersonaID
|
||||
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
|
||||
ORDER BY p.Apellido, p.Nombre
|
||||
"""
|
||||
with db_session() as conn:
|
||||
cursor = conn.cursor(as_dict=True)
|
||||
cursor.execute(query, (lote_id,))
|
||||
return cursor.fetchall()
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -29,7 +29,8 @@ class EntryRequest(BaseModel):
|
||||
entidad: Optional[str] = None
|
||||
cantidad_ocupantes: int = Field(1, ge=1)
|
||||
cantidad_menores: int = Field(0, ge=0)
|
||||
cacheo_salida: bool = False
|
||||
cacheo_salida: bool = True
|
||||
baul_inspeccionado: bool = False
|
||||
abrir_barrera: bool = True
|
||||
foto_evidencia_b64: Optional[str] = None
|
||||
integrantes: List[CompanionDTO] = Field(default_factory=list)
|
||||
@@ -136,6 +137,7 @@ class ActiveTicketDTO(BaseModel):
|
||||
modulo_ingreso: str
|
||||
fecha_ingreso: str
|
||||
ocupantes: int = 1
|
||||
cacheo_salida: bool = False
|
||||
|
||||
|
||||
class PersonSearchDTO(BaseModel):
|
||||
@@ -150,9 +152,23 @@ class PersonSearchDTO(BaseModel):
|
||||
class LotSearchDTO(BaseModel):
|
||||
lote_id: int
|
||||
codigo: str
|
||||
uf: Optional[str] = None
|
||||
calle: Optional[str] = None
|
||||
numero: Optional[str] = None
|
||||
estado: Optional[str] = "Habilitado"
|
||||
propietario: Optional[str] = None
|
||||
|
||||
|
||||
class LotResidentDTO(BaseModel):
|
||||
persona_id: int
|
||||
apellido: str
|
||||
nombre: str
|
||||
documento: Optional[str] = None
|
||||
perfil: str = "Residente"
|
||||
estado: str = "Activo"
|
||||
telefonos: Optional[str] = None
|
||||
|
||||
|
||||
class MovementHistoryDTO(BaseModel):
|
||||
mvt_hist_id: int
|
||||
ticket_id: int
|
||||
|
||||
@@ -13,6 +13,7 @@ from app.schemas.access_schema import (
|
||||
LotSearchDTO,
|
||||
PersonPoliciesDTO,
|
||||
VehicleDetailsDTO,
|
||||
LotResidentDTO,
|
||||
)
|
||||
from app.repositories.access_repository import AccessRepository
|
||||
from app.services.hardware_service import HardwareService
|
||||
@@ -48,11 +49,18 @@ class AccessService:
|
||||
detail="Falta el nombre de la persona (campo obligatorio).",
|
||||
)
|
||||
|
||||
# 3. Validar Lote de Destino
|
||||
if not req.lote_id and not (req.lote_codigo and req.lote_codigo.strip()):
|
||||
# 3. Validar Lote de Destino (Paridad estricta pct_view.py:3183 `if self.lote_id <= 0: return False`)
|
||||
if not req.lote_id or req.lote_id <= 0:
|
||||
if req.lote_codigo and req.lote_codigo.strip():
|
||||
lote_encontrado = AccessRepository.buscar_lote_por_codigo(req.lote_codigo.strip())
|
||||
if lote_encontrado:
|
||||
req.lote_id = lote_encontrado["LoteID"]
|
||||
elif req.lote_codigo.strip().isdigit() and int(req.lote_codigo.strip()) > 0:
|
||||
req.lote_id = int(req.lote_codigo.strip())
|
||||
if not req.lote_id or req.lote_id <= 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Falta seleccionar el lote de destino.",
|
||||
detail="Falta Seleccionar Lote de Destino (obligatorio según normativa de guardia).",
|
||||
)
|
||||
|
||||
# 4. Validar restricción del lote (Categoría 26 en LotCatVal)
|
||||
@@ -136,6 +144,11 @@ class AccessService:
|
||||
# 9. Generación del TicketID
|
||||
ticket_id = AccessRepository.generar_ticket_id()
|
||||
|
||||
# Inspección de baúl en garita (Paridad pct_view.py:2739)
|
||||
if getattr(req, 'baul_inspeccionado', False) and es_conductor:
|
||||
if "[BAUL INSPECCIONADO - OK]" not in (req.motivo or ""):
|
||||
req.motivo = f"{(req.motivo or '').strip()} [BAUL INSPECCIONADO - OK]".strip()
|
||||
|
||||
# 10. Registro transaccional en base de datos
|
||||
AccessRepository.registrar_ticket_ingreso(req, persona_id, ticket_id)
|
||||
|
||||
@@ -227,6 +240,23 @@ class AccessService:
|
||||
"""Verifica restricciones de lote (Cat 26) y relación de persona (LotPer)."""
|
||||
return AccessRepository.obtener_permiso_lote(lote_id, persona_id)
|
||||
|
||||
@staticmethod
|
||||
def obtener_residentes_lote(lote_id: int) -> List[LotResidentDTO]:
|
||||
"""Obtiene el padrón de residentes y teléfonos vinculados a un lote (LotPer JOIN Per)."""
|
||||
filas = AccessRepository.obtener_residentes_lote(lote_id)
|
||||
return [
|
||||
LotResidentDTO(
|
||||
persona_id=int(r.get("PersonaID") or r.get("persona_id") or 0),
|
||||
apellido=str(r.get("Apellido") or r.get("apellido") or "").strip(),
|
||||
nombre=str(r.get("Nombre") or r.get("nombre") or "").strip(),
|
||||
documento=str(r.get("Documento") or r.get("documento") or "").strip(),
|
||||
perfil=str(r.get("Perfil") or r.get("perfil") or "Residente").strip(),
|
||||
estado=str(r.get("Estado") or r.get("estado") or "Activo").strip(),
|
||||
telefonos=str(r.get("Telefonos") or r.get("telefonos") or "").strip() or None,
|
||||
)
|
||||
for r in filas
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def obtener_ocupantes_ticket(ticket_id: int) -> list:
|
||||
"""Obtiene la lista de ocupantes (conductor y acompañantes) vinculados a un ticket."""
|
||||
@@ -253,6 +283,7 @@ class AccessService:
|
||||
modulo_ingreso=str(f.get("ModuloIngreso") or "Módulo Desconocido"),
|
||||
fecha_ingreso=f_ing_str,
|
||||
ocupantes=1,
|
||||
cacheo_salida=str(f.get("CacheoSalida") or "0") == "1",
|
||||
)
|
||||
)
|
||||
return resultado
|
||||
|
||||
@@ -386,12 +386,18 @@ async def test_verificaciones_peaton_vs_conductor_hardware_pulse(monkeypatch):
|
||||
|
||||
from app.services.hardware_service import HardwareService
|
||||
|
||||
import time
|
||||
suffix = str(int(time.time()))[-5:]
|
||||
doc_mol = f"81{suffix}1"
|
||||
doc_bar = f"81{suffix}2"
|
||||
doc_cnd = f"81{suffix}3"
|
||||
|
||||
# Caso 1: Peatón en Molinete Club (100004 -> tipo_acceso=7)
|
||||
res_peaton_molinete = await client.post(
|
||||
"/api/v1/access/entry",
|
||||
json={
|
||||
"modulo_ingreso_id": 100004,
|
||||
"documento": "88771122",
|
||||
"documento": doc_mol,
|
||||
"nombre": "PEATON MOLINETE",
|
||||
"lote_codigo": "100",
|
||||
"tipo_ingreso": "PEATON",
|
||||
@@ -422,7 +428,7 @@ async def test_verificaciones_peaton_vs_conductor_hardware_pulse(monkeypatch):
|
||||
"/api/v1/access/entry",
|
||||
json={
|
||||
"modulo_ingreso_id": 100004,
|
||||
"documento": "88771133",
|
||||
"documento": doc_bar,
|
||||
"nombre": "PEATON BARRERA",
|
||||
"lote_codigo": "100",
|
||||
"tipo_ingreso": "PEATON",
|
||||
@@ -455,7 +461,7 @@ async def test_verificaciones_peaton_vs_conductor_hardware_pulse(monkeypatch):
|
||||
"/api/v1/access/entry",
|
||||
json={
|
||||
"modulo_ingreso_id": 100004,
|
||||
"documento": "88771144",
|
||||
"documento": doc_cnd,
|
||||
"nombre": "CONDUCTOR BARRERA",
|
||||
"lote_codigo": "100",
|
||||
"tipo_ingreso": "CONDUCTOR",
|
||||
@@ -484,4 +490,88 @@ async def test_verificaciones_peaton_vs_conductor_hardware_pulse(monkeypatch):
|
||||
assert exit_cond.json()["barrier_opened"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lote_residents_and_cacheo_garita():
|
||||
"""
|
||||
Verifica las capacidades del buscador de lotes y el sistema de cacheo de garita:
|
||||
1. Consulta de padrón de residentes del lote (GET /api/v1/access/lots/{id}/residents).
|
||||
2. Validación obligatoria de lote (rechazo 422 si lote_id <= 0).
|
||||
3. Registro de ingreso vehicular con flags de Cacheo a la Salida e Inspección de Baúl.
|
||||
4. Comprobación de que el ticket activo conserva cacheo_salida=True.
|
||||
"""
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
login_res = await client.post(
|
||||
"/api/v1/auth/login",
|
||||
json={"username": "guardia", "password": "guardia"},
|
||||
)
|
||||
token = login_res.cookies.get("access_token")
|
||||
|
||||
# 1. Padrón de residentes de un lote
|
||||
res_padron = await client.get(
|
||||
"/api/v1/access/lots/100000/residents",
|
||||
cookies={"access_token": token},
|
||||
)
|
||||
assert res_padron.status_code == 200
|
||||
assert isinstance(res_padron.json(), list)
|
||||
|
||||
# 2. Validación obligatoria de lote
|
||||
res_sin_lote = await client.post(
|
||||
"/api/v1/access/entry",
|
||||
json={
|
||||
"modulo_ingreso_id": 100004,
|
||||
"documento": "99112233",
|
||||
"nombre": "SIN LOTE",
|
||||
"tipo_ingreso": "PEATON",
|
||||
"lote_id": 0,
|
||||
"lote_codigo": "",
|
||||
},
|
||||
cookies={"access_token": token},
|
||||
)
|
||||
assert res_sin_lote.status_code == 422
|
||||
assert "lote" in res_sin_lote.json()["detail"].lower()
|
||||
|
||||
# 3. Registro con cacheo y baúl inspeccionado
|
||||
import time
|
||||
doc_cch = f"95{str(int(time.time()))[-5:]}"
|
||||
res_cch = await client.post(
|
||||
"/api/v1/access/entry",
|
||||
json={
|
||||
"modulo_ingreso_id": 100004,
|
||||
"documento": doc_cch,
|
||||
"apellido": "GARCIA",
|
||||
"nombre": "IGNACIO",
|
||||
"lote_id": 100000,
|
||||
"tipo_ingreso": "CONDUCTOR",
|
||||
"patente": "CACH01",
|
||||
"cacheo_salida": True,
|
||||
"baul_inspeccionado": True,
|
||||
"abrir_barrera": True,
|
||||
},
|
||||
cookies={"access_token": token},
|
||||
)
|
||||
assert res_cch.status_code == 200
|
||||
tck_id = res_cch.json()["ticket_id"]
|
||||
|
||||
# 4. Validar en tickets activos
|
||||
act_res = await client.get("/api/v1/access/tickets/active", cookies={"access_token": token})
|
||||
assert act_res.status_code == 200
|
||||
tickets = act_res.json()
|
||||
encontrado = next((t for t in tickets if t["ticket_id"] == tck_id), None)
|
||||
assert encontrado is not None
|
||||
assert encontrado["cacheo_salida"] is True
|
||||
|
||||
# Egresar
|
||||
await client.post(
|
||||
"/api/v1/access/exit",
|
||||
json={
|
||||
"ticket_id": tck_id,
|
||||
"modulo_salida_id": 100005,
|
||||
"patente_salida": "CACH01",
|
||||
"tipo_salida": "CONDUCTOR",
|
||||
},
|
||||
cookies={"access_token": token},
|
||||
)
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -64,6 +64,12 @@ export const accessApi = {
|
||||
});
|
||||
},
|
||||
|
||||
getLotResidents: (loteId: number) => {
|
||||
return request<import('../types').LotResident[]>(`/access/lots/${loteId}/residents`, {
|
||||
method: 'GET',
|
||||
});
|
||||
},
|
||||
|
||||
getTicketOccupants: (ticketId: number) => {
|
||||
return request<any[]>(`/access/tickets/${ticketId}/occupants`, {
|
||||
method: 'GET',
|
||||
|
||||
@@ -256,6 +256,30 @@ export const ExitVerificationModal: React.FC<ExitVerificationModalProps> = ({
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Alerta de Cacheo Obligatorio de Salida / Baúl (Requisito de Seguridad) */}
|
||||
{ticket.cacheo_salida && (
|
||||
<div
|
||||
style={{
|
||||
padding: '0.65rem 1.25rem',
|
||||
backgroundColor: 'rgba(239, 68, 68, 0.14)',
|
||||
borderBottom: '1px solid var(--status-danger)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '0.65rem',
|
||||
}}
|
||||
>
|
||||
<span style={{ fontSize: '1.25rem' }}>🚨</span>
|
||||
<div>
|
||||
<strong style={{ color: 'var(--status-danger)', fontSize: '0.85rem' }}>
|
||||
CONTROL DE GUARDIA: CACHEO A LA SALIDA OBLIGATORIO
|
||||
</strong>
|
||||
<div style={{ fontSize: '0.78rem', color: 'var(--text-primary)' }}>
|
||||
Este vehículo tiene registrado cacheo obligatorio al egresar. Inspeccione el baúl y habitáculo antes de autorizar la apertura.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Input Rápido de DNI y Escáner Activo */}
|
||||
<div
|
||||
style={{
|
||||
|
||||
@@ -0,0 +1,503 @@
|
||||
// ==============================================================================
|
||||
// Modal de Búsqueda y Selección de Lotes con Padrón de Residentes
|
||||
// Paridad 1:1 con DialogoBuscarLote (pct_dialogs.py - OemspotPySYS / OneverAccess)
|
||||
// ==============================================================================
|
||||
import React, { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { LotSearchItem, LotResident, LotPermission } from '../../types';
|
||||
import { accessApi } from '../../api/accessApi';
|
||||
|
||||
interface LotSearchModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSelectLot: (lote: LotSearchItem, permission?: LotPermission | null) => void;
|
||||
selectedLotId?: number | null;
|
||||
}
|
||||
|
||||
export const LotSearchModal: React.FC<LotSearchModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSelectLot,
|
||||
selectedLotId,
|
||||
}) => {
|
||||
const [query, setQuery] = useState<string>('');
|
||||
const [lotes, setLotes] = useState<LotSearchItem[]>([]);
|
||||
const [isLoadingLotes, setIsLoadingLotes] = useState<boolean>(false);
|
||||
const [selectedLot, setSelectedLot] = useState<LotSearchItem | null>(null);
|
||||
|
||||
const [residentes, setResidentes] = useState<LotResident[]>([]);
|
||||
const [isLoadingResidentes, setIsLoadingResidentes] = useState<boolean>(false);
|
||||
const [lotPermission, setLotPermission] = useState<LotPermission | null>(null);
|
||||
|
||||
const searchTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const loadLotes = useCallback(async (searchTerm: string) => {
|
||||
setIsLoadingLotes(true);
|
||||
try {
|
||||
const data = await accessApi.searchLots(searchTerm);
|
||||
setLotes(data);
|
||||
// Si hay un lote seleccionado actualmente, preservarlo o seleccionar el primero
|
||||
if (data.length > 0) {
|
||||
if (selectedLotId) {
|
||||
const match = data.find((l) => l.lote_id === selectedLotId);
|
||||
if (match) {
|
||||
setSelectedLot(match);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Si no había seleccionado o no se encontró, seleccionar el primero
|
||||
setSelectedLot((prev) => (prev ? (data.find((l) => l.lote_id === prev.lote_id) || data[0]) : data[0]));
|
||||
} else {
|
||||
setSelectedLot(null);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error al cargar lotes:', e);
|
||||
setLotes([]);
|
||||
setSelectedLot(null);
|
||||
} finally {
|
||||
setIsLoadingLotes(false);
|
||||
}
|
||||
}, [selectedLotId]);
|
||||
|
||||
// Al abrir el modal, cargar inicialmente
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
loadLotes('');
|
||||
} else {
|
||||
setQuery('');
|
||||
setResidentes([]);
|
||||
setLotPermission(null);
|
||||
}
|
||||
}, [isOpen, loadLotes]);
|
||||
|
||||
// Debounce en el input de búsqueda
|
||||
const handleQueryChange = (text: string) => {
|
||||
setQuery(text);
|
||||
if (searchTimerRef.current) {
|
||||
clearTimeout(searchTimerRef.current);
|
||||
}
|
||||
searchTimerRef.current = setTimeout(() => {
|
||||
loadLotes(text);
|
||||
}, 250);
|
||||
};
|
||||
|
||||
// Al cambiar el lote seleccionado, cargar sus residentes y permiso
|
||||
useEffect(() => {
|
||||
if (!selectedLot) {
|
||||
setResidentes([]);
|
||||
setLotPermission(null);
|
||||
return;
|
||||
}
|
||||
|
||||
let isMounted = true;
|
||||
setIsLoadingResidentes(true);
|
||||
|
||||
Promise.all([
|
||||
accessApi.getLotResidents(selectedLot.lote_id),
|
||||
accessApi.getLotPermission(selectedLot.lote_id).catch(() => null),
|
||||
])
|
||||
.then(([resData, permData]) => {
|
||||
if (isMounted) {
|
||||
setResidentes(resData);
|
||||
setLotPermission(permData);
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error('Error al cargar datos del lote:', e);
|
||||
if (isMounted) {
|
||||
setResidentes([]);
|
||||
setLotPermission(null);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (isMounted) setIsLoadingResidentes(false);
|
||||
});
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, [selectedLot]);
|
||||
|
||||
const handleConfirm = (loteToConfirm?: LotSearchItem) => {
|
||||
const target = loteToConfirm || selectedLot;
|
||||
if (target) {
|
||||
onSelectLot(target, lotPermission);
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.75)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
zIndex: 1100,
|
||||
padding: '0.75rem',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: '100%',
|
||||
maxWidth: '920px',
|
||||
maxHeight: '92vh',
|
||||
backgroundColor: 'var(--bg-card)',
|
||||
borderRadius: 'var(--radius-lg)',
|
||||
boxShadow: 'var(--shadow-xl)',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
overflow: 'hidden',
|
||||
border: '1px solid var(--border-subtle)',
|
||||
}}
|
||||
>
|
||||
{/* 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>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
|
||||
<span style={{ fontSize: '1.3rem' }}>🏘️</span>
|
||||
<h2 style={{ margin: 0, fontSize: '1.15rem', fontWeight: 700, color: 'var(--text-primary)' }}>
|
||||
Buscador de Lotes y Padrón de Residentes
|
||||
</h2>
|
||||
</div>
|
||||
<div style={{ fontSize: '0.8rem', color: 'var(--text-secondary)', marginTop: '0.2rem' }}>
|
||||
Consulte el padrón de propietarios, residentes y teléfonos de contacto para autorizar el ingreso.
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
style={{
|
||||
background: 'transparent',
|
||||
border: 'none',
|
||||
fontSize: '1.4rem',
|
||||
color: 'var(--text-secondary)',
|
||||
cursor: 'pointer',
|
||||
padding: '0.25rem 0.5rem',
|
||||
}}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Barra de Filtro de Búsqueda */}
|
||||
<div style={{ padding: '0.85rem 1.25rem', borderBottom: '1px solid var(--border-subtle)', display: 'flex', gap: '0.5rem' }}>
|
||||
<div style={{ position: 'relative', flex: 1 }}>
|
||||
<input
|
||||
type="text"
|
||||
className="input-touch"
|
||||
autoFocus
|
||||
placeholder="🔍 Buscar por número de lote, UF, residente o calle..."
|
||||
value={query}
|
||||
onChange={(e) => handleQueryChange(e.target.value)}
|
||||
style={{ width: '100%', minHeight: '44px', paddingLeft: '1rem', fontSize: '0.95rem' }}
|
||||
/>
|
||||
{query && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setQuery('');
|
||||
loadLotes('');
|
||||
}}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
right: '10px',
|
||||
top: '50%',
|
||||
transform: 'translateY(-50%)',
|
||||
background: 'transparent',
|
||||
border: 'none',
|
||||
fontSize: '1rem',
|
||||
color: 'var(--text-secondary)',
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
onClick={() => loadLotes(query)}
|
||||
style={{ minHeight: '44px', padding: '0 1.25rem', fontWeight: 600 }}
|
||||
>
|
||||
Buscar
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Cuerpo Principal Dividido: Panel Superior de Lotes + Panel Inferior de Residentes */}
|
||||
<div style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: '0.75rem', padding: '1rem 1.25rem' }}>
|
||||
{/* 1. SECCIÓN: LOTES ENCONTRADOS */}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.35rem' }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<span style={{ fontSize: '0.8rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase' }}>
|
||||
Lotes Registrados ({lotes.length}) {isLoadingLotes && '• Cargando...'}
|
||||
</span>
|
||||
<span style={{ fontSize: '0.75rem', color: 'var(--text-muted)' }}>
|
||||
Tocar para seleccionar • Doble toque para confirmar
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
maxHeight: '180px',
|
||||
overflowY: 'auto',
|
||||
border: '1px solid var(--border-subtle)',
|
||||
borderRadius: 'var(--radius-sm)',
|
||||
backgroundColor: 'var(--bg-app)',
|
||||
}}
|
||||
>
|
||||
{lotes.length === 0 && !isLoadingLotes ? (
|
||||
<div style={{ padding: '1.5rem', textAlign: 'center', color: 'var(--text-secondary)', fontSize: '0.9rem' }}>
|
||||
No se encontraron lotes que coincidan con la búsqueda.
|
||||
</div>
|
||||
) : (
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', fontSize: '0.85rem' }}>
|
||||
<thead>
|
||||
<tr style={{ backgroundColor: 'var(--bg-surface)', borderBottom: '1px solid var(--border-subtle)' }}>
|
||||
<th style={{ padding: '0.5rem 0.75rem', width: '100px' }}>Lote / UF</th>
|
||||
<th style={{ padding: '0.5rem 0.75rem' }}>Calle y Ubicación</th>
|
||||
<th style={{ padding: '0.5rem 0.75rem' }}>Titular / Propietario</th>
|
||||
<th style={{ padding: '0.5rem 0.75rem', width: '130px' }}>Estado / Cat</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{lotes.map((l) => {
|
||||
const isSel = selectedLot?.lote_id === l.lote_id;
|
||||
return (
|
||||
<tr
|
||||
key={l.lote_id}
|
||||
onClick={() => setSelectedLot(l)}
|
||||
onDoubleClick={() => handleConfirm(l)}
|
||||
style={{
|
||||
cursor: 'pointer',
|
||||
backgroundColor: isSel ? 'rgba(37, 99, 235, 0.18)' : 'transparent',
|
||||
borderBottom: '1px solid var(--border-subtle)',
|
||||
fontWeight: isSel ? 700 : 400,
|
||||
borderLeft: isSel ? '4px solid var(--accent-primary)' : '4px solid transparent',
|
||||
transition: 'background 0.1s ease',
|
||||
}}
|
||||
>
|
||||
<td style={{ padding: '0.55rem 0.75rem' }}>
|
||||
<strong style={{ fontSize: '0.95rem', color: 'var(--text-primary)' }}>
|
||||
Lote {l.codigo}
|
||||
</strong>
|
||||
{l.uf && l.uf !== l.codigo && (
|
||||
<div style={{ fontSize: '0.75rem', color: 'var(--text-secondary)' }}>UF: {l.uf}</div>
|
||||
)}
|
||||
</td>
|
||||
<td style={{ padding: '0.55rem 0.75rem', color: 'var(--text-primary)' }}>
|
||||
{l.calle ? `${l.calle} ${l.numero || ''}`.trim() : 'Sin calle asignada'}
|
||||
</td>
|
||||
<td style={{ padding: '0.55rem 0.75rem', color: 'var(--text-primary)' }}>
|
||||
{l.propietario || <span style={{ color: 'var(--text-muted)' }}>-</span>}
|
||||
</td>
|
||||
<td style={{ padding: '0.55rem 0.75rem' }}>
|
||||
<span
|
||||
style={{
|
||||
display: 'inline-block',
|
||||
padding: '0.2rem 0.5rem',
|
||||
borderRadius: '4px',
|
||||
fontSize: '0.75rem',
|
||||
fontWeight: 600,
|
||||
backgroundColor:
|
||||
l.estado === 'Habilitado' || l.estado === 'Residencia Permanente'
|
||||
? 'rgba(16, 185, 129, 0.15)'
|
||||
: 'rgba(239, 68, 68, 0.15)',
|
||||
color:
|
||||
l.estado === 'Habilitado' || l.estado === 'Residencia Permanente'
|
||||
? 'var(--status-success)'
|
||||
: 'var(--status-danger)',
|
||||
}}
|
||||
>
|
||||
{l.estado || 'General'}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 2. SECCIÓN: PADRÓN DE RESIDENTES DEL LOTE SELECCIONADO */}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.35rem', flex: 1 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<span style={{ fontSize: '0.8rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase' }}>
|
||||
Padrón de Residentes del Lote {selectedLot ? `"${selectedLot.codigo}"` : ''} ({residentes.length}){' '}
|
||||
{isLoadingResidentes && '• Cargando residentes...'}
|
||||
</span>
|
||||
|
||||
{/* Badge de Permiso del Lote */}
|
||||
{lotPermission && (
|
||||
<div
|
||||
style={{
|
||||
fontSize: '0.8rem',
|
||||
fontWeight: 700,
|
||||
padding: '0.2rem 0.6rem',
|
||||
borderRadius: '4px',
|
||||
backgroundColor: lotPermission.bg_color,
|
||||
color: lotPermission.color,
|
||||
border: `1px solid ${lotPermission.color}`,
|
||||
}}
|
||||
>
|
||||
{lotPermission.estado}: {lotPermission.detalle}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
flex: 1,
|
||||
minHeight: '140px',
|
||||
maxHeight: '220px',
|
||||
overflowY: 'auto',
|
||||
border: '1px solid var(--border-subtle)',
|
||||
borderRadius: 'var(--radius-sm)',
|
||||
backgroundColor: 'var(--bg-app)',
|
||||
}}
|
||||
>
|
||||
{!selectedLot ? (
|
||||
<div style={{ padding: '1.5rem', textAlign: 'center', color: 'var(--text-secondary)', fontSize: '0.9rem' }}>
|
||||
Seleccione un lote en la grilla superior para visualizar sus residentes y teléfonos.
|
||||
</div>
|
||||
) : residentes.length === 0 && !isLoadingResidentes ? (
|
||||
<div style={{ padding: '1.5rem', textAlign: 'center', color: 'var(--text-secondary)', fontSize: '0.9rem' }}>
|
||||
No hay residentes o contactos registrados en la ficha de este lote.
|
||||
</div>
|
||||
) : (
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', fontSize: '0.85rem' }}>
|
||||
<thead>
|
||||
<tr style={{ backgroundColor: 'var(--bg-surface)', borderBottom: '1px solid var(--border-subtle)' }}>
|
||||
<th style={{ padding: '0.5rem 0.75rem' }}>Residente</th>
|
||||
<th style={{ padding: '0.5rem 0.75rem', width: '100px' }}>DNI</th>
|
||||
<th style={{ padding: '0.5rem 0.75rem', width: '130px' }}>Perfil / Relación</th>
|
||||
<th style={{ padding: '0.5rem 0.75rem' }}>Teléfonos de Contacto</th>
|
||||
<th style={{ padding: '0.5rem 0.75rem', width: '90px' }}>Estado</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{residentes.map((r) => (
|
||||
<tr key={r.persona_id} style={{ borderBottom: '1px solid var(--border-subtle)' }}>
|
||||
<td style={{ padding: '0.5rem 0.75rem', fontWeight: 600, color: 'var(--text-primary)' }}>
|
||||
{r.apellido}, {r.nombre}
|
||||
</td>
|
||||
<td style={{ padding: '0.5rem 0.75rem', color: 'var(--text-secondary)' }}>
|
||||
{r.documento || '-'}
|
||||
</td>
|
||||
<td style={{ padding: '0.5rem 0.75rem' }}>
|
||||
<span className="badge badge-info" style={{ fontSize: '0.75rem' }}>
|
||||
{r.perfil}
|
||||
</span>
|
||||
</td>
|
||||
<td style={{ padding: '0.5rem 0.75rem', color: 'var(--text-primary)' }}>
|
||||
{r.telefonos && r.telefonos !== '-' ? (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', flexWrap: 'wrap' }}>
|
||||
<span>{r.telefonos}</span>
|
||||
<a
|
||||
href={`tel:${r.telefonos.split('/')[0].trim()}`}
|
||||
style={{
|
||||
fontSize: '0.75rem',
|
||||
padding: '0.15rem 0.4rem',
|
||||
backgroundColor: 'rgba(37, 99, 235, 0.15)',
|
||||
color: 'var(--accent-primary)',
|
||||
borderRadius: '4px',
|
||||
textDecoration: 'none',
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
📞 Llamar
|
||||
</a>
|
||||
</div>
|
||||
) : (
|
||||
<span style={{ color: 'var(--text-muted)' }}>Sin teléfono</span>
|
||||
)}
|
||||
</td>
|
||||
<td style={{ padding: '0.5rem 0.75rem' }}>
|
||||
<span style={{ fontSize: '0.75rem', color: 'var(--status-success)', fontWeight: 600 }}>
|
||||
{r.estado}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Pie de Acciones del Modal */}
|
||||
<div
|
||||
style={{
|
||||
padding: '0.85rem 1.25rem',
|
||||
backgroundColor: 'var(--bg-surface)',
|
||||
borderTop: '1px solid var(--border-subtle)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
{selectedLot ? (
|
||||
<span style={{ fontSize: '0.9rem', color: 'var(--text-primary)' }}>
|
||||
Lote seleccionado:{' '}
|
||||
<strong style={{ color: 'var(--accent-primary)', fontSize: '1rem' }}>
|
||||
Lote {selectedLot.codigo}
|
||||
</strong>{' '}
|
||||
{selectedLot.calle ? `(${selectedLot.calle})` : ''}
|
||||
</span>
|
||||
) : (
|
||||
<span style={{ fontSize: '0.85rem', color: 'var(--text-muted)' }}>
|
||||
Seleccione un lote para continuar
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: '0.75rem' }}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={onClose}
|
||||
style={{ minHeight: '44px', padding: '0 1.25rem' }}
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
disabled={!selectedLot}
|
||||
onClick={() => handleConfirm()}
|
||||
style={{
|
||||
minHeight: '44px',
|
||||
padding: '0 1.5rem',
|
||||
fontWeight: 700,
|
||||
backgroundColor: 'var(--status-success)',
|
||||
color: '#fff',
|
||||
}}
|
||||
>
|
||||
✓ Seleccionar Lote
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -50,6 +50,7 @@ export interface EntryFormData {
|
||||
cantidad_ocupantes: number;
|
||||
cantidad_menores: number;
|
||||
cacheo_salida: boolean;
|
||||
baul_inspeccionado?: boolean;
|
||||
abrir_barrera: boolean;
|
||||
integrantes: Companion[];
|
||||
seguro_empresa?: string;
|
||||
@@ -142,6 +143,7 @@ export interface ActiveTicket {
|
||||
modulo_ingreso: string;
|
||||
fecha_ingreso: string;
|
||||
ocupantes: number;
|
||||
cacheo_salida?: boolean;
|
||||
}
|
||||
|
||||
export interface PersonSearchItem {
|
||||
@@ -155,9 +157,23 @@ export interface PersonSearchItem {
|
||||
export interface LotSearchItem {
|
||||
lote_id: number;
|
||||
codigo: string;
|
||||
uf?: string | null;
|
||||
calle?: string | null;
|
||||
numero?: string | null;
|
||||
estado?: string | null;
|
||||
propietario?: string | null;
|
||||
}
|
||||
|
||||
export interface LotResident {
|
||||
persona_id: number;
|
||||
apellido: string;
|
||||
nombre: string;
|
||||
documento?: string | null;
|
||||
perfil: string;
|
||||
estado: string;
|
||||
telefonos?: string | null;
|
||||
}
|
||||
|
||||
export interface DNIParsedResult {
|
||||
valido: boolean;
|
||||
documento: string;
|
||||
|
||||
@@ -12,6 +12,7 @@ import { useTheme } from '../hooks/useTheme';
|
||||
import { CameraScannerModal } from '../components/scanner/CameraScannerModal';
|
||||
import { CompanionsRegistrationModal } from '../components/modals/CompanionsRegistrationModal';
|
||||
import { ExitVerificationModal } from '../components/modals/ExitVerificationModal';
|
||||
import { LotSearchModal } from '../components/modals/LotSearchModal';
|
||||
import { APP_VERSION, APP_BUILD } from '../version';
|
||||
import {
|
||||
WorkstationConfig,
|
||||
@@ -54,7 +55,8 @@ export const ControlPostView: React.FC = () => {
|
||||
entidad: '',
|
||||
cantidad_ocupantes: 1,
|
||||
cantidad_menores: 0,
|
||||
cacheo_salida: false,
|
||||
cacheo_salida: true,
|
||||
baul_inspeccionado: false,
|
||||
abrir_barrera: true,
|
||||
integrantes: [],
|
||||
seguro_empresa: '',
|
||||
@@ -77,10 +79,9 @@ export const ControlPostView: React.FC = () => {
|
||||
const [confirmRestrictedModal, setConfirmRestrictedModal] = useState<boolean>(false);
|
||||
|
||||
|
||||
// Autocompletado y validación de Lotes
|
||||
const [lotSuggestions, setLotSuggestions] = useState<LotSearchItem[]>([]);
|
||||
const [showLotSuggestions, setShowLotSuggestions] = useState<boolean>(false);
|
||||
// Validación y selección de Lotes
|
||||
const [lotPermission, setLotPermission] = useState<LotPermission | null>(null);
|
||||
const [isLotModalOpen, setIsLotModalOpen] = useState<boolean>(false);
|
||||
|
||||
// Modales y Alertas
|
||||
const [scannerOpen, setScannerOpen] = useState<boolean>(false);
|
||||
@@ -186,46 +187,37 @@ export const ControlPostView: React.FC = () => {
|
||||
onMessage: handleWsEvent,
|
||||
});
|
||||
|
||||
// Búsqueda autocompletada y validación de Lotes (Cat 26)
|
||||
const handleLotSearch = async (val: string) => {
|
||||
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(cod.trim());
|
||||
setLotSuggestions(results);
|
||||
setShowLotSuggestions(true);
|
||||
const selectLot = async (lot: LotSearchItem, preloadedPermission?: LotPermission | null) => {
|
||||
const displayName = lot.calle
|
||||
? `Lote ${lot.codigo} - ${lot.calle} ${lot.numero || ''}`.trim()
|
||||
: `Lote ${lot.codigo}`;
|
||||
|
||||
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([]);
|
||||
}
|
||||
} else {
|
||||
setLotSuggestions([]);
|
||||
setShowLotSuggestions(false);
|
||||
}
|
||||
};
|
||||
|
||||
const selectLot = async (lot: LotSearchItem) => {
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
lote_id: lot.lote_id,
|
||||
lote_codigo: lot.codigo,
|
||||
lote_codigo: displayName,
|
||||
}));
|
||||
setShowLotSuggestions(false);
|
||||
|
||||
if (preloadedPermission !== undefined) {
|
||||
setLotPermission(preloadedPermission);
|
||||
} else {
|
||||
try {
|
||||
const perm = await accessApi.getLotPermission(lot.lote_id);
|
||||
setLotPermission(perm);
|
||||
} catch {
|
||||
setLotPermission(null);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const clearLot = () => {
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
lote_id: null,
|
||||
lote_codigo: '',
|
||||
}));
|
||||
setLotPermission(null);
|
||||
};
|
||||
|
||||
// Evaluación de vigencia de pólizas (Paridad pct_view.py)
|
||||
@@ -350,9 +342,9 @@ export const ControlPostView: React.FC = () => {
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Validar Lote de Destino
|
||||
if (!form.lote_id && !form.lote_codigo.trim()) {
|
||||
setActionError('Debe seleccionar el lote de destino (obligatorio).');
|
||||
// 3. Validar Lote de Destino (Paridad puestocontrol: pct_view.py:3183)
|
||||
if (!form.lote_id || form.lote_id <= 0) {
|
||||
setActionError('Falta Seleccionar Lote de Destino (obligatorio).');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -410,6 +402,7 @@ export const ControlPostView: React.FC = () => {
|
||||
apellido: form.apellido.trim().toUpperCase(),
|
||||
nombre: form.nombre.trim().toUpperCase(),
|
||||
patente: form.tipo_ingreso === 'CONDUCTOR' ? form.patente.trim().toUpperCase() : '',
|
||||
baul_inspeccionado: form.tipo_ingreso === 'CONDUCTOR' ? !!form.baul_inspeccionado : false,
|
||||
forzar_ingreso_lote_restringido: forceRestricted || form.forzar_ingreso_lote_restringido,
|
||||
};
|
||||
|
||||
@@ -432,7 +425,8 @@ export const ControlPostView: React.FC = () => {
|
||||
entidad: '',
|
||||
cantidad_ocupantes: 1,
|
||||
cantidad_menores: 0,
|
||||
cacheo_salida: false,
|
||||
cacheo_salida: true,
|
||||
baul_inspeccionado: false,
|
||||
abrir_barrera: true,
|
||||
integrantes: [],
|
||||
seguro_empresa: '',
|
||||
@@ -1046,61 +1040,91 @@ export const ControlPostView: React.FC = () => {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{ position: 'relative' }}>
|
||||
{/* Selector de Lote con Paridad Desktop DialogoBuscarLote */}
|
||||
<div>
|
||||
<label style={{ fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
||||
LOTE / DESTINO <span style={{ color: '#f44336' }}>*</span>:
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
className="input-touch"
|
||||
value={form.lote_codigo}
|
||||
onChange={(e) => handleLotSearch(e.target.value)}
|
||||
onFocus={() => {
|
||||
if (lotSuggestions.length > 0) setShowLotSuggestions(true);
|
||||
}}
|
||||
placeholder="Ej: 142"
|
||||
required
|
||||
style={{ width: '100%', marginTop: '0.25rem' }}
|
||||
/>
|
||||
{/* Desplegable de sugerencias de Lotes */}
|
||||
{showLotSuggestions && lotSuggestions.length > 0 && (
|
||||
<div style={{ display: 'flex', gap: '0.5rem', marginTop: '0.25rem', alignItems: 'stretch' }}>
|
||||
<div
|
||||
onClick={() => setIsLotModalOpen(true)}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: '100%',
|
||||
left: 0,
|
||||
right: 0,
|
||||
backgroundColor: 'var(--bg-card)',
|
||||
border: '1px solid var(--border-subtle)',
|
||||
flex: 1,
|
||||
backgroundColor: form.lote_id ? 'var(--bg-card)' : 'rgba(0,0,0,0.1)',
|
||||
border: form.lote_id ? '2px solid var(--accent-primary)' : '1px dashed var(--border-subtle)',
|
||||
borderRadius: 'var(--radius-sm)',
|
||||
boxShadow: 'var(--shadow-md)',
|
||||
zIndex: 100,
|
||||
maxHeight: '160px',
|
||||
overflowY: 'auto',
|
||||
}}
|
||||
>
|
||||
{lotSuggestions.map((lot) => (
|
||||
<div
|
||||
key={lot.lote_id}
|
||||
onClick={() => selectLot(lot)}
|
||||
style={{
|
||||
padding: '0.6rem 0.75rem',
|
||||
padding: '0.65rem 0.85rem',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
cursor: 'pointer',
|
||||
fontSize: '0.9rem',
|
||||
borderBottom: '1px solid var(--border-subtle)',
|
||||
minHeight: '48px',
|
||||
userSelect: 'none',
|
||||
}}
|
||||
title="Haga clic para buscar o seleccionar lote de destino"
|
||||
>
|
||||
Lote <strong>{lot.codigo}</strong>
|
||||
</div>
|
||||
))}
|
||||
{form.lote_id ? (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', overflow: 'hidden' }}>
|
||||
<span style={{ fontSize: '1.1rem' }}>🏡</span>
|
||||
<span style={{ fontWeight: 700, fontSize: '1rem', color: 'var(--text-primary)', textOverflow: 'ellipsis', whiteSpace: 'nowrap', overflow: 'hidden' }}>
|
||||
{form.lote_codigo}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<span style={{ color: 'var(--text-muted)', fontSize: '0.9rem', fontStyle: 'italic' }}>
|
||||
Toque para seleccionar lote...
|
||||
</span>
|
||||
)}
|
||||
<span style={{ fontSize: '0.85rem', color: 'var(--accent-primary)', fontWeight: 600 }}>
|
||||
{form.lote_id ? 'Cambiar' : 'Elegir'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() => setIsLotModalOpen(true)}
|
||||
style={{
|
||||
minWidth: '52px',
|
||||
minHeight: '48px',
|
||||
padding: '0 0.85rem',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
fontSize: '1rem',
|
||||
fontWeight: 600,
|
||||
}}
|
||||
title="Abrir buscador de lotes y residentes"
|
||||
>
|
||||
🔍
|
||||
</button>
|
||||
|
||||
{form.lote_id && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn"
|
||||
onClick={clearLot}
|
||||
style={{
|
||||
minWidth: '44px',
|
||||
minHeight: '48px',
|
||||
padding: '0 0.6rem',
|
||||
backgroundColor: 'rgba(239, 68, 68, 0.15)',
|
||||
color: 'var(--status-danger)',
|
||||
border: '1px solid rgba(239, 68, 68, 0.3)',
|
||||
fontSize: '0.9rem',
|
||||
}}
|
||||
title="Quitar lote seleccionado"
|
||||
>
|
||||
🧹
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Badge de Validación de Lote (Categoría 26: Habilitado / Moroso / En Obra) */}
|
||||
{lotPermission && (
|
||||
<div
|
||||
style={{
|
||||
marginTop: '0.35rem',
|
||||
marginTop: '0.4rem',
|
||||
padding: '0.35rem 0.65rem',
|
||||
borderRadius: '6px',
|
||||
fontSize: '0.8rem',
|
||||
@@ -1515,6 +1539,69 @@ export const ControlPostView: React.FC = () => {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Control de Cacheo de Garita (Corazón de la seguridad en puesto de control) */}
|
||||
<div
|
||||
style={{
|
||||
backgroundColor: 'var(--bg-card)',
|
||||
padding: '0.75rem',
|
||||
borderRadius: 'var(--radius-sm)',
|
||||
marginTop: '0.25rem',
|
||||
border: '1px solid var(--border-subtle)',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '0.5rem',
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-secondary)', letterSpacing: '0.5px' }}>
|
||||
SEGURIDAD Y CONTROL DE GUARDIA (CACHEO)
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '1rem', alignItems: 'center' }}>
|
||||
<label
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '0.5rem',
|
||||
cursor: 'pointer',
|
||||
fontSize: '0.9rem',
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.cacheo_salida}
|
||||
onChange={(e) => setForm((prev) => ({ ...prev, cacheo_salida: e.target.checked }))}
|
||||
style={{ width: '20px', height: '20px', cursor: 'pointer' }}
|
||||
/>
|
||||
<span>Cacheo Obligatorio a la Salida</span>
|
||||
</label>
|
||||
|
||||
{form.tipo_ingreso === 'CONDUCTOR' && (
|
||||
<label
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '0.5rem',
|
||||
cursor: 'pointer',
|
||||
fontSize: '0.9rem',
|
||||
fontWeight: 700,
|
||||
color: form.baul_inspeccionado ? 'var(--status-success)' : 'var(--text-primary)',
|
||||
backgroundColor: form.baul_inspeccionado ? 'rgba(76, 175, 80, 0.1)' : 'transparent',
|
||||
padding: '0.2rem 0.5rem',
|
||||
borderRadius: '4px',
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.baul_inspeccionado}
|
||||
onChange={(e) => setForm((prev) => ({ ...prev, baul_inspeccionado: e.target.checked }))}
|
||||
style={{ width: '20px', height: '20px', cursor: 'pointer' }}
|
||||
/>
|
||||
<span>✓ Baúl inspeccionado al ingreso (OK)</span>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Switch Abrir Barrera / Molinete */}
|
||||
<div
|
||||
style={{
|
||||
@@ -1780,6 +1867,25 @@ export const ControlPostView: React.FC = () => {
|
||||
<div style={{ fontSize: '0.8rem', color: 'var(--text-secondary)', marginTop: '0.2rem' }}>
|
||||
Destino: <strong>Lote {t.lote_codigo || 'S/D'}</strong> • Ingreso:{' '}
|
||||
{t.fecha_ingreso} ({t.modulo_ingreso})
|
||||
{t.cacheo_salida && (
|
||||
<span
|
||||
style={{
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
gap: '0.2rem',
|
||||
marginLeft: '0.5rem',
|
||||
backgroundColor: 'rgba(239, 68, 68, 0.15)',
|
||||
color: 'var(--status-danger)',
|
||||
border: '1px solid rgba(239, 68, 68, 0.4)',
|
||||
padding: '0.1rem 0.45rem',
|
||||
borderRadius: '4px',
|
||||
fontSize: '0.75rem',
|
||||
fontWeight: 700,
|
||||
}}
|
||||
>
|
||||
🔍 CACHEO OBLIGATORIO
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -2058,6 +2164,14 @@ export const ControlPostView: React.FC = () => {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Modal de Búsqueda y Selección de Lote (Paridad DialogoBuscarLote) */}
|
||||
<LotSearchModal
|
||||
isOpen={isLotModalOpen}
|
||||
onClose={() => setIsLotModalOpen(false)}
|
||||
onSelectLot={selectLot}
|
||||
selectedLotId={form.lote_id}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user