Bläddra i källkod

Release v1.1.0 — suppression MODX, packs v2, analytics, excel, OutboxStorage

augustin.podvin 8 månader sedan
förälder
incheckning
38c59f48e3
51 ändrade filer med 556 tillägg och 2564 borttagningar
  1. 3 0
      .gitignore
  2. 0 1
      README.md
  3. 1 0
      config/config.php
  4. 1 2
      docs/DOC.md
  5. 0 281
      docs/MODX_INTEGRATION.md
  6. 87 0
      docs/RELEASE.md
  7. 2 3
      docs/SECURITY.md
  8. 0 17
      modx/chunks/ae_cost_hidden.html
  9. 0 36
      modx/chunks/ae_cta_unlocked.html
  10. 0 22
      modx/chunks/ae_optional.html
  11. 0 9
      modx/chunks/ae_optional_field.html
  12. 0 13
      modx/chunks/ae_optional_radio.html
  13. 0 12
      modx/chunks/ae_pack_card.html
  14. 0 10
      modx/chunks/ae_pillar_row.html
  15. 0 12
      modx/chunks/ae_question_option.html
  16. 0 52
      modx/chunks/ae_quiz.html
  17. 0 14
      modx/chunks/ae_quiz_progress.html
  18. 0 50
      modx/chunks/ae_results.html
  19. 0 7
      modx/chunks/ae_risk_item.html
  20. 0 18
      modx/chunks/ae_select_pack.html
  21. 0 38
      modx/chunks/ae_unlock_gate.html
  22. 0 7
      modx/chunks/ae_win_item.html
  23. 0 68
      modx/model/audit_express/auditrequest.class.php
  24. 0 5
      modx/model/audit_express/mysql/auditrequest.class.php
  25. 0 125
      modx/model/audit_express/mysql/auditrequest.map.inc.php
  26. 0 60
      modx/plugins/AuditExpress_Init.php
  27. 0 620
      modx/preview-chunks.html
  28. 0 49
      modx/schema/audit_express.mysql.schema.xml
  29. 0 21
      modx/setup/create_tables.sql
  30. 0 108
      modx/setup/install.php
  31. 0 111
      modx/snippets/AuditExpress_Optional.php
  32. 0 67
      modx/snippets/AuditExpress_PDF.php
  33. 0 159
      modx/snippets/AuditExpress_Quiz.php
  34. 0 175
      modx/snippets/AuditExpress_Results.php
  35. 0 126
      modx/snippets/AuditExpress_SelectPack.php
  36. 0 68
      modx/templates/AuditExpress_Base.html
  37. 0 61
      modx/templates/AuditExpress_Landing.html
  38. 0 36
      modx/templates/AuditExpress_Quiz.html
  39. 0 36
      modx/templates/AuditExpress_Results.html
  40. 53 0
      public/api/analytics-debug.php
  41. 7 3
      public/api/email.php
  42. 59 0
      public/api/excel-complete.php
  43. 2 18
      public/api/notify.php
  44. 8 4
      public/api/pdf.php
  45. 12 8
      public/api/score.php
  46. 3 3
      public/assets/css/app.css
  47. 66 0
      public/assets/js/app.js
  48. 53 0
      scripts/release.sh
  49. 20 26
      src/AdminNotifier.php
  50. 46 3
      src/Analytics.php
  51. 133 0
      src/OutboxStorage.php

+ 3 - 0
.gitignore

@@ -19,6 +19,9 @@ composer-setup.php
 *.docx
 *.txt
 
+# Exports OVH (données sensibles)
+ovh-*-export.csv
+
 # Environnement local
 .env
 .env.local

+ 0 - 1
README.md

@@ -18,4 +18,3 @@ php -S 127.0.0.1:8000 -t public
 |---------|---------|
 | **docs/DOC.md** | Documentation complète (structure, déploiement, config) |
 | **docs/SECURITY.md** | Sécurité et bonnes pratiques |
-| **docs/MODX_INTEGRATION.md** | Intégration MODX |

+ 1 - 0
config/config.php

@@ -20,6 +20,7 @@ return [
         'score'  => ['requests' => 30, 'window' => 60],   // 30 req/min
         'pdf'    => ['requests' => 20, 'window' => 60],   // 20 req/min
         'email'  => ['requests' => 10, 'window' => 60],   // 10 req/min
+        'excel_complete' => ['requests' => 20, 'window' => 60],   // 20 req/min
     ],
     'allowed_notify_tools' => ['process-mapper'],  // Liste blanche pour notify.php
 

+ 1 - 2
docs/DOC.md

@@ -38,7 +38,6 @@ audit express self/
 │   ├── api/
 │   └── assets/
 ├── docs/             Documentation
