API Peñasquito: ticket persistente, company y mejor flujo de búsqueda

- Renombrado «DC3» a «API Peñasquito» (URL base del documento) en UI/docs;
  rutas y claves de config conservadas por compatibilidad.
- Persistencia de ticket_id en nueva tabla `penasquito_tickets`:
  POST /search/ guarda el ticket y los siguientes requests retoman
  GET /result/<ticket_id>/ sin reencolar.
- Polling acotado por request HTTP (~6 s) con `PenasquitoPendingException`
  y caja «reintentar» en lookup; ticket queda válido 1 h.
- `users_cache.company` nuevo (con migración idempotente); persistResult
  guarda empresa + competencias en transacción y aplica source distinto.
- Mensajes HTTP específicos (400/401/403/404/408/429/5xx) y `/` final
  forzado en rutas (DRF), FOLLOWLOCATION habilitado.
- Vista de perfil muestra «Empresa» y aviso cuando no hay competencias.
- Auth::login evita doble fetch cuando ya tenemos el `result` del API.
- i18n ES/EN actualizados; lookup_pending_*; limpieza de archivos lang.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
remaster 2026-05-13 19:43:37 -06:00
parent 84e94dcb55
commit ff0fd6a89d
22 changed files with 789 additions and 193 deletions

View file

@ -1,6 +1,6 @@
# CertiMine # CertiMine
**Gestión de certificaciones y competencias DC3** para el contexto **Newmont Peñasquito**. **Gestión de certificaciones y competencias** para el contexto **Newmont Peñasquito**.
Portal **bilingüe (ES / EN)**, backend en **PHP** y datos en **MariaDB**. Portal **bilingüe (ES / EN)**, backend en **PHP** y datos en **MariaDB**.
--- ---
@ -10,9 +10,9 @@ Portal **bilingüe (ES / EN)**, backend en **PHP** y datos en **MariaDB**.
| Área | Descripción | | Área | Descripción |
|------|-------------| |------|-------------|
| **Biblioteca FRM** | Listado público de estándares FRM y vínculos con competencias NOM (solo consulta). | | **Biblioteca FRM** | Listado público de estándares FRM y vínculos con competencias NOM (solo consulta). |
| **Consulta rápida** | Búsqueda por número de empleado, ID de contratista o **passport** (p. ej. `E000055821`). Puede leer datos locales o, si está configurado el API DC3, consultar en tiempo real y guardar en base. | | **Consulta rápida** | Búsqueda por número de empleado, ID de contratista o **passport** (p. ej. `E000055821`). Puede leer datos locales o, si está configurado el token del **API en la URL base del documento** (Wotbi), consultar en tiempo real y guardar en base. |
| **Perfil público** | Certificaciones, autorizaciones FRM (contratistas) e indicador de **licencia verde**. Enlace tipo QR con firma opcional (`qr_enforce` en config). | | **Perfil público** | Certificaciones, autorizaciones FRM (contratistas) e indicador de **licencia verde**. Enlace tipo QR con firma opcional (`qr_enforce` en config). |
| **Inicio de sesión** | Con **API DC3**: el usuario introduce su **passport**; el sistema valida contra `penasquito.wotbi.com` y sincroniza competencias. Sin token DC3: modo **mock** para demostración. | | **Inicio de sesión** | Con ese **API** configurado, el usuario introduce su **passport**; el sistema valida contra `penasquito.wotbi.com` y sincroniza competencias. Sin token: modo **mock** para demostración. |
| **Panel (dashboard)** | Certificados del usuario y **cursos sugeridos** según competencias NOM válidas. | | **Panel (dashboard)** | Certificados del usuario y **cursos sugeridos** según competencias NOM válidas. |
| **Webhook** | `POST` para sincronizar certificados / autorizaciones desde otros sistemas (eventos idempotentes). | | **Webhook** | `POST` para sincronizar certificados / autorizaciones desde otros sistemas (eventos idempotentes). |
@ -30,15 +30,15 @@ flowchart LR
DB[(MariaDB)] DB[(MariaDB)]
end end
subgraph ext [Servicios] subgraph ext [Servicios]
DC3[API DC3 Wotbi] PQ[API Peñasquito (documento / Wotbi)]
end end
U --> P U --> P
P --> DB P --> DB
P --> DC3 P --> PQ
``` ```
1. **Sin token DC3:** los formularios usan datos de **semilla SQL** y **mock** de login. 1. **Sin token del API (documento):** los formularios usan datos de **semilla SQL** y **mock** de login.
2. **Con `CERTIMINE_DC3_TOKEN`:** búsqueda y login usan el API REST (token estático `Authorization: Token …`, búsqueda por passport y *polling* de tickets si aplica). 2. **Con `CERTIMINE_PENASQUITO_TOKEN` (o alias `CERTIMINE_DC3_TOKEN`):** búsqueda y login usan el API REST (token estático `Authorization: Token …`, búsqueda por passport y *polling* de tickets si aplica).
3. Los resultados se pueden **persistir** en tablas `users_cache`, `certificates`, `contractor_authorizations`. 3. Los resultados se pueden **persistir** en tablas `users_cache`, `certificates`, `contractor_authorizations`.
--- ---
@ -72,10 +72,11 @@ Edita `config/config.php`:
- **`db`**: host, nombre de base, usuario y contraseña. - **`db`**: host, nombre de base, usuario y contraseña.
- **`app.public_url`**: URL pública del sitio (para enlaces y QR). - **`app.public_url`**: URL pública del sitio (para enlaces y QR).
- **API DC3 — token (orden):** - **Token del API (URL base del documento) — orden:**
1) `CERTIMINE_DC3_TOKEN` 1) `CERTIMINE_PENASQUITO_TOKEN`
2) `penasquito_dc3.static_token` en `config.php` 2) `CERTIMINE_DC3_TOKEN` (alias)
3) **`config/token.php`** (copia de `config/token.example.php`; **no se sube a git**). 3) `penasquito_dc3.static_token` en `config.php` (sección que agrupa también `base_url` y rutas del PDF)
4) **`config/token.php`** (copia de `config/token.example.php`; **no se sube a git**).
Documentación del proceso sin secretos: **`docs/DatosPdf.example.txt`**. Tu copia local **`DatosPdf.txt`** puede quedar fuera de git (véase `.gitignore`). Documentación del proceso sin secretos: **`docs/DatosPdf.example.txt`**. Tu copia local **`DatosPdf.txt`** puede quedar fuera de git (véase `.gitignore`).
- **`mobiliseme.mock`:** `true` para demo sin API legacy JWT; `false` solo si usas otro backend configurado en `mobiliseme`. - **`mobiliseme.mock`:** `true` para demo sin API legacy JWT; `false` solo si usas otro backend configurado en `mobiliseme`.
@ -124,7 +125,7 @@ Todas pasan por `public/index.php` con el parámetro **`r`**:
``` ```
certimine/ certimine/
├── public/ # Web pública (index.php, webhook, .htaccess) ├── public/ # Web pública (index.php, webhook, .htaccess)
├── src/ # PHP (Auth, repositorios, cliente DC3, etc.) ├── src/ # PHP (Auth, repositorios, cliente API Peñasquito, etc.)
├── views/ # Plantillas HTML + Bootstrap 5 ├── views/ # Plantillas HTML + Bootstrap 5
├── lang/ # Cadenas ES / EN ├── lang/ # Cadenas ES / EN
├── config/ # config.example.php (plantilla); config.php local ignorado por git) ├── config/ # config.example.php (plantilla); config.php local ignorado por git)

View file

