diff --git a/README.md b/README.md index 69695af..eea766e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 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**. --- @@ -10,9 +10,9 @@ Portal **bilingüe (ES / EN)**, backend en **PHP** y datos en **MariaDB**. | Área | Descripción | |------|-------------| | **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). | -| **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. | | **Webhook** | `POST` para sincronizar certificados / autorizaciones desde otros sistemas (eventos idempotentes). | @@ -30,15 +30,15 @@ flowchart LR DB[(MariaDB)] end subgraph ext [Servicios] - DC3[API DC3 Wotbi] + PQ[API Peñasquito (documento / Wotbi)] end U --> P P --> DB - P --> DC3 + P --> PQ ``` -1. **Sin token DC3:** 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). +1. **Sin token del API (documento):** los formularios usan datos de **semilla SQL** y **mock** de login. +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`. --- @@ -72,10 +72,11 @@ Edita `config/config.php`: - **`db`**: host, nombre de base, usuario y contraseña. - **`app.public_url`**: URL pública del sitio (para enlaces y QR). -- **API DC3 — token (orden):** - 1) `CERTIMINE_DC3_TOKEN` - 2) `penasquito_dc3.static_token` en `config.php` - 3) **`config/token.php`** (copia de `config/token.example.php`; **no se sube a git**). +- **Token del API (URL base del documento) — orden:** + 1) `CERTIMINE_PENASQUITO_TOKEN` + 2) `CERTIMINE_DC3_TOKEN` (alias) + 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`). - **`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/ ├── 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 ├── lang/ # Cadenas ES / EN ├── config/ # config.example.php (plantilla); config.php local ignorado por git) diff --git a/config/config.example.php b/config/config.example.php index 1ba182b..e76a00c 100644 --- a/config/config.example.php +++ b/config/config.example.php @@ -1,8 +1,11 @@ [ @@ -30,8 +33,7 @@ return [ '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. + * API REST en la URL base del PDF (Wotbi): búsqueda por passport. Rutas = las del documento. */ 'penasquito_dc3' => [ 'base_url' => 'https://penasquito.wotbi.com', @@ -41,12 +43,18 @@ return [ 'status_path' => '/api/v1/dc3/competencies/passports/status/', 'authorization_header' => 'Authorization', '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// sin volver a encolar. Para tareas CLI/cron sube max_attempts. + */ 'poll_interval_seconds' => 2, - 'poll_max_attempts' => 20, - 'timeout_seconds' => 45, + 'poll_max_attempts' => 3, + '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' => [ 'base_url' => 'https://api.mobiliseme.example', diff --git a/config/token.example.php b/config/token.example.php index 87bcd03..757abf6 100644 --- a/config/token.example.php +++ b/config/token.example.php @@ -1,13 +1,14 @@ '', 'dc3_token' => '', ]; diff --git a/docs/DatosPdf.example.txt b/docs/DatosPdf.example.txt index fe1891a..359ca20 100644 --- a/docs/DatosPdf.example.txt +++ b/docs/DatosPdf.example.txt @@ -13,7 +13,7 @@ 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 +TOKEN Authorization: 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 diff --git a/docs/mobiliseme-api.md b/docs/mobiliseme-api.md index bc25606..fd88d85 100644 --- a/docs/mobiliseme-api.md +++ b/docs/mobiliseme-api.md @@ -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 Authorization: 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 +``` -`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` -- Body: `{ "passport": "E000055821" }` -- Respuesta si hay caché (~1 h): `status: "completed"` + `result` (name, company, competencies[]). -- Respuesta si encola: `status: "pending"` + `ticket_id` (+ opcional `posicion`). +### Respuesta estándar encolada -## Endpoint 2 — Resultado del ticket (polling) +```json +{ + "status": "pending", + "ticket_id": "2cf364bebf16", + "posicion": 1 +} +``` -`GET /api/v1/dc3/competencies/passports/result//` +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`. -- Al terminar: `status: "completed"` + `result`. +### Respuesta con caché (última hora, mismo passport) -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 | -|--------|-----| -| `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. | +```http +GET https://penasquito.wotbi.com/api/v1/dc3/competencies/passports/result// +Authorization: Token +``` -## 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 +``` + +**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//` 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*). diff --git a/lang/en.php b/lang/en.php index df4c407..019abf9 100644 --- a/lang/en.php +++ b/lang/en.php @@ -12,6 +12,7 @@ return [ 'lang_en' => 'English', 'lang_es' => 'Spanish', '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_intro' => 'Read-only references, verifications, and permissions. Links to corporate documentation where applicable.', 'frm_nom_related' => 'Related NOM competencies', @@ -26,8 +27,10 @@ return [ 'profile_green' => 'Green license', 'profile_green_yes' => 'Critical authorizations valid', 'profile_green_no' => 'Requirements pending', - 'profile_certs' => 'Certifications / DC3', + 'profile_certs' => 'Certifications', 'profile_auths' => 'FRM authorizations', + 'profile_company' => 'Company', + 'profile_no_competencies' => 'No competencies on record at the moment.', 'status_valid' => 'Valid', 'status_expiring' => 'Expiring soon', 'status_expired' => 'Expired', @@ -50,16 +53,23 @@ return [ 'issued' => 'Issued', 'sync_title' => 'Synchronization', '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_title' => 'DC3 API 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' => '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' => '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). 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_dc3_ready' => 'DC3 API enabled: passport lookups will call the service and store results locally.', - 'lookup_token_env' => 'Token from CERTIMINE_DC3_TOKEN.', + 'lookup_dc3_ready' => 'Passport lookup enabled: the configured base URL will be queried and results stored locally.', + 'lookup_token_env' => 'Token from environment (CERTIMINE_PENASQUITO_TOKEN or CERTIMINE_DC3_TOKEN).', '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_passport_hint' => 'Passports like E000055821 are normalized (case). Local DB is tried first; if no match and the API is configured, Wotbi is queried.', - 'dc3_lookup_error' => 'Could not load data from the DC3 API. Check passport, token, and network. Enable debug mode for technical details.', - '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.', + '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.', + '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.)', + 'lookup_pending_title' => 'The portal is processing your search', + '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.', ]; diff --git a/lang/es.php b/lang/es.php index b8063d7..efff3cf 100644 --- a/lang/es.php +++ b/lang/es.php @@ -12,6 +12,7 @@ return [ 'lang_en' => 'English', 'lang_es' => 'Español', '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_intro' => 'Consulta de referencias, verificaciones y permisos en modo lectura. Enlaces a documentación corporativa cuando aplique.', 'frm_nom_related' => 'Competencias NOM relacionadas', @@ -26,8 +27,10 @@ return [ 'profile_green' => 'Licencia verde', 'profile_green_yes' => 'Autorizaciones críticas vigentes', 'profile_green_no' => 'Pendiente de requisitos', - 'profile_certs' => 'Certificaciones / DC3', + 'profile_certs' => 'Certificaciones', 'profile_auths' => 'Autorizaciones FRM', + 'profile_company' => 'Empresa', + 'profile_no_competencies' => 'Sin competencias registradas en este momento.', 'status_valid' => 'Vigente', 'status_expiring' => 'Por vencer', 'status_expired' => 'Vencido', @@ -50,16 +53,23 @@ return [ 'issued' => 'Emitido', 'sync_title' => 'Sincronización', '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_title' => 'API DC3 no configurada', - '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' => '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 Peñasquito (documento) no configurado', + '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_dc3_ready' => 'API DC3 activo: las búsquedas por passport consultarán el servicio y guardarán el resultado aquí.', - 'lookup_token_env' => 'Token vía variable de entorno CERTIMINE_DC3_TOKEN.', + '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_PENASQUITO_TOKEN o CERTIMINE_DC3_TOKEN).', '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_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.', - '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.', - '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.', + '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.', + '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.)', + 'lookup_pending_title' => 'El portal está procesando su búsqueda', + '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.', ]; diff --git a/public/index.php b/public/index.php index 5bbf204..e765fe8 100644 --- a/public/index.php +++ b/public/index.php @@ -7,6 +7,7 @@ use CertiMine\Config; use CertiMine\I18n; use CertiMine\MobilisemeClient; use CertiMine\PenasquitoDc3Api; +use CertiMine\PenasquitoPendingException; use CertiMine\PersonRepository; use CertiMine\Security; use CertiMine\Util; @@ -38,12 +39,19 @@ try { case 'lookup': $error = null; + /** @var string|null */ + $lookupErrorDetail = null; + /** @var array{passport:string,ticket_id:string,status:string,posicion:?int}|null */ + $lookupPending = null; $result = null; - $lookupDc3Ok = PenasquitoDc3Api::isConfigured(); - $envTok = getenv('CERTIMINE_DC3_TOKEN'); - $lookupDc3Env = is_string($envTok) && $envTok !== ''; + $penasquitoApiOk = PenasquitoDc3Api::isConfigured(); + $envTok = getenv('CERTIMINE_PENASQUITO_TOKEN'); + if (!is_string($envTok) || trim($envTok) === '') { + $envTok = getenv('CERTIMINE_DC3_TOKEN'); + } + $penasquitoApiTokenFromEnv = is_string($envTok) && trim($envTok) !== ''; $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 (!Security::verifyCsrf($_POST['_csrf'] ?? null)) { $error = I18n::t('csrf_invalid'); @@ -82,7 +90,7 @@ try { $ptype = $type === 'contractor' || $isContractor ? 'contractor' : 'employee'; $pid = (string) ($apiRes['passport'] ?? $code); PenasquitoDc3Api::persistResult($pid, $apiRes, $ptype); - PersonRepository::logAudit('lookup_dc3_api', $ptype, $code); + PersonRepository::logAudit('lookup_penasquito_api', $ptype, $code); $ecode = (string) ($apiRes['passport'] ?? $code); $sig = Security::qrSignature($ptype, $ecode); header( @@ -92,10 +100,19 @@ try { ]) ); exit; + } catch (PenasquitoPendingException $pex) { + $lookupPending = [ + 'passport' => $pex->passport, + 'ticket_id' => $pex->ticketId, + 'status' => $pex->remoteStatus, + 'posicion' => $pex->posicion, + ]; } catch (Throwable $ex) { - $error = I18n::t('dc3_lookup_error'); - if (Config::debugMode()) { - $error .= ' — ' . $ex->getMessage(); + $error = I18n::t('penasquito_api_lookup_error'); + if ($ex instanceof \RuntimeException) { + $lookupErrorDetail = $ex->getMessage(); + } elseif (Config::debugMode()) { + $lookupErrorDetail = $ex->getMessage(); } } } else { diff --git a/sql/migrations/2026-05-13-penasquito-tickets.sql b/sql/migrations/2026-05-13-penasquito-tickets.sql new file mode 100644 index 0000000..f7a9f0b --- /dev/null +++ b/sql/migrations/2026-05-13-penasquito-tickets.sql @@ -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; diff --git a/sql/migrations/2026-05-13-users-cache-company.sql b/sql/migrations/2026-05-13-users-cache-company.sql new file mode 100644 index 0000000..06281ea --- /dev/null +++ b/sql/migrations/2026-05-13-users-cache-company.sql @@ -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; diff --git a/sql/schema.sql b/sql/schema.sql index 5008993..941b7b6 100644 --- a/sql/schema.sql +++ b/sql/schema.sql @@ -12,6 +12,7 @@ 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 penasquito_tickets; DROP TABLE IF EXISTS users_cache; DROP TABLE IF EXISTS nom_competency; DROP TABLE IF EXISTS frm_standard; @@ -57,12 +58,27 @@ CREATE TABLE users_cache ( mobiliseme_id VARCHAR(64) NOT NULL PRIMARY KEY, employee_number VARCHAR(64) NULL, display_name VARCHAR(255) NOT NULL, + company VARCHAR(255) 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; +-- Tickets pendientes del API Peñasquito (POST /search/ → GET /result//). +-- 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 ( id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, mobiliseme_id VARCHAR(64) NOT NULL, diff --git a/sql/seed.sql b/sql/seed.sql index deaabee..a582611 100644 --- a/sql/seed.sql +++ b/sql/seed.sql @@ -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); 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 LEFT JOIN frm_standard f ON f.code = 'FRM_ALTURAS' 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'); 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'); diff --git a/src/Auth.php b/src/Auth.php index fe1547f..17d50a7 100644 --- a/src/Auth.php +++ b/src/Auth.php @@ -28,7 +28,7 @@ final class Auth /** * @param array $profile - * @param array|null $dc3Result resultado completo del API DC3 (evita segunda llamada) + * @param array|null $dc3Result payload completo del API Peñasquito (documento); evita segunda llamada */ 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'); $emp = Util::arrayPath($profile, $empPath); $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 === '') { throw new \RuntimeException('Profile id missing'); } @@ -56,29 +61,33 @@ final class Auth 'name' => $name, 'type' => $type, 'employee_number' => $empStr, + 'company' => $company, 'token' => $token, ]; 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()) { try { PenasquitoDc3Api::persistResult($id, $dc3Result, $type); + return; } 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 { - if ($dc3Result === null || !PenasquitoDc3Api::isConfigured()) { - $certs = MobilisemeClient::fetchCertificates($id, $token); - PersonRepository::syncCertificatesFromApi($id, $certs); - } + $certs = MobilisemeClient::fetchCertificates($id, $token); + PersonRepository::syncCertificatesFromApi($id, $certs); } catch (\Throwable) { - // offline sync optional + // sincronización opcional offline } $frms = PersonRepository::authorizations($id); $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 diff --git a/src/MobilisemeClient.php b/src/MobilisemeClient.php index 61b287b..ae9ba3a 100644 --- a/src/MobilisemeClient.php +++ b/src/MobilisemeClient.php @@ -5,7 +5,7 @@ declare(strict_types=1); 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 { @@ -83,7 +83,7 @@ final class MobilisemeClient if (!is_array($comps)) { return []; } - return self::dc3CompetenciesToItems($mobilisemeId, $comps); + return self::penasquitoCompetenciesToItems($mobilisemeId, $comps); } if (!is_array($cfgConfig)) { return []; @@ -115,7 +115,7 @@ final class MobilisemeClient * @param list> $comps * @return list> */ - private static function dc3CompetenciesToItems(string $mobilisemeId, array $comps): array + private static function penasquitoCompetenciesToItems(string $mobilisemeId, array $comps): array { $items = []; foreach ($comps as $c) { @@ -179,11 +179,9 @@ final class MobilisemeClient $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); } @@ -219,13 +217,13 @@ final class MobilisemeClient { 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'))], + ['nom_code' => 'NOM-009', 'title' => 'Alturas (demo)', 'expires_at' => date('Y-m-d', strtotime('+300 days'))], + ['nom_code' => 'NOM-001', 'title' => 'Espacios confinados (demo)', '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'))], + ['nom_code' => 'NOM-009', 'title' => 'Alturas (demo)', 'expires_at' => date('Y-m-d', strtotime('+335 days'))], + ['nom_code' => 'NOM-017', 'title' => 'EPP (demo)', 'expires_at' => date('Y-m-d', strtotime('+100 days'))], ]; } } diff --git a/src/PenasquitoDc3Api.php b/src/PenasquitoDc3Api.php index 0ee8071..7f2bf85 100644 --- a/src/PenasquitoDc3Api.php +++ b/src/PenasquitoDc3Api.php @@ -5,22 +5,27 @@ 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). + * Cliente del API REST documentado (URL base penasquito.wotbi.com): POST /search/, GET /result/, GET /status/. + * 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 { public static function resolvedToken(): string { + $env = getenv('CERTIMINE_PENASQUITO_TOKEN'); + if (is_string($env) && trim($env) !== '') { + return trim($env); + } $env = getenv('CERTIMINE_DC3_TOKEN'); - if (is_string($env) && $env !== '') { + if (is_string($env) && trim($env) !== '') { return trim($env); } $cfg = Config::get('penasquito_dc3'); if (is_array($cfg)) { - $t = (string) ($cfg['static_token'] ?? ''); + $t = trim((string) ($cfg['static_token'] ?? '')); if ($t !== '') { - return trim($t); + return $t; } } return self::tokenFromSecretsFile(); @@ -44,7 +49,7 @@ final class PenasquitoDc3Api if (!is_array($data)) { 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); } @@ -56,19 +61,42 @@ final class PenasquitoDc3Api /** * 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// 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>,error:?string} + * @throws PenasquitoPendingException si el portal aún está procesando al terminar el polling local. */ public static function fetchResultForPassport(string $passport): array { 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); if ($passport === '') { 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); - return self::resolveSearchToResult($search); + return self::resolveSearchToResult($passport, $search); } public static function normalizePassport(string $passport): string @@ -87,18 +115,22 @@ final class PenasquitoDc3Api * @param array $search Respuesta del POST /search/ * @return array{passport:string,name:string,company:string,competencies:list>,error:?string} */ - private static function resolveSearchToResult(array $search): array + private static function resolveSearchToResult(string $passport, array $search): array { $status = strtolower((string) ($search['status'] ?? '')); + if ($status === 'completed') { $res = $search['result'] ?? null; if (!is_array($res)) { throw new \RuntimeException('Respuesta completed sin bloque result.'); } 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>,error:?string} $res */ return $res; } + if (in_array($status, ['pending', 'processing'], true)) { $ticket = self::ticketIdFromResponse($search); if ($ticket === '') { @@ -106,35 +138,71 @@ final class PenasquitoDc3Api 'Estado "' . $status . '" sin ticket_id. Claves: ' . implode(', ', array_keys($search)) ); } - $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'] ?? 40) : 40; - for ($i = 0; $i < $max; $i++) { - if ($i > 0) { - usleep((int) max(1, $pollS) * 1_000_000); - } - $r = self::ticketResult($ticket); - $st = strtolower((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>,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.'); + $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//). Si el portal sigue + * pending al terminar, lanza PenasquitoPendingException (el ticket queda guardado). + * + * @return array{passport:string,name:string,company:string,competencies:list>,error:?string} + */ + private static function pollTicketUntilCompleted( + string $passport, + string $ticketId, + string $lastStatus, + ?int $posicion + ): array { + $cfg = Config::get('penasquito_dc3'); + $pollS = is_array($cfg) ? max(1, (int) ($cfg['poll_interval_seconds'] ?? 2)) : 2; + $max = is_array($cfg) ? max(1, (int) ($cfg['poll_max_attempts'] ?? 3)) : 3; + + for ($i = 0; $i < $max; $i++) { + if ($i > 0) { + 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; + } + $st = strtolower((string) ($r['status'] ?? '')); + $lastStatus = $st !== '' ? $st : $lastStatus; + + if ($st === 'completed') { + $res = $r['result'] ?? null; + if (!is_array($res)) { + throw new \RuntimeException('Ticket completado sin bloque result.'); + } + self::assertResultOk($res); + PenasquitoTicketRepository::delete($passport); + /** @var array{passport:string,name:string,company:string,competencies:list>,error:?string} $out */ + $out = $res; + return $out; + } + if ($st !== 'pending' && $st !== 'processing') { + PenasquitoTicketRepository::markPolled($passport, $st, 'Estado inesperado'); + throw new \RuntimeException('Estado de ticket inesperado: ' . $st); + } + PenasquitoTicketRepository::markPolled($passport, $st); + } + + // Polling local agotado, pero el ticket sigue válido en el servidor. + throw new PenasquitoPendingException($passport, $ticketId, $lastStatus, $posicion); + } + /** @param array $r */ private static function ticketIdFromResponse(array $r): string { @@ -152,23 +220,31 @@ final class PenasquitoDc3Api * * @return array{token: string, profile: array} */ + /** + * Perfil mínimo para Auth::login y caché local (un solo round-trip al API). + * + * @return array{token: string, profile: array, dc3_result: array} + */ public static function loginWithPassport(string $passport): array { $result = self::fetchResultForPassport($passport); $tok = self::resolvedToken(); - $isContractor = self::guessContractorFromCompany((string) ($result['company'] ?? '')); + $company = (string) ($result['company'] ?? ''); + $isContractor = self::guessContractorFromCompany($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'] ?? ''), + 'company' => $company, ]; 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 */ @@ -177,21 +253,56 @@ final class PenasquitoDc3Api self::assertResultOk($result); $name = (string) ($result['name'] ?? '—'); $emp = (string) ($result['passport'] ?? $mobilisemeId); + $companyRaw = $result['company'] ?? null; + $company = is_string($companyRaw) ? trim($companyRaw) : null; + if ($company === '') { + $company = null; + } $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]); - } + + $pdo = Database::pdo(); + $started = !$pdo->inTransaction(); + if ($started) { + $pdo->beginTransaction(); + } + try { + PersonRepository::upsertCache($mobilisemeId, $emp, $name, $personType, false, $company); + + $items = self::competenciesToCertificatePayloads($mobilisemeId, $comps); + if ($items !== []) { + PersonRepository::applySyncPayload( + $mobilisemeId, + ['certificates' => $items], + 'penasquito_api' + ); + } + if ($personType === 'contractor') { + $auths = self::competenciesToAuthorizations($comps); + if ($auths !== []) { + PersonRepository::applySyncPayload( + $mobilisemeId, + ['authorizations' => $auths], + 'penasquito_api' + ); + } + } + + $frms = PersonRepository::authorizations($mobilisemeId); + $green = PersonRepository::recomputeGreenLicense($mobilisemeId, $personType, $frms); + PersonRepository::upsertCache($mobilisemeId, $emp, $name, $personType, $green, $company); + + if ($started) { + $pdo->commit(); + } + } catch (\Throwable $e) { + if ($started && $pdo->inTransaction()) { + $pdo->rollBack(); + } + throw $e; } - $frms = PersonRepository::authorizations($mobilisemeId); - $green = PersonRepository::recomputeGreenLicense($mobilisemeId, $personType, $frms); - PersonRepository::upsertCache($mobilisemeId, $emp, $name, $personType, $green); } /** @param array $result */ @@ -199,7 +310,7 @@ final class PenasquitoDc3Api { $err = $result['error'] ?? null; 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'); $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; - $resp = self::request('POST', $url, ['passport' => $passport]); + $resp = self::request('POST', $url, ['passport' => $passport], $passport); $j = $resp['json']; if (!is_array($j)) { $raw = substr(preg_replace('/\s+/', ' ', (string) $resp['raw']), 0, 240); 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); } + private static function ensureTrailingSlash(string $path): string + { + if ($path === '') { + return $path; + } + return str_ends_with($path, '/') ? $path : $path . '/'; + } + /** @param array $j */ private static function unwrapEnvelope(array $j): array { @@ -239,12 +358,12 @@ final class PenasquitoDc3Api $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); + $path = self::ensureTrailingSlash(str_replace('{ticket_id}', rawurlencode($ticketId), $tpl)); $resp = self::request('GET', $base . $path, null); $j = $resp['json']; if (!is_array($j)) { $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); } @@ -261,7 +380,7 @@ final class PenasquitoDc3Api } $cfg = Config::get('penasquito_dc3'); $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); $j = $resp['json']; return is_array($j) ? $j : []; @@ -269,9 +388,10 @@ final class PenasquitoDc3Api /** * @param array|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} */ - 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'); $timeout = is_array($dc3) ? (int) ($dc3['timeout_seconds'] ?? 30) : 30; @@ -291,6 +411,8 @@ final class PenasquitoDc3Api CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => $timeout, CURLOPT_HTTPHEADER => $headers, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_MAXREDIRS => 3, ]); if ($jsonBody !== null) { curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($jsonBody, JSON_UNESCAPED_UNICODE)); @@ -299,23 +421,122 @@ final class PenasquitoDc3Api $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); + $msg = self::buildHttpErrorMessage($status, (string) $raw, $contextPassport); + throw new \RuntimeException($msg); } $decoded = json_decode((string) $raw, true); 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 { return self::guessContractorFromCompany($company); @@ -358,7 +579,7 @@ final class PenasquitoDc3Api } $ext = 'dc3-' . md5($mobilisemeId . '|' . $activity . '|' . (string) $req); $row = [ - 'title' => $activity !== '' ? $activity : 'DC3', + 'title' => $activity !== '' ? $activity : 'Competencia', 'issued_at' => $issued, 'expires_at' => $expires, 'status' => $st, diff --git a/src/PenasquitoPendingException.php b/src/PenasquitoPendingException.php new file mode 100644 index 0000000..a273782 --- /dev/null +++ b/src/PenasquitoPendingException.php @@ -0,0 +1,32 @@ +/ 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); + } +} diff --git a/src/PenasquitoTicketRepository.php b/src/PenasquitoTicketRepository.php new file mode 100644 index 0000000..a775753 --- /dev/null +++ b/src/PenasquitoTicketRepository.php @@ -0,0 +1,89 @@ +/). + * + * 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(); + } +} diff --git a/src/PersonRepository.php b/src/PersonRepository.php index 9a8a047..1f2996a 100644 --- a/src/PersonRepository.php +++ b/src/PersonRepository.php @@ -8,21 +8,39 @@ use PDO; 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( string $mobilisemeId, ?string $employeeNumber, string $displayName, string $personType, - bool $greenLicense + bool $greenLicense, + ?string $company = null ): 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)' + 'INSERT INTO users_cache (mobiliseme_id, employee_number, display_name, company, person_type, green_license_flag) + VALUES (?,?,?,?,?,?) + ON DUPLICATE KEY UPDATE + 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|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 $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(); if (isset($payload['certificates']) && is_array($payload['certificates'])) { @@ -230,10 +249,10 @@ final class PersonRepository } $nomCode = (string) ($c['nom_code'] ?? ''); $nomId = self::nomIdByCode($nomCode); - $title = (string) ($c['title'] ?? 'DC3'); + $title = (string) ($c['title'] ?? 'Competencia'); $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)); + $ext = (string) ($c['external_ref'] ?? uniqid('sync-', true)); $frmCode = (string) ($c['frm_code'] ?? ''); $frmId = $frmCode !== '' ? self::frmIdByCode($frmCode) : null; $status = (string) ($c['status'] ?? 'valid'); @@ -259,10 +278,10 @@ final class PersonRepository $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") + VALUES (?,?,?,?) 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]); } } } diff --git a/src/bootstrap.php b/src/bootstrap.php index cdec4ec..79ecd75 100644 --- a/src/bootstrap.php +++ b/src/bootstrap.php @@ -9,6 +9,8 @@ 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/PenasquitoTicketRepository.php'; +require_once $base . '/src/PenasquitoPendingException.php'; require_once $base . '/src/PenasquitoDc3Api.php'; require_once $base . '/src/MobilisemeClient.php'; require_once $base . '/src/Auth.php'; diff --git a/views/home.php b/views/home.php index 12b5211..f622e6e 100644 --- a/views/home.php +++ b/views/home.php @@ -21,7 +21,7 @@ require __DIR__ . '/partials/header.php';