-├── modx/             Intégration MODX (optionnel)
 ├── composer.json
 └── README.md
 ```
@@ -115,4 +114,4 @@ Racine FTP/
 | Fichier | Contenu |
 |---------|---------|
 | **docs/SECURITY.md** | Checklist sécurité, bonnes pratiques |
-| **docs/MODX_INTEGRATION.md** | Intégration dans MODX (templates, snippets, BD) |
+| **docs/RELEASE.md** | Procédure de release Git et déploiement serveur |

+ 0 - 281
docs/MODX_INTEGRATION.md

@@ -1,281 +0,0 @@
-# Intégration MODX - Audit Express Self
-
-Architecture complète : xPDO en BD + templates/chunks/snippets MODX.
-
----
-
-## Vue d'ensemble de l'architecture
-
-```
-MODX Resource          Template                    Snippet appelé
-─────────────────────  ──────────────────────────  ──────────────────────────────
-/controle-technique/   AuditExpress_Landing        (contenu statique dans la ressource)
-/ct/choix-du-pack/     AuditExpress_Base           [[!AuditExpress_SelectPack]]
-/ct/quiz/              AuditExpress_Quiz           [[!AuditExpress_Quiz]]
-/ct/optional/          AuditExpress_Quiz           [[!AuditExpress_Optional]]
-/ct/resultats/         AuditExpress_Results        [[!AuditExpress_Results]]
-/ct/pdf/               AuditExpress_Results        [[!AuditExpress_PDF]]
-```
-
-**Objet BD** : `AuditRequest` (table `{prefix}audit_requests`) - créé dès le choix du pack, mis à jour à chaque réponse, finalisé avec le score au moment des résultats.
-
----
-
-## 1. Déploiement des fichiers
-
-```
-core/components/audit_express/
-├── model/
-│   └── audit_express/
-│       ├── auditrequest.class.php           ← classe xPDO base
-│       └── mysql/
-│           ├── auditrequest.class.php       ← pilote MySQL
-│           └── auditrequest.map.inc.php     ← map de colonnes
-├── src/                                     ← classes PHP existantes
-│   ├── Engine.php
-│   ├── PackRepository.php
-│   ├── RulesRepository.php
-│   ├── PdfRenderer.php
-│   └── LogMailer.php
-├── config/                                  ← packs JSON existants
-│   ├── pack-onboarding-v1.json
-│   └── packs/…
-├── templates/
-│   └── pdf_a4.php                           ← template PDF existant
-└── schema/
-    └── audit_express.mysql.schema.xml
-
-assets/components/audit_express/
-├── css/app.css
-└── js/ae-base.js                            ← JS minimal (auto-avance radio)
-```
-
-Copier les dossiers source :
-```bash
-cp -r src/          core/components/audit_express/src/
-cp -r config/       core/components/audit_express/config/
-cp -r templates/    core/components/audit_express/templates/
-cp    vendor/       core/components/audit_express/vendor/   # Dompdf
-cp    public/assets/css/app.css   assets/components/audit_express/css/
-```
-
----
-
-## 2. Base de données
-
-**Option A - Script automatique** (recommandé) :
-```bash
-php modx/setup/install.php
-```
-
-**Option B - SQL manuel** :
-```sql
--- Ouvrir modx/setup/create_tables.sql, remplacer modx_ par votre préfixe, exécuter.
-```
-
-Colonnes de `audit_requests` :
-
-| Colonne         | Type                              | Rôle |
-|-----------------|-----------------------------------|------|
-| `id`            | INT PK AUTO_INCREMENT             | Clé interne |
-| `audit_uid`     | VARCHAR(36) UNIQUE                | UUID public (URL résultats, PDF) |
-| `pack_id`       | VARCHAR(64)                       | onboarding-v1, validation-facture… |
-| `answers`       | TEXT (JSON)                       | `{"q1":"q1_3","q2":"q2_dk",…}` |
-| `optional_data` | TEXT (JSON)                       | Volume mensuel, coût horaire… |
-| `result`        | MEDIUMTEXT (JSON)                 | Score, piliers, risques, quick wins |
-| `email`         | VARCHAR(255) nullable             | Saisi lors du déblocage |
-| `status`        | ENUM draft/completed/emailed      | État du cycle de vie |
-| `ip_hash`       | VARCHAR(64) nullable              | sha256(IP) - RGPD, pas d'IP en clair |
-| `step`          | TINYINT                           | Index de la question en cours |
-| `created_at`    | DATETIME                          | - |
-| `updated_at`    | DATETIME                          | Mis à jour automatiquement |
-
----
-
-## 3. System Settings (Gestionnaire → Paramètres système → namespace `audit_express`)
-
-| Clé                    | Valeur à renseigner         |
-|------------------------|-----------------------------|
-| `ae.core_path`         | `{core_path}components/audit_express/` |
-| `ae.resource.landing`  | ID ressource landing        |
-| `ae.resource.select`   | ID ressource choix du pack  |
-| `ae.resource.quiz`     | ID ressource quiz           |
-| `ae.resource.optional` | ID ressource optional       |
-| `ae.resource.results`  | ID ressource résultats      |
-| `ae.resource.pdf`      | ID ressource PDF download   |
-| `ae.booking_url`       | Lien Cal.com / réservation  |
-| `ae.devis_url`         | URL ou mailto devis         |
-
----
-
-## 4. Plugin
-
-Créer un plugin **AuditExpress_Init** avec le code de `modx/plugins/AuditExpress_Init.php`.
-
-Événements à cocher :
-- `OnMODXInit` (priorité **1** - avant tout)
-- `OnHandleRequest`
-
----
-
-## 5. Templates
-
-Importer dans Gestionnaire → Éléments → Templates :
-
-| Fichier source                              | Nom dans MODX               |
-|---------------------------------------------|-----------------------------|
-| `modx/templates/AuditExpress_Landing.html`  | `AuditExpress_Landing`      |
-| `modx/templates/AuditExpress_Base.html`     | `AuditExpress_Base`         |
-| `modx/templates/AuditExpress_Quiz.html`     | `AuditExpress_Quiz`         |
-| `modx/templates/AuditExpress_Results.html`  | `AuditExpress_Results`      |
-
----
-
-## 6. Chunks
-
-Importer dans Gestionnaire → Éléments → Chunks :
-
-```
-ae_pack_card          modx/chunks/ae_pack_card.html
-ae_select_pack        modx/chunks/ae_select_pack.html
-ae_quiz_progress      modx/chunks/ae_quiz_progress.html
-ae_question_option    modx/chunks/ae_question_option.html
-ae_quiz               modx/chunks/ae_quiz.html
-ae_optional_field     modx/chunks/ae_optional_field.html
-ae_optional_radio     modx/chunks/ae_optional_radio.html
-ae_optional           modx/chunks/ae_optional.html
-ae_pillar_row         modx/chunks/ae_pillar_row.html
-ae_risk_item          modx/chunks/ae_risk_item.html
-ae_win_item           modx/chunks/ae_win_item.html
-ae_cost_hidden        modx/chunks/ae_cost_hidden.html
-ae_unlock_gate        modx/chunks/ae_unlock_gate.html
-ae_cta_unlocked       modx/chunks/ae_cta_unlocked.html
-ae_results            modx/chunks/ae_results.html
-```
-
----
-
-## 7. Snippets
-
-Importer dans Gestionnaire → Éléments → Snippets (tous en **uncached** `[[!…]]`) :
-
-```
-AuditExpress_SelectPack    modx/snippets/AuditExpress_SelectPack.php
-AuditExpress_Quiz          modx/snippets/AuditExpress_Quiz.php
-AuditExpress_Optional      modx/snippets/AuditExpress_Optional.php
-AuditExpress_Results       modx/snippets/AuditExpress_Results.php
-AuditExpress_PDF           modx/snippets/AuditExpress_PDF.php
-```
-
----
-
-## 8. Ressources MODX à créer
-
-### Landing (`/controle-technique/`)
-- Template : `AuditExpress_Landing`
-- Contenu : HTML statique (copier le body de `public/index.php`), le bouton "Lancer" pointe vers `/ct/choix-du-pack/`
-
-### Choix du pack (`/ct/choix-du-pack/`)
-- Template : `AuditExpress_Base`
-- Contenu :
-```
-[[!AuditExpress_SelectPack?
-  &quiz_resource_id=`[[++ae.resource.quiz]]`
-  &landing_resource_id=`[[++ae.resource.landing]]`
-]]
-```
-
-### Quiz (`/ct/quiz/`)
-- Template : `AuditExpress_Quiz`
-- Contenu :
-```
-[[!AuditExpress_Quiz?
-  &select_resource_id=`[[++ae.resource.select]]`
-  &optional_resource_id=`[[++ae.resource.optional]]`
-]]
-```
-
-### Optionnel (`/ct/optional/`)
-- Template : `AuditExpress_Quiz`
-- Contenu :
-```
-[[!AuditExpress_Optional?
-  &quiz_resource_id=`[[++ae.resource.quiz]]`
-  &results_resource_id=`[[++ae.resource.results]]`
-]]
-```
-
-### Résultats (`/ct/resultats/`)
-- Template : `AuditExpress_Results`
-- Contenu :
-```
-[[!AuditExpress_Results?
-  &select_resource_id=`[[++ae.resource.select]]`
-  &booking_url=`[[++ae.booking_url]]`
-  &devis_url=`[[++ae.devis_url]]`
-]]
-```
-
-### PDF (`/ct/pdf/`)
-- Template : `AuditExpress_Base` (ou vide)
-- Contenu : `[[!AuditExpress_PDF? &booking_url=`[[++ae.booking_url]]`]]`
-- Cocher "Ne pas mettre en cache"
-
----
-
-## 9. Flux de données complet
-
-```
-[Landing] → [Choix pack]
-                ↓ POST ae_action=select_pack
-           Crée AuditRequest (BD) → session ae_audit_uid
-                ↓ redirect
-            [Quiz Q1]
-                ↓ POST ae_action=ae_answer (x20)
-           Met à jour AuditRequest.answers + step (BD)
-                ↓ redirect (PRG) - question suivante
-            [Optional]
-                ↓ POST ae_action=ae_optional
-           Engine::compute() → AuditRequest.result + status=completed (BD)
-                ↓ redirect ?audit=<uid>
-            [Résultats]
-           Score + risques toujours visibles
-           Gate email → POST ae_action=ae_capture_email
-                ↓ AuditRequest.email + status=emailed (BD) + PDF généré
-                ↓ redirect ?audit=<uid>&unlocked=1
-           Quick wins + CTAs débloqués
-                ↓ lien /ct/pdf/?audit=<uid>
-            [PDF]
-           Téléchargement direct
-```
-
----
-
-## 10. RGPD & purge
-
-La purge des données doit être exécutée régulièrement (cron ou tâche planifiée).
-
-### Cron Linux (exemple)
-
-```cron
-# Purge RGPD - 1er jour du mois à 3h (adapter USER, PASS, BASE_MODX)
-0 3 1 * * mysql -u USER -pPASS BASE_MODX -e "DELETE FROM modx_audit_requests WHERE status='draft' AND created_at < DATE_SUB(NOW(), INTERVAL 7 DAY); DELETE FROM modx_audit_requests WHERE status IN ('completed','emailed') AND created_at < DATE_SUB(NOW(), INTERVAL 90 DAY);" >> /var/log/purge-audit.log 2>&1
-```
-
-### SQL à exécuter (ou via script shell)
-
-```sql
-DELETE FROM modx_audit_requests
-WHERE status = 'draft' AND created_at < DATE_SUB(NOW(), INTERVAL 7 DAY);
-
-DELETE FROM modx_audit_requests
-WHERE status IN ('completed','emailed') AND created_at < DATE_SUB(NOW(), INTERVAL 90 DAY);
-```
-
----
-
-## 11. Email (V1 → production)
-
-La V1 stocke les emails dans `storage/outbox/` via `LogMailer`.  
-Pour passer en production, créer une classe `SmtpMailer` implémentant `AuditExpress\MailerInterface`
-et l'injecter dans `AuditExpress_Results.php` à la place de `LogMailer`.

+ 87 - 0
docs/RELEASE.md

@@ -0,0 +1,87 @@
+# Procédure de release et déploiement
+
+## 1. Préparer une nouvelle version (Git Bash)
+
+### Avant de committer
+
+- [ ] Vérifier que `config.local.php` n’est pas inclus (ignoré par git)
+- [ ] Tester en local : `php -S 127.0.0.1:8000 -t public`
+- [ ] Vérifier que les exports OVH (`ovh-*-export.csv`) ne sont pas trackés
+
+### Commit et tag
+
+```bash
+# 1. Ajouter les fichiers (hors .gitignore)
+git add .
+git status   # Vérifier avant commit
+
+# 2. Commit
+git commit -m "Release v1.1.0 — description des changements"
+
+# 3. Créer le tag (ou utiliser le script)
+git tag -a v1.1.0 -m "Release v1.1.0"
+
+# 4. Pousser
+git push origin master
+git push origin v1.1.0
+```
+
+**Alternative : script release**
+
+```bash
+./scripts/release.sh 1.1.0
+# Puis : git push origin master && git push origin v1.1.0
+```
+
+---
+
+## 2. Déploiement serveur (FileZilla / FTP)
+
+### Prérequis
+
+- Compte FTP OVH (host, user, password)
+- `config.local.php` déjà présent sur le serveur (ne pas l’écraser)
+
+### Checklist déploiement
+
+| Étape | Action |
+|-------|--------|
+| 1 | `composer install --no-dev --ignore-platform-req=ext-mbstring` (si dépendances modifiées) |
+| 2 | Envoyer `config/` → racine FTP (sans écraser `config.local.php`) |
+| 3 | Envoyer `src/` → racine |
+| 4 | Envoyer `templates/` → racine |
+| 5 | Envoyer `vendor/` → racine |
+| 6 | Envoyer contenu de `public/` → `www/` |
+
+### Structure sur OVH
+
+```
+Racine FTP/
+├── config/
+│   ├── config.php
+│   └── config.local.php   ← Ne pas écraser
+├── src/
+├── templates/
+├── vendor/
+├── storage/               ← Créé auto par l'app (outbox, logs, etc.)
+└── www/
+    ├── index.php
+    ├── api/
+    └── assets/
+```
+
+### Après déploiement
+
+- [ ] Tester l’URL de production
+- [ ] Vérifier un parcours complet : landing → pack → quiz → résultats → PDF
+- [ ] Vérifier que `storage/` est accessible en écriture (chmod 755 ou 775)
+
+---
+
+## 3. Numérotation des versions
+
+- **MAJOR** (1.x.x) : changement majeur, rupture de compatibilité
+- **MINOR** (x.1.x) : nouvelles fonctionnalités, packs, endpoints
+- **PATCH** (x.x.1) : corrections, ajustements, doc
+
+Exemple : v1.0.0 → v1.1.0 pour ajout des packs v2 et endpoints analytics/excel.

+ 2 - 3
docs/SECURITY.md

@@ -58,6 +58,5 @@
 
 ## Données sensibles (RGPD)
 
-- Emails et réponses stockés dans `storage/outbox/` (V1 pseudo) ou base MODX
-- Purge recommandée : voir `docs/MODX_INTEGRATION.md` section 10 pour le cron de purge
-- Pas d'IP en clair : `ip_hash` (sha256) uniquement côté MODX
+- Emails et réponses stockés dans `storage/outbox/` (V1 pseudo)
+- Purge recommandée : nettoyer périodiquement `storage/outbox/` selon votre politique de rétention

+ 0 - 17
modx/chunks/ae_cost_hidden.html

@@ -1,17 +0,0 @@
-<!-- Chunk : ae_cost_hidden
-     Placeholders : [[+hours_per_month]] [[+eur_per_month]]
--->
-<div class="cost-block">
-  <div class="h2">Coût caché estimé</div>
-  <div class="cost-figures">
-    <div class="cost-fig">
-      <span class="val">[[+hours_per_month]] h</span>
-      <span class="lbl">par mois (estimé)</span>
-    </div>
-    <div class="cost-fig">
-      <span class="val">~[[+eur_per_month]] €</span>
-      <span class="lbl">par mois (indicatif)</span>
-    </div>
-  </div>
-  <p class="hint">Estimation indicative, à valider par mesure réelle.</p>
-</div>

+ 0 - 36
modx/chunks/ae_cta_unlocked.html

@@ -1,36 +0,0 @@
-<!-- Chunk : ae_cta_unlocked
-     Affiché après la capture email (email débloqué).
-     Placeholders : [[+booking_url]] [[+devis_url]] [[+select_url]] [[+action_url]] [[+audit_uid]] [[+email]]
--->
-<div class="unlocked-ctas">
-  <div class="unlocked-ctas__inner">
-
-    <div class="h2" style="margin-bottom:6px">Et maintenant ?</div>
-    <p class="lead" style="margin-bottom:24px">
-      Votre diagnostic révèle des opportunités concrètes. Réservez un entretien offert avec un consultant pour les prioriser et définir votre plan d'action.
-    </p>
-
-    <div class="cta-block">
-      [[+booking_url:notempty=`<div style="display:flex;flex-direction:column;align-items:center;width:100%"><span class="cta-offert">30 min offert</span><a class="btn btn--primary btn--cta-main" href="[[+booking_url]]" target="_blank" rel="noreferrer">Découvrir les opportunités suite à mon audit - Entretien de 30 min offert avec un consultant</a></div>`]]
-      [[+devis_url:notempty=`<a class="btn btn--outline btn--cta-secondary" href="[[+devis_url]]">Demander un devis</a>`]]
-    </div>
-
-    <p class="hint" style="text-align:center;margin-top:10px">
-      Pas d'engagement. On analyse vos résultats ensemble et on vous propose une solution adaptée.
-    </p>
-
-    <hr style="border:none;border-top:1px solid var(--border,#e2e8f0);margin:24px 0">
-
-    <div class="btnrow" style="justify-content:center;gap:10px">
-      <!-- Téléchargement PDF direct -->
-      <a class="btn btn--outline"
-         href="[[+action_url:replace=`resultats==pdf`]]?audit=[[+audit_uid]]">
-        Télécharger mon PDF
-      </a>
-      <a class="btn btn--outline" href="[[+select_url]]" style="font-size:13px">
-        Diagnostiquer un autre process
-      </a>
-    </div>
-
-  </div>
-</div>

+ 0 - 22
modx/chunks/ae_optional.html

@@ -1,22 +0,0 @@
-<!-- Chunk : ae_optional
-     Placeholders : [[+fields]] [[+action_url]] [[+quiz_url]] [[+audit_uid]]
--->
-<div class="grid">
-  <div class="card">
-    <span class="tag tag--new" style="margin-bottom:12px;display:inline-block">Optionnel</span>
-    <h1 class="h1">Quelques infos pour le coût caché</h1>
-    <p class="lead">Ces données servent uniquement à estimer le coût caché en heures/mois (indicatif). Vous pouvez passer directement.</p>
-
-    <form method="POST" action="[[+action_url]]">
-      <input type="hidden" name="ae_action"  value="ae_optional">
-      <input type="hidden" name="audit_uid"  value="[[+audit_uid]]">
-
-      [[+fields]]
-
-      <div class="btnrow" style="margin-top:20px">
-        <a href="[[+quiz_url]]" class="btn btn--outline">← Retour au quiz</a>
-        <button type="submit" class="btn btn--primary">Voir mes résultats →</button>
-      </div>
-    </form>
-  </div>
-</div>

+ 0 - 9
modx/chunks/ae_optional_field.html

@@ -1,9 +0,0 @@
-<!-- Chunk : ae_optional_field
-     Placeholders : [[+label]] [[+radios]]
--->
-<div class="field">
-  <label>[[+label]]</label>
-  <div class="options" style="margin-top:6px">
-    [[+radios]]
-  </div>
-</div>

+ 0 - 13
modx/chunks/ae_optional_radio.html

@@ -1,13 +0,0 @@
-<!-- Chunk : ae_optional_radio
-     Placeholders : [[+key]] [[+value]] [[+label]] [[+checked]]
--->
-<label class="opt" for="opt_[[+key]]_[[+value]]">
-  <input
-    id="opt_[[+key]]_[[+value]]"
-    type="radio"
-    name="opt_[[+key]]"
-    value="[[+value]]"
-    [[+checked]]
-  >
-  <div><strong>[[+label]]</strong></div>
-</label>

+ 0 - 12
modx/chunks/ae_pack_card.html

@@ -1,12 +0,0 @@
-<!-- Chunk : ae_pack_card
-     Placeholders : [[+pack_id]] [[+title]] [[+desc]] [[+tag]] [[+tag_class]] [[+action_url]]
--->
-<form method="POST" action="[[+action_url]]" style="display:contents">
-  <input type="hidden" name="ae_action" value="select_pack">
-  <input type="hidden" name="pack_id" value="[[+pack_id]]">
-  <button type="submit" class="pack-card" style="width:100%;text-align:left;cursor:pointer;background:none;border:none;padding:0">
-    <span class="tag [[+tag_class]]">[[+tag]]</span>
-    <div class="title" style="margin-top:8px">[[+title]] <span class="arrow">→</span></div>
-    <div class="desc">[[+desc]]</div>
-  </button>
-</form>

+ 0 - 10
modx/chunks/ae_pillar_row.html

@@ -1,10 +0,0 @@
-<!-- Chunk : ae_pillar_row
-     Placeholders : [[+label]] [[+score]] [[+max]] [[+pct]]
--->
-<div class="pRow">
-  <div class="name">[[+label]]</div>
-  <div class="val">[[+score]]/[[+max]]</div>
-  <div class="bar">
-    <div style="width:[[+pct]]%"></div>
-  </div>
-</div>

+ 0 - 12
modx/chunks/ae_question_option.html

@@ -1,12 +0,0 @@
-
-<label class="opt" for="opt_[[+alias]]">
-  <input
-    id="[[+id]]"
-    type="radio"
-    name="option_id"
-    value="[[+alias]]"
-    data-question-id="[[+id]]"
-    class="ae-radio-auto"
-  >
-  <div><strong>[[+pagetitle]]</strong></div>
-</label>

+ 0 - 52
modx/chunks/ae_quiz.html

@@ -1,52 +0,0 @@
-<!-- Chunk : ae_quiz
-     Placeholders : [[+progress]] [[+question_id]] [[+question]] [[+help]] [[+options]]
-                    [[+action_url]] [[+select_url]] [[+audit_uid]]
-                    [[+can_prev]] [[+can_next]] [[+btn_next]] [[+btn_class]]
--->
-<div class="grid">
-  <div class="card">
-    [[+progress]]
-
-    <form method="POST" action="[[+action_url]]" id="ae-quiz-form">
-      <input type="hidden" name="ae_action"   value="ae_answer">
-      <input type="hidden" name="audit_uid"   value="[[+audit_uid]]">
-      <input type="hidden" name="question_id" value="[[+question_id]]">
-
-      <div class="qTitle">[[+question]]</div>
-      [[+help]]
-
-      <div class="options" id="ae-options">
-        [[+options]]
-      </div>
-
-      <div class="btnrow" style="margin-top:18px">
-        <!-- Bouton Précédent via formulaire séparé (évite les conflits de submit) -->
-        <button type="submit" form="ae-prev-form" class="btn btn--outline" [[+can_prev]]>← Précédent</button>
-        <button type="submit" class="btn [[+btn_class]]" [[+can_next]] id="ae-btn-next">[[+btn_next]]</button>
-      </div>
-      <p class="hint" style="margin-top:10px">Vous pouvez modifier vos réponses avant la fin.</p>
-    </form>
-
-    <!-- Formulaire précédent (soumission indépendante) -->
-    <form method="POST" action="[[+action_url]]" id="ae-prev-form" style="display:none">
-      <input type="hidden" name="ae_action" value="ae_prev">
-      <input type="hidden" name="audit_uid" value="[[+audit_uid]]">
-    </form>
-  </div>
-</div>
-
-<!-- Auto-avance au clic radio (380 ms, comme la version JS SPA) -->
-<script>
-(function () {
-  var form = document.getElementById('ae-quiz-form');
-  var opts = document.getElementById('ae-options');
-  if (!form || !opts) return;
-  opts.addEventListener('change', function (e) {
-    if (e.target && e.target.type === 'radio') {
-      var btn = document.getElementById('ae-btn-next');
-      if (btn) btn.removeAttribute('disabled');
-      setTimeout(function () { form.submit(); }, 380);
-    }
-  });
-})();
-</script>

+ 0 - 14
modx/chunks/ae_quiz_progress.html

@@ -1,14 +0,0 @@
-<div class="quizHead">
-  <span class="tag" style="font-size:11px">[[+pagetitle]]</span>
-  <div class="quizStep">
-    <strong class="js-pos"></strong><span class="js-total"></span>
-  </div>
-</div>
-<div class="progressWrap">
-  <div class="progress">
-    <div class="js-bar" style="width:0%"></div>
-  </div>
-  <div class="progressMeta">
-    <span class="progressPct js-pct">0&nbsp;%</span>
-  </div>
-</div>

+ 0 - 50
modx/chunks/ae_results.html

@@ -1,50 +0,0 @@
-<!-- Chunk : ae_results
-     Placeholders : [[+pack_title]] [[+score_total]] [[+level]] [[+level_label]]
-                    [[+dot_color]] [[+confidence]] [[+pillars_html]]
-                    [[+risks_html]] [[+wins_html]] [[+cost_html]] [[+gate_html]] [[+unlocked]]
--->
-<div class="grid">
-
-  <!-- Carte score global -->
-  <div class="card">
-    <div style="display:flex;align-items:center;gap:10px;margin-bottom:16px">
-      <span class="tag">[[+pack_title]]</span>
-    </div>
-    <div class="scoreBox">
-      <div>
-        <div class="scoreLabel">Score global</div>
-        <div class="scoreBig">[[+score_total]]/100</div>
-        <div class="level-badge" style="margin-top:10px">
-          <span class="level-dot" style="background:[[+dot_color]]"></span>
-          <span>[[+level]] - [[+level_label]]</span>
-        </div>
-        <div class="confidence">Confiance du diagnostic : [[+confidence]]</div>
-      </div>
-    </div>
-    <div class="pillars">
-      [[+pillars_html]]
-    </div>
-  </div>
-
-  <!-- 3 risques probables (toujours visibles) -->
-  <div class="card">
-    <div class="h2">3 risques probables</div>
-    [[+risks_html:notempty=`<ol class="list">[[+risks_html]]</ol>`:else=`<p class="muted small">Aucun risque majeur détecté.</p>`]]
-  </div>
-
-  <!-- Coût caché (si calculé) -->
-  [[+cost_html]]
-
-  <!-- Gate email OU CTAs débloqués -->
-  [[+gate_html]]
-
-  <!-- Quick wins (uniquement si débloqué) -->
-  [[+wins_html:notempty=`
-  <div class="card">
-    <div class="h2">5 quick wins prioritaires</div>
-    <ol class="list">[[+wins_html]]</ol>
-    <p class="hint" style="margin-top:8px">Le PDF contient les 5 actions avec détail effort/impact.</p>
-  </div>
-  `]]
-
-</div>

+ 0 - 7
modx/chunks/ae_risk_item.html

@@ -1,7 +0,0 @@
-<!-- Chunk : ae_risk_item
-     Placeholders : [[+title]] [[+what_happens]]
--->
-<li>
-  <strong>[[+title]]</strong>
-  <div class="hint">[[+what_happens]]</div>
-</li>

+ 0 - 18
modx/chunks/ae_select_pack.html

@@ -1,18 +0,0 @@
-<!-- Chunk : ae_select_pack
-     Placeholders : [[+cards]] [[+landing_url]]
--->
-<div class="grid">
-  <div class="card">
-    <h1 class="h1">Choisissez le process à diagnostiquer</h1>
-    <p class="lead">Sélectionnez un pack pré-configuré ou utilisez le questionnaire universel.</p>
-
-    <div class="section-label" style="margin-top:18px">Packs disponibles</div>
-    <div class="grid grid--2">
-      [[+cards]]
-    </div>
-
-    <div class="btnrow" style="margin-top:18px">
-      <a href="[[+landing_url]]" class="btn btn--outline">← Retour</a>
-    </div>
-  </div>
-</div>

+ 0 - 38
modx/chunks/ae_unlock_gate.html

@@ -1,38 +0,0 @@
-<!-- Chunk : ae_unlock_gate
-     Affiché quand l'email n'a pas encore été saisi.
-     Placeholders : [[+action_url]] [[+audit_uid]] [[+risks_html]] [[+email]]
--->
-<div class="unlock-gate">
-  <div class="unlock-gate__inner">
-    <div class="unlock-gate__icon">↓</div>
-    <div class="h2" style="margin-bottom:6px">Débloquez vos axes d'amélioration</div>
-    <p class="lead" style="margin-bottom:20px">
-      Entrez votre email professionnel pour accéder aux 5 actions prioritaires
-      et télécharger votre PDF synthèse.
-    </p>
-
-    <!-- Teaser risques -->
-    <div class="unlock-risks">
-      [[+risks_html]]
-    </div>
-
-    <form class="unlock-form" method="POST" action="[[+action_url]]">
-      <input type="hidden" name="ae_action"  value="ae_capture_email">
-      <input type="hidden" name="audit_uid"  value="[[+audit_uid]]">
-      <div class="unlock-row">
-        <input
-          type="email"
-          name="email"
-          required
-          placeholder="vous@entreprise.com"
-          autocomplete="email"
-          value="[[+email]]"
-        >
-        <button class="btn btn--primary btn--unlock" type="submit">Débloquer →</button>
-      </div>
-      <p class="hint" style="margin-top:8px;text-align:center">
-        Aucun spam. Désinscription en 1 clic.
-      </p>
-    </form>
-  </div>
-</div>

+ 0 - 7
modx/chunks/ae_win_item.html

@@ -1,7 +0,0 @@
-<!-- Chunk : ae_win_item
-     Placeholders : [[+title]] [[+effect]] [[+effort]]
--->
-<li>
-  <strong>[[+title]]</strong>
-  <div class="hint">[[+effect]] ; Effort : [[+effort]]</div>
-</li>

+ 0 - 68
modx/model/audit_express/auditrequest.class.php

@@ -1,68 +0,0 @@
-<?php
-/**
- * AuditRequest - Classe xPDO de base
- * Représente une session d'audit (quiz + résultat) en base de données.
- */
-class AuditRequest extends xPDOSimpleObject
-{
-    /**
-     * Retourne les réponses sous forme de tableau PHP.
-     */
-    public function getAnswersArray(): array
-    {
-        $raw = $this->get('answers');
-        if (!$raw) return [];
-        return json_decode($raw, true) ?? [];
-    }
-
-    /**
-     * Enregistre un tableau de réponses en JSON.
-     */
-    public function setAnswersArray(array $answers): void
-    {
-        $this->set('answers', json_encode($answers, JSON_UNESCAPED_UNICODE));
-    }
-
-    /**
-     * Retourne les données optionnelles sous forme de tableau PHP.
-     */
-    public function getOptionalArray(): array
-    {
-        $raw = $this->get('optional_data');
-        if (!$raw) return [];
-        return json_decode($raw, true) ?? [];
-    }
-
-    public function setOptionalArray(array $optional): void
-    {
-        $this->set('optional_data', json_encode($optional, JSON_UNESCAPED_UNICODE));
-    }
-
-    /**
-     * Retourne le résultat calculé sous forme de tableau PHP.
-     */
-    public function getResultArray(): array
-    {
-        $raw = $this->get('result');
-        if (!$raw) return [];
-        return json_decode($raw, true) ?? [];
-    }
-
-    public function setResultArray(array $result): void
-    {
-        $this->set('result', json_encode($result, JSON_UNESCAPED_UNICODE));
-    }
-
-    /**
-     * Met à jour updated_at automatiquement avant chaque save().
-     */
-    public function save($cacheFlag = null): bool
-    {
-        $now = (new \DateTime())->format('Y-m-d H:i:s');
-        if (!$this->get('created_at')) {
-            $this->set('created_at', $now);
-        }
-        $this->set('updated_at', $now);
-        return parent::save($cacheFlag);
-    }
-}

+ 0 - 5
modx/model/audit_express/mysql/auditrequest.class.php

@@ -1,5 +0,0 @@
-<?php
-/**
- * AuditRequest - Pilote MySQL xPDO
- */
-class AuditRequestMysql extends AuditRequest {}

+ 0 - 125
modx/model/audit_express/mysql/auditrequest.map.inc.php

@@ -1,125 +0,0 @@
-<?php
-/**
- * AuditRequest - Map xPDO MySQL
- * Généré depuis schema/audit_express.mysql.schema.xml
- */
-$xpdo_meta_map['AuditRequest'] = [
-    'package'  => 'audit_express',
-    'version'  => '1.1',
-    'table'    => 'audit_requests',
-    'extends'  => 'xPDOSimpleObject',
-
-    'fields' => [
-        'audit_uid'     => '',
-        'pack_id'       => '',
-        'answers'       => null,
-        'optional_data' => null,
-        'result'        => null,
-        'email'         => null,
-        'status'        => 'draft',
-        'ip_hash'       => null,
-        'step'          => 0,
-        'created_at'    => null,
-        'updated_at'    => null,
-    ],
-
-    'fieldMeta' => [
-        'audit_uid' => [
-            'dbtype'    => 'varchar',
-            'precision' => '36',
-            'phptype'   => 'string',
-            'null'      => false,
-            'default'   => '',
-            'index'     => 'unique',
-        ],
-        'pack_id' => [
-            'dbtype'    => 'varchar',
-            'precision' => '64',
-            'phptype'   => 'string',
-            'null'      => false,
-            'default'   => '',
-        ],
-        'answers' => [
-            'dbtype'  => 'text',
-            'phptype' => 'string',
-            'null'    => true,
-        ],
-        'optional_data' => [
-            'dbtype'  => 'text',
-            'phptype' => 'string',
-            'null'    => true,
-        ],
-        'result' => [
-            'dbtype'  => 'mediumtext',
-            'phptype' => 'string',
-            'null'    => true,
-        ],
-        'email' => [
-            'dbtype'    => 'varchar',
-            'precision' => '255',
-            'phptype'   => 'string',
-            'null'      => true,
-        ],
-        'status' => [
-            'dbtype'    => 'enum',
-            'precision' => "'draft','completed','emailed'",
-            'phptype'   => 'string',
-            'null'      => false,
-            'default'   => 'draft',
-        ],
-        'ip_hash' => [
-            'dbtype'    => 'varchar',
-            'precision' => '64',
-            'phptype'   => 'string',
-            'null'      => true,
-        ],
-        'step' => [
-            'dbtype'    => 'tinyint',
-            'precision' => '3',
-            'phptype'   => 'integer',
-            'null'      => false,
-            'default'   => 0,
-        ],
-        'created_at' => [
-            'dbtype'  => 'datetime',
-            'phptype' => 'datetime',
-            'null'    => false,
-        ],
-        'updated_at' => [
-            'dbtype'  => 'datetime',
-            'phptype' => 'datetime',
-            'null'    => false,
-        ],
-    ],
-
-    'indexes' => [
-        'PRIMARY' => [
-            'alias'   => 'PRIMARY',
-            'primary' => true,
-            'unique'  => true,
-            'type'    => 'BTREE',
-            'columns' => ['id' => ['length' => '', 'collation' => 'A', 'null' => false]],
-        ],
-        'audit_uid' => [
-            'alias'   => 'audit_uid',
-            'primary' => false,
-            'unique'  => true,
-            'type'    => 'BTREE',
-            'columns' => ['audit_uid' => ['length' => '', 'collation' => 'A', 'null' => false]],
-        ],
-        'status' => [
-            'alias'   => 'status',
-            'primary' => false,
-            'unique'  => false,
-            'type'    => 'BTREE',
-            'columns' => ['status' => ['length' => '', 'collation' => 'A', 'null' => false]],
-        ],
-        'created_at' => [
-            'alias'   => 'created_at',
-            'primary' => false,
-            'unique'  => false,
-            'type'    => 'BTREE',
-            'columns' => ['created_at' => ['length' => '', 'collation' => 'A', 'null' => false]],
-        ],
-    ],
-];

+ 0 - 60
modx/plugins/AuditExpress_Init.php

@@ -1,60 +0,0 @@
-<?php
-/**
- * Plugin : AuditExpress_Init
- *
- * Événements à attacher :
- *   - OnMODXInit  (priorité 1) - charge le modèle xPDO à chaque requête
- *   - OnHandleRequest             - redirige si session expirée sur pages quiz/résultats
- *
- * Paramètre plugin :
- *   core_path  - chemin vers components/audit_express/ (facultatif, auto-détecté)
- */
-
-$corePath = $modx->getOption('ae.core_path', null,
-    $modx->getOption('core_path') . 'components/audit_express/');
-
-// ── Charger le modèle xPDO ────────────────────────────────────────────────
-if ($modx->addPackage('audit_express', $corePath . 'model/')) {
-    // Optionnel : logger la version au démarrage (utile pour le debug)
-    // $modx->log(xPDO::LOG_LEVEL_DEBUG, '[AuditExpress] modèle chargé depuis ' . $corePath . 'model/');
-}
-
-// ── OnHandleRequest : guard sur les ressources protégées ──────────────────
-if ($modx->event->name === 'OnHandleRequest') {
-
-    $protectedResources = [
-        (int) $modx->getOption('ae.resource.quiz',     null, 0),
-        (int) $modx->getOption('ae.resource.optional', null, 0),
-        (int) $modx->getOption('ae.resource.results',  null, 0),
-    ];
-
-    $currentResourceId = (int) $modx->resource?->get('id');
-
-    if ($currentResourceId && in_array($currentResourceId, $protectedResources, true)) {
-        $selectResourceId = (int) $modx->getOption('ae.resource.select', null, 0);
-
-        // Ressource quiz/optional : nécessite ae_audit_uid en session
-        if (in_array($currentResourceId, [
-            (int) $modx->getOption('ae.resource.quiz',     null, 0),
-            (int) $modx->getOption('ae.resource.optional', null, 0),
-        ], true)) {
-            if (empty($_SESSION['ae_audit_uid'])) {
-                $url = $selectResourceId
-                    ? $modx->makeUrl($selectResourceId, '', '', 'full')
-                    : '/';
-                $modx->sendRedirect($url);
-            }
-        }
-
-        // Ressource résultats : nécessite le paramètre ?audit= OU la session
-        if ($currentResourceId === (int) $modx->getOption('ae.resource.results', null, 0)) {
-            $uid = trim($_GET['audit'] ?? $_SESSION['ae_audit_uid'] ?? '');
-            if (!$uid) {
-                $url = $selectResourceId
-                    ? $modx->makeUrl($selectResourceId, '', '', 'full')
-                    : '/';
-                $modx->sendRedirect($url);
-            }
-        }
-    }
-}

+ 0 - 620
modx/preview-chunks.html

@@ -1,620 +0,0 @@
-<!doctype html>
-<html lang="fr">
-<head>
-  <meta charset="utf-8">
-  <meta name="viewport" content="width=device-width,initial-scale=1">
-  <title>Spec visuelle - Chunks & Templates ; Audit Express</title>
-  <link rel="preconnect" href="https://fonts.googleapis.com">
-  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
-  <link rel="stylesheet" href="../public/assets/css/app.css">
-  <style>
-    /* ══════════════════════════════════
-       SYSTÈME D'ANNOTATION
-    ══════════════════════════════════ */
-
-    /* Chaque élément annoté */
-    [data-chunk] {
-      position: relative;
-    }
-    [data-chunk]::before {
-      content: attr(data-chunk);
-      position: absolute;
-      top: -1px;
-      left: -1px;
-      z-index: 10;
-      font-family: 'Courier New', monospace;
-      font-size: 10px;
-      font-weight: 700;
-      letter-spacing: .3px;
-      padding: 2px 7px;
-      border-radius: 3px 0 3px 0;
-      line-height: 1.6;
-      pointer-events: none;
-      white-space: nowrap;
-    }
-    [data-chunk] {
-      outline: 2px solid;
-      outline-offset: 1px;
-    }
-
-    /* Couleurs par catégorie */
-    [data-chunk^="ae_pack"]     { outline-color: #e2a300; }
-    [data-chunk^="ae_pack"]::before  { background: #e2a300; color: #fff; }
-    [data-chunk^="ae_select"]   { outline-color: #e2a300; }
-    [data-chunk^="ae_select"]::before { background: #e2a300; color: #fff; }
-
-    [data-chunk^="ae_quiz"]     { outline-color: #7c3aed; }
-    [data-chunk^="ae_quiz"]::before  { background: #7c3aed; color: #fff; }
-    [data-chunk^="ae_question"] { outline-color: #a855f7; }
-    [data-chunk^="ae_question"]::before { background: #a855f7; color: #fff; }
-    [data-chunk^="ae_optional"] { outline-color: #0891b2; }
-    [data-chunk^="ae_optional"]::before { background: #0891b2; color: #fff; }
-
-    [data-chunk^="ae_pillar"]   { outline-color: #059669; }
-    [data-chunk^="ae_pillar"]::before { background: #059669; color: #fff; }
-    [data-chunk^="ae_risk"]     { outline-color: #dc2626; }
-    [data-chunk^="ae_risk"]::before { background: #dc2626; color: #fff; }
-    [data-chunk^="ae_win"]      { outline-color: #16a34a; }
-    [data-chunk^="ae_win"]::before { background: #16a34a; color: #fff; }
-    [data-chunk^="ae_cost"]     { outline-color: #d97706; }
-    [data-chunk^="ae_cost"]::before { background: #d97706; color: #fff; }
-    [data-chunk^="ae_unlock"]   { outline-color: #173258; }
-    [data-chunk^="ae_unlock"]::before { background: #173258; color: #fff; }
-    [data-chunk^="ae_cta"]      { outline-color: #00bef3; }
-    [data-chunk^="ae_cta"]::before { background: #00bef3; color: #fff; }
-    [data-chunk^="ae_results"]  { outline-color: #2F506D; }
-    [data-chunk^="ae_results"]::before { background: #2F506D; color: #fff; }
-
-    /* Templates */
-    [data-tpl] {
-      position: relative;
-      outline: 3px dashed #04173d;
-      outline-offset: 6px;
-    }
-    [data-tpl]::after {
-      content: 'Template : ' attr(data-tpl);
-      position: absolute;
-      top: -20px;
-      right: 0;
-      font-family: 'Courier New', monospace;
-      font-size: 10px;
-      font-weight: 700;
-      background: #04173d;
-      color: #fff;
-      padding: 2px 8px;
-      border-radius: 3px;
-      white-space: nowrap;
-    }
-
-    /* MODE SANS ANNOTATIONS */
-    body.no-annot [data-chunk] { outline: none; }
-    body.no-annot [data-chunk]::before { display: none; }
-    body.no-annot [data-tpl] { outline: none; }
-    body.no-annot [data-tpl]::after { display: none; }
-
-    /* ══════════════════════════════════
-       LAYOUT DE LA PAGE PREVIEW
-    ══════════════════════════════════ */
-    body { background: #eef2f7; }
-
-    .pv-toolbar {
-      position: sticky;
-      top: 0;
-      z-index: 100;
-      background: #04173d;
-      color: #fff;
-      padding: 10px 20px;
-      display: flex;
-      align-items: center;
-      gap: 16px;
-      flex-wrap: wrap;
-      margin: -32px -18px 32px;
-    }
-    .pv-toolbar strong { font-size: 13px; letter-spacing: .3px; }
-    .pv-toggle {
-      display: inline-flex; align-items: center; gap: 8px;
-      background: rgba(255,255,255,.12); border: 1px solid rgba(255,255,255,.25);
-      color: #fff; font-size: 12px; font-weight: 700;
-      padding: 5px 13px; border-radius: 4px; cursor: pointer;
-      transition: background .15s;
-    }
-    .pv-toggle:hover { background: rgba(255,255,255,.22); }
-    .pv-toggle .dot {
-      width: 10px; height: 10px; border-radius: 50%;
-      background: #00bef3; transition: background .2s;
-    }
-    body.no-annot .pv-toggle .dot { background: #6b7280; }
-
-    .pv-legend {
-      display: flex; flex-wrap: wrap; gap: 8px; margin-left: auto;
-    }
-    .pv-leg {
-      display: inline-flex; align-items: center; gap: 5px;
-      font-size: 10px; font-weight: 700; color: #fff;
-      opacity: .8;
-    }
-    .pv-leg span {
-      width: 10px; height: 10px; border-radius: 2px; flex-shrink: 0;
-    }
-
-    .pv-nav {
-      display: flex; flex-wrap: wrap; gap: 4px 12px; margin-bottom: 4px;
-    }
-    .pv-nav a {
-      color: rgba(255,255,255,.65); font-size: 11px; text-decoration: none;
-      padding-bottom: 1px; border-bottom: 1px solid transparent;
-      transition: color .15s, border-color .15s;
-    }
-    .pv-nav a:hover { color: #00bef3; border-color: #00bef3; }
-
-    /* Séparateurs d'étape */
-    .pv-step {
-      display: flex; align-items: center; gap: 14px;
-      margin: 52px 0 24px;
-      font-size: 11px; font-weight: 700; letter-spacing: .8px;
-      text-transform: uppercase; color: #5e789a;
-    }
-    .pv-step::before {
-      content: ''; width: 32px; height: 3px;
-      background: #04173d; border-radius: 2px; flex-shrink: 0;
-    }
-    .pv-step::after {
-      content: ''; flex: 1; height: 1px; background: #dde5ed;
-    }
-
-    /* Zones de padding autour des chunks pour que les labels soient lisibles */
-    .pv-box {
-      padding: 16px;
-      background: #fff;
-      border-radius: 6px;
-      margin-bottom: 24px;
-    }
-    .pv-box + .pv-box { margin-top: 0; }
-    .pv-box--tight { padding: 8px; }
-    .pv-caption {
-      font-size: 11px; color: #5e789a; margin: 0 0 10px;
-      font-style: italic;
-    }
-
-    /* Surcharge mineure pour l'imbrication profonde */
-    [data-chunk] [data-chunk]::before { top: 2px; left: 2px; font-size: 9px; padding: 1px 5px; }
-
-    /* Surcharge unlock-gate pour qu'elle s'affiche bien */
-    .unlock-gate { margin-bottom: 0 !important; }
-  </style>
-</head>
-<body>
-<div class="container">
-
-  <!-- ── Toolbar sticky ── -->
-  <div class="pv-toolbar">
-    <div>
-      <strong>Spec visuelle - Chunks &amp; Templates</strong>
-      <div class="pv-nav" style="margin-top:6px">
-        <a href="#step-select">① Choix pack</a>
-        <a href="#step-quiz">② Quiz</a>
-        <a href="#step-optional">③ Optionnel</a>
-        <a href="#step-results">④ Résultats</a>
-        <a href="#step-full">⑤ Page complète</a>
-      </div>
-    </div>
-    <button class="pv-toggle" onclick="document.body.classList.toggle('no-annot')">
-      <span class="dot"></span> Annotations ON/OFF
-    </button>
-    <div class="pv-legend">
-      <span class="pv-leg"><span style="background:#e2a300"></span> Pack/Sélection</span>
-      <span class="pv-leg"><span style="background:#7c3aed"></span> Quiz</span>
-      <span class="pv-leg"><span style="background:#0891b2"></span> Optionnel</span>
-      <span class="pv-leg"><span style="background:#059669"></span> Piliers</span>
-      <span class="pv-leg"><span style="background:#dc2626"></span> Risques</span>
-      <span class="pv-leg"><span style="background:#16a34a"></span> Wins</span>
-      <span class="pv-leg"><span style="background:#173258"></span> Gate/CTA</span>
-    </div>
-  </div>
-
-
-  <!-- ════════════════════════════════════════════════════
-       ① CHOIX DU PACK
-  ════════════════════════════════════════════════════ -->
-  <div id="step-select" class="pv-step">① Choix du pack</div>
-
-  <div data-tpl="AuditExpress_Base">
-    <div class="pv-box">
-      <p class="pv-caption">Ressource MODX : <code>[[!AuditExpress_SelectPack]]</code></p>
-
-      <div data-chunk="ae_select_pack">
-        <div class="grid">
-          <div class="card">
-            <h1 class="h1">Choisissez le process à diagnostiquer</h1>
-            <p class="lead">Sélectionnez un pack pré-configuré ou utilisez le questionnaire universel.</p>
-
-            <div class="section-label" style="margin-top:18px">Packs disponibles</div>
-            <div class="grid grid--2">
-
-              <div data-chunk="ae_pack_card">
-                <div class="pack-card">
-                  <span class="tag tag--pre">Pré-configuré</span>
-                  <div class="title" style="margin-top:8px">Onboarding collaborateur <span class="arrow">→</span></div>
-                  <div class="desc">Fiabilisez l'intégration de vos nouveaux collaborateurs.</div>
-                </div>
-              </div>
-
-              <div data-chunk="ae_pack_card">
-                <div class="pack-card">
-                  <span class="tag tag--pre">Pré-configuré</span>
-                  <div class="title" style="margin-top:8px">Validation de facture <span class="arrow">→</span></div>
-                  <div class="desc">Évaluez la robustesse de votre circuit factures.</div>
-                </div>
-              </div>
-
-              <div data-chunk="ae_pack_card">
-                <div class="pack-card">
-                  <span class="tag tag--new">Universel</span>
-                  <div class="title" style="margin-top:8px">Process générique <span class="arrow">→</span></div>
-                  <div class="desc">Applicable à tout process opérationnel.</div>
-                </div>
-              </div>
-
-            </div>
-            <div class="btnrow" style="margin-top:18px">
-              <a href="#" class="btn btn--outline">← Retour</a>
-            </div>
-          </div>
-        </div>
-      </div><!-- /ae_select_pack -->
-
-    </div>
-  </div><!-- /Template AuditExpress_Base -->
-
-
-  <!-- ════════════════════════════════════════════════════
-       ② QUIZ - 1 QUESTION
-  ════════════════════════════════════════════════════ -->
-  <div id="step-quiz" class="pv-step">② Quiz - une question</div>
-
-  <div data-tpl="AuditExpress_Quiz">
-    <div class="pv-box">
-      <p class="pv-caption">Ressource MODX : <code>[[!AuditExpress_Quiz]]</code></p>
-
-      <div data-chunk="ae_quiz">
-        <div class="grid">
-          <div class="card">
-
-            <!-- Sous-chunk progress, injecté via [[+progress]] -->
-            <div data-chunk="ae_quiz_progress">
-              <div class="quizHead">
-                <span class="tag" style="font-size:11px">Onboarding collaborateur</span>
-                <div class="quizStep"><strong>5</strong><span> / 20</span></div>
-              </div>
-              <div class="progressWrap">
-                <div class="progress"><div style="width:20%"></div></div>
-                <div class="progressMeta">
-                  <span class="progressPct">20&nbsp;%</span>
-                  <span class="progressRemain">encore 15 questions</span>
-                </div>
-              </div>
-            </div><!-- /ae_quiz_progress -->
-
-            <form method="POST" action="#" id="ae-quiz-form-demo">
-              <input type="hidden" name="ae_action" value="ae_answer">
-              <input type="hidden" name="question_id" value="q5">
-
-              <div class="qTitle">Les étapes et responsabilités du process sont-elles formalisées quelque part ?</div>
-              <p class="qHelp">Procédure écrite, workflow dans un outil, checklist partagée - tout format compte.</p>
-
-              <!-- Chaque option = ae_question_option, injectées via [[+options]] -->
-              <div class="options">
-
-                <div data-chunk="ae_question_option">
-                  <label class="opt" for="d_q5_0">
-                    <input id="d_q5_0" type="radio" name="option_id" value="q5_0">
-                    <div><strong>Oui, un processus clair et documenté existe</strong></div>
-                  </label>
-                </div>
-
-                <div data-chunk="ae_question_option">
-                  <label class="opt opt--selected" for="d_q5_2">
-                    <input id="d_q5_2" type="radio" name="option_id" value="q5_2" checked>
-                    <div><strong>Partiellement - quelques étapes sont formalisées</strong></div>
-                  </label>
-                </div>
-
-                <div data-chunk="ae_question_option">
-                  <label class="opt" for="d_q5_4">
-                    <input id="d_q5_4" type="radio" name="option_id" value="q5_4">
-                    <div><strong>Non, chacun fait à sa manière</strong></div>
-                  </label>
-                </div>
-
-                <div data-chunk="ae_question_option">
-                  <label class="opt opt--na" for="d_q5_na">
-                    <input id="d_q5_na" type="radio" name="option_id" value="q5_na">
-                    <div><strong>Je ne sais pas / Non pertinent - N/A</strong></div>
-                  </label>
-                </div>
-
-              </div><!-- /options -->
-
-              <div class="btnrow" style="margin-top:18px">
-                <button type="button" class="btn btn--outline">← Précédent</button>
-                <button type="button" class="btn btn--primary">Suivant →</button>
-              </div>
-              <p class="hint" style="margin-top:10px">Vous pouvez modifier vos réponses avant la fin.</p>
-            </form>
-
-          </div>
-        </div>
-      </div><!-- /ae_quiz -->
-
-    </div>
-  </div><!-- /Template AuditExpress_Quiz -->
-
-
-  <!-- ════════════════════════════════════════════════════
-       ③ QUESTIONS OPTIONNELLES
-  ════════════════════════════════════════════════════ -->
-  <div id="step-optional" class="pv-step">③ Questions optionnelles</div>
-
-  <div data-tpl="AuditExpress_Quiz">
-    <div class="pv-box">
-      <p class="pv-caption">Ressource MODX : <code>[[!AuditExpress_Optional]]</code> - même template que le quiz</p>
-
-      <div data-chunk="ae_optional">
-        <div class="grid">
-          <div class="card">
-            <span class="tag tag--new" style="margin-bottom:12px;display:inline-block">Optionnel</span>
-            <h1 class="h1">Quelques infos pour le coût caché</h1>
-            <p class="lead">Ces données servent à estimer le coût caché en heures/mois. Vous pouvez passer directement.</p>
-
-            <form method="POST" action="#">
-
-              <!-- Chaque groupe = ae_optional_field, injecté via [[+fields]] -->
-              <div data-chunk="ae_optional_field">
-                <div class="field">
-                  <label>Volume mensuel traité par ce process</label>
-                  <div class="options" style="margin-top:6px">
-
-                    <!-- Chaque radio = ae_optional_radio -->
-                    <div data-chunk="ae_optional_radio">
-                      <label class="opt" for="d_vol_50">
-                        <input id="d_vol_50" type="radio" name="opt_vol" value="50">
-                        <div><strong>Moins de 50 dossiers/mois</strong></div>
-                      </label>
-                    </div>
-
-                    <div data-chunk="ae_optional_radio">
-                      <label class="opt opt--selected" for="d_vol_200">
-                        <input id="d_vol_200" type="radio" name="opt_vol" value="200" checked>
-                        <div><strong>50 à 200 dossiers/mois</strong></div>
-                      </label>
-                    </div>
-
-                    <div data-chunk="ae_optional_radio">
-                      <label class="opt" for="d_vol_500">
-                        <input id="d_vol_500" type="radio" name="opt_vol" value="500">
-                        <div><strong>Plus de 200 dossiers/mois</strong></div>
-                      </label>
-                    </div>
-
-                  </div>
-                </div>
-              </div><!-- /ae_optional_field -->
-
-              <div data-chunk="ae_optional_field">
-                <div class="field">
-                  <label>Coût horaire chargé d'un collaborateur</label>
-                  <div class="options" style="margin-top:6px">
-                    <div data-chunk="ae_optional_radio">
-                      <label class="opt" for="d_ch_40"><input id="d_ch_40" type="radio" name="opt_ch" value="40"><div><strong>Moins de 40 €/h</strong></div></label>
-                    </div>
-                    <div data-chunk="ae_optional_radio">
-                      <label class="opt opt--selected" for="d_ch_60"><input id="d_ch_60" type="radio" name="opt_ch" value="60" checked><div><strong>40 à 80 €/h</strong></div></label>
-                    </div>
-                    <div data-chunk="ae_optional_radio">
-                      <label class="opt" for="d_ch_100"><input id="d_ch_100" type="radio" name="opt_ch" value="100"><div><strong>Plus de 80 €/h</strong></div></label>
-                    </div>
-                  </div>
-                </div>
-              </div><!-- /ae_optional_field -->
-
-              <div class="btnrow" style="margin-top:20px">
-                <a href="#" class="btn btn--outline">← Retour au quiz</a>
-                <button type="button" class="btn btn--primary">Voir mes résultats →</button>
-              </div>
-            </form>
-          </div>
-        </div>
-      </div><!-- /ae_optional -->
-
-    </div>
-  </div><!-- /Template AuditExpress_Quiz -->
-
-
-  <!-- ════════════════════════════════════════════════════
-       ④ RÉSULTATS - ÉTAT NON DÉBLOQUÉ
-  ════════════════════════════════════════════════════ -->
-  <div id="step-results" class="pv-step">④ Résultats - avant déblocage email</div>
-
-  <div data-tpl="AuditExpress_Results">
-    <div class="pv-box">
-      <p class="pv-caption">Ressource MODX : <code>[[!AuditExpress_Results]]</code> - <strong>[[+gate_html]]</strong> = ae_unlock_gate (email non saisi)</p>
-
-      <div data-chunk="ae_results">
-        <div class="grid">
-
-          <!-- Carte score -->
-          <div class="card">
-            <div style="display:flex;align-items:center;gap:10px;margin-bottom:16px">
-              <span class="tag">Onboarding collaborateur</span>
-            </div>
-            <div class="scoreBox">
-              <div>
-                <div class="scoreLabel">Score global</div>
-                <div class="scoreBig">67/100</div>
-                <div class="level-badge" style="margin-top:10px">
-                  <span class="level-dot" style="background:#c07c10"></span>
-                  <span>C - Fragile</span>
-                </div>
-                <div class="confidence">Confiance du diagnostic : Élevée (2 DK)</div>
-              </div>
-            </div>
-            <!-- [[+pillars_html]] = 5 × ae_pillar_row -->
-            <div class="pillars">
-              <div data-chunk="ae_pillar_row"><div class="pRow"><div class="name">Clarté du flux</div><div class="val">14/20</div><div class="bar"><div style="width:70%"></div></div></div></div>
-              <div data-chunk="ae_pillar_row"><div class="pRow"><div class="name">Fiabilité</div><div class="val">11/20</div><div class="bar"><div style="width:55%"></div></div></div></div>
-              <div data-chunk="ae_pillar_row"><div class="pRow"><div class="name">Traçabilité</div><div class="val">10/20</div><div class="bar"><div style="width:50%"></div></div></div></div>
-              <div data-chunk="ae_pillar_row"><div class="pRow"><div class="name">Résilience</div><div class="val">15/20</div><div class="bar"><div style="width:75%"></div></div></div></div>
-              <div data-chunk="ae_pillar_row"><div class="pRow"><div class="name">Coût caché</div><div class="val">17/20</div><div class="bar"><div style="width:85%"></div></div></div></div>
-            </div>
-          </div>
-
-          <!-- [[+risks_html]] = 3 × ae_risk_item -->
-          <div class="card">
-            <div class="h2">3 risques probables</div>
-            <ol class="list">
-              <div data-chunk="ae_risk_item"><li><strong>Statut flou → relances permanentes</strong><div class="hint">Sans état visible partagé, chaque intervenant doit relancer.</div></li></div>
-              <div data-chunk="ae_risk_item"><li><strong>Documents dispersés entre emails, Drive et postes locaux</strong><div class="hint">Un dossier incomplet bloque le traitement et génère des erreurs.</div></li></div>
-              <div data-chunk="ae_risk_item"><li><strong>Dépendance à une personne clé non remplaçable</strong><div class="hint">En cas d'absence, le process s'arrête ou se dégrade fortement.</div></li></div>
-            </ol>
-          </div>
-
-          <!-- [[+cost_html]] = ae_cost_hidden -->
-          <div data-chunk="ae_cost_hidden">
-            <div class="cost-block">
-              <div class="h2">Coût caché estimé</div>
-              <div class="cost-figures">
-                <div class="cost-fig"><span class="val">18 h</span><span class="lbl">par mois (estimé)</span></div>
-                <div class="cost-fig"><span class="val">~1 080 €</span><span class="lbl">par mois (indicatif)</span></div>
-              </div>
-              <p class="hint">Estimation indicative, à valider par mesure réelle.</p>
-            </div>
-          </div>
-
-          <!-- [[+gate_html]] = ae_unlock_gate (email non saisi) -->
-          <div data-chunk="ae_unlock_gate">
-            <div class="unlock-gate">
-              <div class="unlock-gate__inner">
-                <div class="unlock-gate__icon">↓</div>
-                <div class="h2" style="margin-bottom:6px">Débloquez vos axes d'amélioration</div>
-                <p class="lead" style="margin-bottom:20px">Entrez votre email professionnel pour accéder aux 5 actions prioritaires et télécharger votre PDF synthèse.</p>
-                <div class="unlock-risks">
-                  <div class="unlock-risk"><div class="unlock-risk__num">1</div><div class="unlock-risk__body"><strong>Statut flou → relances permanentes</strong><span>Sans état visible partagé, chaque intervenant doit relancer.</span></div></div>
-                  <div class="unlock-risk"><div class="unlock-risk__num">2</div><div class="unlock-risk__body"><strong>Documents dispersés</strong><span>Un dossier incomplet ou introuvable bloque le traitement.</span></div></div>
-                </div>
-                <form class="unlock-form" method="POST" action="#">
-                  <div class="unlock-row">
-                    <input type="email" name="email" placeholder="vous@entreprise.com">
-                    <button class="btn btn--primary btn--unlock" type="button">Débloquer →</button>
-                  </div>
-                  <p class="hint" style="margin-top:8px;text-align:center">Aucun spam. Désinscription en 1 clic.</p>
-                </form>
-              </div>
-            </div>
-          </div><!-- /ae_unlock_gate -->
-
-          <!-- [[+wins_html]] = vide (non débloqué) - absent ici -->
-
-        </div>
-      </div><!-- /ae_results -->
-
-    </div>
-  </div><!-- /Template AuditExpress_Results -->
-
-
-  <!-- ════════════════════════════════════════════════════
-       ⑤ PAGE COMPLÈTE - ÉTAT DÉBLOQUÉ
-  ════════════════════════════════════════════════════ -->
-  <div id="step-full" class="pv-step">⑤ Résultats - après déblocage email (état final)</div>
-
-  <div data-tpl="AuditExpress_Results">
-    <div class="pv-box">
-      <p class="pv-caption">Même ressource, même template. <strong>[[+gate_html]]</strong> = ae_cta_unlocked &amp; <strong>[[+wins_html]]</strong> = 5 × ae_win_item (débloqués)</p>
-
-      <div data-chunk="ae_results">
-        <div class="grid">
-
-          <div class="card">
-            <div style="display:flex;align-items:center;gap:10px;margin-bottom:16px"><span class="tag">Onboarding collaborateur</span></div>
-            <div class="scoreBox">
-              <div>
-                <div class="scoreLabel">Score global</div>
-                <div class="scoreBig">67/100</div>
-                <div class="level-badge" style="margin-top:10px">
-                  <span class="level-dot" style="background:#c07c10"></span><span>C - Fragile</span>
-                </div>
-                <div class="confidence">Confiance du diagnostic : Élevée</div>
-              </div>
-            </div>
-            <div class="pillars">
-              <div data-chunk="ae_pillar_row"><div class="pRow"><div class="name">Clarté du flux</div><div class="val">14/20</div><div class="bar"><div style="width:70%"></div></div></div></div>
-              <div data-chunk="ae_pillar_row"><div class="pRow"><div class="name">Fiabilité</div><div class="val">11/20</div><div class="bar"><div style="width:55%"></div></div></div></div>
-              <div data-chunk="ae_pillar_row"><div class="pRow"><div class="name">Traçabilité</div><div class="val">10/20</div><div class="bar"><div style="width:50%"></div></div></div></div>
-              <div data-chunk="ae_pillar_row"><div class="pRow"><div class="name">Résilience</div><div class="val">15/20</div><div class="bar"><div style="width:75%"></div></div></div></div>
-              <div data-chunk="ae_pillar_row"><div class="pRow"><div class="name">Coût caché</div><div class="val">17/20</div><div class="bar"><div style="width:85%"></div></div></div></div>
-            </div>
-          </div>
-
-          <div class="card">
-            <div class="h2">3 risques probables</div>
-            <ol class="list">
-              <div data-chunk="ae_risk_item"><li><strong>Statut flou → relances permanentes</strong><div class="hint">Sans état visible partagé, chaque intervenant doit relancer.</div></li></div>
-              <div data-chunk="ae_risk_item"><li><strong>Documents dispersés entre emails, Drive et postes locaux</strong><div class="hint">Un dossier incomplet bloque le traitement et génère des erreurs.</div></li></div>
-              <div data-chunk="ae_risk_item"><li><strong>Dépendance à une personne clé</strong><div class="hint">En cas d'absence, le process s'arrête ou se dégrade fortement.</div></li></div>
-            </ol>
-          </div>
-
-          <div data-chunk="ae_cost_hidden">
-            <div class="cost-block">
-              <div class="h2">Coût caché estimé</div>
-              <div class="cost-figures">
-                <div class="cost-fig"><span class="val">18 h</span><span class="lbl">par mois (estimé)</span></div>
-                <div class="cost-fig"><span class="val">~1 080 €</span><span class="lbl">par mois (indicatif)</span></div>
-              </div>
-              <p class="hint">Estimation indicative, à valider par mesure réelle.</p>
-            </div>
-          </div>
-
-          <!-- [[+gate_html]] = ae_cta_unlocked (email déjà saisi) -->
-          <div data-chunk="ae_cta_unlocked">
-            <div style="background:#fff;border:1px solid var(--border);border-radius:var(--radius);padding:32px 28px">
-              <div class="h2" style="margin-bottom:6px">Et maintenant ?</div>
-              <p class="lead" style="margin-bottom:24px">Votre diagnostic révèle des opportunités concrètes. Nous pouvons vous aider à les transformer en plan d'action.</p>
-              <div style="display:flex;flex-wrap:wrap;gap:10px;justify-content:center">
-                <a class="btn btn--primary" href="#">Réserver un appel découverte - 30 min</a>
-                <a class="btn btn--outline" href="#">Demander un devis</a>
-              </div>
-              <hr style="border:none;border-top:1px solid var(--border);margin:24px 0">
-              <div class="btnrow" style="justify-content:center;gap:10px">
-                <a class="btn btn--outline" href="#">Télécharger mon PDF</a>
-                <a class="btn btn--outline" href="#" style="font-size:13px">Diagnostiquer un autre process</a>
-              </div>
-            </div>
-          </div><!-- /ae_cta_unlocked -->
-
-          <!-- [[+wins_html]] = 5 × ae_win_item (visible car unlocked) -->
-          <div class="card">
-            <div class="h2">5 quick wins prioritaires</div>
-            <ol class="list">
-              <div data-chunk="ae_win_item"><li><strong>Checklist jour 1 partagée</strong><div class="hint">Réduction des oublis à l'intégration ; Effort : S</div></li></div>
-              <div data-chunk="ae_win_item"><li><strong>Pré-check 48 h avant arrivée</strong><div class="hint">Accès outils prêts dès J1 ; Effort : S</div></li></div>
-              <div data-chunk="ae_win_item"><li><strong>Tableau de statut unique</strong><div class="hint">Fin des relances sur l'avancement ; Effort : M</div></li></div>
-              <div data-chunk="ae_win_item"><li><strong>Centraliser les documents</strong><div class="hint">Dossier toujours complet et retrouvable ; Effort : S</div></li></div>
-              <div data-chunk="ae_win_item"><li><strong>Escalade simple formalisée</strong><div class="hint">Moins de blocages en cas d'absence ; Effort : S</div></li></div>
-            </ol>
-            <p class="hint" style="margin-top:8px">Le PDF contient les 5 actions avec détail effort/impact.</p>
-          </div>
-
-        </div>
-      </div><!-- /ae_results -->
-
-    </div>
-  </div><!-- /Template AuditExpress_Results -->
-
-
-  <footer class="footer" style="margin-top:48px">
-    Spec visuelle chunks &amp; templates - Audit Express Self ; Livinweb
-  </footer>
-
-</div>
-</body>
-</html>

+ 0 - 49
modx/schema/audit_express.mysql.schema.xml

@@ -1,49 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-    Schéma xPDO - Audit Express Self
-    Table : audit_requests
-    Déploiement : voir modx/setup/install.php
--->
-<model package="audit_express"
-       baseClass="xPDOObject"
-       platform="mysql"
-       defaultEngine="InnoDB"
-       phpdoc-package="AuditExpress"
-       version="1.1">
-
-    <object class="AuditRequest" table="audit_requests" extends="xPDOSimpleObject">
-
-        <!-- Identifiant public UUID (partageable dans l'URL résultats) -->
-        <field key="audit_uid"     dbtype="varchar"  precision="36"                        phptype="string"   null="false" default=""      index="unique" />
-        <!-- Pack sélectionné (ex : onboarding-v1, validation-facture) -->
-        <field key="pack_id"       dbtype="varchar"  precision="64"                        phptype="string"   null="false" default="" />
-        <!-- Réponses JSON : {"q1":"q1_3","q2":"q2_dk",...} -->
-        <field key="answers"       dbtype="text"                                           phptype="string"   null="true"  default="null" />
-        <!-- Données optionnelles JSON (volume, coût horaire…) -->
-        <field key="optional_data" dbtype="text"                                           phptype="string"   null="true"  default="null" />
-        <!-- Résultat calculé JSON (score, piliers, risques, quick_wins…) -->
-        <field key="result"        dbtype="mediumtext"                                     phptype="string"   null="true"  default="null" />
-        <!-- Email saisi lors de la capture (optionnel, RGPD) -->
-        <field key="email"         dbtype="varchar"  precision="255"                       phptype="string"   null="true"  default="null" />
-        <!-- draft → completed → emailed -->
-        <field key="status"        dbtype="enum"     precision="'draft','completed','emailed'" phptype="string" null="false" default="draft" />
-        <!-- Hash de l'IP (sha256) - pas d'IP en clair, RGPD -->
-        <field key="ip_hash"       dbtype="varchar"  precision="64"                        phptype="string"   null="true"  default="null" />
-        <!-- Étape courante (index question, 0-based) - pour reprise -->
-        <field key="step"          dbtype="tinyint"  precision="3"                         phptype="integer"  null="false" default="0" />
-        <field key="created_at"    dbtype="datetime"                                       phptype="datetime" null="false" />
-        <field key="updated_at"    dbtype="datetime"                                       phptype="datetime" null="false" />
-
-        <index alias="audit_uid" name="audit_uid" primary="false" unique="true" type="BTREE">
-            <column key="audit_uid" length="" collation="A" null="false" />
-        </index>
-        <index alias="status" name="status" primary="false" unique="false" type="BTREE">
-            <column key="status" length="" collation="A" null="false" />
-        </index>
-        <index alias="created_at" name="created_at" primary="false" unique="false" type="BTREE">
-            <column key="created_at" length="" collation="A" null="false" />
-        </index>
-
-    </object>
-
-</model>

+ 0 - 21
modx/setup/create_tables.sql

@@ -1,21 +0,0 @@
--- Audit Express - création de table (exécuter si install.php ne peut pas tourner)
--- Remplacer `modx_` par votre préfixe MODX réel.
-
-CREATE TABLE IF NOT EXISTS `modx_audit_requests` (
-  `id`            INT(10) UNSIGNED    NOT NULL AUTO_INCREMENT,
-  `audit_uid`     VARCHAR(36)         NOT NULL DEFAULT '',
-  `pack_id`       VARCHAR(64)         NOT NULL DEFAULT '',
-  `answers`       TEXT                         DEFAULT NULL,
-  `optional_data` TEXT                         DEFAULT NULL,
-  `result`        MEDIUMTEXT                   DEFAULT NULL,
-  `email`         VARCHAR(255)                 DEFAULT NULL,
-  `status`        ENUM('draft','completed','emailed') NOT NULL DEFAULT 'draft',
-  `ip_hash`       VARCHAR(64)                  DEFAULT NULL,
-  `step`          TINYINT(3)          NOT NULL DEFAULT 0,
-  `created_at`    DATETIME            NOT NULL,
-  `updated_at`    DATETIME            NOT NULL,
-  PRIMARY KEY (`id`),
-  UNIQUE KEY `audit_uid` (`audit_uid`),
-  KEY `status` (`status`),
-  KEY `created_at` (`created_at`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

+ 0 - 108
modx/setup/install.php

@@ -1,108 +0,0 @@
-<?php
-/**
- * Script d'installation Audit Express - MODX
- * ============================================
- * À exécuter UNE SEULE FOIS après le déploiement du composant.
- * Requiert que MODX soit correctement configuré (config.core.php présent).
- *
- * Usage : php modx/setup/install.php
- *   ou via le navigateur (protéger avec .htaccess ensuite)
- *
- * Ce script :
- *   1. Crée la table `audit_requests` via xPDO
- *   2. Crée les System Settings ae.*
- *   3. Génère le SQL de création au cas où xPDO échoue (fallback)
- */
-
-declare(strict_types=1);
-
-// ── Bootstrap MODX ────────────────────────────────────────────────────────
-define('MODX_API_MODE', true);
-$modxCorePath = dirname(__DIR__, 3) . '/core/';   // adapter si nécessaire
-require_once $modxCorePath . 'model/modx/modx.class.php';
-
-$modx = new modX();
-$modx->initialize('mgr');
-$modx->setLogLevel(xPDO::LOG_LEVEL_INFO);
-$modx->setLogTarget('ECHO');
-
-echo "<pre>\n";
-
-// ── 1. Charger le package xPDO ────────────────────────────────────────────
-$corePath = $modx->getOption('core_path') . 'components/audit_express/';
-$modx->addPackage('audit_express', $corePath . 'model/');
-
-// Générer les tables à partir du schéma XML
-$manager   = $modx->getManager();
-$generator = $manager->getGenerator();
-
-// Créer la table (ignore si elle existe déjà)
-$result = $manager->createObjectContainer('AuditRequest');
-if ($result) {
-    echo "[OK] Table `audit_requests` créée.\n";
-} else {
-    echo "[INFO] Table `audit_requests` déjà existante ou erreur silencieuse.\n";
-}
-
-// ── 2. System Settings ────────────────────────────────────────────────────
-$settings = [
-    'ae.core_path'      => $corePath,
-    'ae.resource.landing'  => '',
-    'ae.resource.select'   => '',
-    'ae.resource.quiz'     => '',
-    'ae.resource.optional' => '',
-    'ae.resource.results'  => '',
-    'ae.resource.pdf'      => '',
-    'ae.booking_url'    => 'https://cal.com/augustin.podvin/decouvrir-les-opportunites-suite-a-mon-audit',
-    'ae.devis_url'      => 'mailto:contact@livinweb.fr',
-];
-
-foreach ($settings as $key => $value) {
-    $existing = $modx->getObject('modSystemSetting', ['key' => $key]);
-    if (!$existing) {
-        $setting = $modx->newObject('modSystemSetting');
-        $setting->fromArray([
-            'key'       => $key,
-            'value'     => $value,
-            'xtype'     => 'textfield',
-            'namespace' => 'audit_express',
-            'area'      => 'ae_settings',
-        ]);
-        $setting->save();
-        echo "[OK] Setting créé : $key\n";
-    } else {
-        echo "[SKIP] Setting existant : $key\n";
-    }
-}
-
-// ── 3. SQL de fallback ────────────────────────────────────────────────────
-$tablePrefix = $modx->getOption('table_prefix', null, 'modx_');
-$sql = <<<SQL
--- Fallback SQL (exécuter manuellement si le script échoue)
-CREATE TABLE IF NOT EXISTS `{$tablePrefix}audit_requests` (
-  `id`            INT(10) UNSIGNED    NOT NULL AUTO_INCREMENT,
-  `audit_uid`     VARCHAR(36)         NOT NULL DEFAULT '',
-  `pack_id`       VARCHAR(64)         NOT NULL DEFAULT '',
-  `answers`       TEXT                         DEFAULT NULL,
-  `optional_data` TEXT                         DEFAULT NULL,
-  `result`        MEDIUMTEXT                   DEFAULT NULL,
-  `email`         VARCHAR(255)                 DEFAULT NULL,
-  `status`        ENUM('draft','completed','emailed') NOT NULL DEFAULT 'draft',
-  `ip_hash`       VARCHAR(64)                  DEFAULT NULL,
-  `step`          TINYINT(3)          NOT NULL DEFAULT 0,
-  `created_at`    DATETIME            NOT NULL,
-  `updated_at`    DATETIME            NOT NULL,
-  PRIMARY KEY (`id`),
-  UNIQUE KEY `audit_uid` (`audit_uid`),
-  KEY `status` (`status`),
-  KEY `created_at` (`created_at`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-SQL;
-
-$sqlFile = __DIR__ . '/create_tables.sql';
-file_put_contents($sqlFile, $sql);
-echo "[OK] SQL de fallback écrit dans : $sqlFile\n";
-
-echo "\nInstallation terminée.\n";
-echo "→ Renseignez les IDs de ressources dans System Settings (ae.resource.*).\n";
-echo "</pre>\n";

+ 0 - 111
modx/snippets/AuditExpress_Optional.php

@@ -1,111 +0,0 @@
-<?php
-/**
- * Snippet : AuditExpress_Optional
- * Vue "Questions optionnelles" (coût caché)
- *
- * Propriétés :
- *   &quiz_resource_id    = `5`
- *   &results_resource_id = `7`
- *
- * POST action : ae_optional
- *   → sauvegarde les données optionnelles
- *   → calcule le score via Engine
- *   → met à jour AuditRequest (result, status=completed)
- *   → redirige vers résultats
- */
-
-declare(strict_types=1);
-
-$corePath = $modx->getOption('ae.core_path', null,
-    $modx->getOption('core_path') . 'components/audit_express/');
-$modx->addPackage('audit_express', $corePath . 'model/');
-require_once $corePath . 'src/PackRepository.php';
-require_once $corePath . 'src/Engine.php';
-require_once $corePath . 'src/RulesRepository.php';
-
-$quizResourceId    = (int) ($scriptProperties['quiz_resource_id']    ?? $modx->getOption('ae.resource.quiz',    null, 0));
-$resultsResourceId = (int) ($scriptProperties['results_resource_id'] ?? $modx->getOption('ae.resource.results', null, 0));
-
-// ── Récupérer l'audit ──────────────────────────────────────────────────────
-$auditUid = $_SESSION['ae_audit_uid'] ?? '';
-if (!$auditUid) {
-    $modx->sendRedirect($quizResourceId ? $modx->makeUrl($quizResourceId, '', '', 'full') : '/');
-    return '';
-}
-
-/** @var AuditRequest|null $auditReq */
-$auditReq = $modx->getObject('AuditRequest', ['audit_uid' => $auditUid]);
-if (!$auditReq) {
-    $modx->sendRedirect($quizResourceId ? $modx->makeUrl($quizResourceId, '', '', 'full') : '/');
-    return '';
-}
-
-$packId = $auditReq->get('pack_id');
-$repo   = new \AuditExpress\PackRepository($corePath . 'config/');
-$pack   = $repo->getPack($packId);
-
-// ── POST : sauvegarder + calculer ─────────────────────────────────────────
-if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['ae_action'] ?? '') === 'ae_optional') {
-    // Collecter les données optionnelles postées (valeurs numériques)
-    $optional = [];
-    foreach ($pack['optional_questions'] ?? [] as $key => $oq) {
-        if (isset($_POST['opt_' . $key])) {
-            $optional[$key] = (int) $_POST['opt_' . $key];
-        }
-    }
-    $auditReq->setOptionalArray($optional);
-
-    // Calcul du score
-    $rulesRepo  = new \AuditExpress\RulesRepository($corePath);
-    $rulesBundle = $rulesRepo->getRules();
-    $answers = $auditReq->getAnswersArray();
-
-    try {
-        $result = \AuditExpress\Engine::compute($pack, $answers, $optional, $rulesBundle);
-        $auditReq->setResultArray($result);
-        $auditReq->set('status', 'completed');
-        $auditReq->save();
-    } catch (\InvalidArgumentException $e) {
-        // Réponse(s) manquante(s) → retour quiz
-        $modx->sendRedirect($quizResourceId ? $modx->makeUrl($quizResourceId, '', '', 'full') : '/');
-        return '';
-    }
-
-    $resultsUrl = $resultsResourceId
-        ? $modx->makeUrl($resultsResourceId, '', 'audit=' . $auditUid, 'full')
-        : '/resultats/?audit=' . $auditUid;
-    $modx->sendRedirect($resultsUrl);
-    return '';
-}
-
-// ── Rendu GET ──────────────────────────────────────────────────────────────
-$optQs     = $pack['optional_questions'] ?? [];
-$optional  = $auditReq->getOptionalArray();
-$quizUrl   = $quizResourceId ? $modx->makeUrl($quizResourceId, '', '', 'full') : '/';
-$actionUrl = $modx->makeUrl($modx->resource->get('id'), '', '', 'full');
-
-$fieldsHtml = '';
-foreach ($optQs as $key => $oq) {
-    $cur = $optional[$key] ?? null;
-    $radiosHtml = '';
-    foreach ($oq['options'] as $opt) {
-        $val = (string) ($opt['value'] ?? $opt['id']);
-        $radiosHtml .= $modx->getChunk('ae_optional_radio', [
-            'key'     => htmlspecialchars($key, ENT_QUOTES),
-            'value'   => htmlspecialchars($val, ENT_QUOTES),
-            'label'   => htmlspecialchars($opt['label'], ENT_QUOTES),
-            'checked' => ((string) $cur === $val) ? 'checked' : '',
-        ]);
-    }
-    $fieldsHtml .= $modx->getChunk('ae_optional_field', [
-        'label'  => htmlspecialchars($oq['label'], ENT_QUOTES),
-        'radios' => $radiosHtml,
-    ]);
-}
-
-return $modx->getChunk('ae_optional', [
-    'fields'     => $fieldsHtml,
-    'action_url' => $actionUrl,
-    'quiz_url'   => $quizUrl,
-    'audit_uid'  => htmlspecialchars($auditUid, ENT_QUOTES),
-]);

+ 0 - 67
modx/snippets/AuditExpress_PDF.php

@@ -1,67 +0,0 @@
-<?php
-/**
- * Snippet : AuditExpress_PDF
- * Génère et télécharge le PDF à la demande (depuis la page résultats, bouton "Télécharger").
- *
- * Appelé en mode uncached via un lien direct :
- *   /audit-express/pdf/?audit=<uid>
- * ou via une ressource dédiée avec ce snippet.
- *
- * Propriétés :
- *   &booking_url = `https://cal.com/augustin.podvin/decouvrir-les-opportunites-suite-a-mon-audit`
- *
- * Envoie directement les headers PDF + contenu binaire, puis exit.
- */
-
-declare(strict_types=1);
-
-$corePath = $modx->getOption('ae.core_path', null,
-    $modx->getOption('core_path') . 'components/audit_express/');
-$modx->addPackage('audit_express', $corePath . 'model/');
-require_once $corePath . 'src/PackRepository.php';
-require_once $corePath . 'src/PdfRenderer.php';
-
-$bookingUrl = $scriptProperties['booking_url'] ?? $modx->getOption('ae.booking_url', null, '');
-
-$auditUid = trim($_GET['audit'] ?? '');
-if (!$auditUid) {
-    http_response_code(400);
-    echo json_encode(['error' => 'audit_uid manquant']);
-    return '';
-}
-
-/** @var AuditRequest|null $auditReq */
-$auditReq = $modx->getObject('AuditRequest', ['audit_uid' => $auditUid]);
-if (!$auditReq || $auditReq->get('status') === 'draft') {
-    http_response_code(404);
-    echo json_encode(['error' => 'Audit non trouvé ou non terminé']);
-    return '';
-}
-
-try {
-    $packId  = $auditReq->get('pack_id');
-    $repo    = new \AuditExpress\PackRepository($corePath . 'config/');
-    $pack    = $repo->getPack($packId);
-    $result  = $auditReq->getResultArray();
-
-    $renderer = new \AuditExpress\PdfRenderer(
-        $corePath . 'templates/pdf_a4.php',
-        $corePath . '../vendor/autoload.php'
-    );
-    $pdfBytes = $renderer->render($pack, $result, $bookingUrl);
-
-    $filename = 'controle-technique-' . preg_replace('/[^a-z0-9\-]/', '', $packId) . '.pdf';
-
-    header('Content-Type: application/pdf');
-    header('Content-Disposition: attachment; filename="' . $filename . '"');
-    header('Content-Length: ' . strlen($pdfBytes));
-    header('Cache-Control: no-store');
-    echo $pdfBytes;
-    exit;
-
-} catch (\Throwable $e) {
-    http_response_code(500);
-    $modx->log(xPDO::LOG_LEVEL_ERROR, '[AuditExpress] PDF: ' . $e->getMessage());
-    echo json_encode(['error' => 'Erreur génération PDF']);
-    return '';
-}

