CertiMine: aplicación PHP, API DC3 Peñasquito y documentación

- Portal bilingüe (Bootstrap), biblioteca FRM, consulta y perfiles con QR.
- Integración REST penasquito.wotbi.com (Token, búsqueda por passport y polling).
- Webhook de sincronización, esquema MariaDB y semillas FRM/NOM.
- Documentación en docs/ y extracto DatosPdf.txt; ejemplo de config sin secretos locales.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
remaster 2026-05-13 17:56:36 -06:00
commit a72656f9d4
35 changed files with 2778 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
config/config.php
.DS_Store

BIN
DC31.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

BIN
DC32.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

378
DatosPdf.txt Normal file
View file

@ -0,0 +1,378 @@
Scraping Mobilise-Me — Crónica del proceso
Proceso de Scraping
Portal Mobilise-Me — Consulta de Competencias DC3
Crónica del flujo de scraping descubierto
Cliente: Newmont Peñasquito
Página 1 de 11
Scraping Mobilise-Me — Crónica del proceso
1. APIs expuestas
Para que el bot de WhatsApp (o cualquier otro consumidor) pueda obtener las competencias
DC3 sin tener que conocer el detalle del scraping, se exponen tres endpoints REST. El
scraping ocurre del lado del servidor de manera asíncrona; el cliente solo interactúa con estas
APIs.
1.1 Autenticación
Todas las peticiones requieren un header de autorización con un token estático que se entrega
aparte por canal privado:
TOKEN 43eff45fff1422d21d371e3d72d76ae56f435a2c
Authorization: Token <token>
Las peticiones sin este header o con un token inválido son rechazadas con HTTP 401.
1.2 Endpoint 1 — Crear solicitud de búsqueda
POST https://penasquito.wotbi.com/api/v1/dc3/competencies/passports/search/
Content-Type: application/json
Authorization: Token <token>
Body:
{
"passport": "E000055821"
}
Comportamiento. La API valida el passport, encola la tarea de scraping y devuelve
inmediatamente un identificador de ticket. El proceso de scraping corre en segundo plano y no
bloquea la respuesta.
Respuesta cuando la tarea queda encolada (comportamiento estándar):
{
"status": "pending",
"ticket_id": "2cf364bebf16",
"posicion": 1
}
El cliente debe guardar el ticket_id y consultarlo en el endpoint de resultado (1.3) hasta que el
scraping termine.
Respuesta cuando ya hay datos en caché. Si en la última hora ya se consultó ese mismo
passport, la API devuelve directamente el resultado sin volver a encolar nada. Esto evita re-
scrapear información que no cambia con frecuencia y libera carga del portal externo:
{
"status": "completed",
"result": {
"passport": "E000055821",
"name": "ITZEL CARDENAS REYES",
"company": "INGENIERIA NET COM SOCIEDAD ANONIMA",
"competencies": [
{
"activity": "FRM - CONFINED SPACES",
"request_date": "30/07/2025",
Página 2 de 11
Scraping Mobilise-Me — Crónica del proceso
Página 3 de 11
"expiration_date": null,
"status": "Received"
}
],
"error": null
}
}
Recomendación de uso: el cliente siempre llama primero a este endpoint. Si recibe status:
completed usa el resultado al instante; si recibe status: pending pasa a hacer polling con el
ticket_id.
1.3 Endpoint 2 — Consultar estado / resultado del ticket
GET
https://penasquito.wotbi.com/api/v1/dc3/competencies/passports/result/<ticket_id>/
Authorization: Token <token>
Comportamiento. Devuelve el estado actual del ticket. Mientras el worker no haya terminado,
el campo status puede ser pending o processing. Cuando el scraping termina, status pasa a
completed y se incluye el campo result con todos los datos.
Respuesta de un ticket completado:
{
"status": "completed",
"result": {
"passport": "E000055821",
"name": "ITZEL CARDENAS REYES",
"company": "INGENIERIA NET COM SOCIEDAD ANONIMA",
"competencies": [
{
"activity": "FRM - CONFINED SPACES",
"request_date": "30/07/2025",
"expiration_date": null,
"status": "Received"
}
],
"error": null
}
}
Estructura del campo result:
Campo Descripción
passport Passport consultado.
name Nombre del empleado, extraído del HTML del portal.
company Empresa a la que pertenece el empleado.
competencies Lista de competencias DC3. Cada elemento incluye activity,
request_date, expiration_date (puede ser null si no expira) y
status.
Scraping Mobilise-Me — Crónica del proceso
Campo Descripción
error null en caso exitoso. Si hubo un fallo (sesión expirada, passport
no encontrado, etc.) trae el mensaje descriptivo y competencies
viene vacío.
1.4 Endpoint 3 — Estado de la cola
GET https://penasquito.wotbi.com/api/v1/dc3/competencies/passports/status/
Authorization: Token <token>
Endpoint de monitoreo. Devuelve el estado actual de la cola en Redis y si el worker está
procesando algo en este momento. Útil para health checks y para detectar acumulación de
trabajos pendientes.
{
"queue_length": 0,
"processing": false
}
Campo Significado
queue_length Cantidad de tickets esperando ser procesados por el worker.
processing true si el worker está ejecutando un scraping en este momento,
false si está libre.
1.5 Caché de resultados
Cada resultado exitoso se almacena en caché (Redis) durante 1 hora indexado por número de
passport. Durante esa ventana, cualquier nueva solicitud para el mismo passport responde
inmediatamente con el dato cacheado y no encola ningún trabajo.
La razón: las competencias DC3 no cambian con frecuencia, y evitar consultas redundantes al
portal externo reduce carga sobre Mobilise-Me y mejora los tiempos de respuesta para el
usuario.
1.6 Flujo recomendado del cliente
El consumidor de la API (en este caso el bot de WhatsApp) sigue este patrón:
• Llamar al endpoint 1 (POST /search/) con el passport.
• Si la respuesta trae status=completed, usar el resultado.
• Si trae status=pending, guardar el ticket_id y hacer polling al endpoint 2 (GET
/result/<ticket_id>/) cada cierto intervalo (ej: cada 2 segundos) hasta recibir
status=completed.
• Mostrar al usuario el contenido de result.competencies.
El tiempo total típico de respuesta cuando no hay caché es de entre 5 y 15 segundos,
dependiendo de la carga del portal externo.
Página 4 de 11
Scraping Mobilise-Me — Crónica del proceso
2. Punto de partida
El portal de Mobilise-Me utilizado por Newmont Peñasquito está disponible en:
https://testing.newmontpenasquito.mobilise-me.com
La meta es: dado un Passport (ID de empleado, por ejemplo E000055821), obtener el listado
de sus competencias DC3 directamente desde el portal, navegando como si fuéramos un
administrador.
Para descubrir el flujo se navegó manualmente con un navegador, observando con DevTools
(pestaña Network) qué peticiones se hacen, qué cookies se generan, qué formularios se envían
y a qué URL se redirige cada paso. El proceso se replicó con peticiones HTTP secuenciales,
manteniendo una única sesión (cookies vivas) durante toda la operación.
Lo que sigue es la crónica de cómo se hace el scraping, de inicio a fin, con los nombres reales
de campos, URLs, valores y códigos de respuesta observados.
3. Paso 1 — Abrir la página de Login
Lo primero es entrar a /Login con un GET. El servidor responde con HTTP 200 y entrega el
HTML del formulario, y de paso establece las cookies iniciales de sesión.
GET https://testing.newmontpenasquito.mobilise-me.com/Login
De esta primera respuesta nos importan dos cosas:
• Las cookies que el servidor establece. Aparecen en los headers Set-Cookie e
incluyen al menos: ci_session (sesión del backend), csrf_cookie_name (token CSRF) y
lang (idioma de la sesión). Estas cookies hay que conservarlas y enviarlas en todas las
peticiones siguientes.
• El token CSRF dentro del HTML del formulario. Inspeccionando el formulario de login
encontramos un input oculto:
<input type="hidden" name="csrf_test_name" value="..."/>
Ese valor (el value del input csrf_test_name) debe leerse del HTML y reenviarse junto al
usuario y la contraseña en el siguiente POST. Si no, el servidor rechaza la autenticación.
Detalle: hay dos cosas relacionadas con CSRF que es fácil confundir. Una es la cookie
llamada csrf_cookie_name (la maneja el cliente HTTP automáticamente al guardar las cookies).
Otra es el input hidden del formulario llamado csrf_test_name, cuyo valor se envía en el body.
Ambos deben coincidir, y el servidor compara uno contra el otro.
4. Paso 2 — Enviar el formulario de Login
Con las cookies obtenidas y el CSRF leído del HTML, simulamos el envío del formulario
haciendo un POST a la misma URL /Login. El body se envía como application/x-www-form-
urlencoded con los siguientes campos:
Campo (name) Valor
csrf_test_name Token CSRF leído del HTML del paso 1.
Página 5 de 11
Scraping Mobilise-Me — Crónica del proceso
Campo (name) Valor
USERNAME Usuario administrador (variable de entorno
NEWMONT_DC3_USERNAME). En desarrollo se utilizó
E000055821.
PWD Contraseña del usuario (variable de entorno
NEWMONT_DC3_PASSWORD).
action Login (este valor corresponde al name/value del botón de envío
del formulario).
Headers importantes en este POST:
• Content-Type: application/x-www-form-urlencoded
• Referer: https://testing.newmontpenasquito.mobilise-me.com/Login
• User-Agent estándar de navegador, y todas las cookies del paso 1.
Qué responde el servidor
Lo que se observó en el log del cliente HTTP fue:
POST /Login HTTP/1.1" 303 0
GET /Selection HTTP/1.1" 200 1957
El servidor responde 303 See Other y un header Location que apunta a /Selection. Como el
cliente HTTP sigue redirecciones automáticamente, termina haciendo un GET a /Selection y
obtiene HTTP 200 con el HTML de esa página.
Punto clave: aquí descubrimos que el portal NO te lleva directamente al panel de
administración después del login. Te deja en una pantalla intermedia llamada /Selection
donde tienes que elegir con qué "perfil" o "contexto" vas a operar. Sin pasar por esa pantalla
cualquier intento posterior de entrar al área administrativa termina rechazado.
5. Paso 3 — La pantalla de Selección (el paso clave)
Inspeccionando el HTML de /Selection se encontraron dos botones, cada uno dentro de su
propio contenedor. El que nos interesa es el de la base de datos administrativa:
<button type="submit" class="btn selection-btn"
name="action"
value="Administration Database">
<span class="selection-text">Base de datos administrativa</span>
</button>
Y el otro:
<button type="submit" class="btn selection-btn"
name="action"
value="Induction portal">
<span class="selection-text">Continua a la Inducción</span>
</button>
Diferencia importante: la opción Induction portal devuelve únicamente las competencias del
usuario logueado. La opción Administration Database abre el panel de administración donde
se pueden consultar los DC3 de cualquier empleado, que es justamente lo que necesitamos.
Página 6 de 11
Scraping Mobilise-Me — Crónica del proceso
Por qué este paso fue el principal dolor de cabeza
La primera versión del scraper saltaba directo del POST de login al panel /Admin/.... El
servidor respondía con HTTP 307 redirigiendo de regreso a /Selection, o entregaba HTML de
la propia pantalla de selección. Tardamos en darnos cuenta de que el portal exige declarar
explícitamente el contexto antes de acceder al área de administración. Una vez identificado,
agregar esta petición destrabó todo el flujo.
La petición
Hacemos un POST a /Selection simulando el click del botón "Administration Database". El
body se envía como application/x-www-form-urlencoded con:
Campo (name) Valor
csrf_test_name Token CSRF leído de la cookie csrf_cookie_name (que es el
valor vigente en este punto del flujo).
action Administration Database (idéntico al value del button, sensible a
mayúsculas y al espacio).
Headers importantes:
• Referer: https://testing.newmontpenasquito.mobilise-me.com/Selection
• Content-Type: application/x-www-form-urlencoded
Qué responde el servidor
POST /Selection HTTP/1.1" 303 0
GET /Admin/index/Users HTTP/1.1" 200 28500
Otra vez 303, y otra vez seguimos la redirección. El servidor nos lleva a /Admin/index/Users (la
página de inicio del panel administrativo). Ya estamos dentro: la sesión queda "contextualizada"
como administrador y a partir de aquí podemos navegar a cualquier subsección del módulo
Admin.
6. Paso 4 — Localizar el módulo DC3
Dentro del HTML de /Admin/index/Users hay un menú lateral con todas las secciones. La que
nos interesa aparece como un enlace:
<li><a href="https://.../Admin/index/Dc3 Formats Records">Registros Formatos
Dc3</a></li>
La URL del módulo (con el espacio codificado como %20) es:
https://testing.newmontpenasquito.mobilise-me.com/Admin/index/Dc3%20Formats%20Records
Hacemos un GET a esa URL y obtenemos HTTP 200 con la página completa del módulo: una
tabla vacía (porque aún no hemos buscado nada) y, sobre ella, un formulario de búsqueda con
varios filtros.
Importante: hay que volver a leer el CSRF de este HTML, porque el portal lo refresca al cargar
la página. El siguiente POST de búsqueda usará este token nuevo.
Página 7 de 11
Scraping Mobilise-Me — Crónica del proceso
7. Paso 5 — Buscar las competencias por Passport
Ahora simulamos el envío del formulario de búsqueda. El detalle particular de este formulario
es que se envía como multipart/form-data (no como urlencoded), que es lo que hace el portal
por defecto cuando se envía desde el navegador. Replicamos ese mismo encoding.
Petición
POST /Admin/index/Dc3%20Formats%20Records
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDC3
Campos del body:
Campo (name) Valor
csrf_test_name Token CSRF leído del HTML de la página DC3 que se
cargó en el paso 4.
search[data][FOLIO_NUMBER] Número de Passport del empleado a consultar (ej:
E000055821). Este es el filtro principal.
search[data][COMPANY] --Show All-- (literal, así viene por defecto en el form).
search[data][STATUS] action[search] (vacío) — corresponde al botón "Search" del formulario.
--Show All-- (literal).
Nota sobre el name de los inputs: los campos vienen con notación tipo array
PHP/CodeIgniter: search[data][FOLIO_NUMBER], search[data][COMPANY], etc. Hay que
respetarlos exactamente; si se envía solo FOLIO_NUMBER el backend no lo reconoce.
Detección de sesión perdida
Antes de parsear, verificamos que la respuesta no nos haya tirado al login. Si la URL final de la
respuesta contiene /Login, la sesión expiró: hay que repetir todo el flujo desde el paso 1. El
error.
scraper marca al usuario como no autenticado y reintenta el login una vez antes de devolver
8. Paso 6 — Parsear la tabla de resultados
La respuesta del POST de búsqueda trae un HTML que contiene la tabla con los registros DC3
del empleado. La identificamos por su clase:
<table class="admin-table"> ... </table>
Iteramos por las filas del <tbody> y, de cada fila, extraemos las celdas <td> por su posición. La
estructura es la siguiente:
Índice de
Contenido Uso en la API
td
0 Botón de acción Contiene un <button data-fun="verify" data-
id="..."> del que extraemos el record_id
(data-id) que servirá para pedir el documento
PDF.
Página 8 de 11
Scraping Mobilise-Me — Crónica del proceso
Índice de
Contenido Uso en la API
td
6 Nombre de la
actividad/competencia
Campo actividad (ej: "Newmont Peñasquito
Visitor Induction I1").
7 Fecha de solicitud Campo fecha_solicitud.
8 Fecha de expiración 10 Estado Campo fecha_expiracion. Si la celda contiene
"
---" se interpreta como sin expiración (null).
Campo status (ej: vigente, vencida).
Filtro defensivo: se ignoran las filas que tienen menos de 11 celdas. Eso protege contra filas
de cabecera, separadores o filas vacías cuando el portal no encuentra registros.
Si después de iterar la lista de competencias está vacía, devolvemos un resultado con error
"Sin competencias". Esto puede significar que el Passport no existe, o que ese empleado no
tiene DC3 registrados.
9. Paso 7 — Obtener la URL del documento PDF (opcional)
Cada fila de la tabla tiene asociado un PDF (la constancia DC3 firmada). En el portal, al hacer
click en el botón verify de la columna 0, el frontend hace una petición AJAX a otro endpoint y
abre el documento en un modal. Replicamos esa misma petición.
Petición
POST /DC3/index
Content-Type: application/x-www-form-urlencoded
X-Requested-With: XMLHttpRequest
Referer: .../Admin/index/Dc3%20Formats%20Records
Campo Valor
id record_id extraído del data-id del botón verify de la fila.
table DC3_FORMATS_RECORDS
function verify
induction false
csrf_test_name Token CSRF vigente.
Respuesta
Esta petición devuelve JSON (no HTML). Dentro del JSON, en la ruta data.FILE, está el
nombre del archivo PDF. La URL final del documento se construye así:
{BASE_URL}/DC3/showDoc/DC3_FORMATS_RECORDS/dc3/{nombre_archivo}
Esa URL puede compartirse con el empleado para que descargue su constancia.
10. Resumen del flujo completo
Página 9 de 11
Scraping Mobilise-Me — Crónica del proceso
Visto en orden, el flujo es:
# Método URL Qué hace
1 GET /Login Inicializa cookies y obtiene CSRF del
form.
2 POST /Login Envía USERNAME, PWD, action=Login.
Responde 303 → redirige a /Selection.
3 POST /Selection Envía action=Administration Database.
Responde 303 → redirige a
/Admin/index/Users.
4 GET /Admin/index/Dc3%20Formats%20Records Carga la página del módulo y refresca el
CSRF.
5 POST /Admin/index/Dc3%20Formats%20Records Envía búsqueda con
search[data][FOLIO_NUMBER]=passport.
Devuelve HTML con la tabla.
6 (parseo) table.admin-table Extrae actividad, fechas, status y
record_id de cada fila.
7 POST /DC3/index (opcional) por cada record_id, obtiene el
JSON con el nombre del archivo PDF.
11. Puntos críticos
Estos son los detalles que es fácil pasar por alto y que rompen el scraping si se omiten:
• Mantener una única sesión HTTP. Las cookies (especialmente ci_session y
csrf_cookie_name) deben persistir durante todo el flujo. Si el cliente las descarta entre
peticiones, todo falla.
• El paso /Selection no se puede saltar. Sin él, cualquier acceso a /Admin/... termina
redirigido (HTTP 307) o devuelto al login.
• El valor exacto "Administration Database". Es sensible al espacio y a las
mayúsculas. Coincide con el atributo value del botón en el HTML de /Selection.
• El CSRF se refresca por página. Hay que leer el csrf_test_name del HTML de la
página actual antes de cada POST, no reutilizar el del paso anterior. La cookie
csrf_cookie_name también se actualiza.
• El header Referer es obligatorio en los POST. Cada POST debe declarar como
Referer la URL desde la que viene el formulario. Sin él, el portal puede rechazar la
petición.
• La búsqueda DC3 va como multipart, no urlencoded. Es el detalle más fácil de
equivocar. Hay que usar multipart/form-data con boundary. En urlencoded el portal no
procesa los filtros.
• Los nombres de campo del filtro tienen notación de array. Son
search[data][FOLIO_NUMBER], search[data][COMPANY], search[data][STATUS]. Y los
valores de COMPANY y STATUS, cuando no se filtran, van con el literal --Show All--
.
Página 10 de 11
Scraping Mobilise-Me — Crónica del proceso
• Detectar sesión perdida. Si después de un GET o un POST la URL final contiene
/Login, la sesión expiró y hay que volver a empezar desde el paso 1.
• Idioma fijo. Forzar la cookie lang mantiene los textos del HTML predecibles para el
parseo.
Página 11 de 11

Binary file not shown.

10
bin/recompute_green.php Normal file
View file

@ -0,0 +1,10 @@
#!/usr/bin/env php
<?php
declare(strict_types=1);
$base = dirname(__DIR__);
require $base . '/src/bootstrap.php';
\CertiMine\SyncService::recomputeGreenLicenses();
echo "Green licenses recomputed.\n";

69
config/config.example.php Normal file
View file

@ -0,0 +1,69 @@
<?php
/**
* Copiar a config.php y ajustar. config.php está en .gitignore.
*
* Token DC3: preferir variable de entorno CERTIMINE_DC3_TOKEN (no commitear el valor real).
*/
return [
'app' => [
'name' => 'CertiMine',
'base_path' => dirname(__DIR__),
'public_url' => 'http://127.0.0.1:8080',
'timezone' => 'America/Mexico_City',
'qr_secret' => 'change-me-qr-hmac',
'qr_enforce' => false,
],
'db' => [
'host' => '127.0.0.1',
'port' => 3306,
'name' => 'certimine',
'user' => 'root',
'pass' => 'R3m4st3r',
'charset' => 'utf8mb4',
],
'session' => [
'name' => 'CERTIMINESESSID',
'cookie_lifetime' => 0,
'cookie_secure' => false,
'cookie_httponly' => true,
'cookie_samesite' => 'Lax',
],
/**
* API REST expuesto por el backend Peñasquito (Wotbi): competencias DC3 por passport.
* Origen: DatosPdf.txt / documentación de scraping Mobilise-Me.
*/
'penasquito_dc3' => [
'base_url' => 'https://penasquito.wotbi.com',
'static_token' => '',
'search_path' => '/api/v1/dc3/competencies/passports/search/',
'result_path_template' => '/api/v1/dc3/competencies/passports/result/{ticket_id}/',
'status_path' => '/api/v1/dc3/competencies/passports/status/',
'authorization_header' => 'Authorization',
'authorization_scheme' => 'Token ',
'poll_interval_seconds' => 2,
'poll_max_attempts' => 20,
'timeout_seconds' => 45,
],
/**
* Modo legacy (JSON login + JWT) si NO usas penasquito_dc3.static_token / CERTIMINE_DC3_TOKEN.
*/
'mobiliseme' => [
'base_url' => 'https://api.mobiliseme.example',
'timeout_seconds' => 20,
'mock' => true,
'login_path' => '/auth/login',
'login_username_field' => 'username',
'login_password_field' => 'password',
'token_json_path' => 'access_token',
'authorization_header' => 'Authorization',
'authorization_scheme' => 'Bearer ',
'profile_path' => '/me',
'profile_external_id_path' => 'id',
'profile_name_path' => 'full_name',
'profile_type_path' => 'type',
'profile_employee_number_path' => 'employee_number',
'person_certificates_path' => '/persons/{id}/certificates',
'certificate_list_path' => 'items',
'webhook_secret' => '',
],
];

65
docs/mobiliseme-api.md Normal file
View file

@ -0,0 +1,65 @@
# API DC3 Peñasquito (Wotbi) — CertiMine
Fuente detallada del flujo de scraping en Mobilise-Me: ver [DatosPdf.txt](../DatosPdf.txt) en el repositorio (texto extraído manualmente del PDF).
## Autenticación
Todas las peticiones al API REST llevan un **token estático** entregado por canal privado:
```http
Authorization: Token <token>
```
Sin cabecera válida → **HTTP 401**.
En CertiMine configure `CERTIMINE_DC3_TOKEN` (recomendado) o `penasquito_dc3.static_token` en `config/config.php`. **No subir el token real al control de versiones.**
## Base URL
`https://penasquito.wotbi.com` (según DatosPdf.txt).
## Endpoint 1 — Crear solicitud de búsqueda
`POST /api/v1/dc3/competencies/passports/search/`
- `Content-Type: application/json`
- Body: `{ "passport": "E000055821" }`
- Respuesta si hay caché (~1 h): `status: "completed"` + `result` (name, company, competencies[]).
- Respuesta si encola: `status: "pending"` + `ticket_id` (+ opcional `posicion`).
## Endpoint 2 — Resultado del ticket (polling)
`GET /api/v1/dc3/competencies/passports/result/<ticket_id>/`
- Mientras trabaja el worker: `status` puede ser `pending` o `processing`.
- Al terminar: `status: "completed"` + `result`.
Flujo recomendado: llamar endpoint 1; si `pending`, consultar endpoint 2 cada pocos segundos hasta `completed` (implementado en `PenasquitoDc3Api::fetchResultForPassport`).
## Endpoint 3 — Estado de cola
`GET /api/v1/dc3/competencies/passports/status/`
- `queue_length`, `processing` — monitoreo / health.
## Estructura de `result`
| Campo | Uso |
|--------|-----|
| `passport` | ID consultado (coincide con búsqueda). |
| `name` | Nombre. |
| `company` | Empresa; CertiMine infiere contratista vs empleado con reglas heurísticas. |
| `competencies[]` | `activity`, `request_date`, `expiration_date` (null si no aplica), `status`. |
| `error` | Si no es null, mensaje de fallo. |
## Portal Mobilise-Me (scraping interno)
El documento describe además el login web (`testing.newmontpenasquito.mobilise-me.com`), cookies, CSRF, pas **`/Selection`** con `action=Administration Database`, etc. Eso lo ejecuta el **servidor** que alimenta el API anterior, no el navegador del usuario de CertiMine.
## Webhook CertiMine
CertiMine sigue aceptando `POST public/api/webhook.php` para sincronizar certificados desde otros sistemas (ver implementación). Es independiente del API Wotbi anterior.
## Configuración PHP
Rutas y tiempos de polling: `config/config.example.php` → sección `penasquito_dc3`.

56
lang/en.php Normal file
View file

@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
return [
'nav_home' => 'Home',
'nav_frm' => 'FRM library',
'nav_lookup' => 'Certificate lookup',
'nav_login' => 'Sign in',
'nav_logout' => 'Sign out',
'nav_dashboard' => 'My dashboard',
'lang_en' => 'English',
'lang_es' => 'Spanish',
'app_tagline' => 'Certification management — Penasquito',
'frm_title' => 'Public FRM standards library',
'frm_intro' => 'Read-only references, verifications, and permissions. Links to corporate documentation where applicable.',
'frm_nom_related' => 'Related NOM competencies',
'lookup_title' => 'Employee or contractor lookup',
'lookup_intro' => 'Scan the QR code or enter the employee number or contractor ID.',
'lookup_type' => 'Person type',
'lookup_employee' => 'Employee',
'lookup_contractor' => 'Contractor',
'lookup_code' => 'Number / ID',
'lookup_submit' => 'Search',
'lookup_qr_hint' => 'QR URL: paste the signed link if your deployment enables HMAC.',
'profile_green' => 'Green license',
'profile_green_yes' => 'Critical authorizations valid',
'profile_green_no' => 'Requirements pending',
'profile_certs' => 'Certifications / DC3',
'profile_auths' => 'FRM authorizations',
'status_valid' => 'Valid',
'status_expiring' => 'Expiring soon',
'status_expired' => 'Expired',
'status_pending' => 'Pending',
'login_title' => 'CertiMine sign-in',
'login_user' => 'Username',
'login_pass' => 'Password',
'login_submit' => 'Sign in',
'login_error' => 'Sign-in failed. Check credentials or enable API mock for demo.',
'dashboard_welcome' => 'Welcome, :name',
'dashboard_courses' => 'Suggested courses from your competencies',
'dashboard_profile' => 'My profile and certifications',
'no_results' => 'No results',
'api_unreachable' => 'Mobiliseme service unavailable. Try again later.',
'csrf_invalid' => 'Session expired. Resubmit the form.',
'footer_docs' => 'API documentation',
'contractor_profile' => 'Contractor profile',
'employee_profile' => 'Employee profile',
'expires' => 'Expires',
'issued' => 'Issued',
'sync_title' => 'Synchronization',
'webhook_ok' => 'Event received',
'dc3_lookup_error' => 'Could not load DC3 competencies. Check passport or API token.',
'login_passport_hint' => 'With DC3 API (CERTIMINE_DC3_TOKEN), use your passport (e.g. E000055821). Password is unused. Without token: demo user with «contract» or employee.',
'login_demo_hint' => 'Without DC3 API: username containing «contract» simulates contractor; otherwise demo employee.',
];

56
lang/es.php Normal file
View file

@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
return [
'nav_home' => 'Inicio',
'nav_frm' => 'Biblioteca FRM',
'nav_lookup' => 'Consulta certificación',
'nav_login' => 'Iniciar sesión',
'nav_logout' => 'Salir',
'nav_dashboard' => 'Mi panel',
'lang_en' => 'English',
'lang_es' => 'Español',
'app_tagline' => 'Gestión de certificaciones — Penasquito',
'frm_title' => 'Biblioteca pública de estándares FRM',
'frm_intro' => 'Consulta de referencias, verificaciones y permisos en modo lectura. Enlaces a documentación corporativa cuando aplique.',
'frm_nom_related' => 'Competencias NOM relacionadas',
'lookup_title' => 'Consulta por empleado o contratista',
'lookup_intro' => 'Escanee el código QR o ingrese el número de empleado o identificador de contratista.',
'lookup_type' => 'Tipo de persona',
'lookup_employee' => 'Empleado',
'lookup_contractor' => 'Contratista',
'lookup_code' => 'Número / ID',
'lookup_submit' => 'Buscar',
'lookup_qr_hint' => 'URL del QR (misma búsqueda): pegue el enlace o use la firma si está habilitada.',
'profile_green' => 'Licencia verde',
'profile_green_yes' => 'Autorizaciones críticas vigentes',
'profile_green_no' => 'Pendiente de requisitos',
'profile_certs' => 'Certificaciones / DC3',
'profile_auths' => 'Autorizaciones FRM',
'status_valid' => 'Vigente',
'status_expiring' => 'Por vencer',
'status_expired' => 'Vencido',
'status_pending' => 'Pendiente',
'login_title' => 'Acceso CertiMine',
'login_user' => 'Usuario',
'login_pass' => 'Contraseña',
'login_submit' => 'Entrar',
'login_error' => 'No fue posible iniciar sesión. Verifique credenciales o intente con modo demo (API mock).',
'dashboard_welcome' => 'Bienvenido, :name',
'dashboard_courses' => 'Cursos sugeridos según sus competencias',
'dashboard_profile' => 'Mi perfil y certificaciones',
'no_results' => 'Sin resultados',
'api_unreachable' => 'El servicio Mobiliseme no está disponible. Intente más tarde.',
'csrf_invalid' => 'Sesión expirada. Vuelva a enviar el formulario.',
'footer_docs' => 'Documentación API',
'contractor_profile' => 'Perfil de contratista',
'employee_profile' => 'Perfil de empleado',
'expires' => 'Vence',
'issued' => 'Emitido',
'sync_title' => 'Sincronización',
'webhook_ok' => 'Evento recibido',
'dc3_lookup_error' => 'No se pudieron obtener competencias del servicio DC3. Verifique el passport o el token del API.',
'login_passport_hint' => 'Con API DC3 configurado (CERTIMINE_DC3_TOKEN), use su passport (ej. E000055821). La contraseña no se usa. Sin token: modo demo con usuario «contract» o empleado.',
'login_demo_hint' => 'Sin API DC3: si el usuario contiene «contract», se simula contratista; si no, empleado demo.',
];

4
public/.htaccess Normal file
View file

@ -0,0 +1,4 @@
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

14
public/api/webhook.php Normal file
View file

@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
use CertiMine\SyncService;
require dirname(__DIR__, 2) . '/src/bootstrap_api.php';
header('Content-Type: application/json; charset=utf-8');
$raw = file_get_contents('php://input') ?: '';
$sig = $_SERVER['HTTP_X_CERTIMINE_SIGNATURE'] ?? null;
$code = SyncService::handleWebhook($raw, is_string($sig) ? $sig : null);
http_response_code($code);
echo json_encode(['ok' => $code < 400, 'status' => $code], JSON_UNESCAPED_UNICODE);

188
public/index.php Normal file
View file

@ -0,0 +1,188 @@
<?php
declare(strict_types=1);
use CertiMine\Auth;
use CertiMine\Config;
use CertiMine\I18n;
use CertiMine\MobilisemeClient;
use CertiMine\PersonRepository;
use CertiMine\Security;
use CertiMine\Util;
require dirname(__DIR__) . '/src/bootstrap.php';
$route = isset($_GET['r']) ? (string) $_GET['r'] : 'home';
/** @var callable $e */
$e = static function (string $msg): void {
http_response_code(404);
echo '<!DOCTYPE html><html><body><p>Not found</p></body></html>';
exit;
};
try {
switch ($route) {
case 'home':
$titleKey = 'nav_home';
require dirname(__DIR__) . '/views/home.php';
break;
case 'frm-library':
$frms = PersonRepository::frmWithNoms();
$docs = PersonRepository::publicDocuments();
$titleKey = 'frm_title';
require dirname(__DIR__) . '/views/frm_library.php';
break;
case 'lookup':
$error = null;
$result = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!Security::verifyCsrf($_POST['_csrf'] ?? null)) {
$error = I18n::t('csrf_invalid');
} else {
$type = (string) ($_POST['person_type'] ?? 'employee');
$code = trim((string) ($_POST['code'] ?? ''));
if (!in_array($type, ['employee', 'contractor'], true)) {
$type = 'employee';
}
if ($code === '') {
$error = I18n::t('no_results');
} else {
$result = PersonRepository::findByEmployeeNumberAndType($code, $type);
if ($result === null) {
$result = PersonRepository::findByEmployeeNumber($code);
}
if ($result !== null) {
PersonRepository::logAudit('lookup', (string) $result['person_type'], $code);
$ptype = (string) $result['person_type'];
$ecode = (string) ($result['employee_number'] ?? $result['mobiliseme_id']);
$sig = Security::qrSignature($ptype, $ecode);
header(
'Location: ' . Util::url('profile', [
'id' => $result['mobiliseme_id'],
'sig' => $sig,
])
);
exit;
}
if (\CertiMine\PenasquitoDc3Api::isConfigured()) {
try {
$apiRes = \CertiMine\PenasquitoDc3Api::fetchResultForPassport($code);
$isContractor = \CertiMine\PenasquitoDc3Api::guessContractorFromCompanyPublic(
(string) ($apiRes['company'] ?? '')
);
$ptype = $type === 'contractor' || $isContractor ? 'contractor' : 'employee';
$pid = (string) ($apiRes['passport'] ?? $code);
\CertiMine\PenasquitoDc3Api::persistResult($pid, $apiRes, $ptype);
PersonRepository::logAudit('lookup_dc3_api', $ptype, $code);
$ecode = (string) ($apiRes['passport'] ?? $code);
$sig = Security::qrSignature($ptype, $ecode);
header(
'Location: ' . Util::url('profile', [
'id' => $pid,
'sig' => $sig,
])
);
exit;
} catch (Throwable $ex) {
$error = I18n::t('dc3_lookup_error');
if (getenv('CERTIMINE_DEBUG') === '1') {
$error .= ' ' . $ex->getMessage();
}
}
} else {
$error = I18n::t('no_results');
}
}
}
}
$titleKey = 'lookup_title';
require dirname(__DIR__) . '/views/lookup.php';
break;
case 'profile':
$id = (string) ($_GET['id'] ?? '');
$sig = isset($_GET['sig']) ? (string) $_GET['sig'] : null;
if ($id === '') {
$e('missing id');
}
$row = PersonRepository::findByMobilisemeId($id);
if ($row === null) {
$e('unknown');
}
$code = (string) ($row['employee_number'] ?? $row['mobiliseme_id']);
$ptype = (string) $row['person_type'];
if (!Security::verifyQrSignature($ptype, $code, $sig)) {
http_response_code(403);
echo '<!DOCTYPE html><html><body><p>Invalid signature</p></body></html>';
exit;
}
$certs = PersonRepository::certificates($id);
$auths = $ptype === 'contractor' ? PersonRepository::authorizations($id) : [];
$green = (int) ($row['green_license_flag'] ?? 0) === 1;
$qrUrl = Util::url('profile', ['id' => $id, 'sig' => Security::qrSignature($ptype, $code)]);
$titleKey = $ptype === 'contractor' ? 'contractor_profile' : 'employee_profile';
require dirname(__DIR__) . '/views/profile_public.php';
break;
case 'login':
$err = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!Security::verifyCsrf($_POST['_csrf'] ?? null)) {
$err = I18n::t('csrf_invalid');
} else {
$u = (string) ($_POST['username'] ?? '');
$p = (string) ($_POST['password'] ?? '');
try {
$login = MobilisemeClient::login($u, $p);
/** @var array<string,mixed>|null $dr */
$dr = isset($login['dc3_result']) && is_array($login['dc3_result']) ? $login['dc3_result'] : null;
Auth::login($login['profile'], $login['token'], $dr);
header('Location: ' . Util::url('dashboard'));
exit;
} catch (Throwable) {
$err = I18n::t('login_error');
}
}
}
$titleKey = 'login_title';
require dirname(__DIR__) . '/views/login.php';
break;
case 'logout':
Auth::logout();
header('Location: ' . Util::url('home'));
exit;
case 'dashboard':
$user = Auth::requireUser();
$mid = (string) $user['mobiliseme_id'];
$certs = PersonRepository::certificates($mid);
$nomIds = PersonRepository::validNomIdsForPerson($mid);
$courses = PersonRepository::coursesForNoms($nomIds);
$titleKey = 'nav_dashboard';
require dirname(__DIR__) . '/views/dashboard.php';
break;
case 'api-docs':
header('Content-Type: text/plain; charset=utf-8');
$doc = dirname(__DIR__) . '/docs/mobiliseme-api.md';
if (is_readable($doc)) {
readfile($doc);
} else {
echo "Documentation not found.\n";
}
exit;
default:
$e('route');
}
} catch (Throwable $ex) {
http_response_code(500);
echo '<!DOCTYPE html><html><body><p>Server error</p></body></html>';
if (getenv('CERTIMINE_DEBUG') === '1') {
echo '<pre>' . Util::h($ex->getMessage()) . '</pre>';
}
}

