feat(puesto-control): paridad total de validaciones, seguro automotor, ART y UX tablet 9-11 pulgadas
This commit is contained in:
@@ -2,8 +2,30 @@
|
|||||||
|
|
||||||
Todas las modificaciones, adiciones y decisiones de arquitectura notables de este proyecto serán documentadas en este archivo.
|
Todas las modificaciones, adiciones y decisiones de arquitectura notables de este proyecto serán documentadas en este archivo.
|
||||||
|
|
||||||
|
## [v0.6.3-beta] - 2026-10-14 (Paridad de Validaciones de Puesto de Control, Pólizas de Seguro, ART y UX Tablet 9-11")
|
||||||
|
|
||||||
|
### Agregado y Corregido
|
||||||
|
- **Validaciones Estrictas de Formulario (Paridad 1:1 con `puestocontrol/pct_view.py:validar_formulario`):**
|
||||||
|
- **Documento Obligatorio:** Mínimo 4 caracteres alfanuméricos requeridos; rechazo con código 422 si está vacío o incompleto.
|
||||||
|
- **Nombre Obligatorio:** Campo requerido; rechazo con código 422 si falta el nombre del visitante o conductor.
|
||||||
|
- **Lote de Destino Obligatorio:** Campo obligatorio (`lote_id` o `lote_codigo`); validación de restricciones en tiempo real con Categoría 26 de `LotCatVal` (moroso / restringido / en obra). Modal interactivo de confirmación y anulación manual autorizada para operadores.
|
||||||
|
- **Selector Táctil de Modo Conductor vs Peatón:**
|
||||||
|
- Botonera segmentada de 48px de alto para tablets Samsung Galaxy Tab A9 / A11 (`🚗 Conductor` y `🚶 Peatón`).
|
||||||
|
- **Modo Conductor:** Patente obligatoria. Validación estricta de vigencia de póliza de Seguro Automotor (`ps_hasta`): bloqueo inmediato de acceso (403) si la cobertura está vencida, sin fecha o en 1900-01-01.
|
||||||
|
- **Modo Peatón:** Desactiva y omite la exigencia de vehículo/seguro automotor, preservando intactas las coberturas preexistentes en `perpolreg` y `Aut` sin sobrescribirlas.
|
||||||
|
- **Validación de Póliza ART / Accidentes Personales:**
|
||||||
|
- Para motivos de ingreso vinculados a trabajo (`TRABAJADOR`, `SERVICIO`, `PROVEEDOR`, `OBRA`), verificación y bloqueo (403) ante coberturas vencidas.
|
||||||
|
- **Carga Predictiva y Autocompletado Instantáneo:**
|
||||||
|
- Al escribir o escanear DNI: recuperación automática de titular, patentes registradas en `PerAut`, coberturas de seguro en `Aut`/`perpolreg`, ART, licencia y observaciones (`PerPrx`).
|
||||||
|
- Al tipear o seleccionar patente: consulta de póliza de seguro y titular en `Aut`, con botones de selección rápida táctil de patentes asociadas.
|
||||||
|
- **Diseño Táctil y Pólizas en Tablets de 9 a 11 Pulgadas (Samsung Tab A9 y A11):**
|
||||||
|
- Acordeón colapsable con badges de estado en tiempo real (Verde: Vigente, Rojo: Vencida, Naranja: Faltante).
|
||||||
|
- Botones táctiles de vencimiento rápido (+1 Mes, +6 Meses, +1 Año) para agilizar la carga en garita sin requerir teclado virtual.
|
||||||
|
- Targets táctiles $\ge 44-48\text{px}$ en todos los controles interactivos.
|
||||||
|
|
||||||
## [v0.6.1-beta] - 2026-10-13 (Carga Dinámica de Workstations y Movimientos Reales de SQL Server)
|
## [v0.6.1-beta] - 2026-10-13 (Carga Dinámica de Workstations y Movimientos Reales de SQL Server)
|
||||||
|
|
||||||
|
|
||||||
### Agregado y Corregido
|
### Agregado y Corregido
|
||||||
- **Carga Dinámica de Estaciones de Trabajo (`wks`):**
|
- **Carga Dinámica de Estaciones de Trabajo (`wks`):**
|
||||||
- Eliminación de todas las opciones mock en `LoginView.tsx`.
|
- Eliminación de todas las opciones mock en `LoginView.tsx`.
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ from app.schemas.access_schema import (
|
|||||||
LotSearchDTO,
|
LotSearchDTO,
|
||||||
LotPermissionDTO,
|
LotPermissionDTO,
|
||||||
TicketOccupantDTO,
|
TicketOccupantDTO,
|
||||||
|
PersonPoliciesDTO,
|
||||||
|
VehicleDetailsDTO,
|
||||||
)
|
)
|
||||||
from app.services.access_service import AccessService
|
from app.services.access_service import AccessService
|
||||||
from app.services.dni_parser_service import DNIParsingService, DNIParsedResult
|
from app.services.dni_parser_service import DNIParsingService, DNIParsedResult
|
||||||
@@ -127,3 +129,34 @@ def listar_ocupantes_ticket(
|
|||||||
):
|
):
|
||||||
"""Retorna todos los integrantes que ingresaron en el vehículo correspondiente a este ticket."""
|
"""Retorna todos los integrantes que ingresaron en el vehículo correspondiente a este ticket."""
|
||||||
return AccessService.obtener_ocupantes_ticket(ticket_id)
|
return AccessService.obtener_ocupantes_ticket(ticket_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/people/{documento}/details", response_model=PersonPoliciesDTO, summary="Consultar datos completos, patentes y pólizas de persona")
|
||||||
|
def consultar_datos_persona(
|
||||||
|
documento: str,
|
||||||
|
current_user: dict = Depends(obtener_usuario_actual),
|
||||||
|
):
|
||||||
|
"""Retorna ficha de persona con patentes asociadas, seguros, ART y licencia."""
|
||||||
|
res = AccessService.obtener_polizas_y_vehiculos_persona(documento)
|
||||||
|
if not res:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail=f"Persona con DNI {documento} no encontrada.",
|
||||||
|
)
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/vehicles/{patente}/details", response_model=VehicleDetailsDTO, summary="Consultar datos de seguro y titular de vehículo")
|
||||||
|
def consultar_datos_vehiculo(
|
||||||
|
patente: str,
|
||||||
|
current_user: dict = Depends(obtener_usuario_actual),
|
||||||
|
):
|
||||||
|
"""Retorna póliza de seguro y datos del titular asociado a la patente."""
|
||||||
|
res = AccessService.obtener_datos_vehiculo(patente)
|
||||||
|
if not res:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail=f"Vehículo con patente {patente} no encontrado en base de datos.",
|
||||||
|
)
|
||||||
|
return res
|
||||||
|
|
||||||
|
|||||||
@@ -108,7 +108,8 @@ class AccessRepository:
|
|||||||
Registra de manera atómica el ticket en `tck`, `tckprx`, `tckper` y `mvthist`.
|
Registra de manera atómica el ticket en `tck`, `tckprx`, `tckper` y `mvthist`.
|
||||||
"""
|
"""
|
||||||
ahora = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
ahora = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
rol_id = 1 if req.patente else 2 # 1: Conductor, 2: Peatón
|
es_conductor = req.tipo_ingreso.upper() == "CONDUCTOR" or bool(req.patente and req.tipo_ingreso.upper() != "PEATON")
|
||||||
|
rol_id = 1 if es_conductor else 2 # 1: Conductor, 2: Peatón
|
||||||
|
|
||||||
entidad_final = req.entidad or ("CONDUCTOR..." if rol_id == 1 else "PEATON...")
|
entidad_final = req.entidad or ("CONDUCTOR..." if rol_id == 1 else "PEATON...")
|
||||||
|
|
||||||
@@ -121,6 +122,8 @@ class AccessRepository:
|
|||||||
(6, "1" if req.cacheo_salida else "0"),
|
(6, "1" if req.cacheo_salida else "0"),
|
||||||
(7, str(req.lote_id or req.lote_codigo or "")),
|
(7, str(req.lote_id or req.lote_codigo or "")),
|
||||||
]
|
]
|
||||||
|
if req.observaciones and req.observaciones.strip():
|
||||||
|
propiedades.append((10, req.observaciones.strip()))
|
||||||
|
|
||||||
with db_session() as conn:
|
with db_session() as conn:
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
@@ -176,6 +179,12 @@ class AccessRepository:
|
|||||||
(ticket_id, comp_pid, comp.rol_id, 1 if comp.es_menor else 0),
|
(ticket_id, comp_pid, comp.rol_id, 1 if comp.es_menor else 0),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# 6. Persistencia de pólizas, patentes y observaciones en tablas relacionales
|
||||||
|
try:
|
||||||
|
AccessRepository.guardar_polizas_y_vehiculo(persona_id, req)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Nota: error al guardar polizas/vehiculo: {e}")
|
||||||
|
|
||||||
return ticket_id
|
return ticket_id
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -507,3 +516,307 @@ class AccessRepository:
|
|||||||
cursor = conn.cursor(as_dict=True)
|
cursor = conn.cursor(as_dict=True)
|
||||||
cursor.execute(query, (patron,))
|
cursor.execute(query, (patron,))
|
||||||
return cursor.fetchall()
|
return cursor.fetchall()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def buscar_polizas_y_vehiculos_persona(documento: str) -> Optional[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
Retorna la ficha de la persona con sus patentes asociadas, seguros y pólizas de perpolreg y Aut.
|
||||||
|
"""
|
||||||
|
doc_clean = documento.strip()
|
||||||
|
per = AccessRepository.buscar_persona_por_documento(doc_clean)
|
||||||
|
if not per:
|
||||||
|
return None
|
||||||
|
|
||||||
|
pid = per["PersonaID"]
|
||||||
|
resultado: Dict[str, Any] = {
|
||||||
|
"persona_id": pid,
|
||||||
|
"documento": doc_clean,
|
||||||
|
"apellido": per.get("Apellido", "") or "",
|
||||||
|
"nombre": per.get("Nombre", "") or "",
|
||||||
|
"sexo": per.get("Sexo", "M") or "M",
|
||||||
|
"patente_sugerida": None,
|
||||||
|
"patentes_asociadas": [],
|
||||||
|
"seguro_empresa": None,
|
||||||
|
"seguro_poliza": None,
|
||||||
|
"seguro_desde": None,
|
||||||
|
"seguro_hasta": None,
|
||||||
|
"art_empresa": None,
|
||||||
|
"art_poliza": None,
|
||||||
|
"art_desde": None,
|
||||||
|
"art_hasta": None,
|
||||||
|
"licencia_nro": None,
|
||||||
|
"licencia_entidad": None,
|
||||||
|
"licencia_hasta": None,
|
||||||
|
"observaciones": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
with db_session() as conn:
|
||||||
|
cursor = conn.cursor(as_dict=True)
|
||||||
|
# 1. Patentes asociadas en PerAut + Aut
|
||||||
|
sql_pats = """
|
||||||
|
SELECT DISTINCT UPPER(a.Patente) AS Patente, a.Aseguradora, a.PolizaNro,
|
||||||
|
CONVERT(varchar(10), a.PolizaVigenciaDesde, 120) AS FecDesde,
|
||||||
|
CONVERT(varchar(10), a.PolizaVigenciaHasta, 120) AS FecHasta
|
||||||
|
FROM Aut a
|
||||||
|
INNER JOIN PerAut pa ON a.AutoID = pa.AutoID
|
||||||
|
WHERE pa.PersonaID = %s AND a.Patente IS NOT NULL AND a.Patente <> ''
|
||||||
|
ORDER BY UPPER(a.Patente)
|
||||||
|
"""
|
||||||
|
cursor.execute(sql_pats, (pid,))
|
||||||
|
pats_rows = cursor.fetchall()
|
||||||
|
pats = [r["Patente"] for r in pats_rows if r.get("Patente")]
|
||||||
|
resultado["patentes_asociadas"] = pats
|
||||||
|
if pats:
|
||||||
|
resultado["patente_sugerida"] = pats[0]
|
||||||
|
first_row = pats_rows[0]
|
||||||
|
if first_row.get("Aseguradora") or first_row.get("PolizaNro"):
|
||||||
|
resultado["seguro_empresa"] = first_row.get("Aseguradora")
|
||||||
|
resultado["seguro_poliza"] = first_row.get("PolizaNro")
|
||||||
|
resultado["seguro_desde"] = first_row.get("FecDesde")
|
||||||
|
resultado["seguro_hasta"] = first_row.get("FecHasta")
|
||||||
|
|
||||||
|
# 2. Pólizas en perpolreg
|
||||||
|
sql_pol = """
|
||||||
|
SELECT NroRC, ExpedidoRC,
|
||||||
|
CONVERT(varchar(10), FechaFinRC, 120) AS FecFinRC,
|
||||||
|
EmpresaPS, NroPS,
|
||||||
|
CONVERT(varchar(10), FechaInicioPS, 120) AS FecIniPS,
|
||||||
|
CONVERT(varchar(10), FechaFinPS, 120) AS FecFinPS,
|
||||||
|
EmpresaPA, NroPA,
|
||||||
|
CONVERT(varchar(10), FechaInicioPA, 120) AS FecIniPA,
|
||||||
|
CONVERT(varchar(10), FechaFinPA, 120) AS FecFinPA
|
||||||
|
FROM perpolreg
|
||||||
|
WHERE PersonaID = %s
|
||||||
|
"""
|
||||||
|
cursor.execute(sql_pol, (pid,))
|
||||||
|
row_pol = cursor.fetchone()
|
||||||
|
if row_pol:
|
||||||
|
def _clean_str(v):
|
||||||
|
if not v or str(v).strip().upper() in ('-', 'SPACE', 'NULL', 'NONE'):
|
||||||
|
return None
|
||||||
|
return str(v).strip()
|
||||||
|
|
||||||
|
def _clean_date(v):
|
||||||
|
if not v or str(v).strip() in ('1900-01-01', '01-01-1900', '-'):
|
||||||
|
return None
|
||||||
|
return str(v).strip().split()[0]
|
||||||
|
|
||||||
|
resultado["licencia_nro"] = _clean_str(row_pol.get("NroRC"))
|
||||||
|
resultado["licencia_entidad"] = _clean_str(row_pol.get("ExpedidoRC"))
|
||||||
|
resultado["licencia_hasta"] = _clean_date(row_pol.get("FecFinRC"))
|
||||||
|
|
||||||
|
if not resultado["seguro_empresa"]:
|
||||||
|
resultado["seguro_empresa"] = _clean_str(row_pol.get("EmpresaPS"))
|
||||||
|
resultado["seguro_poliza"] = _clean_str(row_pol.get("NroPS"))
|
||||||
|
resultado["seguro_desde"] = _clean_date(row_pol.get("FecIniPS"))
|
||||||
|
resultado["seguro_hasta"] = _clean_date(row_pol.get("FecFinPS"))
|
||||||
|
|
||||||
|
resultado["art_empresa"] = _clean_str(row_pol.get("EmpresaPA"))
|
||||||
|
resultado["art_poliza"] = _clean_str(row_pol.get("NroPA"))
|
||||||
|
resultado["art_desde"] = _clean_date(row_pol.get("FecIniPA"))
|
||||||
|
resultado["art_hasta"] = _clean_date(row_pol.get("FecFinPA"))
|
||||||
|
|
||||||
|
# 3. Observaciones en PerPrx (PropiedadID = 1)
|
||||||
|
sql_obs = "SELECT Valor FROM PerPrx WHERE PersonaID = %s AND PropiedadID = 1"
|
||||||
|
cursor.execute(sql_obs, (pid,))
|
||||||
|
row_obs = cursor.fetchone()
|
||||||
|
if row_obs and row_obs.get("Valor"):
|
||||||
|
resultado["observaciones"] = row_obs["Valor"]
|
||||||
|
|
||||||
|
return resultado
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def buscar_datos_vehiculo(patente: str) -> Optional[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
Busca datos de seguro y titular asociado a una patente.
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
pat_clean = re.sub(r'[\s\-]', '', str(patente)).upper()
|
||||||
|
if not pat_clean:
|
||||||
|
return None
|
||||||
|
|
||||||
|
with db_session() as conn:
|
||||||
|
cursor = conn.cursor(as_dict=True)
|
||||||
|
sql = """
|
||||||
|
SELECT TOP 1
|
||||||
|
a.AutoID, a.Patente, a.Aseguradora, a.PolizaNro,
|
||||||
|
CONVERT(varchar(10), a.PolizaVigenciaDesde, 120) AS VigenciaDesde,
|
||||||
|
CONVERT(varchar(10), a.PolizaVigenciaHasta, 120) AS VigenciaHasta,
|
||||||
|
p.PersonaID, p.Apellido, p.Nombre,
|
||||||
|
(SELECT TOP 1 d.Documento FROM PerDocCatVal d WHERE d.PersonaID = p.PersonaID ORDER BY d.DocumentoID) AS Documento
|
||||||
|
FROM Aut a
|
||||||
|
LEFT JOIN PerAut pa ON a.AutoID = pa.AutoID
|
||||||
|
LEFT JOIN Per p ON pa.PersonaID = p.PersonaID
|
||||||
|
WHERE REPLACE(REPLACE(UPPER(LTRIM(RTRIM(a.Patente))), ' ', ''), '-', '') = %s
|
||||||
|
ORDER BY p.PersonaID DESC
|
||||||
|
"""
|
||||||
|
cursor.execute(sql, (pat_clean,))
|
||||||
|
row = cursor.fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _clean_str(v):
|
||||||
|
if not v or str(v).strip().upper() in ('-', 'SPACE', 'NULL', 'NONE'):
|
||||||
|
return None
|
||||||
|
return str(v).strip()
|
||||||
|
|
||||||
|
def _clean_date(v):
|
||||||
|
if not v or str(v).strip() in ('1900-01-01', '01-01-1900', '-'):
|
||||||
|
return None
|
||||||
|
return str(v).strip().split()[0]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"patente": row.get("Patente") or pat_clean,
|
||||||
|
"aseguradora": _clean_str(row.get("Aseguradora")),
|
||||||
|
"poliza_nro": _clean_str(row.get("PolizaNro")),
|
||||||
|
"vigencia_desde": _clean_date(row.get("VigenciaDesde")),
|
||||||
|
"vigencia_hasta": _clean_date(row.get("VigenciaHasta")),
|
||||||
|
"persona_id": row.get("PersonaID"),
|
||||||
|
"apellido": row.get("Apellido"),
|
||||||
|
"nombre": row.get("Nombre"),
|
||||||
|
"documento": row.get("Documento"),
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def guardar_polizas_y_vehiculo(persona_id: int, req: EntryRequest) -> bool:
|
||||||
|
"""
|
||||||
|
Persiste coberturas en perpolreg, seguro en Aut (si Conductor) y observaciones en PerPrx.
|
||||||
|
"""
|
||||||
|
if persona_id <= 0:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _iso_date(val: Optional[str]) -> str:
|
||||||
|
if not val:
|
||||||
|
return "1900-01-01"
|
||||||
|
v = str(val).strip().split()[0].replace('/', '-')
|
||||||
|
if v in ("1900-01-01", "01-01-1900", "-", ""):
|
||||||
|
return "1900-01-01"
|
||||||
|
parts = v.split('-')
|
||||||
|
if len(parts) == 3:
|
||||||
|
if len(parts[0]) == 4:
|
||||||
|
return f"{int(parts[0]):04d}-{int(parts[1]):02d}-{int(parts[2]):02d}"
|
||||||
|
elif len(parts[2]) == 4:
|
||||||
|
return f"{int(parts[2]):04d}-{int(parts[1]):02d}-{int(parts[0]):02d}"
|
||||||
|
return "1900-01-01"
|
||||||
|
|
||||||
|
def _str_clean(val: Optional[str]) -> str:
|
||||||
|
if not val:
|
||||||
|
return "-"
|
||||||
|
v = str(val).strip()
|
||||||
|
return v if v else "-"
|
||||||
|
|
||||||
|
es_conductor = req.tipo_ingreso.upper() == "CONDUCTOR" or bool(req.patente and req.tipo_ingreso.upper() != "PEATON")
|
||||||
|
|
||||||
|
with db_session() as conn:
|
||||||
|
cursor = conn.cursor()
|
||||||
|
|
||||||
|
# 1. Si es Conductor y hay patente, gestionar Aut y PerAut
|
||||||
|
if es_conductor and req.patente:
|
||||||
|
pat_upper = req.patente.strip().upper()
|
||||||
|
cursor.execute("SELECT AutoID FROM Aut WHERE UPPER(Patente) = %s", (pat_upper,))
|
||||||
|
row_aut = cursor.fetchone()
|
||||||
|
if row_aut:
|
||||||
|
auto_id = row_aut[0]
|
||||||
|
if req.seguro_empresa or req.seguro_poliza or req.seguro_hasta:
|
||||||
|
cursor.execute("""
|
||||||
|
UPDATE Aut
|
||||||
|
SET Aseguradora = COALESCE(NULLIF(%s, '-'), Aseguradora),
|
||||||
|
PolizaNro = COALESCE(NULLIF(%s, '-'), PolizaNro),
|
||||||
|
PolizaVigenciaDesde = CASE WHEN %s != '1900-01-01' THEN %s ELSE PolizaVigenciaDesde END,
|
||||||
|
PolizaVigenciaHasta = CASE WHEN %s != '1900-01-01' THEN %s ELSE PolizaVigenciaHasta END
|
||||||
|
WHERE AutoID = %s
|
||||||
|
""", (
|
||||||
|
_str_clean(req.seguro_empresa),
|
||||||
|
_str_clean(req.seguro_poliza),
|
||||||
|
_iso_date(req.seguro_desde), _iso_date(req.seguro_desde),
|
||||||
|
_iso_date(req.seguro_hasta), _iso_date(req.seguro_hasta),
|
||||||
|
auto_id
|
||||||
|
))
|
||||||
|
else:
|
||||||
|
cursor.execute("SELECT COALESCE(MAX(AutoID), 0) + 1 FROM Aut")
|
||||||
|
auto_id = cursor.fetchone()[0]
|
||||||
|
cursor.execute("""
|
||||||
|
INSERT INTO Aut (AutoID, Patente, Aseguradora, PolizaNro, PolizaVigenciaDesde, PolizaVigenciaHasta)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s)
|
||||||
|
""", (
|
||||||
|
auto_id, pat_upper,
|
||||||
|
_str_clean(req.seguro_empresa),
|
||||||
|
_str_clean(req.seguro_poliza),
|
||||||
|
_iso_date(req.seguro_desde),
|
||||||
|
_iso_date(req.seguro_hasta),
|
||||||
|
))
|
||||||
|
|
||||||
|
# Vincular en PerAut si no existe
|
||||||
|
cursor.execute("SELECT 1 FROM PerAut WHERE PersonaID = %s AND AutoID = %s", (persona_id, auto_id))
|
||||||
|
if not cursor.fetchone():
|
||||||
|
cursor.execute("INSERT INTO PerAut (PersonaID, AutoID) VALUES (%s, %s)", (persona_id, auto_id))
|
||||||
|
|
||||||
|
# 2. Gestionar perpolreg
|
||||||
|
cursor.execute("SELECT 1 FROM perpolreg WHERE PersonaID = %s", (persona_id,))
|
||||||
|
existe_pol = cursor.fetchone() is not None
|
||||||
|
|
||||||
|
if es_conductor:
|
||||||
|
rc_ini = _iso_date(req.seguro_desde)
|
||||||
|
rc_fin = _iso_date(req.licencia_hasta)
|
||||||
|
rc_nro = _str_clean(req.licencia_nro)
|
||||||
|
rc_ent = _str_clean(req.licencia_entidad)
|
||||||
|
|
||||||
|
ps_ini = _iso_date(req.seguro_desde)
|
||||||
|
ps_fin = _iso_date(req.seguro_hasta)
|
||||||
|
ps_nro = _str_clean(req.seguro_poliza)
|
||||||
|
ps_emp = _str_clean(req.seguro_empresa)
|
||||||
|
|
||||||
|
pa_ini = _iso_date(req.art_desde)
|
||||||
|
pa_fin = _iso_date(req.art_hasta)
|
||||||
|
pa_nro = _str_clean(req.art_poliza)
|
||||||
|
pa_emp = _str_clean(req.art_empresa)
|
||||||
|
|
||||||
|
if existe_pol:
|
||||||
|
cursor.execute("""
|
||||||
|
UPDATE perpolreg SET
|
||||||
|
FechaInicioRC = %s, FechaFinRC = %s, NroRC = %s, ExpedidoRC = %s,
|
||||||
|
FechaInicioPS = %s, FechaFinPS = %s, NroPS = %s, EmpresaPS = %s,
|
||||||
|
FechaInicioPA = %s, FechaFinPA = %s, NroPA = %s, EmpresaPA = %s
|
||||||
|
WHERE PersonaID = %s
|
||||||
|
""", (rc_ini, rc_fin, rc_nro, rc_ent, ps_ini, ps_fin, ps_nro, ps_emp, pa_ini, pa_fin, pa_nro, pa_emp, persona_id))
|
||||||
|
else:
|
||||||
|
cursor.execute("""
|
||||||
|
INSERT INTO perpolreg (
|
||||||
|
PersonaID, FechaInicioRC, FechaFinRC, NroRC, ExpedidoRC,
|
||||||
|
FechaInicioPS, FechaFinPS, NroPS, EmpresaPS,
|
||||||
|
FechaInicioPA, FechaFinPA, NroPA, EmpresaPA
|
||||||
|
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
|
""", (persona_id, rc_ini, rc_fin, rc_nro, rc_ent, ps_ini, ps_fin, ps_nro, ps_emp, pa_ini, pa_fin, pa_nro, pa_emp))
|
||||||
|
else:
|
||||||
|
# Peatón: No sobrescribe ni borra pólizas de auto o licencia existentes
|
||||||
|
pa_ini = _iso_date(req.art_desde)
|
||||||
|
pa_fin = _iso_date(req.art_hasta)
|
||||||
|
pa_nro = _str_clean(req.art_poliza)
|
||||||
|
pa_emp = _str_clean(req.art_empresa)
|
||||||
|
|
||||||
|
if existe_pol:
|
||||||
|
cursor.execute("""
|
||||||
|
UPDATE perpolreg SET
|
||||||
|
FechaInicioPA = %s, FechaFinPA = %s, NroPA = %s, EmpresaPA = %s
|
||||||
|
WHERE PersonaID = %s
|
||||||
|
""", (pa_ini, pa_fin, pa_nro, pa_emp, persona_id))
|
||||||
|
else:
|
||||||
|
cursor.execute("""
|
||||||
|
INSERT INTO perpolreg (
|
||||||
|
PersonaID, FechaInicioRC, FechaFinRC, NroRC, ExpedidoRC,
|
||||||
|
FechaInicioPS, FechaFinPS, NroPS, EmpresaPS,
|
||||||
|
FechaInicioPA, FechaFinPA, NroPA, EmpresaPA
|
||||||
|
) VALUES (%s, '1900-01-01', '1900-01-01', '-', '-', '1900-01-01', '1900-01-01', '-', '-', %s, %s, %s, %s)
|
||||||
|
""", (persona_id, pa_ini, pa_fin, pa_nro, pa_emp))
|
||||||
|
|
||||||
|
# 3. Observaciones en PerPrx (PropiedadID = 1)
|
||||||
|
if req.observaciones is not None:
|
||||||
|
obs_val = req.observaciones.strip()
|
||||||
|
cursor.execute("SELECT 1 FROM PerPrx WHERE PersonaID = %s AND PropiedadID = 1", (persona_id,))
|
||||||
|
if cursor.fetchone():
|
||||||
|
cursor.execute("UPDATE PerPrx SET Valor = %s WHERE PersonaID = %s AND PropiedadID = 1", (obs_val, persona_id))
|
||||||
|
else:
|
||||||
|
cursor.execute("INSERT INTO PerPrx (PersonaID, PropiedadID, Valor) VALUES (%s, 1, %s)", (persona_id, obs_val))
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ class EntryRequest(BaseModel):
|
|||||||
apellido: Optional[str] = ""
|
apellido: Optional[str] = ""
|
||||||
nombre: Optional[str] = ""
|
nombre: Optional[str] = ""
|
||||||
sexo: Optional[str] = "M"
|
sexo: Optional[str] = "M"
|
||||||
|
tipo_ingreso: str = Field("CONDUCTOR", description="CONDUCTOR o PEATON")
|
||||||
patente: Optional[str] = Field(None, description="Patente del vehículo (o None si es peatonal)")
|
patente: Optional[str] = Field(None, description="Patente del vehículo (o None si es peatonal)")
|
||||||
lote_id: Optional[int] = Field(None, description="Lote de destino")
|
lote_id: Optional[int] = Field(None, description="Lote de destino")
|
||||||
lote_codigo: Optional[str] = Field(None, description="Código de lote (ej: 142)")
|
lote_codigo: Optional[str] = Field(None, description="Código de lote (ej: 142)")
|
||||||
@@ -32,6 +33,56 @@ class EntryRequest(BaseModel):
|
|||||||
abrir_barrera: bool = True
|
abrir_barrera: bool = True
|
||||||
foto_evidencia_b64: Optional[str] = None
|
foto_evidencia_b64: Optional[str] = None
|
||||||
integrantes: List[CompanionDTO] = Field(default_factory=list)
|
integrantes: List[CompanionDTO] = Field(default_factory=list)
|
||||||
|
# Pólizas de Seguro Automotor (Aut y perpolreg)
|
||||||
|
seguro_empresa: Optional[str] = None
|
||||||
|
seguro_poliza: Optional[str] = None
|
||||||
|
seguro_desde: Optional[str] = None
|
||||||
|
seguro_hasta: Optional[str] = None
|
||||||
|
# Póliza ART / Accidentes Personales (perpolreg)
|
||||||
|
art_empresa: Optional[str] = None
|
||||||
|
art_poliza: Optional[str] = None
|
||||||
|
art_desde: Optional[str] = None
|
||||||
|
art_hasta: Optional[str] = None
|
||||||
|
# Registro de Conductor / Licencia (perpolreg)
|
||||||
|
licencia_nro: Optional[str] = None
|
||||||
|
licencia_entidad: Optional[str] = None
|
||||||
|
licencia_hasta: Optional[str] = None
|
||||||
|
observaciones: Optional[str] = None
|
||||||
|
forzar_ingreso_lote_restringido: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class PersonPoliciesDTO(BaseModel):
|
||||||
|
persona_id: int = 0
|
||||||
|
documento: str = ""
|
||||||
|
apellido: str = ""
|
||||||
|
nombre: str = ""
|
||||||
|
sexo: str = "M"
|
||||||
|
patente_sugerida: Optional[str] = None
|
||||||
|
patentes_asociadas: List[str] = Field(default_factory=list)
|
||||||
|
seguro_empresa: Optional[str] = None
|
||||||
|
seguro_poliza: Optional[str] = None
|
||||||
|
seguro_desde: Optional[str] = None
|
||||||
|
seguro_hasta: Optional[str] = None
|
||||||
|
art_empresa: Optional[str] = None
|
||||||
|
art_poliza: Optional[str] = None
|
||||||
|
art_desde: Optional[str] = None
|
||||||
|
art_hasta: Optional[str] = None
|
||||||
|
licencia_nro: Optional[str] = None
|
||||||
|
licencia_entidad: Optional[str] = None
|
||||||
|
licencia_hasta: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class VehicleDetailsDTO(BaseModel):
|
||||||
|
patente: str
|
||||||
|
aseguradora: Optional[str] = None
|
||||||
|
poliza_nro: Optional[str] = None
|
||||||
|
vigencia_desde: Optional[str] = None
|
||||||
|
vigencia_hasta: Optional[str] = None
|
||||||
|
persona_id: Optional[int] = None
|
||||||
|
apellido: Optional[str] = None
|
||||||
|
nombre: Optional[str] = None
|
||||||
|
documento: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class LotPermissionDTO(BaseModel):
|
class LotPermissionDTO(BaseModel):
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ from app.schemas.access_schema import (
|
|||||||
ActiveTicketDTO,
|
ActiveTicketDTO,
|
||||||
PersonSearchDTO,
|
PersonSearchDTO,
|
||||||
LotSearchDTO,
|
LotSearchDTO,
|
||||||
|
PersonPoliciesDTO,
|
||||||
|
VehicleDetailsDTO,
|
||||||
)
|
)
|
||||||
from app.repositories.access_repository import AccessRepository
|
from app.repositories.access_repository import AccessRepository
|
||||||
from app.services.hardware_service import HardwareService
|
from app.services.hardware_service import HardwareService
|
||||||
@@ -21,37 +23,123 @@ class AccessService:
|
|||||||
def procesar_ingreso(req: EntryRequest) -> TicketResponse:
|
def procesar_ingreso(req: EntryRequest) -> TicketResponse:
|
||||||
"""
|
"""
|
||||||
Ejecuta la regla de negocio para registrar el ingreso:
|
Ejecuta la regla de negocio para registrar el ingreso:
|
||||||
1. Verifica antipassback del titular.
|
1. Valida documento, nombre y lote (obligatorios).
|
||||||
2. Obtiene o crea la entidad Per / PerDocCatVal.
|
2. Valida patente y seguro vigente si Conductor.
|
||||||
3. Genera el TicketID canónico.
|
3. Valida ART si motivo laboral / servicios.
|
||||||
4. Persiste en tck, tckprx, tckper, mvthist de forma atómica.
|
4. Verifica antipassback del titular.
|
||||||
5. Encola la apertura de barrera en pdtmdl si fue solicitada.
|
5. Obtiene o crea la entidad Per / PerDocCatVal.
|
||||||
|
6. Genera el TicketID canónico.
|
||||||
|
7. Persiste en tck, tckprx, tckper, mvthist y tablas relacionales (perpolreg, Aut).
|
||||||
|
8. Encola la apertura de barrera en pdtmdl si fue solicitada.
|
||||||
"""
|
"""
|
||||||
# 1. Búsqueda preliminar para verificación de antipassback
|
# 1. Validar Documento
|
||||||
persona_existente = AccessRepository.buscar_persona_por_documento(req.documento)
|
doc_clean = (req.documento or "").strip()
|
||||||
|
if not doc_clean or len(doc_clean) < 4:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
|
detail="Falta número de documento válido (mínimo 4 caracteres).",
|
||||||
|
)
|
||||||
|
|
||||||
|
# 2. Validar Nombre
|
||||||
|
nombre_clean = (req.nombre or "").strip()
|
||||||
|
if not nombre_clean:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
|
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()):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
|
detail="Falta seleccionar el lote de destino.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# 4. Validar restricción del lote (Categoría 26 en LotCatVal)
|
||||||
|
if req.lote_id and req.lote_id > 0:
|
||||||
|
permiso = AccessRepository.obtener_permiso_lote(req.lote_id)
|
||||||
|
if permiso.get("estado") == "Restringido" and not req.forzar_ingreso_lote_restringido:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail=f"Acceso Bloqueado: {permiso.get('detalle', 'Lote Restringido')}. Por políticas del consorcio no se autoriza el ingreso sin anulación manual de restricción.",
|
||||||
|
)
|
||||||
|
|
||||||
|
es_conductor = req.tipo_ingreso.upper() == "CONDUCTOR" or bool(req.patente and req.tipo_ingreso.upper() != "PEATON")
|
||||||
|
|
||||||
|
# 5. Validaciones Conductor (Patente y Seguro)
|
||||||
|
if es_conductor:
|
||||||
|
pat_clean = (req.patente or "").strip().upper()
|
||||||
|
if not pat_clean:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
|
detail="Falta la patente del vehículo (obligatoria para conductores).",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Validar seguro automotor si viene fecha de vencimiento
|
||||||
|
if req.seguro_hasta:
|
||||||
|
sh = req.seguro_hasta.strip().split()[0].replace('/', '-')
|
||||||
|
if sh in ("1900-01-01", "01-01-1900", "-"):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Acceso Bloqueado: Seguro Automotor Inválido. La póliza tiene fecha no válida (1900-01-01).",
|
||||||
|
)
|
||||||
|
dt_vence = None
|
||||||
|
for fmt in ("%Y-%m-%d", "%d-%m-%Y"):
|
||||||
|
try:
|
||||||
|
dt_vence = datetime.strptime(sh, fmt).date()
|
||||||
|
break
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
if dt_vence and dt_vence < datetime.now().date():
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail=f"Acceso Bloqueado: Seguro Automotor Inválido. La póliza de seguro del vehículo ({pat_clean}) se encuentra VENCIDA ({dt_vence.strftime('%d/%m/%Y')}). Por políticas de seguridad, no se autoriza el ingreso de vehículos sin cobertura vigente.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# 6. Validar ART si es trabajador / contratista / proveedor / servicio
|
||||||
|
motivo_upper = (req.motivo or "").upper()
|
||||||
|
if any(m in motivo_upper for m in ["TRABAJADOR", "SERVICIO", "PROVEEDOR", "OBRA"]):
|
||||||
|
if req.art_hasta:
|
||||||
|
ah = req.art_hasta.strip().split()[0].replace('/', '-')
|
||||||
|
if ah not in ("1900-01-01", "01-01-1900", "-"):
|
||||||
|
dt_art = None
|
||||||
|
for fmt in ("%Y-%m-%d", "%d-%m-%Y"):
|
||||||
|
try:
|
||||||
|
dt_art = datetime.strptime(ah, fmt).date()
|
||||||
|
break
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
if dt_art and dt_art < datetime.now().date():
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail=f"Acceso Bloqueado: Cobertura ART / Accidentes Personales VENCIDA ({dt_art.strftime('%d/%m/%Y')}). Para personal de trabajo o servicios se exige póliza vigente.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# 7. Búsqueda preliminar para verificación de antipassback
|
||||||
|
persona_existente = AccessRepository.buscar_persona_por_documento(doc_clean)
|
||||||
if persona_existente:
|
if persona_existente:
|
||||||
pid = persona_existente["PersonaID"]
|
pid = persona_existente["PersonaID"]
|
||||||
if AccessRepository.verificar_antipassback(pid):
|
if AccessRepository.verificar_antipassback(pid):
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_409_CONFLICT,
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
detail=f"Antipassback detectado: La persona con DNI {req.documento} ya posee un ingreso activo en el predio.",
|
detail=f"Antipassback detectado: La persona con DNI {doc_clean} ya posee un ingreso activo en el predio.",
|
||||||
)
|
)
|
||||||
|
|
||||||
# 2. Búsqueda o creación de la persona
|
# 8. Búsqueda o creación de la persona
|
||||||
persona_id = AccessRepository.buscar_o_crear_persona(
|
persona_id = AccessRepository.buscar_o_crear_persona(
|
||||||
documento=req.documento,
|
documento=doc_clean,
|
||||||
apellido=req.apellido or "",
|
apellido=req.apellido or "",
|
||||||
nombre=req.nombre or "",
|
nombre=req.nombre or "",
|
||||||
sexo=req.sexo or "M",
|
sexo=req.sexo or "M",
|
||||||
)
|
)
|
||||||
|
|
||||||
# 3. Generación del TicketID
|
# 9. Generación del TicketID
|
||||||
ticket_id = AccessRepository.generar_ticket_id()
|
ticket_id = AccessRepository.generar_ticket_id()
|
||||||
|
|
||||||
# 4. Registro transaccional en base de datos
|
# 10. Registro transaccional en base de datos
|
||||||
AccessRepository.registrar_ticket_ingreso(req, persona_id, ticket_id)
|
AccessRepository.registrar_ticket_ingreso(req, persona_id, ticket_id)
|
||||||
|
|
||||||
# 5. Apertura física de barrera vía pdtmdl
|
# 11. Apertura física de barrera vía pdtmdl
|
||||||
barrier_opened = False
|
barrier_opened = False
|
||||||
if req.abrir_barrera and req.modulo_ingreso_id:
|
if req.abrir_barrera and req.modulo_ingreso_id:
|
||||||
ok, _ = HardwareService.encolar_apertura(req.modulo_ingreso_id, ticket_id)
|
ok, _ = HardwareService.encolar_apertura(req.modulo_ingreso_id, ticket_id)
|
||||||
@@ -195,3 +283,20 @@ class AccessService:
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
return resultado
|
return resultado
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def obtener_polizas_y_vehiculos_persona(documento: str) -> Optional[PersonPoliciesDTO]:
|
||||||
|
"""Obtiene el perfil extendido de coberturas, patentes y pólizas de la persona."""
|
||||||
|
datos = AccessRepository.buscar_polizas_y_vehiculos_persona(documento)
|
||||||
|
if not datos:
|
||||||
|
return None
|
||||||
|
return PersonPoliciesDTO(**datos)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def obtener_datos_vehiculo(patente: str) -> Optional[VehicleDetailsDTO]:
|
||||||
|
"""Obtiene el seguro automotor y titular asignado de un vehículo por su patente."""
|
||||||
|
datos = AccessRepository.buscar_datos_vehiculo(patente)
|
||||||
|
if not datos:
|
||||||
|
return None
|
||||||
|
return VehicleDetailsDTO(**datos)
|
||||||
|
|
||||||
|
|||||||
@@ -206,6 +206,7 @@ async def test_lot_permission_and_occupants_api():
|
|||||||
"apellido": "GARCIA",
|
"apellido": "GARCIA",
|
||||||
"nombre": "ROBERTO",
|
"nombre": "ROBERTO",
|
||||||
"patente": "GRC888",
|
"patente": "GRC888",
|
||||||
|
"lote_codigo": "1",
|
||||||
"cantidad_ocupantes": 3,
|
"cantidad_ocupantes": 3,
|
||||||
"abrir_barrera": False,
|
"abrir_barrera": False,
|
||||||
"integrantes": [
|
"integrantes": [
|
||||||
@@ -272,3 +273,95 @@ async def test_lot_permission_and_occupants_api():
|
|||||||
cursor.execute("DELETE FROM tckper WHERE TicketID = %s", (tid,))
|
cursor.execute("DELETE FROM tckper WHERE TicketID = %s", (tid,))
|
||||||
cursor.execute("DELETE FROM tck WHERE TicketID = %s", (tid,))
|
cursor.execute("DELETE FROM tck WHERE TicketID = %s", (tid,))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_validations_and_policies():
|
||||||
|
"""Valida los chequeos de paridad de OnEverAccess (documento, nombre, lote, seguro automotor, ART)."""
|
||||||
|
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. Falta nombre -> 422
|
||||||
|
res_no_nombre = await client.post(
|
||||||
|
"/api/v1/access/entry",
|
||||||
|
json={
|
||||||
|
"modulo_ingreso_id": 100004,
|
||||||
|
"documento": "11223344",
|
||||||
|
"nombre": "",
|
||||||
|
"lote_codigo": "100",
|
||||||
|
"tipo_ingreso": "PEATON",
|
||||||
|
},
|
||||||
|
cookies={"access_token": token},
|
||||||
|
)
|
||||||
|
assert res_no_nombre.status_code == 422
|
||||||
|
assert "nombre" in res_no_nombre.json()["detail"].lower()
|
||||||
|
|
||||||
|
# 2. Falta lote -> 422
|
||||||
|
res_no_lote = await client.post(
|
||||||
|
"/api/v1/access/entry",
|
||||||
|
json={
|
||||||
|
"modulo_ingreso_id": 100004,
|
||||||
|
"documento": "11223344",
|
||||||
|
"nombre": "CARLOS",
|
||||||
|
"tipo_ingreso": "PEATON",
|
||||||
|
},
|
||||||
|
cookies={"access_token": token},
|
||||||
|
)
|
||||||
|
assert res_no_lote.status_code == 422
|
||||||
|
assert "lote" in res_no_lote.json()["detail"].lower()
|
||||||
|
|
||||||
|
# 3. Conductor sin patente -> 422
|
||||||
|
res_no_patente = await client.post(
|
||||||
|
"/api/v1/access/entry",
|
||||||
|
json={
|
||||||
|
"modulo_ingreso_id": 100004,
|
||||||
|
"documento": "11223344",
|
||||||
|
"nombre": "CARLOS",
|
||||||
|
"lote_codigo": "100",
|
||||||
|
"tipo_ingreso": "CONDUCTOR",
|
||||||
|
"patente": "",
|
||||||
|
},
|
||||||
|
cookies={"access_token": token},
|
||||||
|
)
|
||||||
|
assert res_no_patente.status_code == 422
|
||||||
|
assert "patente" in res_no_patente.json()["detail"].lower()
|
||||||
|
|
||||||
|
# 4. Conductor con seguro automotor vencido -> 403
|
||||||
|
res_seguro_vencido = await client.post(
|
||||||
|
"/api/v1/access/entry",
|
||||||
|
json={
|
||||||
|
"modulo_ingreso_id": 100004,
|
||||||
|
"documento": "11223344",
|
||||||
|
"nombre": "CARLOS",
|
||||||
|
"lote_codigo": "100",
|
||||||
|
"tipo_ingreso": "CONDUCTOR",
|
||||||
|
"patente": "ABC123",
|
||||||
|
"seguro_hasta": "2020-01-01",
|
||||||
|
},
|
||||||
|
cookies={"access_token": token},
|
||||||
|
)
|
||||||
|
assert res_seguro_vencido.status_code == 403
|
||||||
|
assert "seguro" in res_seguro_vencido.json()["detail"].lower()
|
||||||
|
|
||||||
|
# 5. Trabajador con ART vencida -> 403
|
||||||
|
res_art_vencida = await client.post(
|
||||||
|
"/api/v1/access/entry",
|
||||||
|
json={
|
||||||
|
"modulo_ingreso_id": 100004,
|
||||||
|
"documento": "11223344",
|
||||||
|
"nombre": "CARLOS",
|
||||||
|
"lote_codigo": "100",
|
||||||
|
"tipo_ingreso": "PEATON",
|
||||||
|
"motivo": "TRABAJADOR DE OBRA",
|
||||||
|
"art_hasta": "2021-05-10",
|
||||||
|
},
|
||||||
|
cookies={"access_token": token},
|
||||||
|
)
|
||||||
|
assert res_art_vencida.status_code == 403
|
||||||
|
assert "art" in res_art_vencida.json()["detail"].lower()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -69,5 +69,18 @@ export const accessApi = {
|
|||||||
method: 'GET',
|
method: 'GET',
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
|
getPersonDetails: (documento: string) => {
|
||||||
|
return request<import('../types').PersonPolicies>(`/access/people/${encodeURIComponent(documento)}/details`, {
|
||||||
|
method: 'GET',
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
getVehicleDetails: (patente: string) => {
|
||||||
|
return request<import('../types').VehicleDetails>(`/access/vehicles/${encodeURIComponent(patente)}/details`, {
|
||||||
|
method: 'GET',
|
||||||
|
});
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -38,17 +38,67 @@ export interface EntryFormData {
|
|||||||
apellido: string;
|
apellido: string;
|
||||||
nombre: string;
|
nombre: string;
|
||||||
sexo: string;
|
sexo: string;
|
||||||
|
tipo_ingreso: 'CONDUCTOR' | 'PEATON';
|
||||||
patente: string;
|
patente: string;
|
||||||
lote_id?: number | null;
|
lote_id?: number | null;
|
||||||
lote_codigo: string;
|
lote_codigo: string;
|
||||||
motivo: string;
|
motivo: string;
|
||||||
|
entidad?: string;
|
||||||
cantidad_ocupantes: number;
|
cantidad_ocupantes: number;
|
||||||
cantidad_menores: number;
|
cantidad_menores: number;
|
||||||
cacheo_salida: boolean;
|
cacheo_salida: boolean;
|
||||||
abrir_barrera: boolean;
|
abrir_barrera: boolean;
|
||||||
integrantes: Companion[];
|
integrantes: Companion[];
|
||||||
|
seguro_empresa?: string;
|
||||||
|
seguro_poliza?: string;
|
||||||
|
seguro_desde?: string;
|
||||||
|
seguro_hasta?: string;
|
||||||
|
art_empresa?: string;
|
||||||
|
art_poliza?: string;
|
||||||
|
art_desde?: string;
|
||||||
|
art_hasta?: string;
|
||||||
|
licencia_nro?: string;
|
||||||
|
licencia_entidad?: string;
|
||||||
|
licencia_hasta?: string;
|
||||||
|
observaciones?: string;
|
||||||
|
forzar_ingreso_lote_restringido?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface PersonPolicies {
|
||||||
|
persona_id: number;
|
||||||
|
documento: string;
|
||||||
|
apellido: string;
|
||||||
|
nombre: string;
|
||||||
|
sexo: string;
|
||||||
|
patente_sugerida?: string | null;
|
||||||
|
patentes_asociadas: string[];
|
||||||
|
seguro_empresa?: string | null;
|
||||||
|
seguro_poliza?: string | null;
|
||||||
|
seguro_desde?: string | null;
|
||||||
|
seguro_hasta?: string | null;
|
||||||
|
art_empresa?: string | null;
|
||||||
|
art_poliza?: string | null;
|
||||||
|
art_desde?: string | null;
|
||||||
|
art_hasta?: string | null;
|
||||||
|
licencia_nro?: string | null;
|
||||||
|
licencia_entidad?: string | null;
|
||||||
|
licencia_hasta?: string | null;
|
||||||
|
observaciones?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VehicleDetails {
|
||||||
|
patente: string;
|
||||||
|
aseguradora?: string | null;
|
||||||
|
poliza_nro?: string | null;
|
||||||
|
vigencia_desde?: string | null;
|
||||||
|
vigencia_hasta?: string | null;
|
||||||
|
persona_id?: number | null;
|
||||||
|
apellido?: string | null;
|
||||||
|
nombre?: string | null;
|
||||||
|
documento?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
export interface LotPermission {
|
export interface LotPermission {
|
||||||
estado: string;
|
estado: string;
|
||||||
color: string;
|
color: string;
|
||||||
|
|||||||
@@ -46,17 +46,37 @@ export const ControlPostView: React.FC = () => {
|
|||||||
apellido: '',
|
apellido: '',
|
||||||
nombre: '',
|
nombre: '',
|
||||||
sexo: 'M',
|
sexo: 'M',
|
||||||
|
tipo_ingreso: 'CONDUCTOR',
|
||||||
patente: '',
|
patente: '',
|
||||||
lote_id: null,
|
lote_id: null,
|
||||||
lote_codigo: '',
|
lote_codigo: '',
|
||||||
motivo: 'VISITA',
|
motivo: 'VISITA',
|
||||||
|
entidad: '',
|
||||||
cantidad_ocupantes: 1,
|
cantidad_ocupantes: 1,
|
||||||
cantidad_menores: 0,
|
cantidad_menores: 0,
|
||||||
cacheo_salida: false,
|
cacheo_salida: false,
|
||||||
abrir_barrera: true,
|
abrir_barrera: true,
|
||||||
integrantes: [],
|
integrantes: [],
|
||||||
|
seguro_empresa: '',
|
||||||
|
seguro_poliza: '',
|
||||||
|
seguro_desde: '',
|
||||||
|
seguro_hasta: '',
|
||||||
|
art_empresa: '',
|
||||||
|
art_poliza: '',
|
||||||
|
art_desde: '',
|
||||||
|
art_hasta: '',
|
||||||
|
licencia_nro: '',
|
||||||
|
licencia_entidad: '',
|
||||||
|
licencia_hasta: '',
|
||||||
|
observaciones: '',
|
||||||
|
forzar_ingreso_lote_restringido: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const [associatedPatentes, setAssociatedPatentes] = useState<string[]>([]);
|
||||||
|
const [showPoliciesSection, setShowPoliciesSection] = useState<boolean>(true);
|
||||||
|
const [confirmRestrictedModal, setConfirmRestrictedModal] = useState<boolean>(false);
|
||||||
|
|
||||||
|
|
||||||
// Autocompletado y validación de Lotes
|
// Autocompletado y validación de Lotes
|
||||||
const [lotSuggestions, setLotSuggestions] = useState<LotSearchItem[]>([]);
|
const [lotSuggestions, setLotSuggestions] = useState<LotSearchItem[]>([]);
|
||||||
const [showLotSuggestions, setShowLotSuggestions] = useState<boolean>(false);
|
const [showLotSuggestions, setShowLotSuggestions] = useState<boolean>(false);
|
||||||
@@ -208,6 +228,97 @@ export const ControlPostView: React.FC = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Evaluación de vigencia de pólizas (Paridad pct_view.py)
|
||||||
|
const getPolicyStatus = (dateStr?: string) => {
|
||||||
|
if (!dateStr || dateStr === '1900-01-01' || dateStr === '-' || !dateStr.trim()) {
|
||||||
|
return { status: 'missing', label: 'Sin Cargar', color: '#ff9800', bg: 'rgba(255, 152, 0, 0.15)', border: '#ff9800' };
|
||||||
|
}
|
||||||
|
const clean = dateStr.split(' ')[0].replace(/\//g, '-');
|
||||||
|
let dt: Date | null = null;
|
||||||
|
const parts = clean.split('-');
|
||||||
|
if (parts.length === 3) {
|
||||||
|
if (parts[0].length === 4) {
|
||||||
|
dt = new Date(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2]));
|
||||||
|
} else {
|
||||||
|
dt = new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!dt || isNaN(dt.getTime())) {
|
||||||
|
return { status: 'invalid', label: 'Inválida', color: '#f44336', bg: 'rgba(244, 67, 54, 0.15)', border: '#f44336' };
|
||||||
|
}
|
||||||
|
const today = new Date();
|
||||||
|
today.setHours(0, 0, 0, 0);
|
||||||
|
if (dt < today) {
|
||||||
|
return { status: 'expired', label: 'VENCIDA', color: '#f44336', bg: 'rgba(244, 67, 54, 0.2)', border: '#f44336' };
|
||||||
|
}
|
||||||
|
return { status: 'valid', label: 'VIGENTE', color: '#4caf50', bg: 'rgba(76, 175, 80, 0.15)', border: '#4caf50' };
|
||||||
|
};
|
||||||
|
|
||||||
|
// Carga predictiva al tipear o escanear DNI
|
||||||
|
const lookupPerson = useCallback(async (doc: string) => {
|
||||||
|
const clean = doc.trim();
|
||||||
|
if (clean.length < 4) return;
|
||||||
|
try {
|
||||||
|
const details = await accessApi.getPersonDetails(clean);
|
||||||
|
if (details) {
|
||||||
|
setAssociatedPatentes(details.patentes_asociadas || []);
|
||||||
|
setForm((prev) => ({
|
||||||
|
...prev,
|
||||||
|
apellido: details.apellido || prev.apellido,
|
||||||
|
nombre: details.nombre || prev.nombre,
|
||||||
|
sexo: details.sexo || prev.sexo,
|
||||||
|
patente: prev.patente || details.patente_sugerida || '',
|
||||||
|
seguro_empresa: details.seguro_empresa || prev.seguro_empresa,
|
||||||
|
seguro_poliza: details.seguro_poliza || prev.seguro_poliza,
|
||||||
|
seguro_desde: details.seguro_desde || prev.seguro_desde,
|
||||||
|
seguro_hasta: details.seguro_hasta || prev.seguro_hasta,
|
||||||
|
art_empresa: details.art_empresa || prev.art_empresa,
|
||||||
|
art_poliza: details.art_poliza || prev.art_poliza,
|
||||||
|
art_desde: details.art_desde || prev.art_desde,
|
||||||
|
art_hasta: details.art_hasta || prev.art_hasta,
|
||||||
|
licencia_nro: details.licencia_nro || prev.licencia_nro,
|
||||||
|
licencia_entidad: details.licencia_entidad || prev.licencia_entidad,
|
||||||
|
licencia_hasta: details.licencia_hasta || prev.licencia_hasta,
|
||||||
|
observaciones: details.observaciones || prev.observaciones,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Persona nueva sin registro previo
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Carga predictiva al tipear o seleccionar patente
|
||||||
|
const lookupVehicle = useCallback(async (pat: string) => {
|
||||||
|
const clean = pat.replace(/[\s-]/g, '').toUpperCase();
|
||||||
|
if (clean.length < 6) return;
|
||||||
|
try {
|
||||||
|
const v = await accessApi.getVehicleDetails(clean);
|
||||||
|
if (v) {
|
||||||
|
setForm((prev) => ({
|
||||||
|
...prev,
|
||||||
|
seguro_empresa: v.aseguradora || prev.seguro_empresa,
|
||||||
|
seguro_poliza: v.poliza_nro || prev.seguro_poliza,
|
||||||
|
seguro_desde: v.vigencia_desde || prev.seguro_desde,
|
||||||
|
seguro_hasta: v.vigencia_hasta || prev.seguro_hasta,
|
||||||
|
documento: prev.documento || v.documento || '',
|
||||||
|
apellido: prev.apellido || v.apellido || '',
|
||||||
|
nombre: prev.nombre || v.nombre || '',
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Auto nuevo
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const setQuickExpiry = (field: 'seguro_hasta' | 'art_hasta' | 'licencia_hasta', months: number) => {
|
||||||
|
const d = new Date();
|
||||||
|
d.setMonth(d.getMonth() + months);
|
||||||
|
const yyyy = d.getFullYear();
|
||||||
|
const mm = String(d.getMonth() + 1).padStart(2, '0');
|
||||||
|
const dd = String(d.getDate()).padStart(2, '0');
|
||||||
|
setForm((prev) => ({ ...prev, [field]: `${yyyy}-${mm}-${dd}` }));
|
||||||
|
};
|
||||||
|
|
||||||
// Callback al escanear DNI con cámara
|
// Callback al escanear DNI con cámara
|
||||||
const handleDniScanned = (data: DNIParsedResult) => {
|
const handleDniScanned = (data: DNIParsedResult) => {
|
||||||
setForm((prev) => ({
|
setForm((prev) => ({
|
||||||
@@ -217,17 +328,71 @@ export const ControlPostView: React.FC = () => {
|
|||||||
nombre: data.nombre,
|
nombre: data.nombre,
|
||||||
sexo: data.sexo || 'M',
|
sexo: data.sexo || 'M',
|
||||||
}));
|
}));
|
||||||
|
lookupPerson(data.documento);
|
||||||
setActionSuccess(`DNI escaneado exitosamente: ${data.apellido}, ${data.nombre} (${data.documento})`);
|
setActionSuccess(`DNI escaneado exitosamente: ${data.apellido}, ${data.nombre} (${data.documento})`);
|
||||||
setTimeout(() => setActionSuccess(null), 4000);
|
setTimeout(() => setActionSuccess(null), 4000);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Envío del formulario de Ingreso
|
// Envío del formulario de Ingreso con Validación Estricta
|
||||||
const handleRegisterEntry = async (e: React.FormEvent) => {
|
const handleRegisterEntry = async (e?: React.FormEvent, forceRestricted = false) => {
|
||||||
e.preventDefault();
|
if (e) e.preventDefault();
|
||||||
if (!form.documento.trim()) {
|
|
||||||
setActionError('El número de documento es obligatorio.');
|
// 1. Validar Documento
|
||||||
|
const docClean = form.documento.trim();
|
||||||
|
if (!docClean || docClean.length < 4) {
|
||||||
|
setActionError('El número de documento es obligatorio (mínimo 4 caracteres).');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 2. Validar Nombre
|
||||||
|
if (!form.nombre.trim()) {
|
||||||
|
setActionError('El nombre de la persona es obligatorio.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Validar Lote de Destino
|
||||||
|
if (!form.lote_id && !form.lote_codigo.trim()) {
|
||||||
|
setActionError('Debe seleccionar el lote de destino (obligatorio).');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Validar Restricción de Lote (Categoría 26)
|
||||||
|
if (lotPermission?.estado === 'Restringido' && !forceRestricted && !form.forzar_ingreso_lote_restringido) {
|
||||||
|
setConfirmRestrictedModal(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Validar Conductor (Patente y Seguro)
|
||||||
|
if (form.tipo_ingreso === 'CONDUCTOR') {
|
||||||
|
const patClean = form.patente.trim().toUpperCase();
|
||||||
|
if (!patClean) {
|
||||||
|
setActionError('Falta la Patente del vehículo (obligatoria para conductores).');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const segStat = getPolicyStatus(form.seguro_hasta);
|
||||||
|
if (segStat.status === 'missing' || segStat.status === 'invalid' || segStat.status === 'expired') {
|
||||||
|
setActionError(
|
||||||
|
`Acceso Bloqueado: Seguro Automotor Inválido (${segStat.label}). Por políticas de seguridad, no se autoriza el ingreso de vehículos sin cobertura de seguro vigente.`
|
||||||
|
);
|
||||||
|
setShowPoliciesSection(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. Validar ART para Trabajadores / Servicios / Proveedores
|
||||||
|
const esTrabajador = ['TRABAJADOR', 'SERVICIO', 'PROVEEDOR', 'OBRA'].includes(form.motivo);
|
||||||
|
if (esTrabajador && form.art_hasta) {
|
||||||
|
const artStat = getPolicyStatus(form.art_hasta);
|
||||||
|
if (artStat.status === 'expired' || artStat.status === 'invalid') {
|
||||||
|
setActionError(
|
||||||
|
`Acceso Bloqueado: Cobertura ART / Accidentes Personales ${artStat.label}. Para personal de trabajo se exige póliza vigente.`
|
||||||
|
);
|
||||||
|
setShowPoliciesSection(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!selectedEntryModuleId) {
|
if (!selectedEntryModuleId) {
|
||||||
setActionError('Debe seleccionar un módulo de entrada.');
|
setActionError('Debe seleccionar un módulo de entrada.');
|
||||||
return;
|
return;
|
||||||
@@ -241,34 +406,52 @@ export const ControlPostView: React.FC = () => {
|
|||||||
const payload: EntryFormData = {
|
const payload: EntryFormData = {
|
||||||
...form,
|
...form,
|
||||||
modulo_ingreso_id: selectedEntryModuleId,
|
modulo_ingreso_id: selectedEntryModuleId,
|
||||||
documento: form.documento.trim(),
|
documento: docClean,
|
||||||
apellido: form.apellido.trim().toUpperCase(),
|
apellido: form.apellido.trim().toUpperCase(),
|
||||||
nombre: form.nombre.trim().toUpperCase(),
|
nombre: form.nombre.trim().toUpperCase(),
|
||||||
patente: form.patente.trim().toUpperCase() || '',
|
patente: form.tipo_ingreso === 'CONDUCTOR' ? form.patente.trim().toUpperCase() : '',
|
||||||
|
forzar_ingreso_lote_restringido: forceRestricted || form.forzar_ingreso_lote_restringido,
|
||||||
};
|
};
|
||||||
|
|
||||||
const res = await accessApi.registerEntry(payload);
|
const res = await accessApi.registerEntry(payload);
|
||||||
setActionSuccess(`Ingreso registrado con éxito (Ticket #${res.ticket_id}) - ${res.barrier_opened ? 'Barrera Abierta' : ''}`);
|
setActionSuccess(`✓ Ingreso registrado con éxito (Ticket #${res.ticket_id}) - ${res.barrier_opened ? 'Barrera Abierta' : ''}`);
|
||||||
setTimeout(() => setActionSuccess(null), 5000);
|
setTimeout(() => setActionSuccess(null), 5000);
|
||||||
|
|
||||||
// Limpiar formulario para el siguiente vehículo
|
// Limpiar formulario para el siguiente acceso
|
||||||
setForm({
|
setForm({
|
||||||
modulo_ingreso_id: selectedEntryModuleId,
|
modulo_ingreso_id: selectedEntryModuleId,
|
||||||
documento: '',
|
documento: '',
|
||||||
apellido: '',
|
apellido: '',
|
||||||
nombre: '',
|
nombre: '',
|
||||||
sexo: 'M',
|
sexo: 'M',
|
||||||
|
tipo_ingreso: 'CONDUCTOR',
|
||||||
patente: '',
|
patente: '',
|
||||||
lote_id: null,
|
lote_id: null,
|
||||||
lote_codigo: '',
|
lote_codigo: '',
|
||||||
motivo: 'VISITA',
|
motivo: 'VISITA',
|
||||||
|
entidad: '',
|
||||||
cantidad_ocupantes: 1,
|
cantidad_ocupantes: 1,
|
||||||
cantidad_menores: 0,
|
cantidad_menores: 0,
|
||||||
cacheo_salida: false,
|
cacheo_salida: false,
|
||||||
abrir_barrera: true,
|
abrir_barrera: true,
|
||||||
integrantes: [],
|
integrantes: [],
|
||||||
|
seguro_empresa: '',
|
||||||
|
seguro_poliza: '',
|
||||||
|
seguro_desde: '',
|
||||||
|
seguro_hasta: '',
|
||||||
|
art_empresa: '',
|
||||||
|
art_poliza: '',
|
||||||
|
art_desde: '',
|
||||||
|
art_hasta: '',
|
||||||
|
licencia_nro: '',
|
||||||
|
licencia_entidad: '',
|
||||||
|
licencia_hasta: '',
|
||||||
|
observaciones: '',
|
||||||
|
forzar_ingreso_lote_restringido: false,
|
||||||
});
|
});
|
||||||
|
setAssociatedPatentes([]);
|
||||||
setLotPermission(null);
|
setLotPermission(null);
|
||||||
|
setConfirmRestrictedModal(false);
|
||||||
|
|
||||||
loadActiveTickets();
|
loadActiveTickets();
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
@@ -278,6 +461,7 @@ export const ControlPostView: React.FC = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
// Abrir diálogo interactivo de verificación de salida
|
// Abrir diálogo interactivo de verificación de salida
|
||||||
const handleOpenExitModal = (ticket: ActiveTicket) => {
|
const handleOpenExitModal = (ticket: ActiveTicket) => {
|
||||||
if (!selectedExitModuleId) {
|
if (!selectedExitModuleId) {
|
||||||
@@ -615,7 +799,53 @@ export const ControlPostView: React.FC = () => {
|
|||||||
ESCANEAR DNI CON CÁMARA
|
ESCANEAR DNI CON CÁMARA
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<form onSubmit={handleRegisterEntry} style={{ display: 'flex', flexDirection: 'column', gap: '0.85rem' }}>
|
<form onSubmit={(e) => handleRegisterEntry(e)} style={{ display: 'flex', flexDirection: 'column', gap: '0.85rem' }}>
|
||||||
|
{/* Selector de Modo: Conductor (Vehicular) vs Peatón (Tablet Friendly 48px) */}
|
||||||
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.5rem' }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setForm((prev) => ({ ...prev, tipo_ingreso: 'CONDUCTOR' }))}
|
||||||
|
style={{
|
||||||
|
minHeight: '48px',
|
||||||
|
borderRadius: '8px',
|
||||||
|
border: form.tipo_ingreso === 'CONDUCTOR' ? '2px solid var(--accent-primary)' : '1px solid var(--border-subtle)',
|
||||||
|
backgroundColor: form.tipo_ingreso === 'CONDUCTOR' ? 'var(--accent-primary)' : 'var(--bg-card)',
|
||||||
|
color: form.tipo_ingreso === 'CONDUCTOR' ? '#fff' : 'var(--text-primary)',
|
||||||
|
fontWeight: 700,
|
||||||
|
fontSize: '0.95rem',
|
||||||
|
cursor: 'pointer',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
gap: '0.45rem',
|
||||||
|
transition: 'all 0.15s ease',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span>🚗</span> Conductor
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setForm((prev) => ({ ...prev, tipo_ingreso: 'PEATON' }))}
|
||||||
|
style={{
|
||||||
|
minHeight: '48px',
|
||||||
|
borderRadius: '8px',
|
||||||
|
border: form.tipo_ingreso === 'PEATON' ? '2px solid var(--accent-primary)' : '1px solid var(--border-subtle)',
|
||||||
|
backgroundColor: form.tipo_ingreso === 'PEATON' ? 'var(--accent-primary)' : 'var(--bg-card)',
|
||||||
|
color: form.tipo_ingreso === 'PEATON' ? '#fff' : 'var(--text-primary)',
|
||||||
|
fontWeight: 700,
|
||||||
|
fontSize: '0.95rem',
|
||||||
|
cursor: 'pointer',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
gap: '0.45rem',
|
||||||
|
transition: 'all 0.15s ease',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span>🚶</span> Peatón
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Selector de Módulo de Entrada */}
|
{/* Selector de Módulo de Entrada */}
|
||||||
{config && config.entry_modules.length > 0 && (
|
{config && config.entry_modules.length > 0 && (
|
||||||
<div>
|
<div>
|
||||||
@@ -645,17 +875,45 @@ export const ControlPostView: React.FC = () => {
|
|||||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 90px', gap: '0.5rem' }}>
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 90px', gap: '0.5rem' }}>
|
||||||
<div>
|
<div>
|
||||||
<label style={{ fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
<label style={{ fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
||||||
DOCUMENTO / DNI:
|
DOCUMENTO / DNI <span style={{ color: '#f44336' }}>*</span>:
|
||||||
</label>
|
</label>
|
||||||
<input
|
<div style={{ position: 'relative', marginTop: '0.25rem' }}>
|
||||||
type="text"
|
<input
|
||||||
className="input-touch"
|
type="text"
|
||||||
value={form.documento}
|
className="input-touch"
|
||||||
onChange={(e) => setForm((prev) => ({ ...prev, documento: e.target.value }))}
|
value={form.documento}
|
||||||
placeholder="Ej: 30123456"
|
onChange={(e) => setForm((prev) => ({ ...prev, documento: e.target.value }))}
|
||||||
required
|
onBlur={() => lookupPerson(form.documento)}
|
||||||
style={{ width: '100%', marginTop: '0.25rem' }}
|
onKeyDown={(e) => {
|
||||||
/>
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
lookupPerson(form.documento);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
placeholder="Ej: 30123456"
|
||||||
|
required
|
||||||
|
style={{ width: '100%', paddingRight: '2rem' }}
|
||||||
|
/>
|
||||||
|
{form.documento && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setForm((prev) => ({ ...prev, documento: '' }))}
|
||||||
|
style={{
|
||||||
|
position: 'absolute',
|
||||||
|
right: '8px',
|
||||||
|
top: '50%',
|
||||||
|
transform: 'translateY(-50%)',
|
||||||
|
background: 'none',
|
||||||
|
border: 'none',
|
||||||
|
color: 'var(--text-muted)',
|
||||||
|
cursor: 'pointer',
|
||||||
|
fontSize: '1rem',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label style={{ fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
<label style={{ fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
||||||
@@ -691,7 +949,7 @@ export const ControlPostView: React.FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label style={{ fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
<label style={{ fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
||||||
NOMBRE:
|
NOMBRE <span style={{ color: '#f44336' }}>*</span>:
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
@@ -699,30 +957,70 @@ export const ControlPostView: React.FC = () => {
|
|||||||
value={form.nombre}
|
value={form.nombre}
|
||||||
onChange={(e) => setForm((prev) => ({ ...prev, nombre: e.target.value }))}
|
onChange={(e) => setForm((prev) => ({ ...prev, nombre: e.target.value }))}
|
||||||
placeholder="Ej: JUAN"
|
placeholder="Ej: JUAN"
|
||||||
|
required
|
||||||
style={{ width: '100%', marginTop: '0.25rem', textTransform: 'uppercase' }}
|
style={{ width: '100%', marginTop: '0.25rem', textTransform: 'uppercase' }}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Patente y Lote de Destino con Autocomplete */}
|
{/* Patente (Solo si Conductor) y Lote de Destino con Autocomplete */}
|
||||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.5rem' }}>
|
<div style={{ display: 'grid', gridTemplateColumns: form.tipo_ingreso === 'CONDUCTOR' ? '1fr 1fr' : '1fr', gap: '0.5rem' }}>
|
||||||
<div>
|
{form.tipo_ingreso === 'CONDUCTOR' && (
|
||||||
<label style={{ fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
<div>
|
||||||
PATENTE VEHÍCULO:
|
<label style={{ fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
||||||
</label>
|
PATENTE VEHÍCULO <span style={{ color: '#f44336' }}>*</span>:
|
||||||
<input
|
</label>
|
||||||
type="text"
|
<input
|
||||||
className="input-touch"
|
type="text"
|
||||||
value={form.patente}
|
className="input-touch"
|
||||||
onChange={(e) => setForm((prev) => ({ ...prev, patente: e.target.value.toUpperCase() }))}
|
value={form.patente}
|
||||||
placeholder="Ej: AB123CD"
|
onChange={(e) => {
|
||||||
style={{ width: '100%', marginTop: '0.25rem', textTransform: 'uppercase' }}
|
const p = e.target.value.toUpperCase();
|
||||||
/>
|
setForm((prev) => ({ ...prev, patente: p }));
|
||||||
</div>
|
}}
|
||||||
|
onBlur={() => lookupVehicle(form.patente)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
lookupVehicle(form.patente);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
placeholder="Ej: AB123CD"
|
||||||
|
style={{ width: '100%', marginTop: '0.25rem', textTransform: 'uppercase' }}
|
||||||
|
/>
|
||||||
|
{associatedPatentes.length > 0 && (
|
||||||
|
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.3rem', marginTop: '0.35rem' }}>
|
||||||
|
<span style={{ fontSize: '0.7rem', color: 'var(--text-secondary)', alignSelf: 'center' }}>Sugeridas:</span>
|
||||||
|
{associatedPatentes.map((p) => (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
key={p}
|
||||||
|
onClick={() => {
|
||||||
|
setForm((prev) => ({ ...prev, patente: p }));
|
||||||
|
lookupVehicle(p);
|
||||||
|
}}
|
||||||
|
style={{
|
||||||
|
padding: '0.2rem 0.5rem',
|
||||||
|
borderRadius: '4px',
|
||||||
|
border: '1px solid var(--border-subtle)',
|
||||||
|
backgroundColor: form.patente === p ? 'var(--accent-primary)' : 'var(--bg-app)',
|
||||||
|
color: form.patente === p ? '#fff' : 'var(--text-primary)',
|
||||||
|
fontSize: '0.75rem',
|
||||||
|
fontWeight: 700,
|
||||||
|
cursor: 'pointer',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{p}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div style={{ position: 'relative' }}>
|
<div style={{ position: 'relative' }}>
|
||||||
<label style={{ fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
<label style={{ fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
||||||
LOTE / DESTINO:
|
LOTE / DESTINO <span style={{ color: '#f44336' }}>*</span>:
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
@@ -733,6 +1031,7 @@ export const ControlPostView: React.FC = () => {
|
|||||||
if (lotSuggestions.length > 0) setShowLotSuggestions(true);
|
if (lotSuggestions.length > 0) setShowLotSuggestions(true);
|
||||||
}}
|
}}
|
||||||
placeholder="Ej: 142"
|
placeholder="Ej: 142"
|
||||||
|
required
|
||||||
style={{ width: '100%', marginTop: '0.25rem' }}
|
style={{ width: '100%', marginTop: '0.25rem' }}
|
||||||
/>
|
/>
|
||||||
{/* Desplegable de sugerencias de Lotes */}
|
{/* Desplegable de sugerencias de Lotes */}
|
||||||
@@ -902,11 +1201,292 @@ export const ControlPostView: React.FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<span style={{ fontSize: '0.75rem', color: 'var(--text-secondary)' }}>
|
<span style={{ fontSize: '0.75rem', color: 'var(--text-secondary)' }}>
|
||||||
Solo conductor registrado. Haga clic en "+ Cargar Acompañantes" para registrar más ocupantes.
|
{form.tipo_ingreso === 'CONDUCTOR' ? 'Solo conductor.' : 'Solo peatón.'} Presione "+ Cargar Acompañantes" para registrar más ocupantes.
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* ===================================================================
|
||||||
|
SECCIÓN DE DOCUMENTACIÓN Y PÓLIZAS (Seguro / ART / Licencia)
|
||||||
|
=================================================================== */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
backgroundColor: 'var(--bg-card)',
|
||||||
|
borderRadius: '8px',
|
||||||
|
border: '1px solid var(--border-subtle)',
|
||||||
|
overflow: 'hidden',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* Cabecera del Accordion con Badges de Estado */}
|
||||||
|
<div
|
||||||
|
onClick={() => setShowPoliciesSection((prev) => !prev)}
|
||||||
|
style={{
|
||||||
|
padding: '0.65rem 0.85rem',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
cursor: 'pointer',
|
||||||
|
backgroundColor: 'var(--bg-surface)',
|
||||||
|
borderBottom: showPoliciesSection ? '1px solid var(--border-subtle)' : 'none',
|
||||||
|
userSelect: 'none',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: '0.45rem', flexWrap: 'wrap' }}>
|
||||||
|
<span style={{ fontSize: '0.95rem' }}>🛡️</span>
|
||||||
|
<span style={{ fontSize: '0.85rem', fontWeight: 700, color: 'var(--text-primary)' }}>
|
||||||
|
Pólizas y Coberturas
|
||||||
|
</span>
|
||||||
|
{form.tipo_ingreso === 'CONDUCTOR' && (
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
fontSize: '0.7rem',
|
||||||
|
padding: '0.12rem 0.4rem',
|
||||||
|
borderRadius: '4px',
|
||||||
|
backgroundColor: getPolicyStatus(form.seguro_hasta).bg,
|
||||||
|
color: getPolicyStatus(form.seguro_hasta).color,
|
||||||
|
border: `1px solid ${getPolicyStatus(form.seguro_hasta).border}`,
|
||||||
|
fontWeight: 700,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Seguro: {getPolicyStatus(form.seguro_hasta).label}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{['TRABAJADOR', 'SERVICIO', 'PROVEEDOR', 'OBRA'].includes(form.motivo) && (
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
fontSize: '0.7rem',
|
||||||
|
padding: '0.12rem 0.4rem',
|
||||||
|
borderRadius: '4px',
|
||||||
|
backgroundColor: getPolicyStatus(form.art_hasta).bg,
|
||||||
|
color: getPolicyStatus(form.art_hasta).color,
|
||||||
|
border: `1px solid ${getPolicyStatus(form.art_hasta).border}`,
|
||||||
|
fontWeight: 700,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
ART: {getPolicyStatus(form.art_hasta).label}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<span style={{ fontSize: '0.85rem', color: 'var(--text-secondary)' }}>
|
||||||
|
{showPoliciesSection ? '▲' : '▼'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{showPoliciesSection && (
|
||||||
|
<div style={{ padding: '0.75rem', display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
|
||||||
|
{/* 1. Seguro Automotor (Solo Conductor) */}
|
||||||
|
{form.tipo_ingreso === 'CONDUCTOR' && (
|
||||||
|
<div style={{ padding: '0.6rem', borderRadius: '6px', backgroundColor: 'var(--bg-app)', border: '1px solid var(--border-subtle)' }}>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '0.4rem' }}>
|
||||||
|
<span style={{ fontSize: '0.8rem', fontWeight: 700, color: 'var(--text-primary)' }}>
|
||||||
|
🚗 Seguro Automotor <span style={{ color: '#f44336' }}>*</span>
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
fontSize: '0.7rem',
|
||||||
|
padding: '0.12rem 0.45rem',
|
||||||
|
borderRadius: '4px',
|
||||||
|
backgroundColor: getPolicyStatus(form.seguro_hasta).bg,
|
||||||
|
color: getPolicyStatus(form.seguro_hasta).color,
|
||||||
|
fontWeight: 700,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{getPolicyStatus(form.seguro_hasta).label}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.4rem', marginBottom: '0.4rem' }}>
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Aseguradora:</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="input-touch"
|
||||||
|
value={form.seguro_empresa || ''}
|
||||||
|
onChange={(e) => setForm((prev) => ({ ...prev, seguro_empresa: e.target.value }))}
|
||||||
|
placeholder="Ej: La Segunda / Zurich"
|
||||||
|
style={{ width: '100%', minHeight: '38px', fontSize: '0.85rem' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Nro. Póliza:</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="input-touch"
|
||||||
|
value={form.seguro_poliza || ''}
|
||||||
|
onChange={(e) => setForm((prev) => ({ ...prev, seguro_poliza: e.target.value }))}
|
||||||
|
placeholder="Ej: POL-998822"
|
||||||
|
style={{ width: '100%', minHeight: '38px', fontSize: '0.85rem' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||||
|
<label style={{ fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Vencimiento Cobertura:</label>
|
||||||
|
<div style={{ display: 'flex', gap: '0.25rem' }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setQuickExpiry('seguro_hasta', 1)}
|
||||||
|
style={{ fontSize: '0.68rem', padding: '0.1rem 0.4rem', borderRadius: '4px', border: '1px solid var(--border-subtle)', background: 'var(--bg-card)', cursor: 'pointer' }}
|
||||||
|
>
|
||||||
|
+1M
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setQuickExpiry('seguro_hasta', 6)}
|
||||||
|
style={{ fontSize: '0.68rem', padding: '0.1rem 0.4rem', borderRadius: '4px', border: '1px solid var(--border-subtle)', background: 'var(--bg-card)', cursor: 'pointer' }}
|
||||||
|
>
|
||||||
|
+6M
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setQuickExpiry('seguro_hasta', 12)}
|
||||||
|
style={{ fontSize: '0.68rem', padding: '0.1rem 0.4rem', borderRadius: '4px', border: '1px solid var(--border-subtle)', background: 'var(--bg-card)', cursor: 'pointer' }}
|
||||||
|
>
|
||||||
|
+1A
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
className="input-touch"
|
||||||
|
value={form.seguro_hasta || ''}
|
||||||
|
onChange={(e) => setForm((prev) => ({ ...prev, seguro_hasta: e.target.value }))}
|
||||||
|
style={{
|
||||||
|
width: '100%',
|
||||||
|
minHeight: '40px',
|
||||||
|
marginTop: '0.2rem',
|
||||||
|
border: getPolicyStatus(form.seguro_hasta).status === 'expired' ? '2px solid #f44336' : undefined,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 2. Póliza ART / Accidentes Personales */}
|
||||||
|
<div style={{ padding: '0.6rem', borderRadius: '6px', backgroundColor: 'var(--bg-app)', border: '1px solid var(--border-subtle)' }}>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '0.4rem' }}>
|
||||||
|
<span style={{ fontSize: '0.8rem', fontWeight: 700, color: 'var(--text-primary)' }}>
|
||||||
|
👷 ART / Accidentes Personales
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
fontSize: '0.7rem',
|
||||||
|
padding: '0.12rem 0.45rem',
|
||||||
|
borderRadius: '4px',
|
||||||
|
backgroundColor: getPolicyStatus(form.art_hasta).bg,
|
||||||
|
color: getPolicyStatus(form.art_hasta).color,
|
||||||
|
fontWeight: 700,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{getPolicyStatus(form.art_hasta).label}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.4rem', marginBottom: '0.4rem' }}>
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Compañía ART:</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="input-touch"
|
||||||
|
value={form.art_empresa || ''}
|
||||||
|
onChange={(e) => setForm((prev) => ({ ...prev, art_empresa: e.target.value }))}
|
||||||
|
placeholder="Ej: Prevención ART"
|
||||||
|
style={{ width: '100%', minHeight: '38px', fontSize: '0.85rem' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Nro. Póliza ART:</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="input-touch"
|
||||||
|
value={form.art_poliza || ''}
|
||||||
|
onChange={(e) => setForm((prev) => ({ ...prev, art_poliza: e.target.value }))}
|
||||||
|
placeholder="Ej: ART-5544"
|
||||||
|
style={{ width: '100%', minHeight: '38px', fontSize: '0.85rem' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||||
|
<label style={{ fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Vencimiento Cobertura ART:</label>
|
||||||
|
<div style={{ display: 'flex', gap: '0.25rem' }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setQuickExpiry('art_hasta', 1)}
|
||||||
|
style={{ fontSize: '0.68rem', padding: '0.1rem 0.4rem', borderRadius: '4px', border: '1px solid var(--border-subtle)', background: 'var(--bg-card)', cursor: 'pointer' }}
|
||||||
|
>
|
||||||
|
+1M
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setQuickExpiry('art_hasta', 6)}
|
||||||
|
style={{ fontSize: '0.68rem', padding: '0.1rem 0.4rem', borderRadius: '4px', border: '1px solid var(--border-subtle)', background: 'var(--bg-card)', cursor: 'pointer' }}
|
||||||
|
>
|
||||||
|
+6M
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
className="input-touch"
|
||||||
|
value={form.art_hasta || ''}
|
||||||
|
onChange={(e) => setForm((prev) => ({ ...prev, art_hasta: e.target.value }))}
|
||||||
|
style={{
|
||||||
|
width: '100%',
|
||||||
|
minHeight: '40px',
|
||||||
|
marginTop: '0.2rem',
|
||||||
|
border: getPolicyStatus(form.art_hasta).status === 'expired' ? '2px solid #f44336' : undefined,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 3. Licencia de Conducir (Opcional) */}
|
||||||
|
<div style={{ padding: '0.6rem', borderRadius: '6px', backgroundColor: 'var(--bg-app)', border: '1px solid var(--border-subtle)' }}>
|
||||||
|
<span style={{ fontSize: '0.8rem', fontWeight: 700, color: 'var(--text-primary)', display: 'block', marginBottom: '0.4rem' }}>
|
||||||
|
🪪 Licencia de Conducir
|
||||||
|
</span>
|
||||||
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.4rem' }}>
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Nro. Registro:</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="input-touch"
|
||||||
|
value={form.licencia_nro || ''}
|
||||||
|
onChange={(e) => setForm((prev) => ({ ...prev, licencia_nro: e.target.value }))}
|
||||||
|
placeholder="Ej: B-30123456"
|
||||||
|
style={{ width: '100%', minHeight: '38px', fontSize: '0.85rem' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Vigencia Hasta:</label>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
className="input-touch"
|
||||||
|
value={form.licencia_hasta || ''}
|
||||||
|
onChange={(e) => setForm((prev) => ({ ...prev, licencia_hasta: e.target.value }))}
|
||||||
|
style={{ width: '100%', minHeight: '38px' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 4. Observaciones */}
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: '0.7rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
||||||
|
OBSERVACIONES Y NOTAS:
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
className="input-touch"
|
||||||
|
rows={2}
|
||||||
|
value={form.observaciones || ''}
|
||||||
|
onChange={(e) => setForm((prev) => ({ ...prev, observaciones: e.target.value }))}
|
||||||
|
placeholder="Notas de guardia, autorizaciones especiales..."
|
||||||
|
style={{ width: '100%', marginTop: '0.2rem', resize: 'vertical' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Switch Abrir Barrera */}
|
{/* Switch Abrir Barrera */}
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
@@ -1350,6 +1930,81 @@ export const ControlPostView: React.FC = () => {
|
|||||||
loadActiveTickets();
|
loadActiveTickets();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* Modal de Confirmación para Lote con Restricción (Cat 26) */}
|
||||||
|
{confirmRestrictedModal && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
position: 'fixed',
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
bottom: 0,
|
||||||
|
backgroundColor: 'rgba(0, 0, 0, 0.7)',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
zIndex: 1000,
|
||||||
|
padding: '1rem',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
backgroundColor: 'var(--bg-card)',
|
||||||
|
borderRadius: '12px',
|
||||||
|
padding: '1.5rem',
|
||||||
|
maxWidth: '480px',
|
||||||
|
width: '100%',
|
||||||
|
boxShadow: '0 10px 25px rgba(0,0,0,0.5)',
|
||||||
|
border: '2px solid #f44336',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', marginBottom: '1rem' }}>
|
||||||
|
<span style={{ fontSize: '2rem' }}>⛔</span>
|
||||||
|
<div>
|
||||||
|
<h3 style={{ margin: 0, fontSize: '1.2rem', color: '#f44336' }}>
|
||||||
|
Lote con Restricción Activa
|
||||||
|
</h3>
|
||||||
|
<span style={{ fontSize: '0.85rem', color: 'var(--text-secondary)' }}>
|
||||||
|
Categoría 26 - {lotPermission?.detalle}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p style={{ fontSize: '0.95rem', color: 'var(--text-primary)', lineHeight: 1.4, margin: '0 0 1.25rem 0' }}>
|
||||||
|
El lote <strong>{form.lote_codigo}</strong> posee una restricción registrada en el consorcio.
|
||||||
|
¿Desea forzar el ingreso bajo responsabilidad del operador de guardia?
|
||||||
|
</p>
|
||||||
|
<div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end' }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-secondary"
|
||||||
|
onClick={() => setConfirmRestrictedModal(false)}
|
||||||
|
style={{ minHeight: '44px', padding: '0 1.25rem', fontWeight: 600 }}
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn"
|
||||||
|
onClick={() => {
|
||||||
|
setConfirmRestrictedModal(false);
|
||||||
|
handleRegisterEntry(undefined, true);
|
||||||
|
}}
|
||||||
|
style={{
|
||||||
|
minHeight: '44px',
|
||||||
|
padding: '0 1.25rem',
|
||||||
|
fontWeight: 700,
|
||||||
|
backgroundColor: '#f44336',
|
||||||
|
color: '#fff',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Forzar Ingreso Autorizado
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user