app.js 51 KB

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