129
sql/schema.sql Normal file
View file

@ -0,0 +1,129 @@
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
CREATE DATABASE IF NOT EXISTS certimine CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE certimine;
DROP TABLE IF EXISTS audit_log;
DROP TABLE IF EXISTS sync_event;
DROP TABLE IF EXISTS course_requirement;
DROP TABLE IF EXISTS courses;
DROP TABLE IF EXISTS certificates;
DROP TABLE IF EXISTS contractor_authorizations;
DROP TABLE IF EXISTS frm_nom_map;
DROP TABLE IF EXISTS public_documents;
DROP TABLE IF EXISTS users_cache;
DROP TABLE IF EXISTS nom_competency;
DROP TABLE IF EXISTS frm_standard;
CREATE TABLE frm_standard (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
code VARCHAR(64) NOT NULL UNIQUE,
name_en VARCHAR(255) NOT NULL,
name_es VARCHAR(255) NOT NULL,
sort_order INT NOT NULL DEFAULT 0,
doc_url VARCHAR(512) NULL,
description_en TEXT NULL,
description_es TEXT NULL
) ENGINE=InnoDB;
CREATE TABLE nom_competency (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
code VARCHAR(32) NOT NULL UNIQUE,
name_en VARCHAR(255) NOT NULL,
name_es VARCHAR(255) NOT NULL,
sort_order INT NOT NULL DEFAULT 0
) ENGINE=InnoDB;
CREATE TABLE frm_nom_map (
frm_id INT UNSIGNED NOT NULL,
nom_id INT UNSIGNED NOT NULL,
PRIMARY KEY (frm_id, nom_id),
CONSTRAINT fk_frm_nom_frm FOREIGN KEY (frm_id) REFERENCES frm_standard(id) ON DELETE CASCADE,
CONSTRAINT fk_frm_nom_nom FOREIGN KEY (nom_id) REFERENCES nom_competency(id) ON DELETE CASCADE
) ENGINE=InnoDB;
CREATE TABLE public_documents (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title_en VARCHAR(255) NOT NULL,
title_es VARCHAR(255) NOT NULL,
url VARCHAR(512) NOT NULL,
frm_id INT UNSIGNED NULL,
sort_order INT NOT NULL DEFAULT 0,
CONSTRAINT fk_pubdoc_frm FOREIGN KEY (frm_id) REFERENCES frm_standard(id) ON DELETE SET NULL
) ENGINE=InnoDB;
CREATE TABLE users_cache (
mobiliseme_id VARCHAR(64) NOT NULL PRIMARY KEY,
employee_number VARCHAR(64) NULL,
display_name VARCHAR(255) NOT NULL,
person_type ENUM('employee','contractor') NOT NULL DEFAULT 'employee',
green_license_flag TINYINT(1) NOT NULL DEFAULT 0,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY idx_employee_number (employee_number)
) ENGINE=InnoDB;
CREATE TABLE certificates (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
mobiliseme_id VARCHAR(64) NOT NULL,
nom_id INT UNSIGNED NULL,
frm_id INT UNSIGNED NULL,
title VARCHAR(255) NOT NULL,
issued_at DATE NULL,
expires_at DATE NULL,
status ENUM('valid','expiring','expired','pending') NOT NULL DEFAULT 'pending',
external_ref VARCHAR(128) NULL,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY idx_person (mobiliseme_id),
UNIQUE KEY uq_cert_ext (mobiliseme_id, external_ref),
CONSTRAINT fk_cert_nom FOREIGN KEY (nom_id) REFERENCES nom_competency(id) ON DELETE SET NULL,
CONSTRAINT fk_cert_frm FOREIGN KEY (frm_id) REFERENCES frm_standard(id) ON DELETE SET NULL
) ENGINE=InnoDB;
CREATE TABLE contractor_authorizations (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
mobiliseme_id VARCHAR(64) NOT NULL,
frm_id INT UNSIGNED NOT NULL,
valid_until DATE NULL,
source VARCHAR(32) NOT NULL DEFAULT 'sync',
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uq_contractor_frm (mobiliseme_id, frm_id),
CONSTRAINT fk_auth_frm FOREIGN KEY (frm_id) REFERENCES frm_standard(id) ON DELETE CASCADE
) ENGINE=InnoDB;
CREATE TABLE courses (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title_en VARCHAR(255) NOT NULL,
title_es VARCHAR(255) NOT NULL,
url VARCHAR(512) NOT NULL,
sort_order INT NOT NULL DEFAULT 0
) ENGINE=InnoDB;
CREATE TABLE course_requirement (
course_id INT UNSIGNED NOT NULL,
nom_id INT UNSIGNED NOT NULL,
PRIMARY KEY (course_id, nom_id),
CONSTRAINT fk_cr_course FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE,
CONSTRAINT fk_cr_nom FOREIGN KEY (nom_id) REFERENCES nom_competency(id) ON DELETE CASCADE
) ENGINE=InnoDB;
CREATE TABLE sync_event (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
external_id VARCHAR(128) NOT NULL,
event_type VARCHAR(64) NOT NULL,
payload_hash CHAR(64) NOT NULL,
received_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
processed_at DATETIME NULL,
UNIQUE KEY uq_ext (external_id, event_type)
) ENGINE=InnoDB;
CREATE TABLE audit_log (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
action VARCHAR(64) NOT NULL,
subject_type VARCHAR(32) NOT NULL,
subject_id VARCHAR(128) NOT NULL,
ip VARCHAR(45) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;
SET FOREIGN_KEY_CHECKS = 1;

84
sql/seed.sql Normal file
View file

@ -0,0 +1,84 @@
USE certimine;
INSERT IGNORE INTO frm_standard (code, name_en, name_es, sort_order, doc_url, description_en, description_es) VALUES
('FRM_CONFINED', 'FRM - Confined Spaces', 'FRM - Espacios confinados', 10, NULL, 'Consultation standard — link to corporate library.', 'Estándar de consulta — enlace a biblioteca corporativa.'),
('FRM_BARRICADAS', 'FRM - Barricades and Exclusion Zones', 'FRM - Barricadas y Zonas de Exclusión', 20, NULL, NULL, NULL),
('FRM_TERRENO', 'FRM - Surface Ground Control', 'FRM - Control de Terreno Superficial', 30, NULL, NULL, NULL),
('FRM_ENERGIA', 'FRM - Stored Energy Management', 'FRM - Gestión de Energía Almacenada', 40, NULL, NULL, NULL),
('FRM_GRUAS', 'FRM - Cranes and Lifting', 'FRM - Grúas y Levantamiento', 50, NULL, NULL, NULL),
('FRM_SALUD', 'FRM - Health and Hygiene (site exposures)', 'FRM - Salud e Higiene por exposiciones en sitio', 60, NULL, NULL, NULL),
('FRM_MATPEL', 'FRM - Hazardous Materials', 'FRM - Materiales Peligrosos', 70, NULL, NULL, NULL),
('FRM_ELEC', 'FRM - Electrical Safety', 'FRM - Seguridad Eléctrica', 80, NULL, NULL, NULL),
('FRM_ALTURAS', 'FRM - Work at Heights', 'FRM - Trabajo en Alturas', 90, NULL, NULL, NULL),
('FRM_VEHICULOS', 'FRM - Vehicles and Driving', 'FRM - Vehículos y Manejo', 100, NULL, NULL, NULL),
('FRM_AVIACION', 'FRM - Loss of Aviation Control', 'FRM - Perdida de Control de Aviación', 110, NULL, NULL, NULL);
INSERT IGNORE INTO nom_competency (code, name_en, name_es, sort_order) VALUES
('NOM-001', 'Buildings, premises and facilities', 'Edificios, locales e instalaciones', 1),
('NOM-002', 'Fire prevention and protection', 'Prevención y protección contra incendios', 2),
('NOM-004', 'Safety systems and devices in machinery', 'Sistemas y dispositivos de seguridad en maquinaria', 4),
('NOM-005', 'Handling, transport and storage of hazardous substances', 'Manejo, transporte y almacenamiento de sustancias peligrosas', 5),
('NOM-006', 'Handling and storage of materials', 'Manejo y almacenamiento de materiales', 6),
('NOM-009', 'Working at heights', 'Trabajos en altura', 9),
('NOM-010', 'Chemical pollutants', 'Contaminantes por sustancias químicas', 10),
('NOM-011', 'Noise', 'Ruido', 11),
('NOM-012', 'Conditions and risks from ionizing radiation', 'Condiciones y Riesgos por Exposición a Fuentes de Radiación Ionizante', 12),
('NOM-013', 'Non-ionizing radiation', 'Radiaciones no ionizantes', 13),
('NOM-015', 'High or low temperature conditions', 'Condiciones térmicas elevadas o abatidas', 15),
('NOM-017', 'Personal protective equipment', 'Equipo de protección personal', 17),
('NOM-018', 'Hazard and risk identification (chemical)', 'Identificación de peligros y riesgos por sustancias químicas', 18),
('NOM-019', 'Safety and hygiene committees', 'Comisiones de seguridad e higiene', 19),
('NOM-020', 'Pressure vessels and boilers', 'Recipientes sujetos a presión y calderas', 20),
('NOM-022', 'Static electricity', 'Electricidad estática', 22),
('NOM-023', 'Work in underground and open-pit mines', 'Trabajos en minas subterráneas y a cielo abierto', 23),
('NOM-024', 'Vibrations', 'Vibraciones', 24),
('NOM-025', 'Lighting', 'Iluminación', 25),
('NOM-026', 'Colors and safety signs', 'Colores y señales de seguridad', 26),
('NOM-027', 'Welding and cutting', 'Soldadura y corte', 27),
('NOM-029', 'Maintenance of electrical installations', 'Mantenimiento de instalaciones eléctricas', 29),
('NOM-030', 'Preventive safety and health services', 'Servicios preventivos de seguridad y salud', 30);
INSERT IGNORE INTO frm_nom_map (frm_id, nom_id)
SELECT f.id, n.id FROM frm_standard f
JOIN nom_competency n ON (
(f.code = 'FRM_ALTURAS' AND n.code = 'NOM-009')
OR (f.code = 'FRM_CONFINED' AND n.code = 'NOM-001')
OR (f.code = 'FRM_MATPEL' AND n.code = 'NOM-005')
OR (f.code = 'FRM_ELEC' AND n.code = 'NOM-029')
);
INSERT IGNORE INTO public_documents (title_en, title_es, url, frm_id, sort_order)
SELECT 'FRM overview — Penasquito library', 'Resumen FRM — biblioteca Penasquito', 'https://www.gob.mx/stps', id, sort_order
FROM frm_standard WHERE code = 'FRM_ALTURAS' LIMIT 1;
INSERT IGNORE INTO courses (title_en, title_es, url, sort_order) VALUES
('Height work orientation', 'Inducción trabajos en altura', 'https://example.org/course/alturas', 1),
('Confined space entry', 'Acceso a espacios confinados', 'https://example.org/course/confinados', 2),
('Electrical safety basics', 'Bases de seguridad eléctrica', 'https://example.org/course/electrico', 3);
INSERT IGNORE INTO course_requirement (course_id, nom_id)
SELECT c.id, n.id FROM courses c
JOIN nom_competency n ON (
(c.title_en = 'Height work orientation' AND n.code = 'NOM-009')
OR (c.title_en = 'Confined space entry' AND n.code = 'NOM-001')
OR (c.title_en = 'Electrical safety basics' AND n.code = 'NOM-029')
);
INSERT INTO users_cache (mobiliseme_id, employee_number, display_name, person_type, green_license_flag) VALUES
('demo-employee-1', '10001', 'Demo Employee', 'employee', 1),
('demo-contractor-1', 'C-5001', 'Demo Contractor SA', 'contractor', 0)
ON DUPLICATE KEY UPDATE display_name=VALUES(display_name), employee_number=VALUES(employee_number), person_type=VALUES(person_type), green_license_flag=VALUES(green_license_flag);
INSERT IGNORE INTO certificates (mobiliseme_id, nom_id, frm_id, title, issued_at, expires_at, status, external_ref)
SELECT 'demo-employee-1', n.id, f.id, CONCAT('DC3 ', n.code), DATE_SUB(CURDATE(), INTERVAL 30 DAY), DATE_ADD(CURDATE(), INTERVAL 335 DAY), 'valid', CONCAT('EXT-', n.code)
FROM nom_competency n
LEFT JOIN frm_standard f ON f.code = 'FRM_ALTURAS'
WHERE n.code IN ('NOM-009','NOM-017');
INSERT IGNORE INTO contractor_authorizations (mobiliseme_id, frm_id, valid_until, source)
SELECT 'demo-contractor-1', id, DATE_ADD(CURDATE(), INTERVAL 180 DAY), 'seed'
FROM frm_standard WHERE code IN ('FRM_ALTURAS','FRM_CONFINED');
INSERT IGNORE INTO certificates (mobiliseme_id, nom_id, frm_id, title, issued_at, expires_at, status, external_ref)
SELECT 'demo-contractor-1', n.id, NULL, CONCAT('DC3 ', n.code), CURDATE(), DATE_ADD(CURDATE(), INTERVAL 300 DAY), 'valid', CONCAT('DC3-C-', n.code)
FROM nom_competency n WHERE n.code IN ('NOM-009','NOM-001');

109
src/Auth.php Normal file
View file

@ -0,0 +1,109 @@
<?php
declare(strict_types=1);
namespace CertiMine;
final class Auth
{
public static function startSession(): void
{
$s = Config::get('session');
if (!is_array($s)) {
session_start();
return;
}
session_name((string) ($s['name'] ?? 'CERTIMINESESSID'));
session_set_cookie_params([
'lifetime' => (int) ($s['cookie_lifetime'] ?? 0),
'path' => '/',
'secure' => (bool) ($s['cookie_secure'] ?? false),
'httponly' => (bool) ($s['cookie_httponly'] ?? true),
'samesite' => (string) ($s['cookie_samesite'] ?? 'Lax'),
]);
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
}
/**
* @param array<string,mixed> $profile
* @param array<string,mixed>|null $dc3Result resultado completo del API DC3 (evita segunda llamada)
*/
public static function login(array $profile, string $token, ?array $dc3Result = null): void
{
$cfg = Config::get('mobiliseme');
if (!is_array($cfg)) {
throw new \RuntimeException('Config');
}
$idPath = (string) $cfg['profile_external_id_path'];
$namePath = (string) $cfg['profile_name_path'];
$typePath = (string) $cfg['profile_type_path'];
$empPath = (string) $cfg['profile_employee_number_path'];
$id = (string) (Util::arrayPath($profile, $idPath) ?? '');
$name = (string) (Util::arrayPath($profile, $namePath) ?? '');
$type = (string) (Util::arrayPath($profile, $typePath) ?? 'employee');
$emp = Util::arrayPath($profile, $empPath);
$empStr = $emp !== null ? (string) $emp : null;
if ($id === '') {
throw new \RuntimeException('Profile id missing');
}
if (!in_array($type, ['employee', 'contractor'], true)) {
$type = 'employee';
}
$_SESSION['user'] = [
'mobiliseme_id' => $id,
'name' => $name,
'type' => $type,
'employee_number' => $empStr,
'token' => $token,
];
session_regenerate_id(true);
if ($dc3Result !== null && PenasquitoDc3Api::isConfigured()) {
try {
PenasquitoDc3Api::persistResult($id, $dc3Result, $type);
} catch (\Throwable) {
// continúa con sincronización por fetch
}
}
$green = false;
PersonRepository::upsertCache($id, $empStr, $name, $type, $green);
try {
if ($dc3Result === null || !PenasquitoDc3Api::isConfigured()) {
$certs = MobilisemeClient::fetchCertificates($id, $token);
PersonRepository::syncCertificatesFromApi($id, $certs);
}
} catch (\Throwable) {
// offline sync optional
}
$frms = PersonRepository::authorizations($id);
$green = PersonRepository::recomputeGreenLicense($id, $type, $frms);
PersonRepository::upsertCache($id, $empStr, $name, $type, $green);
}
public static function logout(): void
{
$_SESSION = [];
if (ini_get('session.use_cookies')) {
$p = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000, $p['path'], $p['domain'] ?? '', $p['secure'], $p['httponly']);
}
session_destroy();
}
/** @return array<string,mixed>|null */
public static function user(): ?array
{
return isset($_SESSION['user']) && is_array($_SESSION['user']) ? $_SESSION['user'] : null;
}
public static function requireUser(): array
{
$u = self::user();
if ($u === null) {
header('Location: ' . Util::url('login'));
exit;
}
return $u;
}
}