shield_person Mobiliseme

-

— DC3 / competencias vinculadas.

+

diff --git a/views/lookup.php b/views/lookup.php index 6e9cab2..ab1f09d 100644 --- a/views/lookup.php +++ b/views/lookup.php @@ -7,17 +7,19 @@ use CertiMine\Security; use CertiMine\Util; /** @var string|null $error */ -/** @var bool $lookupDc3Ok */ -/** @var bool $lookupDc3Env */ +/** @var string|null $lookupErrorDetail */ +/** @var array{passport:string,ticket_id:string,status:string,posicion:?int}|null $lookupPending */ +/** @var bool $penasquitoApiOk */ +/** @var bool $penasquitoApiTokenFromEnv */ /** @var bool $lookupUsingExample */ -/** @var string $lookupDc3Base */ +/** @var string $penasquitoApiBaseUrl */ require __DIR__ . '/partials/header.php'; ?>

- +
warning
@@ -31,8 +33,8 @@ require __DIR__ . '/partials/header.php'; cloud_done - - — — + + — —
@@ -41,8 +43,38 @@ require __DIR__ . '/partials/header.php';
+ +
+
+ hourglass_top + +
+

+
    +
  • :
  • +
  • :
  • +
  • : · :
  • +
+
+ + + + +
+
+ + -
+
+ + +
+
+ +
diff --git a/views/profile_public.php b/views/profile_public.php index b30ce89..675b233 100644 --- a/views/profile_public.php +++ b/views/profile_public.php @@ -32,6 +32,14 @@ $statusLabel = static function (string $s): string { ·

+ + +

+ apartment + : + +

+
@@ -52,7 +60,7 @@ $statusLabel = static function (string $s): string { - +