') .setTitle(APP.NAME) .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL); } /** API via fetch (pagina ospitata fuori da Apps Script, es. Netlify) */ function doPost(e) { let req = {}; try { req = JSON.parse(e.postData.contents); } catch (err) { return json_({ ok: false, error: 'Richiesta non valida' }); } return json_(handle_(req)); } /** API via google.script.run (pagina servita da Apps Script) */ function api(req) { return JSON.stringify(handle_(req)); } function json_(o) { return ContentService.createTextOutput(JSON.stringify(o)).setMimeType(ContentService.MimeType.JSON); } const ROUTES = { 'app.config': { pub: 1, read: 1, fn: function () { return { name: APP.NAME, googleClientId: cfg_('GOOGLE_CLIENT_ID'), appUrl: cfg_('APP_URL') }; } }, 'lead.create': { pub: 1, fn: leadCreate_ }, 'auth.register': { pub: 1, fn: authRegister_ }, 'auth.login': { pub: 1, fn: authLogin_ }, 'auth.google': { pub: 1, fn: authGoogle_ }, 'auth.reset': { pub: 1, fn: authReset_ }, 'auth.me': { read: 1, fn: function (p, u) { return { user: pubUser_(u) }; } }, 'auth.logout': { fn: authLogout_ }, 'profile.save': { fn: profileSave_ }, 'events.list': { admin: 1, read: 1, fn: eventsList_ }, 'events.save': { admin: 1, fn: eventsSave_ }, 'events.delete': { admin: 1, fn: eventsDelete_ }, 'events.perms': { admin: 1, fn: eventsPerms_ }, 'event.get': { admin: 1, read: 1, fn: eventGet_ }, 'staff.save': { admin: 1, fn: staffSave_ }, 'staff.delete': { admin: 1, fn: staffDelete_ }, 'staff.invite': { admin: 1, fn: staffInvite_ }, 'att.set': { admin: 1, fn: attSet_ }, 'break.toggle': { admin: 1, fn: breakToggle_ }, 'break.save': { admin: 1, fn: breakSave_ }, 'break.delete': { admin: 1, fn: breakDelete_ }, 'feedback.add': { admin: 1, fn: feedbackAdd_ }, 'feedback.delete': { admin: 1, fn: feedbackDelete_ }, 'note.add': { fn: noteAdd_ }, 'note.delete': { admin: 1, fn: noteDelete_ }, 'photo.upload': { fn: photoUpload_ }, 'photo.delete': { fn: photoDelete_ }, 'users.list': { admin: 1, read: 1, fn: usersList_ }, 'users.save': { admin: 1, fn: usersSave_ }, 'users.resetCode': { admin: 1, fn: usersResetCode_ }, 'leads.list': { admin: 1, read: 1, fn: leadsList_ }, 'leads.save': { admin: 1, fn: leadsSave_ }, 'my.events': { read: 1, fn: myEvents_ }, 'my.event': { read: 1, fn: myEvent_ }, 'my.checkin': { fn: myCheckin_ }, 'my.checkout': { fn: myCheckout_ }, 'my.break': { fn: myBreak_ } }; function handle_(req) { const r = ROUTES[req && req.action]; if (!r) return { ok: false, error: 'Azione non valida' }; let lock = null; try { if (!r.read) { lock = LockService.getScriptLock(); lock.waitLock(25000); } let user = null; if (!r.pub) { user = auth_(req.token); if (!user) return { ok: false, code: 'AUTH', error: 'Sessione scaduta: accedi di nuovo' }; if (r.admin && user.role !== 'admin') return { ok: false, error: 'Permesso negato' }; } return { ok: true, data: r.fn(req.p || {}, user, req) }; } catch (e) { return { ok: false, error: String((e && e.message) || e) }; } finally { if (lock) { try { lock.releaseLock(); } catch (e) {} } } } /* ============================================================ * DATA LAYER (Google Sheets) * ============================================================ */ const _T = {}; function ss_() { if (!_T.__ss) { const id = PropertiesService.getScriptProperties().getProperty('SHEET_ID'); if (!id) throw new Error('Database non configurato: esegui la funzione setup()'); _T.__ss = SpreadsheetApp.openById(id); } return _T.__ss; } function table_(n) { if (_T[n]) return _T[n]; let sh = ss_().getSheetByName(n); if (!sh && SCHEMA[n]) { sh = ss_().insertSheet(n); sh.getRange(1, 1, 1, SCHEMA[n].length).setValues([SCHEMA[n]]).setFontWeight('bold').setBackground('#14213d').setFontColor('#ffffff'); sh.setFrozenRows(1); } if (!sh) throw new Error('Foglio mancante: ' + n + ' (esegui setup)'); let v = sh.getDataRange().getValues(); if (SCHEMA[n]) { const head = v[0].map(String); const missing = SCHEMA[n].filter(function (k) { return head.indexOf(k) < 0; }); if (missing.length && head.join('') !== '') { sh.getRange(1, head.length + 1, 1, missing.length).setValues([missing]).setFontWeight('bold').setBackground('#14213d').setFontColor('#ffffff'); v = sh.getDataRange().getValues(); } } const h = v[0].map(String); const rows = []; for (let i = 1; i < v.length; i++) { const r = v[i]; if (r.join('') === '') continue; const o = { _r: i + 1 }; h.forEach(function (k, j) { if (k) o[k] = norm_(r[j]); }); rows.push(o); } _T[n] = { sh: sh, h: h, rows: rows }; return _T[n]; } function all_(n) { return table_(n).rows; } function find_(n, f) { return all_(n).find(f) || null; } function filter_(n, f) { return all_(n).filter(f); } function insert_(n, o) { const t = table_(n); if (!o.id && t.h.indexOf('id') >= 0) o.id = uid_(); const vals = t.h.map(function (k) { return val_(o[k]); }); const r = Math.max(t.sh.getLastRow(), 1) + 1; t.sh.getRange(r, 1, 1, t.h.length).setNumberFormat('@').setValues([vals]); o._r = r; t.rows.push(o); return o; } function update_(n, o, patch) { const t = table_(n); Object.assign(o, patch || {}); const vals = t.h.map(function (k) { return val_(o[k]); }); t.sh.getRange(o._r, 1, 1, t.h.length).setNumberFormat('@').setValues([vals]); return o; } function remove_(n, list) { if (!list || !list.length) return; const t = table_(n); if (list.length <= 5) { list.map(function (o) { return o._r; }).sort(function (a, b) { return b - a; }) .forEach(function (r) { t.sh.deleteRow(r); }); } else { const del = {}; list.forEach(function (o) { del[o._r] = 1; }); const data = t.sh.getDataRange().getValues(); const keep = data.slice(1).filter(function (r, i) { return !del[i + 2]; }); const last = t.sh.getLastRow(); if (last > 1) t.sh.getRange(2, 1, last - 1, data[0].length).clearContent(); if (keep.length) t.sh.getRange(2, 1, keep.length, data[0].length).setNumberFormat('@').setValues(keep); } delete _T[n]; } function norm_(v) { if (v instanceof Date) { if (v.getFullYear() < 1900) return Utilities.formatDate(v, APP.TZ, 'HH:mm'); const t = Utilities.formatDate(v, APP.TZ, 'HH:mm'); return Utilities.formatDate(v, APP.TZ, 'yyyy-MM-dd') + (t === '00:00' ? '' : ' ' + t); } return v === null || v === undefined ? '' : String(v); } function val_(v) { return v === null || v === undefined ? '' : String(v); } function pick_(o) { const c = {}; Object.keys(o).forEach(function (k) { if (k !== '_r' && k !== 'passHash' && k !== 'salt' && k !== 'resetCode' && k !== 'resetExp') c[k] = o[k]; }); return c; } function uid_() { return Utilities.getUuid().replace(/-/g, '').slice(0, 10) + Date.now().toString(36).slice(-4); } function now_() { return Utilities.formatDate(new Date(), APP.TZ, 'yyyy-MM-dd HH:mm'); } function today_() { return Utilities.formatDate(new Date(), APP.TZ, 'yyyy-MM-dd'); } function clean_(v, max) { return String(v === null || v === undefined ? '' : v).replace(/[\u0000-\u001f]+/g, ' ').trim().slice(0, max || 200); } function cleanML_(v, max) { return String(v === null || v === undefined ? '' : v).replace(/\r/g, '').trim().slice(0, max || 2000); } function normEmail_(e) { return String(e || '').trim().toLowerCase(); } function validEmail_(e) { return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e); } function validDate_(d) { return /^\d{4}-\d{2}-\d{2}$/.test(d || ''); } function validTime_(t) { return /^([01]\d|2[0-3]):[0-5]\d$/.test(t || ''); } function cfg_(key) { const r = find_('Config', function (x) { return x.key === key; }); return r ? String(r.value || '').trim() : ''; } function setCfg_(key, val) { const r = find_('Config', function (x) { return x.key === key; }); if (r) update_('Config', r, { value: val }); else insert_('Config', { key: key, value: val, descrizione: '' }); } function adminEmails_() { return cfg_('ADMIN_EMAILS').split(/[,;\s]+/).map(normEmail_).filter(Boolean); } function isAdminEmail_(e) { return adminEmails_().indexOf(normEmail_(e)) >= 0; } function daysOf_(e) { const out = []; if (!validDate_(e.dateStart)) return out; const end = validDate_(e.dateEnd) && e.dateEnd >= e.dateStart ? e.dateEnd : e.dateStart; const d = new Date(e.dateStart + 'T12:00:00Z'); for (let i = 0; i < APP.MAX_EVENT_DAYS; i++) { const s = Utilities.formatDate(d, 'UTC', 'yyyy-MM-dd'); out.push(s); if (s >= end) break; d.setUTCDate(d.getUTCDate() + 1); } return out; } /* ============================================================ * AUTENTICAZIONE * ============================================================ */ function hash_(pw, salt) { let h = salt + '|' + pw; for (let i = 0; i < 300; i++) { h = Utilities.base64Encode(Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, h + salt, Utilities.Charset.UTF_8)); } return h; } function pubUser_(u) { return { id: u.id, email: u.email, name: u.name, phone: u.phone, role: u.role, provider: u.provider, hasPassword: !!u.passHash }; } function session_(u) { const token = Utilities.getUuid().replace(/-/g, '') + Utilities.getUuid().replace(/-/g, ''); const exp = Utilities.formatDate(new Date(Date.now() + APP.SESSION_DAYS * 864e5), APP.TZ, 'yyyy-MM-dd HH:mm'); insert_('Sessions', { token: token, userId: u.id, createdAt: now_(), expiresAt: exp }); update_('Users', u, { lastLogin: now_() }); try { CacheService.getScriptCache().put('s_' + token, u.id, 21600); } catch (e) {} if (Math.random() < 0.05) { const n = now_(); remove_('Sessions', filter_('Sessions', function (s) { return s.expiresAt < n; })); } return { token: token, user: pubUser_(u) }; } function auth_(token) { if (!token) return null; const cache = CacheService.getScriptCache(); let userId = null; try { userId = cache.get('s_' + token); } catch (e) {} if (!userId) { const s = find_('Sessions', function (x) { return x.token === token; }); if (!s || s.expiresAt < now_()) return null; userId = s.userId; try { cache.put('s_' + token, userId, 21600); } catch (e) {} } const u = find_('Users', function (x) { return x.id === userId; }); if (!u || u.active === 'no') return null; return u; } function syncRole_(u) { if (isAdminEmail_(u.email) && u.role !== 'admin') update_('Users', u, { role: 'admin' }); } function authRegister_(p) { const email = normEmail_(p.email); const name = clean_(p.name, 80); if (!name) throw new Error('Inserisci nome e cognome'); if (!validEmail_(email)) throw new Error('Email non valida'); if (String(p.password || '').length < 6) throw new Error('La password deve avere almeno 6 caratteri'); if (find_('Users', function (u) { return u.email === email; })) throw new Error('Email già registrata: accedi oppure recupera la password'); const salt = uid_() + uid_(); const u = insert_('Users', { email: email, name: name, phone: clean_(p.phone, 30), role: isAdminEmail_(email) ? 'admin' : 'hostess', provider: 'password', passHash: hash_(String(p.password), salt), salt: salt, resetCode: '', resetExp: '', active: 'si', createdAt: now_(), lastLogin: '' }); return session_(u); } function authLogin_(p) { const email = normEmail_(p.email); const u = find_('Users', function (x) { return x.email === email; }); if (!u) throw new Error('Email o password non corretti'); if (u.active === 'no') throw new Error('Account disattivato: contatta l\'agenzia'); if (!u.passHash) throw new Error('Questo account usa Google: premi "Accedi con Google" oppure imposta una password con "Password dimenticata?"'); if (hash_(String(p.password || ''), u.salt) !== u.passHash) throw new Error('Email o password non corretti'); syncRole_(u); return session_(u); } function authGoogle_(p) { const cid = cfg_('GOOGLE_CLIENT_ID'); if (!cid) throw new Error('Accesso con Google non configurato'); const res = UrlFetchApp.fetch('https://oauth2.googleapis.com/tokeninfo?id_token=' + encodeURIComponent(p.credential || ''), { muteHttpExceptions: true }); if (res.getResponseCode() !== 200) throw new Error('Accesso Google non valido, riprova'); const t = JSON.parse(res.getContentText()); if (t.aud !== cid) throw new Error('Accesso Google non valido (client)'); if (String(t.email_verified) !== 'true') throw new Error('Email Google non verificata'); const email = normEmail_(t.email); let u = find_('Users', function (x) { return x.email === email; }); if (!u) { u = insert_('Users', { email: email, name: clean_(t.name || email.split('@')[0], 80), phone: '', role: isAdminEmail_(email) ? 'admin' : 'hostess', provider: 'google', passHash: '', salt: '', resetCode: '', resetExp: '', active: 'si', createdAt: now_(), lastLogin: '' }); } else if (u.provider.indexOf('google') < 0) { update_('Users', u, { provider: u.provider ? u.provider + '+google' : 'google' }); } if (u.active === 'no') throw new Error('Account disattivato: contatta l\'agenzia'); syncRole_(u); return session_(u); } function authReset_(p) { const email = normEmail_(p.email); const u = find_('Users', function (x) { return x.email === email; }); if (!u || !u.resetCode || u.resetCode !== String(p.code || '').trim() || Number(u.resetExp) < Date.now()) { throw new Error('Codice non valido o scaduto'); } if (String(p.password || '').length < 6) throw new Error('La password deve avere almeno 6 caratteri'); const salt = uid_() + uid_(); const prov = u.provider && u.provider.indexOf('password') < 0 ? 'password+' + u.provider : (u.provider || 'password'); update_('Users', u, { passHash: hash_(String(p.password), salt), salt: salt, resetCode: '', resetExp: '', provider: prov }); syncRole_(u); return session_(u); } function authLogout_(p, u, req) { const s = find_('Sessions', function (x) { return x.token === req.token; }); if (s) remove_('Sessions', [s]); try { CacheService.getScriptCache().remove('s_' + req.token); } catch (e) {} return { ok: true }; } function profileSave_(p, u) { const patch = {}; if (p.name !== undefined) { const n = clean_(p.name, 80); if (!n) throw new Error('Il nome è obbligatorio'); patch.name = n; } if (p.phone !== undefined) patch.phone = clean_(p.phone, 30); if (p.password) { if (String(p.password).length < 6) throw new Error('La password deve avere almeno 6 caratteri'); if (u.passHash && hash_(String(p.oldPassword || ''), u.salt) !== u.passHash) throw new Error('La password attuale non è corretta'); const salt = uid_() + uid_(); patch.passHash = hash_(String(p.password), salt); patch.salt = salt; if (u.provider.indexOf('password') < 0) patch.provider = 'password+' + u.provider; } update_('Users', u, patch); return { user: pubUser_(u) }; } /* ============================================================ * EVENTI (admin) * ============================================================ */ function eventsList_(p) { const today = today_(); const staff = all_('Staff'); const att = filter_('Attendance', function (a) { return a.date === today; }); const list = all_('Events').map(function (e) { const st = staff.filter(function (s) { return s.eventId === e.id; }); const ids = {}; st.forEach(function (s) { ids[s.id] = 1; }); const present = att.filter(function (a) { return ids[a.staffId] && a.status === 'presente'; }).length; return Object.assign(pick_(e), { staffAssigned: st.length, presentToday: present }); }); return { today: today, events: list }; } function eventsSave_(p, u) { const fields = ['name', 'client', 'location', 'address', 'dateStart', 'dateEnd', 'timeStart', 'timeEnd', 'breaks', 'staffCount', 'notes', 'status', 'selfCheckin', 'selfBreaks']; const d = {}; fields.forEach(function (k) { if (p[k] !== undefined) d[k] = k === 'notes' ? cleanML_(p[k], 2000) : clean_(p[k], 300); }); if (!d.name) throw new Error('Inserisci il nome dell\'evento'); if (!validDate_(d.dateStart)) throw new Error('Data di inizio non valida'); if (!validDate_(d.dateEnd) || d.dateEnd < d.dateStart) d.dateEnd = d.dateStart; if (daysOf_(d).slice(-1)[0] !== d.dateEnd) throw new Error('Durata massima evento: ' + APP.MAX_EVENT_DAYS + ' giorni'); if (d.timeStart && !validTime_(d.timeStart)) throw new Error('Orario di inizio non valido'); if (d.timeEnd && !validTime_(d.timeEnd)) throw new Error('Orario di fine non valido'); if (d.selfCheckin !== undefined) d.selfCheckin = d.selfCheckin === 'no' ? 'no' : 'si'; if (d.selfBreaks !== undefined) d.selfBreaks = d.selfBreaks === 'si' ? 'si' : 'no'; const n = parseInt(d.staffCount, 10); d.staffCount = isNaN(n) || n < 0 ? '' : String(n); d.updatedAt = now_(); if (p.id) { const e = find_('Events', function (x) { return x.id === p.id; }); if (!e) throw new Error('Evento non trovato'); update_('Events', e, d); return { event: pick_(e) }; } d.status = d.status || 'attivo'; if (!d.selfCheckin) d.selfCheckin = 'si'; if (!d.selfBreaks) d.selfBreaks = 'no'; d.createdBy = u.email; d.createdAt = now_(); d.folderId = ''; return { event: pick_(insert_('Events', d)) }; } /** Permessi dello staff per evento: arrivo/fine turno e pause dall'app */ function eventsPerms_(p) { const e = find_('Events', function (x) { return x.id === p.id; }); if (!e) throw new Error('Evento non trovato'); const patch = { updatedAt: now_() }; if (p.selfCheckin !== undefined) patch.selfCheckin = p.selfCheckin ? 'si' : 'no'; if (p.selfBreaks !== undefined) patch.selfBreaks = p.selfBreaks ? 'si' : 'no'; update_('Events', e, patch); return { event: pick_(e) }; } function canSelfCheckin_(e) { return e.selfCheckin !== 'no'; } function canSelfBreaks_(e) { return e.selfBreaks === 'si'; } function eventsDelete_(p) { const e = find_('Events', function (x) { return x.id === p.id; }); if (!e) throw new Error('Evento non trovato'); if (e.folderId) { try { DriveApp.getFolderById(e.folderId).setTrashed(true); } catch (err) {} } const byEv = function (x) { return x.eventId === e.id; }; ['Attendance', 'Breaks', 'Feedback', 'Notes', 'Photos', 'Staff'].forEach(function (t) { remove_(t, filter_(t, byEv)); }); remove_('Events', [find_('Events', function (x) { return x.id === p.id; })]); return { deleted: true }; } function photoOut_(ph) { const o = pick_(ph); o.thumb = 'https://drive.google.com/thumbnail?id=' + ph.fileId + '&sz=w600'; o.full = 'https://drive.google.com/thumbnail?id=' + ph.fileId + '&sz=w1600'; o.link = 'https://drive.google.com/file/d/' + ph.fileId + '/view'; return o; } function desc_(k) { return function (a, b) { return String(b[k]).localeCompare(String(a[k])); }; } function eventGet_(p) { const e = find_('Events', function (x) { return x.id === p.id; }); if (!e) throw new Error('Evento non trovato'); const byEv = function (x) { return x.eventId === e.id; }; const staff = filter_('Staff', byEv).map(pick_).sort(function (a, b) { return a.name.localeCompare(b.name); }); return { event: pick_(e), days: daysOf_(e), today: today_(), now: now_(), staff: staff, attendance: filter_('Attendance', byEv).map(pick_), breaks: filter_('Breaks', byEv).map(pick_), feedback: filter_('Feedback', byEv).map(pick_).sort(desc_('createdAt')), notes: filter_('Notes', byEv).map(pick_).sort(desc_('createdAt')), photos: filter_('Photos', byEv).sort(desc_('createdAt')).map(photoOut_) }; } /* ============================================================ * STAFF (admin) * ============================================================ */ function staffSave_(p) { const e = find_('Events', function (x) { return x.id === p.eventId; }); if (!e) throw new Error('Evento non trovato'); const list = Array.isArray(p.list) ? p.list : []; if (!list.length) throw new Error('Nessun nominativo da salvare'); const created = []; let updated = 0; list.forEach(function (it) { const d = { name: clean_(it.name, 80), email: normEmail_(it.email), phone: clean_(it.phone, 30), role: clean_(it.role, 60), timeStart: clean_(it.timeStart, 5), timeEnd: clean_(it.timeEnd, 5), notes: cleanML_(it.notes, 500) }; if (!d.name) return; if (d.email && !validEmail_(d.email)) throw new Error('Email non valida per ' + d.name + ': ' + d.email); if (d.timeStart && !validTime_(d.timeStart)) d.timeStart = ''; if (d.timeEnd && !validTime_(d.timeEnd)) d.timeEnd = ''; if (it.id) { const s = find_('Staff', function (x) { return x.id === it.id && x.eventId === e.id; }); if (s) { if (s.email !== d.email) d.invitedAt = ''; update_('Staff', s, d); updated++; } } else { d.eventId = e.id; d.createdAt = now_(); d.invitedAt = ''; created.push(insert_('Staff', d)); } }); return { created: created.length, updated: updated, ids: created.map(function (s) { return s.id; }) }; } function staffDelete_(p) { const s = find_('Staff', function (x) { return x.id === p.id; }); if (!s) throw new Error('Nominativo non trovato'); const bySt = function (x) { return x.staffId === s.id; }; ['Attendance', 'Breaks', 'Feedback'].forEach(function (t) { remove_(t, filter_(t, bySt)); }); remove_('Staff', [find_('Staff', function (x) { return x.id === p.id; })]); return { deleted: true }; } /** Segna come invitati (l'invito parte dal WhatsApp dell'admin, non dal server) */ function staffInvite_(p) { const ids = Array.isArray(p.ids) ? p.ids : []; let n = 0; filter_('Staff', function (s) { return ids.indexOf(s.id) >= 0; }).forEach(function (s) { update_('Staff', s, { invitedAt: now_() }); n++; }); return { invited: n }; } /* ============================================================ * APPELLO / PAUSE / FEEDBACK (admin) * ============================================================ */ function staffCtx_(staffId, date) { const s = find_('Staff', function (x) { return x.id === staffId; }); if (!s) throw new Error('Nominativo non trovato'); const e = find_('Events', function (x) { return x.id === s.eventId; }); if (!e) throw new Error('Evento non trovato'); if (date !== undefined && daysOf_(e).indexOf(date) < 0) throw new Error('La data non rientra nell\'evento'); return { s: s, e: e }; } function stamp_(date, s, e) { return date === today_() ? now_() : date + ' ' + (s.timeStart || e.timeStart || '09:00'); } function attUpsert_(s, date, patch, by) { let a = find_('Attendance', function (x) { return x.staffId === s.id && x.date === date; }); patch.updatedAt = now_(); patch.updatedBy = by; if (a) update_('Attendance', a, patch); else a = insert_('Attendance', Object.assign({ staffId: s.id, eventId: s.eventId, date: date, status: 'attesa', arrivalAt: '', arrivalBy: '', lat: '', lng: '', exitAt: '' }, patch)); return pick_(a); } function closeOpenBreak_(s, date) { const b = find_('Breaks', function (x) { return x.staffId === s.id && x.date === date && !x.endAt; }); if (b) update_('Breaks', b, { endAt: date === today_() ? now_() : b.startAt }); } function attSet_(p, u) { const c = staffCtx_(p.staffId, p.date); const s = c.s, e = c.e, date = p.date; const cur = find_('Attendance', function (x) { return x.staffId === s.id && x.date === date; }); const patch = {}; if (p.status) { if (['attesa', 'presente', 'assente', 'uscito'].indexOf(p.status) < 0) throw new Error('Stato non valido'); patch.status = p.status; if (p.status === 'presente') { if (!cur || !cur.arrivalAt) { patch.arrivalAt = stamp_(date, s, e); patch.arrivalBy = 'agenzia'; } patch.exitAt = ''; } if (p.status === 'uscito') { if (!cur || !cur.arrivalAt) { patch.arrivalAt = date + ' ' + (s.timeStart || e.timeStart || '09:00'); patch.arrivalBy = 'agenzia'; } if (!cur || !cur.exitAt) patch.exitAt = date === today_() ? now_() : date + ' ' + (s.timeEnd || e.timeEnd || '18:00'); closeOpenBreak_(s, date); } if (p.status === 'attesa' || p.status === 'assente') { patch.arrivalAt = ''; patch.arrivalBy = ''; patch.exitAt = ''; patch.lat = ''; patch.lng = ''; closeOpenBreak_(s, date); } } if (p.arrivalTime !== undefined) { if (!validTime_(p.arrivalTime)) throw new Error('Orario di arrivo non valido'); patch.arrivalAt = date + ' ' + p.arrivalTime; patch.arrivalBy = 'agenzia'; const st = patch.status || (cur ? cur.status : ''); if (st !== 'presente' && st !== 'uscito') patch.status = 'presente'; } if (p.exitTime !== undefined) { if (p.exitTime === '') { patch.exitAt = ''; if (cur && cur.status === 'uscito') patch.status = 'presente'; } else { if (!validTime_(p.exitTime)) throw new Error('Orario di uscita non valido'); patch.exitAt = date + ' ' + p.exitTime; patch.status = 'uscito'; closeOpenBreak_(s, date); } } return { att: attUpsert_(s, date, patch, u.name) }; } function breakToggle_(p, u) { const c = staffCtx_(p.staffId, p.date); const open = find_('Breaks', function (x) { return x.staffId === c.s.id && x.date === p.date && !x.endAt; }); if (open) { update_('Breaks', open, { endAt: now_() }); return { break: pick_(open), running: false }; } const a = find_('Attendance', function (x) { return x.staffId === c.s.id && x.date === p.date; }); if (!a || a.status !== 'presente') throw new Error('Segna prima la presenza di ' + c.s.name); if (p.date !== today_()) throw new Error('Per date diverse da oggi aggiungi la pausa manualmente'); const b = insert_('Breaks', { staffId: c.s.id, eventId: c.s.eventId, date: p.date, startAt: now_(), endAt: '', by: u.name }); return { break: pick_(b), running: true }; } function breakSave_(p, u) { if (!validTime_(p.start)) throw new Error('Orario di inizio pausa non valido'); if (p.end && !validTime_(p.end)) throw new Error('Orario di fine pausa non valido'); if (p.end && p.end < p.start) throw new Error('La fine pausa è prima dell\'inizio'); if (p.id) { const b = find_('Breaks', function (x) { return x.id === p.id; }); if (!b) throw new Error('Pausa non trovata'); update_('Breaks', b, { startAt: b.date + ' ' + p.start, endAt: p.end ? b.date + ' ' + p.end : '' }); return { break: pick_(b) }; } const c = staffCtx_(p.staffId, p.date); const b = insert_('Breaks', { staffId: c.s.id, eventId: c.s.eventId, date: p.date, startAt: p.date + ' ' + p.start, endAt: p.end ? p.date + ' ' + p.end : '', by: u.name }); return { break: pick_(b) }; } function breakDelete_(p) { const b = find_('Breaks', function (x) { return x.id === p.id; }); if (!b) throw new Error('Pausa non trovata'); remove_('Breaks', [b]); return { deleted: true }; } function feedbackAdd_(p, u) { const c = staffCtx_(p.staffId); const r = parseInt(p.rating, 10); if (!(r >= 1 && r <= 5) && !clean_(p.text)) throw new Error('Inserisci un voto o un commento'); const f = insert_('Feedback', { staffId: c.s.id, eventId: c.s.eventId, rating: r >= 1 && r <= 5 ? String(r) : '', text: cleanML_(p.text, 1000), by: u.name, createdAt: now_() }); return { feedback: pick_(f) }; } function feedbackDelete_(p) { const f = find_('Feedback', function (x) { return x.id === p.id; }); if (!f) throw new Error('Feedback non trovato'); remove_('Feedback', [f]); return { deleted: true }; } /* ============================================================ * NOTE & FOTO (admin + staff) * ============================================================ */ function memberOf_(eventId, u) { return find_('Staff', function (x) { return x.eventId === eventId && x.email && x.email === u.email; }); } function noteAdd_(p, u) { const e = find_('Events', function (x) { return x.id === p.eventId; }); if (!e) throw new Error('Evento non trovato'); const text = cleanML_(p.text, 2000); if (!text) throw new Error('Scrivi il testo della nota'); let staffId = clean_(p.staffId, 40); if (u.role !== 'admin') { const s = memberOf_(e.id, u); if (!s) throw new Error('Non fai parte dello staff di questo evento'); staffId = s.id; } const kind = p.kind === 'segnalazione' ? 'segnalazione' : 'nota'; const n = insert_('Notes', { eventId: e.id, staffId: staffId, userId: u.id, author: u.name, authorRole: u.role, kind: kind, text: text, createdAt: now_() }); if (u.role !== 'admin' && kind === 'segnalazione') { notifyAdmin_('⚠️ Segnalazione urgente · ' + e.name, '