@ -1,8 +1,11 @@
<?php <?php
/** /**
* Copiar a config.php y ajustar. config.php está en .gitignore. * Plantilla: copiar a **config.php** (config.php está en .gitignore).
* *
* Token DC3: ver orden en PenasquitoDc3Api::resolvedToken() (env → config → config/token.php). * Token del API en la **URL base del documento** (p. ej. penasquito.wotbi.com). La clave de array
* `penasquito_dc3` es histórica: las rutas remotas llevan `/api/v1/dc3/...` según ese documento.
*
* Orden del token: CERTIMINE_PENASQUITO_TOKEN → CERTIMINE_DC3_TOKEN (alias) → static_token en config.php → config/token.php.
*/ */
return [ return [
'app' => [ 'app' => [
@ -30,8 +33,7 @@ return [
'cookie_samesite' => 'Lax', 'cookie_samesite' => 'Lax',
], ],
/** /**
* API REST expuesto por el backend Peñasquito (Wotbi): competencias DC3 por passport. * API REST en la URL base del PDF (Wotbi): búsqueda por passport. Rutas = las del documento.
* Origen: DatosPdf.txt / documentación de scraping Mobilise-Me.
*/ */
'penasquito_dc3' => [ 'penasquito_dc3' => [
'base_url' => 'https://penasquito.wotbi.com', 'base_url' => 'https://penasquito.wotbi.com',
@ -41,12 +43,18 @@ return [
'status_path' => '/api/v1/dc3/competencies/passports/status/', 'status_path' => '/api/v1/dc3/competencies/passports/status/',
'authorization_header' => 'Authorization', 'authorization_header' => 'Authorization',
'authorization_scheme' => 'Token ', 'authorization_scheme' => 'Token ',
/**
* Doc §1.6: polling al GET /result/ cada ~2 s (típico 5–15 s sin caché).
* Aquí se hace polling acotado por request HTTP (≈6 s) para no agotar el max_execution_time
* del web; el ticket_id se persiste en penasquito_tickets y el siguiente request retoma
* el GET /result/<ticket_id>/ sin volver a encolar. Para tareas CLI/cron sube max_attempts.
*/
'poll_interval_seconds' => 2, 'poll_interval_seconds' => 2,
'poll_max_attempts' => 20, 'poll_max_attempts' => 3,
'timeout_seconds' => 45, 'timeout_seconds' => 30,
], ],
/** /**
* Modo legacy (JSON login + JWT) si NO usas penasquito_dc3.static_token / CERTIMINE_DC3_TOKEN. * Modo legacy (JSON login + JWT) si no usa token del API Peñasquito (documento).
*/ */
'mobiliseme' => [ 'mobiliseme' => [
'base_url' => 'https://api.mobiliseme.example', 'base_url' => 'https://api.mobiliseme.example',

View file

@ -1,13 +1,14 @@
<?php <?php
/** /**
* Secreto local del API DC3 — NO versionar. * Secreto local del API Peñasquito (URL base del documento) — NO versionar.
* *
* Instalación: * Instalación:
* cp config/token.example.php config/token.php * cp config/token.example.php config/token.php
* Edite dc3_token con el valor real (o deje vacío y use CERTIMINE_DC3_TOKEN). * Rellene penasquito_token (o dc3_token por compatibilidad), o use variables de entorno.
*/ */
declare(strict_types=1); declare(strict_types=1);
return [ return [
'penasquito_token' => '',
'dc3_token' => '', 'dc3_token' => '',
]; ];

View file

@ -13,7 +13,7 @@ APIs.
1.1 Autenticación 1.1 Autenticación
Todas las peticiones requieren un header de autorización con un token estático que se entrega Todas las peticiones requieren un header de autorización con un token estático que se entrega
aparte por canal privado: aparte por canal privado:
TOKEN <defina en config/token.php o CERTIMINE_DC3_TOKEN> TOKEN <defina en config/token.php, CERTIMINE_PENASQUITO_TOKEN o CERTIMINE_DC3_TOKEN (alias)>
Authorization: Token <token> Authorization: Token <token>
Las peticiones sin este header o con un token inválido son rechazadas con HTTP 401. 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 1.2 Endpoint 1 — Crear solicitud de búsqueda

View file

@ -1,71 +1,162 @@
# API DC3 Peñasquito (Wotbi) — CertiMine # API REST Peñasquito (Wotbi) — tres endpoints principales — CertiMine
Fuente detallada del flujo: copia de trabajo sin secretos en [DatosPdf.example.txt](DatosPdf.example.txt). El archivo local **DatosPdf.txt** (si lo tienes) está en `.gitignore` y no debe contener el token en repositorios compartidos; use **`config/token.php`** o **`CERTIMINE_DC3_TOKEN`**. Este documento refleja el contrato descrito en el PDF de proceso (p. ej. `DatosPdf.txt` / `docs/DatosPdf.example.txt`). CertiMine consume **solo** estos tres endpoints sobre la URL base; el scraping de Mobilise-Me ocurre **en el servidor Wotbi**, no en el navegador del usuario.
## Autenticación **No versionar tokens.** Usar `CERTIMINE_PENASQUITO_TOKEN`, `config.php` (`penasquito_dc3.static_token`) o `config/token.php`.
Todas las peticiones al API REST llevan un **token estático** entregado por canal privado: ---
## 1.1 Autenticación
Todas las peticiones requieren un header de autorización con un **token estático** entregado por canal privado:
```http ```http
Authorization: Token <token> Authorization: Token <token>
``` ```
Sin cabecera válida → **HTTP 401**. Petición sin header o con token inválido → **HTTP 401**.
En CertiMine el token se resuelve en este **orden**: En CertiMine el valor se resuelve en este orden: `CERTIMINE_PENASQUITO_TOKEN` → `CERTIMINE_DC3_TOKEN` (alias) → `penasquito_dc3.static_token` → `config/token.php`.
1. Variable de entorno **`CERTIMINE_DC3_TOKEN`** (recomendado en producción). ---
2. **`penasquito_dc3.static_token`** en `config/config.php`.
3. Archivo local **`config/token.php`** (copiar de `config/token.example.php`; está en **`.gitignore`**).
No leer el token desde documentación versionada. El ejemplo público del texto del PDF está en **`docs/DatosPdf.example.txt`** (línea del token redactada). ## 1.2 Endpoint 1 — Crear solicitud de búsqueda
## Base URL ```http
POST https://penasquito.wotbi.com/api/v1/dc3/competencies/passports/search/
Content-Type: application/json
Authorization: Token <token>
```
`https://penasquito.wotbi.com` (según la documentación en `docs/DatosPdf.example.txt`). **Cuerpo:**
## Endpoint 1 — Crear solicitud de búsqueda ```json
{ "passport": "E000055821" }
```
`POST /api/v1/dc3/competencies/passports/search/` **Comportamiento:** La API valida el passport, **encola** la tarea de scraping y responde de inmediato con un **ticket**. El scraping corre en segundo plano.
- `Content-Type: application/json` ### Respuesta estándar encolada
- 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) ```json
{
"status": "pending",
"ticket_id": "2cf364bebf16",
"posicion": 1
}
```
`GET /api/v1/dc3/competencies/passports/result/<ticket_id>/` El cliente debe **guardar `ticket_id`** y consultar el endpoint 1.3 hasta que termine el trabajo.
- Mientras trabaja el worker: `status` puede ser `pending` o `processing`. ### Respuesta con caché (última hora, mismo passport)
- Al terminar: `status: "completed"` + `result`.
Flujo recomendado: llamar endpoint 1; si `pending`, consultar endpoint 2 cada pocos segundos hasta `completed` (implementado en `PenasquitoDc3Api::fetchResultForPassport`). Si ya se consultó ese passport en la ventana de caché (~1 h), la API devuelve **directamente** el resultado **sin encolar**:
## Endpoint 3 — Estado de cola ```json
{
"status": "completed",
"result": {
"passport": "E000055821",
"name": "…",
"company": "…",
"competencies": [
{
"activity": "FRM - CONFINED SPACES",
"request_date": "30/07/2025",
"expiration_date": null,
"status": "Received"
}
],
"error": null
}
}
```
`GET /api/v1/dc3/competencies/passports/status/` **Recomendación:** siempre llamar primero a este endpoint; si `status === "completed"` usar `result`; si `status === "pending"` hacer *polling* en 1.3.
- `queue_length`, `processing` — monitoreo / health. ---
## Estructura de `result` ## 1.3 Endpoint 2 — Estado y resultado del ticket
| Campo | Uso | ```http
|--------|-----| GET https://penasquito.wotbi.com/api/v1/dc3/competencies/passports/result/<ticket_id>/
| `passport` | ID consultado (coincide con búsqueda). | Authorization: Token <token>
| `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) **Comportamiento:** Devuelve el estado del ticket. Mientras el worker no termina, `status` puede ser **`pending`** o **`processing`**. Al terminar, `status` es **`completed`** y viene el objeto **`result`**.
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. ### Ejemplo completado
## Webhook CertiMine ```json
{
"status": "completed",
"result": {
"passport": "E000055821",
"name": "…",
"company": "…",
"competencies": [ … ],
"error": null
}
}
```
CertiMine sigue aceptando `POST public/api/webhook.php` para sincronizar certificados desde otros sistemas (ver implementación). Es independiente del API Wotbi anterior. ### Estructura de `result`
## Configuración PHP | Campo | Descripción |
|--------|-------------|
| `passport` | Passport consultado. |
| `name` | Nombre (extraído del portal por el backend). |
| `company` | Empresa. |
| `competencies` | Lista de ítems con `activity`, `request_date`, `expiration_date` (puede ser `null`), `status`. |
| `error` | `null` si todo bien; si hubo fallo (sesión, passport no encontrado, etc.) trae mensaje y `competencies` puede ir vacío. CertiMine rechaza estos casos vía excepción para mostrar el mensaje al usuario. |
Rutas y tiempos de polling: `config/config.example.php` → sección `penasquito_dc3`. ---
## 1.4 Endpoint 3 — Estado de la cola
```http
GET https://penasquito.wotbi.com/api/v1/dc3/competencies/passports/status/
Authorization: Token <token>
```
**Monitoreo / health:** estado de la cola (p. ej. Redis) y si el worker está ocupado.
```json
{
"queue_length": 0,
"processing": false
}
```
| Campo | Significado |
|--------|-------------|
| `queue_length` | Tickets esperando procesamiento. |
| `processing` | `true` si el worker está ejecutando un scraping ahora. |
En PHP: `PenasquitoDc3Api::queueStatus()`.
---
## 1.5 Caché de resultados (lado servidor)
Los resultados exitosos se guardan en caché **~1 hora** por passport. Durante ese tiempo, una nueva solicitud del mismo passport responde al instante con datos cacheados y **no encola** trabajo nuevo.
---
## 1.6 Flujo recomendado del cliente
1. **POST** `/search/` con el passport.
2. Si `status === "completed"` → usar `result`.
3. Si `status === "pending"` → guardar `ticket_id` y hacer **GET** `/result/<ticket_id>/` cada **~2 s** hasta `status === "completed"`.
4. Presentar `result.competencies` (y demás campos según la UI).
Tiempo típico sin caché: **unos 5–15 s**, según carga del portal externo. Por eso en `config.example.php` se configuran `poll_interval_seconds` y `poll_max_attempts` con margen.
**Implementación en CertiMine:** `PenasquitoDc3Api::fetchResultForPassport()` (búsqueda + *polling*).
---
## Otros
- **Webhook CertiMine** (`public/api/webhook.php`): distinto; sincronización desde otros sistemas.
- **Configuración PHP:** `config/config.example.php` → bloque `penasquito_dc3` (`base_url`, rutas, timeout, intervalos de *polling*).

View file

@ -12,6 +12,7 @@ return [
'lang_en' => 'English', 'lang_en' => 'English',
'lang_es' => 'Spanish', 'lang_es' => 'Spanish',
'app_tagline' => 'Certification management — Penasquito', 'app_tagline' => 'Certification management — Penasquito',
'home_mobiliseme_blurb' => 'Sign-in — passport lookup against the Penasquito base API (project docs / Wotbi) and linked competencies.',
'frm_title' => 'Public FRM standards library', 'frm_title' => 'Public FRM standards library',
'frm_intro' => 'Read-only references, verifications, and permissions. Links to corporate documentation where applicable.', 'frm_intro' => 'Read-only references, verifications, and permissions. Links to corporate documentation where applicable.',
'frm_nom_related' => 'Related NOM competencies', 'frm_nom_related' => 'Related NOM competencies',
@ -26,8 +27,10 @@ return [
'profile_green' => 'Green license', 'profile_green' => 'Green license',
'profile_green_yes' => 'Critical authorizations valid', 'profile_green_yes' => 'Critical authorizations valid',
'profile_green_no' => 'Requirements pending', 'profile_green_no' => 'Requirements pending',
'profile_certs' => 'Certifications / DC3', 'profile_certs' => 'Certifications',
'profile_auths' => 'FRM authorizations', 'profile_auths' => 'FRM authorizations',
'profile_company' => 'Company',
'profile_no_competencies' => 'No competencies on record at the moment.',
'status_valid' => 'Valid', 'status_valid' => 'Valid',
'status_expiring' => 'Expiring soon', 'status_expiring' => 'Expiring soon',
'status_expired' => 'Expired', 'status_expired' => 'Expired',
@ -50,16 +53,23 @@ return [
'issued' => 'Issued', 'issued' => 'Issued',
'sync_title' => 'Synchronization', 'sync_title' => 'Synchronization',
'webhook_ok' => 'Event received', 'webhook_ok' => 'Event received',
'lookup_need_dc3' => 'No local record for that code. To query by passport (e.g. E000055821), configure the DC3 API token (CERTIMINE_DC3_TOKEN or config.php).', 'lookup_need_dc3' => 'No local record for that code. To query by passport (e.g. E000055821), set the token for the Penasquito base API from the project docs (CERTIMINE_PENASQUITO_TOKEN or config.php).',
'lookup_need_dc3_title' => 'DC3 API not configured', 'lookup_need_dc3_title' => 'Penasquito API (per docs) not configured',
'lookup_need_dc3_body' => 'Without a token, only local DB lookup works (demo numbers like 10001 or C-5001). Set the token via CERTIMINE_DC3_TOKEN, or penasquito_dc3.static_token in config.php, or copy config/token.example.php to config/token.php and set dc3_token (token.php is gitignored).', 'lookup_need_dc3_body' => 'Without a token, only local DB lookup works (demo numbers like 10001 or C-5001). Recommended order: CERTIMINE_PENASQUITO_TOKEN (or alias CERTIMINE_DC3_TOKEN), then penasquito_dc3.static_token in config.php, then config/token.php with penasquito_token or dc3_token (gitignored). Config key penasquito_dc3 holds the base URL and paths as in the PDF.',
'lookup_using_example_config' => 'Currently loading config.example.php (config/config.php is missing): example token is empty. You may use config/token.php (see token.example.php).', 'lookup_using_example_config' => 'Currently loading config.example.php (config/config.php is missing): example token is empty. You may use config/token.php (see token.example.php).',
'lookup_dc3_ready' => 'DC3 API enabled: passport lookups will call the service and store results locally.', 'lookup_dc3_ready' => 'Passport lookup enabled: the configured base URL will be queried and results stored locally.',
'lookup_token_env' => 'Token from CERTIMINE_DC3_TOKEN.', 'lookup_token_env' => 'Token from environment (CERTIMINE_PENASQUITO_TOKEN or CERTIMINE_DC3_TOKEN).',
'lookup_token_config' => 'Token from config.php.', 'lookup_token_config' => 'Token from config.php.',
'lookup_debug_hint' => 'Debug mode: API errors may include details on screen. Set app.debug=true or CERTIMINE_DEBUG=1.', 'lookup_debug_hint' => 'Debug mode: API errors may include details on screen. Set app.debug=true or CERTIMINE_DEBUG=1.',
'lookup_passport_hint' => 'Passports like E000055821 are normalized (case). Local DB is tried first; if no match and the API is configured, Wotbi is queried.', 'lookup_passport_hint' => 'Passports like E000055821 are normalized (case). Local DB is tried first; if no match and the API is configured, the document base URL is queried.',
'dc3_lookup_error' => 'Could not load data from the DC3 API. Check passport, token, and network. Enable debug mode for technical details.', 'penasquito_api_lookup_error' => 'Could not load data from the Penasquito API (document base URL). Check passport, token, and network. If the service returned details, they appear below. (Debug mode: more internal errors.)',
'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.', 'lookup_pending_title' => 'The portal is processing your search',
'login_demo_hint' => 'Without DC3 API: username containing «contract» simulates contractor; otherwise demo employee.', 'lookup_pending_body' => 'The Mobilise-Me server already received the request and is scraping the competencies. Wait a few seconds and use the button to retry; nothing is re-queued, only the stored ticket is polled.',
'lookup_pending_passport' => 'Passport',
'lookup_pending_ticket' => 'Ticket',
'lookup_pending_status' => 'Status',
'lookup_pending_position' => 'Queue position',
'lookup_pending_retry' => 'Retry lookup',
'login_passport_hint' => 'With the API configured (CERTIMINE_PENASQUITO_TOKEN or other), use your passport (e.g. E000055821). Password is unused. Without token: demo user with «contract» or employee.',
'login_demo_hint' => 'Without the document API: username containing «contract» simulates contractor; otherwise demo employee.',
]; ];

View file

@ -12,6 +12,7 @@ return [
'lang_en' => 'English', 'lang_en' => 'English',
'lang_es' => 'Español', 'lang_es' => 'Español',
'app_tagline' => 'Gestión de certificaciones — Penasquito', 'app_tagline' => 'Gestión de certificaciones — Penasquito',
'home_mobiliseme_blurb' => 'Acceso — consulta por passport al API en la URL base del documento (Wotbi) y competencias vinculadas.',
'frm_title' => 'Biblioteca pública de estándares FRM', '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_intro' => 'Consulta de referencias, verificaciones y permisos en modo lectura. Enlaces a documentación corporativa cuando aplique.',
'frm_nom_related' => 'Competencias NOM relacionadas', 'frm_nom_related' => 'Competencias NOM relacionadas',
@ -26,8 +27,10 @@ return [
'profile_green' => 'Licencia verde', 'profile_green' => 'Licencia verde',
'profile_green_yes' => 'Autorizaciones críticas vigentes', 'profile_green_yes' => 'Autorizaciones críticas vigentes',
'profile_green_no' => 'Pendiente de requisitos', 'profile_green_no' => 'Pendiente de requisitos',
'profile_certs' => 'Certificaciones / DC3', 'profile_certs' => 'Certificaciones',
'profile_auths' => 'Autorizaciones FRM', 'profile_auths' => 'Autorizaciones FRM',
'profile_company' => 'Empresa',
'profile_no_competencies' => 'Sin competencias registradas en este momento.',
'status_valid' => 'Vigente', 'status_valid' => 'Vigente',
'status_expiring' => 'Por vencer', 'status_expiring' => 'Por vencer',
'status_expired' => 'Vencido', 'status_expired' => 'Vencido',
@ -50,16 +53,23 @@ return [
'issued' => 'Emitido', 'issued' => 'Emitido',
'sync_title' => 'Sincronización', 'sync_title' => 'Sincronización',
'webhook_ok' => 'Evento recibido', 'webhook_ok' => 'Evento recibido',
'lookup_need_dc3' => 'No hay registro local con ese código. Para consultar por passport (p. ej. E000055821) hace falta configurar el token del API DC3 (CERTIMINE_DC3_TOKEN o config.php).', 'lookup_need_dc3' => 'No hay registro local con ese código. Para consultar por passport (p. ej. E000055821) configure el token del API en la URL base del documento (variable CERTIMINE_PENASQUITO_TOKEN o config.php).',
'lookup_need_dc3_title' => 'API DC3 no configurada', 'lookup_need_dc3_title' => 'API Peñasquito (documento) no configurado',
'lookup_need_dc3_body' => 'Sin token de acceso, solo se puede buscar en la base de datos local (números demo como 10001 o C-5001). Configure el token en este orden: variable CERTIMINE_DC3_TOKEN, o penasquito_dc3.static_token en config.php, o copie config/token.example.php a config/token.php y rellene dc3_token (token.php no se sube a git).', 'lookup_need_dc3_body' => 'Sin token, solo se busca en la base de datos local (números demo como 10001 o C-5001). Orden recomendado: CERTIMINE_PENASQUITO_TOKEN (o alias CERTIMINE_DC3_TOKEN), luego penasquito_dc3.static_token en config.php, luego config/token.php con penasquito_token o dc3_token (gitignored). La clave penasquito_dc3 en config agrupa la URL base y rutas tal como en el PDF.',
'lookup_using_example_config' => 'Ahora mismo está cargando config.example.php (no existe config/config.php): el token del ejemplo está vacío. Puede usar config/token.php (véase token.example.php).', 'lookup_using_example_config' => 'Ahora mismo está cargando config.example.php (no existe config/config.php): el token del ejemplo está vacío. Puede usar config/token.php (véase token.example.php).',
'lookup_dc3_ready' => 'API DC3 activo: las búsquedas por passport consultarán el servicio y guardarán el resultado aquí.', 'lookup_dc3_ready' => 'Consulta por passport activa: se usará el servicio en la URL base configurada y se guardará el resultado aquí.',
'lookup_token_env' => 'Token vía variable de entorno CERTIMINE_DC3_TOKEN.', 'lookup_token_env' => 'Token vía variable de entorno (CERTIMINE_PENASQUITO_TOKEN o CERTIMINE_DC3_TOKEN).',
'lookup_token_config' => 'Token definido en config.php.', 'lookup_token_config' => 'Token definido en config.php.',
'lookup_debug_hint' => 'Modo debug: los errores del API pueden mostrarse en pantalla. active app.debug=true o CERTIMINE_DEBUG=1.', 'lookup_debug_hint' => 'Modo debug: los errores del API pueden mostrarse en pantalla. active app.debug=true o CERTIMINE_DEBUG=1.',
'lookup_passport_hint' => 'Passport tipo E000055821: puede escribirse en minúsculas; se normaliza. Primero se busca en BD local; si no hay coincidencia y el API está configurado, se consulta Wotbi.', 'lookup_passport_hint' => 'Passport tipo E000055821: puede escribirse en minúsculas; se normaliza. Primero se busca en BD local; si no hay coincidencia y el API está configurado, se consulta la URL base del documento.',
'dc3_lookup_error' => 'No se pudieron obtener datos del API DC3. Revise el passport, el token y la red. Active el modo debug para ver el detalle técnico.', 'penasquito_api_lookup_error' => 'No se pudieron obtener datos del API Peñasquito (URL base del documento). Revise el passport, el token y la red. Si el servicio devolvió detalle, aparece debajo. (Modo debug: errores internos adicionales.)',
'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.', 'lookup_pending_title' => 'El portal está procesando su búsqueda',
'login_demo_hint' => 'Sin API DC3: si el usuario contiene «contract», se simula contratista; si no, empleado demo.', 'lookup_pending_body' => 'El servidor Mobilise-Me ya recibió la solicitud y está extrayendo las competencias. Espere unos segundos y use el botón para reintentar; ya no se vuelve a encolar, solo se consulta el ticket guardado.',
'lookup_pending_passport' => 'Passport',
'lookup_pending_ticket' => 'Ticket',
'lookup_pending_status' => 'Estado',
'lookup_pending_position' => 'Posición en la cola',
'lookup_pending_retry' => 'Reintentar consulta',
'login_passport_hint' => 'Con el API configurado (CERTIMINE_PENASQUITO_TOKEN u otro medio), 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 del documento: si el usuario contiene «contract», se simula contratista; si no, empleado demo.',
]; ];

View file

@ -7,6 +7,7 @@ use CertiMine\Config;
use CertiMine\I18n; use CertiMine\I18n;
use CertiMine\MobilisemeClient; use CertiMine\MobilisemeClient;
use CertiMine\PenasquitoDc3Api; use CertiMine\PenasquitoDc3Api;
use CertiMine\PenasquitoPendingException;
use CertiMine\PersonRepository; use CertiMine\PersonRepository;
use CertiMine\Security; use CertiMine\Security;
use CertiMine\Util; use CertiMine\Util;
@ -38,12 +39,19 @@ try {
case 'lookup': case 'lookup':
$error = null; $error = null;
/** @var string|null */
$lookupErrorDetail = null;
/** @var array{passport:string,ticket_id:string,status:string,posicion:?int}|null */
$lookupPending = null;
$result = null; $result = null;
$lookupDc3Ok = PenasquitoDc3Api::isConfigured(); $penasquitoApiOk = PenasquitoDc3Api::isConfigured();
$envTok = getenv('CERTIMINE_PENASQUITO_TOKEN');
if (!is_string($envTok) || trim($envTok) === '') {
$envTok = getenv('CERTIMINE_DC3_TOKEN'); $envTok = getenv('CERTIMINE_DC3_TOKEN');
$lookupDc3Env = is_string($envTok) && $envTok !== ''; }
$penasquitoApiTokenFromEnv = is_string($envTok) && trim($envTok) !== '';
$lookupUsingExample = !Config::loadedFromLocalFile(); $lookupUsingExample = !Config::loadedFromLocalFile();
$lookupDc3Base = (string) (Config::get('penasquito_dc3', 'base_url') ?? ''); $penasquitoApiBaseUrl = (string) (Config::get('penasquito_dc3', 'base_url') ?? '');
if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!Security::verifyCsrf($_POST['_csrf'] ?? null)) { if (!Security::verifyCsrf($_POST['_csrf'] ?? null)) {
$error = I18n::t('csrf_invalid'); $error = I18n::t('csrf_invalid');
@ -82,7 +90,7 @@ try {
$ptype = $type === 'contractor' || $isContractor ? 'contractor' : 'employee'; $ptype = $type === 'contractor' || $isContractor ? 'contractor' : 'employee';
$pid = (string) ($apiRes['passport'] ?? $code); $pid = (string) ($apiRes['passport'] ?? $code);
PenasquitoDc3Api::persistResult($pid, $apiRes, $ptype); PenasquitoDc3Api::persistResult($pid, $apiRes, $ptype);
PersonRepository::logAudit('lookup_dc3_api', $ptype, $code); PersonRepository::logAudit('lookup_penasquito_api', $ptype, $code);
$ecode = (string) ($apiRes['passport'] ?? $code); $ecode = (string) ($apiRes['passport'] ?? $code);
$sig = Security::qrSignature($ptype, $ecode); $sig = Security::qrSignature($ptype, $ecode);
header( header(
@ -92,10 +100,19 @@ try {
]) ])
); );
exit; exit;
} catch (PenasquitoPendingException $pex) {
$lookupPending = [
'passport' => $pex->passport,
'ticket_id' => $pex->ticketId,
'status' => $pex->remoteStatus,
'posicion' => $pex->posicion,
];
} catch (Throwable $ex) { } catch (Throwable $ex) {
$error = I18n::t('dc3_lookup_error'); $error = I18n::t('penasquito_api_lookup_error');
if (Config::debugMode()) { if ($ex instanceof \RuntimeException) {
$error .= ' — ' . $ex->getMessage(); $lookupErrorDetail = $ex->getMessage();
} elseif (Config::debugMode()) {
$lookupErrorDetail = $ex->getMessage();
} }
} }
} else { } else {

View file

@ -0,0 +1,14 @@
-- Migración idempotente: tabla penasquito_tickets (persiste ticket_id por passport).
-- mysql -u root -p certimine < sql/migrations/2026-05-13-penasquito-tickets.sql
CREATE TABLE IF NOT EXISTS penasquito_tickets (
passport VARCHAR(64) NOT NULL PRIMARY KEY,
ticket_id VARCHAR(128) NOT NULL,
status VARCHAR(32) NOT NULL DEFAULT 'pending',
posicion INT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_polled_at DATETIME NULL,
last_error VARCHAR(255) NULL,
KEY idx_pt_status (status),
KEY idx_pt_ticket (ticket_id)
) ENGINE=InnoDB;

View file

@ -0,0 +1,18 @@
-- Migración idempotente: añade `company` a users_cache.
-- Aplicar manualmente en bases existentes:
-- mysql -u root -p certimine < sql/migrations/2026-05-13-users-cache-company.sql
SET @col_exists := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'users_cache'
AND COLUMN_NAME = 'company'
);
SET @stmt := IF(
@col_exists = 0,
'ALTER TABLE users_cache ADD COLUMN company VARCHAR(255) NULL AFTER display_name',
'SELECT 1'
);
PREPARE s FROM @stmt;
EXECUTE s;
DEALLOCATE PREPARE s;

View file

@ -12,6 +12,7 @@ DROP TABLE IF EXISTS certificates;
DROP TABLE IF EXISTS contractor_authorizations; DROP TABLE IF EXISTS contractor_authorizations;
DROP TABLE IF EXISTS frm_nom_map; DROP TABLE IF EXISTS frm_nom_map;
DROP TABLE IF EXISTS public_documents; DROP TABLE IF EXISTS public_documents;
DROP TABLE IF EXISTS penasquito_tickets;
DROP TABLE IF EXISTS users_cache; DROP TABLE IF EXISTS users_cache;
DROP TABLE IF EXISTS nom_competency; DROP TABLE IF EXISTS nom_competency;
DROP TABLE IF EXISTS frm_standard; DROP TABLE IF EXISTS frm_standard;
@ -57,12 +58,27 @@ CREATE TABLE users_cache (
mobiliseme_id VARCHAR(64) NOT NULL PRIMARY KEY, mobiliseme_id VARCHAR(64) NOT NULL PRIMARY KEY,
employee_number VARCHAR(64) NULL, employee_number VARCHAR(64) NULL,
display_name VARCHAR(255) NOT NULL, display_name VARCHAR(255) NOT NULL,
company VARCHAR(255) NULL,
person_type ENUM('employee','contractor') NOT NULL DEFAULT 'employee', person_type ENUM('employee','contractor') NOT NULL DEFAULT 'employee',
green_license_flag TINYINT(1) NOT NULL DEFAULT 0, green_license_flag TINYINT(1) NOT NULL DEFAULT 0,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY idx_employee_number (employee_number) KEY idx_employee_number (employee_number)
) ENGINE=InnoDB; ) ENGINE=InnoDB;
-- Tickets pendientes del API Peñasquito (POST /search/ → GET /result/<ticket_id>/).
-- Permite reanudar el polling entre requests HTTP sin tener que reencolar.
CREATE TABLE penasquito_tickets (
passport VARCHAR(64) NOT NULL PRIMARY KEY,
ticket_id VARCHAR(128) NOT NULL,
status VARCHAR(32) NOT NULL DEFAULT 'pending',
posicion INT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_polled_at DATETIME NULL,
last_error VARCHAR(255) NULL,
KEY idx_pt_status (status),
KEY idx_pt_ticket (ticket_id)
) ENGINE=InnoDB;
CREATE TABLE certificates ( CREATE TABLE certificates (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
mobiliseme_id VARCHAR(64) NOT NULL, mobiliseme_id VARCHAR(64) NOT NULL,

View file

@ -70,7 +70,7 @@ INSERT INTO users_cache (mobiliseme_id, employee_number, display_name, person_ty
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); 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) 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) SELECT 'demo-employee-1', n.id, f.id, CONCAT('Demo ', n.code), DATE_SUB(CURDATE(), INTERVAL 30 DAY), DATE_ADD(CURDATE(), INTERVAL 335 DAY), 'valid', CONCAT('EXT-', n.code)
FROM nom_competency n FROM nom_competency n
LEFT JOIN frm_standard f ON f.code = 'FRM_ALTURAS' LEFT JOIN frm_standard f ON f.code = 'FRM_ALTURAS'
WHERE n.code IN ('NOM-009','NOM-017'); WHERE n.code IN ('NOM-009','NOM-017');
@ -80,5 +80,5 @@ SELECT 'demo-contractor-1', id, DATE_ADD(CURDATE(), INTERVAL 180 DAY), 'seed'
FROM frm_standard WHERE code IN ('FRM_ALTURAS','FRM_CONFINED'); 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) 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) SELECT 'demo-contractor-1', n.id, NULL, CONCAT('Demo ', n.code), CURDATE(), DATE_ADD(CURDATE(), INTERVAL 300 DAY), 'valid', CONCAT('demo-C-', n.code)
FROM nom_competency n WHERE n.code IN ('NOM-009','NOM-001'); FROM nom_competency n WHERE n.code IN ('NOM-009','NOM-001');

View file

@ -28,7 +28,7 @@ final class Auth
/** /**
* @param array<string,mixed> $profile * @param array<string,mixed> $profile
* @param array<string,mixed>|null $dc3Result resultado completo del API DC3 (evita segunda llamada) * @param array<string,mixed>|null $dc3Result payload completo del API Peñasquito (documento); evita segunda llamada
*/ */
public static function login(array $profile, string $token, ?array $dc3Result = null): void public static function login(array $profile, string $token, ?array $dc3Result = null): void
{ {
@ -45,6 +45,11 @@ final class Auth
$type = (string) (Util::arrayPath($profile, $typePath) ?? 'employee'); $type = (string) (Util::arrayPath($profile, $typePath) ?? 'employee');
$emp = Util::arrayPath($profile, $empPath); $emp = Util::arrayPath($profile, $empPath);
$empStr = $emp !== null ? (string) $emp : null; $empStr = $emp !== null ? (string) $emp : null;
$companyRaw = $profile['company'] ?? ($dc3Result['company'] ?? null);
$company = is_string($companyRaw) ? trim($companyRaw) : null;
if ($company === '') {
$company = null;
}
if ($id === '') { if ($id === '') {
throw new \RuntimeException('Profile id missing'); throw new \RuntimeException('Profile id missing');
} }
@ -56,29 +61,33 @@ final class Auth
'name' => $name, 'name' => $name,
'type' => $type, 'type' => $type,
'employee_number' => $empStr, 'employee_number' => $empStr,
'company' => $company,
'token' => $token, 'token' => $token,
]; ];
session_regenerate_id(true); session_regenerate_id(true);
// Caso A: tenemos el `result` del API Peñasquito → persistResult ya hace todo
// (users_cache con company, certificates, authorizations FRM, licencia verde) en una transacción.
if ($dc3Result !== null && PenasquitoDc3Api::isConfigured()) { if ($dc3Result !== null && PenasquitoDc3Api::isConfigured()) {
try { try {
PenasquitoDc3Api::persistResult($id, $dc3Result, $type); PenasquitoDc3Api::persistResult($id, $dc3Result, $type);
return;
} catch (\Throwable) { } catch (\Throwable) {
// continúa con sincronización por fetch // sigue al fallback offline
} }
} }
$green = false;
PersonRepository::upsertCache($id, $empStr, $name, $type, $green); // Caso B: modo legacy / mock. Sincronización best-effort.
PersonRepository::upsertCache($id, $empStr, $name, $type, false, $company);
try { try {
if ($dc3Result === null || !PenasquitoDc3Api::isConfigured()) {
$certs = MobilisemeClient::fetchCertificates($id, $token); $certs = MobilisemeClient::fetchCertificates($id, $token);
PersonRepository::syncCertificatesFromApi($id, $certs); PersonRepository::syncCertificatesFromApi($id, $certs);
}
} catch (\Throwable) { } catch (\Throwable) {
// offline sync optional // sincronización opcional offline
} }
$frms = PersonRepository::authorizations($id); $frms = PersonRepository::authorizations($id);
$green = PersonRepository::recomputeGreenLicense($id, $type, $frms); $green = PersonRepository::recomputeGreenLicense($id, $type, $frms);
PersonRepository::upsertCache($id, $empStr, $name, $type, $green); PersonRepository::upsertCache($id, $empStr, $name, $type, $green, $company);
} }
public static function logout(): void public static function logout(): void

View file

@ -5,7 +5,7 @@ declare(strict_types=1);
namespace CertiMine; namespace CertiMine;
/** /**
* Cliente HTTP: modo legacy (JSON login) o API Peñasquito DC3 (token estático + passport). * Cliente HTTP: modo legacy (JSON login) o API Peñasquito por passport (token estático del documento).
*/ */
final class MobilisemeClient final class MobilisemeClient
{ {
@ -83,7 +83,7 @@ final class MobilisemeClient
if (!is_array($comps)) { if (!is_array($comps)) {
return []; return [];
} }
return self::dc3CompetenciesToItems($mobilisemeId, $comps); return self::penasquitoCompetenciesToItems($mobilisemeId, $comps);
} }
if (!is_array($cfgConfig)) { if (!is_array($cfgConfig)) {
return []; return [];
@ -115,7 +115,7 @@ final class MobilisemeClient
* @param list<array<string,mixed>> $comps * @param list<array<string,mixed>> $comps
* @return list<array<string,mixed>> * @return list<array<string,mixed>>
*/ */
private static function dc3CompetenciesToItems(string $mobilisemeId, array $comps): array private static function penasquitoCompetenciesToItems(string $mobilisemeId, array $comps): array
{ {
$items = []; $items = [];
foreach ($comps as $c) { foreach ($comps as $c) {
@ -179,11 +179,9 @@ final class MobilisemeClient
$raw = curl_exec($ch); $raw = curl_exec($ch);
if ($raw === false) { if ($raw === false) {
$err = curl_error($ch); $err = curl_error($ch);
curl_close($ch);
throw new \RuntimeException('cURL error: ' . $err); throw new \RuntimeException('cURL error: ' . $err);
} }
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($method !== 'POST' && ($status < 200 || $status >= 300)) { if ($method !== 'POST' && ($status < 200 || $status >= 300)) {
throw new \RuntimeException('HTTP ' . $status); throw new \RuntimeException('HTTP ' . $status);
} }
@ -219,13 +217,13 @@ final class MobilisemeClient
{ {
if ($mobilisemeId === 'demo-contractor-1') { if ($mobilisemeId === 'demo-contractor-1') {
return [ return [
['nom_code' => 'NOM-009', 'title' => 'DC3 Heights', 'expires_at' => date('Y-m-d', strtotime('+300 days'))], ['nom_code' => 'NOM-009', 'title' => 'Alturas (demo)', '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'))], ['nom_code' => 'NOM-001', 'title' => 'Espacios confinados (demo)', 'expires_at' => date('Y-m-d', strtotime('+200 days'))],
]; ];
} }
return [ return [
['nom_code' => 'NOM-009', 'title' => 'DC3 Heights', 'expires_at' => date('Y-m-d', strtotime('+335 days'))], ['nom_code' => 'NOM-009', 'title' => 'Alturas (demo)', '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'))], ['nom_code' => 'NOM-017', 'title' => 'EPP (demo)', 'expires_at' => date('Y-m-d', strtotime('+100 days'))],
]; ];
} }
} }

View file

@ -5,22 +5,27 @@ declare(strict_types=1);
namespace CertiMine; namespace CertiMine;
/** /**
* Cliente del API REST Peñasquito / Wotbi (competencias DC3 por passport). * Cliente del API REST documentado (URL base penasquito.wotbi.com): POST /search/, GET /result/, GET /status/.
* Documentación de origen: DatosPdf.txt (extraído del PDF de scraping Mobilise-Me). * Flujo: ver docs/mobiliseme-api.md §1.6 (completed inmediato o pending + polling hasta completed).
* Rutas bajo /api/v1/dc3/... son las del PDF; no implican el módulo «DC3» del portal principal.
*/ */
final class PenasquitoDc3Api final class PenasquitoDc3Api
{ {
public static function resolvedToken(): string public static function resolvedToken(): string
{ {
$env = getenv('CERTIMINE_PENASQUITO_TOKEN');
if (is_string($env) && trim($env) !== '') {
return trim($env);
}
$env = getenv('CERTIMINE_DC3_TOKEN'); $env = getenv('CERTIMINE_DC3_TOKEN');
if (is_string($env) && $env !== '') { if (is_string($env) && trim($env) !== '') {
return trim($env); return trim($env);
} }
$cfg = Config::get('penasquito_dc3'); $cfg = Config::get('penasquito_dc3');
if (is_array($cfg)) { if (is_array($cfg)) {
$t = (string) ($cfg['static_token'] ?? ''); $t = trim((string) ($cfg['static_token'] ?? ''));
if ($t !== '') { if ($t !== '') {
return trim($t); return $t;
} }
} }
return self::tokenFromSecretsFile(); return self::tokenFromSecretsFile();
@ -44,7 +49,7 @@ final class PenasquitoDc3Api
if (!is_array($data)) { if (!is_array($data)) {
return ''; return '';
} }
$t = (string) ($data['dc3_token'] ?? $data['CERTIMINE_DC3_TOKEN'] ?? ''); $t = (string) ($data['penasquito_token'] ?? $data['dc3_token'] ?? $data['CERTIMINE_PENASQUITO_TOKEN'] ?? $data['CERTIMINE_DC3_TOKEN'] ?? '');
return trim($t); return trim($t);
} }
@ -56,19 +61,42 @@ final class PenasquitoDc3Api
/** /**
* Respuesta combinada: mismo shape que `result` del JSON cuando status=completed. * Respuesta combinada: mismo shape que `result` del JSON cuando status=completed.
* *
* Flujo (doc §1.6):
* 1) Si hay ticket persistido <= 1 h para el passport → GET /result/<ticket_id>/ directamente.
* 2) Si no, POST /search/ con el passport.
* - status=completed (caché Wotbi) → usar `result`.
* - status=pending → guardar ticket_id en BD y entrar en polling corto.
* 3) Polling corto (ver `poll_max_attempts` × `poll_interval_seconds`). Si todavía
* está pending al terminar, lanza PenasquitoPendingException para que el caller
* muestre "reintentar" y la siguiente request retome el GET /result/ sin reencolar.
*
* @return array{passport:string,name:string,company:string,competencies:list<array<string,mixed>>,error:?string} * @return array{passport:string,name:string,company:string,competencies:list<array<string,mixed>>,error:?string}
* @throws PenasquitoPendingException si el portal aún está procesando al terminar el polling local.
*/ */
public static function fetchResultForPassport(string $passport): array public static function fetchResultForPassport(string $passport): array
{ {
if (!self::isConfigured()) { if (!self::isConfigured()) {
throw new \RuntimeException('DC3 API not configured (token vacío).'); throw new \RuntimeException('API Peñasquito no configurado (token vacío).');
} }
$passport = self::normalizePassport($passport); $passport = self::normalizePassport($passport);
if ($passport === '') { if ($passport === '') {
throw new \RuntimeException('Passport vacío.'); throw new \RuntimeException('Passport vacío.');
} }
// 1) Si tenemos un ticket persistido reciente, vamos directo al GET /result/.
$saved = PenasquitoTicketRepository::findFresh($passport);
if ($saved !== null) {
return self::pollTicketUntilCompleted(
$passport,
$saved['ticket_id'],
$saved['status'],
$saved['posicion']
);
}
// 2) POST /search/
$search = self::search($passport); $search = self::search($passport);
return self::resolveSearchToResult($search); return self::resolveSearchToResult($passport, $search);
} }
public static function normalizePassport(string $passport): string public static function normalizePassport(string $passport): string
@ -87,18 +115,22 @@ final class PenasquitoDc3Api
* @param array<string,mixed> $search Respuesta del POST /search/ * @param array<string,mixed> $search Respuesta del POST /search/
* @return array{passport:string,name:string,company:string,competencies:list<array<string,mixed>>,error:?string} * @return array{passport:string,name:string,company:string,competencies:list<array<string,mixed>>,error:?string}
*/ */
private static function resolveSearchToResult(array $search): array private static function resolveSearchToResult(string $passport, array $search): array
{ {
$status = strtolower((string) ($search['status'] ?? '')); $status = strtolower((string) ($search['status'] ?? ''));
if ($status === 'completed') { if ($status === 'completed') {
$res = $search['result'] ?? null; $res = $search['result'] ?? null;
if (!is_array($res)) { if (!is_array($res)) {
throw new \RuntimeException('Respuesta completed sin bloque result.'); throw new \RuntimeException('Respuesta completed sin bloque result.');
} }
self::assertResultOk($res); self::assertResultOk($res);
// Si por alguna razón teníamos un ticket viejo guardado, ya no hace falta.
PenasquitoTicketRepository::delete($passport);
/** @var array{passport:string,name:string,company:string,competencies:list<array<string,mixed>>,error:?string} $res */ /** @var array{passport:string,name:string,company:string,competencies:list<array<string,mixed>>,error:?string} $res */
return $res; return $res;
} }
if (in_array($status, ['pending', 'processing'], true)) { if (in_array($status, ['pending', 'processing'], true)) {
$ticket = self::ticketIdFromResponse($search); $ticket = self::ticketIdFromResponse($search);
if ($ticket === '') { if ($ticket === '') {
@ -106,33 +138,69 @@ final class PenasquitoDc3Api
'Estado "' . $status . '" sin ticket_id. Claves: ' . implode(', ', array_keys($search)) 'Estado "' . $status . '" sin ticket_id. Claves: ' . implode(', ', array_keys($search))
); );
} }
$posicion = isset($search['posicion']) && is_numeric($search['posicion'])
? (int) $search['posicion']
: null;
// Persistimos el ticket inmediatamente para no perderlo si esta request agota tiempo.
PenasquitoTicketRepository::save($passport, $ticket, $status, $posicion);
return self::pollTicketUntilCompleted($passport, $ticket, $status, $posicion);
}
$hint = substr((string) json_encode($search, JSON_UNESCAPED_UNICODE), 0, 400);
throw new \RuntimeException('Estado de búsqueda no reconocido: "' . $status . '". ' . $hint);
}
/**
* Polling acotado al endpoint 2 (GET /result/<ticket_id>/). Si el portal sigue
* pending al terminar, lanza PenasquitoPendingException (el ticket queda guardado).
*
* @return array{passport:string,name:string,company:string,competencies:list<array<string,mixed>>,error:?string}
*/
private static function pollTicketUntilCompleted(
string $passport,
string $ticketId,
string $lastStatus,
?int $posicion
): array {
$cfg = Config::get('penasquito_dc3'); $cfg = Config::get('penasquito_dc3');
$pollS = is_array($cfg) ? (int) ($cfg['poll_interval_seconds'] ?? 2) : 2; $pollS = is_array($cfg) ? max(1, (int) ($cfg['poll_interval_seconds'] ?? 2)) : 2;
$max = is_array($cfg) ? (int) ($cfg['poll_max_attempts'] ?? 40) : 40; $max = is_array($cfg) ? max(1, (int) ($cfg['poll_max_attempts'] ?? 3)) : 3;
for ($i = 0; $i < $max; $i++) { for ($i = 0; $i < $max; $i++) {
if ($i > 0) { if ($i > 0) {
usleep((int) max(1, $pollS) * 1_000_000); sleep($pollS);
}
try {
$r = self::ticketResult($ticketId);
} catch (\Throwable $e) {
// Guardamos el último error para diagnóstico y propagamos.
PenasquitoTicketRepository::markPolled($passport, $lastStatus, $e->getMessage());
throw $e;
} }
$r = self::ticketResult($ticket);
$st = strtolower((string) ($r['status'] ?? '')); $st = strtolower((string) ($r['status'] ?? ''));
$lastStatus = $st !== '' ? $st : $lastStatus;
if ($st === 'completed') { if ($st === 'completed') {
$res = $r['result'] ?? null; $res = $r['result'] ?? null;
if (!is_array($res)) { if (!is_array($res)) {
throw new \RuntimeException('Ticket completado sin result.'); throw new \RuntimeException('Ticket completado sin bloque result.');
} }
self::assertResultOk($res); self::assertResultOk($res);
PenasquitoTicketRepository::delete($passport);
/** @var array{passport:string,name:string,company:string,competencies:list<array<string,mixed>>,error:?string} $out */ /** @var array{passport:string,name:string,company:string,competencies:list<array<string,mixed>>,error:?string} $out */
$out = $res; $out = $res;
return $out; return $out;
} }
if ($st !== 'pending' && $st !== 'processing') { if ($st !== 'pending' && $st !== 'processing') {
PenasquitoTicketRepository::markPolled($passport, $st, 'Estado inesperado');
throw new \RuntimeException('Estado de ticket inesperado: ' . $st); throw new \RuntimeException('Estado de ticket inesperado: ' . $st);
} }
PenasquitoTicketRepository::markPolled($passport, $st);
} }
throw new \RuntimeException('Tiempo de espera agotado consultando el ticket DC3.');
} // Polling local agotado, pero el ticket sigue válido en el servidor.
$hint = substr((string) json_encode($search, JSON_UNESCAPED_UNICODE), 0, 400); throw new PenasquitoPendingException($passport, $ticketId, $lastStatus, $posicion);
throw new \RuntimeException('Estado de búsqueda no reconocido: "' . $status . '". ' . $hint);
} }
/** @param array<string,mixed> $r */ /** @param array<string,mixed> $r */
@ -152,23 +220,31 @@ final class PenasquitoDc3Api
* *
* @return array{token: string, profile: array<string,mixed>} * @return array{token: string, profile: array<string,mixed>}
*/ */
/**
* Perfil mínimo para Auth::login y caché local (un solo round-trip al API).
*
* @return array{token: string, profile: array<string,mixed>, dc3_result: array<string,mixed>}
*/
public static function loginWithPassport(string $passport): array public static function loginWithPassport(string $passport): array
{ {
$result = self::fetchResultForPassport($passport); $result = self::fetchResultForPassport($passport);
$tok = self::resolvedToken(); $tok = self::resolvedToken();
$isContractor = self::guessContractorFromCompany((string) ($result['company'] ?? '')); $company = (string) ($result['company'] ?? '');
$isContractor = self::guessContractorFromCompany($company);
$profile = [ $profile = [
'id' => (string) ($result['passport'] ?? $passport), 'id' => (string) ($result['passport'] ?? $passport),
'full_name' => (string) ($result['name'] ?? ''), 'full_name' => (string) ($result['name'] ?? ''),
'type' => $isContractor ? 'contractor' : 'employee', 'type' => $isContractor ? 'contractor' : 'employee',
'employee_number' => (string) ($result['passport'] ?? $passport), 'employee_number' => (string) ($result['passport'] ?? $passport),
'company' => (string) ($result['company'] ?? ''), 'company' => $company,
]; ];
return ['token' => $tok, 'profile' => $profile, 'dc3_result' => $result]; return ['token' => $tok, 'profile' => $profile, 'dc3_result' => $result];
} }
/** /**
* Persiste competencias DC3 en users_cache, certificates y autorizaciones FRM. * Persiste el `result` del API (documento) en users_cache, certificates y autorizaciones FRM.
*
* Usa una transacción para que el perfil quede consistente si alguna parte falla.
* *
* @param array{passport?:string,name?:string,company?:string,competencies?:mixed,error?:mixed} $result * @param array{passport?:string,name?:string,company?:string,competencies?:mixed,error?:mixed} $result
*/ */
@ -177,21 +253,56 @@ final class PenasquitoDc3Api
self::assertResultOk($result); self::assertResultOk($result);
$name = (string) ($result['name'] ?? '—'); $name = (string) ($result['name'] ?? '—');
$emp = (string) ($result['passport'] ?? $mobilisemeId); $emp = (string) ($result['passport'] ?? $mobilisemeId);
$companyRaw = $result['company'] ?? null;
$company = is_string($companyRaw) ? trim($companyRaw) : null;
if ($company === '') {
$company = null;
}
$comps = $result['competencies'] ?? []; $comps = $result['competencies'] ?? [];
if (!is_array($comps)) { if (!is_array($comps)) {
$comps = []; $comps = [];
} }
$pdo = Database::pdo();
$started = !$pdo->inTransaction();
if ($started) {
$pdo->beginTransaction();
}
try {
PersonRepository::upsertCache($mobilisemeId, $emp, $name, $personType, false, $company);
$items = self::competenciesToCertificatePayloads($mobilisemeId, $comps); $items = self::competenciesToCertificatePayloads($mobilisemeId, $comps);
PersonRepository::applySyncPayload($mobilisemeId, ['certificates' => $items]); if ($items !== []) {
PersonRepository::applySyncPayload(
$mobilisemeId,
['certificates' => $items],
'penasquito_api'
);
}
if ($personType === 'contractor') { if ($personType === 'contractor') {
$auths = self::competenciesToAuthorizations($comps); $auths = self::competenciesToAuthorizations($comps);
if ($auths !== []) { if ($auths !== []) {
PersonRepository::applySyncPayload($mobilisemeId, ['authorizations' => $auths]); PersonRepository::applySyncPayload(
$mobilisemeId,
['authorizations' => $auths],
'penasquito_api'
);
} }
} }
$frms = PersonRepository::authorizations($mobilisemeId); $frms = PersonRepository::authorizations($mobilisemeId);
$green = PersonRepository::recomputeGreenLicense($mobilisemeId, $personType, $frms); $green = PersonRepository::recomputeGreenLicense($mobilisemeId, $personType, $frms);
PersonRepository::upsertCache($mobilisemeId, $emp, $name, $personType, $green); PersonRepository::upsertCache($mobilisemeId, $emp, $name, $personType, $green, $company);
if ($started) {
$pdo->commit();
}
} catch (\Throwable $e) {
if ($started && $pdo->inTransaction()) {
$pdo->rollBack();
}
throw $e;
}
} }
/** @param array<string,mixed> $result */ /** @param array<string,mixed> $result */
@ -199,7 +310,7 @@ final class PenasquitoDc3Api
{ {
$err = $result['error'] ?? null; $err = $result['error'] ?? null;
if ($err !== null && $err !== '') { if ($err !== null && $err !== '') {
throw new \RuntimeException(is_string($err) ? $err : 'Error DC3'); throw new \RuntimeException(is_string($err) ? $err : 'Error en la respuesta del servicio');
} }
} }
@ -208,19 +319,27 @@ final class PenasquitoDc3Api
{ {
$cfg = Config::get('penasquito_dc3'); $cfg = Config::get('penasquito_dc3');
$base = rtrim((string) (is_array($cfg) ? $cfg['base_url'] : ''), '/'); $base = rtrim((string) (is_array($cfg) ? $cfg['base_url'] : ''), '/');
$path = (string) (is_array($cfg) ? $cfg['search_path'] : ''); $path = self::ensureTrailingSlash((string) (is_array($cfg) ? $cfg['search_path'] : ''));
$url = $base . $path; $url = $base . $path;
$resp = self::request('POST', $url, ['passport' => $passport]); $resp = self::request('POST', $url, ['passport' => $passport], $passport);
$j = $resp['json']; $j = $resp['json'];
if (!is_array($j)) { if (!is_array($j)) {
$raw = substr(preg_replace('/\s+/', ' ', (string) $resp['raw']), 0, 240); $raw = substr(preg_replace('/\s+/', ' ', (string) $resp['raw']), 0, 240);
throw new \RuntimeException( throw new \RuntimeException(
'DC3 search no devolvió JSON válido (HTTP ' . $resp['status'] . '). Inicio: ' . $raw 'La búsqueda en el servicio no devolvió JSON válido (HTTP ' . $resp['status'] . '). Inicio: ' . $raw
); );
} }
return self::unwrapEnvelope($j); return self::unwrapEnvelope($j);
} }
private static function ensureTrailingSlash(string $path): string
{
if ($path === '') {
return $path;
}
return str_ends_with($path, '/') ? $path : $path . '/';
}
/** @param array<string,mixed> $j */ /** @param array<string,mixed> $j */
private static function unwrapEnvelope(array $j): array private static function unwrapEnvelope(array $j): array
{ {
@ -239,12 +358,12 @@ final class PenasquitoDc3Api
$cfg = Config::get('penasquito_dc3'); $cfg = Config::get('penasquito_dc3');
$base = rtrim((string) (is_array($cfg) ? $cfg['base_url'] : ''), '/'); $base = rtrim((string) (is_array($cfg) ? $cfg['base_url'] : ''), '/');
$tpl = (string) (is_array($cfg) ? $cfg['result_path_template'] : ''); $tpl = (string) (is_array($cfg) ? $cfg['result_path_template'] : '');
$path = str_replace('{ticket_id}', rawurlencode($ticketId), $tpl); $path = self::ensureTrailingSlash(str_replace('{ticket_id}', rawurlencode($ticketId), $tpl));
$resp = self::request('GET', $base . $path, null); $resp = self::request('GET', $base . $path, null);
$j = $resp['json']; $j = $resp['json'];
if (!is_array($j)) { if (!is_array($j)) {
$raw = substr(preg_replace('/\s+/', ' ', (string) $resp['raw']), 0, 240); $raw = substr(preg_replace('/\s+/', ' ', (string) $resp['raw']), 0, 240);
throw new \RuntimeException('DC3 ticket result no JSON (HTTP ' . $resp['status'] . '): ' . $raw); throw new \RuntimeException('Resultado de ticket: respuesta no JSON (HTTP ' . $resp['status'] . '): ' . $raw);
} }
return self::unwrapEnvelope($j); return self::unwrapEnvelope($j);
} }
@ -261,7 +380,7 @@ final class PenasquitoDc3Api
} }
$cfg = Config::get('penasquito_dc3'); $cfg = Config::get('penasquito_dc3');
$base = rtrim((string) (is_array($cfg) ? $cfg['base_url'] : ''), '/'); $base = rtrim((string) (is_array($cfg) ? $cfg['base_url'] : ''), '/');
$path = (string) (is_array($cfg) ? $cfg['status_path'] : ''); $path = self::ensureTrailingSlash((string) (is_array($cfg) ? $cfg['status_path'] : ''));
$resp = self::request('GET', $base . $path, null); $resp = self::request('GET', $base . $path, null);
$j = $resp['json']; $j = $resp['json'];
return is_array($j) ? $j : []; return is_array($j) ? $j : [];
@ -269,9 +388,10 @@ final class PenasquitoDc3Api
/** /**
* @param array<string,mixed>|null $jsonBody * @param array<string,mixed>|null $jsonBody
* @param string $contextPassport Passport del contexto (para mensajes de error). Vacío si no aplica.
* @return array{status:int, json:mixed, raw:string} * @return array{status:int, json:mixed, raw:string}
*/ */
private static function request(string $method, string $url, ?array $jsonBody): array private static function request(string $method, string $url, ?array $jsonBody, string $contextPassport = ''): array
{ {
$dc3 = Config::get('penasquito_dc3'); $dc3 = Config::get('penasquito_dc3');
$timeout = is_array($dc3) ? (int) ($dc3['timeout_seconds'] ?? 30) : 30; $timeout = is_array($dc3) ? (int) ($dc3['timeout_seconds'] ?? 30) : 30;
@ -291,6 +411,8 @@ final class PenasquitoDc3Api
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $timeout, CURLOPT_TIMEOUT => $timeout,
CURLOPT_HTTPHEADER => $headers, CURLOPT_HTTPHEADER => $headers,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 3,
]); ]);
if ($jsonBody !== null) { if ($jsonBody !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($jsonBody, JSON_UNESCAPED_UNICODE)); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($jsonBody, JSON_UNESCAPED_UNICODE));
@ -299,23 +421,122 @@ final class PenasquitoDc3Api
$raw = curl_exec($ch); $raw = curl_exec($ch);
if ($raw === false) { if ($raw === false) {
$err = curl_error($ch); $err = curl_error($ch);
curl_close($ch);
throw new \RuntimeException('cURL: ' . $err); throw new \RuntimeException('cURL: ' . $err);
} }
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); $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) { if ($status < 200 || $status >= 300) {
throw new \RuntimeException('DC3 API HTTP ' . $status); $msg = self::buildHttpErrorMessage($status, (string) $raw, $contextPassport);
throw new \RuntimeException($msg);
} }
$decoded = json_decode((string) $raw, true); $decoded = json_decode((string) $raw, true);
return ['status' => $status, 'json' => $decoded, 'raw' => (string) $raw]; return ['status' => $status, 'json' => $decoded, 'raw' => (string) $raw];
} }
/**
* Mensaje amigable según el código HTTP (en español, contextualizado).
*/
private static function buildHttpErrorMessage(int $status, string $raw, string $passport): string
{
$hint = self::httpErrorBodyHint($raw);
$hintSuffix = $hint !== '' ? ' Detalle del servicio: "' . $hint . '".' : '';
$ctx = $passport !== '' ? ' (passport "' . $passport . '")' : '';
if ($status === 400) {
return 'API Peñasquito: petición inválida (HTTP 400)' . $ctx
. '. Revise el formato del passport.' . $hintSuffix;
}
if ($status === 401) {
return 'API Peñasquito: 401 (token inválido o ausente).' . $hintSuffix;
}
if ($status === 403) {
return 'API Peñasquito: 403 (token sin permisos para este recurso).' . $hintSuffix;
}
if ($status === 404) {
return 'API Peñasquito: el portal no encontró información para el passport'
. ($passport !== '' ? ' "' . $passport . '"' : '')
. ' (HTTP 404).'
. ' Verifique que el código exista en Mobilise-Me y que esté escrito como aparece allí.'
. $hintSuffix;
}
if ($status === 408 || $status === 504) {
return 'API Peñasquito: tiempo de espera agotado (HTTP ' . $status . ').' . $hintSuffix;
}
if ($status === 429) {
return 'API Peñasquito: demasiadas solicitudes (HTTP 429). Intente más tarde.' . $hintSuffix;
}
if ($status >= 500) {
return 'API Peñasquito: servicio no disponible temporalmente (HTTP ' . $status . ').' . $hintSuffix;
}
return 'API Peñasquito: HTTP ' . $status . '.' . $hintSuffix;
}
/**
* Texto breve y seguro para mensajes de error (sin incluir cabeceras ni token).
*/
private static function httpErrorBodyHint(string $raw): string
{
$raw = trim($raw);
if ($raw === '') {
return '';
}
$decoded = json_decode($raw, true);
if (is_array($decoded)) {
foreach (['detail', 'message', 'error', 'non_field_errors'] as $k) {
if (!isset($decoded[$k])) {
continue;
}
$v = $decoded[$k];
if (is_string($v) && $v !== '') {
return self::truncateHint($v, 280);
}
if (is_array($v)) {
$flat = [];
self::flattenMessages($v, $flat);
if ($flat !== []) {
return self::truncateHint(implode(' ', $flat), 280);
}
}
}
}
$plain = trim(preg_replace('/\s+/', ' ', strip_tags($raw)));
return self::truncateHint($plain, 200);
}
/** @param mixed $v */
private static function flattenMessages($v, array &$out): void
{
if (is_string($v) && $v !== '') {
$out[] = $v;
return;
}
if (!is_array($v)) {
return;
}
foreach ($v as $item) {
self::flattenMessages($item, $out);
}
}
private static function truncateHint(string $s, int $max): string
{
if (function_exists('mb_strlen') && function_exists('mb_substr')) {
if (mb_strlen($s, 'UTF-8') <= $max) {
return $s;
}
return mb_substr($s, 0, $max - 1, 'UTF-8') . '…';
}
if (strlen($s) <= $max) {
return $s;
}
return substr($s, 0, $max - 3) . '...';
}
public static function guessContractorFromCompanyPublic(string $company): bool public static function guessContractorFromCompanyPublic(string $company): bool
{ {
return self::guessContractorFromCompany($company); return self::guessContractorFromCompany($company);
@ -358,7 +579,7 @@ final class PenasquitoDc3Api
} }
$ext = 'dc3-' . md5($mobilisemeId . '|' . $activity . '|' . (string) $req); $ext = 'dc3-' . md5($mobilisemeId . '|' . $activity . '|' . (string) $req);
$row = [ $row = [
'title' => $activity !== '' ? $activity : 'DC3', 'title' => $activity !== '' ? $activity : 'Competencia',
'issued_at' => $issued, 'issued_at' => $issued,
'expires_at' => $expires, 'expires_at' => $expires,
'status' => $st, 'status' => $st,

View file

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace CertiMine;
/**
* El passport está siendo procesado por el worker remoto. No es un error: el caller
* debería mostrar un mensaje amable y permitir reintentar (el ticket queda persistido,
* el reintento solo consulta GET /result/<ticket_id>/ sin volver a encolar).
*/
final class PenasquitoPendingException extends \RuntimeException
{
public function __construct(
public readonly string $passport,
public readonly string $ticketId,
public readonly string $remoteStatus,
public readonly ?int $posicion = null,
string $message = ''
) {
if ($message === '') {
$message = sprintf(
'El portal aún está procesando el passport "%s" (ticket %s, estado: %s%s).',
$passport,
$ticketId,
$remoteStatus,
$posicion !== null ? ', posición ' . $posicion : ''
);
}
parent::__construct($message);
}
}

View file

@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace CertiMine;
use PDO;
/**
* Persistencia de tickets del API Peñasquito (POST /search/ → GET /result/<ticket_id>/).
*
* Permite que un segundo request HTTP retome el polling sin volver a encolar.
*/
final class PenasquitoTicketRepository
{
/** TTL para considerar un ticket caducado y descartarlo (1 hora, alineado con la caché Redis del backend). */
public const TTL_SECONDS = 3600;
/** @return array{passport:string,ticket_id:string,status:string,posicion:?int,created_at:string}|null */
public static function findFresh(string $passport): ?array
{
$pdo = Database::pdo();
$st = $pdo->prepare(
'SELECT passport, ticket_id, status, posicion, created_at
FROM penasquito_tickets
WHERE passport = ?
AND created_at >= (NOW() - INTERVAL ? SECOND)
LIMIT 1'
);
$st->execute([$passport, self::TTL_SECONDS]);
$row = $st->fetch(PDO::FETCH_ASSOC);
if (!$row) {
return null;
}
return [
'passport' => (string) $row['passport'],
'ticket_id' => (string) $row['ticket_id'],
'status' => (string) $row['status'],
'posicion' => isset($row['posicion']) ? (int) $row['posicion'] : null,
'created_at' => (string) $row['created_at'],
];
}
public static function save(string $passport, string $ticketId, string $status, ?int $posicion): void
{
$pdo = Database::pdo();
$st = $pdo->prepare(
'INSERT INTO penasquito_tickets (passport, ticket_id, status, posicion, created_at, last_polled_at)
VALUES (?, ?, ?, ?, NOW(), NOW())
ON DUPLICATE KEY UPDATE
ticket_id = VALUES(ticket_id),
status = VALUES(status),
posicion = VALUES(posicion),
created_at = VALUES(created_at),
last_polled_at = VALUES(last_polled_at),
last_error = NULL'
);
$st->execute([$passport, $ticketId, $status, $posicion]);
}
public static function markPolled(string $passport, string $status, ?string $error = null): void
{
$pdo = Database::pdo();
$st = $pdo->prepare(
'UPDATE penasquito_tickets
SET status = ?, last_polled_at = NOW(), last_error = ?
WHERE passport = ?'
);
$st->execute([$status, $error, $passport]);
}
public static function delete(string $passport): void
{
$pdo = Database::pdo();
$st = $pdo->prepare('DELETE FROM penasquito_tickets WHERE passport = ?');
$st->execute([$passport]);
}
public static function purgeStale(): int
{
$pdo = Database::pdo();
$st = $pdo->prepare(
'DELETE FROM penasquito_tickets
WHERE created_at < (NOW() - INTERVAL ? SECOND)'
);
$st->execute([self::TTL_SECONDS]);
return $st->rowCount();
}
}

View file

@ -8,21 +8,39 @@ use PDO;
final class PersonRepository final class PersonRepository
{ {
/**
* Inserta o actualiza la caché del usuario.
*
* Pasar `$company = null` no borra el valor previo (se preserva vía COALESCE);
* pasar cadena vacía sí lo limpia explícitamente.
*/
public static function upsertCache( public static function upsertCache(
string $mobilisemeId, string $mobilisemeId,
?string $employeeNumber, ?string $employeeNumber,
string $displayName, string $displayName,
string $personType, string $personType,
bool $greenLicense bool $greenLicense,
?string $company = null
): void { ): void {
$pdo = Database::pdo(); $pdo = Database::pdo();
$st = $pdo->prepare( $st = $pdo->prepare(
'INSERT INTO users_cache (mobiliseme_id, employee_number, display_name, person_type, green_license_flag) 'INSERT INTO users_cache (mobiliseme_id, employee_number, display_name, company, person_type, green_license_flag)
VALUES (?,?,?,?,?) VALUES (?,?,?,?,?,?)
ON DUPLICATE KEY UPDATE employee_number=VALUES(employee_number), display_name=VALUES(display_name), ON DUPLICATE KEY UPDATE
person_type=VALUES(person_type), green_license_flag=VALUES(green_license_flag)' employee_number = VALUES(employee_number),
display_name = VALUES(display_name),
company = COALESCE(VALUES(company), company),
person_type = VALUES(person_type),
green_license_flag = VALUES(green_license_flag)'
); );
$st->execute([$mobilisemeId, $employeeNumber, $displayName, $personType, $greenLicense ? 1 : 0]); $st->execute([
$mobilisemeId,
$employeeNumber,
$displayName,
$company,
$personType,
$greenLicense ? 1 : 0,
]);
} }
/** @return array<string,mixed>|null */ /** @return array<string,mixed>|null */
@ -216,11 +234,12 @@ final class PersonRepository
} }
/** /**
* Apply webhook payload certificates/authorizations. * Aplica payload de certificados/autorizaciones (webhook o API Peñasquito).
* *
* @param array<string,mixed> $payload * @param array<string,mixed> $payload
* @param string $source Origen para `contractor_authorizations.source`.
*/ */
public static function applySyncPayload(string $mobilisemeId, array $payload): void public static function applySyncPayload(string $mobilisemeId, array $payload, string $source = 'webhook'): void
{ {
$pdo = Database::pdo(); $pdo = Database::pdo();
if (isset($payload['certificates']) && is_array($payload['certificates'])) { if (isset($payload['certificates']) && is_array($payload['certificates'])) {
@ -230,10 +249,10 @@ final class PersonRepository
} }
$nomCode = (string) ($c['nom_code'] ?? ''); $nomCode = (string) ($c['nom_code'] ?? '');
$nomId = self::nomIdByCode($nomCode); $nomId = self::nomIdByCode($nomCode);
$title = (string) ($c['title'] ?? 'DC3'); $title = (string) ($c['title'] ?? 'Competencia');
$issued = isset($c['issued_at']) ? (string) $c['issued_at'] : null; $issued = isset($c['issued_at']) ? (string) $c['issued_at'] : null;
$exp = isset($c['expires_at']) ? (string) $c['expires_at'] : null; $exp = isset($c['expires_at']) ? (string) $c['expires_at'] : null;
$ext = (string) ($c['external_ref'] ?? uniqid('wh-', true)); $ext = (string) ($c['external_ref'] ?? uniqid('sync-', true));
$frmCode = (string) ($c['frm_code'] ?? ''); $frmCode = (string) ($c['frm_code'] ?? '');
$frmId = $frmCode !== '' ? self::frmIdByCode($frmCode) : null; $frmId = $frmCode !== '' ? self::frmIdByCode($frmCode) : null;
$status = (string) ($c['status'] ?? 'valid'); $status = (string) ($c['status'] ?? 'valid');
@ -259,10 +278,10 @@ final class PersonRepository
$vu = isset($a['valid_until']) ? (string) $a['valid_until'] : null; $vu = isset($a['valid_until']) ? (string) $a['valid_until'] : null;
$st = $pdo->prepare( $st = $pdo->prepare(
'INSERT INTO contractor_authorizations (mobiliseme_id, frm_id, valid_until, source) 'INSERT INTO contractor_authorizations (mobiliseme_id, frm_id, valid_until, source)
VALUES (?,?,?, "webhook") VALUES (?,?,?,?)
ON DUPLICATE KEY UPDATE valid_until=VALUES(valid_until), source=VALUES(source)' ON DUPLICATE KEY UPDATE valid_until=VALUES(valid_until), source=VALUES(source)'
); );
$st->execute([$mobilisemeId, $fid, $vu ?: null]); $st->execute([$mobilisemeId, $fid, $vu ?: null, $source]);
} }
} }
} }

View file

@ -9,6 +9,8 @@ require_once $base . '/src/Database.php';
require_once $base . '/src/I18n.php'; require_once $base . '/src/I18n.php';
require_once $base . '/src/Security.php'; require_once $base . '/src/Security.php';
require_once $base . '/src/PersonRepository.php'; require_once $base . '/src/PersonRepository.php';
require_once $base . '/src/PenasquitoTicketRepository.php';
require_once $base . '/src/PenasquitoPendingException.php';
require_once $base . '/src/PenasquitoDc3Api.php'; require_once $base . '/src/PenasquitoDc3Api.php';
require_once $base . '/src/MobilisemeClient.php'; require_once $base . '/src/MobilisemeClient.php';
require_once $base . '/src/Auth.php'; require_once $base . '/src/Auth.php';

View file

@ -21,7 +21,7 @@ require __DIR__ . '/partials/header.php';
<div class="col-lg-5"> <div class="col-lg-5">
<div class="card p-4"> <div class="card p-4">
<h2 class="h5 mb-3"><span class="material-symbols-outlined align-middle">shield_person</span> Mobiliseme</h2> <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> <p class="small text-muted mb-0"><?= Util::h(I18n::t('home_mobiliseme_blurb')) ?></p>
</div> </div>
</div> </div>
</div> </div>

View file

@ -7,17 +7,19 @@ use CertiMine\Security;
use CertiMine\Util; use CertiMine\Util;
/** @var string|null $error */ /** @var string|null $error */
/** @var bool $lookupDc3Ok */ /** @var string|null $lookupErrorDetail */
/** @var bool $lookupDc3Env */ /** @var array{passport:string,ticket_id:string,status:string,posicion:?int}|null $lookupPending */
/** @var bool $penasquitoApiOk */
/** @var bool $penasquitoApiTokenFromEnv */
/** @var bool $lookupUsingExample */ /** @var bool $lookupUsingExample */
/** @var string $lookupDc3Base */ /** @var string $penasquitoApiBaseUrl */
require __DIR__ . '/partials/header.php'; require __DIR__ . '/partials/header.php';
?> ?>
<h1 class="h3 mb-3"><?= Util::h(I18n::t('lookup_title')) ?></h1> <h1 class="h3 mb-3"><?= Util::h(I18n::t('lookup_title')) ?></h1>
<p class="text-muted"><?= Util::h(I18n::t('lookup_intro')) ?></p> <p class="text-muted"><?= Util::h(I18n::t('lookup_intro')) ?></p>
<?php if (!$lookupDc3Ok): ?> <?php if (!$penasquitoApiOk): ?>
<div class="alert alert-warning border-0 shadow-sm" role="status"> <div class="alert alert-warning border-0 shadow-sm" role="status">
<span class="material-symbols-outlined align-middle">warning</span> <span class="material-symbols-outlined align-middle">warning</span>
<strong><?= Util::h(I18n::t('lookup_need_dc3_title')) ?></strong><br> <strong><?= Util::h(I18n::t('lookup_need_dc3_title')) ?></strong><br>
@ -31,8 +33,8 @@ require __DIR__ . '/partials/header.php';
<span class="material-symbols-outlined align-middle">cloud_done</span> <span class="material-symbols-outlined align-middle">cloud_done</span>
<?= Util::h(I18n::t('lookup_dc3_ready')) ?> <?= Util::h(I18n::t('lookup_dc3_ready')) ?>
<span class="small text-muted d-block mt-1"> <span class="small text-muted d-block mt-1">
<?= Util::h($lookupDc3Base) ?> <?= Util::h($penasquitoApiBaseUrl) ?>
<?php if ($lookupDc3Env): ?> — <?= Util::h(I18n::t('lookup_token_env')) ?><?php else: ?> — <?= Util::h(I18n::t('lookup_token_config')) ?><?php endif; ?> <?php if ($penasquitoApiTokenFromEnv): ?> — <?= Util::h(I18n::t('lookup_token_env')) ?><?php else: ?> — <?= Util::h(I18n::t('lookup_token_config')) ?><?php endif; ?>
</span> </span>
</div> </div>
<?php endif; ?> <?php endif; ?>
@ -41,8 +43,38 @@ require __DIR__ . '/partials/header.php';
<div class="alert alert-secondary small"><?= Util::h(I18n::t('lookup_debug_hint')) ?></div> <div class="alert alert-secondary small"><?= Util::h(I18n::t('lookup_debug_hint')) ?></div>
<?php endif; ?> <?php endif; ?>
<?php if (!empty($lookupPending)): ?>
<div class="alert alert-info border-0 shadow-sm">
<div class="d-flex align-items-center gap-2 mb-2">
<span class="material-symbols-outlined">hourglass_top</span>
<strong><?= Util::h(I18n::t('lookup_pending_title')) ?></strong>
</div>
<p class="mb-2"><?= Util::h(I18n::t('lookup_pending_body')) ?></p>
<ul class="small text-muted mb-3">
<li><?= Util::h(I18n::t('lookup_pending_passport')) ?>: <code><?= Util::h($lookupPending['passport']) ?></code></li>
<li><?= Util::h(I18n::t('lookup_pending_ticket')) ?>: <code><?= Util::h($lookupPending['ticket_id']) ?></code></li>
<li><?= Util::h(I18n::t('lookup_pending_status')) ?>: <code><?= Util::h($lookupPending['status']) ?></code><?php if ($lookupPending['posicion'] !== null): ?> · <?= Util::h(I18n::t('lookup_pending_position')) ?>: <strong><?= (int) $lookupPending['posicion'] ?></strong><?php endif; ?></li>
</ul>
<form method="post" class="d-inline">
<input type="hidden" name="_csrf" value="<?= Util::h(Security::csrfToken()) ?>">
<input type="hidden" name="person_type" value="employee">
<input type="hidden" name="code" value="<?= Util::h($lookupPending['passport']) ?>">
<button class="btn btn-primary" type="submit">
<span class="material-symbols-outlined align-middle">refresh</span>
<?= Util::h(I18n::t('lookup_pending_retry')) ?>
</button>
</form>
</div>
<?php endif; ?>
<?php if ($error): ?> <?php if ($error): ?>
<div class="alert alert-danger"><?= Util::h($error) ?></div> <div class="alert alert-danger">
<?= Util::h($error) ?>
<?php if (!empty($lookupErrorDetail)): ?>
<hr class="my-2">
<div class="small font-monospace text-break mb-0"><?= Util::h((string) $lookupErrorDetail) ?></div>
<?php endif; ?>
</div>
<?php endif; ?> <?php endif; ?>
<form method="post" class="card p-4 mb-3" style="max-width:520px"> <form method="post" class="card p-4 mb-3" style="max-width:520px">

View file

@ -32,6 +32,14 @@ $statusLabel = static function (string $s): string {
<?= $ptype === 'contractor' ? Util::h(I18n::t('lookup_contractor')) : Util::h(I18n::t('lookup_employee')) ?> <?= $ptype === 'contractor' ? Util::h(I18n::t('lookup_contractor')) : Util::h(I18n::t('lookup_employee')) ?>
· <?= Util::h((string) ($row['employee_number'] ?? '')) ?> · <?= Util::h((string) ($row['employee_number'] ?? '')) ?>
</p> </p>
<?php $company = trim((string) ($row['company'] ?? '')); ?>
<?php if ($company !== ''): ?>
<p class="mb-3">
<span class="material-symbols-outlined align-middle text-muted">apartment</span>
<span class="text-muted"><?= Util::h(I18n::t('profile_company')) ?>:</span>
<strong><?= Util::h($company) ?></strong>
</p>
<?php endif; ?>
<div class="mb-4"> <div class="mb-4">
<label class="form-label small text-muted">QR / deep link</label> <label class="form-label small text-muted">QR / deep link</label>
@ -52,7 +60,7 @@ $statusLabel = static function (string $s): string {
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>
<?php if ($certs === []): ?> <?php if ($certs === []): ?>
<tr><td colspan="4" class="text-muted"><?= Util::h(I18n::t('no_results')) ?></td></tr> <tr><td colspan="4" class="text-muted"><?= Util::h(I18n::t('profile_no_competencies')) ?></td></tr>
<?php endif; ?> <?php endif; ?>
</tbody> </tbody>
</table> </table>