app.js 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  1. /* Audit Express Self — Livinweb */
  2. const appEl = document.getElementById('app');
  3. const API_BASE = appEl?.dataset?.apiBase || '/api';
  4. const BOOKING_URL = appEl?.dataset?.bookingUrl || '';
  5. const DEVIS_URL = appEl?.dataset?.devisUrl || '';
  6. /* ── Catalogue packs ── */
  7. const PACK_CATALOGUE = [
  8. {
  9. id: 'onboarding-v1',
  10. title: 'Onboarding collaborateur',
  11. desc: "Fiabilisez l'intégration de vos nouveaux collaborateurs : clarté du flux, traçabilité, continuité.",
  12. tag: 'Pré-configuré',
  13. tagStyle: 'tag--pre',
  14. },
  15. {
  16. id: 'validation-facture',
  17. title: 'Validation de facture',
  18. desc: 'Contrôles, séparation des tâches, preuve : évaluez la robustesse de votre circuit factures.',
  19. tag: 'Pré-configuré',
  20. tagStyle: 'tag--pre',
  21. },
  22. {
  23. id: 'process-generique',
  24. title: 'Process générique',
  25. desc: 'Applicable à tout process opérationnel : achat, production, relation client, support, projet…',
  26. tag: 'Universel',
  27. tagStyle: 'tag--new',
  28. },
  29. {
  30. id: 'process-generique-v2',
  31. title: 'Diagnostic d\'opportunité',
  32. desc: 'Évaluez sur 8 axes si ce process est prioritaire à automatiser : friction, volume, risque, données, outils, variabilité, collaboration, déploiement.',
  33. tag: 'Diagnostic d\'opportunité',
  34. tagStyle: 'tag--v2',
  35. },
  36. ];
  37. /* ── Outils à venir ── */
  38. const COMING_SOON_TOOLS = [
  39. {
  40. id: 'process-mapper',
  41. title: 'Process Mapper',
  42. desc: 'Cartographiez visuellement votre process étape par étape, identifiez les goulots d\'étranglement et générez une documentation structurée prête à partager.',
  43. },
  44. ];
  45. const state = {
  46. view: 'landing',
  47. packId: null,
  48. pack: null,
  49. idx: 0,
  50. answers: {},
  51. optional: {},
  52. result: null,
  53. emailUnlocked: false,
  54. unlockExiting: false,
  55. captureEmail: '',
  56. notifyTool: '',
  57. roiInputs: { volume: '', tempsActuel: '', tempsCible: '', coutHoraire: '', tauxErreurs: '', tempsErreur: '', delaiActuel: '', delaiCible: '' },
  58. roiResult: null,
  59. qwfSignals: {},
  60. qwfResult: null,
  61. };
  62. let autoAdvanceTimer = null;
  63. /* ── DOM helpers ── */
  64. function h(tag, attrs = {}, children = []) {
  65. const el = document.createElement(tag);
  66. for (const [k, v] of Object.entries(attrs || {})) {
  67. if (k === 'class') el.className = v;
  68. else if (k.startsWith('on') && typeof v === 'function') el.addEventListener(k.slice(2).toLowerCase(), v);
  69. else if (v !== undefined && v !== null && v !== false) el.setAttribute(k, String(v));
  70. }
  71. for (const child of (Array.isArray(children) ? children : [children])) {
  72. if (child == null) continue;
  73. el.appendChild(typeof child === 'string' ? document.createTextNode(child) : child);
  74. }
  75. return el;
  76. }
  77. function storageKey(packId) { return `aes_${packId}_v1`; }
  78. function saveProgress() {
  79. if (!state.packId) return;
  80. localStorage.setItem(storageKey(state.packId), JSON.stringify({ answers: state.answers, optional: state.optional }));
  81. }
  82. function loadProgress(packId) {
  83. try {
  84. const obj = JSON.parse(localStorage.getItem(storageKey(packId)) || '{}');
  85. return {
  86. answers: typeof obj?.answers === 'object' ? obj.answers : {},
  87. optional: typeof obj?.optional === 'object' ? obj.optional : {},
  88. };
  89. } catch { return { answers: {}, optional: {} }; }
  90. }
  91. async function apiJson(path, { method = 'GET', body } = {}) {
  92. const headers = {};
  93. if (body) {
  94. headers['Content-Type'] = 'application/json';
  95. const csrf = appEl?.dataset?.csrfToken;
  96. if (csrf) headers['X-CSRF-Token'] = csrf;
  97. }
  98. const res = await fetch(`${API_BASE}${path}`, {
  99. method,
  100. headers: Object.keys(headers).length ? headers : undefined,
  101. body: body ? JSON.stringify(body) : undefined,
  102. credentials: 'same-origin',
  103. });
  104. const data = await res.json().catch(() => ({}));
  105. if (!res.ok) throw new Error(data?.error || 'Erreur API');
  106. return data;
  107. }
  108. function setView(v) { state.view = v; render(); }
  109. function goStart() {
  110. Object.assign(state, { packId: null, pack: null, idx: 0, answers: {}, optional: {}, result: null, emailUnlocked: false, unlockExiting: false, captureEmail: '' });
  111. setView('landing');
  112. }
  113. async function selectPack(packId) {
  114. state.packId = packId;
  115. const saved = loadProgress(packId);
  116. state.answers = saved.answers;
  117. state.optional = saved.optional;
  118. try {
  119. const data = await apiJson(`/pack.php?pack=${encodeURIComponent(packId)}`);
  120. state.pack = data.pack;
  121. state.idx = 0;
  122. setView('intro');
  123. } catch (e) {
  124. alert('Impossible de charger le pack : ' + (e.message || ''));
  125. }
  126. }
  127. function levelColor(level) {
  128. return { A: '#1e8a5e', B: '#1e8a5e', C: '#c07c10', D: '#b83040' }[level] || '#2F506D';
  129. }
  130. /* ── COMING-SOON card helper ── */
  131. function makeComingSoonCard(tool) {
  132. return h('div', {
  133. class: 'pack-card pack-card--soon',
  134. onClick: () => {
  135. state.notifyTool = tool.id;
  136. document.getElementById('notifyDialog')?.showModal();
  137. },
  138. }, [
  139. h('span', { class: 'tag tag--soon' }, ['Bientôt disponible']),
  140. h('div', { class: 'title', style: 'margin-top:8px' }, [tool.title]),
  141. h('div', { class: 'desc' }, [tool.desc]),
  142. h('div', { class: 'soon-overlay' }, [
  143. h('div', { class: 'soon-overlay__label' }, ['Bientôt disponible']),
  144. h('div', { class: 'soon-overlay__text' }, ['Me notifier du lancement →']),
  145. ]),
  146. ]);
  147. }
  148. /* ── NOTIFY DIALOG (Coming soon) ── */
  149. function renderNotifyDialog() {
  150. const toolMeta = COMING_SOON_TOOLS.find(t => t.id === state.notifyTool);
  151. const toolName = toolMeta?.title || 'cet outil';
  152. const onSubmit = async (e) => {
  153. e.preventDefault();
  154. const email = e.target.querySelector('input[type="email"]').value.trim();
  155. if (!email) return;
  156. const btn = e.target.querySelector('button[type="submit"]');
  157. btn.disabled = true;
  158. btn.textContent = 'Envoi…';
  159. try {
  160. await apiJson('/notify.php', { method: 'POST', body: { email, tool: state.notifyTool } });
  161. const body = document.querySelector('#notifyDialog .dialog__body');
  162. if (body) {
  163. body.innerHTML = '';
  164. body.appendChild(h('div', { style: 'text-align:center;padding:20px 0' }, [
  165. h('div', { class: 'h2', style: 'color:var(--good);margin-bottom:8px' }, ['C\'est noté !']),
  166. h('p', { class: 'lead' }, [`Vous serez parmi les premiers informés du lancement de ${toolName}.`]),
  167. h('button', {
  168. class: 'btn btn--primary', style: 'margin-top:16px',
  169. onClick: () => document.getElementById('notifyDialog')?.close(),
  170. }, ['Fermer']),
  171. ]));
  172. }
  173. } catch (err) {
  174. btn.disabled = false;
  175. btn.textContent = 'Me prévenir au lancement →';
  176. alert('Erreur : ' + (err.message || 'Réessayez.'));
  177. }
  178. };
  179. return h('dialog', { id: 'notifyDialog', class: 'dialog' }, [
  180. h('div', { class: 'dialog__inner' }, [
  181. h('div', { class: 'dialog__head' }, [
  182. h('strong', {}, [`Soyez informé : ${toolName}`]),
  183. h('button', {
  184. class: 'btn btn--outline', style: 'padding:6px 12px;font-size:13px', type: 'button',
  185. onClick: () => document.getElementById('notifyDialog')?.close(),
  186. }, ['Fermer']),
  187. ]),
  188. h('div', { class: 'dialog__body' }, [
  189. h('p', { class: 'lead', style: 'margin-bottom:16px' }, [
  190. `${toolName} est en cours de développement. Laissez votre email et on vous prévient en priorité au lancement.`,
  191. ]),
  192. h('form', { onSubmit }, [
  193. h('div', { class: 'field' }, [
  194. h('label', { for: 'notifyEmail' }, ['Email professionnel']),
  195. h('input', {
  196. id: 'notifyEmail', type: 'email', required: 'required',
  197. placeholder: 'vous@entreprise.com', autocomplete: 'email',
  198. }),
  199. ]),
  200. h('div', { class: 'btnrow', style: 'margin-top:14px' }, [
  201. h('button', { class: 'btn btn--primary', type: 'submit' }, ['Me prévenir au lancement →']),
  202. ]),
  203. h('p', { class: 'hint' }, ['Aucun spam. Désabonnement en 1 clic.']),
  204. ]),
  205. ]),
  206. ]),
  207. ]);
  208. }
  209. /* ── LANDING (page d'accueil) ── */
  210. const DIAGNOSTIC_PROCESS_TOOL = {
  211. id: 'diagnostic-process',
  212. title: 'Diagnostique process',
  213. desc: 'Choisissez un pack pré-configuré (onboarding, validation de facture) ou le questionnaire universel. Évaluez votre process en 7 minutes.',
  214. };
  215. function renderLanding() {
  216. const diagnosticV2 = PACK_CATALOGUE.find(p => p.id === 'process-generique-v2');
  217. const tools = [
  218. h('div', { class: 'pack-card', onClick: () => setView('select') }, [
  219. h('span', { class: 'tag tag--pre' }, ['Diagnostic']),
  220. h('div', { class: 'title' }, [DIAGNOSTIC_PROCESS_TOOL.title, h('span', { class: 'arrow' }, [' →'])]),
  221. h('div', { class: 'desc' }, [DIAGNOSTIC_PROCESS_TOOL.desc]),
  222. ]),
  223. diagnosticV2 ? h('div', { class: 'pack-card', onClick: () => selectPack(diagnosticV2.id) }, [
  224. h('span', { class: `tag ${diagnosticV2.tagStyle}` }, [diagnosticV2.tag]),
  225. h('div', { class: 'title' }, [diagnosticV2.title, h('span', { class: 'arrow' }, [' →'])]),
  226. h('div', { class: 'desc' }, [diagnosticV2.desc]),
  227. ]) : null,
  228. h('div', { class: 'pack-card', onClick: () => setView('roi') }, [
  229. h('span', { class: 'tag tag--roi' }, ['ROI Calculator']),
  230. h('div', { class: 'title' }, ['ROI Calculator', h('span', { class: 'arrow' }, [' →'])]),
  231. h('div', { class: 'desc' }, ['Transformez "ça nous coûte" en "ça vaut X €". 10 questions pour chiffrer le gain mensuel, le ROI annuel et les 2 leviers qui pèsent le plus.']),
  232. ]),
  233. h('div', { class: 'pack-card', onClick: () => setView('qwf') }, [
  234. h('span', { class: 'tag tag--qwf' }, ['Quick Wins Finder']),
  235. h('div', { class: 'title' }, ['Quick Wins Finder', h('span', { class: 'arrow' }, [' →'])]),
  236. h('div', { class: 'desc' }, ['3 actions concrètes et personnalisées basées sur vos signaux — résultat attendu, effort estimé et délai typique pour chaque recommandation.']),
  237. ]),
  238. BOOKING_URL ? h('a', {
  239. class: 'pack-card pack-card--link',
  240. href: BOOKING_URL,
  241. target: '_blank',
  242. rel: 'noreferrer',
  243. }, [
  244. h('span', { class: 'tag tag--booking' }, ['Prise de décision']),
  245. h('div', { class: 'title' }, ['Faisabilité d\'automatisation d\'un process', h('span', { class: 'arrow' }, [' →'])]),
  246. h('div', { class: 'desc' }, ['Moins d\'une heure. Prenez rendez-vous pour évaluer ensemble si votre process est prioritaire à automatiser.']),
  247. ]) : null,
  248. ].filter(Boolean);
  249. return h('div', { class: 'grid' }, [
  250. h('div', { class: 'card' }, [
  251. h('h1', { class: 'h1' }, ['Choisissez un outil']),
  252. h('p', { class: 'lead' }, ['Diagnostiquez vos process opérationnels.']),
  253. h('div', { class: 'section-label', style: 'margin-top:18px' }, ['Outils disponibles']),
  254. h('div', { class: 'grid grid--2' }, tools),
  255. h('div', { class: 'section-label', style: 'margin-top:18px' }, ['Bientôt disponible']),
  256. h('div', { class: 'grid grid--2' }, COMING_SOON_TOOLS.map(makeComingSoonCard)),
  257. ]),
  258. renderNotifyDialog(),
  259. ]);
  260. }
  261. /* ── SELECT (page Diagnostic process) ── */
  262. function renderSelect() {
  263. const makeCard = (p) =>
  264. h('div', { class: 'pack-card', onClick: () => selectPack(p.id) }, [
  265. h('span', { class: `tag ${p.tagStyle}` }, [p.tag]),
  266. h('div', { class: 'title' }, [p.title, h('span', { class: 'arrow' }, [' →'])]),
  267. h('div', { class: 'desc' }, [p.desc]),
  268. ]);
  269. const preConfigured = PACK_CATALOGUE.filter(p => p.tag === 'Pré-configuré');
  270. const generic = PACK_CATALOGUE.find(p => p.id === 'process-generique');
  271. return h('div', { class: 'grid' }, [
  272. h('div', { class: 'card' }, [
  273. h('h1', { class: 'h1' }, ['Choisissez le process à diagnostiquer']),
  274. h('p', { class: 'lead' }, ['Sélectionnez un pack pré-configuré ou utilisez le questionnaire universel.']),
  275. h('div', { class: 'section-label', style: 'margin-top:18px' }, ['Packs pré-configurés']),
  276. h('div', { class: 'grid grid--2' }, preConfigured.map(makeCard)),
  277. h('div', { class: 'section-label', style: 'margin-top:18px' }, ['Process universel']),
  278. h('div', { class: 'grid grid--2' }, generic ? [makeCard(generic)] : []),
  279. h('div', { class: 'btnrow', style: 'margin-top:18px' }, [
  280. h('button', { class: 'btn btn--outline', onClick: () => setView('landing') }, ['← Retour']),
  281. ]),
  282. ]),
  283. ]);
  284. }
  285. /* ── INTRO ── */
  286. function renderIntro() {
  287. const meta = PACK_CATALOGUE.find(p => p.id === state.packId);
  288. const answeredCount = Object.keys(state.answers).length;
  289. const total = state.pack?.questions?.length || 20;
  290. const hasSaved = answeredCount > 0;
  291. const startFresh = () => {
  292. state.answers = {};
  293. state.optional = {};
  294. state.idx = 0;
  295. state.emailUnlocked = false;
  296. state.unlockExiting = false;
  297. state.captureEmail = '';
  298. saveProgress();
  299. setView('quiz');
  300. };
  301. const resume = () => {
  302. const qs = state.pack?.questions || [];
  303. let resumeIdx = 0;
  304. for (let i = 0; i < qs.length; i++) {
  305. if (state.answers[qs[i].id]) resumeIdx = i;
  306. }
  307. state.idx = Math.min(resumeIdx + 1, qs.length - 1);
  308. setView('quiz');
  309. };
  310. return h('div', { class: 'grid' }, [
  311. h('div', { class: 'card' }, [
  312. h('span', { class: `tag ${meta?.tagStyle || ''}`, style: 'margin-bottom:12px;display:inline-block' }, [
  313. state.pack?.pack_title || '',
  314. ]),
  315. h('h1', { class: 'h1' }, ['Avant de commencer']),
  316. h('p', { class: 'lead' }, [
  317. 'Répondez franchement. Le score sert à prioriser, pas à juger. ',
  318. 'Temps estimé : 7 minutes. Questions : 20.',
  319. ]),
  320. state.pack?.pack_description
  321. ? h('p', { style: 'color:var(--muted);font-size:14px;margin-top:0' }, [state.pack.pack_description])
  322. : null,
  323. hasSaved
  324. ? h('div', { class: 'resume-notice' }, [
  325. h('span', {}, [`Progression sauvegardée : ${answeredCount} / ${total} questions`]),
  326. ])
  327. : null,
  328. h('div', { class: 'btnrow' }, [
  329. h('button', { class: 'btn btn--outline', onClick: () => setView('select') }, ['← Choisir un autre pack']),
  330. hasSaved
  331. ? h('button', { class: 'btn btn--outline', onClick: startFresh }, ['Recommencer à zéro'])
  332. : null,
  333. h('button', { class: 'btn btn--primary', onClick: hasSaved ? resume : startFresh }, [
  334. hasSaved ? `Reprendre (Q${Math.min(Object.keys(state.answers).length + 1, total)}) →` : 'Commencer →',
  335. ]),
  336. ]),
  337. ]),
  338. ]);
  339. }
  340. /* ── QUIZ ── */
  341. function renderQuiz() {
  342. const q = state.pack?.questions?.[state.idx];
  343. if (!q) return h('div', { class: 'card' }, ['Chargement…']);
  344. const total = state.pack.questions.length;
  345. const pos = state.idx + 1;
  346. const pct = Math.round(((pos - 1) / total) * 100);
  347. const selected = state.answers[q.id] || '';
  348. const opts = (q.options || []).map(opt => {
  349. const id = `opt_${q.id}_${opt.id}`;
  350. const isSelected = selected === opt.id;
  351. const isNa = opt.id === 'NA' || opt.id.toLowerCase().endsWith('_na');
  352. return h('label', { class: `opt${isSelected ? ' opt--selected' : ''}${isNa ? ' opt--na' : ''}`, for: id }, [
  353. h('input', {
  354. id, type: 'radio', name: q.id, value: opt.id,
  355. checked: isSelected ? 'checked' : null,
  356. onChange: (e) => {
  357. state.answers[q.id] = e.target.value;
  358. saveProgress();
  359. render();
  360. if (autoAdvanceTimer) clearTimeout(autoAdvanceTimer);
  361. autoAdvanceTimer = setTimeout(() => {
  362. autoAdvanceTimer = null;
  363. const t = state.pack?.questions?.length || 0;
  364. if (state.idx < t - 1) { state.idx++; saveProgress(); render(); }
  365. else setView('optional');
  366. }, 380);
  367. },
  368. }),
  369. h('div', {}, [h('strong', {}, [opt.label])]),
  370. ]);
  371. });
  372. const canPrev = state.idx > 0;
  373. const canNext = !!selected;
  374. const isLast = state.idx === total - 1;
  375. const next = async () => {
  376. if (!canNext) return;
  377. if (!isLast) { state.idx++; saveProgress(); render(); return; }
  378. setView('optional');
  379. };
  380. return h('div', { class: 'grid' }, [
  381. h('div', { class: 'card' }, [
  382. h('div', { class: 'quizHead' }, [
  383. h('span', { class: 'tag', style: 'font-size:11px' }, [state.pack.pack_title]),
  384. h('div', { class: 'quizStep' }, [
  385. h('strong', {}, [`${pos}`]),
  386. h('span', {}, [` / ${total}`]),
  387. ]),
  388. ]),
  389. h('div', { class: 'progressWrap' }, [
  390. h('div', { class: 'progress' }, [h('div', { style: `width:${pct}%` })]),
  391. h('div', { class: 'progressMeta' }, [
  392. h('span', { class: 'progressPct' }, [`${pct}\u00a0%`]),
  393. h('span', { class: 'progressRemain' }, [
  394. isLast ? 'Dernière question' : `encore ${total - pos} question${total - pos > 1 ? 's' : ''}`,
  395. ]),
  396. ]),
  397. ]),
  398. h('div', { class: 'qTitle' }, [q.label]),
  399. q.help ? h('p', { class: 'qHelp' }, [q.help]) : null,
  400. h('div', { class: 'options' }, opts),
  401. h('div', { class: 'btnrow', style: 'margin-top:18px' }, [
  402. h('button', { class: 'btn btn--outline', disabled: canPrev ? null : 'disabled', onClick: () => { state.idx--; saveProgress(); render(); } }, ['← Précédent']),
  403. h('button', { class: `btn ${canNext ? 'btn--primary' : 'btn--outline'}`, disabled: canNext ? null : 'disabled', onClick: next }, [
  404. isLast ? 'Voir mon résultat →' : 'Suivant →',
  405. ]),
  406. ]),
  407. h('p', { class: 'hint', style: 'margin-top:10px' }, ['Vous pouvez modifier vos réponses avant la fin.']),
  408. ]),
  409. ]);
  410. }
  411. /* ── OPTIONAL ── */
  412. function renderOptional() {
  413. const opt = state.pack?.optional_questions || {};
  414. const volumeKey = Object.keys(opt).find(k => opt[k]?.required_for_cost);
  415. const volumeQ = volumeKey ? opt[volumeKey] : null;
  416. const hourlyQ = opt.hourly_cost || null;
  417. const makeRadioGroup = (q, stateKey) => {
  418. const cur = state.optional[stateKey];
  419. return h('div', { class: 'field' }, [
  420. h('label', {}, [q.label]),
  421. h('div', { class: 'options', style: 'margin-top:6px' }, q.options.map(o => {
  422. const id = `opt_${stateKey}_${o.id}`;
  423. const val = String(o.value ?? o.id);
  424. return h('label', { class: 'opt', for: id }, [
  425. h('input', {
  426. id, type: 'radio', name: stateKey, value: val,
  427. checked: String(cur) === val ? 'checked' : null,
  428. onChange: (e) => { state.optional[stateKey] = Number(e.target.value); saveProgress(); },
  429. }),
  430. h('div', {}, [h('strong', {}, [o.label])]),
  431. ]);
  432. })),
  433. ]);
  434. };
  435. const compute = async () => {
  436. try {
  437. const data = await apiJson('/score.php', {
  438. method: 'POST',
  439. body: { pack_id: state.packId, answers: state.answers, optional: state.optional },
  440. });
  441. state.result = data.result;
  442. saveProgress();
  443. setView('results');
  444. } catch (e) { alert(e.message || 'Erreur'); }
  445. };
  446. return h('div', { class: 'grid' }, [
  447. h('div', { class: 'card' }, [
  448. h('span', { class: 'tag tag--new', style: 'margin-bottom:12px;display:inline-block' }, ['Optionnel']),
  449. h('h1', { class: 'h1' }, ['Quelques infos pour le coût caché']),
  450. h('p', { class: 'lead' }, ['Ces données servent uniquement à estimer le coût caché en heures/mois (indicatif). Vous pouvez passer.']),
  451. volumeQ ? makeRadioGroup(volumeQ, volumeKey) : null,
  452. hourlyQ ? makeRadioGroup(hourlyQ, 'hourly_cost') : null,
  453. h('div', { class: 'btnrow', style: 'margin-top:20px' }, [
  454. h('button', { class: 'btn btn--outline', onClick: () => setView('quiz') }, ['← Retour']),
  455. h('button', { class: 'btn btn--primary', onClick: compute }, ['Voir mes résultats →']),
  456. ]),
  457. ]),
  458. ]);
  459. }
  460. /* ── RESULTS ── */
  461. function renderResults() {
  462. const r = state.result;
  463. if (!r) return h('div', { class: 'card' }, ['Calcul en cours…']);
  464. const dotColor = levelColor(r.level);
  465. const cost = r.cost_hidden;
  466. const unlocked = state.emailUnlocked;
  467. const pillarRows = (r.pillars || []).map(p => {
  468. const pct = p.max ? Math.round((p.score / p.max) * 100) : 0;
  469. return h('div', { class: 'pRow' }, [
  470. h('div', { class: 'name' }, [p.label]),
  471. h('div', { class: 'val' }, [`${p.score}/${p.max}`]),
  472. h('div', { class: 'bar' }, [h('div', { style: `width:${pct}%` })]),
  473. ]);
  474. });
  475. const riskItems = (r.risks_top3 || []).map(x =>
  476. h('li', {}, [
  477. h('strong', {}, [x.title]),
  478. h('div', { class: 'hint' }, [x.what_happens]),
  479. ])
  480. );
  481. const winItems = (r.quick_wins_preview || []).map(x =>
  482. h('li', {}, [
  483. h('strong', {}, [x.title]),
  484. h('div', { class: 'hint' }, [`${x.effect} · Effort : ${x.effort}`]),
  485. ])
  486. );
  487. /* ── V2 Diagnostic ── */
  488. const v2 = r.v2_diagnostic || null;
  489. const renderV2Diagnostic = () => {
  490. if (!v2) return null;
  491. const potColor = v2.potentiel >= 70 ? '#1e8a5e' : v2.potentiel >= 40 ? '#c07c10' : '#b83040';
  492. const cplxColor = v2.complexite <= 35 ? '#1e8a5e' : v2.complexite <= 65 ? '#c07c10' : '#b83040';
  493. const verdictColor = { prioritaire: '#1e8a5e', candidat: '#c07c10', attente: '#5e789a' }[v2.verdict.code] || '#2F506D';
  494. const meter = (score, label, color) =>
  495. h('div', { class: 'v2-meter' }, [
  496. h('div', { class: 'v2-meter__num', style: `color:${color}` }, [String(score)]),
  497. h('div', { class: 'v2-meter__sub' }, ['/100']),
  498. h('div', { class: 'v2-meter__lbl' }, [label]),
  499. h('div', { class: 'v2-meter__track' }, [
  500. h('div', { class: 'v2-meter__fill', style: `width:${score}%;background:${color}` }),
  501. ]),
  502. ]);
  503. return h('div', { class: 'card v2-diagnostic' }, [
  504. h('div', { class: 'v2-meters' }, [
  505. meter(v2.potentiel, 'Potentiel d\'automatisation', potColor),
  506. meter(v2.complexite, 'Complexité de mise en œuvre', cplxColor),
  507. ]),
  508. h('div', { class: 'v2-badges' }, [
  509. h('span', { class: 'v2-verdict-badge', style: `border-color:${verdictColor};color:${verdictColor}` }, [
  510. `${v2.verdict.label} — ${v2.verdict.desc}`,
  511. ]),
  512. h('span', { class: `v2-tag-badge${v2.tag === 'quick_win' ? ' v2-tag-badge--qw' : ' v2-tag-badge--proj'}` }, [
  513. v2.tag_label,
  514. ]),
  515. ]),
  516. ]);
  517. };
  518. const renderMiniPlan = () => {
  519. if (!v2 || !unlocked) return null;
  520. const actionList = (items, startNum) =>
  521. h('ol', { class: 'v2-plan-list', start: String(startNum) },
  522. (items || []).map(a => h('li', {}, [
  523. h('strong', {}, [a.title]),
  524. h('span', { class: 'hint' }, [` — ${a.effect} · Effort : ${a.effort}`]),
  525. ]))
  526. );
  527. return h('div', { class: 'v2-mini-plan' }, [
  528. h('div', { class: 'v2-plan-cols' }, [
  529. h('div', { class: 'card v2-plan-section' }, [
  530. h('div', { class: 'v2-plan-title' }, ['3 actions immédiates']),
  531. actionList(v2.actions, 1),
  532. ]),
  533. h('div', { class: 'card v2-plan-section v2-plan-section--qw' }, [
  534. h('div', { class: 'v2-plan-title' }, ['2 quick wins possibles']),
  535. actionList(v2.quick_wins, 4),
  536. ]),
  537. ]),
  538. v2.risque_majeur ? h('div', { class: 'v2-plan-risk-block' }, [
  539. h('div', { class: 'v2-plan-title v2-plan-title--risk' }, ['1 risque majeur à adresser en parallèle']),
  540. h('div', { class: 'v2-plan-risk-card' }, [
  541. h('strong', {}, [v2.risque_majeur.title]),
  542. h('p', { class: 'hint', style: 'margin-top:4px' }, [v2.risque_majeur.what_happens]),
  543. ]),
  544. ]) : null,
  545. ]);
  546. };
  547. /* ── Unlock gate ── */
  548. const renderUnlockGate = () => {
  549. const onUnlock = (e) => {
  550. e.preventDefault();
  551. const email = e.target.querySelector('input[type="email"]').value.trim();
  552. if (!email.includes('@') || email.length < 5) return;
  553. state.captureEmail = email;
  554. state.unlockExiting = true;
  555. render();
  556. setTimeout(() => {
  557. state.emailUnlocked = true;
  558. state.unlockExiting = false;
  559. saveProgress();
  560. render();
  561. setTimeout(() => document.getElementById('pdfDialog')?.showModal(), 50);
  562. }, 320);
  563. };
  564. const exiting = state.unlockExiting;
  565. return h('div', { class: 'unlock-gate' + (exiting ? ' unlock-gate--exiting' : '') }, [
  566. h('div', { class: 'unlock-gate__inner' }, [
  567. h('div', { class: 'unlock-gate__icon' }, ['↓']),
  568. h('div', { class: 'h2', style: 'margin-bottom:6px' }, ['Débloquez vos axes d\'amélioration']),
  569. h('p', { class: 'lead', style: 'margin-bottom:20px' }, [
  570. 'Entrez votre email professionnel pour accéder aux 5 actions prioritaires et télécharger votre PDF synthèse.',
  571. ]),
  572. h('form', { class: 'unlock-form', onSubmit: onUnlock }, [
  573. h('div', { class: 'unlock-row' }, [
  574. h('input', {
  575. type: 'email', required: 'required',
  576. placeholder: 'vous@entreprise.com',
  577. autocomplete: 'email',
  578. }),
  579. h('button', { class: 'btn btn--primary btn--unlock', type: 'submit' }, ['Débloquer →']),
  580. ]),
  581. h('p', { class: 'hint', style: 'margin-top:8px;text-align:center' }, [
  582. 'Aucun spam. Désinscription en 1 clic.',
  583. ]),
  584. ]),
  585. ]),
  586. ]);
  587. };
  588. /* ── CTAs débloqués ── */
  589. const renderUnlockedCtas = () =>
  590. h('div', { class: 'unlocked-ctas unlocked-ctas--entering' }, [
  591. h('div', { class: 'unlocked-ctas__inner' }, [
  592. /* En-tête */
  593. h('div', { class: 'h2', style: 'margin-bottom:6px' }, ['Et maintenant ?']),
  594. h('p', { class: 'lead', style: 'margin-bottom:24px' }, [
  595. '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.',
  596. ]),
  597. /* CTAs commerciaux */
  598. h('div', { class: 'cta-block' }, [
  599. BOOKING_URL ? h('div', { style: 'display:flex;flex-direction:column;align-items:center;width:100%' }, [
  600. h('span', { class: 'cta-offert' }, ['30 min offert']),
  601. h('a', {
  602. class: 'btn btn--primary btn--cta-main',
  603. href: BOOKING_URL, target: '_blank', rel: 'noreferrer',
  604. }, ['Découvrir les opportunités suite à mon audit — Entretien de 30 min offert avec un consultant']),
  605. ]) : null,
  606. DEVIS_URL ? h('a', {
  607. class: 'btn btn--outline btn--cta-secondary',
  608. href: DEVIS_URL,
  609. }, ['Demander un devis']) : null,
  610. ]),
  611. h('p', { class: 'hint', style: 'text-align:center;margin-top:10px' }, [
  612. 'Pas d\'engagement. On analyse vos résultats ensemble et on vous propose une solution adaptée.',
  613. ]),
  614. /* Séparateur */
  615. h('hr', { style: 'border:none;border-top:1px solid var(--border,#e2e8f0);margin:24px 0' }),
  616. /* Actions secondaires */
  617. h('div', { class: 'btnrow', style: 'justify-content:center;gap:10px' }, [
  618. h('button', {
  619. class: 'btn btn--outline',
  620. onClick: () => document.getElementById('pdfDialog')?.showModal(),
  621. }, ['Télécharger mon PDF']),
  622. h('button', {
  623. class: 'btn btn--outline',
  624. style: 'font-size:13px',
  625. onClick: goStart,
  626. }, ['Diagnostiquer un autre process']),
  627. ]),
  628. ]),
  629. ]);
  630. return h('div', { class: 'grid' }, [
  631. /* Score header */
  632. h('div', { class: 'card' }, [
  633. h('div', { style: 'display:flex;align-items:center;gap:10px;margin-bottom:16px' }, [
  634. h('span', { class: 'tag' }, [state.pack?.pack_title || '']),
  635. ]),
  636. h('div', { class: 'scoreBox' }, [
  637. h('div', {}, [
  638. h('div', { class: 'scoreLabel' }, ['Score global']),
  639. h('div', { class: 'scoreBig' }, [`${r.score_total}/100`]),
  640. h('div', { class: 'level-badge', style: 'margin-top:10px' }, [
  641. h('span', { class: 'level-dot', style: `background:${dotColor}` }),
  642. h('span', {}, [`${r.level} — ${r.level_label}`]),
  643. ]),
  644. h('div', { class: 'confidence' }, [`Confiance du diagnostic : ${r.confidence?.label || ''}`]),
  645. ]),
  646. ]),
  647. h('div', { class: 'pillars' }, pillarRows),
  648. ]),
  649. /* V2 : carte diagnostic (toujours visible) */
  650. v2 ? renderV2Diagnostic() : null,
  651. /* Non-V2 : risques (visibles uniquement après déblocage) */
  652. !v2 && unlocked && !state.unlockExiting ? h('div', { class: 'card' }, [
  653. h('div', { class: 'h2' }, ['3 risques probables']),
  654. riskItems.length
  655. ? h('ol', { class: 'list' }, riskItems)
  656. : h('p', { class: 'muted small' }, ['Aucun risque majeur détecté.']),
  657. ]) : null,
  658. /* Non-V2 : coût caché (visible uniquement après déblocage) */
  659. !v2 && unlocked && !state.unlockExiting && cost ? h('div', { class: 'cost-block' }, [
  660. h('div', { class: 'h2' }, ['Coût caché estimé']),
  661. h('div', { class: 'cost-figures' }, [
  662. h('div', { class: 'cost-fig' }, [
  663. h('span', { class: 'val' }, [`${cost.hours_per_month} h`]),
  664. h('span', { class: 'lbl' }, ['par mois (estimé)']),
  665. ]),
  666. h('div', { class: 'cost-fig' }, [
  667. h('span', { class: 'val' }, [`~${cost.eur_per_month} €`]),
  668. h('span', { class: 'lbl' }, ['par mois (indicatif)']),
  669. ]),
  670. ]),
  671. h('p', { class: 'hint' }, ['Estimation indicative, à valider par mesure réelle.']),
  672. ]) : null,
  673. /* Gate (formulaire déblocage) ou contenu débloqué — gate visible pendant animation de sortie */
  674. !unlocked || state.unlockExiting ? renderUnlockGate() : null,
  675. /* V2 : mini plan (débloqué) */
  676. v2 ? renderMiniPlan() : null,
  677. /* Non-V2 : quick wins (débloqués) */
  678. !v2 && unlocked && !state.unlockExiting ? h('div', { class: 'card' }, [
  679. h('div', { class: 'h2' }, ['5 quick wins prioritaires']),
  680. winItems.length
  681. ? h('ol', { class: 'list' }, winItems)
  682. : h('p', { class: 'muted small' }, ['—']),
  683. h('p', { class: 'hint', style: 'margin-top:8px' }, ['Le PDF contient les 5 actions avec détail effort/impact.']),
  684. ]) : null,
  685. /* CTA débloqué */
  686. unlocked && !state.unlockExiting ? renderUnlockedCtas() : null,
  687. renderPdfDialog(),
  688. ]);
  689. }
  690. /* ── PDF DIALOG ── */
  691. function renderPdfDialog() {
  692. const onSubmit = async (e) => {
  693. e.preventDefault();
  694. const email = e.target.email.value.trim();
  695. if (!email) return;
  696. try {
  697. const headers = { 'Content-Type': 'application/json' };
  698. const csrf = appEl?.dataset?.csrfToken;
  699. if (csrf) headers['X-CSRF-Token'] = csrf;
  700. const res = await fetch(`${API_BASE}/pdf.php`, {
  701. method: 'POST',
  702. headers,
  703. credentials: 'same-origin',
  704. body: JSON.stringify({
  705. pack_id: state.packId, answers: state.answers,
  706. optional: state.optional, booking_url: BOOKING_URL, email,
  707. }),
  708. });
  709. if (!res.ok) { const j = await res.json().catch(() => ({})); throw new Error(j?.error || 'Erreur PDF'); }
  710. const blob = await res.blob();
  711. const url = URL.createObjectURL(blob);
  712. const a = document.createElement('a');
  713. a.href = url; a.download = `controle-technique-${state.packId}.pdf`;
  714. document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);
  715. document.getElementById('pdfDialog')?.close();
  716. } catch (err) { alert(err.message || 'Erreur'); }
  717. };
  718. return h('dialog', { id: 'pdfDialog', class: 'dialog' }, [
  719. h('form', { class: 'dialog__inner', onSubmit }, [
  720. h('div', { class: 'dialog__head' }, [
  721. h('strong', {}, ['Télécharger votre synthèse PDF']),
  722. h('button', { class: 'btn btn--outline', style: 'padding:6px 12px;font-size:13px', type: 'button',
  723. onClick: () => document.getElementById('pdfDialog')?.close() }, ['Fermer']),
  724. ]),
  725. h('div', { class: 'dialog__body' }, [
  726. h('div', { class: 'field' }, [
  727. h('label', { for: 'pdfEmail' }, ['Email professionnel']),
  728. h('input', {
  729. id: 'pdfEmail', name: 'email', type: 'email', required: 'required',
  730. placeholder: 'vous@entreprise.com',
  731. value: state.captureEmail || '',
  732. }),
  733. ]),
  734. h('label', { class: 'check' }, [
  735. h('input', { type: 'checkbox', required: 'required' }),
  736. h('span', {}, ['J\'accepte de recevoir mon PDF et un email de suivi éventuel.']),
  737. ]),
  738. h('div', { class: 'btnrow', style: 'margin-top:14px' }, [
  739. h('button', { class: 'btn btn--primary', type: 'submit' }, ['Télécharger mon PDF →']),
  740. ]),
  741. h('p', { class: 'hint' }, ['Désinscription en 1 clic. Suppression des données sur demande.']),
  742. ]),
  743. ]),
  744. ]);
  745. }
  746. /* ════════════════════════════════════════════════════
  747. ROI CALCULATOR — données & calcul
  748. ════════════════════════════════════════════════════ */
  749. const ROI_DEFAULTS = { coutHoraire: 60, tauxErreurs: 10, tempsErreur: 15 };
  750. function computeRoi(inp) {
  751. const v = Math.max(0, parseFloat(inp.volume) || 0);
  752. const tA = Math.max(0, parseFloat(inp.tempsActuel) || 0);
  753. const tC = Math.max(0, parseFloat(inp.tempsCible) || 0);
  754. const ch = inp.coutHoraire !== '' ? (parseFloat(inp.coutHoraire) || 0) : ROI_DEFAULTS.coutHoraire;
  755. const te = inp.tauxErreurs !== '' ? (parseFloat(inp.tauxErreurs) || 0) : ROI_DEFAULTS.tauxErreurs;
  756. const tpe = inp.tempsErreur !== '' ? (parseFloat(inp.tempsErreur) || 0) : ROI_DEFAULTS.tempsErreur;
  757. const usedDefaults = [inp.coutHoraire, inp.tauxErreurs, inp.tempsErreur].filter(x => x === '').length;
  758. const confidence = usedDefaults === 0 ? 'Fort' : usedDefaults <= 1 ? 'Moyen' : 'Faible';
  759. const gainTempsMin = v * Math.max(0, tA - tC);
  760. const gainTempsH = gainTempsMin / 60;
  761. const gainTraitement = gainTempsH * ch;
  762. const nbErreurs = v * (te / 100);
  763. const gainErreursMin = nbErreurs * tpe;
  764. const gainErreursH = gainErreursMin / 60;
  765. const gainErreurs = gainErreursH * ch;
  766. const roiMensuel = gainTraitement + gainErreurs;
  767. const roiAnnuel = roiMensuel * 12;
  768. const levers = [
  769. { label: 'Gain de traitement', euros: gainTraitement, heures: gainTempsH, detail: `${v} cas × ${Math.max(0, tA - tC)} min gagnées` },
  770. { label: 'Réduction des erreurs', euros: gainErreurs, heures: gainErreursH, detail: `~${Math.round(nbErreurs * 10) / 10} erreurs évitées × ${tpe} min` },
  771. ].sort((a, b) => b.euros - a.euros);
  772. const conclusion =
  773. roiAnnuel >= 50000 ? 'À ce niveau, l\'investissement se rentabilise en quelques semaines — difficile de ne pas le faire.' :
  774. roiAnnuel >= 20000 ? 'À ce niveau, ça se rentabilise en moins de 3 mois sur la plupart des projets.' :
  775. roiAnnuel >= 5000 ? 'Des gains concrets et mesurables — suffisant pour déclencher une discussion interne.' :
  776. 'Des gains modestes en valeur absolue, mais chaque heure récupérée libère du temps à forte valeur.';
  777. return { gainTempsH, gainTraitement, gainErreursH, gainErreurs, roiMensuel, roiAnnuel, levers, conclusion, confidence, usedDefaults };
  778. }
  779. function renderRoi() {
  780. const inp = state.roiInputs;
  781. const roiField = (key, label, unit, required, placeholder, defHint) =>
  782. h('div', { class: 'roi-field' }, [
  783. h('label', { for: `roi_${key}` }, [
  784. label,
  785. h('span', { class: 'roi-unit' }, [` (${unit})`]),
  786. ]),
  787. h('input', {
  788. id: `roi_${key}`, type: 'number', min: '0', step: 'any',
  789. required: required ? 'required' : null,
  790. placeholder: placeholder != null ? String(placeholder) : undefined,
  791. value: inp[key] !== undefined ? String(inp[key]) : '',
  792. onInput: (e) => { state.roiInputs[key] = e.target.value; },
  793. }),
  794. defHint ? h('div', { class: 'field-hint' }, [defHint]) : null,
  795. ]);
  796. return h('div', { class: 'grid' }, [
  797. h('form', { class: 'card', onSubmit: (e) => { e.preventDefault(); state.roiResult = computeRoi(state.roiInputs); setView('roi-results'); } }, [
  798. h('div', { style: 'margin-bottom:14px' }, [h('span', { class: 'tag tag--roi' }, ['ROI Calculator'])]),
  799. h('h1', { class: 'h1' }, ['Calculez le gain potentiel de votre optimisation']),
  800. h('p', { class: 'lead' }, [
  801. 'Renseignez vos données — les valeurs par défaut permettent d\'avancer sans avoir tous les chiffres.',
  802. ]),
  803. h('div', { class: 'section-label', style: 'margin-top:18px' }, ['Données de base']),
  804. h('p', { class: 'hint', style: 'margin:0 0 10px' }, ['Ces 3 champs sont nécessaires au calcul.']),
  805. h('div', { class: 'roi-grid' }, [
  806. roiField('volume', 'Volume mensuel', 'cas/mois', true, 80),
  807. roiField('tempsActuel', 'Temps actuel par cas', 'min', true, 45),
  808. roiField('tempsCible', 'Temps cible après opt.', 'min', true, 20),
  809. ]),
  810. h('div', { class: 'section-label', style: 'margin-top:20px' }, ['Paramètres de coût']),
  811. h('p', { class: 'hint', style: 'margin:0 0 10px' }, ['Pré-remplis avec des valeurs types — modifiez si vous les connaissez.']),
  812. h('div', { class: 'roi-grid' }, [
  813. roiField('coutHoraire', 'Coût horaire chargé', '€/h', false, null, 'Par défaut : 60 €/h'),
  814. roiField('tauxErreurs', 'Taux erreurs / retours', '%', false, null, 'Par défaut : 10 %'),
  815. roiField('tempsErreur', 'Temps perdu par erreur', 'min', false, null, 'Par défaut : 15 min'),
  816. ]),
  817. h('div', { class: 'btnrow', style: 'margin-top:24px' }, [
  818. h('button', { class: 'btn btn--outline', type: 'button', onClick: () => setView('select') }, ['← Retour']),
  819. h('button', { class: 'btn btn--primary', type: 'submit' }, ['Calculer mon ROI →']),
  820. ]),
  821. ]),
  822. ]);
  823. }
  824. function renderRoiResults() {
  825. const r = state.roiResult;
  826. if (!r) { setView('roi'); return h('div', {}); }
  827. const fmt = (n) => Math.round(n).toLocaleString('fr-FR');
  828. const fmtH = (n) => n < 1 ? `${Math.round(n * 60)} min` : `${(Math.round(n * 10) / 10).toLocaleString('fr-FR')} h`;
  829. const confClass = { Fort: 'confidence-pill--fort', Moyen: 'confidence-pill--moyen', Faible: 'confidence-pill--faible' }[r.confidence] || '';
  830. const confLabel = {
  831. Fort: '● Confiance forte — vos propres chiffres',
  832. Moyen: '◐ Confiance moyenne — mix données + défauts',
  833. Faible: '○ Confiance faible — majorité de valeurs par défaut',
  834. }[r.confidence] || '';
  835. return h('div', { class: 'grid' }, [
  836. h('div', { class: 'card' }, [
  837. h('div', { style: 'display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;margin-bottom:12px' }, [
  838. h('span', { class: 'tag tag--roi' }, ['ROI Calculator — Résultats']),
  839. h('span', { class: `confidence-pill ${confClass}` }, [confLabel]),
  840. ]),
  841. h('div', { class: 'roi-hero' }, [
  842. h('div', { class: 'roi-hero__item' }, [
  843. h('div', { class: 'roi-hero__val' }, [`${fmt(r.roiMensuel)} €`]),
  844. h('div', { class: 'roi-hero__lbl' }, ['ROI mensuel estimé']),
  845. h('div', { class: 'roi-hero__sub' }, [`≈ ${fmt(r.roiAnnuel)} €/an`]),
  846. ]),
  847. h('div', { class: 'roi-hero__sep' }),
  848. h('div', { class: 'roi-hero__item' }, [
  849. h('div', { class: 'roi-hero__val' }, [fmtH(r.gainTempsH + r.gainErreursH)]),
  850. h('div', { class: 'roi-hero__lbl' }, ['Heures récupérées / mois']),
  851. ]),
  852. ]),
  853. ]),
  854. h('div', { class: 'card' }, [
  855. h('div', { class: 'h2' }, ['Les 2 leviers qui pèsent le plus']),
  856. h('div', { class: 'lever-cards' }, r.levers.map((l, i) =>
  857. h('div', { class: `lever-card${i === 0 ? ' lever-card--top' : ''}` }, [
  858. h('div', { class: 'lever-card__lbl' }, [i === 0 ? '🏆 Levier principal' : 'Levier secondaire']),
  859. h('div', { style: 'font-weight:700;font-size:15px;color:var(--navy);margin:4px 0 2px' }, [l.label]),
  860. h('div', { class: 'lever-card__amt' }, [`${fmt(l.euros)} €/mois`]),
  861. h('div', { class: 'lever-card__det' }, [`${fmtH(l.heures)} récupérées · ${l.detail}`]),
  862. ])
  863. )),
  864. ]),
  865. h('div', { class: 'conclusion-box' }, [
  866. h('p', {}, [r.conclusion]),
  867. r.usedDefaults > 0
  868. ? h('p', { class: 'hint' }, [
  869. `${r.usedDefaults} valeur${r.usedDefaults > 1 ? 's' : ''} par défaut utilisée${r.usedDefaults > 1 ? 's' : ''} — affinez avec vos chiffres réels pour plus de précision.`,
  870. ])
  871. : null,
  872. ]),
  873. h('div', { class: 'card' }, [
  874. h('div', { class: 'h2' }, ['Et maintenant ?']),
  875. h('p', { class: 'lead', style: 'margin-bottom:16px' }, [
  876. 'Utilisez ces chiffres pour déclencher une décision. La prochaine étape : identifier les 3 actions concrètes à mettre en œuvre.',
  877. ]),
  878. h('div', { class: 'btnrow' }, [
  879. h('button', { class: 'btn btn--primary', onClick: () => setView('qwf') }, ['Trouver mes 3 quick wins →']),
  880. BOOKING_URL ? h('a', { class: 'btn btn--outline', href: BOOKING_URL, target: '_blank', rel: 'noreferrer' }, ['Entretien 30 min offert avec un consultant']) : null,
  881. ]),
  882. h('div', { class: 'btnrow', style: 'margin-top:6px' }, [
  883. h('button', { class: 'btn btn--outline', style: 'font-size:13px', onClick: () => setView('roi') }, ['← Modifier mes données']),
  884. h('button', { class: 'btn btn--outline', style: 'font-size:13px', onClick: () => setView('select') }, ['Autres outils']),
  885. ]),
  886. ]),
  887. ]);
  888. }
  889. /* ════════════════════════════════════════════════════
  890. QUICK WINS FINDER — données & calcul
  891. ════════════════════════════════════════════════════ */
  892. const QW_LIBRARY = [
  893. {
  894. id: 'statuts-notifications',
  895. title: 'Statuts uniques + notifications ciblées',
  896. result: 'Fin des relances et visibilité instantanée sur l\'avancement',
  897. setup: 'Statut central (ex : "à valider", "en cours IT", "bloqué", "terminé") + notifications automatiques aux bons rôles',
  898. prereqs: 'Définir un owner, les statuts métier, accès boîtes mail ou Teams',
  899. effort: 'S à M', delay: '2 à 4 semaines',
  900. impact: ['Baisse du délai global', 'Moins d\'interruptions', 'Moins de relances'],
  901. triggers: { relancesFrequentes: 3, validationsMultiples: 1 },
  902. },
  903. {
  904. id: 'formulaire-intelligent',
  905. title: 'Formulaire intelligent de collecte',
  906. result: 'Moins de retours arrière, dossiers complets dès le départ',
  907. setup: 'Champs conditionnels + contrôles à la saisie + pièces demandées au bon moment + validation de cohérence',
  908. prereqs: 'Liste des champs obligatoires, règles simples, rôles définis',
  909. effort: 'M', delay: '3 à 6 semaines',
  910. impact: ['Baisse des erreurs', 'Baisse du temps de traitement', 'Moins de rejets'],
  911. triggers: { erreursFréquentes: 3, validationsMultiples: 2 },
  912. },
  913. {
  914. id: 'suppression-double-saisie',
  915. title: 'Suppression de la double saisie entre outils',
  916. result: 'Arrêt du copier-coller Excel/email vers outil final',
  917. setup: 'Synchronisation des champs clés (push) ou import structuré automatique entre les outils',
  918. prereqs: 'Accès API ou export/import structuré, mapping des champs clés',
  919. effort: 'M', delay: '4 à 8 semaines',
  920. impact: ['Gain de temps direct', 'Moins d\'erreurs de saisie', 'Données fiables partout'],
  921. triggers: { doubleSaisie: 3, nbOutilsEleve: 2 },
  922. },
  923. {
  924. id: 'dossier-unique',
  925. title: 'Dossier unique par dossier',
  926. result: 'Fin du chaos documentaire — tout au même endroit',
  927. setup: 'Convention de nommage + dépôt structuré des pièces + lien unique accessible depuis le process',
  928. prereqs: 'Choix d\'un espace de stockage partagé, définition des règles de nommage',
  929. effort: 'S', delay: '1 à 3 semaines',
  930. impact: ['Moins de temps perdu à chercher', 'Moins d\'erreurs', 'Meilleure traçabilité'],
  931. triggers: { docsEparpilles: 3, erreursFréquentes: 1 },
  932. },
  933. {
  934. id: 'workflow-validation',
  935. title: 'Workflow de validation simplifié',
  936. result: 'Validation en un clic, délais réduits, zéro perte en route',
  937. setup: 'Règles de validation claires + SLA définis + tableau de bord de suivi des en-cours',
  938. prereqs: 'Matrice de validation, SLA définis, accès configuré pour les validateurs',
  939. effort: 'M', delay: '3 à 5 semaines',
  940. impact: ['Baisse du délai global', 'Moins de blocages', 'Meilleure traçabilité'],
  941. triggers: { validationsMultiples: 3, relancesFrequentes: 1 },
  942. },
  943. {
  944. id: 'exports-automatiques',
  945. title: 'Exports propres automatiques',
  946. result: 'Fin du reporting manuel — données toujours à jour',
  947. setup: 'Export planifié + format standard + envoi automatique aux destinataires',
  948. prereqs: 'Accès aux sources de données, liste des destinataires, fréquence définie',
  949. effort: 'S à M', delay: '2 à 5 semaines',
  950. impact: ['Temps récupéré sur le reporting', 'Fiabilité des données', 'Partage facilité'],
  951. triggers: { reportingManuel: 3, nbOutilsEleve: 1 },
  952. },
  953. ];
  954. const QWF_QUESTIONS = [
  955. { id: 'doubleSaisie', label: 'Des données sont saisies manuellement dans plusieurs outils différents (copier-coller, ressaisie…)' },
  956. { id: 'validationsMultiples', label: 'Plusieurs personnes ou étapes distinctes doivent valider chaque dossier' },
  957. { id: 'relancesFrequentes', label: 'Des relances sont nécessaires pour savoir où en est un dossier' },
  958. { id: 'docsEparpilles', label: 'Les documents d\'un dossier sont éparpillés (email, drive, bureau local…)' },
  959. { id: 'reportingManuel', label: 'Du reporting est préparé manuellement (copier-coller, recomposition de données)' },
  960. { id: 'erreursFréquentes', label: 'Des dossiers reviennent en arrière à cause d\'informations manquantes ou incorrectes' },
  961. { id: 'nbOutilsEleve', label: 'Ce process fait intervenir 3 outils ou plus (ERP, email, tableur, outil métier…)' },
  962. ];
  963. function computeQuickWins(signals) {
  964. return QW_LIBRARY
  965. .map(qw => {
  966. let score = 0;
  967. for (const [trigger, weight] of Object.entries(qw.triggers)) {
  968. if (signals[trigger]) score += weight;
  969. }
  970. return { ...qw, score };
  971. })
  972. .sort((a, b) => b.score - a.score)
  973. .slice(0, 3);
  974. }
  975. function renderQwf() {
  976. const sig = state.qwfSignals;
  977. const makeSignalRow = (q) => {
  978. const isOui = sig[q.id] === true;
  979. const isNon = sig[q.id] === false;
  980. return h('div', { class: 'signal-row' }, [
  981. h('span', { class: 'signal-row__lbl' }, [q.label]),
  982. h('div', { class: 'signal-row__btns' }, [
  983. h('button', {
  984. type: 'button',
  985. class: `signal-btn signal-btn--oui${isOui ? ' active' : ''}`,
  986. onClick: () => { state.qwfSignals[q.id] = isOui ? undefined : true; render(); },
  987. }, ['Oui']),
  988. h('button', {
  989. type: 'button',
  990. class: `signal-btn signal-btn--non${isNon ? ' active' : ''}`,
  991. onClick: () => { state.qwfSignals[q.id] = isNon ? undefined : false; render(); },
  992. }, ['Non']),
  993. ]),
  994. ]);
  995. };
  996. const answeredCount = QWF_QUESTIONS.filter(q => sig[q.id] !== undefined).length;
  997. const canSubmit = answeredCount >= 3;
  998. return h('div', { class: 'grid' }, [
  999. h('div', { class: 'card' }, [
  1000. h('div', { style: 'margin-bottom:14px' }, [h('span', { class: 'tag tag--qwf' }, ['Quick Wins Finder'])]),
  1001. h('h1', { class: 'h1' }, ['Identifiez vos 3 actions prioritaires']),
  1002. h('p', { class: 'lead' }, [
  1003. 'Répondez à ces 7 signaux pour recevoir 3 recommandations concrètes adaptées à votre process.',
  1004. ]),
  1005. h('div', { class: 'signal-list' }, QWF_QUESTIONS.map(makeSignalRow)),
  1006. h('div', { class: 'btnrow', style: 'margin-top:22px' }, [
  1007. h('button', { class: 'btn btn--outline', onClick: () => setView('select') }, ['← Retour']),
  1008. h('button', {
  1009. class: 'btn btn--primary',
  1010. disabled: canSubmit ? null : 'disabled',
  1011. onClick: () => { if (canSubmit) { state.qwfResult = computeQuickWins(state.qwfSignals); setView('qwf-results'); } },
  1012. }, [canSubmit ? 'Voir mes 3 quick wins →' : `Répondre à encore ${3 - answeredCount} signal${3 - answeredCount > 1 ? 's' : ''}`]),
  1013. ]),
  1014. h('p', { class: 'hint', style: 'margin-top:8px' }, ['Répondez à au moins 3 signaux pour déverrouiller le résultat.']),
  1015. ]),
  1016. ]);
  1017. }
  1018. function renderQwfResults() {
  1019. const qws = state.qwfResult;
  1020. if (!qws || qws.length === 0) { setView('qwf'); return h('div', {}); }
  1021. const makeQwCard = (qw, idx) =>
  1022. h('div', { class: 'qw-card' }, [
  1023. h('div', { class: 'qw-card__head' }, [
  1024. h('div', { class: 'qw-card__num' }, [String(idx + 1)]),
  1025. h('div', { class: 'qw-card__head-title' }, [qw.title]),
  1026. ]),
  1027. h('div', { class: 'qw-card__body' }, [
  1028. h('div', { class: 'qw-card__result' }, [qw.result]),
  1029. h('div', { class: 'qw-section' }, [
  1030. h('div', { class: 'qw-section__lbl' }, ['Ce qu\'on met en place']),
  1031. h('div', { class: 'qw-section__val' }, [qw.setup]),
  1032. ]),
  1033. h('div', { class: 'qw-section' }, [
  1034. h('div', { class: 'qw-section__lbl' }, ['Pré-requis']),
  1035. h('div', { class: 'qw-section__val' }, [qw.prereqs]),
  1036. ]),
  1037. h('div', { class: 'qw-meta' }, [
  1038. h('span', { class: 'badge-effort' }, [`Effort : ${qw.effort}`]),
  1039. h('span', { class: 'badge-delay' }, [`Délai : ${qw.delay}`]),
  1040. ]),
  1041. h('div', { class: 'impact-chips' }, qw.impact.map(i =>
  1042. h('span', { class: 'impact-chip' }, [i])
  1043. )),
  1044. ]),
  1045. ]);
  1046. return h('div', { class: 'grid' }, [
  1047. h('div', { class: 'card' }, [
  1048. h('div', { style: 'margin-bottom:12px' }, [h('span', { class: 'tag tag--qwf' }, ['Quick Wins Finder — Résultats'])]),
  1049. h('h1', { class: 'h1' }, ['Vos 3 actions prioritaires']),
  1050. h('p', { class: 'lead' }, [
  1051. 'Commencez par la première — elle a le plus fort impact selon vos signaux. Chaque fiche contient tout ce qu\'il faut pour démarrer.',
  1052. ]),
  1053. ]),
  1054. h('div', { class: 'qw-cards' }, qws.map(makeQwCard)),
  1055. h('div', { class: 'card' }, [
  1056. h('div', { class: 'h2' }, ['Et maintenant ?']),
  1057. h('p', { class: 'lead', style: 'margin-bottom:16px' }, [
  1058. 'Ces 3 quick wins sont un point de départ solide. Un entretien offert avec un consultant permet de découvrir les opportunités et de cadrer le quick win n°1 en plan d\'action.',
  1059. ]),
  1060. h('div', { class: 'btnrow' }, [
  1061. BOOKING_URL ? h('a', {
  1062. class: 'btn btn--primary', href: BOOKING_URL, target: '_blank', rel: 'noreferrer',
  1063. }, ['Découvrir les opportunités — Entretien 30 min offert']) : null,
  1064. h('button', { class: 'btn btn--outline', onClick: () => setView('roi') }, ['Calculer le ROI →']),
  1065. ]),
  1066. h('div', { class: 'btnrow', style: 'margin-top:6px' }, [
  1067. h('button', { class: 'btn btn--outline', style: 'font-size:13px', onClick: () => setView('qwf') }, ['← Modifier mes signaux']),
  1068. h('button', { class: 'btn btn--outline', style: 'font-size:13px', onClick: () => setView('select') }, ['Autres outils']),
  1069. ]),
  1070. ]),
  1071. ]);
  1072. }
  1073. /* ── RENDER ── */
  1074. function render() {
  1075. if (!appEl) return;
  1076. appEl.innerHTML = '';
  1077. const views = {
  1078. landing: renderLanding,
  1079. select: renderSelect,
  1080. intro: renderIntro,
  1081. quiz: renderQuiz,
  1082. optional: renderOptional,
  1083. results: renderResults,
  1084. 'roi': renderRoi,
  1085. 'roi-results': renderRoiResults,
  1086. 'qwf': renderQwf,
  1087. 'qwf-results': renderQwfResults,
  1088. };
  1089. appEl.appendChild((views[state.view] || renderLanding)());
  1090. }
  1091. /* ── HEADER update ── */
  1092. function initHeader() {
  1093. const header = document.querySelector('.header');
  1094. if (!header) return;
  1095. header.innerHTML = '';
  1096. const brand = document.createElement('div');
  1097. brand.innerHTML =
  1098. '<div class="brand__logo">Contrôle technique process</div>' +
  1099. '<div class="brand__sub">Diagnostic self-serve · Livinweb</div>';
  1100. const badge = document.createElement('span');
  1101. badge.className = 'brand__badge';
  1102. badge.textContent = 'V1';
  1103. header.appendChild(brand);
  1104. header.appendChild(badge);
  1105. }
  1106. initHeader();
  1107. render();