36
src/Config.php Normal file
View file

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace CertiMine;
final class Config
{
/** @var array<string,mixed> */
private static array $data = [];
public static function load(string $basePath): void
{
$local = $basePath . '/config/config.php';
$example = $basePath . '/config/config.example.php';
$file = is_file($local) ? $local : $example;
/** @var array<string,mixed> $cfg */
$cfg = require $file;
self::$data = $cfg;
}
/** @return mixed */
public static function get(string $key, ?string $sub = null)
{
if ($sub === null) {
return self::$data[$key] ?? null;
}
$block = self::$data[$key] ?? [];
return is_array($block) ? ($block[$sub] ?? null) : null;
}
public static function all(): array
{
return self::$data;
}
}

40
src/Database.php Normal file
View file

@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace CertiMine;
use PDO;
use PDOException;
final class Database
{
private static ?PDO $pdo = null;
public static function pdo(): PDO
{
if (self::$pdo instanceof PDO) {
return self::$pdo;
}
$db = Config::get('db');
if (!is_array($db)) {
throw new \RuntimeException('Database config missing');
}
$dsn = sprintf(
'mysql:host=%s;port=%d;dbname=%s;charset=%s',
$db['host'],
(int) $db['port'],
$db['name'],
$db['charset']
);
try {
self::$pdo = new PDO($dsn, $db['user'], $db['pass'], [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
} catch (PDOException $e) {
throw new \RuntimeException('DB connection failed: ' . $e->getMessage(), 0, $e);
}
return self::$pdo;
}
}

47
src/I18n.php Normal file
View file

@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace CertiMine;
final class I18n
{
private const COOKIE = 'certimine_lang';
/** @var array<string,string> */
private static array $strings = [];
public static function bootstrap(): void
{
$allowed = ['es', 'en'];
if (isset($_GET['lang']) && in_array($_GET['lang'], $allowed, true)) {
setcookie(self::COOKIE, $_GET['lang'], [
'expires' => time() + 365 * 86400,
'path' => '/',
'secure' => false,
'httponly' => false,
'samesite' => 'Lax',
]);
$_COOKIE[self::COOKIE] = $_GET['lang'];
}
$lang = $_COOKIE[self::COOKIE] ?? 'es';
if (!in_array($lang, $allowed, true)) {
$lang = 'es';
}
$file = dirname(__DIR__) . '/lang/' . $lang . '.php';
self::$strings = is_file($file) ? require $file : [];
}
public static function lang(): string
{
return $_COOKIE[self::COOKIE] ?? 'es';
}
public static function t(string $key, array $replace = []): string
{
$s = self::$strings[$key] ?? $key;
foreach ($replace as $k => $v) {
$s = str_replace(':' . $k, (string) $v, $s);
}
return $s;
}
}

231
src/MobilisemeClient.php Normal file
View file

@ -0,0 +1,231 @@
<?php
declare(strict_types=1);
namespace CertiMine;
/**
* Cliente HTTP: modo legacy (JSON login) o API Peñasquito DC3 (token estático + passport).
*/
final class MobilisemeClient
{
/**
* @return array{token: string, profile: array<string,mixed>, dc3_result: ?array<string,mixed>}
*/
public static function login(string $username, string $password): array
{
$cfg = Config::get('mobiliseme');
if (!is_array($cfg)) {
throw new \RuntimeException('Mobiliseme config missing');
}
if (PenasquitoDc3Api::isConfigured()) {
$pack = PenasquitoDc3Api::loginWithPassport($username);
return [
'token' => $pack['token'],
'profile' => $pack['profile'],
'dc3_result' => $pack['dc3_result'],
];
}
if (!empty($cfg['mock'])) {
$profile = self::mockProfile($username);
return [
'token' => 'mock-token-' . $profile['id'],
'profile' => $profile,
'dc3_result' => null,
];
}
$base = rtrim((string) $cfg['base_url'], '/');
$path = (string) $cfg['login_path'];
$body = [
(string) $cfg['login_username_field'] => $username,
(string) $cfg['login_password_field'] => $password,
];
$resp = self::request('POST', $base . $path, null, $body);
$token = Util::arrayPath($resp['json'], (string) $cfg['token_json_path']);
if (!is_string($token) || $token === '') {
throw new \RuntimeException('Invalid login response');
}
$prof = self::fetchProfile($token);
return ['token' => $token, 'profile' => $prof, 'dc3_result' => null];
}
/** @return array<string,mixed> */
public static function fetchProfile(string $token): array
{
$cfg = Config::get('mobiliseme');
if (!is_array($cfg)) {
throw new \RuntimeException('Mobiliseme config missing');
}
if (!empty($cfg['mock'])) {
return self::mockProfile('demo');
}
if (PenasquitoDc3Api::isConfigured()) {
return [];
}
$base = rtrim((string) $cfg['base_url'], '/');
$path = (string) $cfg['profile_path'];
$resp = self::request('GET', $base . $path, $token, null);
$json = $resp['json'];
return is_array($json) ? $json : [];
}
/** @return list<array<string,mixed>> */
public static function fetchCertificates(string $mobilisemeId, string $token): array
{
$cfgConfig = Config::get('mobiliseme');
if (PenasquitoDc3Api::isConfigured()) {
try {
$res = PenasquitoDc3Api::fetchResultForPassport($mobilisemeId);
} catch (\Throwable) {
return [];
}
$comps = $res['competencies'] ?? [];
if (!is_array($comps)) {
return [];
}
return self::dc3CompetenciesToItems($mobilisemeId, $comps);
}
if (!is_array($cfgConfig)) {
return [];
}
if (!empty($cfgConfig['mock'])) {
return self::mockCertificates($mobilisemeId);
}
$base = rtrim((string) $cfgConfig['base_url'], '/');
$tpl = (string) $cfgConfig['person_certificates_path'];
$path = str_replace('{id}', rawurlencode($mobilisemeId), $tpl);
$resp = self::request('GET', $base . $path, $token, null);
$json = $resp['json'];
$listPath = (string) $cfgConfig['certificate_list_path'];
$items = Util::arrayPath($json, $listPath);
if (is_array($items)) {
/** @var list<array<string,mixed>> $out */
$out = [];
foreach ($items as $it) {
if (is_array($it)) {
$out[] = $it;
}
}
return $out;
}
return is_array($json) ? [$json] : [];
}
/**
* @param list<array<string,mixed>> $comps
* @return list<array<string,mixed>>
*/
private static function dc3CompetenciesToItems(string $mobilisemeId, array $comps): array
{
$items = [];
foreach ($comps as $c) {
if (!is_array($c)) {
continue;
}
$activity = (string) ($c['activity'] ?? '');
$frm = PenasquitoDc3Api::activityToFrmCode($activity);
$nom = $frm !== null ? PersonRepository::firstNomCodeForFrmCode($frm) : null;
$req = isset($c['request_date']) ? (string) $c['request_date'] : null;
$expRaw = $c['expiration_date'] ?? null;
$expStr = ($expRaw === null || $expRaw === '' || $expRaw === '---') ? null : (string) $expRaw;
$issued = null;
$expires = null;
if ($req !== null) {
$dt = \DateTime::createFromFormat('d/m/Y', trim($req));
$issued = $dt ? $dt->format('Y-m-d') : null;
}
if ($expStr !== null) {
$dt2 = \DateTime::createFromFormat('d/m/Y', trim($expStr));
$expires = $dt2 ? $dt2->format('Y-m-d') : null;
}
$items[] = [
'title' => $activity,
'nom_code' => (string) ($nom ?? ''),
'issued_at' => $issued,
'expires_at' => $expires,
'external_ref' => 'dc3-' . md5($mobilisemeId . '|' . $activity . '|' . $req),
];
}
return $items;
}
/**
* @param array<string,mixed>|null $jsonBody
* @return array{status:int, json:mixed, raw:string}
*/
private static function request(string $method, string $url, ?string $token, ?array $jsonBody): array
{
$cfg = Config::get('mobiliseme');
$timeout = is_array($cfg) ? (int) ($cfg['timeout_seconds'] ?? 15) : 15;
$ch = curl_init($url);
$headers = ['Accept: application/json'];
if ($jsonBody !== null) {
$headers[] = 'Content-Type: application/json';
}
if ($token !== null && is_array($cfg)) {
$hName = (string) $cfg['authorization_header'];
$scheme = (string) $cfg['authorization_scheme'];
$headers[] = $hName . ': ' . $scheme . $token;
}
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_HTTPHEADER => $headers,
]);
if ($jsonBody !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($jsonBody, JSON_UNESCAPED_UNICODE));
}
$raw = curl_exec($ch);
if ($raw === false) {
$err = curl_error($ch);
curl_close($ch);
throw new \RuntimeException('cURL error: ' . $err);
}
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($method !== 'POST' && ($status < 200 || $status >= 300)) {
throw new \RuntimeException('HTTP ' . $status);
}
if ($method === 'POST' && is_array($cfg) && isset($cfg['login_path']) && str_contains($url, (string) $cfg['login_path']) && ($status < 200 || $status >= 300)) {
throw new \RuntimeException('Login HTTP ' . $status);
}
$decoded = json_decode((string) $raw, true);
return ['status' => $status, 'json' => $decoded, 'raw' => (string) $raw];
}
/** @return array<string,mixed> */
private static function mockProfile(string $username): array
{
$u = strtolower($username);
if (str_contains($u, 'contract')) {
return [
'id' => 'demo-contractor-1',
'full_name' => 'Demo Contractor SA',
'type' => 'contractor',
'employee_number' => 'C-5001',
];
}
return [
'id' => 'demo-employee-1',
'full_name' => 'Demo Employee',
'type' => 'employee',
'employee_number' => '10001',
];
}
/** @return list<array<string,mixed>> */
private static function mockCertificates(string $mobilisemeId): array
{
if ($mobilisemeId === 'demo-contractor-1') {
return [
['nom_code' => 'NOM-009', 'title' => 'DC3 Heights', 'expires_at' => date('Y-m-d', strtotime('+300 days'))],
['nom_code' => 'NOM-001', 'title' => 'DC3 Confined', 'expires_at' => date('Y-m-d', strtotime('+200 days'))],
];
}
return [
['nom_code' => 'NOM-009', 'title' => 'DC3 Heights', 'expires_at' => date('Y-m-d', strtotime('+335 days'))],
['nom_code' => 'NOM-017', 'title' => 'DC3 PPE', 'expires_at' => date('Y-m-d', strtotime('+100 days'))],
];
}
}

