/* * Sportello per il Cittadino — assistente pratiche multilingua (versione test). * Si aggancia al bottone WhatsApp: al clic apre la chat guidata; da qui l'utente * può passare a WhatsApp con un messaggio già compilato. * * Uso: * tag script con src="chatbot.js" defer * data-whatsapp="39XXXXXXXXXX" * data-trigger="#whatsapp-button" (opzionale: bottone esistente da intercettare) * data-base="./data/"> * Senza data-trigger il widget crea un proprio bottone flottante. */ (() => { 'use strict'; const IN_BROWSER = typeof document !== 'undefined'; const script = IN_BROWSER ? document.currentScript : null; const CFG = { whatsapp: script?.dataset.whatsapp || '', trigger: script?.dataset.trigger || '', base: script?.dataset.base || './data/', lang: script?.dataset.lang || '', // Mappa opzionale nome-file -> URL (es. file caricati su WordPress come .txt): window.SPC_CHATBOT_FILES files: (IN_BROWSER && window.SPC_CHATBOT_FILES) || null, }; const url = (nome) => (CFG.files && CFG.files[nome]) || CFG.base + nome; const CATEGORIE = [ 'Assegni Familiari', 'Agevolazioni e Bonus', 'Bonus Vari e Sostegno al Reddito', 'Disoccupazione', 'Handicap e Danni da Lavoro', 'Immigrazione', 'Invalidità Civile', 'Invalidità Pensionabile', 'Maternità e Congedi', 'Pensioni e Estratto Contributivo', 'Fisco e Casa', 'Lavoro Domestico', 'Servizi Digitali', ]; const LINGUE = [ ['it', 'Italiano'], ['en', 'English'], ['fr', 'Français'], ['es', 'Español'], ['ar', 'العربية'], ['ro', 'Română'], ['sq', 'Shqip'], ['uk', 'Українська'], ['zh', '中文'], ['bn', 'বাংলা'], ]; const RTL = new Set(['ar']); /* Testi dell'interfaccia. I contenuti delle pratiche stanno in data/i18n/.json */ const UI = { it: { title: 'Roberta', subtitle: 'Assistente pratiche · Sportello per il Cittadino', hello: 'Ciao, sono Roberta! Ti aiuto a capire quali documenti servono per la tua pratica. In che lingua preferisci parlare?', askTopic: 'Di cosa hai bisogno? Scegli un argomento oppure scrivi il nome della pratica.', askPractice: 'Quale pratica ti interessa?', search: 'Cerca una pratica (es. ISEE, NASpI, 730)…', send: 'Cerca', what: "Cos'è", who: 'A chi spetta', docs: 'Documenti da portare', how: 'Come si presenta', deadlines: 'Scadenze', notes: 'Da sapere', wa: 'Continua su WhatsApp con un operatore', other: 'Un’altra pratica', topics: 'Torna agli argomenti', copy: 'Copia elenco documenti', copied: 'Elenco copiato', none: 'Non ho trovato pratiche con queste parole. Prova con un altro termine o scegli un argomento.', found: 'Ho trovato queste pratiche:', privacy: 'Assistente automatico: informazioni generali, non sostituiscono la consulenza di un operatore. Non inserire dati personali.', waMsg: (p) => p ? `Salve, vorrei assistenza per la pratica: ${p}.` : 'Salve, vorrei assistenza per una pratica.', close: 'Chiudi', lang: 'Lingua', itNote: null, open: 'Apri Roberta, assistente pratiche', }, en: { title: 'Roberta', subtitle: 'Paperwork assistant · Sportello per il Cittadino', hello: 'Hi, I’m Roberta! I can help you find out which documents you need. Which language do you prefer?', askTopic: 'What do you need? Pick a topic or type the name of the procedure.', askPractice: 'Which procedure are you interested in?', search: 'Search a procedure (e.g. ISEE, NASpI, 730)…', send: 'Search', what: 'What it is', who: 'Who can apply', docs: 'Documents to bring', how: 'How to apply', deadlines: 'Deadlines', notes: 'Good to know', wa: 'Continue on WhatsApp with an operator', other: 'Another procedure', topics: 'Back to topics', copy: 'Copy document list', copied: 'List copied', none: 'I could not find a procedure with those words. Try another term or pick a topic.', found: 'I found these procedures:', privacy: 'Automated assistant: general information only, not a substitute for an operator. Do not enter personal data.', waMsg: (p) => p ? `Hello, I need help with: ${p}.` : 'Hello, I need help with a procedure.', close: 'Close', lang: 'Language', itNote: 'Some details are only available in Italian.', open: 'Open paperwork assistant', }, fr: { title: 'Roberta', subtitle: 'Assistant démarches · Sportello per il Cittadino', hello: 'Bonjour, je suis Roberta ! Je vous aide à savoir quels documents apporter. Quelle langue préférez-vous ?', askTopic: 'De quoi avez-vous besoin ? Choisissez un thème ou écrivez le nom de la démarche.', askPractice: 'Quelle démarche vous intéresse ?', search: 'Chercher une démarche (ex. ISEE, NASpI, 730)…', send: 'Chercher', what: 'De quoi s’agit-il', who: 'Qui peut en bénéficier', docs: 'Documents à apporter', how: 'Comment faire la demande', deadlines: 'Délais', notes: 'À savoir', wa: 'Continuer sur WhatsApp avec un conseiller', other: 'Une autre démarche', topics: 'Retour aux thèmes', copy: 'Copier la liste', copied: 'Liste copiée', none: 'Aucune démarche trouvée avec ces mots. Essayez un autre terme ou choisissez un thème.', found: 'Voici les démarches trouvées :', privacy: 'Assistant automatique : informations générales, ne remplace pas un conseiller. N’indiquez pas de données personnelles.', waMsg: (p) => p ? `Bonjour, j’ai besoin d’aide pour : ${p}.` : 'Bonjour, j’ai besoin d’aide pour une démarche.', close: 'Fermer', lang: 'Langue', itNote: 'Certains détails ne sont disponibles qu’en italien.', open: 'Ouvrir l’assistant', }, es: { title: 'Roberta', subtitle: 'Asistente de trámites · Sportello per il Cittadino', hello: '¡Hola, soy Roberta! Te ayudo a saber qué documentos necesitas. ¿En qué idioma prefieres hablar?', askTopic: '¿Qué necesitas? Elige un tema o escribe el nombre del trámite.', askPractice: '¿Qué trámite te interesa?', search: 'Buscar un trámite (ej. ISEE, NASpI, 730)…', send: 'Buscar', what: 'Qué es', who: 'Quién puede solicitarlo', docs: 'Documentos que debes llevar', how: 'Cómo se solicita', deadlines: 'Plazos', notes: 'A tener en cuenta', wa: 'Continuar en WhatsApp con un operador', other: 'Otro trámite', topics: 'Volver a los temas', copy: 'Copiar lista de documentos', copied: 'Lista copiada', none: 'No encontré trámites con esas palabras. Prueba otro término o elige un tema.', found: 'He encontrado estos trámites:', privacy: 'Asistente automático: información general, no sustituye a un operador. No introduzcas datos personales.', waMsg: (p) => p ? `Hola, necesito ayuda con: ${p}.` : 'Hola, necesito ayuda con un trámite.', close: 'Cerrar', lang: 'Idioma', itNote: 'Algunos detalles solo están disponibles en italiano.', open: 'Abrir asistente', }, ar: { title: 'Roberta', subtitle: 'مساعد المعاملات · Sportello per il Cittadino', hello: 'مرحبًا، أنا روبرتا! سأساعدك في معرفة المستندات المطلوبة لمعاملتك. ما هي اللغة التي تفضلها؟', askTopic: 'بماذا يمكنني مساعدتك؟ اختر موضوعًا أو اكتب اسم المعاملة.', askPractice: 'ما هي المعاملة التي تهمك؟', search: 'ابحث عن معاملة (مثل ISEE أو NASpI أو 730)…', send: 'بحث', what: 'ما هي', who: 'من يحق له', docs: 'المستندات المطلوبة', how: 'كيفية التقديم', deadlines: 'المواعيد النهائية', notes: 'معلومات مهمة', wa: 'تابع عبر واتساب مع موظف', other: 'معاملة أخرى', topics: 'العودة إلى المواضيع', copy: 'نسخ قائمة المستندات', copied: 'تم نسخ القائمة', none: 'لم أجد معاملات بهذه الكلمات. جرّب كلمة أخرى أو اختر موضوعًا.', found: 'وجدت هذه المعاملات:', privacy: 'مساعد آلي: معلومات عامة فقط ولا تغني عن استشارة الموظف. لا تُدخل بيانات شخصية.', waMsg: (p) => p ? `مرحبًا، أحتاج إلى مساعدة في: ${p}.` : 'مرحبًا، أحتاج إلى مساعدة في معاملة.', close: 'إغلاق', lang: 'اللغة', itNote: 'بعض التفاصيل متوفرة باللغة الإيطالية فقط.', open: 'افتح مساعد المعاملات', }, ro: { title: 'Roberta', subtitle: 'Asistent dosare · Sportello per il Cittadino', hello: 'Bună, sunt Roberta! Te ajut să afli ce documente îți trebuie. În ce limbă preferi să vorbim?', askTopic: 'De ce ai nevoie? Alege un subiect sau scrie numele dosarului.', askPractice: 'Ce dosar te interesează?', search: 'Caută un dosar (ex. ISEE, NASpI, 730)…', send: 'Caută', what: 'Ce este', who: 'Cine are dreptul', docs: 'Documente necesare', how: 'Cum se depune', deadlines: 'Termene', notes: 'De reținut', wa: 'Continuă pe WhatsApp cu un operator', other: 'Alt dosar', topics: 'Înapoi la subiecte', copy: 'Copiază lista de documente', copied: 'Listă copiată', none: 'Nu am găsit dosare cu aceste cuvinte. Încearcă alt termen sau alege un subiect.', found: 'Am găsit aceste dosare:', privacy: 'Asistent automat: informații generale, nu înlocuiește un operator. Nu introduce date personale.', waMsg: (p) => p ? `Bună ziua, am nevoie de ajutor pentru: ${p}.` : 'Bună ziua, am nevoie de ajutor pentru un dosar.', close: 'Închide', lang: 'Limba', itNote: 'Unele detalii sunt disponibile doar în italiană.', open: 'Deschide asistentul', }, sq: { title: 'Roberta', subtitle: 'Asistenti i praktikave · Sportello per il Cittadino', hello: 'Përshëndetje, jam Roberta! Të ndihmoj të kuptosh cilat dokumente duhen. Në cilën gjuhë preferon të flasim?', askTopic: 'Për çfarë ke nevojë? Zgjidh një temë ose shkruaj emrin e praktikës.', askPractice: 'Cila praktikë të intereson?', search: 'Kërko një praktikë (p.sh. ISEE, NASpI, 730)…', send: 'Kërko', what: 'Çfarë është', who: 'Kush ka të drejtë', docs: 'Dokumentet që duhen sjellë', how: 'Si paraqitet', deadlines: 'Afatet', notes: 'Për t’u ditur', wa: 'Vazhdo në WhatsApp me një operator', other: 'Një praktikë tjetër', topics: 'Kthehu te temat', copy: 'Kopjo listën e dokumenteve', copied: 'Lista u kopjua', none: 'Nuk gjeta praktika me këto fjalë. Provo një term tjetër ose zgjidh një temë.', found: 'Gjeta këto praktika:', privacy: 'Asistent automatik: informacion i përgjithshëm, nuk zëvendëson operatorin. Mos fut të dhëna personale.', waMsg: (p) => p ? `Përshëndetje, kam nevojë për ndihmë për: ${p}.` : 'Përshëndetje, kam nevojë për ndihmë për një praktikë.', close: 'Mbyll', lang: 'Gjuha', itNote: 'Disa detaje janë vetëm në italisht.', open: 'Hap asistentin', }, uk: { title: 'Roberta', subtitle: 'Помічник із документів · Sportello per il Cittadino', hello: 'Вітаю, я Роберта! Я допоможу дізнатися, які документи потрібні. Якою мовою вам зручніше?', askTopic: 'Що вам потрібно? Оберіть тему або напишіть назву процедури.', askPractice: 'Яка процедура вас цікавить?', search: 'Пошук процедури (напр. ISEE, NASpI, 730)…', send: 'Шукати', what: 'Що це', who: 'Хто має право', docs: 'Які документи принести', how: 'Як подати', deadlines: 'Терміни', notes: 'Варто знати', wa: 'Продовжити у WhatsApp з оператором', other: 'Інша процедура', topics: 'Назад до тем', copy: 'Скопіювати список документів', copied: 'Список скопійовано', none: 'Не знайшов процедур за цими словами. Спробуйте інше слово або оберіть тему.', found: 'Ось знайдені процедури:', privacy: 'Автоматичний помічник: загальна інформація, не замінює консультацію оператора. Не вводьте особисті дані.', waMsg: (p) => p ? `Добрий день, мені потрібна допомога з: ${p}.` : 'Добрий день, мені потрібна допомога з процедурою.', close: 'Закрити', lang: 'Мова', itNote: 'Деякі деталі доступні лише італійською.', open: 'Відкрити помічника', }, zh: { title: 'Roberta', subtitle: '办事助手 · Sportello per il Cittadino', hello: '您好,我是 Roberta!我可以帮您了解办理手续需要哪些文件。您想用哪种语言交流?', askTopic: '您需要办理什么?请选择主题或输入手续名称。', askPractice: '您想了解哪项手续?', search: '搜索手续(例如 ISEE、NASpI、730)…', send: '搜索', what: '简介', who: '适用对象', docs: '需要携带的文件', how: '办理方式', deadlines: '截止日期', notes: '注意事项', wa: '通过 WhatsApp 联系工作人员', other: '其他手续', topics: '返回主题', copy: '复制文件清单', copied: '清单已复制', none: '没有找到相关手续。请换个词或选择一个主题。', found: '找到以下手续:', privacy: '自动助手:仅提供一般信息,不能替代工作人员的咨询。请勿输入个人信息。', waMsg: (p) => p ? `您好,我需要办理:${p}。` : '您好,我需要办理一项手续。', close: '关闭', lang: '语言', itNote: '部分内容仅提供意大利语版本。', open: '打开办事助手', }, bn: { title: 'Roberta', subtitle: 'কাগজপত্র সহায়ক · Sportello per il Cittadino', hello: 'নমস্কার, আমি রোবের্তা! আপনার আবেদনের জন্য কোন কাগজপত্র লাগবে তা জানতে আমি সাহায্য করব। কোন ভাষায় কথা বলতে চান?', askTopic: 'আপনার কী দরকার? একটি বিষয় বেছে নিন বা আবেদনের নাম লিখুন।', askPractice: 'কোন আবেদনটি জানতে চান?', search: 'আবেদন খুঁজুন (যেমন ISEE, NASpI, 730)…', send: 'খুঁজুন', what: 'এটি কী', who: 'কে আবেদন করতে পারেন', docs: 'যে কাগজপত্র আনতে হবে', how: 'কীভাবে আবেদন করবেন', deadlines: 'সময়সীমা', notes: 'জেনে রাখুন', wa: 'WhatsApp-এ একজন কর্মীর সাথে কথা বলুন', other: 'অন্য আবেদন', topics: 'বিষয়ে ফিরে যান', copy: 'কাগজপত্রের তালিকা কপি করুন', copied: 'তালিকা কপি হয়েছে', none: 'এই শব্দে কোনো আবেদন পাওয়া যায়নি। অন্য শব্দ চেষ্টা করুন বা একটি বিষয় বেছে নিন।', found: 'এই আবেদনগুলো পাওয়া গেছে:', privacy: 'স্বয়ংক্রিয় সহায়ক: শুধু সাধারণ তথ্য, কর্মীর পরামর্শের বিকল্প নয়। ব্যক্তিগত তথ্য লিখবেন না।', waMsg: (p) => p ? `নমস্কার, আমার এই বিষয়ে সাহায্য দরকার: ${p}।` : 'নমস্কার, একটি আবেদনের জন্য সাহায্য দরকার।', close: 'বন্ধ করুন', lang: 'ভাষা', itNote: 'কিছু তথ্য শুধু ইতালীয় ভাষায় পাওয়া যায়।', open: 'সহায়ক খুলুন', }, }; /* ---------- stato ---------- */ let lang = 'it'; let pratiche = []; // dati base in italiano const traduzioni = {}; // lang -> { categorie:{}, pratiche:{id:{...}} } let ultimaPratica = null; const t = (k) => (UI[lang] && UI[lang][k] != null ? UI[lang][k] : UI.it[k]); /* ---------- dati ---------- */ // I file possono avere una riga di intestazione prima del JSON (su WordPress sono caricati come .txt) async function leggi(r) { const s = await r.text(); return JSON.parse(s.slice(s.search(/[\[{]/))); } async function caricaDati() { const r = await fetch(url('pratiche.json')); pratiche = await leggi(r); } async function caricaLingua(l) { await caricaTestiP(l); if (l === 'it' || traduzioni[l]) return; try { const r = await fetch(url(`i18n/${l}.json`)); traduzioni[l] = r.ok ? await leggi(r) : { categorie: {}, pratiche: {} }; } catch { traduzioni[l] = { categorie: {}, pratiche: {} }; } } const nomeCategoria = (c) => traduzioni[lang]?.categorie?.[c] || c; function campo(p, k) { const tr = traduzioni[lang]?.pratiche?.[p.id]; return tr && tr[k] != null ? tr[k] : p[k]; } const tradotta = (p) => lang === 'it' || !!traduzioni[lang]?.pratiche?.[p.id]?.documenti; /* ---------- percorsi a domande (data/percorsi.json + data/percorsi/.json) ---------- */ let M = null; // percorsi preparati const testiP = {}; // lang -> { chiave: testo } const tp = (k) => testiP[lang]?.[k] ?? testiP.it?.[k] ?? k; async function caricaPercorsi() { const r = await fetch(url('percorsi.json')); M = prepara(await leggi(r)); await caricaTestiP('it'); } async function caricaTestiP(l) { if (testiP[l]) return; try { const r = await fetch(url(`percorsi/${l}.json`)); testiP[l] = r.ok ? await leggi(r) : {}; } catch { testiP[l] = {}; } } /* ---------- comprensione del testo (tutto nel browser: niente server, niente AI) ---------- */ // Minuscolo, senza accenti/vocali arabe, cifre arabe -> 0-9, punteggiatura -> spazio. Spazi ai bordi per i confronti "inizio parola". function norm(s) { return ' ' + (s || '').toString().toLowerCase() .replace(/[٠-٩]/g, (d) => String(d.charCodeAt(0) - 0x660)) .replace(/[۰-۹]/g, (d) => String(d.charCodeAt(0) - 0x6f0)) .replace(/٪/g, '%') .normalize('NFD').replace(/[̀-ًͯ-ٰٟ]/g, '') .replace(/ة/g, 'ه').replace(/ى/g, 'ي') .replace(/[^\p{L}\p{M}\p{N}%]+/gu, ' ').replace(/\s+/g, ' ').trim() + ' '; } const SENZA_SPAZI = /[\p{Script=Han}\p{Script=Arabic}]/u; // parole attaccate: si cerca la sottostringa const parole = (T) => T.trim().split(' ').filter(Boolean); function lev(a, b) { if (a === b) return 0; let prev = Array.from({ length: b.length + 1 }, (_, i) => i); for (let i = 1; i <= a.length; i++) { const cur = [i]; for (let j = 1; j <= b.length; j++) cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)); prev = cur; } return prev[b.length]; } // "Scheletro" di una parola per gli errori più comuni: doppie (acompagnamento, disoccupazzione), // y/j/k/w/ph/h muta (naspy, penzione → pensione), gn/ni, ci/si e z/s. function scheletro(w) { return w.replace(/ph/g, 'f').replace(/y/g, 'i').replace(/j/g, 'i').replace(/k/g, 'c').replace(/w/g, 'v') .replace(/ch/g, 'c').replace(/h/g, '').replace(/gni/g, 'gn').replace(/z/g, 's').replace(/sci/g, 'si') .replace(/([a-z])\1+/g, '$1'); } const LATINA = /^[a-z0-9 ]+$/; // Una parola del testo w "è" la parola chiave k (inizio parola), anche con un refuso? 0 = esatta, 1 = refuso, -1 = no function parolaSimile(w, k) { if (w.startsWith(k)) return 0; if (/\d/.test(k) || !LATINA.test(k) || k.length < 4) return -1; const sw = scheletro(w), sk = scheletro(k); if (sk.length >= 4 && sw.startsWith(sk)) return 1; if (k.length < 6) return -1; const max = k.length >= 9 ? 2 : 1; if (w.length < k.length - max) return -1; for (let L = k.length - 1; L <= k.length + 1; L++) if (lev(w.slice(0, L), k) <= max) return 1; for (let L = sk.length - 1; L <= sk.length + 1; L++) if (sk.length >= 5 && lev(sw.slice(0, L), sk) <= 1) return 1; return -1; } // Dove compare k in T? Restituisce { w: indice parola | -1 per frasi/sottostringhe, f: true se trovata con un errore di battitura } o null function trova(T, k) { if (SENZA_SPAZI.test(k)) return T.includes(k) ? { w: -1 } : null; const ws = parole(T); if (k.includes(' ')) { if (T.includes(' ' + k)) return { w: -1 }; // frase con refusi: ogni parola della frase, in fila, simile alla parola del testo const ks = k.split(' '); if (!LATINA.test(k) || ks.every((x) => x.length < 4)) return null; for (let i = 0; i + ks.length <= ws.length; i++) { let ok = true, f = false; for (let j = 0; j < ks.length && ok; j++) { const r = ks[j].length < 4 ? (ws[i + j].startsWith(ks[j]) ? 0 : -1) : parolaSimile(ws[i + j], ks[j]); if (r < 0) ok = false; else if (r) f = true; } if (ok) return { w: -1, f: true }; } return null; } let best = null; for (let i = 0; i < ws.length; i++) { const r = parolaSimile(ws[i], k); if (r === 0) return { w: i }; if (r === 1 && !best) best = { w: i, f: true }; } return best; } const haParola = (T, k) => !!trova(T, k); function prepKw(list) { return (list || []).map((k) => (k[0] === '@' ? { ref: k.slice(1) } : k[0] === '=' ? { esatta: norm(k.slice(1)).trim() } : { k: norm(k).trim() })); } // Punteggio = lunghezza delle parole chiave trovate (frasi più specifiche pesano di più). // Ogni parola del testo conta una volta sola, con la parola chiave migliore; i refusi valgono metà. function corrisponde(T, kws, breve) { let s = 0; const perParola = new Map(); for (const x of kws) { if (x.ref) { if (breve) s += corrisponde(T, M.siNo[x.ref] || [], true) ? 3 : 0; } else if (x.esatta) { const ok = SENZA_SPAZI.test(x.esatta) ? breve && T.includes(x.esatta) : T.includes(' ' + x.esatta + ' '); if (ok) s += Math.max(3, x.esatta.length); } else if (x.k) { const r = trova(T, x.k); if (!r) continue; const v = SENZA_SPAZI.test(x.k) ? x.k.length * 2 + 2 : r.f ? x.k.length / 2 : x.k.length; if (r.w < 0) s += r.f ? x.k.length / 2 : v; else perParola.set(r.w, Math.max(perParola.get(r.w) || 0, v)); } } for (const v of perParola.values()) s += v; return s; } function prepara(raw) { const P = { siNo: {}, codici: [], speciali: {}, intenti: [], nodi: {} }; for (const [k, v] of Object.entries(raw.sinonimi_si_no || {})) P.siNo[k] = prepKw(v); P.codici = (raw.codici || []).map((c) => ({ kw: prepKw(c.kw), pratiche: c.pratiche || [], intento: c.intento })); for (const s of raw.speciali || []) P.speciali[s.id] = prepKw(s.kw); P.intenti = (raw.intenti || []).map((i) => ({ id: i.id, start: i.start, peso: i.peso || 1, kw: prepKw(i.kw) })); for (const [id, n] of Object.entries(raw.nodi || {})) { P.nodi[id] = { ...n, opts: (n.opts || []).map((o) => ({ ...o, kwP: prepKw(o.kw) })) }; } return P; } // Età e percentuale scritte nel testo ("ho 70 anni", "invalido al 80%"). Con `attesa` vale anche il numero da solo. function estraiSlot(T, attesa) { const s = {}; let m = T.match(/ (\d{1,3}) ?(%|per ?cento|percent|pour ?cent|por ?ciento|procent|perqind|відсот|百分)/); if (m && +m[1] <= 100) s.perc = +m[1]; m = T.match(/ (\d{1,3}) ?(anni|anno|enne|years?|yrs|yo|ans|anos|ani|vjec|vjet|рок|рік|років|岁|周岁|বছর|سنه|سنوات|عام|عاما)/); if (m && +m[1] <= 120) s.eta = +m[1]; if (attesa && s[attesa] == null) { const n = T.match(/ (\d{1,3}) /); if (n) s[attesa] = +n[1]; } return s; } // Sceglie l'opzione di una domanda in base al testo. Restituisce null se nessuna o se è ambiguo. function sceltaDaTesto(id, n, T, slot, risposta) { if (n.slot && slot[n.slot] != null) { const v = slot[n.slot]; const o = n.opts.find((o) => o[n.slot] && v >= o[n.slot][0] && v <= o[n.slot][1]); if (o) return o; } const breve = risposta && parole(T).length <= 4; const q = T.trim(); let best = null, bs = 0, pari = false; for (const o of n.opts) { let s = corrisponde(T, o.kwP, breve); if (o.slot && slot[o.slot] != null) s += 10; if (risposta && q.length >= 2) { for (const lab of new Set([tp(`${id}.${o.id}`), testiP.it?.[`${id}.${o.id}`]])) { const L = norm(lab).trim(); if (L && (L === q || L.startsWith(q + ' '))) s += 20; } } if (s > bs) { best = o; bs = s; pari = false; } else if (s && s === bs) pari = true; } return best && !pari ? best : null; } /* ---------- ricerca nelle pratiche (parole con radice, peso alle parole rare) ---------- */ const STOP = new Set(('il lo la i gli le un uno una di da in con su per tra fra a e o ma se che chi come cosa dove quando quale quali quanto quanti mi ti si ci vi ne non ho hai ha hanno sono sei era del della dei delle degli al alla ai alle dal dalla nel nella sul sulla posso puoi puo devo vorrei voglio fare avere ricevere serve servono richiedere chiedere domanda pratica pratiche info informazioni aiuto bisogno documenti documento sapere capire spiegare ciao salve buongiorno grazie mio mia miei mie tuo tua suo sua anche gia ancora molto piu ' + 'the an of to for on and or is are my me what how can do does which who need want get help please hello thanks ' + 'de les des du et ou en pour une est je mon ma mes que qui quoi comment el los las y es mi como quiero puedo necesito para por con').split(' ')); function cerca(q) { const tok = parole(norm(q)).filter((w) => (w.length > 1 || /\d/.test(w)) && !STOP.has(w)); if (!tok.length) return []; const docs = pratiche.map((p) => ({ p, titolo: norm([p.pratica, campo(p, 'pratica'), p.id.replace(/-/g, ' '), ...(p.sinonimi || [])].join(' ')), corpo: norm([p.categoria, nomeCategoria(p.categoria), campo(p, 'cos_e'), campo(p, 'a_chi_spetta')].join(' ')), })); // parole che non compaiono in nessuna pratica: provo a correggerle con il vocabolario (refusi) const voc = new Set(); for (const d of docs) for (const w of parole(d.titolo + d.corpo)) if (w.length >= 4) voc.add(w); const corretti = tok.map((w) => { if (voc.has(w) || w.length < 4 || /\d/.test(w) || !LATINA.test(w) || [...voc].some((v) => v.startsWith(w.length > 5 ? w.slice(0, -2) : w))) return w; let mig = null, md = 9; for (const v of voc) { if (Math.abs(v.length - w.length) > 2) continue; const dd = scheletro(v) === scheletro(w) ? 0 : lev(v, w); if (dd < md) { md = dd; mig = v; } } return mig && md <= (w.length >= 8 ? 2 : 1) ? mig : w; }); tok.splice(0, tok.length, ...corretti); const punti = new Map(); for (const w of tok) { const r = w.length > 5 && !/\d/.test(w) ? w.slice(0, w.length - 2) : w; const inTit = (d) => (SENZA_SPAZI.test(r) ? d.titolo.includes(r) : d.titolo.includes(' ' + r)); const inCor = (d) => (SENZA_SPAZI.test(r) ? d.corpo.includes(r) : d.corpo.includes(' ' + r)); const df = docs.filter((d) => inTit(d) || inCor(d)).length; if (!df) continue; const idf = Math.log(1 + docs.length / df); for (const d of docs) { const s = inTit(d) ? 3 * idf : inCor(d) ? idf : 0; if (s) punti.set(d.p, (punti.get(d.p) || 0) + s); } } const ord = [...punti].sort((a, b) => b[1] - a[1]); if (!ord.length) return []; const top = ord[0][1]; return ord.filter(([, s]) => s >= top * 0.5).slice(0, 5).map(([p]) => p); } // Cosa ha scritto l'utente? (fuori da una domanda in corso) function classifica(q) { const T = norm(q); const breve = parole(T).length <= 4; const sp = (id) => corrisponde(T, M.speciali[id] || [], breve) > 0; if (sp('operatore')) return { tipo: 'operatore' }; const ids = []; for (const c of M.codici) { if (!corrisponde(T, c.kw, breve)) continue; if (c.intento) { const it = M.intenti.find((i) => i.id === c.intento); if (it) return { tipo: 'intento', intento: it }; } for (const id of c.pratiche) if (!ids.includes(id)) ids.push(id); } if (ids.length) return { tipo: 'pratiche', ids, diretta: true }; let best = null, bs = 0; for (const it of M.intenti) { const s = corrisponde(T, it.kw, breve) * it.peso; if (s > bs) { bs = s; best = it; } } if (best) return { tipo: 'intento', intento: best }; if (sp('grazie')) return { tipo: 'grazie' }; if (sp('saluto') && breve) return { tipo: 'saluto' }; const r = cerca(q); if (r.length) return { tipo: 'pratiche', ids: r.map((p) => p.id), diretta: false }; if (sp('saluto')) return { tipo: 'saluto' }; return { tipo: 'nulla' }; } /* ---------- DOM ---------- */ const css = ` .scb-launch{position:fixed;inset-block-end:20px;inset-inline-end:20px;z-index:2147483000;width:60px;height:60px;border-radius:50%;border:0;background:#25d366;color:#fff;box-shadow:0 10px 28px -8px rgba(0,0,0,.45);cursor:pointer;display:grid;place-items:center} .scb-launch{background:#fff;padding:0;width:64px;height:64px;transition:transform .2s} .scb-launch:hover{transform:translateY(-3px) scale(1.04)} .scb-launch img{width:64px;height:64px;border-radius:50%;display:block} .scb-launch .wa{position:absolute;inset-block-end:-2px;inset-inline-end:-2px;width:26px;height:26px;border-radius:50%;background:#25d366;color:#fff;display:grid;place-items:center;border:2px solid #fff} .scb-launch .wa svg{width:15px;height:15px} .scb header .scb-av{width:42px;height:42px;border-radius:50%;flex:none;box-shadow:0 0 0 2px rgba(255,255,255,.7)} .scb .msg.rb{display:flex;gap:8px;align-items:flex-start;background:none;border:0;padding:0;max-width:94%} .scb .msg.rb img{width:30px;height:30px;border-radius:50%;flex:none} .scb .msg.rb span{background:#fff;border:1px solid var(--line);border-radius:14px;padding:10px 12px} .scb-launch:focus-visible{outline:3px solid #1356a5;outline-offset:3px} .scb{--blue:#1356a5;--ink:#0d2340;--orange:#ef7f1a;--line:#dbe2eb;--soft:#e6eef8;margin:0;padding:0;border:0;position:fixed;inset:auto 20px 92px auto;width:min(390px,calc(100vw - 24px));height:min(640px,calc(100dvh - 120px));border-radius:16px;background:#fff;color:#2b3a4f;box-shadow:0 24px 60px -20px rgba(13,35,64,.55);font:15px/1.45 "Public Sans",system-ui,-apple-system,"Segoe UI",sans-serif;overflow:hidden} .scb[open],.scb:popover-open{display:flex;flex-direction:column} .scb[dir=rtl]{inset:auto auto 92px 20px} @media (max-width:520px){.scb,.scb[dir=rtl]{inset:auto 0 0 0;width:100vw;height:88dvh;border-radius:18px 18px 0 0}} .scb header{background:var(--blue);color:#fff;padding:14px 16px;display:flex;align-items:center;gap:10px} .scb header h2{font:600 16px/1.2 Lexend,system-ui,sans-serif;margin:0;color:#fff!important;letter-spacing:normal;text-transform:none} .scb header p{color:#fff!important} .scb header p{margin:2px 0 0;font-size:12px;opacity:.85} .scb header .sp{flex:1} .scb header button{background:rgba(255,255,255,.14);border:0;color:#fff;border-radius:8px;min-width:36px;height:36px;font-size:13px;cursor:pointer;padding:0 10px} .scb .log{flex:1;overflow-y:auto;overscroll-behavior:contain;padding:16px;display:flex;flex-direction:column;gap:10px;background:#f4f6f9} .scb .msg{max-width:88%;padding:10px 12px;border-radius:14px;background:#fff;border:1px solid var(--line);white-space:pre-line} .scb .msg.me{align-self:flex-end;background:var(--blue);color:#fff;border-color:var(--blue)} .scb .opts{display:flex;flex-wrap:wrap;gap:6px} .scb .btnlink{display:inline-block;border:1px solid var(--blue);background:#fff;color:var(--blue);border-radius:999px;padding:7px 12px;font-size:14px;text-decoration:none} .scb .btnlink.wa{background:#25d366;border-color:#25d366;color:#073b1c;font-weight:600} .scb .sedebox{display:grid;gap:4px} .scb .sedebox .opts{margin-top:8px} .scb .opts button{border:1px solid var(--blue);background:#fff;color:var(--blue);border-radius:999px;padding:7px 12px;font:inherit;font-size:14px;cursor:pointer;text-align:start} .scb .opts button:hover{background:var(--soft)} .scb .opts button:disabled{opacity:.4;cursor:default;background:#fff} .scb .msg.note{background:transparent;border:0;padding:0 4px;font-size:13px;color:#5d6b7e} .scb .opts button.wa{background:#25d366;border-color:#25d366;color:#fff;font-weight:600} .scb .card{background:#fff;border:1px solid var(--line);border-radius:14px;padding:12px 14px;max-width:100%} .scb .card h3{margin:0 0 6px;font:600 16px/1.25 Lexend,system-ui,sans-serif;color:var(--ink)} .scb .card h4{margin:10px 0 2px;font-size:13px;text-transform:uppercase;letter-spacing:.03em;color:var(--blue)} .scb .card p{margin:0} .scb .card ul{margin:4px 0 0;padding-inline-start:20px} .scb .card li{margin:2px 0} .scb .msg strong,.scb .card strong{font-weight:700;color:var(--ink)} .scb .msg.me strong{color:#fff} .scb .card .docs{background:#fff7ec;border:1px solid #f6d3a8;border-inline-start:4px solid var(--orange);border-radius:10px;padding:8px 10px;margin-top:10px} .scb .card .docs h4{margin-top:0;color:#9a4a00} .scb .card .docs .hint{font-size:12px;color:#7a5a36;margin:0 0 4px} .scb .card .docs ul{list-style:none;padding:0} .scb .card .docs li{display:flex;gap:8px;align-items:flex-start;padding:5px 0;border-top:1px dashed #f0d2ad} .scb .card .docs li:first-child{border-top:0} .scb .card .docs li .t{flex:1} .scb .card .docs li .t::before{content:"☐ ";color:#9a4a00} .scb .card .docs li.ok .t::before{content:"✅ "} .scb .card .docs li .f{display:block;font-size:12px;color:#1d7a3e} .scb .card .docs li button{flex:none;border:1px solid var(--orange);background:#fff;color:#9a4a00;border-radius:999px;padding:3px 9px;font:600 12px system-ui;cursor:pointer} .scb .card .scad{background:var(--soft);border-radius:10px;padding:8px 10px;margin-top:10px} .scb .card .scad h4{margin-top:0} .scb details.guida{background:#fff;border:1px solid var(--line);border-radius:12px;padding:8px 12px;max-width:100%} .scb details.guida summary{cursor:pointer;font-weight:600;color:var(--blue)} .scb details.guida ul{margin:6px 0 0;padding-inline-start:18px} .scb details.guida li{margin:4px 0} .scb .tray{display:none;gap:6px;padding:8px 10px 0;background:#fff;border-top:1px solid var(--line);overflow-x:auto} .scb .tray.on{display:flex} .scb .chip{flex:none;display:flex;align-items:center;gap:6px;border:1px solid var(--line);border-radius:10px;padding:4px 6px;font-size:12px;max-width:180px;background:#f9fafc} .scb .chip img,.scb .chip .pdf{width:28px;height:28px;border-radius:6px;object-fit:cover;flex:none;display:grid;place-items:center;background:#e9edf3;font-size:10px;font-weight:700;color:#b42318} .scb .chip span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap} .scb .chip button{border:0;background:none;cursor:pointer;color:#5d6b7e;font-size:14px;padding:0 2px} .scb .passi{background:#fff;border:1px solid var(--line);border-radius:14px;padding:10px 12px;display:flex;flex-direction:column;gap:8px;max-width:100%} .scb .passi p{margin:0} .scb .passi button{align-self:flex-start;border:0;border-radius:999px;padding:8px 14px;font:600 14px system-ui;cursor:pointer;background:#25d366;color:#fff} .scb .passi button.files{background:var(--blue)} .scb .passi button.files.pronto{animation:scb-pulse 1.2s ease-in-out 3;box-shadow:0 0 0 0 rgba(19,86,165,.5)} @keyframes scb-pulse{50%{box-shadow:0 0 0 8px rgba(19,86,165,0)}} .scb .passi ul{margin:0;padding-inline-start:18px;font-size:13px} .scb .card .tag{display:inline-block;font-size:12px;background:var(--soft);color:var(--blue);border-radius:999px;padding:2px 8px;margin-bottom:6px} .scb .card .itnote{font-size:12px;color:#b55a07;margin-top:8px} .scb form{display:flex;gap:8px;padding:10px;border-top:1px solid var(--line);background:#fff} .scb .tray.on + form{border-top:0} .scb form button.clip{background:var(--soft);color:var(--blue);padding:0 10px;font-size:18px} .scb input{flex:1;min-width:0;border:1px solid var(--line);border-radius:10px;padding:10px 12px;font:inherit} .scb form button{border:0;background:var(--orange);color:#fff;border-radius:10px;padding:0 14px;font:600 14px system-ui;cursor:pointer} .scb .privacy{font-size:11px;color:#5d6b7e;padding:0 12px 10px;background:#fff;margin:0} `; // Volto di Roberta (stesso disegno di roberta.svg) const ROBERTA = 'data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 200 200%22 role=%22img%22 aria-label=%22Roberta%22%3E %3Cdefs%3E %3CradialGradient id=%22rb-bg%22 cx=%2235%25%22 cy=%2228%25%22 r=%2280%25%22%3E%3Cstop offset=%220%22 stop-color=%22%23eaf2fc%22/%3E%3Cstop offset=%22.6%22 stop-color=%22%23bcd3ef%22/%3E%3Cstop offset=%221%22 stop-color=%22%237fa6d8%22/%3E%3C/radialGradient%3E %3CradialGradient id=%22rb-skin%22 cx=%2240%25%22 cy=%2235%25%22 r=%2270%25%22%3E%3Cstop offset=%220%22 stop-color=%22%23ffe3cf%22/%3E%3Cstop offset=%22.55%22 stop-color=%22%23f6c3a0%22/%3E%3Cstop offset=%221%22 stop-color=%22%23d9946c%22/%3E%3C/radialGradient%3E %3CradialGradient id=%22rb-neck%22 cx=%2250%25%22 cy=%2220%25%22 r=%2290%25%22%3E%3Cstop offset=%220%22 stop-color=%22%23e9ad87%22/%3E%3Cstop offset=%221%22 stop-color=%22%23c98060%22/%3E%3C/radialGradient%3E %3ClinearGradient id=%22rb-hair%22 x1=%220%22 y1=%220%22 x2=%220%22 y2=%221%22%3E%3Cstop offset=%220%22 stop-color=%22%237a4a2c%22/%3E%3Cstop offset=%22.55%22 stop-color=%22%234f2d1a%22/%3E%3Cstop offset=%221%22 stop-color=%22%232f1a0f%22/%3E%3C/linearGradient%3E %3CradialGradient id=%22rb-hairhi%22 cx=%2238%25%22 cy=%2222%25%22 r=%2245%25%22%3E%3Cstop offset=%220%22 stop-color=%22%23b9805a%22 stop-opacity=%22.9%22/%3E%3Cstop offset=%221%22 stop-color=%22%23b9805a%22 stop-opacity=%220%22/%3E%3C/radialGradient%3E %3ClinearGradient id=%22rb-shirt%22 x1=%220%22 y1=%220%22 x2=%220%22 y2=%221%22%3E%3Cstop offset=%220%22 stop-color=%22%232a6fc4%22/%3E%3Cstop offset=%221%22 stop-color=%22%23123f7a%22/%3E%3C/linearGradient%3E %3CradialGradient id=%22rb-cheek%22 cx=%2250%25%22 cy=%2250%25%22 r=%2250%25%22%3E%3Cstop offset=%220%22 stop-color=%22%23f08a7a%22 stop-opacity=%22.55%22/%3E%3Cstop offset=%221%22 stop-color=%22%23f08a7a%22 stop-opacity=%220%22/%3E%3C/radialGradient%3E %3CradialGradient id=%22rb-iris%22 cx=%2240%25%22 cy=%2235%25%22 r=%2270%25%22%3E%3Cstop offset=%220%22 stop-color=%22%238a5a3a%22/%3E%3Cstop offset=%221%22 stop-color=%22%232b170c%22/%3E%3C/radialGradient%3E %3ClinearGradient id=%22rb-set%22 x1=%220%22 y1=%220%22 x2=%221%22 y2=%221%22%3E%3Cstop offset=%220%22 stop-color=%22%233b3f47%22/%3E%3Cstop offset=%221%22 stop-color=%22%2315171b%22/%3E%3C/linearGradient%3E %3CradialGradient id=%22rb-mic%22 cx=%2235%25%22 cy=%2235%25%22 r=%2270%25%22%3E%3Cstop offset=%220%22 stop-color=%22%23ffb066%22/%3E%3Cstop offset=%221%22 stop-color=%22%23e0700f%22/%3E%3C/radialGradient%3E %3CradialGradient id=%22rb-shade%22 cx=%2245%25%22 cy=%2240%25%22 r=%2262%25%22%3E%3Cstop offset=%22.7%22 stop-color=%22%23b8704c%22 stop-opacity=%220%22/%3E%3Cstop offset=%221%22 stop-color=%22%23b8704c%22 stop-opacity=%22.45%22/%3E%3C/radialGradient%3E %3Cfilter id=%22rb-soft%22 x=%22-20%25%22 y=%22-20%25%22 width=%22140%25%22 height=%22140%25%22%3E%3CfeGaussianBlur stdDeviation=%223%22/%3E%3C/filter%3E %3CclipPath id=%22rb-clip%22%3E%3Ccircle cx=%22100%22 cy=%22100%22 r=%22100%22/%3E%3C/clipPath%3E %3C/defs%3E %3Cg clip-path=%22url(%23rb-clip)%22%3E %3Ccircle cx=%22100%22 cy=%22100%22 r=%22100%22 fill=%22url(%23rb-bg)%22/%3E %3Cpath d=%22M44 96c-6-44 22-74 58-74s62 28 56 74c-2 30 4 56 10 84H34c6-28 12-54 10-84z%22 fill=%22url(%23rb-hair)%22/%3E %3Cpath d=%22M60 60c10-22 30-30 50-28%22 fill=%22none%22 stroke=%22%23c48a62%22 stroke-width=%225%22 stroke-linecap=%22round%22 opacity=%22.45%22 filter=%22url(%23rb-soft)%22/%3E %3Cpath d=%22M28 214c4-34 30-52 72-52s68 18 72 52z%22 fill=%22url(%23rb-shirt)%22/%3E %3Cpath d=%22M40 200c6-20 22-30 40-33%22 fill=%22none%22 stroke=%22%23fff%22 stroke-width=%226%22 stroke-linecap=%22round%22 opacity=%22.18%22 filter=%22url(%23rb-soft)%22/%3E %3Cpath d=%22M78 164l22 20 22-20%22 fill=%22none%22 stroke=%22%23fff%22 stroke-width=%225%22 stroke-linejoin=%22round%22 opacity=%22.9%22/%3E %3Cpath d=%22M84 140h32v26c-6 8-26 8-32 0z%22 fill=%22url(%23rb-neck)%22/%3E %3Cellipse cx=%22100%22 cy=%22146%22 rx=%2230%22 ry=%228%22 fill=%22%239c5b3c%22 opacity=%22.35%22 filter=%22url(%23rb-soft)%22/%3E %3Cellipse cx=%2255%22 cy=%22104%22 rx=%229%22 ry=%2213%22 fill=%22url(%23rb-skin)%22/%3E %3Cellipse cx=%22145%22 cy=%22104%22 rx=%229%22 ry=%2213%22 fill=%22url(%23rb-skin)%22/%3E %3Cpath d=%22M56 92c0-30 20-50 44-50s44 20 44 50c0 34-20 56-44 56s-44-22-44-56z%22 fill=%22url(%23rb-skin)%22/%3E %3Cpath d=%22M56 92c0-30 20-50 44-50s44 20 44 50c0 34-20 56-44 56s-44-22-44-56z%22 fill=%22url(%23rb-shade)%22/%3E %3Cellipse cx=%2288%22 cy=%22112%22 rx=%2222%22 ry=%2216%22 fill=%22%23fff%22 opacity=%22.18%22 filter=%22url(%23rb-soft)%22/%3E %3Cpath d=%22M54 92c-2-34 20-58 48-58 26 0 46 18 46 50-14-4-30-14-38-30-8 18-30 34-56 38z%22 fill=%22url(%23rb-hair)%22/%3E %3Cpath d=%22M54 92c-2-34 20-58 48-58 26 0 46 18 46 50-14-4-30-14-38-30-8 18-30 34-56 38z%22 fill=%22url(%23rb-hairhi)%22/%3E %3Cpath d=%22M73 86q9-6 18-1%22 fill=%22none%22 stroke=%22%234a2a18%22 stroke-width=%223.2%22 stroke-linecap=%22round%22/%3E %3Cpath d=%22M109 85q9-5 18 1%22 fill=%22none%22 stroke=%22%234a2a18%22 stroke-width=%223.2%22 stroke-linecap=%22round%22/%3E %3Cellipse cx=%2282%22 cy=%22100%22 rx=%228.5%22 ry=%229.5%22 fill=%22%23fff%22/%3E %3Cellipse cx=%22118%22 cy=%22100%22 rx=%228.5%22 ry=%229.5%22 fill=%22%23fff%22/%3E %3Ccircle cx=%2283%22 cy=%22101%22 r=%226%22 fill=%22url(%23rb-iris)%22/%3E %3Ccircle cx=%22117%22 cy=%22101%22 r=%226%22 fill=%22url(%23rb-iris)%22/%3E %3Ccircle cx=%2283%22 cy=%22101%22 r=%222.6%22 fill=%22%23120904%22/%3E %3Ccircle cx=%22117%22 cy=%22101%22 r=%222.6%22 fill=%22%23120904%22/%3E %3Ccircle cx=%2285.5%22 cy=%2298%22 r=%222.1%22 fill=%22%23fff%22/%3E %3Ccircle cx=%22119.5%22 cy=%2298%22 r=%222.1%22 fill=%22%23fff%22/%3E %3Cpath d=%22M73 95q9-8 18 0%22 fill=%22none%22 stroke=%22%232b170c%22 stroke-width=%222.6%22 stroke-linecap=%22round%22/%3E %3Cpath d=%22M109 95q9-8 18 0%22 fill=%22none%22 stroke=%22%232b170c%22 stroke-width=%222.6%22 stroke-linecap=%22round%22/%3E %3Cpath d=%22M100 106q-4 10 0 14q3 1 5-1%22 fill=%22none%22 stroke=%22%23c98060%22 stroke-width=%222.4%22 stroke-linecap=%22round%22/%3E %3Ccircle cx=%2272%22 cy=%22120%22 r=%2210%22 fill=%22url(%23rb-cheek)%22/%3E %3Ccircle cx=%22128%22 cy=%22120%22 r=%2210%22 fill=%22url(%23rb-cheek)%22/%3E %3Cpath d=%22M86 128q14 13 28 0q-14 5-28 0z%22 fill=%22%23c2453f%22/%3E %3Cpath d=%22M90 130q10 4 20 0%22 fill=%22none%22 stroke=%22%23fff%22 stroke-width=%222.4%22 stroke-linecap=%22round%22/%3E %3Cpath d=%22M50 100c0-38 22-62 50-62s50 24 50 62%22 fill=%22none%22 stroke=%22url(%23rb-set)%22 stroke-width=%226%22 stroke-linecap=%22round%22/%3E %3Crect x=%2240%22 y=%2292%22 width=%2216%22 height=%2226%22 rx=%228%22 fill=%22url(%23rb-set)%22/%3E %3Crect x=%22144%22 y=%2292%22 width=%2216%22 height=%2226%22 rx=%228%22 fill=%22url(%23rb-set)%22/%3E %3Crect x=%22146%22 y=%2296%22 width=%225%22 height=%2212%22 rx=%222.5%22 fill=%22%23fff%22 opacity=%22.25%22/%3E %3Cpath d=%22M48 116c2 18 16 24 34 22%22 fill=%22none%22 stroke=%22url(%23rb-set)%22 stroke-width=%224%22 stroke-linecap=%22round%22/%3E %3Ccircle cx=%2286%22 cy=%22138%22 r=%226%22 fill=%22url(%23rb-mic)%22/%3E %3C/g%3E %3C/svg%3E'; const WA_ICON = ''; let dlg, log, input, form, privacyEl, titleEl, subEl, langBtn, closeBtn, clipBtn, fileInput, tray; const hasPopover = IN_BROWSER && 'popover' in HTMLElement.prototype; function el(tag, attrs = {}, ...children) { const n = document.createElement(tag); for (const [k, v] of Object.entries(attrs)) { if (k === 'class') n.className = v; else if (k.startsWith('on')) n.addEventListener(k.slice(2), v); else n.setAttribute(k, v); } for (const c of children) if (c != null) n.append(c); return n; } function build() { dlg = el('dialog', { class: 'scb', 'aria-labelledby': 'scb-title' }); if (hasPopover) dlg.setAttribute('popover', 'manual'); titleEl = el('h2', { id: 'scb-title' }); const avatar = el('img', { class: 'scb-av', src: ROBERTA, alt: '', width: '42', height: '42' }); subEl = el('p'); langBtn = el('button', { type: 'button', onclick: chiediLingua }); closeBtn = el('button', { type: 'button', onclick: chiudi }, '✕'); log = el('div', { class: 'log', role: 'log', 'aria-live': 'polite' }); input = el('input', { type: 'search', enterkeyhint: 'search', autocomplete: 'off' }); clipBtn = el('button', { type: 'button', class: 'clip', onclick: () => scegliFile(null) }, '📎'); fileInput = el('input', { type: 'file', multiple: '', accept: ACCETTA, hidden: '' }); fileInput.addEventListener('change', () => { aggiungiFile([...fileInput.files], fileInput._doc); fileInput.value = ''; }); form = el('form', { onsubmit: (e) => { e.preventDefault(); const q = input.value.trim(); if (q && M) { input.value = ''; gestisciTesto(q); } } }, clipBtn, input, el('button', { type: 'submit' }), fileInput); tray = el('div', { class: 'tray', 'aria-live': 'polite' }); privacyEl = el('p', { class: 'privacy' }); dlg.append(el('header', {}, avatar, el('div', {}, titleEl, subEl), el('span', { class: 'sp' }), langBtn, closeBtn), log, tray, form, privacyEl); document.body.append(dlg); traduciInterfaccia(); } function traduciInterfaccia() { dlg.lang = lang; dlg.dir = RTL.has(lang) ? 'rtl' : 'ltr'; titleEl.textContent = t('title'); subEl.textContent = t('subtitle'); langBtn.textContent = lang.toUpperCase(); langBtn.setAttribute('aria-label', t('lang')); closeBtn.setAttribute('aria-label', t('close')); input.placeholder = tp('ui.placeholder'); input.setAttribute('aria-label', tp('ui.placeholder')); form.querySelector('button[type=submit]').textContent = tp('ui.invia'); privacyEl.textContent = tp('ui.privacy'); clipBtn.setAttribute('aria-label', tp('ui.allegaFile')); clipBtn.title = tp('ui.allegaFile'); disegnaTray(); } /* ---------- messaggi ---------- */ const scorri = () => requestAnimationFrame(() => { log.scrollTop = log.scrollHeight; }); function bot(testo) { log.append(el('div', { class: 'msg' }, ricco(testo))); scorri(); } // messaggio con il volto di Roberta (saluto iniziale) function botRb(testo) { log.append(el('div', { class: 'msg rb' }, el('img', { src: ROBERTA, alt: '' }), el('span', {}, ricco(testo)))); scorri(); } // **testo** -> grassetto (senza innerHTML). Con auto=true mette in grassetto anche cifre, importi, date e durate. const RE_NUM = /(? { if (i % 2) { frag.append(el('strong', {}, parte)); return; } if (!auto) { frag.append(parte); return; } let ultimo = 0; for (const m of parte.matchAll(RE_NUM)) { frag.append(parte.slice(ultimo, m.index), el('strong', {}, m[0])); ultimo = m.index + m[0].length; } frag.append(parte.slice(ultimo)); }); return frag; } // Nome breve del documento in grassetto: la parte prima di ':' o '(' (o tutto, se corto) function docRicco(d) { const m = d.match(/^([^:(]{3,60})([:(].*)$/s); if (m) return el('span', {}, el('strong', {}, m[1].trim()), (m[2][0] === ':' ? '' : ' ') + m[2]); return d.length <= 60 ? el('strong', {}, d) : el('span', {}, d); } function utente(testo) { log.append(el('div', { class: 'msg me' }, testo)); scorri(); } function opzioni(lista) { const box = el('div', { class: 'opts' }); for (const o of lista) { box.append(el('button', { type: 'button', class: o.cls || '', onclick: () => { if (o.echo !== false) utente(o.label); o.go(); } }, o.label)); } log.append(box); scorri(); return box; } /* ---------- flusso ---------- */ function chiediLingua() { botRb(UI[lang].hello); opzioni(LINGUE.map(([code, nome]) => ({ label: nome, go: () => scegliLingua(code) }))); } async function scegliLingua(code, silenzioso) { lang = code; await caricaLingua(code); traduciInterfaccia(); if (silenzioso) { bot(tp('ui.saluto')); return; } menu(tp('ui.benvenuto')); } /* --- conversazione guidata --- */ let corrente = null; // domanda in attesa di risposta let storia = []; // domande già risposte nel percorso (per "Indietro") let contesto = { T: '', slot: {} }; // ciò che l'utente ha scritto: serve a saltare le domande a cui ha già risposto let boxDomanda = null; function nota(testo) { log.append(el('div', { class: 'msg note' }, testo)); scorri(); } function disattiva() { boxDomanda?.querySelectorAll('button').forEach((b) => { b.disabled = true; }); boxDomanda = null; } function menu(intro) { disattiva(); corrente = null; storia = []; contesto = { T: '', slot: {} }; bot(intro || tp('ui.situazioni')); opzioni([ ...M.intenti.map((it) => ({ label: tp('int.' + it.id), go: () => avviaIntento(it, '') })), { label: '📍 ' + tp('ui.sede'), go: sede }, { label: '☰ ' + tp('ui.perArgomento'), go: argomenti }, ]); input.focus(); } /* --- sede più vicina (usa window.SPC_sedeVicina e window.SPC_SEDI del sito) --- */ let attesaCitta = false; const RE_SEDE = /(sede|sedi|vostr[oi] uffic|uffici vicin|ufficio vicin|sportello piu vicin|piu vicin|dove siete|dove vi trovo|vostro indirizz|near|nearest|office|where are you|address|bureau|agence|adresse|ou etes vous|proche|oficina|sucursal|direccion|donde estais|donde estan|cerca de mi|مكتب|مقر|عنوان|اقرب|أقرب|زياره|birou|sediu|adresa|zyra|adresa|офіс|відділен|адрес|найближч|办公|办事处|地址|最近|অফিস|ঠিকানা|কাছাকাছি)/; const sediSito = () => (Array.isArray(window.SPC_SEDI) ? window.SPC_SEDI : []).filter((x) => x && x.lat && x.lng); function sede() { disattiva(); corrente = null; attesaCitta = false; bot(tp('ui.sedeChiedi')); const ops = []; if (navigator.geolocation) ops.push({ label: '📍 ' + tp('ui.sedePosizione'), go: sedeDaPosizione }); ops.push({ label: '🏙️ ' + tp('ui.sedeCitta'), go: () => { attesaCitta = true; bot(tp('ui.sedeCittaChiedi')); input.focus(); } }); ops.push({ label: '↩ ' + tp('ui.ricomincia'), go: () => menu() }); opzioni(ops); } function linkBtn(label, href, cls) { return el('a', { class: 'btnlink ' + (cls || ''), href, target: '_blank', rel: 'noopener' }, label); } function mostraSede(s, km) { const righe = [s.nome, [s.indirizzo, s.citta].filter(Boolean).join(', ')]; if (km != null) righe.push(`${km.toFixed(1)} km`); if (s.orari) righe.push(s.orari); bot(tp('ui.sedeTrovata')); log.append(el('div', { class: 'msg sedebox' }, el('strong', {}, righe[0]), ...righe.slice(1).filter(Boolean).map((r) => el('div', {}, r)), el('div', { class: 'opts' }, linkBtn('🧭 ' + tp('ui.sedeIndicazioni'), `https://www.google.com/maps/dir/?api=1&destination=${s.lat},${s.lng}`), CFG.whatsapp ? linkBtn(tp('ui.operatore'), `https://wa.me/${CFG.whatsapp}?text=${encodeURIComponent(`${tp('ui.sedeWaMsg')} (${s.nome})`)}`, 'wa') : null))); scorri(); finale(false); } function sedeNonTrovata(extra) { bot(tp('ui.sedeNessuna')); const msg = `${testiP.it?.['ui.sedeWaMsg'] || tp('ui.sedeWaMsg')}${extra ? ' ' + extra : ''}`; if (CFG.whatsapp) { log.append(el('div', { class: 'opts' }, linkBtn(tp('ui.sedeWa'), `https://wa.me/${CFG.whatsapp}?text=${encodeURIComponent(msg)}`, 'wa'))); scorri(); } opzioni([{ label: '↩ ' + tp('ui.ricomincia'), go: () => menu() }]); } async function sedeDaPosizione() { bot(tp('ui.sedeAttendi')); try { if (typeof window.SPC_sedeVicina !== 'function') throw new Error('no'); const r = await window.SPC_sedeVicina(); if (r.sede) return mostraSede(r.sede, r.dist); sedeNonTrovata(`https://maps.google.com/?q=${r.pos.lat.toFixed(4)},${r.pos.lng.toFixed(4)}`); } catch { bot(tp('ui.sedeNegata')); attesaCitta = true; input.focus(); } } function sedeDaCitta(q) { attesaCitta = false; const T = norm(q); const s = sediSito().find((x) => norm(`${x.citta || ''} ${x.cap || ''} ${x.provincia || ''} ${x.nome || ''}`).includes(T.trim()) || T.includes(norm(x.citta || '#').trim())); if (s) return mostraSede(s, null); sedeNonTrovata(`(${q})`); } function avviaIntento(it, testo) { storia = []; const T = testo ? norm(testo) : ''; contesto = { T, slot: T ? estraiSlot(T) : {} }; vai(it.start); } function vai(id) { const n = M.nodi[id]; if (!n) return menu(); if (n.tipo === 'esito') return esito(id, n); const auto = contesto.T || Object.keys(contesto.slot).length ? sceltaDaTesto(id, n, contesto.T || ' ', contesto.slot, false) : null; if (auto) { nota(`✓ ${tp('ui.capito')}: ${tp(`${id}.${auto.id}`)}`); storia.push(id); return vai(auto.go); } chiedi(id); } function chiedi(id, soloOpzioni) { const n = M.nodi[id]; corrente = id; if (!soloOpzioni) bot(tp(id)); const ops = n.opts.map((o) => ({ label: tp(`${id}.${o.id}`), go: () => scegli(id, o) })); ops.push(storia.length ? { label: '↩ ' + tp('ui.indietro'), go: indietro } : { label: '↩ ' + tp('ui.ricomincia'), go: () => menu() }); disattiva(); boxDomanda = opzioni(ops); input.focus(); } function scegli(id, o) { disattiva(); corrente = null; storia.push(id); vai(o.go); } function indietro() { disattiva(); contesto = { T: '', slot: {} }; const prev = storia.pop(); if (prev) chiedi(prev); else menu(); } function esito(id, n) { corrente = null; bot(tp(id)); const ps = (n.pratiche || []).map((pid) => pratiche.find((p) => p.id === pid)).filter(Boolean); if (ps.length) { bot(tp('ui.esito')); opzioni(ps.map((p) => ({ label: '📄 ' + campo(p, 'pratica'), go: () => scheda(p) }))); } if (n.next) return vai(n.next); nota(tp('ui.disclaimer')); finale(n.wa); } function finale(waEvidenza) { const ops = []; if (CFG.whatsapp) ops.push({ label: tp('ui.operatore'), cls: waEvidenza ? 'wa' : '', echo: false, go: () => inviaWhatsApp(null) }); ops.push({ label: '↩ ' + tp('ui.ricomincia'), go: () => menu() }); opzioni(ops); } function listaPratiche(ids) { const ps = ids.map((id) => pratiche.find((p) => p.id === id)).filter(Boolean); if (ps.length === 1) return scheda(ps[0]); bot(tp('ui.forse')); opzioni([ ...ps.map((p) => ({ label: '📄 ' + campo(p, 'pratica'), go: () => scheda(p) })), { label: '☰ ' + tp('ui.situazioni'), go: () => menu() }, ]); } // Testo scritto dall'utente function gestisciTesto(q) { utente(q); const T = norm(q); if (attesaCitta) return sedeDaCitta(q); if (RE_SEDE.test(T) && !corrente) return sede(); if (corrente) { const id = corrente, n = M.nodi[id]; const slot = estraiSlot(T, n.slot); const o = sceltaDaTesto(id, n, T, slot, true); if (o) { contesto = { T: contesto.T + T, slot: { ...contesto.slot, ...slot } }; return scegli(id, o); } } const c = classifica(q); if (c.tipo === 'nulla' && corrente) { bot(tp('ui.rispostaNonCapita')); return chiedi(corrente, true); } disattiva(); corrente = null; switch (c.tipo) { case 'intento': return avviaIntento(c.intento, q); case 'pratiche': return listaPratiche(c.ids); case 'operatore': bot(CFG.whatsapp ? tp('ui.operatoreMsg') : tp('ui.operatoreNo')); return finale(true); case 'grazie': bot(tp('ui.grazie')); return finale(false); case 'saluto': return menu(tp('ui.saluto')); default: return menu(tp('ui.nonCapito')); } } function argomenti() { bot(t('askTopic')); // prima le categorie note nell'ordine previsto, poi quelle nuove nell'ordine di pratiche.json const presenti = [...CATEGORIE, ...pratiche.map((p) => p.categoria)].filter((c, i, a) => a.indexOf(c) === i && pratiche.some((p) => p.categoria === c)); opzioni(presenti.map((c) => ({ label: nomeCategoria(c), go: () => categoria(c) }))); input.focus(); } function categoria(c) { bot(t('askPractice')); opzioni([ ...pratiche.filter((p) => p.categoria === c).map((p) => ({ label: campo(p, 'pratica'), go: () => scheda(p) })), { label: '↩ ' + t('topics'), go: argomenti }, ]); } function sezione(titolo, v) { if (!v || (Array.isArray(v) && !v.length)) return null; const frag = document.createDocumentFragment(); frag.append(el('h4', {}, titolo)); if (Array.isArray(v)) { const ul = el('ul'); v.forEach((d) => ul.append(el('li', {}, ricco(d, true)))); frag.append(ul); } else frag.append(el('p', {}, ricco(v, true))); return frag; } function scheda(p) { ultimaPratica = p; const card = el('article', { class: 'card' }, el('span', { class: 'tag' }, nomeCategoria(p.categoria)), el('h3', {}, campo(p, 'pratica')), sezione(t('what'), campo(p, 'cos_e')), sezione(t('who'), campo(p, 'a_chi_spetta')), sezioneDocumenti(p), sezione(t('how'), campo(p, 'dove_e_come')), campo(p, 'scadenze') ? el('div', { class: 'scad' }, sezione('⏰ ' + t('deadlines'), campo(p, 'scadenze'))) : null, sezione(t('notes'), campo(p, 'note')), !tradotta(p) && t('itNote') ? el('p', { class: 'itnote' }, t('itNote')) : null, ); log.append(card, guida()); scorri(); const ops = []; if (CFG.whatsapp) ops.push({ label: t('wa'), cls: 'wa', echo: false, go: () => inviaWhatsApp(p) }); ops.push({ label: t('copy'), echo: false, go: () => copia(p) }); ops.push({ label: '↩ ' + t('other'), go: () => menu() }); opzioni(ops); requestAnimationFrame(() => card.scrollIntoView({ block: 'start', behavior: 'smooth' })); } async function copia(p) { const testo = `${campo(p, 'pratica')}\n${t('docs')}:\n` + (campo(p, 'documenti') || []).map((d) => `- ${d}`).join('\n'); try { await navigator.clipboard.writeText(testo); bot('✓ ' + t('copied')); } catch { /* clipboard non disponibile */ } } /* ---------- documenti allegati (restano nel browser finché l'utente non li condivide) ---------- */ const ACCETTA = 'image/*,application/pdf'; const MAX_FILE = 10, MAX_MB = 15; let allegati = []; // { id, file, url, doc: { pid, i } | null } let seqFile = 0; const fmt = (k, v) => tp(k).replace(/\{(\w+)\}/g, (_, x) => v[x] ?? ''); function scegliFile(doc) { fileInput._doc = doc; if (doc) fileInput.removeAttribute('multiple'); else fileInput.setAttribute('multiple', ''); fileInput.click(); } function aggiungiFile(files, doc) { const ok = []; for (const f of files) { if (!(f.type.startsWith('image/') || f.type === 'application/pdf' || /\.(pdf|jpe?g|png|heic|heif|webp)$/i.test(f.name))) { bot(fmt('ui.fileTipo', { nome: f.name })); continue; } if (f.size > MAX_MB * 1024 * 1024) { bot(fmt('ui.fileTroppoGrande', { nome: f.name })); continue; } if (allegati.length >= MAX_FILE) { bot(tp('ui.fileMax')); break; } const a = { id: ++seqFile, file: f, url: f.type.startsWith('image/') ? URL.createObjectURL(f) : null, doc: doc || null }; if (doc) allegati = allegati.filter((x) => { const same = x.doc && x.doc.pid === doc.pid && x.doc.i === doc.i; if (same && x.url) URL.revokeObjectURL(x.url); return !same; }); allegati.push(a); ok.push(a); } if (!ok.length) return; utente('📎 ' + ok.map((a) => a.file.name).join(', ')); bot(fmt('ui.fileAggiunti', { n: allegati.length })); disegnaTray(); aggiornaDocumenti(); } function rimuoviFile(id) { const a = allegati.find((x) => x.id === id); if (a?.url) URL.revokeObjectURL(a.url); allegati = allegati.filter((x) => x.id !== id); disegnaTray(); aggiornaDocumenti(); } function disegnaTray() { if (!tray) return; tray.replaceChildren(...allegati.map((a) => el('div', { class: 'chip', title: a.file.name }, a.url ? el('img', { src: a.url, alt: '' }) : el('span', { class: 'pdf' }, 'PDF'), el('span', {}, a.file.name), el('button', { type: 'button', 'aria-label': `${tp('ui.rimuovi')}: ${a.file.name}`, onclick: () => rimuoviFile(a.id) }, '✕')))); tray.classList.toggle('on', allegati.length > 0); } // Riquadro "Documenti da portare" con 📎 accanto a ogni documento function sezioneDocumenti(p) { const docs = campo(p, 'documenti') || []; if (!docs.length) return null; const ul = el('ul'); docs.forEach((d, i) => { ul.append(el('li', { 'data-pid': p.id, 'data-i': String(i) }, el('span', { class: 't' }, docRicco(d), el('span', { class: 'f' })), el('button', { type: 'button', onclick: () => scegliFile({ pid: p.id, i }) }, '📎 ' + tp('ui.allega')))); }); const box = el('div', { class: 'docs' }, el('h4', {}, '📋 ' + t('docs')), el('p', { class: 'hint' }, ricco(tp('ui.docsHint'))), ul); queueMicrotask(aggiornaDocumenti); return box; } function aggiornaDocumenti() { log?.querySelectorAll('.docs li[data-pid]').forEach((li) => { const a = allegati.find((x) => x.doc && x.doc.pid === li.dataset.pid && x.doc.i === +li.dataset.i); li.classList.toggle('ok', !!a); li.querySelector('.f').textContent = a ? '📎 ' + a.file.name : ''; }); } function guida() { const righe = tp('ui.guida').split('\n').filter(Boolean); return el('details', { class: 'guida' }, el('summary', {}, '📸 ' + tp('ui.guidaTitolo')), el('ul', {}, ...righe.map((r) => el('li', {}, ricco(r.replace(/^[-•]\s*/, '')))))); } // Messaggio WhatsApp: pratica + documenti inviati + documenti mancanti. Nomi dei documenti in italiano per l'operatore. function messaggioWhatsApp(p) { const nome = p ? (lang === 'it' ? p.pratica : `${campo(p, 'pratica')} (${p.pratica})`) : ''; const hdr = (k) => (lang === 'it' ? testiP.it[k] : `${testiP.it[k]} / ${tp(k)}`); let txt = t('waMsg')(nome); const conDoc = p ? allegati.filter((a) => a.doc && a.doc.pid === p.id) : []; const altri = allegati.filter((a) => !conDoc.includes(a)); if (allegati.length) { txt += `\n\n${hdr('ui.waHdrInvio')} (${allegati.length} file):`; for (const a of conDoc) txt += `\n✅ ${p.documenti[a.doc.i]} → ${a.file.name}`; for (const a of altri) txt += `\n📎 ${a.doc ? (pratiche.find((x) => x.id === a.doc.pid)?.documenti[a.doc.i] + ' → ') : ''}${a.file.name}`; } if (p && p.documenti?.length) { const mancanti = p.documenti.filter((_, i) => !conDoc.some((a) => a.doc.i === i)); if (mancanti.length) txt += `\n\n${hdr('ui.waHdrMancanti')}:\n` + mancanti.map((d) => `☐ ${d}`).join('\n'); } return txt; } function apriWhatsApp(p) { const url = `https://wa.me/${CFG.whatsapp}?text=${encodeURIComponent(messaggioWhatsApp(p))}`; window.open(url, '_blank', 'noopener'); } function inviaWhatsApp(p) { // Un solo tocco: si apre la chat dello Sportello con il riepilogo (wa.me funziona anche senza il numero in rubrica). // I link wa.me non possono portare file: i documenti si allegano con la graffetta nella chat appena aperta. apriWhatsApp(p); if (!allegati.length) return; log.append(el('div', { class: 'passi' }, el('p', {}, ricco(tp('ui.allegaInChat'))), el('ul', {}, ...allegati.map((a) => el('li', {}, a.file.name))))); scorri(); } /* ---------- apertura / chiusura ---------- */ let avviato = false; async function apri(linguaPagina, domanda) { if (typeof linguaPagina !== 'string') linguaPagina = ''; if (!dlg) build(); if (hasPopover) { if (!dlg.matches(':popover-open')) dlg.showPopover(); } else if (!dlg.open) dlg.show(); if (!avviato) { avviato = true; try { await Promise.all([caricaDati(), caricaPercorsi()]); } catch { bot('⚠️ Dati non disponibili.'); return; } traduciInterfaccia(); const pag = linguaPagina || CFG.lang; if (pag && UI[pag]) { if (!domanda) botRb(UI[pag].hello.split(/(?<=[!!])\s*/)[0]); await scegliLingua(pag, !!domanda); } else { const pref = (navigator.language || 'it').slice(0, 2); if (UI[pref] && pref !== 'it') { lang = pref; await caricaLingua(pref); traduciInterfaccia(); } chiediLingua(); } } if (domanda) gestisciTesto(domanda); input.focus(); } function chiudi() { if (hasPopover) dlg.hidePopover(); else dlg.close(); } function toggle() { const aperto = dlg && (hasPopover ? dlg.matches(':popover-open') : dlg.open); aperto ? chiudi() : apri(); } function init() { document.head.append(el('style', {}, css)); const trig = CFG.trigger && document.querySelector(CFG.trigger); if (trig) { trig.addEventListener('click', (e) => { e.preventDefault(); toggle(); }); } else { const b = el('button', { type: 'button', class: 'scb-launch', 'aria-label': UI.it.open, onclick: toggle }); b.innerHTML = ``; document.body.append(b); } } if (!IN_BROWSER) { // Per i test in Node: node tools/test-chatbot.js module.exports = { imposta(pr, perc, testi, l = 'it') { pratiche = pr; M = prepara(perc); Object.assign(testiP, testi); lang = l; }, classifica, sceltaDaTesto, estraiSlot, norm, cerca, nodo: (id) => M.nodi[id], }; return; } if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init); else init(); window.SportelloChatbot = { apri, chiudi, chiedi: (testo, l) => apri(l || '', testo), sede: async (l) => { await apri(l || ''); sede(); }, apriWhatsApp: () => inviaWhatsApp(ultimaPratica) }; })();