' + esc_(u.name) + ' ha inviato una segnalazione urgente per ' + esc_(e.name) + ':

' + '

' + esc_(text).replace(/\n/g, '
') + '

' + '

' + now_() + '

'); } return { note: pick_(n) }; } function noteDelete_(p) { const n = find_('Notes', function (x) { return x.id === p.id; }); if (!n) throw new Error('Nota non trovata'); remove_('Notes', [n]); return { deleted: true }; } function eventFolder_(e) { if (e.folderId) { try { return DriveApp.getFolderById(e.folderId); } catch (err) {} } let root = null; const rid = cfg_('PHOTO_FOLDER_ID'); if (rid) { try { root = DriveApp.getFolderById(rid); } catch (err) {} } if (!root) { root = DriveApp.createFolder(APP.NAME + ' — Foto eventi'); setCfg_('PHOTO_FOLDER_ID', root.getId()); } const f = root.createFolder(e.dateStart + ' · ' + e.name); try { f.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW); } catch (err) {} update_('Events', e, { folderId: f.getId() }); return f; } function photoUpload_(p, u) { const e = find_('Events', function (x) { return x.id === p.eventId; }); if (!e) throw new Error('Evento non trovato'); let staffId = clean_(p.staffId, 40); if (u.role !== 'admin') { const s = memberOf_(e.id, u); if (!s) throw new Error('Non fai parte dello staff di questo evento'); staffId = s.id; } if (!p.data) throw new Error('Foto mancante'); const bytes = Utilities.base64Decode(String(p.data)); if (bytes.length > APP.MAX_PHOTO_MB * 1024 * 1024) throw new Error('Foto troppo grande'); const mime = /^image\/(jpeg|png|webp)$/.test(p.mime || '') ? p.mime : 'image/jpeg'; const ext = mime.split('/')[1].replace('jpeg', 'jpg'); const stamp = Utilities.formatDate(new Date(), APP.TZ, 'yyyyMMdd-HHmmss'); const fname = stamp + '_' + u.name.replace(/[^\w\- ]+/g, '').replace(/\s+/g, '-') + '.' + ext; const file = eventFolder_(e).createFile(Utilities.newBlob(bytes, mime, fname)); try { file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW); } catch (err) {} const caption = clean_(p.caption, 300); if (caption) file.setDescription(caption); const ph = insert_('Photos', { eventId: e.id, staffId: staffId, userId: u.id, author: u.name, fileId: file.getId(), caption: caption, createdAt: now_() }); return { photo: photoOut_(ph) }; } function photoDelete_(p, u) { const ph = find_('Photos', function (x) { return x.id === p.id; }); if (!ph) throw new Error('Foto non trovata'); if (u.role !== 'admin' && ph.userId !== u.id) throw new Error('Permesso negato'); try { DriveApp.getFileById(ph.fileId).setTrashed(true); } catch (err) {} remove_('Photos', [ph]); return { deleted: true }; } /* ============================================================ * UTENTI (admin) * ============================================================ */ function usersList_() { return { users: all_('Users').map(function (u) { return Object.assign(pubUser_(u), { active: u.active !== 'no', createdAt: u.createdAt, lastLogin: u.lastLogin }); }).sort(function (a, b) { return a.name.localeCompare(b.name); }) }; } function usersSave_(p, me) { const u = find_('Users', function (x) { return x.id === p.id; }); if (!u) throw new Error('Utente non trovato'); const patch = {}; if (p.role !== undefined) { if (['admin', 'hostess'].indexOf(p.role) < 0) throw new Error('Ruolo non valido'); if (u.id === me.id && p.role !== 'admin') throw new Error('Non puoi togliere a te stesso il ruolo admin'); if (p.role !== 'admin' && isAdminEmail_(u.email)) throw new Error('Questa email è nella lista ADMIN_EMAILS del foglio Config: rimuovila da lì'); patch.role = p.role; } if (p.active !== undefined) { if (u.id === me.id && !p.active) throw new Error('Non puoi disattivare il tuo account'); patch.active = p.active ? 'si' : 'no'; } update_('Users', u, patch); return { user: pubUser_(u) }; } /* ============================================================ * AREA STAFF (hostess) * ============================================================ */ function myEvents_(p, u) { const today = today_(); const mine = filter_('Staff', function (s) { return s.email && s.email === u.email; }); const evs = all_('Events'); const att = all_('Attendance'); const items = mine.map(function (s) { const e = evs.find(function (x) { return x.id === s.eventId; }); if (!e) return null; const a = att.find(function (x) { return x.staffId === s.id && x.date === today; }); return { staff: pick_(s), event: pick_(e), todayAtt: a ? pick_(a) : null }; }).filter(Boolean); return { today: today, items: items }; } function myCtx_(staffId, u) { const s = find_('Staff', function (x) { return x.id === staffId; }); if (!s || !s.email || s.email !== u.email) throw new Error('Evento non trovato'); const e = find_('Events', function (x) { return x.id === s.eventId; }); if (!e) throw new Error('Evento non trovato'); return { s: s, e: e }; } function myEvent_(p, u) { const c = myCtx_(p.staffId, u); const s = c.s, e = c.e; return { event: pick_(e), staff: pick_(s), days: daysOf_(e), today: today_(), now: now_(), attendance: filter_('Attendance', function (x) { return x.staffId === s.id; }).map(pick_), breaks: filter_('Breaks', function (x) { return x.staffId === s.id; }).map(pick_), photos: filter_('Photos', function (x) { return x.eventId === e.id && (x.staffId === s.id || x.userId === u.id); }).sort(desc_('createdAt')).map(photoOut_), notes: filter_('Notes', function (x) { return x.eventId === e.id && x.userId === u.id; }).map(pick_).sort(desc_('createdAt')) }; } /** Arrivo segnato dalla hostess: SOLO in tempo reale, orario non modificabile (le correzioni le fa l'admin) */ function myCheckin_(p, u) { const c = myCtx_(p.staffId, u); if (!canSelfCheckin_(c.e)) throw new Error('Per questo evento arrivo e fine turno li registra l\'agenzia'); const date = today_(); if (daysOf_(c.e).indexOf(date) < 0) throw new Error('Puoi segnare l\'arrivo solo il giorno dell\'evento'); const a = find_('Attendance', function (x) { return x.staffId === c.s.id && x.date === date; }); if (a && a.arrivalAt && (a.status === 'presente' || a.status === 'uscito')) { throw new Error('Arrivo già registrato alle ' + a.arrivalAt.slice(11) + '. Per correzioni contatta l\'agenzia'); } const patch = { status: 'presente', arrivalAt: now_(), arrivalBy: 'staff', exitAt: '' }; if (p.lat && p.lng) { patch.lat = String(Number(p.lat).toFixed(5)); patch.lng = String(Number(p.lng).toFixed(5)); } return { att: attUpsert_(c.s, date, patch, u.name) }; } /** Fine turno segnata dalla hostess: SOLO in tempo reale, una volta sola */ function myCheckout_(p, u) { const c = myCtx_(p.staffId, u); if (!canSelfCheckin_(c.e)) throw new Error('Per questo evento arrivo e fine turno li registra l\'agenzia'); const date = today_(); const a = find_('Attendance', function (x) { return x.staffId === c.s.id && x.date === date; }); if (!a || !a.arrivalAt || a.status === 'attesa' || a.status === 'assente') throw new Error('Segna prima il tuo arrivo'); if (a.status === 'uscito') throw new Error('Fine turno già registrata. Per correzioni contatta l\'agenzia'); closeOpenBreak_(c.s, date); return { att: attUpsert_(c.s, date, { status: 'uscito', exitAt: now_() }, u.name) }; } function esc_(s) { return String(s === null || s === undefined ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; }); } /* ============================================================ * MODULO CONTATTI DEL SITO (staffnow.checkfast.it) * ============================================================ */ function leadCreate_(p) { if (p.website) return { ok: true }; // honeypot anti-spam const name = clean_(p.name, 80); const email = normEmail_(p.email); if (!name) throw new Error('Inserisci nome e cognome'); if (!validEmail_(email)) throw new Error('Inserisci un indirizzo email valido'); if (!p.privacy) throw new Error('Per inviare la richiesta accetta l\'informativa privacy'); const cache = CacheService.getScriptCache(); if (cache.get('lead_' + email)) throw new Error('Richiesta già ricevuta: ti risponderemo a breve'); cache.put('lead_' + email, '1', 120); const lead = insert_('Leads', { createdAt: now_(), name: name, company: clean_(p.company, 120), email: email, phone: clean_(p.phone, 30), plan: clean_(p.plan, 40), message: cleanML_(p.message, 3000), source: clean_(p.source, 80), status: 'nuovo' }); notifyAdmin_('Nuova richiesta Staff NOW: ' + name + (lead.company ? ' (' + lead.company + ')' : '') + ' · ' + (lead.plan || '-'), '

' + esc_(name) + '' + (lead.company ? ' · ' + esc_(lead.company) : '') + '

' + '

Email: ' + esc_(email) + '
Telefono: ' + esc_(lead.phone || '-') + '
Pacchetto: ' + esc_(lead.plan || '-') + '

' + (lead.message ? '

' + esc_(lead.message) + '

' : '') + '

Gestisci la richiesta dalla pagina Richieste dell\'app.

', email); return { ok: true }; } function leadsList_() { return { leads: all_('Leads').map(pick_).sort(desc_('createdAt')) }; } function leadsSave_(p) { const l = find_('Leads', function (x) { return x.id === p.id; }); if (!l) throw new Error('Richiesta non trovata'); update_('Leads', l, { status: ['nuovo', 'contattato', 'chiuso'].indexOf(p.status) >= 0 ? p.status : 'nuovo' }); return { lead: pick_(l) }; } /* ============================================================ * PASSWORD DIMENTICATA (senza email) * L'admin genera un codice e lo manda alla persona su WhatsApp. * ============================================================ */ function usersResetCode_(p) { const u = find_('Users', function (x) { return x.id === p.id; }); if (!u) throw new Error('Utente non trovato'); const code = String(Math.floor(100000 + Math.random() * 900000)); update_('Users', u, { resetCode: code, resetExp: String(Date.now() + 24 * 3600 * 1000) }); let phone = u.phone; if (!phone) { const st = find_('Staff', function (x) { return x.email === u.email && x.phone; }); if (st) phone = st.phone; } return { code: code, name: u.name, email: u.email, phone: phone || '', appUrl: cfg_('APP_URL') }; } /** Pausa gestita dalla hostess (se autorizzata dall'agenzia): avvia o termina */ function myBreak_(p, u) { const c = myCtx_(p.staffId, u); if (!canSelfBreaks_(c.e)) throw new Error('Per questo evento le pause le registra l\'agenzia'); const date = today_(); if (daysOf_(c.e).indexOf(date) < 0) throw new Error('L\'evento non è in programma oggi'); const open = find_('Breaks', function (x) { return x.staffId === c.s.id && x.date === date && !x.endAt; }); if (open) { update_('Breaks', open, { endAt: now_() }); return { break: pick_(open), running: false }; } const a = find_('Attendance', function (x) { return x.staffId === c.s.id && x.date === date; }); if (!a || a.status !== 'presente') throw new Error(a && a.status === 'uscito' ? 'Il turno è già concluso' : 'Segna prima il tuo arrivo'); const b = insert_('Breaks', { staffId: c.s.id, eventId: c.s.eventId, date: date, startAt: now_(), endAt: '', by: u.name + ' (app)' }); return { break: pick_(b), running: true }; } /* ============================================================ * AVVISI AMMINISTRATIVI (pochi, solo verso l'agenzia) * Mittente: staffnow@checkfast.it se configurato come "Invia messaggi come" * nel Gmail del progetto; altrimenti l'indirizzo Gmail predefinito. * ============================================================ */ function notifyAdmin_(subject, html, replyTo) { const to = cfg_('NOTIFY_EMAIL') || 'staffnow@checkfast.it'; const from = cfg_('NOTIFY_FROM') || 'staffnow@checkfast.it'; try { const opts = { htmlBody: '
' + html + '
', name: APP.NAME }; if (replyTo) opts.replyTo = replyTo; if (GmailApp.getAliases().indexOf(from) >= 0) opts.from = from; GmailApp.sendEmail(to, subject, '', opts); } catch (e) { /* l'avviso è facoltativo: il dato resta comunque nel foglio */ } } /** Esegui una volta per verificare gli avvisi (manda un'email di prova) */ function testAvvisi() { notifyAdmin_('Staff NOW · prova avvisi', '

Se leggi questa email, gli avvisi amministrativi di Staff NOW funzionano.

'); } /* ---------- adattamenti demo ---------- */ photoOut_ = function(ph){ const o=pick_(ph); const u=files[ph.fileId]||''; o.thumb=u; o.full=u; o.link='#'; return o; }; function save(){ LS.set(DBK,JSON.stringify(store)); try{LS.set(FK,JSON.stringify(files))}catch(e){} } function call(req){ for(const k in _T) delete _T[k]; const r=handle_(req); save(); return r; } function seed(){ store={}; files={}; for(const k in _T) delete _T[k]; for(const k in cache) delete cache[k]; setup(); const T=today_(), d=(n)=>Utilities.formatDate(new Date(Date.now()+n*864e5),'Europe/Rome','yyyy-MM-dd'); const A=call({action:'auth.register',p:{name:'Agenzia With You',email:'agenzia@demo.it',password:'demo123',phone:'080 1234567'}}).data.token; const ev=call({action:'events.save',token:A,p:{name:'Lancio Nuova Collezione',client:'Brand Moda Srl',location:'Fiera del Levante, Pad. 9',address:'Lungomare Starita, Bari',dateStart:T,dateEnd:d(1),timeStart:'09:00',timeEnd:'18:00',breaks:'13:00–13:45 pranzo · 2 pause da 15 min',staffCount:'8',selfCheckin:'si',selfBreaks:'si',notes:'Dress code: total black, scarpe comode.\nReferente in loco: Marco (347 0000000).\nRitrovo all\'ingresso staff 15 minuti prima del turno.'}}).data.event; call({action:'events.save',token:A,p:{name:'Convention Farmaceutica',client:'Pharma Group',location:'Hotel Excelsior',address:'Bari',dateStart:d(6),dateEnd:d(6),timeStart:'08:30',timeEnd:'17:30',staffCount:'4'}}); const old=call({action:'events.save',token:A,p:{name:'Inaugurazione Showroom',client:'Auto Puglia',location:'Showroom Modugno',dateStart:d(-9),dateEnd:d(-9),timeStart:'18:00',timeEnd:'23:00',staffCount:'3'}}).data.event; call({action:'staff.save',token:A,p:{eventId:ev.id,list:[ {name:'Giulia Rossi',email:'giulia@demo.it',phone:'333 1234567',role:'Hostess accoglienza'}, {name:'Sara Neri',email:'sara@demo.it',phone:'340 2223344',role:'Hostess accoglienza'}, {name:'Martina Greco',email:'martina@demo.it',phone:'349 5556677',role:'Hostess guardaroba'}, {name:'Luca Verdi',email:'luca@demo.it',phone:'328 8889900',role:'Team leader',timeStart:'08:30',timeEnd:'18:30'}, {name:'Francesca Lupo',email:'francesca@demo.it',phone:'347 1112233',role:'Promoter'}, {name:'Davide Ferri',phone:'393 4445566',role:'Steward'}, {name:'Chiara Bianco',email:'chiara@demo.it',role:'Promoter',timeStart:'13:00',timeEnd:'20:00'}]}}); call({action:'staff.save',token:A,p:{eventId:old.id,list:[{name:'Giulia Rossi',email:'giulia@demo.it',role:'Hostess'},{name:'Sara Neri',email:'sara@demo.it',role:'Hostess'}]}}); for(const k in _T) delete _T[k]; const st=all_('Staff').filter(s=>s.eventId===ev.id), by=n=>st.find(s=>s.name===n).id; call({action:'att.set',token:A,p:{staffId:by('Luca Verdi'),date:T,arrivalTime:'08:22'}}); call({action:'att.set',token:A,p:{staffId:by('Sara Neri'),date:T,arrivalTime:'08:51'}}); call({action:'att.set',token:A,p:{staffId:by('Martina Greco'),date:T,arrivalTime:'09:18'}}); call({action:'att.set',token:A,p:{staffId:by('Francesca Lupo'),date:T,arrivalTime:'08:47'}}); call({action:'att.set',token:A,p:{staffId:by('Davide Ferri'),date:T,status:'assente'}}); call({action:'break.save',token:A,p:{staffId:by('Sara Neri'),date:T,start:'11:00',end:'11:15'}}); call({action:'feedback.add',token:A,p:{staffId:by('Luca Verdi'),rating:5,text:'Ottima gestione del team, sempre in anticipo.'}}); call({action:'note.add',token:A,p:{eventId:ev.id,text:'Consegnati 40 badge e 2 radio al team leader.'}}); const So=call({action:'auth.register',p:{name:'Sara Neri',email:'sara@demo.it',password:'demo123'}}).data.token; call({action:'note.add',token:So,p:{eventId:ev.id,kind:'segnalazione',text:'All\'ingresso B mancano i braccialetti VIP, ne servono almeno 50.'}}); call({action:'auth.register',p:{name:'Giulia Rossi',email:'giulia@demo.it',password:'demo123',phone:'333 1234567'}}); for(const k in _T) delete _T[k]; call({action:'auth.logout',token:A}); call({action:'auth.logout',token:So}); // la sessione di Giulia creata dalla registrazione non serve store.Sessions=[store.Sessions[0]]; for(const k in cache) delete cache[k]; mails.length=0; save(); } if(!store.Users || !store.Config) seed(); return { api(body){ return new Promise(res=>setTimeout(()=>{ const n=mails.length; const r=call(body); const sent=mails.slice(n); if(sent.length) setTimeout(()=>toast('📧 Demo: '+(sent.length===1?'email simulata a '+sent[0].to:sent.length+' email simulate (invio reale da agenziawithyou@gmail.com)')),2700); res(JSON.parse(JSON.stringify(r))); },180)); }, reset(){ seed(); } }; })(); window.DEMO_API = b=>window.DEMO.api(b);