+ 0 - 159
modx/snippets/AuditExpress_Quiz.php

@@ -1,159 +0,0 @@
-<?php
-/**
- * Snippet : AuditExpress_Quiz
- * Vue "Question N/20" - 1 question par chargement de page, PRG pattern
- *
- * Propriétés :
- *   &select_resource_id   = `4`  Ressource choix du pack
- *   &optional_resource_id = `6`  Ressource questions optionnelles
- *
- * Session attendue : ae_audit_uid, ae_pack_id
- *
- * POST action : ae_answer
- *   body : question_id, option_id
- *   → sauvegarde la réponse dans AuditRequest.answers
- *   → incrémente AuditRequest.step
- *   → redirige sur la même ressource (question suivante) ou vers optional
- */
-
-declare(strict_types=1);
-
-$corePath = $modx->getOption('ae.core_path', null,
-    $modx->getOption('core_path') . 'components/audit_express/');
-$modx->addPackage('audit_express', $corePath . 'model/');
-require_once $corePath . 'src/PackRepository.php';
-
-$selectResourceId   = (int) ($scriptProperties['select_resource_id']   ?? $modx->getOption('ae.resource.select',   null, 0));
-$optionalResourceId = (int) ($scriptProperties['optional_resource_id'] ?? $modx->getOption('ae.resource.optional', null, 0));
-
-// ── Récupérer l'audit en cours ─────────────────────────────────────────────
-$auditUid = $_SESSION['ae_audit_uid'] ?? '';
-if (!$auditUid) {
-    $url = $selectResourceId ? $modx->makeUrl($selectResourceId, '', '', 'full') : '/';
-    $modx->sendRedirect($url);
-    return '';
-}
-
-/** @var AuditRequest|null $auditReq */
-$auditReq = $modx->getObject('AuditRequest', ['audit_uid' => $auditUid]);
-if (!$auditReq) {
-    unset($_SESSION['ae_audit_uid'], $_SESSION['ae_pack_id']);
-    $url = $selectResourceId ? $modx->makeUrl($selectResourceId, '', '', 'full') : '/';
-    $modx->sendRedirect($url);
-    return '';
-}
-
-$packId = $auditReq->get('pack_id');
-$repo   = new \AuditExpress\PackRepository($corePath . 'config/');
-$pack   = $repo->getPack($packId);
-$questions = $pack['questions'] ?? [];
-$total     = count($questions);
-
-// ── Traitement POST ────────────────────────────────────────────────────────
-if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['ae_action'] ?? '') === 'ae_answer') {
-    $questionId = trim($_POST['question_id'] ?? '');
-    $optionId   = trim($_POST['option_id']   ?? '');
-
-    // Valider que l'option appartient bien à la question
-    $validOption = false;
-    foreach ($questions as $q) {
-        if ($q['id'] === $questionId) {
-            foreach ($q['options'] as $opt) {
-                if ($opt['id'] === $optionId) { $validOption = true; break 2; }
-            }
-        }
-    }
-
-    if ($validOption) {
-        $answers = $auditReq->getAnswersArray();
-        $answers[$questionId] = $optionId;
-        $auditReq->setAnswersArray($answers);
-
-        // Calculer le nouvel index : prochaine question sans réponse
-        $nextStep = 0;
-        foreach ($questions as $idx => $q) {
-            if (empty($answers[$q['id']])) { $nextStep = $idx; break; }
-            $nextStep = $idx + 1;
-        }
-
-        $auditReq->set('step', min($nextStep, $total));
-        $auditReq->save();
-
-        // Toutes les questions répondues → aller vers optional
-        if ($nextStep >= $total) {
-            $optUrl = $optionalResourceId
-                ? $modx->makeUrl($optionalResourceId, '', '', 'full')
-                : '/optional/';
-            $modx->sendRedirect($optUrl);
-            return '';
-        }
-    }
-
-    // Rediriger vers la même page (PRG) pour afficher la prochaine question
-    $modx->sendRedirect($modx->makeUrl($modx->resource->get('id'), '', '', 'full'));
-    return '';
-}
-
-// ── Action "retour" ────────────────────────────────────────────────────────
-if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['ae_action'] ?? '') === 'ae_prev') {
-    $currentStep = max(0, $auditReq->get('step') - 1);
-    $auditReq->set('step', $currentStep);
-    $auditReq->save();
-    $modx->sendRedirect($modx->makeUrl($modx->resource->get('id'), '', '', 'full'));
-    return '';
-}
-
-// ── Rendu GET ──────────────────────────────────────────────────────────────
-$step = (int) $auditReq->get('step');
-$step = max(0, min($step, $total - 1));
-
-$q      = $questions[$step];
-$pos    = $step + 1;
-$pct    = (int) round(($step / $total) * 100);
-$isLast = ($step === $total - 1);
-$answers = $auditReq->getAnswersArray();
-$selected = $answers[$q['id']] ?? '';
-
-// Construire les options radio
-$optionsHtml = '';
-foreach ($q['options'] as $opt) {
-    $isSelected = ($selected === $opt['id']);
-    $isNa       = ($opt['id'] === 'NA' || $opt['id'] === 'DK' || str_ends_with(strtolower($opt['id']), '_na') || str_ends_with(strtolower($opt['id']), '_dk'));
-    $optionsHtml .= $modx->getChunk('ae_question_option', [
-        'question_id' => htmlspecialchars($q['id'], ENT_QUOTES),
-        'option_id'   => htmlspecialchars($opt['id'], ENT_QUOTES),
-        'label'       => htmlspecialchars($opt['label'], ENT_QUOTES),
-        'checked'     => $isSelected ? 'checked' : '',
-        'cls_selected'=> $isSelected ? 'opt--selected' : '',
-        'cls_na'      => $isNa       ? 'opt--na'       : '',
-    ]);
-}
-
-$actionUrl    = $modx->makeUrl($modx->resource->get('id'), '', '', 'full');
-$selectUrl    = $selectResourceId ? $modx->makeUrl($selectResourceId, '', '', 'full') : '/';
-$remainLabel  = $isLast
-    ? 'Dernière question'
-    : 'encore ' . ($total - $pos) . ' question' . ($total - $pos > 1 ? 's' : '');
-
-$progressHtml = $modx->getChunk('ae_quiz_progress', [
-    'pos'          => $pos,
-    'total'        => $total,
-    'pct'          => $pct,
-    'remain_label' => htmlspecialchars($remainLabel, ENT_QUOTES),
-    'pack_title'   => htmlspecialchars($pack['pack_title'] ?? $packId, ENT_QUOTES),
-]);
-
-return $modx->getChunk('ae_quiz', [
-    'progress'    => $progressHtml,
-    'question_id' => htmlspecialchars($q['id'], ENT_QUOTES),
-    'question'    => htmlspecialchars($q['label'], ENT_QUOTES),
-    'help'        => isset($q['help']) ? '<p class="qHelp">' . htmlspecialchars($q['help'], ENT_QUOTES) . '</p>' : '',
-    'options'     => $optionsHtml,
-    'action_url'  => $actionUrl,
-    'select_url'  => $selectUrl,
-    'audit_uid'   => htmlspecialchars($auditUid, ENT_QUOTES),
-    'can_prev'    => $step > 0 ? '' : 'disabled',
-    'btn_next'    => $isLast ? 'Voir mon résultat →' : 'Suivant →',
-    'btn_class'   => $selected ? 'btn--primary' : 'btn--outline',
-    'can_next'    => $selected ? '' : 'disabled',
-]);

