feat(real-data): carga dinamica de workstations y tickets/movimientos reales desde SQL Server
This commit is contained in:
@@ -2,6 +2,22 @@
|
||||
|
||||
Todas las modificaciones, adiciones y decisiones de arquitectura notables de este proyecto serán documentadas en este archivo.
|
||||
|
||||
## [v0.6.1-beta] - 2026-10-13 (Carga Dinámica de Workstations y Movimientos Reales de SQL Server)
|
||||
|
||||
### Agregado y Corregido
|
||||
- **Carga Dinámica de Estaciones de Trabajo (`wks`):**
|
||||
- Eliminación de todas las opciones mock en `LoginView.tsx`.
|
||||
- Integración del endpoint `/api/v1/control-posts/workstations` para poblar el dropdown de estaciones directamente desde la tabla `wks` de SQL Server (`CFT-DESK`, `REGATAS-R`).
|
||||
- **Configuración de Módulos de Entrada y Salida (`wksmdl` + `mdl`):**
|
||||
- Implementación de `/api/v1/control-posts/{workstation_name}/config` y `/api/v1/control-posts/workstation/{workstation_name}/config`.
|
||||
- Detección precisa de sentido de carril (Entrada vs Salida) con base en nombres y flags en base de datos.
|
||||
- **Pestaña de Historial de Movimientos Reales (`mvthist`):**
|
||||
- Nuevo endpoint `/api/v1/access/movements/recent` para consultar las últimas transacciones registradas en SQL Server.
|
||||
- Implementación en `ControlPostView.tsx` de selector de pestañas entre "🟢 En Predio (Activos)" y "📜 Historial Movimientos BD".
|
||||
- **Visualización sin Mocks de Tickets Activos (`tck`):**
|
||||
- Ajuste en `AccessRepository.listar_tickets_activos` con `LEFT JOIN` a integrantes y desduplicación por `TicketID`.
|
||||
- Botón de refresco manual "🔄 Actualizar" en la barra de control para sincronización inmediata.
|
||||
|
||||
## [v0.6.0-beta] - 2026-10-13 (Fase 6: Despliegue Piloto y Convivencia Híbrida)
|
||||
|
||||
### Agregado
|
||||
|
||||
@@ -22,6 +22,8 @@ Memoria del proyecto entre sesiones. Máximo ~50 líneas: resume o elimina lo qu
|
||||
- **Repositorio Oficial Gitea y Versionado:** `https://gitea.oemspot.com.ar/carlostellocba/OnEverControl`. Obligatorio incrementar versiones en backend/frontend, documentar en `CHANGELOG.md` y pasar pruebas antes de cada push.
|
||||
|
||||
## Aprendizajes y errores a evitar
|
||||
- **Workstations y Módulos Dinámicos:** Las workstations se consultan directamente de la tabla `wks` (`/api/v1/control-posts/workstations`) y sus módulos de `wksmdl` + `mdl`. Cero mocks en login o cockpit.
|
||||
- **Historial vs Activos:** `tck` contiene solo ocupantes activos dentro del predio. Para auditoría y visualización de pasadas se consulta `mvthist` (`/api/v1/access/movements/recent`).
|
||||
- **Tabla `Per` en SQL Server:** Exige columnas obligatorias `CREATEdByID` (2) y `LastUpdateDateByID` (2).
|
||||
- **Tabla `lot`:** El nombre del lote está en la columna `Lote`, no `Nombre`.
|
||||
- **Tabla `PerDocCatVal`:** Requiere `DocumentoID` (100000), `CategoriaID` (11) y `ValorID` (1).
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# ==============================================================================
|
||||
# OnEverControl - Versión del Backend
|
||||
# ==============================================================================
|
||||
__version__ = "0.6.0-beta"
|
||||
__version__ = "0.6.1-beta"
|
||||
__app_name__ = "OnEverControl"
|
||||
__description__ = "Cliente Web Reducido para Puesto de Control en Red Local de OnEverAccess"
|
||||
|
||||
@@ -65,6 +65,15 @@ def listar_tickets_activos(
|
||||
return AccessService.obtener_tickets_activos()
|
||||
|
||||
|
||||
@router.get("/movements/recent", summary="Listar últimos movimientos registrados en SQL Server")
|
||||
def listar_ultimos_movimientos(
|
||||
limit: int = Query(30, ge=1, le=100),
|
||||
current_user: dict = Depends(obtener_usuario_actual),
|
||||
):
|
||||
"""Obtiene los últimos movimientos de ingreso y salida registrados en la tabla mvthist."""
|
||||
return AccessService.obtener_ultimos_movimientos(limite=limit)
|
||||
|
||||
|
||||
@router.get("/people/search", response_model=List[PersonSearchDTO], summary="Búsqueda predictiva de personas")
|
||||
def buscar_personas(
|
||||
q: str = Query(..., min_length=2, description="Texto de búsqueda por apellido o documento"),
|
||||
|
||||
@@ -1,29 +1,48 @@
|
||||
# ==============================================================================
|
||||
# Endpoints de Puestos de Control y Workstations (/api/v1/control-posts)
|
||||
# ==============================================================================
|
||||
from typing import List, Dict, Any
|
||||
from typing import List
|
||||
from fastapi import APIRouter
|
||||
from app.schemas.workstation_schema import WorkstationStatusResponse
|
||||
from app.schemas.workstation_schema import (
|
||||
WorkstationStatusResponse,
|
||||
WorkstationConfigResponse,
|
||||
WorkstationItemDTO,
|
||||
)
|
||||
from app.services.workstation_service import WorkstationService
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get(
|
||||
"/workstations",
|
||||
response_model=List[WorkstationItemDTO],
|
||||
summary="Listar todas las Workstations reales registradas en SQL Server",
|
||||
)
|
||||
async def list_workstations():
|
||||
"""Listado real de estaciones desde la tabla wks para selector de login."""
|
||||
return WorkstationService.listar_estaciones_disponibles()
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{name}/config",
|
||||
response_model=WorkstationConfigResponse,
|
||||
summary="Consultar configuración de módulos de carril asignados a la workstation",
|
||||
)
|
||||
@router.get(
|
||||
"/workstation/{name}/config",
|
||||
response_model=WorkstationConfigResponse,
|
||||
summary="Consultar configuración de módulos de carril asignados a la workstation (alias)",
|
||||
)
|
||||
async def get_workstation_config(name: str):
|
||||
"""Retorna los módulos de entrada y salida asignados a la estación en wksmdl y mdl."""
|
||||
return WorkstationService.obtener_config_workstation(name)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/workstation/{name}/status",
|
||||
response_model=WorkstationStatusResponse,
|
||||
summary="Consultar estado y carriles asignados a una Workstation",
|
||||
summary="Consultar estado y módulos de la Workstation",
|
||||
)
|
||||
async def get_workstation_status(name: str):
|
||||
"""Verifica si la tablet/estación está autorizada como Puesto de Control y retorna sus carriles."""
|
||||
return WorkstationService.obtener_estado_workstation(name)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/workstations",
|
||||
response_model=List[Dict[str, Any]],
|
||||
summary="Listar todas las Workstations registradas",
|
||||
)
|
||||
async def list_workstations():
|
||||
"""Listado de estaciones para selector de tablets o supervisores."""
|
||||
return WorkstationService.listar_estaciones_disponibles()
|
||||
|
||||
+10
-3
@@ -48,9 +48,16 @@ async def health_check():
|
||||
)
|
||||
|
||||
|
||||
@app.get("/", tags=["Información"], summary="Información del servicio")
|
||||
async def root():
|
||||
"""Ruta raíz informativa."""
|
||||
from fastapi import Request
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
@app.get("/", tags=["Información"], summary="Interfaz Web o Información del servicio")
|
||||
async def root(request: Request):
|
||||
"""Sirve la aplicación React SPA si está compilada, o metadata JSON."""
|
||||
accept = request.headers.get("accept", "")
|
||||
frontend_index = Path(__file__).resolve().parent.parent.parent / "frontend" / "dist" / "index.html"
|
||||
if "text/html" in accept and frontend_index.is_file():
|
||||
return FileResponse(frontend_index)
|
||||
return {
|
||||
"app": __app_name__,
|
||||
"version": __version__,
|
||||
|
||||
@@ -235,17 +235,17 @@ class AccessRepository:
|
||||
SELECT
|
||||
t.TicketID,
|
||||
t.FechaHoraIngreso,
|
||||
m.Nombre AS ModuloIngreso,
|
||||
p.PersonaID,
|
||||
p.Apellido,
|
||||
p.Nombre,
|
||||
d.Documento,
|
||||
COALESCE(m.Nombre, 'MODULO_ING') AS ModuloIngreso,
|
||||
COALESCE(p.PersonaID, 0) AS PersonaID,
|
||||
COALESCE(p.Apellido, 'VISITANTE') AS Apellido,
|
||||
COALESCE(p.Nombre, '') AS Nombre,
|
||||
COALESCE(d.Documento, '') AS Documento,
|
||||
pat.Valor AS Patente,
|
||||
lot.Valor AS LoteCodigo
|
||||
FROM tck t
|
||||
LEFT JOIN mdl m ON t.ModuloIngresoID = m.ModuloID
|
||||
INNER JOIN tckper tp ON t.TicketID = tp.TicketID AND tp.RolID = 1
|
||||
INNER JOIN Per p ON tp.PersonaID = p.PersonaID
|
||||
LEFT JOIN tckper tp ON t.TicketID = tp.TicketID
|
||||
LEFT JOIN Per p ON tp.PersonaID = p.PersonaID
|
||||
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
|
||||
@@ -254,6 +254,42 @@ class AccessRepository:
|
||||
with db_session() as conn:
|
||||
cursor = conn.cursor(as_dict=True)
|
||||
cursor.execute(query)
|
||||
# Desduplicar por TicketID si hay múltiples ocupantes en el mismo ticket
|
||||
rows = cursor.fetchall()
|
||||
seen = set()
|
||||
unique_tickets = []
|
||||
for r in rows:
|
||||
tid = r["TicketID"]
|
||||
if tid not in seen:
|
||||
seen.add(tid)
|
||||
unique_tickets.append(r)
|
||||
return unique_tickets
|
||||
|
||||
@staticmethod
|
||||
def listar_ultimos_movimientos(limite: int = 50) -> List[Dict[str, Any]]:
|
||||
"""Retorna los últimos movimientos registrados en mvthist desde SQL Server."""
|
||||
query = """
|
||||
SELECT TOP (%s)
|
||||
m.MvtHistID,
|
||||
m.TicketID,
|
||||
m.PersonaID,
|
||||
p.Apellido,
|
||||
p.Nombre,
|
||||
d.Documento,
|
||||
m.Patente,
|
||||
m.Sentido,
|
||||
m.Entidad,
|
||||
m.FechaHora,
|
||||
md.Nombre AS ModuloNombre
|
||||
FROM mvthist m
|
||||
LEFT JOIN Per p ON m.PersonaID = p.PersonaID
|
||||
LEFT JOIN PerDocCatVal d ON p.PersonaID = d.PersonaID
|
||||
LEFT JOIN mdl md ON m.ModuloID = md.ModuloID
|
||||
ORDER BY m.FechaHora DESC, m.MvtHistID DESC
|
||||
"""
|
||||
with db_session() as conn:
|
||||
cursor = conn.cursor(as_dict=True)
|
||||
cursor.execute(query, (limite,))
|
||||
return cursor.fetchall()
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -79,3 +79,17 @@ class LotSearchDTO(BaseModel):
|
||||
lote_id: int
|
||||
codigo: str
|
||||
propietario: Optional[str] = None
|
||||
|
||||
|
||||
class MovementHistoryDTO(BaseModel):
|
||||
mvt_hist_id: int
|
||||
ticket_id: int
|
||||
sentido: str
|
||||
patente: Optional[str] = None
|
||||
apellido: Optional[str] = None
|
||||
nombre: Optional[str] = None
|
||||
documento: Optional[str] = None
|
||||
lote_codigo: Optional[str] = None
|
||||
modulo_nombre: Optional[str] = None
|
||||
fecha_hora: str
|
||||
entidad: Optional[str] = None
|
||||
|
||||
@@ -1,17 +1,57 @@
|
||||
# ==============================================================================
|
||||
# Esquemas Pydantic v2 para Estaciones de Trabajo y Carriles
|
||||
# ==============================================================================
|
||||
from typing import List, Optional
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import List, Optional, Any
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
|
||||
class LaneModuleDTO(BaseModel):
|
||||
modulo_id: int
|
||||
nombre: str
|
||||
id: int
|
||||
name: str
|
||||
address: int
|
||||
type: str = "ENTRY"
|
||||
grupo_modulos: Optional[int] = None
|
||||
es_entrada: bool = True
|
||||
duracion_pulso: Optional[int] = None
|
||||
modulo_id: Optional[int] = None
|
||||
nombre: Optional[str] = None
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def populate_aliases(cls, data: Any):
|
||||
if isinstance(data, dict):
|
||||
if "modulo_id" in data and "id" not in data:
|
||||
data["id"] = data["modulo_id"]
|
||||
if "id" in data and "modulo_id" not in data:
|
||||
data["modulo_id"] = data["id"]
|
||||
if "nombre" in data and "name" not in data:
|
||||
data["name"] = data["nombre"]
|
||||
if "name" in data and "nombre" not in data:
|
||||
data["nombre"] = data["name"]
|
||||
return data
|
||||
|
||||
|
||||
class WorkstationItemDTO(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
nombre: Optional[str] = None
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def populate_aliases(cls, data: Any):
|
||||
if isinstance(data, dict):
|
||||
if "nombre" in data and "name" not in data:
|
||||
data["name"] = data["nombre"]
|
||||
if "name" in data and "nombre" not in data:
|
||||
data["nombre"] = data["name"]
|
||||
return data
|
||||
|
||||
|
||||
class WorkstationConfigResponse(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
entry_modules: List[LaneModuleDTO] = Field(default_factory=list)
|
||||
exit_modules: List[LaneModuleDTO] = Field(default_factory=list)
|
||||
|
||||
|
||||
class WorkstationStatusResponse(BaseModel):
|
||||
|
||||
@@ -155,3 +155,29 @@ class AccessService:
|
||||
)
|
||||
for f in filas
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def obtener_ultimos_movimientos(limite: int = 50) -> List[dict]:
|
||||
"""Retorna los últimos movimientos reales registrados en SQL Server mvthist."""
|
||||
from app.schemas.access_schema import MovementHistoryDTO
|
||||
filas = AccessRepository.listar_ultimos_movimientos(limite)
|
||||
resultado = []
|
||||
for f in filas:
|
||||
fh = f["FechaHora"]
|
||||
fh_str = fh.strftime("%Y-%m-%d %H:%M:%S") if isinstance(fh, datetime) else str(fh)
|
||||
resultado.append(
|
||||
MovementHistoryDTO(
|
||||
mvt_hist_id=f["MvtHistID"],
|
||||
ticket_id=f["TicketID"] or 0,
|
||||
sentido=str(f["Sentido"] or "Ingreso"),
|
||||
patente=f.get("Patente"),
|
||||
apellido=f.get("Apellido"),
|
||||
nombre=f.get("Nombre"),
|
||||
documento=f.get("Documento"),
|
||||
lote_codigo=None,
|
||||
modulo_nombre=f.get("ModuloNombre"),
|
||||
fecha_hora=fh_str,
|
||||
entidad=f.get("Entidad"),
|
||||
)
|
||||
)
|
||||
return resultado
|
||||
|
||||
@@ -3,50 +3,81 @@
|
||||
# ==============================================================================
|
||||
from typing import List, Dict, Any
|
||||
from app.repositories.workstation_repository import WorkstationRepository
|
||||
from app.schemas.workstation_schema import WorkstationStatusResponse, LaneModuleDTO
|
||||
from app.schemas.workstation_schema import (
|
||||
WorkstationStatusResponse,
|
||||
WorkstationConfigResponse,
|
||||
WorkstationItemDTO,
|
||||
LaneModuleDTO,
|
||||
)
|
||||
|
||||
|
||||
class WorkstationService:
|
||||
@staticmethod
|
||||
def obtener_estado_workstation(name: str) -> WorkstationStatusResponse:
|
||||
"""Determina si la tablet/workstation está registrada y qué carriles tiene asignados."""
|
||||
def obtener_config_workstation(name: str) -> WorkstationConfigResponse:
|
||||
"""Retorna la configuración esperada por el cliente web: id, name, entry_modules, exit_modules."""
|
||||
wks_row = WorkstationRepository.obtener_workstation_por_nombre(name)
|
||||
if not wks_row:
|
||||
return WorkstationStatusResponse(
|
||||
workstation_name=name,
|
||||
is_control_post=False,
|
||||
workstation_id=None,
|
||||
modules=[],
|
||||
return WorkstationConfigResponse(
|
||||
id=0,
|
||||
name=name,
|
||||
entry_modules=[],
|
||||
exit_modules=[],
|
||||
)
|
||||
|
||||
wks_id = wks_row["WorkstationID"]
|
||||
nombre_oficial = wks_row["Nombre"].strip()
|
||||
modulos_rows = WorkstationRepository.listar_modulos_por_workstation(wks_id)
|
||||
|
||||
modules_dto: List[LaneModuleDTO] = []
|
||||
entry_modules: List[LaneModuleDTO] = []
|
||||
exit_modules: List[LaneModuleDTO] = []
|
||||
|
||||
for m in modulos_rows:
|
||||
# Determinamos si es entrada o salida según ModuloEntradaID o nombre
|
||||
es_entrada = bool(m.get("ModuloEntradaID")) or "ENTRADA" in m["Nombre"].upper()
|
||||
modules_dto.append(
|
||||
LaneModuleDTO(
|
||||
modulo_id=m["ModuloID"],
|
||||
nombre=m["Nombre"].strip(),
|
||||
nom = m["Nombre"].strip()
|
||||
nom_upper = nom.upper()
|
||||
if "SALIDA" in nom_upper or "EGRESO" in nom_upper:
|
||||
es_entrada = False
|
||||
elif "ENTRADA" in nom_upper or "INGRESO" in nom_upper:
|
||||
es_entrada = True
|
||||
else:
|
||||
es_entrada = not bool(m.get("ModuloEntradaID"))
|
||||
dto = LaneModuleDTO(
|
||||
id=m["ModuloID"],
|
||||
name=nom,
|
||||
address=m["Address"],
|
||||
type="ENTRY" if es_entrada else "EXIT",
|
||||
grupo_modulos=m.get("GrupoModulos"),
|
||||
es_entrada=es_entrada,
|
||||
duracion_pulso=m.get("duracion_pulso"),
|
||||
)
|
||||
)
|
||||
if es_entrada:
|
||||
entry_modules.append(dto)
|
||||
else:
|
||||
exit_modules.append(dto)
|
||||
|
||||
return WorkstationStatusResponse(
|
||||
workstation_name=nombre_oficial,
|
||||
is_control_post=len(modules_dto) > 0,
|
||||
workstation_id=wks_id,
|
||||
modules=modules_dto,
|
||||
return WorkstationConfigResponse(
|
||||
id=wks_id,
|
||||
name=nombre_oficial,
|
||||
entry_modules=entry_modules,
|
||||
exit_modules=exit_modules,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def listar_estaciones_disponibles() -> List[Dict[str, Any]]:
|
||||
"""Retorna el listado de todas las workstations disponibles para selección de supervisor."""
|
||||
def obtener_estado_workstation(name: str) -> WorkstationStatusResponse:
|
||||
"""Determina si la tablet/workstation está registrada y qué carriles tiene asignados."""
|
||||
cfg = WorkstationService.obtener_config_workstation(name)
|
||||
all_modules = cfg.entry_modules + cfg.exit_modules
|
||||
return WorkstationStatusResponse(
|
||||
workstation_name=cfg.name,
|
||||
is_control_post=len(all_modules) > 0,
|
||||
workstation_id=cfg.id,
|
||||
modules=all_modules,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def listar_estaciones_disponibles() -> List[WorkstationItemDTO]:
|
||||
"""Retorna el listado de todas las workstations reales desde la tabla wks de SQL Server."""
|
||||
rows = WorkstationRepository.listar_todas()
|
||||
return [{"workstation_id": r["WorkstationID"], "nombre": r["Nombre"].strip()} for r in rows]
|
||||
return [
|
||||
WorkstationItemDTO(id=r["WorkstationID"], name=r["Nombre"].strip())
|
||||
for r in rows
|
||||
]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "onevercontrol-frontend",
|
||||
"private": true,
|
||||
"version": "0.6.0-beta",
|
||||
"version": "0.6.1-beta",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -51,4 +51,10 @@ export const accessApi = {
|
||||
body: JSON.stringify({ raw_data: rawData }),
|
||||
});
|
||||
},
|
||||
|
||||
getRecentMovements: (limit: number = 30) => {
|
||||
return request<any[]>(`/access/movements/recent?limit=${limit}`, {
|
||||
method: 'GET',
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
@@ -4,10 +4,21 @@
|
||||
import { request } from './client';
|
||||
import { WorkstationConfig } from '../types';
|
||||
|
||||
export interface WorkstationListItem {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export const workstationApi = {
|
||||
getConfig: (workstationName: string) => {
|
||||
return request<WorkstationConfig>(`/control-posts/${encodeURIComponent(workstationName)}/config`, {
|
||||
method: 'GET',
|
||||
});
|
||||
},
|
||||
|
||||
getAvailableWorkstations: () => {
|
||||
return request<WorkstationListItem[]>('/control-posts/workstations', {
|
||||
method: 'GET',
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
@@ -99,3 +99,16 @@ export interface TicketResponse {
|
||||
barrier_opened: boolean;
|
||||
fecha_hora: string;
|
||||
}
|
||||
|
||||
export interface RecentMovement {
|
||||
mvt_hist_id: number;
|
||||
ticket_id: number;
|
||||
sentido: string;
|
||||
patente?: string | null;
|
||||
apellido?: string | null;
|
||||
nombre?: string | null;
|
||||
documento?: string | null;
|
||||
modulo_nombre?: string | null;
|
||||
fecha_hora: string;
|
||||
entidad?: string | null;
|
||||
}
|
||||
|
||||
@@ -25,8 +25,10 @@ export const ControlPostView: React.FC = () => {
|
||||
const [selectedEntryModuleId, setSelectedEntryModuleId] = useState<number>(0);
|
||||
const [selectedExitModuleId, setSelectedExitModuleId] = useState<number>(0);
|
||||
|
||||
// Tickets activos en el predio
|
||||
// Tickets activos y movimientos registrados en BD
|
||||
const [activeTickets, setActiveTickets] = useState<ActiveTicket[]>([]);
|
||||
const [recentMovements, setRecentMovements] = useState<any[]>([]);
|
||||
const [viewTab, setViewTab] = useState<'active' | 'movements'>('active');
|
||||
const [filterQuery, setFilterQuery] = useState<string>('');
|
||||
const [isLoadingTickets, setIsLoadingTickets] = useState<boolean>(false);
|
||||
|
||||
@@ -73,24 +75,28 @@ export const ControlPostView: React.FC = () => {
|
||||
try {
|
||||
const wksConfig = await workstationApi.getConfig(workstation);
|
||||
setConfig(wksConfig);
|
||||
if (wksConfig.entry_modules.length > 0) {
|
||||
if (wksConfig.entry_modules && wksConfig.entry_modules.length > 0) {
|
||||
setSelectedEntryModuleId(wksConfig.entry_modules[0].id);
|
||||
setForm((prev) => ({ ...prev, modulo_ingreso_id: wksConfig.entry_modules[0].id }));
|
||||
}
|
||||
if (wksConfig.exit_modules.length > 0) {
|
||||
if (wksConfig.exit_modules && wksConfig.exit_modules.length > 0) {
|
||||
setSelectedExitModuleId(wksConfig.exit_modules[0].id);
|
||||
}
|
||||
} catch (err: any) {
|
||||
setActionError(`Error al cargar configuración de ${workstation}: ${err.message}`);
|
||||
console.warn(`Configuración de ${workstation}:`, err);
|
||||
}
|
||||
}, [workstation]);
|
||||
|
||||
// Carga de tickets activos
|
||||
// Carga de tickets activos y movimientos reales
|
||||
const loadActiveTickets = useCallback(async () => {
|
||||
setIsLoadingTickets(true);
|
||||
try {
|
||||
const tickets = await accessApi.getActiveTickets();
|
||||
const [tickets, movements] = await Promise.all([
|
||||
accessApi.getActiveTickets(),
|
||||
accessApi.getRecentMovements(30).catch(() => []),
|
||||
]);
|
||||
setActiveTickets(tickets);
|
||||
setRecentMovements(movements);
|
||||
} catch (err: any) {
|
||||
console.error('Error al listar tickets:', err);
|
||||
} finally {
|
||||
@@ -266,6 +272,20 @@ export const ControlPostView: React.FC = () => {
|
||||
);
|
||||
}, [activeTickets, filterQuery]);
|
||||
|
||||
// Filtro de movimientos historicos de la BD
|
||||
const filteredMovements = useMemo(() => {
|
||||
if (!filterQuery.trim()) return recentMovements;
|
||||
const q = filterQuery.toLowerCase().trim();
|
||||
return recentMovements.filter(
|
||||
(m: any) =>
|
||||
(m.documento && m.documento.toLowerCase().includes(q)) ||
|
||||
(m.apellido && m.apellido.toLowerCase().includes(q)) ||
|
||||
(m.nombre && m.nombre.toLowerCase().includes(q)) ||
|
||||
(m.patente && m.patente.toLowerCase().includes(q)) ||
|
||||
(m.modulo_nombre && m.modulo_nombre.toLowerCase().includes(q))
|
||||
);
|
||||
}, [recentMovements, filterQuery]);
|
||||
|
||||
const toggleFullscreen = () => {
|
||||
if (!document.fullscreenElement) {
|
||||
document.documentElement.requestFullscreen().catch(() => {});
|
||||
@@ -723,10 +743,66 @@ export const ControlPostView: React.FC = () => {
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
{/* Pestañas de Selección: Activos vs Historial BD */}
|
||||
<div
|
||||
style={{
|
||||
padding: '0.5rem 1.25rem 0',
|
||||
backgroundColor: 'var(--bg-surface)',
|
||||
borderBottom: '1px solid var(--border-subtle)',
|
||||
display: 'flex',
|
||||
gap: '0.75rem',
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setViewTab('active')}
|
||||
style={{
|
||||
padding: '0.65rem 1.25rem',
|
||||
border: 'none',
|
||||
borderBottom: viewTab === 'active' ? '3px solid var(--brand-primary)' : '3px solid transparent',
|
||||
backgroundColor: 'transparent',
|
||||
fontWeight: viewTab === 'active' ? 700 : 500,
|
||||
color: viewTab === 'active' ? 'var(--brand-primary)' : 'var(--text-secondary)',
|
||||
cursor: 'pointer',
|
||||
fontSize: '0.95rem',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '0.5rem',
|
||||
}}
|
||||
>
|
||||
<span>🟢 En Predio (Activos)</span>
|
||||
<span className="badge badge-info" style={{ fontSize: '0.8rem' }}>
|
||||
{activeTickets.length}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setViewTab('movements')}
|
||||
style={{
|
||||
padding: '0.65rem 1.25rem',
|
||||
border: 'none',
|
||||
borderBottom: viewTab === 'movements' ? '3px solid var(--brand-primary)' : '3px solid transparent',
|
||||
backgroundColor: 'transparent',
|
||||
fontWeight: viewTab === 'movements' ? 700 : 500,
|
||||
color: viewTab === 'movements' ? 'var(--brand-primary)' : 'var(--text-secondary)',
|
||||
cursor: 'pointer',
|
||||
fontSize: '0.95rem',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '0.5rem',
|
||||
}}
|
||||
>
|
||||
<span>📜 Historial Movimientos BD</span>
|
||||
<span className="badge badge-neutral" style={{ fontSize: '0.8rem' }}>
|
||||
{recentMovements.length}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Barra de Filtros y Módulo de Salida */}
|
||||
<div
|
||||
style={{
|
||||
padding: '1rem 1.25rem',
|
||||
padding: '0.75rem 1.25rem',
|
||||
backgroundColor: 'var(--bg-surface)',
|
||||
borderBottom: '1px solid var(--border-subtle)',
|
||||
display: 'flex',
|
||||
@@ -739,18 +815,27 @@ export const ControlPostView: React.FC = () => {
|
||||
<input
|
||||
type="text"
|
||||
className="input-touch"
|
||||
placeholder="🔍 Filtrar por patente, DNI o apellido..."
|
||||
placeholder={viewTab === 'active' ? "🔍 Filtrar por patente, DNI o apellido..." : "🔍 Filtrar historial..."}
|
||||
value={filterQuery}
|
||||
onChange={(e) => setFilterQuery(e.target.value)}
|
||||
style={{ maxWidth: '380px' }}
|
||||
/>
|
||||
<span className="badge badge-info" style={{ fontSize: '0.9rem', padding: '0.4rem 0.8rem' }}>
|
||||
{filteredTickets.length} dentro del predio
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() => loadActiveTickets()}
|
||||
title="Refrescar datos de la Base de Datos"
|
||||
style={{ minHeight: '40px', padding: '0 0.8rem', fontSize: '0.85rem' }}
|
||||
>
|
||||
🔄 Actualizar
|
||||
</button>
|
||||
<span className="badge badge-info" style={{ fontSize: '0.85rem', padding: '0.35rem 0.7rem' }}>
|
||||
{viewTab === 'active' ? `${filteredTickets.length} ocupantes` : `${filteredMovements.length} registros`}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Módulo de Salida para Egresos */}
|
||||
{config && config.exit_modules.length > 0 && (
|
||||
{/* Módulo de Salida para Egresos (solo visible en pestaña Activos) */}
|
||||
{viewTab === 'active' && config && config.exit_modules.length > 0 && (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
|
||||
<span style={{ fontSize: '0.75rem', fontWeight: 600, color: 'var(--text-secondary)' }}>
|
||||
BARRERA SALIDA:
|
||||
@@ -771,13 +856,15 @@ export const ControlPostView: React.FC = () => {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Grilla / Lista de Tickets Activos */}
|
||||
{/* Grilla / Lista de Contenido Según Pestaña */}
|
||||
<div style={{ flex: 1, overflowY: 'auto', padding: '1.25rem' }}>
|
||||
{isLoadingTickets && activeTickets.length === 0 ? (
|
||||
{isLoadingTickets && activeTickets.length === 0 && recentMovements.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', padding: '2rem', color: 'var(--text-muted)' }}>
|
||||
Cargando ocupantes del predio...
|
||||
Cargando datos desde la base de datos...
|
||||
</div>
|
||||
) : filteredTickets.length === 0 ? (
|
||||
) : viewTab === 'active' ? (
|
||||
/* TAB 1: TICKETS ACTIVOS EN PREDIO */
|
||||
filteredTickets.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', padding: '3rem', color: 'var(--text-muted)' }}>
|
||||
{filterQuery ? 'No se encontraron coincidencias para la búsqueda.' : 'No hay visitas ni vehículos activos en el predio actualmente.'}
|
||||
</div>
|
||||
@@ -846,6 +933,80 @@ export const ControlPostView: React.FC = () => {
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
/* TAB 2: HISTORIAL DE MOVIMIENTOS REALES EN BASE DE DATOS */
|
||||
filteredMovements.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', padding: '3rem', color: 'var(--text-muted)' }}>
|
||||
{filterQuery ? 'No se encontraron movimientos que coincidan.' : 'No hay movimientos registrados en la base de datos.'}
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
|
||||
{filteredMovements.map((m: any, idx: number) => {
|
||||
const isIngreso = (m.sentido || '').toUpperCase() === 'INGRESO' || (m.sentido || '').toUpperCase() === 'ENTRADA';
|
||||
return (
|
||||
<div
|
||||
key={`${m.hist_id || idx}-${m.fecha_hora}`}
|
||||
className="card"
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
padding: '0.85rem 1.25rem',
|
||||
backgroundColor: 'var(--bg-surface)',
|
||||
borderRadius: 'var(--radius-md)',
|
||||
boxShadow: 'var(--shadow-sm)',
|
||||
border: '1px solid var(--border-subtle)',
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '1.25rem' }}>
|
||||
<span
|
||||
className={isIngreso ? 'badge badge-success' : 'badge badge-warning'}
|
||||
style={{ fontSize: '0.85rem', fontWeight: 700, minWidth: '85px', textAlign: 'center' }}
|
||||
>
|
||||
{m.sentido || 'MOVIMIENTO'}
|
||||
</span>
|
||||
|
||||
<div
|
||||
style={{
|
||||
backgroundColor: m.patente ? 'var(--status-info-bg)' : 'var(--border-subtle)',
|
||||
color: m.patente ? 'var(--status-info)' : 'var(--text-secondary)',
|
||||
padding: '0.4rem 0.65rem',
|
||||
borderRadius: '6px',
|
||||
fontWeight: 700,
|
||||
fontSize: '0.95rem',
|
||||
minWidth: '85px',
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
{m.patente || 'PEATÓN'}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div style={{ fontSize: '0.95rem', fontWeight: 600 }}>
|
||||
{m.apellido || m.nombre ? `${m.apellido || ''}, ${m.nombre || ''}` : 'S/D'}{' '}
|
||||
{m.documento && (
|
||||
<span style={{ fontSize: '0.8rem', fontWeight: 400, color: 'var(--text-muted)' }}>
|
||||
(DNI: {m.documento})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ fontSize: '0.8rem', color: 'var(--text-secondary)', marginTop: '0.15rem' }}>
|
||||
Módulo: <strong>{m.modulo_nombre || `ID ${m.modulo_id}`}</strong> • Motivo: {m.motivo || 'N/A'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ textAlign: 'right' }}>
|
||||
<span style={{ fontSize: '0.85rem', fontWeight: 600, color: 'var(--text-primary)' }}>
|
||||
{m.fecha_hora ? new Date(m.fecha_hora).toLocaleString('es-AR') : 'S/F'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -2,17 +2,38 @@
|
||||
// Vista de Inicio de Sesión de Operador / Guardia
|
||||
// Optimizado para uso táctil en tablets Samsung Galaxy Tab (Touch-First)
|
||||
// ==============================================================================
|
||||
import React, { useState } from 'react';
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { workstationApi, WorkstationListItem } from '../api/workstationApi';
|
||||
|
||||
export const LoginView: React.FC = () => {
|
||||
const { login, workstation, setWorkstation } = useAuth();
|
||||
const [username, setUsername] = useState<string>('guardia');
|
||||
const [password, setPassword] = useState<string>('');
|
||||
const [selectedWks, setSelectedWks] = useState<string>(workstation || 'CFT-DESK');
|
||||
const [availableWorkstations, setAvailableWorkstations] = useState<WorkstationListItem[]>([]);
|
||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
// Carga de Workstations reales desde SQL Server
|
||||
workstationApi.getAvailableWorkstations()
|
||||
.then((list) => {
|
||||
if (list && list.length > 0) {
|
||||
setAvailableWorkstations(list);
|
||||
const currentMatch = list.find((w) => w.name.toUpperCase() === (workstation || 'CFT-DESK').toUpperCase());
|
||||
if (currentMatch) {
|
||||
setSelectedWks(currentMatch.name);
|
||||
} else {
|
||||
setSelectedWks(list[0].name);
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
console.warn('No se pudieron listar estaciones desde DB:', err);
|
||||
});
|
||||
}, [workstation]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!username.trim() || !password) {
|
||||
@@ -98,7 +119,7 @@ export const LoginView: React.FC = () => {
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
|
||||
{/* Selector de Workstation / Garita */}
|
||||
{/* Selector de Workstation Real desde SQL Server */}
|
||||
<div>
|
||||
<label
|
||||
style={{
|
||||
@@ -117,10 +138,15 @@ export const LoginView: React.FC = () => {
|
||||
onChange={(e) => setSelectedWks(e.target.value)}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
<option value="CFT-DESK">CFT-DESK (Garita Principal)</option>
|
||||
<option value="GARITA_SUR">GARITA_SUR</option>
|
||||
<option value="GARITA_NORTE">GARITA_NORTE</option>
|
||||
<option value="ACCESO_PROVEEDORES">ACCESO_PROVEEDORES</option>
|
||||
{availableWorkstations.length > 0 ? (
|
||||
availableWorkstations.map((w) => (
|
||||
<option key={w.id} value={w.name}>
|
||||
{w.name} (ID {w.id})
|
||||
</option>
|
||||
))
|
||||
) : (
|
||||
<option value="CFT-DESK">CFT-DESK (ID 100001)</option>
|
||||
)}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -192,7 +218,7 @@ export const LoginView: React.FC = () => {
|
||||
</form>
|
||||
|
||||
<div style={{ marginTop: '2rem', textAlign: 'center', fontSize: '0.75rem', color: 'var(--text-muted)' }}>
|
||||
OnEverControl Web v0.5.0-beta • Samsung Galaxy Tab Ready
|
||||
OnEverControl Web v0.6.0-beta • Conectado a Microsoft SQL Server videoman
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user