383
src/PenasquitoDc3Api.php Normal file
View file

@ -0,0 +1,383 @@
<?php
declare(strict_types=1);
namespace CertiMine;
/**
* Cliente del API REST Peñasquito / Wotbi (competencias DC3 por passport).
* Documentación de origen: DatosPdf.txt (extraído del PDF de scraping Mobilise-Me).
*/
final class PenasquitoDc3Api
{
public static function resolvedToken(): string
{
$env = getenv('CERTIMINE_DC3_TOKEN');
if (is_string($env) && $env !== '') {
return $env;
}
$cfg = Config::get('penasquito_dc3');
if (!is_array($cfg)) {
return '';
}
$t = (string) ($cfg['static_token'] ?? '');
return $t;
}
public static function isConfigured(): bool
{
return self::resolvedToken() !== '';
}
/**
* Respuesta combinada: mismo shape que `result` del JSON cuando status=completed.
*
* @return array{passport:string,name:string,company:string,competencies:list<array<string,mixed>>,error:?string}
*/
public static function fetchResultForPassport(string $passport): array
{
if (!self::isConfigured()) {
throw new \RuntimeException('DC3 API not configured (token vacío).');
}
$passport = trim($passport);
if ($passport === '') {
throw new \RuntimeException('Passport vacío.');
}
$search = self::search($passport);
$status = (string) ($search['status'] ?? '');
if ($status === 'completed') {
$res = $search['result'] ?? null;
if (!is_array($res)) {
throw new \RuntimeException('Respuesta completed sin result.');
}
self::assertResultOk($res);
/** @var array{passport:string,name:string,company:string,competencies:list<array<string,mixed>>,error:?string} $res */
return $res;
}
if ($status === 'pending') {
$ticket = (string) ($search['ticket_id'] ?? '');
if ($ticket === '') {
throw new \RuntimeException('pending sin ticket_id.');
}
$cfg = Config::get('penasquito_dc3');
$pollS = is_array($cfg) ? (int) ($cfg['poll_interval_seconds'] ?? 2) : 2;
$max = is_array($cfg) ? (int) ($cfg['poll_max_attempts'] ?? 20) : 20;
for ($i = 0; $i < $max; $i++) {
usleep((int) max(1, $pollS) * 1_000_000);
$r = self::ticketResult($ticket);
$st = (string) ($r['status'] ?? '');
if ($st === 'completed') {
$res = $r['result'] ?? null;
if (!is_array($res)) {
throw new \RuntimeException('Ticket completado sin result.');
}
self::assertResultOk($res);
/** @var array{passport:string,name:string,company:string,competencies:list<array<string,mixed>>,error:?string} $out */
$out = $res;
return $out;
}
if ($st !== 'pending' && $st !== 'processing') {
throw new \RuntimeException('Estado de ticket inesperado: ' . $st);
}
}
throw new \RuntimeException('Tiempo de espera agotado consultando el ticket DC3.');
}
throw new \RuntimeException('Estado de búsqueda inesperado: ' . $status);
}
/**
* Perfil mínimo para Auth::login y caché local.
*
* @return array{token: string, profile: array<string,mixed>}
*/
public static function loginWithPassport(string $passport): array
{
$result = self::fetchResultForPassport($passport);
$tok = self::resolvedToken();
$isContractor = self::guessContractorFromCompany((string) ($result['company'] ?? ''));
$profile = [
'id' => (string) ($result['passport'] ?? $passport),
'full_name' => (string) ($result['name'] ?? ''),
'type' => $isContractor ? 'contractor' : 'employee',
'employee_number' => (string) ($result['passport'] ?? $passport),
'company' => (string) ($result['company'] ?? ''),
];
return ['token' => $tok, 'profile' => $profile, 'dc3_result' => $result];
}
/**
* Persiste competencias DC3 en users_cache, certificates y autorizaciones FRM.
*
* @param array{passport?:string,name?:string,company?:string,competencies?:mixed,error?:mixed} $result
*/
public static function persistResult(string $mobilisemeId, array $result, string $personType): void
{
self::assertResultOk($result);
$name = (string) ($result['name'] ?? '—');
$emp = (string) ($result['passport'] ?? $mobilisemeId);
$comps = $result['competencies'] ?? [];
if (!is_array($comps)) {
$comps = [];
}
$items = self::competenciesToCertificatePayloads($mobilisemeId, $comps);
PersonRepository::applySyncPayload($mobilisemeId, ['certificates' => $items]);
if ($personType === 'contractor') {
$auths = self::competenciesToAuthorizations($comps);
if ($auths !== []) {
PersonRepository::applySyncPayload($mobilisemeId, ['authorizations' => $auths]);
}
}
$frms = PersonRepository::authorizations($mobilisemeId);
$green = PersonRepository::recomputeGreenLicense($mobilisemeId, $personType, $frms);
PersonRepository::upsertCache($mobilisemeId, $emp, $name, $personType, $green);
}
/** @param array<string,mixed> $result */
private static function assertResultOk(array $result): void
{
$err = $result['error'] ?? null;
if ($err !== null && $err !== '') {
throw new \RuntimeException(is_string($err) ? $err : 'Error DC3');
}
}
/** @return array<string,mixed> */
private static function search(string $passport): array
{
$cfg = Config::get('penasquito_dc3');
$base = rtrim((string) (is_array($cfg) ? $cfg['base_url'] : ''), '/');
$path = (string) (is_array($cfg) ? $cfg['search_path'] : '');
$url = $base . $path;
$resp = self::request('POST', $url, ['passport' => $passport]);
$j = $resp['json'];
return is_array($j) ? $j : [];
}
/** @return array<string,mixed> */
private static function ticketResult(string $ticketId): array
{
$cfg = Config::get('penasquito_dc3');
$base = rtrim((string) (is_array($cfg) ? $cfg['base_url'] : ''), '/');
$tpl = (string) (is_array($cfg) ? $cfg['result_path_template'] : '');
$path = str_replace('{ticket_id}', rawurlencode($ticketId), $tpl);
$resp = self::request('GET', $base . $path, null);
$j = $resp['json'];
return is_array($j) ? $j : [];
}
/**
* Estado de cola (monitoreo).
*
* @return array<string,mixed>
*/
public static function queueStatus(): array
{
if (!self::isConfigured()) {
return [];
}
$cfg = Config::get('penasquito_dc3');
$base = rtrim((string) (is_array($cfg) ? $cfg['base_url'] : ''), '/');
$path = (string) (is_array($cfg) ? $cfg['status_path'] : '');
$resp = self::request('GET', $base . $path, null);
$j = $resp['json'];
return is_array($j) ? $j : [];
}
/**
* @param array<string,mixed>|null $jsonBody
* @return array{status:int, json:mixed, raw:string}
*/
private static function request(string $method, string $url, ?array $jsonBody): array
{
$dc3 = Config::get('penasquito_dc3');
$timeout = is_array($dc3) ? (int) ($dc3['timeout_seconds'] ?? 30) : 30;
$token = self::resolvedToken();
$headerName = is_array($dc3) ? (string) ($dc3['authorization_header'] ?? 'Authorization') : 'Authorization';
$scheme = is_array($dc3) ? (string) ($dc3['authorization_scheme'] ?? 'Token ') : 'Token ';
$ch = curl_init($url);
$headers = ['Accept: application/json'];
if ($jsonBody !== null) {
$headers[] = 'Content-Type: application/json';
}
$headers[] = $headerName . ': ' . $scheme . $token;
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_HTTPHEADER => $headers,
]);
if ($jsonBody !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($jsonBody, JSON_UNESCAPED_UNICODE));
}
$raw = curl_exec($ch);
if ($raw === false) {
$err = curl_error($ch);
curl_close($ch);
throw new \RuntimeException('cURL: ' . $err);
}
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status === 401) {
throw new \RuntimeException('DC3 API 401 (token inválido o ausente).');
}
if ($status < 200 || $status >= 300) {
throw new \RuntimeException('DC3 API HTTP ' . $status);
}
$decoded = json_decode((string) $raw, true);
return ['status' => $status, 'json' => $decoded, 'raw' => (string) $raw];
}
public static function guessContractorFromCompanyPublic(string $company): bool
{
return self::guessContractorFromCompany($company);
}
private static function guessContractorFromCompany(string $company): bool
{
$u = strtoupper($company);
if ($u === '' || str_contains($u, 'NEWMONT') || str_contains($u, 'PEÑASQUETO') || str_contains($u, 'PENASQUITO')) {
return false;
}
return str_contains($u, 'SOCIEDAD') || str_contains($u, ' S.A.') || str_contains($u, ' SA ') || str_contains($u, 'CONTRACT');
}
/**
* @param list<array<string,mixed>> $comps
* @return list<array<string,mixed>>
*/
private static function competenciesToCertificatePayloads(string $mobilisemeId, array $comps): array
{
$out = [];
foreach ($comps as $c) {
if (!is_array($c)) {
continue;
}
$activity = (string) ($c['activity'] ?? '');
$req = isset($c['request_date']) ? (string) $c['request_date'] : null;
$expRaw = $c['expiration_date'] ?? null;
$expStr = ($expRaw === null || $expRaw === '' || $expRaw === '---') ? null : (string) $expRaw;
$st = self::mapDc3Status((string) ($c['status'] ?? ''));
$frmCode = self::activityToFrmCode($activity);
$nomCode = '';
if ($frmCode !== null) {
$nomCode = (string) (PersonRepository::firstNomCodeForFrmCode($frmCode) ?? '');
}
$issued = self::parseDateDmY($req);
$expires = $expStr !== null ? self::parseDateDmY($expStr) : null;
if ($expires !== null && $expires < date('Y-m-d') && $st === 'valid') {
$st = 'expired';
}
$ext = 'dc3-' . md5($mobilisemeId . '|' . $activity . '|' . (string) $req);
$row = [
'title' => $activity !== '' ? $activity : 'DC3',
'issued_at' => $issued,
'expires_at' => $expires,
'status' => $st,
'external_ref' => $ext,
'frm_code' => $frmCode ?? '',
'nom_code' => $nomCode,
];
$out[] = $row;
}
return $out;
}
/**
* @param list<array<string,mixed>> $comps
* @return list<array<string,mixed>>
*/
private static function competenciesToAuthorizations(array $comps): array
{
$out = [];
foreach ($comps as $c) {
if (!is_array($c)) {
continue;
}
$activity = (string) ($c['activity'] ?? '');
$frm = self::activityToFrmCode($activity);
if ($frm === null) {
continue;
}
$expRaw = $c['expiration_date'] ?? null;
$expStr = ($expRaw === null || $expRaw === '' || $expRaw === '---') ? null : (string) $expRaw;
$vu = $expStr !== null ? self::parseDateDmY($expStr) : null;
$st = strtolower((string) ($c['status'] ?? ''));
if (str_contains($st, 'vencid')) {
continue;
}
$out[] = ['frm_code' => $frm, 'valid_until' => $vu];
}
return $out;
}
public static function mapDc3Status(string $raw): string
{
$s = strtolower(trim($raw));
if ($s === '' || $s === 'received') {
return 'valid';
}
if (str_contains($s, 'vencid')) {
return 'expired';
}
if (str_contains($s, 'pend')) {
return 'pending';
}
return 'valid';
}
private static function parseDateDmY(?string $d): ?string
{
if ($d === null || $d === '' || $d === '---') {
return null;
}
$d = trim($d);
$dt = \DateTime::createFromFormat('d/m/Y', $d);
if ($dt instanceof \DateTime) {
return $dt->format('Y-m-d');
}
$ts = strtotime($d);
if ($ts !== false) {
return date('Y-m-d', $ts);
}
return null;
}
public static function activityToFrmCode(string $activity): ?string
{
$u = strtoupper($activity);
$pairs = [
'CONFINED' => 'FRM_CONFINED',
'BARICAD' => 'FRM_BARRICADAS',
'EXCLUSION' => 'FRM_BARRICADAS',
'TERRENO' => 'FRM_TERRENO',
'GROUND' => 'FRM_TERRENO',
'ENERGÍA' => 'FRM_ENERGIA',
'ENERGIA' => 'FRM_ENERGIA',
'STORED ENERGY' => 'FRM_ENERGIA',
'CRANE' => 'FRM_GRUAS',
'GRÚA' => 'FRM_GRUAS',
'LEVANTAMIENTO' => 'FRM_GRUAS',
'SALUD' => 'FRM_SALUD',
'HIGIENE' => 'FRM_SALUD',
'MATERIAL' => 'FRM_MATPEL',
'PELIGROS' => 'FRM_MATPEL',
'ELECTR' => 'FRM_ELEC',
'ALTURA' => 'FRM_ALTURAS',
'HEIGHT' => 'FRM_ALTURAS',
'VEHICLE' => 'FRM_VEHICULOS',
'MANEJO' => 'FRM_VEHICULOS',
'AVIATION' => 'FRM_AVIACION',
];
foreach ($pairs as $needle => $code) {
if (str_contains($u, $needle)) {
return $code;
}
}
return null;
}
}