+ 0 - 175
modx/snippets/AuditExpress_Results.php

@@ -1,175 +0,0 @@
-<?php
-/**
- * Snippet : AuditExpress_Results
- * Vue "Résultats du diagnostic"
- *
- * Propriétés :
- *   &select_resource_id = `4`  Pour "Diagnostiquer un autre process"
- *   &booking_url        = `https://cal.com/augustin.podvin/decouvrir-les-opportunites-suite-a-mon-audit`
- *   &devis_url          = `mailto:contact@livinweb.fr`
- *
- * L'audit_uid passe en GET (?audit=xxxx) ou est lu depuis la session.
- *
- * POST action : ae_capture_email
- *   → sauvegarde l'email dans AuditRequest
- *   → génère + envoie le PDF
- *   → redirige sur la même page avec ?unlocked=1
- */
-
-declare(strict_types=1);
-
-$corePath = $modx->getOption('ae.core_path', null,
-    $modx->getOption('core_path') . 'components/audit_express/');
-$modx->addPackage('audit_express', $corePath . 'model/');
-require_once $corePath . 'src/PdfRenderer.php';
-require_once $corePath . 'src/LogMailer.php';
-
-$selectResourceId = (int) ($scriptProperties['select_resource_id'] ?? $modx->getOption('ae.resource.select', null, 0));
-$bookingUrl       = $scriptProperties['booking_url'] ?? $modx->getOption('ae.booking_url', null, '');
-$devisUrl         = $scriptProperties['devis_url']   ?? $modx->getOption('ae.devis_url',   null, '');
-
-// ── Charger l'audit ────────────────────────────────────────────────────────
-$auditUid = trim($_GET['audit'] ?? $_SESSION['ae_audit_uid'] ?? '');
-if (!$auditUid) {
-    $modx->sendRedirect($selectResourceId ? $modx->makeUrl($selectResourceId, '', '', 'full') : '/');
-    return '';
-}
-
-/** @var AuditRequest|null $auditReq */
-$auditReq = $modx->getObject('AuditRequest', ['audit_uid' => $auditUid]);
-if (!$auditReq || $auditReq->get('status') === 'draft') {
-    $modx->sendRedirect($selectResourceId ? $modx->makeUrl($selectResourceId, '', '', 'full') : '/');
-    return '';
-}
-
-// ── POST : capture email + PDF ─────────────────────────────────────────────
-if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['ae_action'] ?? '') === 'ae_capture_email') {
-    $email = trim(filter_var($_POST['email'] ?? '', FILTER_SANITIZE_EMAIL));
-    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
-        $auditReq->set('email', $email);
-        $auditReq->set('status', 'emailed');
-        $auditReq->save();
-
-        // Stocker en session pour pré-remplir le formulaire PDF
-        $_SESSION['ae_email'] = $email;
-        $_SESSION['ae_unlocked_' . $auditUid] = true;
-
-        // Générer et envoyer le PDF (LogMailer V1 = stockage fichier)
-        try {
-            $packId  = $auditReq->get('pack_id');
-            $repo    = new \AuditExpress\PackRepository($corePath . 'config/');
-            $pack    = $repo->getPack($packId);
-            $result  = $auditReq->getResultArray();
-            $answers = $auditReq->getAnswersArray();
-
-            $renderer = new \AuditExpress\PdfRenderer(
-                $corePath . 'templates/pdf_a4.php',
-                $corePath . '../vendor/autoload.php'
-            );
-            $pdfBytes = $renderer->render($pack, $result, $bookingUrl);
-
-            $mailer = new \AuditExpress\LogMailer($corePath . '../storage/outbox/');
-            $mailer->send(
-                $email,
-                'Votre diagnostic - Contrôle technique process',
-                "Bonjour,\n\nVeuillez trouver ci-joint votre synthèse PDF.\n\nBonne continuation,\nL'équipe Livinweb",
-                $pdfBytes,
-                'controle-technique-' . $packId . '.pdf'
-            );
-        } catch (\Throwable $e) {
-            // Ne pas bloquer l'utilisateur si le PDF échoue
-            $modx->log(xPDO::LOG_LEVEL_ERROR, '[AuditExpress] PDF error: ' . $e->getMessage());
-        }
-    }
-
-    $selfUrl = $modx->makeUrl($modx->resource->get('id'), '', 'audit=' . $auditUid . '&unlocked=1', 'full');
-    $modx->sendRedirect($selfUrl);
-    return '';
-}
-
-// ── Rendu GET ──────────────────────────────────────────────────────────────
-$r        = $auditReq->getResultArray();
-$unlocked = isset($_GET['unlocked']) || ($_SESSION['ae_unlocked_' . $auditUid] ?? false);
-$email    = $auditReq->get('email') ?? ($_SESSION['ae_email'] ?? '');
-
-$actionUrl  = $modx->makeUrl($modx->resource->get('id'), '', 'audit=' . $auditUid, 'full');
-$selectUrl  = $selectResourceId ? $modx->makeUrl($selectResourceId, '', '', 'full') : '/';
-
-// Niveaux
-$levelColors = ['A' => '#1e8a5e', 'B' => '#1e8a5e', 'C' => '#c07c10', 'D' => '#b83040'];
-$dotColor    = $levelColors[$r['level'] ?? ''] ?? '#2F506D';
-
-// Piliers
-$pillarsHtml = '';
-foreach ($r['pillars'] ?? [] as $p) {
-    $pct = $p['max'] ? (int) round(($p['score'] / $p['max']) * 100) : 0;
-    $pillarsHtml .= $modx->getChunk('ae_pillar_row', [
-        'label' => htmlspecialchars($p['label'], ENT_QUOTES),
-        'score' => $p['score'],
-        'max'   => $p['max'],
-        'pct'   => $pct,
-    ]);
-}
-
-// Risques
-$risksHtml = '';
-foreach ($r['risks_top3'] ?? [] as $risk) {
-    $risksHtml .= $modx->getChunk('ae_risk_item', [
-        'title'       => htmlspecialchars($risk['title'], ENT_QUOTES),
-        'what_happens'=> htmlspecialchars($risk['what_happens'], ENT_QUOTES),
-    ]);
-}
-
-// Quick wins (uniquement si débloqué)
-$winsHtml = '';
-if ($unlocked) {
-    foreach ($r['quick_wins_preview'] ?? [] as $win) {
-        $winsHtml .= $modx->getChunk('ae_win_item', [
-            'title'  => htmlspecialchars($win['title'], ENT_QUOTES),
-            'effect' => htmlspecialchars($win['effect'], ENT_QUOTES),
-            'effort' => htmlspecialchars($win['effort'], ENT_QUOTES),
-        ]);
-    }
-}
-
-// Coût caché
-$costHtml = '';
-$cost = $r['cost_hidden'] ?? null;
-if ($cost) {
-    $costHtml = $modx->getChunk('ae_cost_hidden', [
-        'hours_per_month' => $cost['hours_per_month'],
-        'eur_per_month'   => $cost['eur_per_month'],
-    ]);
-}
-
-// Gate email ou CTAs débloqués
-$gateOrCtaHtml = $unlocked
-    ? $modx->getChunk('ae_cta_unlocked', [
-        'booking_url' => htmlspecialchars($bookingUrl, ENT_QUOTES),
-        'devis_url'   => htmlspecialchars($devisUrl,   ENT_QUOTES),
-        'select_url'  => $selectUrl,
-        'action_url'  => $actionUrl,
-        'email'       => htmlspecialchars($email, ENT_QUOTES),
-        'audit_uid'   => htmlspecialchars($auditUid, ENT_QUOTES),
-      ])
-    : $modx->getChunk('ae_unlock_gate', [
-        'action_url' => $actionUrl,
-        'audit_uid'  => htmlspecialchars($auditUid, ENT_QUOTES),
-        'risks_html' => $risksHtml,
-        'email'      => htmlspecialchars($email, ENT_QUOTES),
-      ]);
-
-return $modx->getChunk('ae_results', [
-    'pack_title'   => htmlspecialchars($r['pack_title'] ?? $auditReq->get('pack_id'), ENT_QUOTES),
-    'score_total'  => $r['score_total'] ?? 0,
-    'level'        => $r['level'] ?? '-',
-    'level_label'  => htmlspecialchars($r['level_label'] ?? '', ENT_QUOTES),
-    'dot_color'    => $dotColor,
-    'confidence'   => htmlspecialchars($r['confidence']['label'] ?? '', ENT_QUOTES),
-    'pillars_html' => $pillarsHtml,
-    'risks_html'   => $risksHtml,
-    'wins_html'    => $winsHtml,
-    'cost_html'    => $costHtml,
-    'gate_html'    => $gateOrCtaHtml,
-    'unlocked'     => $unlocked ? '1' : '',
-]);