300
src/PersonRepository.php Normal file
View file

@ -0,0 +1,300 @@
<?php
declare(strict_types=1);
namespace CertiMine;
use PDO;
final class PersonRepository
{
public static function upsertCache(
string $mobilisemeId,
?string $employeeNumber,
string $displayName,
string $personType,
bool $greenLicense
): void {
$pdo = Database::pdo();
$st = $pdo->prepare(
'INSERT INTO users_cache (mobiliseme_id, employee_number, display_name, person_type, green_license_flag)
VALUES (?,?,?,?,?)
ON DUPLICATE KEY UPDATE employee_number=VALUES(employee_number), display_name=VALUES(display_name),
person_type=VALUES(person_type), green_license_flag=VALUES(green_license_flag)'
);
$st->execute([$mobilisemeId, $employeeNumber, $displayName, $personType, $greenLicense ? 1 : 0]);
}
/** @return array<string,mixed>|null */
public static function findByMobilisemeId(string $id): ?array
{
$pdo = Database::pdo();
$st = $pdo->prepare('SELECT * FROM users_cache WHERE mobiliseme_id = ? LIMIT 1');
$st->execute([$id]);
$row = $st->fetch(PDO::FETCH_ASSOC);
return $row ?: null;
}
/** @return array<string,mixed>|null */
public static function findByEmployeeNumber(string $num): ?array
{
$pdo = Database::pdo();
$st = $pdo->prepare('SELECT * FROM users_cache WHERE employee_number = ? LIMIT 1');
$st->execute([$num]);
$row = $st->fetch(PDO::FETCH_ASSOC);
return $row ?: null;
}
/** @return array<string,mixed>|null */
public static function findByEmployeeNumberAndType(string $num, string $type): ?array
{
$pdo = Database::pdo();
$st = $pdo->prepare(
'SELECT * FROM users_cache WHERE employee_number = ? AND person_type = ? LIMIT 1'
);
$st->execute([$num, $type]);
$row = $st->fetch(PDO::FETCH_ASSOC);
return $row ?: null;
}
/** @return list<int> */
public static function validNomIdsForPerson(string $mobilisemeId): array
{
$pdo = Database::pdo();
$st = $pdo->prepare(
'SELECT DISTINCT nom_id FROM certificates WHERE mobiliseme_id = ? AND status = "valid" AND nom_id IS NOT NULL'
);
$st->execute([$mobilisemeId]);
$out = [];
while (($v = $st->fetchColumn()) !== false) {
$out[] = (int) $v;
}
return $out;
}
/** @return list<array<string,mixed>> */
public static function certificates(string $mobilisemeId): array
{
$pdo = Database::pdo();
$sql = 'SELECT c.*, n.code AS nom_code, n.name_en AS nom_name_en, n.name_es AS nom_name_es,
f.code AS frm_code, f.name_en AS frm_name_en, f.name_es AS frm_name_es
FROM certificates c
LEFT JOIN nom_competency n ON n.id = c.nom_id
LEFT JOIN frm_standard f ON f.id = c.frm_id
WHERE c.mobiliseme_id = ?
ORDER BY c.expires_at IS NULL, c.expires_at ASC';
$st = $pdo->prepare($sql);
$st->execute([$mobilisemeId]);
return $st->fetchAll(PDO::FETCH_ASSOC);
}
/** @return list<array<string,mixed>> */
public static function authorizations(string $mobilisemeId): array
{
$pdo = Database::pdo();
$sql = 'SELECT a.*, f.code, f.name_en, f.name_es FROM contractor_authorizations a
JOIN frm_standard f ON f.id = a.frm_id
WHERE a.mobiliseme_id = ? ORDER BY f.sort_order';
$st = $pdo->prepare($sql);
$st->execute([$mobilisemeId]);
return $st->fetchAll(PDO::FETCH_ASSOC);
}
/** @return list<array<string,mixed>> */
public static function coursesForNoms(array $nomIds): array
{
if ($nomIds === []) {
return [];
}
$pdo = Database::pdo();
$place = implode(',', array_fill(0, count($nomIds), '?'));
$sql = "SELECT DISTINCT co.id, co.title_en, co.title_es, co.url
FROM courses co
JOIN course_requirement cr ON cr.course_id = co.id
WHERE cr.nom_id IN ($place)
ORDER BY co.sort_order";
$st = $pdo->prepare($sql);
$st->execute(array_values($nomIds));
return $st->fetchAll(PDO::FETCH_ASSOC);
}
public static function logAudit(string $action, string $subjectType, string $subjectId): void
{
$pdo = Database::pdo();
$ip = $_SERVER['REMOTE_ADDR'] ?? null;
$st = $pdo->prepare('INSERT INTO audit_log (action, subject_type, subject_id, ip) VALUES (?,?,?,?)');
$st->execute([$action, $subjectType, $subjectId, $ip]);
}
/** @param list<array<string,mixed>> $frms */
public static function recomputeGreenLicense(string $mobilisemeId, string $personType, array $frms): bool
{
if ($personType !== 'contractor') {
return true;
}
$today = date('Y-m-d');
foreach ($frms as $a) {
$vu = $a['valid_until'] ?? null;
if ($vu !== null && $vu < $today) {
return false;
}
}
return $frms !== [];
}
/**
* Sync certificate rows from API-shaped items (nom_code, title, expires_at, ...).
*
* @param list<array<string,mixed>> $items
*/
public static function syncCertificatesFromApi(string $mobilisemeId, array $items): void
{
$pdo = Database::pdo();
foreach ($items as $it) {
if (!is_array($it)) {
continue;
}
$code = isset($it['nom_code']) ? (string) $it['nom_code'] : '';
$nomId = self::nomIdByCode($code);
$title = (string) ($it['title'] ?? $code);
$exp = isset($it['expires_at']) ? (string) $it['expires_at'] : null;
$issued = isset($it['issued_at']) ? (string) $it['issued_at'] : null;
$ext = (string) ($it['external_ref'] ?? ('api-' . md5($mobilisemeId . $code . $title)));
$status = 'valid';
if ($exp !== null && $exp !== '' && $exp < date('Y-m-d')) {
$status = 'expired';
}
$st = $pdo->prepare(
'INSERT INTO certificates (mobiliseme_id, nom_id, title, issued_at, expires_at, status, external_ref)
VALUES (?,?,?,?,?,?,?)
ON DUPLICATE KEY UPDATE title=VALUES(title), issued_at=VALUES(issued_at), expires_at=VALUES(expires_at),
status=VALUES(status), nom_id=VALUES(nom_id)'
);
$st->execute([$mobilisemeId, $nomId, $title, $issued ?: null, $exp ?: null, $status, $ext]);
}
}
/** Primer NOM vinculado al estándar FRM (para sugerir cursos). */
public static function firstNomCodeForFrmCode(string $frmCode): ?string
{
if ($frmCode === '') {
return null;
}
$fid = self::frmIdByCode($frmCode);
if ($fid === null) {
return null;
}
$pdo = Database::pdo();
$st = $pdo->prepare(
'SELECT n.code FROM frm_nom_map m JOIN nom_competency n ON n.id = m.nom_id
WHERE m.frm_id = ? ORDER BY n.sort_order LIMIT 1'
);
$st->execute([$fid]);
$v = $st->fetchColumn();
return $v !== false ? (string) $v : null;
}
private static function nomIdByCode(string $code): ?int
{
if ($code === '') {
return null;
}
$pdo = Database::pdo();
$st = $pdo->prepare('SELECT id FROM nom_competency WHERE code = ? LIMIT 1');
$st->execute([$code]);
$v = $st->fetchColumn();
return $v !== false ? (int) $v : null;
}
private static function frmIdByCode(string $code): ?int
{
$pdo = Database::pdo();
$st = $pdo->prepare('SELECT id FROM frm_standard WHERE code = ? LIMIT 1');
$st->execute([$code]);
$v = $st->fetchColumn();
return $v !== false ? (int) $v : null;
}
/**
* Apply webhook payload certificates/authorizations.
*
* @param array<string,mixed> $payload
*/
public static function applySyncPayload(string $mobilisemeId, array $payload): void
{
$pdo = Database::pdo();
if (isset($payload['certificates']) && is_array($payload['certificates'])) {
foreach ($payload['certificates'] as $c) {
if (!is_array($c)) {
continue;
}
$nomCode = (string) ($c['nom_code'] ?? '');
$nomId = self::nomIdByCode($nomCode);
$title = (string) ($c['title'] ?? 'DC3');
$issued = isset($c['issued_at']) ? (string) $c['issued_at'] : null;
$exp = isset($c['expires_at']) ? (string) $c['expires_at'] : null;
$ext = (string) ($c['external_ref'] ?? uniqid('wh-', true));
$frmCode = (string) ($c['frm_code'] ?? '');
$frmId = $frmCode !== '' ? self::frmIdByCode($frmCode) : null;
$status = (string) ($c['status'] ?? 'valid');
$st = $pdo->prepare(
'INSERT INTO certificates (mobiliseme_id, nom_id, frm_id, title, issued_at, expires_at, status, external_ref)
VALUES (?,?,?,?,?,?,?,?)
ON DUPLICATE KEY UPDATE title=VALUES(title), issued_at=VALUES(issued_at), expires_at=VALUES(expires_at),
status=VALUES(status), nom_id=VALUES(nom_id), frm_id=VALUES(frm_id)'
);
$st->execute([$mobilisemeId, $nomId, $frmId, $title, $issued ?: null, $exp ?: null, $status, $ext]);
}
}
if (isset($payload['authorizations']) && is_array($payload['authorizations'])) {
foreach ($payload['authorizations'] as $a) {
if (!is_array($a)) {
continue;
}
$fc = (string) ($a['frm_code'] ?? '');
$fid = self::frmIdByCode($fc);
if ($fid === null) {
continue;
}
$vu = isset($a['valid_until']) ? (string) $a['valid_until'] : null;
$st = $pdo->prepare(
'INSERT INTO contractor_authorizations (mobiliseme_id, frm_id, valid_until, source)
VALUES (?,?,?, "webhook")
ON DUPLICATE KEY UPDATE valid_until=VALUES(valid_until), source=VALUES(source)'
);
$st->execute([$mobilisemeId, $fid, $vu ?: null]);
}
}
}
/** @return list<array<string,mixed>> */
public static function frmWithNoms(): array
{
$pdo = Database::pdo();
$frms = $pdo->query(
'SELECT * FROM frm_standard ORDER BY sort_order, id'
)->fetchAll(PDO::FETCH_ASSOC);
$out = [];
foreach ($frms as $f) {
$st = $pdo->prepare(
'SELECT n.code, n.name_en, n.name_es FROM frm_nom_map m
JOIN nom_competency n ON n.id = m.nom_id WHERE m.frm_id = ? ORDER BY n.sort_order'
);
$st->execute([(int) $f['id']]);
$f['noms'] = $st->fetchAll(PDO::FETCH_ASSOC);
$out[] = $f;
}
return $out;
}
/** @return list<array<string,mixed>> */
public static function publicDocuments(): array
{
$pdo = Database::pdo();
return $pdo->query(
'SELECT d.*, f.code AS frm_code FROM public_documents d
LEFT JOIN frm_standard f ON f.id = d.frm_id
ORDER BY d.sort_order, d.id'
)->fetchAll(PDO::FETCH_ASSOC);
}
}