+ 0 - 126
modx/snippets/AuditExpress_SelectPack.php

@@ -1,126 +0,0 @@
-<?php
-/**
- * Snippet : AuditExpress_SelectPack
- * Vue "Choisir un pack"
- *
- * Propriétés (dans le tag snippet MODX) :
- *   &quiz_resource_id  = `5`   ID de la ressource quiz
- *   &landing_resource_id = `3` ID de la ressource landing
- *
- * POST action : ae_select_pack
- *   → crée un AuditRequest en BD, stocke audit_uid en session
- *   → redirige vers la ressource quiz
- */
-
-declare(strict_types=1);
-
-// ── Bootstrap ──────────────────────────────────────────────────────────────
-$corePath = $modx->getOption('ae.core_path', null,
-    $modx->getOption('core_path') . 'components/audit_express/');
-$modx->addPackage('audit_express', $corePath . 'model/');
-
-require_once $corePath . 'src/PackRepository.php';
-
-$quizResourceId    = (int) ($scriptProperties['quiz_resource_id']    ?? $modx->getOption('ae.resource.quiz', null, 0));
-$landingResourceId = (int) ($scriptProperties['landing_resource_id'] ?? $modx->getOption('ae.resource.landing', null, 0));
-
-// ── Traitement POST ────────────────────────────────────────────────────────
-if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['ae_action'] ?? '') === 'select_pack') {
-    $packId = trim($_POST['pack_id'] ?? '');
-    if (!$packId) {
-        $modx->sendRedirect($modx->makeUrl($modx->resource->get('id'), '', '', 'full'));
-        return '';
-    }
-
-    // Vérifier que le pack existe
-    $repo = new \AuditExpress\PackRepository($corePath . 'config/');
-    try {
-        $packData = $repo->getPack($packId);
-    } catch (\InvalidArgumentException $e) {
-        $modx->sendRedirect($modx->makeUrl($modx->resource->get('id'), '', '', 'full'));
-        return '';
-    }
-
-    // Créer l'objet AuditRequest en BD
-    /** @var AuditRequest $auditReq */
-    $auditReq = $modx->newObject('AuditRequest');
-    $auditReq->set('audit_uid',  sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
-        mt_rand(0, 0xffff), mt_rand(0, 0xffff),
-        mt_rand(0, 0xffff),
-        mt_rand(0, 0x0fff) | 0x4000,
-        mt_rand(0, 0x3fff) | 0x8000,
-        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
-    ));
-    $auditReq->set('pack_id', $packId);
-    $auditReq->set('status',  'draft');
-    $auditReq->set('step',    0);
-    $auditReq->set('ip_hash', hash('sha256', $_SERVER['REMOTE_ADDR'] ?? ''));
-    $auditReq->setAnswersArray([]);
-    $auditReq->setOptionalArray([]);
-    $auditReq->save();
-
-    // Stocker en session
-    $modx->user->getUserProfile(); // init session MODX
-    $_SESSION['ae_audit_uid'] = $auditReq->get('audit_uid');
-    $_SESSION['ae_pack_id']   = $packId;
-
-    // Rediriger vers quiz
-    $quizUrl = $quizResourceId
-        ? $modx->makeUrl($quizResourceId, '', '', 'full')
-        : '/quiz/';
-    $modx->sendRedirect($quizUrl);
-    return '';
-}
-
-// ── Rendu GET ──────────────────────────────────────────────────────────────
-$packCatalogue = [
-    [
-        'id'       => 'onboarding-v1',
-        'title'    => 'Onboarding collaborateur',
-        'desc'     => "Clarté du flux, traçabilité, continuité — auditez votre process d'intégration.",
-        'tag'      => 'Pré-configuré',
-        'tagClass' => 'tag--pre',
-    ],
-    [
-        'id'       => 'validation-facture',
-        'title'    => 'Validation de facture',
-        'desc'     => 'Contrôles, séparation des tâches, preuve — évaluez votre circuit factures.',
-        'tag'      => 'Pré-configuré',
-        'tagClass' => 'tag--pre',
-    ],
-    [
-        'id'       => 'process-generique',
-        'title'    => 'Process générique',
-        'desc'     => 'Applicable à tout process opérationnel : achat, production, relation client, support, projet…',
-        'tag'      => 'Universel',
-        'tagClass' => 'tag--new',
-    ],
-    [
-        'id'       => 'process-generique-v2',
-        'title'    => 'Diagnostic d\'opportunité',
-        'desc'     => 'Évaluez sur 8 axes si ce process est prioritaire à automatiser : friction, volume, risque, données, outils, variabilité, collaboration, déploiement.',
-        'tag'      => 'Diagnostic d\'opportunité',
-        'tagClass' => 'tag--v2',
-    ],
-];
-
-$actionUrl = $modx->makeUrl($modx->resource->get('id'), '', '', 'full');
-$landingUrl = $landingResourceId ? $modx->makeUrl($landingResourceId, '', '', 'full') : '/';
-
-$cards = '';
-foreach ($packCatalogue as $p) {
-    $cards .= $modx->getChunk('ae_pack_card', [
-        'pack_id'    => htmlspecialchars($p['id'], ENT_QUOTES),
-        'title'      => htmlspecialchars($p['title'], ENT_QUOTES),
-        'desc'       => htmlspecialchars($p['desc'], ENT_QUOTES),
-        'tag'        => htmlspecialchars($p['tag'], ENT_QUOTES),
-        'tag_class'  => htmlspecialchars($p['tagClass'], ENT_QUOTES),
-        'action_url' => $actionUrl,
-    ]);
-}
-
-return $modx->getChunk('ae_select_pack', [
-    'cards'       => $cards,
-    'action_url'  => $actionUrl,
-    'landing_url' => $landingUrl,
-]);

+ 0 - 68
modx/templates/AuditExpress_Base.html

@@ -1,68 +0,0 @@
-<!doctype html>
-<html lang="fr">
-<head>
-  <meta charset="utf-8">
-  <meta name="viewport" content="width=device-width,initial-scale=1">
-  <title>[[*pagetitle]] - Contrôle technique process ; Livinweb</title>
-  <meta name="description" content="[[*description:default=`En 7 minutes, obtenez une note sur 100, vos risques probables et 5 actions prioritaires pour fiabiliser votre process.`]]">
-  <link rel="preconnect" href="https://fonts.googleapis.com">
-  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
-  <link rel="stylesheet" href="[[++assets_url]]components/audit_express/css/app.css">
-  [[*ae_extra_head]]
-</head>
-<body>
-  <div class="container">
-
-    <header class="header">
-      <div>
-        <div class="brand__logo">
-          <a href="[[~[[++ae.resource.landing]]]]" style="color:inherit;text-decoration:none">Contrôle technique process</a>
-        </div>
-        <div class="brand__sub">
-          Diagnostic self-serve ;
-          <a href="https://livinweb.fr" target="_blank" rel="noreferrer" style="color:inherit;text-decoration:none">Livinweb</a>
-        </div>
-      </div>
-      <span class="brand__badge">V2</span>
-    </header>
-
-    <main id="app">
-      [[*content]]
-    </main>
-
-    <footer class="footer">
-      <a href="#" id="privacyLink">Données &amp; confidentialité</a>
-      &nbsp;;&nbsp;
-      <a href="https://livinweb.fr" target="_blank" rel="noreferrer">Livinweb</a>
-    </footer>
-
-  </div><!-- /.container -->
-
-  <!-- Dialog confidentialité -->
-  <dialog id="privacyDialog" class="dialog">
-    <div class="dialog__inner">
-      <div class="dialog__head">
-        <strong>Données &amp; confidentialité</strong>
-        <button class="btn btn--outline" style="padding:6px 12px;font-size:13px" id="closePrivacy">Fermer</button>
-      </div>
-      <div class="dialog__body">
-        <p><strong>Données collectées</strong> : réponses au questionnaire, et email uniquement si vous demandez le PDF.</p>
-        <p><strong>Finalité</strong> : calculer un score, générer votre PDF, et vous l'envoyer.</p>
-        <p><strong>Durée</strong> : sessions sans email 7 jours ; avec email 90 jours max.</p>
-        <p><strong>Droits</strong> : accès, rectification, effacement. Contact :
-          <a href="mailto:[[++emailsender]]">[[++emailsender]]</a></p>
-      </div>
-    </div>
-  </dialog>
-
-  <script src="[[++assets_url]]components/audit_express/js/ae-base.js"></script>
-  <script>
-    var link = document.getElementById('privacyLink');
-    var dlg  = document.getElementById('privacyDialog');
-    var cls  = document.getElementById('closePrivacy');
-    if (link && dlg) link.addEventListener('click', function(e){ e.preventDefault(); dlg.showModal(); });
-    if (cls  && dlg) cls.addEventListener('click', function(){ dlg.close(); });
-  </script>
-  [[*ae_extra_js]]
-</body>
-</html>