45
src/Security.php Normal file
View file

@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace CertiMine;
final class Security
{
public static function csrfToken(): string
{
if (empty($_SESSION['_csrf'])) {
$_SESSION['_csrf'] = bin2hex(random_bytes(32));
}
return $_SESSION['_csrf'];
}
public static function verifyCsrf(?string $token): bool
{
return is_string($token)
&& isset($_SESSION['_csrf'])
&& hash_equals($_SESSION['_csrf'], $token);
}
public static function qrSignature(string $type, string $code): string
{
$app = Config::get('app');
$secret = is_array($app) ? (string) ($app['qr_secret'] ?? '') : '';
$payload = $type . '|' . $code;
return hash_hmac('sha256', $payload, $secret);
}
public static function verifyQrSignature(string $type, string $code, ?string $sig): bool
{
$app = Config::get('app');
$enforce = is_array($app) && !empty($app['qr_enforce']);
if (!$enforce) {
return true;
}
if ($sig === null || $sig === '') {
return false;
}
$expected = self::qrSignature($type, $code);
return hash_equals($expected, $sig);
}
}

95
src/SyncService.php Normal file
View file

@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
namespace CertiMine;
use PDO;
final class SyncService
{
public static function handleWebhook(string $rawBody, ?string $signatureHeader): int
{
$cfg = Config::get('mobiliseme');
$secret = is_array($cfg) ? (string) ($cfg['webhook_secret'] ?? '') : '';
if ($secret !== '') {
$expected = 'sha256=' . hash_hmac('sha256', $rawBody, $secret);
if ($signatureHeader === null || !hash_equals($expected, $signatureHeader)) {
return 401;
}
}
/** @var mixed $data */
$data = json_decode($rawBody, true);
if (!is_array($data)) {
return 400;
}
$event = (string) ($data['event'] ?? 'unknown');
$externalId = (string) ($data['external_id'] ?? '');
if ($externalId === '') {
return 400;
}
$personId = (string) ($data['person_id'] ?? '');
if ($personId === '') {
return 400;
}
$pdo = Database::pdo();
$hash = hash('sha256', $rawBody);
try {
$st = $pdo->prepare(
'INSERT INTO sync_event (external_id, event_type, payload_hash, processed_at)
VALUES (?,?,?,NULL)'
);
$st->execute([$externalId, $event, $hash]);
} catch (\PDOException $e) {
if (isset($e->errorInfo[1]) && (int) $e->errorInfo[1] === 1062) {
return 200;
}
throw $e;
}
/** @var array<string,mixed> $payload */
$payload = isset($data['payload']) && is_array($data['payload']) ? $data['payload'] : [];
PersonRepository::applySyncPayload($personId, $payload);
$row = PersonRepository::findByMobilisemeId($personId);
$type = is_array($row) ? (string) $row['person_type'] : 'contractor';
$frms = PersonRepository::authorizations($personId);
$green = PersonRepository::recomputeGreenLicense($personId, $type, $frms);
if (is_array($row)) {
PersonRepository::upsertCache(
$personId,
$row['employee_number'] !== null ? (string) $row['employee_number'] : null,
(string) $row['display_name'],
$type,
$green
);
} else {
PersonRepository::upsertCache($personId, null, 'Contractor ' . $personId, 'contractor', $green);
}
$upd = $pdo->prepare('UPDATE sync_event SET processed_at = NOW() WHERE external_id = ? AND event_type = ?');
$upd->execute([$externalId, $event]);
return 200;
}
public static function recomputeGreenLicenses(): void
{
$pdo = Database::pdo();
$st = $pdo->query('SELECT mobiliseme_id, person_type FROM users_cache');
$rows = $st->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $r) {
$id = (string) $r['mobiliseme_id'];
$type = (string) $r['person_type'];
$frms = PersonRepository::authorizations($id);
$green = PersonRepository::recomputeGreenLicense($id, $type, $frms);
$row = PersonRepository::findByMobilisemeId($id);
if ($row === null) {
continue;
}
PersonRepository::upsertCache(
$id,
$row['employee_number'] !== null ? (string) $row['employee_number'] : null,
(string) $row['display_name'],
$type,
$green
);
}
}
}