+ 0 - 61
modx/templates/AuditExpress_Landing.html

@@ -1,61 +0,0 @@
-<!doctype html>
-<html lang="fr">
-<head>
-  <meta charset="utf-8">
-  <meta name="viewport" content="width=device-width,initial-scale=1">
-  <title>Contrôle technique de votre process - Livinweb</title>
-  <meta name="description" content="En 7 minutes, obtenez une note sur 100, vos risques probables et 5 actions prioritaires pour fiabiliser votre process.">
-  <link rel="preconnect" href="https://fonts.googleapis.com">
-  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
-  <link rel="stylesheet" href="[[++assets_url]]components/audit_express/css/app.css">
-</head>
-<body>
-  <div class="container">
-
-    <header class="header">
-      <div>
-        <div class="brand__logo">Contrôle technique process</div>
-        <div class="brand__sub">
-          Diagnostic self-serve ;
-          <a href="https://livinweb.fr" target="_blank" rel="noreferrer" style="color:inherit;text-decoration:none">Livinweb</a>
-        </div>
-      </div>
-      <span class="brand__badge">V2</span>
-    </header>
-
-    <main id="app">
-      [[*content]]
-    </main>
-
-    <footer class="footer">
-      <a href="#" id="privacyLink">Données &amp; confidentialité</a>
-      &nbsp;;&nbsp;
-      <a href="https://livinweb.fr" target="_blank" rel="noreferrer">Livinweb</a>
-    </footer>
-
-  </div>
-
-  <dialog id="privacyDialog" class="dialog">
-    <div class="dialog__inner">
-      <div class="dialog__head">
-        <strong>Données &amp; confidentialité</strong>
-        <button class="btn btn--outline" style="padding:6px 12px;font-size:13px" id="closePrivacy">Fermer</button>
-      </div>
-      <div class="dialog__body">
-        <p><strong>Données collectées</strong> : réponses au questionnaire, et email uniquement si vous demandez le PDF.</p>
-        <p><strong>Finalité</strong> : calculer un score, générer votre PDF, et vous l'envoyer.</p>
-        <p><strong>Durée</strong> : sessions sans email 7 jours ; avec email 90 jours max.</p>
-        <p><strong>Droits</strong> : accès, rectification, effacement. Contact : <a href="mailto:contact@livinweb.fr">contact@livinweb.fr</a></p>
-      </div>
-    </div>
-  </dialog>
-
-  <script>
-    var link = document.getElementById('privacyLink');
-    var dlg  = document.getElementById('privacyDialog');
-    var cls  = document.getElementById('closePrivacy');
-    if (link && dlg) link.addEventListener('click', function(e){ e.preventDefault(); dlg.showModal(); });
-    if (cls  && dlg) cls.addEventListener('click', function(){ dlg.close(); });
-  </script>
-</body>
-</html>

+ 0 - 36
modx/templates/AuditExpress_Quiz.html

@@ -1,36 +0,0 @@
-<!doctype html>
-<html lang="fr">
-<head>
-  <meta charset="utf-8">
-  <meta name="viewport" content="width=device-width,initial-scale=1">
-  <title>[[*pagetitle]] - Contrôle technique process</title>
-  <meta name="robots" content="noindex,nofollow">
-  <link rel="preconnect" href="https://fonts.googleapis.com">
-  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
-  <link rel="stylesheet" href="[[++assets_url]]components/audit_express/css/app.css">
-</head>
-<body>
-  <div class="container">
-
-    <header class="header">
-      <div>
-        <div class="brand__logo">
-          <a href="[[~[[++ae.resource.landing]]]]" style="color:inherit;text-decoration:none">Contrôle technique process</a>
-        </div>
-        <div class="brand__sub">Diagnostic self-serve ; Livinweb</div>
-      </div>
-    </header>
-
-    <main id="app">
-      [[*content]]
-    </main>
-
-    <footer class="footer">
-      <a href="[[~[[++ae.resource.landing]]]]">Accueil</a>
-      &nbsp;;&nbsp;
-      <a href="https://livinweb.fr" target="_blank" rel="noreferrer">Livinweb</a>
-    </footer>
-
-  </div>
-</body>
-</html>

+ 0 - 36
modx/templates/AuditExpress_Results.html

@@ -1,36 +0,0 @@
-<!doctype html>
-<html lang="fr">
-<head>
-  <meta charset="utf-8">
-  <meta name="viewport" content="width=device-width,initial-scale=1">
-  <title>Vos résultats - Contrôle technique process</title>
-  <meta name="robots" content="noindex,nofollow">
-  <link rel="preconnect" href="https://fonts.googleapis.com">
-  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
-  <link rel="stylesheet" href="[[++assets_url]]components/audit_express/css/app.css">
-</head>
-<body>
-  <div class="container">
-
-    <header class="header">
-      <div>
-        <div class="brand__logo">
-          <a href="[[~[[++ae.resource.landing]]]]" style="color:inherit;text-decoration:none">Contrôle technique process</a>
-        </div>
-        <div class="brand__sub">Diagnostic self-serve ; Livinweb</div>
-      </div>
-    </header>
-
-    <main id="app">
-      [[*content]]
-    </main>
-
-    <footer class="footer">
-      <a href="[[~[[++ae.resource.landing]]]]">Accueil</a>
-      &nbsp;;&nbsp;
-      <a href="https://livinweb.fr" target="_blank" rel="noreferrer">Livinweb</a>
-    </footer>
-
-  </div>
-</body>
-</html>

+ 53 - 0
public/api/analytics-debug.php

@@ -0,0 +1,53 @@
+<?php
+
+declare(strict_types=1);
+
+/**
+ * Endpoint de diagnostic analytics — à supprimer en production.
+ * GET /api/analytics-debug.php
+ */
+use AuditExpress\Analytics;
+use AuditExpress\Http;
+
+['root' => $root] = require __DIR__ . '/_bootstrap.php';
+
+$storageDir = $root . '/storage';
+$file = $storageDir . '/analytics.json';
+
+$checks = [
+    'root_exists' => is_dir($root),
+    'storage_dir_exists' => is_dir($storageDir),
+    'storage_writable' => is_writable($storageDir),
+    'file_exists' => is_file($file),
+    'file_writable' => is_file($file) ? is_writable($file) : (is_dir($storageDir) && is_writable($storageDir)),
+];
+
+// Tenter un track test
+$before = null;
+$after = null;
+$trackOk = false;
+$trackError = null;
+
+try {
+    $analytics = new Analytics($root);
+    $before = $analytics->getStats();
+    $analytics->track(Analytics::EVENT_DIA_INIT, '_debug_test');
+    $after = $analytics->getStats();
+    $trackOk = ($after['total'][Analytics::EVENT_DIA_INIT] ?? 0) > ($before['total'][Analytics::EVENT_DIA_INIT] ?? 0);
+} catch (Throwable $e) {
+    $trackError = $e->getMessage();
+}
+
+Http::json([
+    'diagnostic' => [
+        'root' => $root,
+        'storage_dir' => $storageDir,
+        'file' => $file,
+        'checks' => $checks,
+        'track_test_ok' => $trackOk,
+        'track_error' => $trackError,
+        'before_dia_init' => $before['total'][Analytics::EVENT_DIA_INIT] ?? null,
+        'after_dia_init' => $after['total'][Analytics::EVENT_DIA_INIT] ?? null,
+    ],
+    'last_updated' => $after['last_updated'] ?? null,
+]);

+ 7 - 3
public/api/email.php

@@ -4,6 +4,7 @@ declare(strict_types=1);
 
 use AuditExpress\AdminNotifier;
 use AuditExpress\Analytics;
+use AuditExpress\OutboxStorage;
 use AuditExpress\Engine;
 use AuditExpress\Http;
 use AuditExpress\InputValidator;
@@ -53,11 +54,14 @@ try {
 
     $filename = 'controle-technique-' . ($pack['pack_id'] ?? 'resultat') . '.pdf';
 
-    // Notification admin via webhook (pas d'envoi aux utilisateurs finaux)
+    // Stockage local (toujours) + webhook si configuré
+    $ctx = ['pack_id' => $packId, 'answers' => $answers, 'optional' => $optional, 'result' => $result];
+    $outbox = new OutboxStorage($root . '/storage/outbox');
     $webhookUrl = (string) ($config['admin_notify_webhook'] ?? '');
     if ($webhookUrl !== '' && filter_var($webhookUrl, FILTER_VALIDATE_URL)) {
-        $ctx = ['pack_id' => $packId, 'answers' => $answers, 'optional' => $optional, 'result' => $result];
-        (new AdminNotifier($webhookUrl, $root . '/storage/outbox'))->notify('email', $ctx, $filename, $pdfBytes, $userEmail);
+        (new AdminNotifier($webhookUrl, $outbox))->notify('email', $ctx, $filename, $pdfBytes, $userEmail);
+    } else {
+        $outbox->store('email', $ctx, $filename, $pdfBytes, $userEmail);
     }
 
     Http::json([

+ 59 - 0
public/api/excel-complete.php

@@ -0,0 +1,59 @@
+<?php
+
+declare(strict_types=1);
+
+use AuditExpress\AdminNotifier;
+use AuditExpress\Http;
+use AuditExpress\OutboxStorage;
+use AuditExpress\RateLimiter;
+use AuditExpress\Security;
+
+['root' => $root, 'config' => $config] = require __DIR__ . '/_bootstrap.php';
+
+if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
+    Http::methodNotAllowed(['POST']);
+    exit;
+}
+
+Security::validateCsrf();
+(new RateLimiter($root, $config, RateLimiter::clientIp()))->check('excel_complete');
+
+$maxBody = (int) ($config['max_body_bytes'] ?? 1_048_576);
+$body = Http::readJsonBody($maxBody > 0 ? $maxBody : null);
+$email = isset($body['email']) ? trim((string) $body['email']) : null;
+$raw = is_array($body['result'] ?? null) ? $body['result'] : null;
+
+if ($raw === null || !isset($raw['level'], $raw['title'], $raw['summary'], $raw['score'], $raw['total'], $raw['actions'])) {
+    Http::json(['error' => 'Données du verdict manquantes ou invalides'], 400);
+    exit;
+}
+
+// Email optionnel : si fourni, doit être valide
+if ($email !== null && $email !== '') {
+    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
+        Http::json(['error' => 'Email invalide'], 400);
+        exit;
+    }
+} else {
+    $email = null;
+}
+
+$result = [
+    'level' => (string) $raw['level'],
+    'title' => (string) $raw['title'],
+    'summary' => (string) $raw['summary'],
+    'score' => (int) $raw['score'],
+    'total' => (int) $raw['total'],
+    'actions' => array_values(array_map('strval', (array) ($raw['actions'] ?? []))),
+    'qual' => is_array($raw['qual'] ?? null) ? $raw['qual'] : [],
+];
+
+$outbox = new OutboxStorage($root . '/storage/outbox');
+$outbox->storeExcelComplete($result, $email);
+
+$webhookUrl = (string) ($config['admin_notify_webhook'] ?? '');
+if ($webhookUrl !== '' && filter_var($webhookUrl, FILTER_VALIDATE_URL)) {
+    (new AdminNotifier($webhookUrl, $outbox))->notifyExcelComplete($result, $email);
+}
+
+Http::json(['status' => 'ok']);

+ 2 - 18
public/api/notify.php

@@ -3,6 +3,7 @@
 declare(strict_types=1);
 
 use AuditExpress\Http;
+use AuditExpress\OutboxStorage;
 use AuditExpress\RateLimiter;
 use AuditExpress\Security;
 
@@ -31,23 +32,6 @@ if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
     exit;
 }
 
-$outboxDir = $root . '/storage/outbox';
-if (!is_dir($outboxDir)) {
-    @mkdir($outboxDir, 0775, true);
-}
-
-$id   = date('Ymd_His') . '_' . bin2hex(random_bytes(4));
-$meta = [
-    'id'         => $id,
-    'type'       => 'notify_interest',
-    'tool'       => $tool,
-    'email'      => $email,
-    'created_at' => date(DATE_ATOM),
-];
-
-file_put_contents(
-    $outboxDir . DIRECTORY_SEPARATOR . $id . '_notify.json',
-    json_encode($meta, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)
-);
+(new OutboxStorage($root . '/storage/outbox'))->storeNotify($tool, $email);
 
 Http::json(['status' => 'ok']);

+ 8 - 4
public/api/pdf.php

@@ -4,6 +4,7 @@ declare(strict_types=1);
 
 use AuditExpress\AdminNotifier;
 use AuditExpress\Analytics;
+use AuditExpress\OutboxStorage;
 use AuditExpress\Engine;
 use AuditExpress\Http;
 use AuditExpress\InputValidator;
@@ -47,12 +48,15 @@ try {
 
     $filename = 'controle-technique-' . ($pack['pack_id'] ?? 'resultat') . '.pdf';
 
-    // Notification admin via webhook
-    $webhookUrl = (string) ($config['admin_notify_webhook'] ?? '');
+    // Stockage local (toujours) + webhook si configuré
+    $ctx = ['pack_id' => $packId, 'answers' => $answers, 'optional' => $optional, 'result' => $result];
     $userEmail = (string) ($body['email'] ?? '');
+    $outbox = new OutboxStorage($root . '/storage/outbox');
+    $webhookUrl = (string) ($config['admin_notify_webhook'] ?? '');
     if ($webhookUrl !== '' && filter_var($webhookUrl, FILTER_VALIDATE_URL)) {
-        $ctx = ['pack_id' => $packId, 'answers' => $answers, 'optional' => $optional, 'result' => $result];
-        (new AdminNotifier($webhookUrl, $root . '/storage/outbox'))->notify('pdf', $ctx, $filename, $pdf, $userEmail !== '' ? $userEmail : null);
+        (new AdminNotifier($webhookUrl, $outbox))->notify('pdf', $ctx, $filename, $pdf, $userEmail !== '' ? $userEmail : null);
+    } else {
+        $outbox->store('pdf', $ctx, $filename, $pdf, $userEmail !== '' ? $userEmail : null);
     }
 
     header('Content-Type: application/pdf');

+ 12 - 8
public/api/score.php

@@ -4,6 +4,7 @@ declare(strict_types=1);
 
 use AuditExpress\AdminNotifier;
 use AuditExpress\Analytics;
+use AuditExpress\OutboxStorage;
 use AuditExpress\Engine;
 use AuditExpress\Http;
 use AuditExpress\InputValidator;
@@ -39,16 +40,19 @@ try {
 
     (new Analytics($root))->track(Analytics::EVENT_DIA_COMPLETED, $packId);
 
-    // Notification admin via webhook
+    // Stockage local (toujours) + webhook si configuré
+    $pdfBytes = (new PdfRenderer($root))->renderPdfBytes($pack, $result, [
+        'booking_url' => '',
+        'date' => date('Y-m-d'),
+    ]);
+    $filename = 'controle-technique-' . ($pack['pack_id'] ?? 'resultat') . '.pdf';
+    $ctx = ['pack_id' => $packId, 'answers' => $answers, 'optional' => $optional, 'result' => $result];
+    $outbox = new OutboxStorage($root . '/storage/outbox');
     $webhookUrl = (string) ($config['admin_notify_webhook'] ?? '');
     if ($webhookUrl !== '' && filter_var($webhookUrl, FILTER_VALIDATE_URL)) {
-        $pdfBytes = (new PdfRenderer($root))->renderPdfBytes($pack, $result, [
-            'booking_url' => '',
-            'date' => date('Y-m-d'),
-        ]);
-        $filename = 'controle-technique-' . ($pack['pack_id'] ?? 'resultat') . '.pdf';
-        $ctx = ['pack_id' => $packId, 'answers' => $answers, 'optional' => $optional, 'result' => $result];
-        (new AdminNotifier($webhookUrl, $root . '/storage/outbox'))->notify('score', $ctx, $filename, $pdfBytes, null);
+        (new AdminNotifier($webhookUrl, $outbox))->notify('score', $ctx, $filename, $pdfBytes, null);
+    } else {
+        $outbox->store('score', $ctx, $filename, $pdfBytes, null);
     }
 
     Http::json(['result' => $result]);

+ 3 - 3
public/assets/css/app.css

@@ -382,7 +382,7 @@ body {
   border-radius: 4px;
 }
 
-/* Legacy brand (MODX / fallback) */
+/* Brand (style compact) */
 .brand__logo { font-size: 20px; font-weight: 700; color: var(--navy); letter-spacing: .3px; }
 .brand__sub   { color: var(--muted); font-size: 13px; margin-top: 2px; font-weight: 400; }
 .brand__badge {
@@ -588,13 +588,13 @@ body {
 /* ── Forms / inputs ── */
 .field { display: grid; gap: 6px; margin: 10px 0; }
 .field label { font-weight: 700; font-size: 14px; color: var(--navy); }
-.field input {
+.input, .field input {
   padding: 10px 12px; border-radius: var(--radius);
   border: 1.5px solid var(--border); background: var(--bg);
   color: var(--navy); font-family: Lato, sans-serif; font-size: 15px;
   transition: border-color 0.2s ease, box-shadow 0.2s ease;
 }
-.field input:focus {
+.input:focus, .field input:focus {
   outline: none; border-color: var(--cyan);
   box-shadow: 0 0 0 3px rgba(0, 190, 243, 0.2);
 }

+ 66 - 0
public/assets/js/app.js

@@ -94,6 +94,9 @@ const state = {
   excelResult: null,
   excelQual: { outil: null, personnes: null, consequence: [] },
   excelStep: 1,
+  excelNotified: false,
+  excelSubmitting: false,
+  excelCaptureEmail: '',
 };
 
 let autoAdvanceTimer = null;
@@ -1642,6 +1645,36 @@ function renderExcelTool() {
   ]);
 }
 
+async function submitExcelComplete(withEmail = false) {
+  const r = state.excelResult;
+  if (!r || state.excelSubmitting || state.excelNotified) return;
+  const email = withEmail ? (state.excelCaptureEmail || '').trim() : null;
+  if (withEmail && (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))) return;
+  state.excelSubmitting = true;
+  render();
+  try {
+    const payload = {
+      result: {
+        level: r.level,
+        title: r.title,
+        summary: r.summary,
+        score: r.score,
+        total: r.total,
+        actions: r.actions,
+        qual: r.qual || {},
+      },
+    };
+    if (email) payload.email = email;
+    await apiJson('/excel-complete.php', { method: 'POST', body: payload });
+    state.excelNotified = true;
+    state.excelSubmitting = false;
+  } catch (err) {
+    state.excelSubmitting = false;
+    alert(err?.message || 'Erreur lors de l\'envoi.');
+  }
+  render();
+}
+
 function renderExcelResults() {
   const r = state.excelResult;
   if (!r) { setView('excel'); return h('div', {}); }
@@ -1663,6 +1696,38 @@ function renderExcelResults() {
     ].filter(Boolean)),
   ]) : null;
 
+  const excelNotifyCard = state.excelNotified
+    ? h('div', { class: 'card' }, [
+        h('div', { class: 'h2' }, ['Merci !']),
+        h('p', { class: 'lead' }, ['Votre diagnostic a bien été enregistré.']),
+      ])
+    : h('div', { class: 'card' }, [
+        h('div', { class: 'h2' }, ['Recevoir les résultats par email ?']),
+        h('p', { style: 'margin-bottom:12px;font-size:14px;color:var(--text)' }, [
+          'Optionnel : indiquez votre email pour recevoir une synthèse, ou continuez sans.',
+        ]),
+        h('div', { class: 'btnrow', style: 'gap:8px;flex-wrap:wrap;align-items:center' }, [
+          h('input', {
+            type: 'email',
+            placeholder: 'votre@email.fr',
+            value: state.excelCaptureEmail,
+            class: 'input',
+            style: 'flex:1;min-width:180px',
+            onInput: (e) => { state.excelCaptureEmail = e.target.value; render(); },
+          }),
+          h('button', {
+            class: 'btn btn--primary',
+            disabled: state.excelSubmitting || !(state.excelCaptureEmail || '').trim(),
+            onClick: () => submitExcelComplete(true),
+          }, [state.excelSubmitting ? 'Envoi…' : 'Recevoir par email']),
+          h('button', {
+            class: 'btn btn--outline',
+            disabled: state.excelSubmitting,
+            onClick: () => submitExcelComplete(false),
+          }, ['Continuer sans email']),
+        ]),
+      ]);
+
   return h('div', { class: 'grid' }, [
     h('div', { class: 'card' }, [
       h('div', { style: 'margin-bottom:14px' }, [h('span', { class: 'tag tag--excel' }, ['Excel → Application - Verdict'])]),
@@ -1677,6 +1742,7 @@ function renderExcelResults() {
       ]),
     ]),
     qualCard,
+    excelNotifyCard,
     h('div', { class: 'card' }, [
       h('div', { class: 'h2' }, ['Nos recommandations']),
       h('div', { class: 'excel-actions' }, r.actions.map((action, i) =>

+ 53 - 0
scripts/release.sh

@@ -0,0 +1,53 @@
+#!/bin/bash
+# Release Audit Express Self — à lancer dans Git Bash
+# Usage: ./scripts/release.sh [version]   ex: ./scripts/release.sh 1.1.0
+
+set -e
+cd "$(dirname "$0")/.."
+
+VERSION="${1:-}"
+if [ -z "$VERSION" ]; then
+  echo "Usage: ./scripts/release.sh <version>"
+  echo "Exemple: ./scripts/release.sh 1.1.0"
+  exit 1
+fi
+
+# Format tag
+TAG="v${VERSION}"
+if [[ "$VERSION" == v* ]]; then
+  TAG="$VERSION"
+fi
+
+echo "=== Release Audit Express Self $TAG ==="
+echo ""
+
+# 1. Vérifier état propre
+if [ -n "$(git status --porcelain)" ]; then
+  echo "⚠️  Des modifications non commitées existent."
+  git status --short
+  echo ""
+  read -p "Continuer quand même ? (y/N) " -n 1 -r
+  echo
+  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
+    exit 1
+  fi
+fi
+
+# 2. Composer (si vendor modifié)
+if [ -f composer.json ] && [ ! -d vendor ] || [ composer.lock -nt vendor 2>/dev/null ]; then
+  echo "→ composer install..."
+  composer install --no-dev --ignore-platform-req=ext-mbstring
+fi
+
+# 3. Tag
+echo "→ Création du tag $TAG..."
+git tag -a "$TAG" -m "Release $TAG"
+
+echo ""
+echo "✅ Tag $TAG créé."
+echo ""
+echo "Prochaines étapes :"
+echo "  1. git push origin master"
+echo "  2. git push origin $TAG"
+echo "  3. Déployer sur le serveur (voir docs/RELEASE.md)"
+echo ""

+ 20 - 26
src/AdminNotifier.php

@@ -6,13 +6,13 @@ namespace AuditExpress;
 
 /**
  * Appelle un webhook à chaque soumission (données complètes + PDF en base64).
- * Stocke aussi dans outbox pour traçabilité.
+ * Utilise OutboxStorage pour le stockage local (toujours effectué).
  */
 final class AdminNotifier
 {
     public function __construct(
         private readonly string $webhookUrl,
-        private readonly string $outboxDir
+        private readonly OutboxStorage $outbox
     ) {
     }
 
@@ -21,6 +21,10 @@ final class AdminNotifier
      */
     public function notify(string $source, array $context, string $pdfFilename, string $pdfBytes, ?string $userEmail = null): void
     {
+        // Stockage local (toujours)
+        $this->outbox->store($source, $context, $pdfFilename, $pdfBytes, $userEmail);
+
+        // Appel webhook Make/Zapier
         $payload = [
             'source' => $source,
             'pack_id' => $context['pack_id'] ?? null,
@@ -32,34 +36,24 @@ final class AdminNotifier
             'pdf_filename' => $pdfFilename,
             'pdf_base64' => base64_encode($pdfBytes),
         ];
-
-        // Stockage outbox (toujours, pour traçabilité)
-        $this->storeInOutbox($source, $payload, $pdfFilename, $pdfBytes, $userEmail);
-
-        // Appel webhook
         $this->callWebhook($payload);
     }
 
-    private function storeInOutbox(string $source, array $payload, string $pdfFilename, string $pdfBytes, ?string $userEmail): void
+    /**
+     * Notifie le webhook pour une complétion du diagnostic Excel (sans PDF).
+     * Payload inclut result + user_email (optionnel).
+     */
+    public function notifyExcelComplete(array $result, ?string $userEmail = null): void
     {
-        if (!is_dir($this->outboxDir)) {
-            @mkdir($this->outboxDir, 0775, true);
-        }
-        $id = date('Ymd_His') . '_' . bin2hex(random_bytes(4));
-        $pdfPath = rtrim($this->outboxDir, '/\\') . DIRECTORY_SEPARATOR . $id . '_' . $pdfFilename;
-        file_put_contents($pdfPath, $pdfBytes);
-
-        $meta = $payload;
-        unset($meta['pdf_base64']);
-        $meta['id'] = $id;
-        $meta['type'] = 'admin_notify';
-        $meta['attachment'] = basename($pdfPath);
-        $meta['created_at'] = date(DATE_ATOM);
-
-        file_put_contents(
-            rtrim($this->outboxDir, '/\\') . DIRECTORY_SEPARATOR . $id . '_admin.json',
-            json_encode($meta, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)
-        );
+        $payload = [
+            'source' => 'excel-diagnostic',
+            'tool' => 'transformation-excel',
+            'user_email' => $userEmail,
+            'with_email' => $userEmail !== null && $userEmail !== '',
+            'date' => date('c'),
+            'result' => $result,
+        ];
+        $this->callWebhook($payload);
     }
 
     private function callWebhook(array $payload): void

+ 46 - 3
src/Analytics.php

@@ -33,15 +33,18 @@ final class Analytics
     {
         $fp = fopen($this->file, 'c+');
         if ($fp === false) {
+            error_log('[AuditExpress Analytics] fopen failed: ' . $this->file);
             return;
         }
 
         if (!flock($fp, LOCK_EX)) {
             fclose($fp);
+            // Fallback : flock peut échouer sur certains hébergements/Windows
+            $this->trackFallback($event, $packId);
             return;
         }
 
-        $data = $this->readOrInit($fp);
+        $data = $this->readOrInitFp($fp);
         $today = date('Y-m-d');
 
         // Total global
@@ -103,14 +106,54 @@ final class Analytics
             return $this->defaultStructure();
         }
 
-        $data = $this->readOrInit($fp);
+        $data = $this->readOrInitFp($fp);
         flock($fp, LOCK_UN);
         fclose($fp);
 
         return $data;
     }
 
-    private function readOrInit($fp): array
+    private function trackFallback(string $event, ?string $packId): void
+    {
+        $raw = @file_get_contents($this->file);
+        $data = ($raw !== false && trim($raw) !== '') && is_array($decoded = json_decode($raw, true))
+            ? array_merge($this->defaultStructure(), $decoded)
+            : $this->defaultStructure();
+
+        $today = date('Y-m-d');
+        $data['total'][$event] = ($data['total'][$event] ?? 0) + 1;
+        if ($packId !== null && $packId !== '') {
+            if (!isset($data['by_pack'][$packId])) {
+                $data['by_pack'][$packId] = array_fill_keys(
+                    [self::EVENT_DIA_INIT, self::EVENT_DIA_COMPLETED, self::EVENT_PDF_GENERATED, self::EVENT_EMAIL_CAPTURED],
+                    0
+                );
+            }
+            $data['by_pack'][$packId][$event] = ($data['by_pack'][$packId][$event] ?? 0) + 1;
+        }
+        if (!isset($data['by_day'][$today])) {
+            $data['by_day'][$today] = [
+                self::EVENT_DIA_INIT => 0,
+                self::EVENT_DIA_COMPLETED => 0,
+                self::EVENT_PDF_GENERATED => 0,
+                self::EVENT_EMAIL_CAPTURED => 0,
+            ];
+        }
+        $data['by_day'][$today][$event] = ($data['by_day'][$today][$event] ?? 0) + 1;
+        if ($packId !== null && $packId !== '') {
+            if (!isset($data['by_day'][$today]['by_pack'][$packId])) {
+                $data['by_day'][$today]['by_pack'][$packId] = array_fill_keys(
+                    [self::EVENT_DIA_INIT, self::EVENT_DIA_COMPLETED, self::EVENT_PDF_GENERATED, self::EVENT_EMAIL_CAPTURED],
+                    0
+                );
+            }
+            $data['by_day'][$today]['by_pack'][$packId][$event] = ($data['by_day'][$today]['by_pack'][$packId][$event] ?? 0) + 1;
+        }
+        $data['last_updated'] = date('c');
+        file_put_contents($this->file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), LOCK_EX);
+    }
+
+    private function readOrInitFp($fp): array
     {
         $raw = stream_get_contents($fp);
         if ($raw === false || trim($raw) === '') {

+ 133 - 0
src/OutboxStorage.php

@@ -0,0 +1,133 @@
+<?php
+
+declare(strict_types=1);
+
+namespace AuditExpress;
+
+/**
+ * Stockage local des actions (email, pdf, score) dans storage/outbox.
+ * Organisé par date (YYYY-MM-DD) pour faciliter la consultation.
+ * Indépendant du webhook — stocke toujours pour traçabilité.
+ */
+final class OutboxStorage
+{
+    public function __construct(
+        private readonly string $outboxDir
+    ) {
+    }
+
+    /**
+     * @param array{pack_id?: string, answers?: array, optional?: array, result?: array} $context
+     */
+    public function store(
+        string $source,
+        array $context,
+        string $pdfFilename,
+        string $pdfBytes,
+        ?string $userEmail = null
+    ): string {
+        $dateDir = date('Y-m-d');
+        $dir = rtrim($this->outboxDir, '/\\') . DIRECTORY_SEPARATOR . $dateDir;
+
+        if (!is_dir($dir)) {
+            @mkdir($dir, 0775, true);
+        }
+
+        $id = date('His') . '_' . bin2hex(random_bytes(4));
+        $prefix = $source . '_' . $id;
+
+        // PDF
+        $pdfPath = $dir . DIRECTORY_SEPARATOR . $prefix . '_' . $pdfFilename;
+        file_put_contents($pdfPath, $pdfBytes);
+
+        // Métadonnées (sans le PDF en base64)
+        $meta = [
+            'id' => $prefix,
+            'source' => $source,
+            'pack_id' => $context['pack_id'] ?? null,
+            'user_email' => $userEmail,
+            'date' => date(DATE_ATOM),
+            'answers' => $context['answers'] ?? [],
+            'optional' => $context['optional'] ?? [],
+            'result' => $context['result'] ?? [],
+            'attachment' => basename($pdfPath),
+        ];
+
+        $metaPath = $dir . DIRECTORY_SEPARATOR . $prefix . '.json';
+        file_put_contents(
+            $metaPath,
+            json_encode($meta, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)
+        );
+
+        return $prefix;
+    }
+
+    /**
+     * Stocke une demande "prévenir au lancement" (notify) sans PDF.
+     */
+    public function storeNotify(string $tool, string $email): string
+    {
+        $dateDir = date('Y-m-d');
+        $dir = rtrim($this->outboxDir, '/\\') . DIRECTORY_SEPARATOR . $dateDir;
+
+        if (!is_dir($dir)) {
+            @mkdir($dir, 0775, true);
+        }
+
+        $id = date('His') . '_' . bin2hex(random_bytes(4));
+        $prefix = 'notify_' . $id;
+
+        $meta = [
+            'id' => $prefix,
+            'source' => 'notify',
+            'tool' => $tool,
+            'user_email' => $email,
+            'date' => date(DATE_ATOM),
+        ];
+
+        $metaPath = $dir . DIRECTORY_SEPARATOR . $prefix . '.json';
+        file_put_contents(
+            $metaPath,
+            json_encode($meta, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)
+        );
+
+        return $prefix;
+    }
+
+    /**
+     * Stocke une complétion du diagnostic Excel (avec ou sans email).
+     * Permet de notifier l'admin dans les deux cas.
+     *
+     * @param array{level: string, title: string, summary: string, score: int, total: int, actions: array, qual?: array} $result
+     */
+    public function storeExcelComplete(array $result, ?string $userEmail = null): string
+    {
+        $dateDir = date('Y-m-d');
+        $dir = rtrim($this->outboxDir, '/\\') . DIRECTORY_SEPARATOR . $dateDir;
+
+        if (!is_dir($dir)) {
+            @mkdir($dir, 0775, true);
+        }
+
+        $id = date('His') . '_' . bin2hex(random_bytes(4));
+        $prefix = 'excel_' . $id;
+
+        $meta = [
+            'id' => $prefix,
+            'source' => 'excel-diagnostic',
+            'tool' => 'transformation-excel',
+            'user_email' => $userEmail,
+            'with_email' => $userEmail !== null && $userEmail !== '',
+            'date' => date(DATE_ATOM),
+            'result' => $result,
+        ];
+
+        $metaPath = $dir . DIRECTORY_SEPARATOR . $prefix . '.json';
+        file_put_contents(
+            $metaPath,
+            json_encode($meta, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)
+        );
+
+        return $prefix;
+    }
+}