37
src/Util.php Normal file
View file

@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace CertiMine;
final class Util
{
/** @param mixed $data */
public static function arrayPath($data, string $path): mixed
{
if ($path === '') {
return $data;
}
$cur = $data;
foreach (explode('.', $path) as $seg) {
if (!is_array($cur) || !array_key_exists($seg, $cur)) {
return null;
}
$cur = $cur[$seg];
}
return $cur;
}
public static function h(string $s): string
{
return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
public static function url(string $route, array $query = []): string
{
$app = Config::get('app');
$base = is_array($app) ? (string) ($app['public_url'] ?? '') : '';
$q = array_merge(['r' => $route], $query);
return rtrim($base, '/') . '/index.php?' . http_build_query($q);
}
}

20
src/bootstrap.php Normal file
View file

@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
$base = dirname(__DIR__);
require_once $base . '/src/Config.php';
require_once $base . '/src/Util.php';
require_once $base . '/src/Database.php';
require_once $base . '/src/I18n.php';
require_once $base . '/src/Security.php';
require_once $base . '/src/PersonRepository.php';
require_once $base . '/src/PenasquitoDc3Api.php';
require_once $base . '/src/MobilisemeClient.php';
require_once $base . '/src/Auth.php';
require_once $base . '/src/SyncService.php';
\CertiMine\Config::load($base);
date_default_timezone_set((string) (\CertiMine\Config::get('app', 'timezone') ?: 'UTC'));
\CertiMine\I18n::bootstrap();
\CertiMine\Auth::startSession();

14
src/bootstrap_api.php Normal file
View file

@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
$base = dirname(__DIR__);
require_once $base . '/src/Config.php';
require_once $base . '/src/Util.php';
require_once $base . '/src/Database.php';
require_once $base . '/src/PersonRepository.php';
require_once $base . '/src/SyncService.php';
\CertiMine\Config::load($base);
date_default_timezone_set((string) (\CertiMine\Config::get('app', 'timezone') ?: 'UTC'));

64
views/dashboard.php Normal file
View file

@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
use CertiMine\I18n;
use CertiMine\Util;
/** @var array<string,mixed> $user */
/** @var array<string,mixed>|null $row */
/** @var list<array<string,mixed>> $certs */
/** @var list<array<string,mixed>> $courses */
require __DIR__ . '/partials/header.php';
$isEs = I18n::lang() === 'es';
$name = (string) $user['name'];
$statusLabel = static function (string $s): string {
return I18n::t('status_' . $s);
};
?>
<h1 class="h3 mb-2"><?= Util::h(I18n::t('dashboard_welcome', ['name' => $name])) ?></h1>
<p class="text-muted"><?= Util::h(I18n::t('dashboard_profile')) ?></p>
<div class="row g-4">
<div class="col-lg-6">
<div class="card p-3">
<h2 class="h5"><?= Util::h(I18n::t('profile_certs')) ?></h2>
<ul class="list-group list-group-flush">
<?php foreach ($certs as $c): ?>
<li class="list-group-item d-flex justify-content-between">
<div>
<div class="fw-semibold"><?= Util::h((string) $c['title']) ?></div>
<small class="text-muted">
<?= $c['nom_code'] ? Util::h((string) $c['nom_code']) . ' — ' : '' ?>
<?= Util::h($isEs ? (string) ($c['nom_name_es'] ?? '') : (string) ($c['nom_name_en'] ?? '')) ?>
</small>
</div>
<span class="badge text-bg-secondary align-self-center"><?= Util::h($statusLabel((string) $c['status'])) ?></span>
</li>
<?php endforeach; ?>
<?php if ($certs === []): ?>
<li class="list-group-item text-muted"><?= Util::h(I18n::t('no_results')) ?></li>
<?php endif; ?>
</ul>
</div>
</div>
<div class="col-lg-6">
<div class="card p-3">
<h2 class="h5"><?= Util::h(I18n::t('dashboard_courses')) ?></h2>
<ul class="list-group list-group-flush">
<?php foreach ($courses as $co): ?>
<li class="list-group-item d-flex justify-content-between align-items-center">
<span><?= Util::h($isEs ? (string) $co['title_es'] : (string) $co['title_en']) ?></span>
<a class="btn btn-sm btn-outline-success" target="_blank" rel="noopener" href="<?= Util::h((string) $co['url']) ?>">LMS</a>
</li>
<?php endforeach; ?>
<?php if ($courses === []): ?>
<li class="list-group-item text-muted"><?= Util::h(I18n::t('no_results')) ?></li>
<?php endif; ?>
</ul>
</div>
</div>
</div>
<?php require __DIR__ . '/partials/footer.php'; ?>

57
views/frm_library.php Normal file
View file

@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
use CertiMine\I18n;
use CertiMine\Util;
/** @var list<array<string,mixed>> $frms */
/** @var list<array<string,mixed>> $docs */
require __DIR__ . '/partials/header.php';
$isEs = I18n::lang() === 'es';
?>
<h1 class="h3 mb-3"><?= Util::h(I18n::t('frm_title')) ?></h1>
<p class="text-muted"><?= Util::h(I18n::t('frm_intro')) ?></p>
<?php if ($docs !== []): ?>
<h2 class="h5 mt-4"><?= $isEs ? 'Enlaces públicos' : 'Public links' ?></h2>
<ul class="list-group mb-4">
<?php foreach ($docs as $d): ?>
<li class="list-group-item d-flex justify-content-between align-items-center">
<span><?= Util::h($isEs ? (string) $d['title_es'] : (string) $d['title_en']) ?></span>
<a class="btn btn-sm btn-outline-primary" target="_blank" rel="noopener" href="<?= Util::h((string) $d['url']) ?>">URL</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<div class="accordion" id="frmAcc">
<?php foreach ($frms as $i => $f): ?>
<?php
$name = $isEs ? (string) $f['name_es'] : (string) $f['name_en'];
$desc = $isEs ? (string) ($f['description_es'] ?? '') : (string) ($f['description_en'] ?? '');
?>
<div class="accordion-item">
<h2 class="accordion-header" id="h<?= (int) $i ?>">
<button class="accordion-button<?= $i ? ' collapsed' : '' ?>" type="button" data-bs-toggle="collapse" data-bs-target="#c<?= (int) $i ?>">
<?= Util::h((string) $f['code']) ?> — <?= Util::h($name) ?>
</button>
</h2>
<div id="c<?= (int) $i ?>" class="accordion-collapse collapse<?= $i === 0 ? ' show' : '' ?>" data-bs-parent="#frmAcc">
<div class="accordion-body">
<?php if ($desc !== ''): ?><p><?= Util::h($desc) ?></p><?php endif; ?>
<?php if (!empty($f['noms']) && is_array($f['noms'])): ?>
<p class="fw-semibold mb-1"><?= Util::h(I18n::t('frm_nom_related')) ?></p>
<ul class="mb-0">
<?php foreach ($f['noms'] as $n): ?>
<li><strong><?= Util::h((string) $n['code']) ?></strong> — <?= Util::h($isEs ? (string) $n['name_es'] : (string) $n['name_en']) ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<?php require __DIR__ . '/partials/footer.php'; ?>

29
views/home.php Normal file
View file

@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
use CertiMine\I18n;
use CertiMine\Util;
require __DIR__ . '/partials/header.php';
?>
<div class="row g-4 align-items-center">
<div class="col-lg-7">
<h1 class="display-6 fw-bold">CertiMine</h1>
<p class="lead text-muted"><?= Util::h(I18n::t('app_tagline')) ?></p>
<p><?= Util::h(I18n::t('lookup_intro')) ?></p>
<a class="btn btn-success me-2" href="<?= Util::h(Util::url('frm-library')) ?>">
<span class="material-symbols-outlined align-middle">menu_book</span> <?= Util::h(I18n::t('nav_frm')) ?>
</a>
<a class="btn btn-outline-secondary" href="<?= Util::h(Util::url('lookup')) ?>">
<span class="material-symbols-outlined align-middle">qr_code_scanner</span> <?= Util::h(I18n::t('nav_lookup')) ?>
</a>
</div>
<div class="col-lg-5">
<div class="card p-4">
<h2 class="h5 mb-3"><span class="material-symbols-outlined align-middle">shield_person</span> Mobiliseme</h2>
<p class="small text-muted mb-0"><?= Util::h(I18n::t('login_title')) ?> — DC3 / competencias vinculadas.</p>
</div>
</div>
</div>
<?php require __DIR__ . '/partials/footer.php'; ?>

35
views/login.php Normal file
View file

@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
use CertiMine\I18n;
use CertiMine\Security;
use CertiMine\Util;
/** @var string|null $err */
require __DIR__ . '/partials/header.php';
?>
<div class="row justify-content-center">
<div class="col-md-5">
<div class="card p-4">
<h1 class="h4 mb-3"><?= Util::h(I18n::t('login_title')) ?></h1>
<?php if ($err): ?><div class="alert alert-danger"><?= Util::h($err) ?></div><?php endif; ?>
<form method="post">
<input type="hidden" name="_csrf" value="<?= Util::h(Security::csrfToken()) ?>">
<div class="mb-3">
<label class="form-label"><?= Util::h(I18n::t('login_user')) ?></label>
<input class="form-control" name="username" required autocomplete="username">
</div>
<div class="mb-3">
<label class="form-label"><?= Util::h(I18n::t('login_pass')) ?></label>
<input type="password" class="form-control" name="password" required autocomplete="current-password">
</div>
<button class="btn btn-success w-100" type="submit"><?= Util::h(I18n::t('login_submit')) ?></button>
</form>
<p class="small text-muted mt-3 mb-0"><?= Util::h(I18n::t('login_passport_hint')) ?></p>
<p class="small text-muted"><?= Util::h(I18n::t('login_demo_hint')) ?></p>
</div>
</div>
</div>
<?php require __DIR__ . '/partials/footer.php'; ?>

36
views/lookup.php Normal file
View file

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
use CertiMine\I18n;
use CertiMine\Security;
use CertiMine\Util;
/** @var string|null $error */
require __DIR__ . '/partials/header.php';
?>
<h1 class="h3 mb-3"><?= Util::h(I18n::t('lookup_title')) ?></h1>
<p class="text-muted"><?= Util::h(I18n::t('lookup_intro')) ?></p>
<?php if ($error): ?>
<div class="alert alert-warning"><?= Util::h($error) ?></div>
<?php endif; ?>
<form method="post" class="card p-4 mb-3" style="max-width:520px">
<input type="hidden" name="_csrf" value="<?= Util::h(Security::csrfToken()) ?>">
<div class="mb-3">
<label class="form-label"><?= Util::h(I18n::t('lookup_type')) ?></label>
<select name="person_type" class="form-select">
<option value="employee"><?= Util::h(I18n::t('lookup_employee')) ?></option>
<option value="contractor"><?= Util::h(I18n::t('lookup_contractor')) ?></option>
</select>
</div>
<div class="mb-3">
<label class="form-label"><?= Util::h(I18n::t('lookup_code')) ?></label>
<input class="form-control" name="code" required placeholder="10001 / C-5001">
</div>
<button class="btn btn-success" type="submit"><?= Util::h(I18n::t('lookup_submit')) ?></button>
</form>
<p class="small text-muted"><?= Util::h(I18n::t('lookup_qr_hint')) ?></p>
<?php require __DIR__ . '/partials/footer.php'; ?>

10
views/partials/footer.php Normal file
View file

@ -0,0 +1,10 @@
</main>
<footer class="border-top py-4 mt-auto bg-white">
<div class="container small text-muted d-flex flex-wrap justify-content-between gap-2">
<span><?= \CertiMine\Util::h(\CertiMine\I18n::t('app_tagline')) ?></span>
<a href="<?= \CertiMine\Util::h(\CertiMine\Util::url('api-docs')) ?>"><?= \CertiMine\Util::h(\CertiMine\I18n::t('footer_docs')) ?></a>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

62
views/partials/header.php Normal file
View file

@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
use CertiMine\I18n;
use CertiMine\Util;
/** @var string $titleKey */
$pageTitle = I18n::t($titleKey);
$lang = I18n::lang();
$other = $lang === 'es' ? 'en' : 'es';
$qs = $_GET;
$qs['lang'] = $other;
$langSwitch = '?' . http_build_query($qs);
?>
<!DOCTYPE html>
<html lang="<?= Util::h($lang) ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= Util::h($pageTitle) ?> — CertiMine</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined" rel="stylesheet">
<style>
:root { --cm-accent:#0d6b58; --cm-accent-2:#0b4f6c; }
.navbar-cert { background: linear-gradient(90deg, var(--cm-accent), var(--cm-accent-2)); }
.navbar-cert .nav-link, .navbar-cert .navbar-brand { color: #f4faf8 !important; }
.navbar-cert .nav-link.active { font-weight: 600; text-decoration: underline; }
body { background:#f6f8f8; }
.card { border:0; box-shadow:0 .35rem 1rem rgba(13,107,88,.08); }
.badge-green { background:#198754; }
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark navbar-cert mb-4">
<div class="container">
<a class="navbar-brand fw-semibold" href="<?= Util::h(Util::url('home')) ?>">
<span class="material-symbols-outlined align-middle">verified_user</span> CertiMine
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#nav">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="nav">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item"><a class="nav-link" href="<?= Util::h(Util::url('home')) ?>"><?= Util::h(I18n::t('nav_home')) ?></a></li>
<li class="nav-item"><a class="nav-link" href="<?= Util::h(Util::url('frm-library')) ?>"><?= Util::h(I18n::t('nav_frm')) ?></a></li>
<li class="nav-item"><a class="nav-link" href="<?= Util::h(Util::url('lookup')) ?>"><?= Util::h(I18n::t('nav_lookup')) ?></a></li>
<?php if (\CertiMine\Auth::user()): ?>
<li class="nav-item"><a class="nav-link" href="<?= Util::h(Util::url('dashboard')) ?>"><?= Util::h(I18n::t('nav_dashboard')) ?></a></li>
<?php endif; ?>
</ul>
<div class="d-flex align-items-center gap-2">
<a class="nav-link" href="<?= Util::h($langSwitch) ?>"><?= $lang === 'es' ? Util::h(I18n::t('lang_en')) : Util::h(I18n::t('lang_es')) ?></a>
<?php if (\CertiMine\Auth::user()): ?>
<a class="btn btn-light btn-sm" href="<?= Util::h(Util::url('logout')) ?>"><?= Util::h(I18n::t('nav_logout')) ?></a>
<?php else: ?>
<a class="btn btn-light btn-sm" href="<?= Util::h(Util::url('login')) ?>"><?= Util::h(I18n::t('nav_login')) ?></a>
<?php endif; ?>
</div>
</div>
</div>
</nav>
<main class="container pb-5">

73
views/profile_public.php Normal file
View file

@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
use CertiMine\I18n;
use CertiMine\Util;
/** @var array<string,mixed> $row */
/** @var list<array<string,mixed>> $certs */
/** @var list<array<string,mixed>> $auths */
/** @var bool $green */
/** @var string $qrUrl */
require __DIR__ . '/partials/header.php';
$isEs = I18n::lang() === 'es';
$ptype = (string) $row['person_type'];
$name = (string) $row['display_name'];
$statusLabel = static function (string $s): string {
return I18n::t('status_' . $s);
};
?>
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
<h1 class="h3 mb-0"><?= Util::h($name) ?></h1>
<?php if ($ptype === 'contractor'): ?>
<span class="badge <?= $green ? 'bg-success' : 'bg-warning text-dark' ?> fs-6">
<span class="material-symbols-outlined align-middle">eco</span>
<?= Util::h(I18n::t('profile_green')) ?>: <?= Util::h($green ? I18n::t('profile_green_yes') : I18n::t('profile_green_no')) ?>
</span>
<?php endif; ?>
</div>
<p class="text-muted mb-2">
<?= $ptype === 'contractor' ? Util::h(I18n::t('lookup_contractor')) : Util::h(I18n::t('lookup_employee')) ?>
· <?= Util::h((string) ($row['employee_number'] ?? '')) ?>
</p>
<div class="mb-4">
<label class="form-label small text-muted">QR / deep link</label>
<input class="form-control form-control-sm" readonly value="<?= Util::h($qrUrl) ?>">
</div>
<h2 class="h5"><?= Util::h(I18n::t('profile_certs')) ?></h2>
<div class="table-responsive card mb-4">
<table class="table mb-0">
<thead><tr><th><?= $isEs ? 'Título' : 'Title' ?></th><th>NOM</th><th><?= Util::h(I18n::t('expires')) ?></th><th><?= $isEs ? 'Estado' : 'Status' ?></th></tr></thead>
<tbody>
<?php foreach ($certs as $c): ?>
<tr>
<td><?= Util::h((string) $c['title']) ?></td>
<td><?= Util::h((string) ($c['nom_code'] ?? '—')) ?></td>
<td><?= Util::h((string) ($c['expires_at'] ?? '—')) ?></td>
<td><span class="badge text-bg-light border"><?= Util::h($statusLabel((string) $c['status'])) ?></span></td>
</tr>
<?php endforeach; ?>
<?php if ($certs === []): ?>
<tr><td colspan="4" class="text-muted"><?= Util::h(I18n::t('no_results')) ?></td></tr>
<?php endif; ?>
</tbody>
</table>
</div>
<?php if ($ptype === 'contractor' && $auths !== []): ?>
<h2 class="h5"><?= Util::h(I18n::t('profile_auths')) ?></h2>
<ul class="list-group mb-4">
<?php foreach ($auths as $a): ?>
<li class="list-group-item d-flex justify-content-between">
<span><?= Util::h((string) $a['code']) ?> — <?= Util::h($isEs ? (string) $a['name_es'] : (string) $a['name_en']) ?></span>
<small class="text-muted"><?= Util::h(I18n::t('expires')) ?>: <?= Util::h((string) ($a['valid_until'] ?? '—')) ?></small>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<?php require __DIR__ . '/partials/footer.php'; ?>