Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XGaEeUbVSdKNfpFRgWfCXa
1010 lines
78 KiB
JavaScript
1010 lines
78 KiB
JavaScript
/* Courrier : interface v1 (lecture seule). Tout le texte passe par textContent, aucun balisage injecté. */
|
||
(function () {
|
||
'use strict';
|
||
var TZ = 'Africa/Tunis';
|
||
var API = '/api/v1';
|
||
var NS = 'http://www.w3.org/2000/svg';
|
||
|
||
var ICONES = {
|
||
tri: 'M22 12h-6l-2 3h-4l-2-3H2|M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z',
|
||
categories: 'M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z|M7.5 7.5h.01',
|
||
regles: 'M3 6h18|M7 12h10|M10 18h4',
|
||
recherche: 'm21 21-4.34-4.34|M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16',
|
||
courses: 'M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z|M12 13a3 3 0 1 0 0-6 3 3 0 0 0 0 6',
|
||
suivi: 'M12 6v6l4 2|M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0',
|
||
asuivre: 'm19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z',
|
||
pj: 'm21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48',
|
||
groupes: 'M3 7h7v7H3z|M14 7h7v7h-7z|M3 17h18',
|
||
telecharger: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4|m7 10 5 5 5-5|M12 15V3', fermer: 'M18 6 6 18|m6 6 12 12', gauche: 'm15 18-6-6 6-6', droite: 'm9 18 6-6-6-6', bas: 'm6 9 6 6 6-6', fleche: 'M5 12h14|m12 5 7 7-7 7'
|
||
};
|
||
var NAV = [
|
||
['tri', 'Tri du jour', true], ['asuivre', 'À suivre', true], ['categories', 'Catégories', true], ['groupes', 'Groupes', true], ['recherche', 'Recherche', true], ['courses', 'Courses pour Tunis', true], ['suivi', 'Suivi des demandes', true], ['regles', 'Règles', true]
|
||
];
|
||
var BIENTOT = {};
|
||
var COULEUR_NOM = { 'Tunis': 1, 'Demande FB': 2, 'CI': 3, 'Câbles': 4, 'Sans objet': 5, 'À classer': 0 };
|
||
var SYSTEME = 'À classer';
|
||
|
||
var S = { chargeA: 0, chargeJour: '', vue: 'tri', jour: auj(), filtre: null, cats: [], mails: [], etat: 'chargement', banniere: null, notif: null, regles: [], reglesEtat: 'ok', miroirErreur: false, majHeure: '', groupe: { jours: 7, cat: null, etq: null, mails: [], etat: 'chargement' }, courses: { liste: [], filtre: 'a_faire', etat: 'chargement' }, asuivre: { items: [], compte: { actif: 0, termine: 0 }, filtre: 'actif', etat: 'chargement', annuler: null }, suivreSet: {}, suivi: { items: [], jours: 14, filtre: 'attente', compte: {}, etat: 'chargement' }, recherche: { q: '', periode: 'tout', avecPj: false, etat: 'repos', resultats: [], plafond: false, cherche: '' } };
|
||
|
||
/* ---------- Utilitaires ---------- */
|
||
function auj() { return new Intl.DateTimeFormat('en-CA', { timeZone: TZ }).format(new Date()); }
|
||
function d2(n) { return (n < 10 ? '0' : '') + n; }
|
||
function dateUTC(s) { var p = s.split('-'); return new Date(Date.UTC(+p[0], +p[1] - 1, +p[2], 12)); }
|
||
function versISO(d) { return d.getUTCFullYear() + '-' + d2(d.getUTCMonth() + 1) + '-' + d2(d.getUTCDate()); }
|
||
function fr(s) { var p = s.split('-'); return p[2] + '/' + p[1] + '/' + p[0]; }
|
||
function nomJour(s) { var n = new Intl.DateTimeFormat('fr-FR', { weekday: 'long', timeZone: 'UTC' }).format(dateUTC(s)); return n.charAt(0).toUpperCase() + n.slice(1); }
|
||
function heureTunis(v) {
|
||
if (!v) return '--:--';
|
||
var d = new Date(v);
|
||
if (isNaN(d.getTime())) { var m = String(v).match(/(\d{2}):(\d{2})/); return m ? m[1] + ':' + m[2] : '--:--'; }
|
||
return new Intl.DateTimeFormat('fr-FR', { hour: '2-digit', minute: '2-digit', hour12: false, timeZone: TZ }).format(d);
|
||
}
|
||
function couleur(nom, id) {
|
||
/* Chaque catégorie a sa couleur, enregistrée avec elle (jamais deux catégories sur la même teinte). */
|
||
var cat = S.cats.find(function (x) { return x.nom === nom; });
|
||
if (cat && typeof cat.couleur === 'number') return cat.couleur;
|
||
if (Object.prototype.hasOwnProperty.call(COULEUR_NOM, nom)) return COULEUR_NOM[nom];
|
||
return 6 + ((id || 0) % 3);
|
||
}
|
||
function h(tag, attrs) {
|
||
var el = document.createElement(tag);
|
||
if (attrs) for (var k in attrs) {
|
||
var v = attrs[k];
|
||
if (v === null || v === undefined || v === false) continue;
|
||
if (k === 'class') el.className = v;
|
||
else if (k === 'text') el.textContent = v;
|
||
else if (k.slice(0, 2) === 'on') el.addEventListener(k.slice(2), v);
|
||
else el.setAttribute(k, v === true ? '' : v);
|
||
}
|
||
for (var i = 2; i < arguments.length; i++) {
|
||
var c = arguments[i];
|
||
if (c === null || c === undefined || c === false) continue;
|
||
el.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
|
||
}
|
||
return el;
|
||
}
|
||
function icone(cle, taille) {
|
||
var svg = document.createElementNS(NS, 'svg');
|
||
svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('fill', 'none'); svg.setAttribute('stroke', 'currentColor');
|
||
svg.setAttribute('stroke-width', '2'); svg.setAttribute('stroke-linecap', 'round'); svg.setAttribute('stroke-linejoin', 'round');
|
||
svg.setAttribute('aria-hidden', 'true');
|
||
if (taille) { svg.setAttribute('width', taille); svg.setAttribute('height', taille); }
|
||
ICONES[cle].split('|').forEach(function (d) { var p = document.createElementNS(NS, 'path'); p.setAttribute('d', d); svg.appendChild(p); });
|
||
return svg;
|
||
}
|
||
function pastille(c, extra) { return h('span', { class: 'pt c' + c + (extra ? ' ' + extra : ''), 'aria-hidden': 'true' }); }
|
||
function annoncer(t) { var a = document.getElementById('annonce'); a.textContent = ''; setTimeout(function () { a.textContent = t; }, 30); }
|
||
|
||
/* ---------- API ---------- */
|
||
function api(chemin, opts) {
|
||
opts = opts || {};
|
||
var init = { method: opts.method || 'GET', credentials: 'same-origin', redirect: 'manual', headers: { 'Accept': 'application/json' } };
|
||
if (opts.body !== undefined) { init.headers['Content-Type'] = 'application/json'; init.body = JSON.stringify(opts.body); }
|
||
return fetch(API + chemin, init).then(function (r) {
|
||
if (r.type === 'opaqueredirect' || r.status === 401 || r.status === 403) { sessionExpiree(); throw new Error('session'); }
|
||
if (!r.ok) throw new Error('http ' + r.status);
|
||
var ct = r.headers.get('content-type') || '';
|
||
if (ct.indexOf('application/json') === -1) { sessionExpiree(); throw new Error('session'); }
|
||
return r.json();
|
||
});
|
||
}
|
||
|
||
/* ---------- Données ---------- */
|
||
function nomExp(brut) {
|
||
var x = String(brut || '').match(/^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/);
|
||
if (!x) return brut || '(expéditeur inconnu)';
|
||
return x[1].trim() || x[2];
|
||
}
|
||
function normaliser(m) {
|
||
var c = m.classement || m;
|
||
var cat = c.categorie || SYSTEME;
|
||
return {
|
||
id: m.message_id, exp: nomExp(m.expediteur || c.expediteur || ''), expBrut: m.expediteur || c.expediteur || '', objet: m.objet || c.objet || '',
|
||
date: m.date || c.date_mail || '', cat: cat, source: c.source || 'regle', traite: !!c.traite, etiquettes: m.etiquettes || []
|
||
};
|
||
}
|
||
function chargerCats() {
|
||
return api('/categories').then(function (r) {
|
||
var l = (r.categories || []).map(function (c) { return { id: c.id, nom: c.name, couleur: c.couleur }; });
|
||
l.sort(function (a, b) { return (a.nom === SYSTEME) - (b.nom === SYSTEME) || a.id - b.id; });
|
||
S.cats = l;
|
||
});
|
||
}
|
||
function chargerMails() {
|
||
S.etat = 'chargement'; S.miroirErreur = false; rendre();
|
||
var jour = S.jour;
|
||
return Promise.all([chargerCats(), api('/mails?date=' + jour + '&n=200')]).then(function (rs) {
|
||
if (jour !== S.jour) return;
|
||
var r = rs[1];
|
||
S.miroirErreur = !!r.miroir_erreur;
|
||
S.mails = (r.mails || []).map(normaliser).sort(function (a, b) { return String(b.date).localeCompare(String(a.date)); });
|
||
S.etat = 'ok'; S.majHeure = heureTunis(new Date().toISOString()); S.chargeA = Date.now(); S.chargeJour = jour;
|
||
rendre();
|
||
}).catch(function (e) { if (e.message === 'session') return; if (jour !== S.jour) return; S.etat = 'erreur'; rendre(); });
|
||
}
|
||
function chargerGroupe() {
|
||
var G = S.groupe, jours = G.jours;
|
||
G.etat = 'chargement'; rendre();
|
||
return Promise.all([chargerCats(), api('/mails/periode?jours=' + jours)]).then(function (rs) {
|
||
if (jours !== G.jours) return;
|
||
G.mails = (rs[1].mails || []).map(normaliser).sort(function (a, b) { return String(b.date).localeCompare(String(a.date)); });
|
||
G.miroirErreur = !!rs[1].miroir_erreur; G.etat = 'ok'; rendre();
|
||
}).catch(function (e) { if (e.message === 'session') return; if (jours !== G.jours) return; G.etat = 'erreur'; rendre(); });
|
||
}
|
||
function chargerRegles() {
|
||
S.reglesEtat = 'chargement'; rendre();
|
||
return Promise.all([chargerCats(), api('/regles')]).then(function (rs) {
|
||
S.regles = rs[1].regles || []; S.reglesEtat = 'ok'; rendre();
|
||
}).catch(function (e) { if (e.message === 'session') return; S.reglesEtat = 'erreur'; rendre(); });
|
||
}
|
||
|
||
/* ---------- Actions ---------- */
|
||
function flash(t) { S.notif = t; rendre(); annoncer(t); clearTimeout(flash.t); flash.t = setTimeout(function () { S.notif = null; rendre(); }, 5000); }
|
||
function changerJour(delta) {
|
||
var d = dateUTC(S.jour); d.setUTCDate(d.getUTCDate() + delta); var j = versISO(d);
|
||
if (j > auj()) return;
|
||
S.jour = j; S.filtre = null; S.banniere = null; chargerMails(); annoncer(nomJour(j) + ' ' + fr(j));
|
||
}
|
||
function allerA(vue) {
|
||
S.vue = vue; S.banniere = null;
|
||
if (vue === 'tri' || vue === 'categories') {
|
||
if (S.etat === 'ok' && S.chargeJour === S.jour && Date.now() - S.chargeA < 30000) rendre(); else chargerMails();
|
||
}
|
||
else if (vue === 'groupes') chargerGroupe();
|
||
else if (vue === 'regles') chargerRegles();
|
||
else if (vue === 'courses') chargerCourses();
|
||
else if (vue === 'suivi') chargerSuivi();
|
||
else if (vue === 'asuivre') chargerASuivre();
|
||
else if (vue === 'recherche') { rendre(); var ch = document.getElementById('rech-q'); if (ch) ch.focus(); return; }
|
||
else rendre();
|
||
document.getElementById('principal').focus();
|
||
}
|
||
function basculerTraite(m, val) {
|
||
var avant = m.traite; m.traite = val; rendre();
|
||
api('/classements/' + encodeURIComponent(m.id) + '/traite', { method: 'PATCH', body: { traite: val } }).catch(function (e) {
|
||
if (e.message === 'session') return; m.traite = avant; rendre(); flash('Impossible d\'enregistrer le statut « traité ». Réessayez.');
|
||
});
|
||
}
|
||
function corriger(m, cat) {
|
||
var avant = { cat: m.cat, source: m.source };
|
||
m.cat = cat; m.source = 'manuel'; S.banniere = null; rendre();
|
||
api('/classements/' + encodeURIComponent(m.id), { method: 'POST', body: { categorie: cat, mail_info: { message_id: m.id, expediteur: m.expBrut || m.exp, objet: m.objet, date: m.date, etiquettes: m.etiquettes } } })
|
||
.then(function (r) {
|
||
var rp = r.regle_proposee;
|
||
if (rp && rp.id) {
|
||
var autres = (S.vue === 'groupes' ? S.groupe.mails : S.mails).filter(function (x) { return x.exp === m.exp && x.id !== m.id && x.source !== 'manuel' && x.cat !== cat; }).length;
|
||
S.banniere = { id: rp.id, exp: m.exp, cat: cat, autres: autres }; rendre();
|
||
}
|
||
}).catch(function (e) { if (e.message === 'session') return; m.cat = avant.cat; m.source = avant.source; rendre(); flash('La correction n\'a pas été enregistrée. Réessayez.'); });
|
||
}
|
||
function confirmerRegle() {
|
||
var b = S.banniere; if (!b) return;
|
||
api('/regles/' + b.id + '/confirmer', { method: 'POST' }).then(function () { S.banniere = null; flash('Règle créée : ' + b.exp + ' → ' + b.cat + '.'); return chargerMails(); })
|
||
.catch(function (e) { if (e.message !== 'session') flash('La règle n\'a pas pu être créée. Réessayez.'); });
|
||
}
|
||
function ignorerRegle() {
|
||
var b = S.banniere; S.banniere = null; rendre();
|
||
if (b) api('/regles/' + b.id, { method: 'DELETE' }).catch(function () {});
|
||
}
|
||
function basculerRegle(r) {
|
||
var req = r.statut === 'active' ? api('/regles/' + r.id, { method: 'PUT', body: { statut: 'proposee' } }) : api('/regles/' + r.id + '/confirmer', { method: 'POST' });
|
||
req.then(function () { return chargerRegles(); }).then(function () { annoncer(r.statut === 'active' ? 'Règle désactivée' : 'Règle activée'); })
|
||
.catch(function (e) { if (e.message !== 'session') flash('La règle n\'a pas pu être modifiée. Réessayez.'); });
|
||
}
|
||
|
||
/* ---------- Dialogues ---------- */
|
||
var dialogue = null;
|
||
function ouvrir(construire) {
|
||
fermer(true);
|
||
var retour = document.activeElement;
|
||
var voile = h('div', { class: 'voile leger' });
|
||
var boite = construire(function () { fermer(); });
|
||
voile.appendChild(boite);
|
||
document.getElementById('calque').appendChild(voile);
|
||
document.getElementById('app').setAttribute('inert', '');
|
||
dialogue = { voile: voile, retour: retour, etiquette: retour && retour.getAttribute ? retour.getAttribute('aria-label') : null };
|
||
var premier = boite.querySelector('[data-focus]') || boite.querySelector('input,button');
|
||
if (premier) premier.focus();
|
||
voile.addEventListener('keydown', function (e) {
|
||
if (e.key === 'Escape') { e.preventDefault(); fermer(); return; }
|
||
if (e.key === 'Tab') {
|
||
var f = boite.querySelectorAll('button:not([hidden]),input,select,[href],summary,[tabindex="0"]'); if (!f.length) return;
|
||
var a = f[0], z = f[f.length - 1];
|
||
if (e.shiftKey && document.activeElement === a) { e.preventDefault(); z.focus(); }
|
||
else if (!e.shiftKey && document.activeElement === z) { e.preventDefault(); a.focus(); }
|
||
}
|
||
});
|
||
return boite;
|
||
}
|
||
function fermer(sansRetour) {
|
||
if (!dialogue) return;
|
||
dialogue.voile.remove(); document.getElementById('app').removeAttribute('inert');
|
||
var r = dialogue.retour, et = dialogue.etiquette; dialogue = null;
|
||
if (sansRetour) return;
|
||
if (r && !document.body.contains(r) && et) r = document.querySelector('[aria-label="' + et.replace(/"/g, '\\"') + '"]');
|
||
if (r && document.body.contains(r)) r.focus();
|
||
}
|
||
function dialogueCategorie(cat) {
|
||
var nouveau = !cat, systeme = cat && cat.nom === SYSTEME;
|
||
ouvrir(function (clore) {
|
||
var champ = h('input', { id: 'cat-nom', type: 'text', maxlength: '100', 'data-focus': '', autocomplete: 'off', value: cat ? cat.nom : '' });
|
||
if (systeme) { champ.setAttribute('readonly', ''); }
|
||
var err = h('div', { class: 'err', role: 'alert' });
|
||
function enregistrer() {
|
||
var nom = champ.value.trim();
|
||
if (!nom) { err.textContent = 'Saisissez un nom de catégorie.'; champ.focus(); return; }
|
||
if (S.cats.some(function (c) { return c.nom.toLowerCase() === nom.toLowerCase() && (!cat || c.id !== cat.id); })) { err.textContent = 'Cette catégorie existe déjà.'; champ.focus(); return; }
|
||
var req = nouveau ? api('/categories', { method: 'POST', body: { name: nom } }) : api('/categories/' + cat.id, { method: 'PUT', body: { name: nom } });
|
||
req.then(function () { clore(); return chargerMails(); }).then(function () { flash(nouveau ? 'Catégorie ajoutée.' : 'Catégorie renommée.'); })
|
||
.catch(function (e) { if (e.message !== 'session') err.textContent = 'Enregistrement impossible. Réessayez.'; });
|
||
}
|
||
champ.addEventListener('keydown', function (e) { if (e.key === 'Enter' && !systeme) { e.preventDefault(); enregistrer(); } });
|
||
var acts = h('div', { class: 'acts' }, h('button', { type: 'button', class: 'btn-ligne', onclick: clore }, 'Annuler'),
|
||
systeme ? null : h('button', { type: 'button', class: 'btn-plein', onclick: enregistrer }, nouveau ? 'Ajouter' : 'Enregistrer'));
|
||
var pied = null;
|
||
if (cat && !systeme) pied = h('div', { class: 'pave' }, h('button', { type: 'button', class: 'btn-danger-ligne', onclick: function () { clore(); dialogueSuppression(cat); } }, 'Supprimer la catégorie'));
|
||
return h('section', { class: 'boite', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'dlg-t' },
|
||
h('h2', { id: 'dlg-t' }, nouveau ? 'Nouvelle catégorie' : systeme ? SYSTEME : 'Modifier la catégorie'),
|
||
systeme ? h('p', null, '« À classer » reçoit les mails qu\'aucune règle ne reconnaît. Elle ne peut être ni renommée ni supprimée.') : null,
|
||
h('div', { class: 'champ' }, h('label', { for: 'cat-nom' }, 'Nom'), champ, err), acts, pied);
|
||
});
|
||
}
|
||
function dialogueSuppression(cat) {
|
||
ouvrir(function (clore) {
|
||
var err = h('div', { class: 'err', role: 'alert' });
|
||
return h('section', { class: 'boite', role: 'alertdialog', 'aria-modal': 'true', 'aria-labelledby': 'sup-t', 'aria-describedby': 'sup-p' },
|
||
h('h2', { id: 'sup-t' }, 'Supprimer « ' + cat.nom + ' » ?'),
|
||
h('p', { id: 'sup-p' }, 'La catégorie disparaît de la liste. Ses mails repassent dans « À classer » et ses règles sont supprimées. Votre messagerie n\'est pas modifiée.'),
|
||
err,
|
||
h('div', { class: 'acts' },
|
||
h('button', { type: 'button', class: 'btn-ligne', 'data-focus': '', onclick: clore }, 'Annuler'),
|
||
h('button', { type: 'button', class: 'btn-danger', onclick: function () {
|
||
api('/categories/' + cat.id, { method: 'DELETE' }).then(function () { clore(); return chargerMails(); }).then(function () { flash('Catégorie supprimée.'); })
|
||
.catch(function (e) { if (e.message !== 'session') err.textContent = 'Suppression impossible. Réessayez.'; });
|
||
} }, 'Supprimer')));
|
||
});
|
||
}
|
||
function sessionExpiree() {
|
||
if (document.getElementById('sess')) return;
|
||
fermer(true);
|
||
var btn = h('button', { type: 'button', class: 'btn-plein', id: 'sess-b', 'data-focus': '', onclick: function () { location.reload(); } }, 'Se reconnecter');
|
||
var voile = h('div', { class: 'voile', id: 'sess' }, h('section', { class: 'boite', role: 'alertdialog', 'aria-modal': 'true', 'aria-labelledby': 'sess-t' },
|
||
h('h2', { id: 'sess-t' }, 'Session expirée'),
|
||
h('p', null, 'La connexion à la messagerie a pris fin. Vos corrections et vos règles sont conservées.'), btn));
|
||
document.getElementById('calque').appendChild(voile);
|
||
document.getElementById('app').setAttribute('inert', '');
|
||
btn.focus();
|
||
voile.addEventListener('keydown', function (e) { if (e.key === 'Tab') { e.preventDefault(); btn.focus(); } });
|
||
}
|
||
|
||
/* ---------- Rendu ---------- */
|
||
function rendreNav() {
|
||
var bureau = document.getElementById('nav-bureau'), mobile = document.getElementById('nav-mobile');
|
||
bureau.textContent = ''; mobile.textContent = '';
|
||
function bouton(n) {
|
||
return h('button', { type: 'button', class: 'nav-btn', 'aria-current': S.vue === n[0] ? 'page' : null, onclick: function () { allerA(n[0]); } }, icone(n[0]), h('span', null, n[1]), n[0] === 'asuivre' && S.asuivre.compte.actif > 0 ? h('span', { class: 'nav-n', text: String(S.asuivre.compte.actif) }) : null);
|
||
}
|
||
var liste = h('div', { class: 'nav-liste' });
|
||
NAV.forEach(function (n, i) {
|
||
liste.appendChild(bouton(n));
|
||
if (n[2]) mobile.appendChild(bouton(n));
|
||
});
|
||
bureau.appendChild(h('div', { class: 'marque' }, h('b', null, 'Courrier'), h('span', null, 'Lecture seule')));
|
||
bureau.appendChild(liste);
|
||
bureau.appendChild(h('div', { class: 'pied-nyora' }, 'Nyora'));
|
||
}
|
||
function enteteJour() {
|
||
var estAuj = S.jour === auj();
|
||
return h('header', { class: 'entete' },
|
||
h('div', null, h('h1', null, 'Tri du jour'), h('div', { class: 'maj' }, estAuj ? 'Dernière mise à jour à ' + (S.majHeure || '--:--') + ' · heure de Tunis' : 'Journée close')),
|
||
h('div', { class: 'jour' },
|
||
h('button', { type: 'button', class: 'btn-icone', 'aria-label': 'Jour précédent', onclick: function () { changerJour(-1); } }, icone('gauche')),
|
||
h('div', { class: 'jour-carte' }, h('span', null, nomJour(S.jour)), h('span', { class: 'num' }, fr(S.jour))),
|
||
h('button', { type: 'button', class: 'btn-icone', 'aria-label': 'Jour suivant', disabled: estAuj, onclick: function () { changerJour(1); } }, icone('droite')),
|
||
estAuj ? null : h('button', { type: 'button', class: 'btn-lien', onclick: function () { S.jour = auj(); S.filtre = null; S.banniere = null; chargerMails(); } }, 'Aujourd\'hui')));
|
||
}
|
||
function selecteur(m) {
|
||
var c = S.cats.find(function (x) { return x.nom === m.cat; });
|
||
var sel = h('select', { 'aria-label': 'Catégorie : ' + m.exp + ', ' + (m.objet || 'sans objet'), onchange: function (e) { corriger(m, e.target.value); } });
|
||
var noms = S.cats.map(function (x) { return x.nom; });
|
||
if (noms.indexOf(m.cat) === -1) noms.push(m.cat);
|
||
noms.forEach(function (n) { var o = h('option', { value: n }, n); if (n === m.cat) o.selected = true; sel.appendChild(o); });
|
||
return h('div', { class: 'sel' }, pastille(couleur(m.cat, c && c.id)), sel, h('span', { class: 'chev' }, icone('bas')));
|
||
}
|
||
/* ---------- Lecture d'un mail (texte seul, lecture seule) ---------- */
|
||
var RUPT_FORT = /^\s*(?:-{3,}\s*(?:Original Message|Message d.origine)|Le\s.{5,140}\sa\s+écrit\s?:|On\s.{5,140}\swrote:)/i;
|
||
var RUPT_ENTETE = /^\s*(?:De|From)\s?:/i;
|
||
var SUITE_ENTETE = /^\s*(?:Envoy[ée]|Sent|Date|Objet|Subject|À|To)\s?:/i;
|
||
var URL_RE = /(https?:\/\/[^\s<>"')\]]*[^\s<>"')\].,;:!?])/g;
|
||
function debutHistorique(l) {
|
||
for (var i = 1; i < l.length; i++) {
|
||
if (RUPT_FORT.test(l[i])) return i;
|
||
if (RUPT_ENTETE.test(l[i])) { for (var k = i + 1; k <= i + 4 && k < l.length; k++) if (SUITE_ENTETE.test(l[k])) return i; }
|
||
}
|
||
return -1;
|
||
}
|
||
function avecLiens(el, ligne) {
|
||
ligne.split(URL_RE).forEach(function (t, i) {
|
||
if (!t) return;
|
||
if (i % 2 === 1) el.appendChild(h('a', { href: t, target: '_blank', rel: 'noopener noreferrer nofollow', text: t }));
|
||
else el.appendChild(document.createTextNode(t));
|
||
});
|
||
}
|
||
function blocsTexte(texte) {
|
||
var sortie = h('div', { class: 'lect-texte' }), para = [], cit = false;
|
||
function vider() {
|
||
if (!para.length) return;
|
||
var el = h(cit ? 'blockquote' : 'p');
|
||
para.forEach(function (l, i) { if (i) el.appendChild(h('br')); avecLiens(el, l); });
|
||
sortie.appendChild(el); para = [];
|
||
}
|
||
texte.split('\n').forEach(function (l) {
|
||
if (!l.trim()) { vider(); return; }
|
||
var estCit = /^\s*>/.test(l);
|
||
if (estCit !== cit) vider();
|
||
cit = estCit;
|
||
para.push(estCit ? l.replace(/^(\s*>)+\s?/, '') : l);
|
||
});
|
||
vider();
|
||
return sortie;
|
||
}
|
||
function decouperAdresses(s) { return String(s || '').split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/).map(function (x) { return x.trim(); }).filter(Boolean); }
|
||
function pastilleAdresse(a) {
|
||
var m = a.match(/^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/), nom = m ? m[1].trim() : '', adr = m ? m[2].trim() : a.trim();
|
||
return h('span', { class: 'qui' }, nom ? h('span', { class: 'nom', text: nom }) : null, nom ? ' ' : null, h('span', { class: nom ? 'adr' : 'nom', text: nom ? '<' + adr + '>' : adr }));
|
||
}
|
||
function listeAdresses(s) {
|
||
var l = decouperAdresses(s);
|
||
if (!l.length) return null;
|
||
var dd = h('dd', { class: 'adrs' });
|
||
l.forEach(function (a, i) { var e = pastilleAdresse(a); if (i >= 3) e.setAttribute('hidden', ''); dd.appendChild(e); });
|
||
if (l.length > 3) {
|
||
var b = h('button', { type: 'button', class: 'btn-petit plus' }, '+ ' + (l.length - 3) + (l.length - 3 > 1 ? ' autres' : ' autre'));
|
||
b.addEventListener('click', function () {
|
||
dd.querySelectorAll('[hidden]').forEach(function (x) { x.removeAttribute('hidden'); }); b.remove();
|
||
var z = document.querySelector('.lect-scroll'); if (z) z.focus();
|
||
});
|
||
dd.appendChild(b);
|
||
}
|
||
return dd;
|
||
}
|
||
function tailleLisible(n) {
|
||
n = Number(n) || 0;
|
||
if (n < 1024) return n + ' o';
|
||
if (n < 1048576) return (n / 1024).toFixed(n < 10240 ? 1 : 0).replace('.', ',') + ' Ko';
|
||
return (n / 1048576).toFixed(1).replace('.', ',') + ' Mo';
|
||
}
|
||
function dateLongue(v) {
|
||
var iso = String(v || '').slice(0, 10);
|
||
if (!/^\d{4}-\d{2}-\d{2}$/.test(iso)) return String(v || '');
|
||
return nomJour(iso).toLowerCase() + ' ' + fr(iso) + ' à ' + heureTunis(v);
|
||
}
|
||
function estSignature(p) {
|
||
return /^image\//.test(p.type || '') && Number(p.taille) < 20480 && !p.bloquee;
|
||
}
|
||
function telechargerPiece(id, p, bt) {
|
||
bt.disabled = true; annoncer('Téléchargement de ' + p.nom + ' en cours');
|
||
fetch(API + '/mail/piece?id=' + encodeURIComponent(id) + '&nom=' + encodeURIComponent(p.nom), { credentials: 'same-origin', redirect: 'manual' })
|
||
.then(function (rep) {
|
||
if (rep.type === 'opaqueredirect') { sessionExpiree(); throw new Error('session'); }
|
||
if (rep.status === 403) throw new Error('Ce type de fichier est bloqué par sécurité.');
|
||
if (rep.status === 413) throw new Error('Pièce jointe trop volumineuse (25 Mo maximum).');
|
||
if (!rep.ok) throw new Error('Pièce jointe indisponible pour le moment.');
|
||
return rep.blob();
|
||
})
|
||
.then(function (blob) {
|
||
var url = URL.createObjectURL(blob), a = document.createElement('a');
|
||
a.href = url; a.download = p.nom; document.body.appendChild(a); a.click(); a.remove();
|
||
setTimeout(function () { URL.revokeObjectURL(url); }, 4000);
|
||
annoncer(p.nom + ' téléchargé');
|
||
})
|
||
.catch(function (e) { if (e.message !== 'session') annoncer(e.message); })
|
||
.then(function () { bt.disabled = false; });
|
||
}
|
||
function afficherMail(cont, m, r, c) {
|
||
var badges = h('div', { class: 'lect-badges' }, m.cat ? h('span', { class: 'lect-cat' }, pastille(couleur(m.cat, c && c.id)), m.cat) : null);
|
||
(m.etiquettes || []).forEach(function (t) { badges.appendChild(h('span', { class: 'etq', text: t })); });
|
||
var meta = h('dl', { class: 'lect-meta' });
|
||
function ligne(lib, dd) { if (!dd) return; meta.appendChild(h('dt', { text: lib })); meta.appendChild(dd); }
|
||
ligne('De', listeAdresses(r.de || m.expBrut)); ligne('À', listeAdresses(r.a)); ligne('Cc', listeAdresses(r.cc));
|
||
ligne('Date', h('dd', { text: dateLongue(m.date || r.date) }));
|
||
var lignes = String(r.corps || '').replace(/\r\n?/g, '\n').replace(/ /g, ' ').split('\n');
|
||
var cut = debutHistorique(lignes), principal = lignes, histo = null;
|
||
if (cut > 0) {
|
||
principal = lignes.slice(0, cut); histo = lignes.slice(cut);
|
||
while (principal.length && /^[\s_\-=]*$/.test(principal[principal.length - 1])) principal.pop();
|
||
}
|
||
var corps = principal.join('\n').trim() ? blocsTexte(principal.join('\n')) : h('p', { class: 'lect-vide', text: 'Ce mail ne contient pas de texte à afficher.' });
|
||
badges.appendChild(boutonSuivreLecture(m));
|
||
badges.appendChild(h('button', { type: 'button', class: 'btn-ligne lect-course', onclick: function () { dialogueCourse(null, { message_id: r.message_id || m.id, objet_mail: m.objet || r.objet || '', expediteur: m.expBrut || r.de || '', date_mail: m.date || '' }); } }, icone('courses', 18), 'Ajouter aux courses'));
|
||
cont.appendChild(badges); cont.appendChild(meta); cont.appendChild(corps);
|
||
if (histo && histo.join('\n').trim()) {
|
||
cont.appendChild(h('details', { class: 'lect-histo' }, h('summary', null, 'Afficher l\'historique de la conversation'), blocsTexte(histo.join('\n'))));
|
||
}
|
||
if (r.tronque) cont.appendChild(h('p', { class: 'lect-note', text: 'Le texte est très long : seul le début est affiché.' }));
|
||
var pj = r.pieces_jointes || [];
|
||
var signature = pj.filter(estSignature), utiles = pj.filter(function (p) { return !estSignature(p); });
|
||
function extDe(p) { var e = String(p.nom || '').indexOf('.') > -1 ? String(p.nom).split('.').pop().toUpperCase() : ''; return e && e.length <= 5 ? e + ' · ' : ''; }
|
||
if (utiles.length) {
|
||
var ul = h('ul');
|
||
utiles.forEach(function (p) {
|
||
var action;
|
||
if (p.bloquee) action = h('span', { class: 'info bloquee', text: 'Bloquée par sécurité' });
|
||
else {
|
||
var bt = h('button', { type: 'button', class: 'btn-icone', 'aria-label': 'Télécharger ' + p.nom, title: 'Télécharger' }, icone('telecharger'));
|
||
bt.addEventListener('click', function () { telechargerPiece(r.message_id || m.id, p, bt); });
|
||
action = bt;
|
||
}
|
||
ul.appendChild(h('li', null, icone('pj', 18), h('span', { class: 'nom coupe', title: p.nom, text: p.nom }),
|
||
h('span', { class: 'info', text: extDe(p) + tailleLisible(p.taille) }), action));
|
||
});
|
||
cont.appendChild(h('section', { class: 'lect-pj', 'aria-labelledby': 'lect-pj-t' }, h('h3', { id: 'lect-pj-t', text: 'Pièces jointes (' + utiles.length + ')' }), ul));
|
||
}
|
||
if (signature.length) {
|
||
var us = h('ul');
|
||
signature.forEach(function (p) { us.appendChild(h('li', null, icone('pj', 18), h('span', { class: 'nom coupe', title: p.nom, text: p.nom }), h('span', { class: 'info', text: tailleLisible(p.taille) }))); });
|
||
cont.appendChild(h('details', { class: 'lect-histo lect-sig' }, h('summary', null, 'Images intégrées au message (' + signature.length + ')'), us));
|
||
}
|
||
cont.appendChild(h('p', { class: 'lect-note', text: 'Lecture seule : le mail n\'est pas modifié dans votre messagerie.' }));
|
||
}
|
||
function lireMail(m) {
|
||
var c = S.cats.find(function (x) { return x.nom === m.cat; });
|
||
ouvrir(function (clore) {
|
||
var defil = h('div', { class: 'lect-scroll', tabindex: '0', 'data-focus': '', role: 'region', 'aria-label': 'Contenu du mail' });
|
||
var boite = h('section', { class: 'boite lecture', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'lect-t' },
|
||
h('div', { class: 'lect-tete' }, h('h2', { id: 'lect-t', text: m.objet || '(sans objet)' }),
|
||
h('button', { type: 'button', class: 'btn-icone', 'aria-label': 'Fermer la lecture', onclick: clore }, icone('fermer'))),
|
||
defil);
|
||
function charger() {
|
||
defil.textContent = ''; defil.setAttribute('aria-busy', 'true'); defil.focus();
|
||
defil.appendChild(h('div', { class: 'lect-etat', role: 'status' }, h('p', { text: 'Ouverture du mail…' }), h('span', { class: 'lect-sq' }), h('span', { class: 'lect-sq court' }), h('span', { class: 'lect-sq' })));
|
||
api('/mail?id=' + encodeURIComponent(m.id)).then(function (r) {
|
||
if (!document.body.contains(boite)) return;
|
||
defil.removeAttribute('aria-busy'); defil.textContent = '';
|
||
afficherMail(defil, m, r, c);
|
||
}).catch(function (e) {
|
||
if (e.message === 'session' || !document.body.contains(boite)) return;
|
||
defil.removeAttribute('aria-busy'); defil.textContent = '';
|
||
defil.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Lecture du mail impossible'),
|
||
h('p', null, 'Le service de lecture n\'a pas répondu. Le mail reste intact dans votre messagerie.'),
|
||
h('button', { type: 'button', class: 'btn-plein', onclick: charger }, 'Réessayer')));
|
||
});
|
||
}
|
||
charger();
|
||
return boite;
|
||
});
|
||
}
|
||
function reperes(m) {
|
||
if (!m.etiquettes || !m.etiquettes.length) return null;
|
||
var d = h('div', { class: 'etqs', 'aria-label': 'Étiquettes du miroir' });
|
||
m.etiquettes.forEach(function (t) { d.appendChild(h('span', { class: 'etq', text: t })); });
|
||
return d;
|
||
}
|
||
function ligneMail(m) {
|
||
var orig = m.source === 'manuel' ? 'manuel' : (m.cat === SYSTEME ? 'sans règle' : 'règle');
|
||
var origCls = orig === 'manuel' ? ' manuel' : orig === 'sans règle' ? ' sansregle' : '';
|
||
var objetAff = m.objet || '(sans objet)';
|
||
var etq = 'Traité : ' + m.exp + ', ' + (m.objet || 'sans objet');
|
||
var libLire = 'Lire le mail de ' + m.exp + ' : ' + (m.objet || 'sans objet');
|
||
var cb = h('input', { type: 'checkbox', 'aria-label': etq, onchange: function (e) { basculerTraite(m, e.target.checked); } });
|
||
cb.checked = m.traite;
|
||
return h('div', { class: 'ligne' + (m.traite ? ' fait' : ''), role: 'listitem' },
|
||
h('label', { class: 'coche' }, cb),
|
||
h('div', { class: 'corps d' }, h('div', { class: 'exp coupe', title: m.expBrut, text: m.exp })),
|
||
h('div', { class: 'corps d' }, h('button', { type: 'button', class: 'lire', 'aria-label': libLire, onclick: function () { lireMail(m); } }, h('span', { class: 'objet coupe' + (m.objet ? '' : ' sans'), text: objetAff })), reperes(m)),
|
||
h('div', { class: 'heure d', text: heureTunis(m.date) }),
|
||
h('div', { class: 'd' }, h('span', { class: 'origine' + origCls, text: orig })),
|
||
h('div', { class: 'm-corps' },
|
||
h('button', { type: 'button', class: 'lire', 'aria-label': libLire, onclick: function () { lireMail(m); } },
|
||
h('span', { class: 'exp coupe', title: m.expBrut, text: m.exp }), h('span', { class: 'objet coupe' + (m.objet ? '' : ' sans'), text: objetAff }),
|
||
h('span', { class: 'm-meta' }, h('span', { class: 'heure', text: heureTunis(m.date) }), ' · ', h('span', { class: 'o' + (orig === 'manuel' ? ' manuel' : ''), text: orig }))), reperes(m)),
|
||
selecteur(m),
|
||
boutonSuivre(m));
|
||
}
|
||
function vueTri() {
|
||
var frag = document.createDocumentFragment();
|
||
frag.appendChild(enteteJour());
|
||
if (S.etat === 'chargement') {
|
||
var sq = h('section', { class: 'carte squelette', 'aria-busy': 'true' }, h('div', { class: 'sq-statut', role: 'status', text: 'Lecture du courrier du ' + fr(S.jour) + '…' }));
|
||
for (var i = 0; i < 8; i++) sq.appendChild(h('div', { class: 'sq-ligne' }, h('span'), h('span'), h('span'), h('span'), h('span'), h('span')));
|
||
frag.appendChild(sq); return frag;
|
||
}
|
||
if (S.etat === 'erreur') {
|
||
frag.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Lecture du courrier impossible'),
|
||
h('p', null, 'Le service de lecture n\'a pas répondu pour le ' + fr(S.jour) + '. Vos corrections et vos règles sont conservées.'),
|
||
h('button', { type: 'button', class: 'btn-plein', onclick: chargerMails }, 'Réessayer')));
|
||
return frag;
|
||
}
|
||
if (S.miroirErreur) frag.appendChild(h('div', { class: 'bandeau', role: 'status' }, h('div', { class: 'txt' }, 'Lecture du courrier momentanément indisponible', h('small', null, 'Affichage des derniers classements enregistrés.'))));
|
||
var tous = S.mails, nbT = tous.filter(function (m) { return m.traite; }).length;
|
||
var compte = {}; tous.forEach(function (m) { compte[m.cat] = (compte[m.cat] || 0) + 1; });
|
||
var puces = h('div', { class: 'puces', role: 'group', 'aria-label': 'Filtrer par catégorie' });
|
||
var defs = [{ nom: 'Tous', c: -1, n: tous.length, filtre: null }].concat(S.cats.map(function (c, i) { return { nom: c.nom, c: couleur(c.nom, c.id), n: compte[c.nom] || 0, filtre: c.nom, rang: i }; }).sort(function (x, y) { return y.n - x.n || x.rang - y.rang; }));
|
||
defs.forEach(function (p) {
|
||
var actif = S.filtre === p.filtre;
|
||
puces.appendChild(h('button', { type: 'button', 'aria-pressed': actif ? 'true' : 'false', class: 'puce' + (p.c === 0 ? ' vide' : '') + (p.c > 0 ? ' t' + p.c : ''), onclick: function () { S.filtre = actif ? null : p.filtre; rendre(); } },
|
||
h('span', { class: 'pt ' + (p.c === -1 ? 'tous' : 'c' + p.c), 'aria-hidden': 'true' }), h('span', { text: p.nom }), h('span', { class: 'n', text: d2(p.n) })));
|
||
});
|
||
var barre = h('div', null); barre.style.width = tous.length ? Math.round(nbT / tous.length * 100) + '%' : '0%';
|
||
frag.appendChild(h('section', { class: 'carte repartition', 'aria-label': 'Répartition du jour' }, h('h2', null, 'Répartition du jour'), puces,
|
||
h('div', { class: 'avancement' }, h('div', { class: 'barre' }, barre), h('span', null, 'Traités ', h('b', { text: d2(nbT) + '/' + d2(tous.length) })))));
|
||
if (S.banniere) {
|
||
var b = S.banniere;
|
||
frag.appendChild(h('div', { class: 'bandeau', role: 'region', 'aria-label': 'Règle proposée' },
|
||
h('div', { class: 'txt' }, 'Toujours classer les mails de « ' + b.exp + ' » dans « ' + b.cat + ' » ?',
|
||
h('small', null, (b.autres ? b.autres + ' autre' + (b.autres > 1 ? 's' : '') + ' mail' + (b.autres > 1 ? 's' : '') + ' de ce jour ser' + (b.autres > 1 ? 'ont' : 'a') + ' aussi reclassé' + (b.autres > 1 ? 's' : '') + '. ' : '') + 'Votre messagerie n\'est pas modifiée.')),
|
||
h('div', { class: 'acts' }, h('button', { type: 'button', class: 'btn-plein', onclick: confirmerRegle }, 'Confirmer la règle'), h('button', { type: 'button', class: 'btn-ligne', onclick: ignorerRegle }, 'Pas maintenant'))));
|
||
}
|
||
if (S.notif) frag.appendChild(h('div', { class: 'notif', role: 'status', text: S.notif }));
|
||
var visibles = tous.filter(function (m) { return !S.filtre || m.cat === S.filtre; });
|
||
var liste = h('div', { role: 'list' });
|
||
var carte = h('section', { class: 'carte', 'aria-label': 'Mails du jour' });
|
||
carte.appendChild(h('div', { class: 'liste-entete', 'aria-hidden': 'true' }, h('span'), h('span', null, 'Expéditeur'), h('span', null, 'Objet'), h('span', null, 'Heure'), h('span', null, 'Origine'), h('span', null, 'Catégorie'), h('span')));
|
||
visibles.forEach(function (m) { liste.appendChild(ligneMail(m)); });
|
||
carte.appendChild(liste);
|
||
if (tous.length === 0) carte.appendChild(h('div', { class: 'etat' }, icone('tri', 28), h('h2', null, 'Aucun mail ce jour'), h('p', null, 'Rien n\'est arrivé le ' + fr(S.jour) + '.')));
|
||
else if (visibles.length === 0) carte.appendChild(h('div', { class: 'etat-filtre' }, 'Aucun mail dans « ' + S.filtre + ' » ce jour.', h('button', { type: 'button', class: 'btn-lien', onclick: function () { S.filtre = null; rendre(); } }, 'Tout afficher')));
|
||
frag.appendChild(carte);
|
||
return frag;
|
||
}
|
||
function vueCategories() {
|
||
var frag = document.createDocumentFragment();
|
||
frag.appendChild(h('header', { class: 'entete' }, h('h1', null, 'Catégories'), h('button', { type: 'button', class: 'btn-plein', onclick: function () { dialogueCategorie(null); } }, 'Ajouter une catégorie')));
|
||
if (S.notif) frag.appendChild(h('div', { class: 'notif', role: 'status', text: S.notif }));
|
||
if (S.etat === 'erreur') { frag.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Chargement impossible'), h('p', null, 'Les catégories n\'ont pas pu être lues.'), h('button', { type: 'button', class: 'btn-plein', onclick: chargerMails }, 'Réessayer'))); return frag; }
|
||
var compte = {}; S.mails.forEach(function (m) { compte[m.cat] = (compte[m.cat] || 0) + 1; });
|
||
var carte = h('section', { class: 'carte limite', 'aria-label': 'Catégories' });
|
||
S.cats.forEach(function (c) {
|
||
carte.appendChild(h('div', { class: 'rang' }, pastille(couleur(c.nom, c.id)), h('span', { class: 'nom', text: c.nom }),
|
||
h('span', { class: 'nb' }, h('b', { text: d2(compte[c.nom] || 0) }), ' ce jour'),
|
||
h('button', { type: 'button', class: 'btn-petit', 'aria-label': (c.nom === SYSTEME ? 'Détails de ' : 'Modifier ') + c.nom, onclick: function () { dialogueCategorie(c); } }, c.nom === SYSTEME ? 'Détails' : 'Modifier')));
|
||
});
|
||
if (S.etat === 'chargement') carte.appendChild(h('div', { class: 'sq-statut', role: 'status', text: 'Chargement…' }));
|
||
frag.appendChild(carte); return frag;
|
||
}
|
||
function critere(r) {
|
||
var p = [];
|
||
if (r.expediteur) p.push(['Expéditeur', r.expediteur]);
|
||
if (r.mot_cle) p.push(['Mot-clé', r.mot_cle]);
|
||
if (r.etiquette_miroir) p.push(['Étiquette', r.etiquette_miroir]);
|
||
return p.length ? p : [['Règle', '']];
|
||
}
|
||
function vueRegles() {
|
||
var frag = document.createDocumentFragment();
|
||
var act = S.regles.filter(function (r) { return r.statut === 'active'; }).length, prop = S.regles.length - act;
|
||
frag.appendChild(h('header', { class: 'entete' }, h('div', null, h('h1', null, 'Règles'), h('div', { class: 'maj', text: act + ' active' + (act > 1 ? 's' : '') + (prop ? ' · ' + prop + ' à confirmer' : '') }))));
|
||
if (S.notif) frag.appendChild(h('div', { class: 'notif', role: 'status', text: S.notif }));
|
||
if (S.reglesEtat === 'erreur') { frag.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Chargement impossible'), h('p', null, 'Les règles n\'ont pas pu être lues.'), h('button', { type: 'button', class: 'btn-plein', onclick: chargerRegles }, 'Réessayer'))); return frag; }
|
||
var carte = h('section', { class: 'carte limite-l', 'aria-label': 'Règles de classement' });
|
||
var flv = icone('fleche', 16); flv.classList.add('fl');
|
||
carte.appendChild(h('div', { class: 'regle' }, h('span', { class: 'crit' }, 'Objet ', h('b', { text: 'vide' })), flv, h('span', { class: 'cat' }, pastille(5), 'Sans objet'), h('span', { class: 'etiq active', text: 'règle de départ' }), h('span')));
|
||
var tri = S.regles.slice().sort(function (a, b) { return (a.statut === 'active') - (b.statut === 'active') || a.id - b.id; });
|
||
tri.forEach(function (r) {
|
||
var c = S.cats.find(function (x) { return x.nom === r.categorie; });
|
||
var crit = h('span', { class: 'crit' });
|
||
critere(r).forEach(function (p, i) { if (i) crit.appendChild(document.createTextNode(' · ')); crit.appendChild(document.createTextNode(p[0] + ' ')); crit.appendChild(h('b', { text: p[1] })); });
|
||
var actif = r.statut === 'active';
|
||
var sw = h('button', { type: 'button', class: 'interrupteur', role: 'switch', 'aria-checked': actif ? 'true' : 'false', 'aria-label': 'Règle ' + critere(r).map(function (p) { return p.join(' '); }).join(', ') + ' vers ' + r.categorie, onclick: function () { basculerRegle(r); } }, h('span', { class: 'piste' }, h('span', { class: 'bouton' })));
|
||
carte.appendChild(h('div', { class: 'regle' + (actif ? '' : ' propose') }, crit, icone('fleche', 16), h('span', { class: 'cat' }, pastille(couleur(r.categorie, c && c.id)), r.categorie),
|
||
h('span', { class: 'etiq ' + (actif ? 'active' : 'propose'), text: actif ? 'règle active' : 'à confirmer' }), sw));
|
||
carte.lastChild.querySelector('svg').classList.add('fl');
|
||
});
|
||
if (S.reglesEtat === 'chargement') carte.appendChild(h('div', { class: 'sq-statut', role: 'status', text: 'Chargement…' }));
|
||
else if (!S.regles.length) carte.appendChild(h('div', { class: 'etat' }, h('h2', null, 'Aucune règle'), h('p', null, 'Corrigez la catégorie d\'un mail pour en proposer une.')));
|
||
frag.appendChild(carte);
|
||
frag.appendChild(h('p', { class: 'note' }, 'Une règle activée s\'applique aux mails du jour qui n\'ont pas été corrigés à la main.'));
|
||
return frag;
|
||
}
|
||
function vueGroupes() {
|
||
var G = S.groupe, frag = document.createDocumentFragment();
|
||
frag.appendChild(h('header', { class: 'entete' }, h('div', null, h('h1', null, 'Groupes'), h('div', { class: 'maj' }, 'Un seul groupe, sur plusieurs jours · heure de Tunis'))));
|
||
if (S.notif) frag.appendChild(h('div', { class: 'notif', role: 'status', text: S.notif }));
|
||
var per = h('div', { class: 'puces', role: 'group', 'aria-label': 'Période' });
|
||
[[7, '7 jours'], [30, '30 jours']].forEach(function (p) {
|
||
per.appendChild(h('button', { type: 'button', class: 'puce', 'aria-pressed': G.jours === p[0] ? 'true' : 'false', onclick: function () { if (G.jours !== p[0]) { G.jours = p[0]; chargerGroupe(); } } }, h('span', { text: p[1] })));
|
||
});
|
||
frag.appendChild(h('section', { class: 'carte repartition', 'aria-label': 'Choisir un groupe' }, h('h2', null, 'Période'), per));
|
||
if (G.etat === 'erreur') {
|
||
frag.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Lecture du courrier impossible'), h('p', null, 'Le service de lecture n\'a pas répondu.'), h('button', { type: 'button', class: 'btn-plein', onclick: chargerGroupe }, 'Réessayer')));
|
||
return frag;
|
||
}
|
||
if (G.etat === 'chargement') { frag.appendChild(h('section', { class: 'carte squelette', 'aria-busy': 'true' }, h('div', { class: 'sq-statut', role: 'status', text: 'Lecture des ' + G.jours + ' derniers jours…' }))); return frag; }
|
||
if (G.miroirErreur) frag.appendChild(h('div', { class: 'bandeau', role: 'status' }, h('div', { class: 'txt' }, 'Lecture du courrier momentanément indisponible')));
|
||
var cc = {}, ce = {};
|
||
G.mails.forEach(function (m) { cc[m.cat] = (cc[m.cat] || 0) + 1; (m.etiquettes || []).forEach(function (t) { ce[t] = (ce[t] || 0) + 1; }); });
|
||
var pc = h('div', { class: 'puces', role: 'group', 'aria-label': 'Catégorie' });
|
||
S.cats.map(function (c, i) { return { c: c, rang: i }; }).sort(function (x, y) { return (cc[y.c.nom] || 0) - (cc[x.c.nom] || 0) || x.rang - y.rang; }).forEach(function (o) {
|
||
var c = o.c, k = couleur(c.nom, c.id), actif = G.cat === c.nom;
|
||
pc.appendChild(h('button', { type: 'button', 'aria-pressed': actif ? 'true' : 'false', class: 'puce' + (k === 0 ? ' vide' : '') + (k > 0 ? ' t' + k : ''), onclick: function () { G.cat = actif ? null : c.nom; rendre(); } },
|
||
h('span', { class: 'pt c' + k, 'aria-hidden': 'true' }), h('span', { text: c.nom }), h('span', { class: 'n', text: d2(cc[c.nom] || 0) })));
|
||
});
|
||
var pe = h('div', { class: 'puces', role: 'group', 'aria-label': 'Étiquette du miroir' });
|
||
Object.keys(ce).sort(function (a, b) { return ce[b] - ce[a] || a.localeCompare(b); }).forEach(function (t) {
|
||
var actif = G.etq === t;
|
||
pe.appendChild(h('button', { type: 'button', 'aria-pressed': actif ? 'true' : 'false', class: 'puce', onclick: function () { G.etq = actif ? null : t; rendre(); } }, h('span', { text: t }), h('span', { class: 'n', text: d2(ce[t]) })));
|
||
});
|
||
frag.appendChild(h('section', { class: 'carte repartition', 'aria-label': 'Groupes' }, h('h2', null, 'Catégorie'), pc, h('h2', null, 'Étiquette du miroir'), pe));
|
||
if (!G.cat && !G.etq) {
|
||
frag.appendChild(h('section', { class: 'carte' }, h('div', { class: 'etat' }, icone('groupes', 28), h('h2', null, 'Choisissez un groupe'), h('p', null, G.mails.length + ' mails sur ' + G.jours + ' jours. Touchez une catégorie ou une étiquette pour ne voir que celle-ci.'))));
|
||
return frag;
|
||
}
|
||
var vis = G.mails.filter(function (m) { return (!G.cat || m.cat === G.cat) && (!G.etq || (m.etiquettes || []).indexOf(G.etq) !== -1); });
|
||
var titreG = [G.cat, G.etq].filter(Boolean).join(' + ');
|
||
if (!vis.length) {
|
||
frag.appendChild(h('section', { class: 'carte' }, h('div', { class: 'etat-filtre' }, 'Aucun mail dans « ' + titreG + ' » sur ' + G.jours + ' jours.', h('button', { type: 'button', class: 'btn-lien', onclick: function () { G.cat = null; G.etq = null; rendre(); } }, 'Changer de groupe'))));
|
||
return frag;
|
||
}
|
||
frag.appendChild(h('h2', { class: 'titre-groupe', text: titreG + ' · ' + vis.length + (vis.length > 1 ? ' mails' : ' mail') }));
|
||
var jours = [], par = {};
|
||
vis.forEach(function (m) { var j = String(m.date).slice(0, 10); if (!par[j]) { par[j] = []; jours.push(j); } par[j].push(m); });
|
||
jours.forEach(function (j) {
|
||
var carte = h('section', { class: 'carte', 'aria-label': nomJour(j) + ' ' + fr(j) });
|
||
carte.appendChild(h('div', { class: 'jour-titre' }, h('span', { text: nomJour(j) + ' ' + fr(j) }), h('span', { class: 'nb', text: par[j].length + (par[j].length > 1 ? ' mails' : ' mail') })));
|
||
var liste = h('div', { role: 'list' }); par[j].forEach(function (m) { liste.appendChild(ligneMail(m)); });
|
||
carte.appendChild(liste); frag.appendChild(carte);
|
||
});
|
||
return frag;
|
||
}
|
||
/* ---------- Courses pour Tunis ---------- */
|
||
var SENS = { tunis_sfax: 'Tunis vers Sfax', sfax_tunis: 'Sfax vers Tunis' };
|
||
function chargerCourses() {
|
||
var C = S.courses; C.etat = 'chargement'; rendre();
|
||
return api('/courses/synchroniser', { method: 'POST' }).catch(function (e) { if (e.message === 'session') throw e; return null; }).then(function (sy) { return api('/courses?statut=toutes').then(function (r) { C.liste = r.courses || []; C.etat = 'ok'; rendre(); if (sy && sy.ajoutees) flash(sy.ajoutees === 1 ? '1 course ajoutée depuis vos mails Tunis.' : sy.ajoutees + ' courses ajoutées depuis vos mails Tunis.'); }); })
|
||
.catch(function (e) { if (e.message === 'session') return; C.etat = 'erreur'; rendre(); });
|
||
}
|
||
function exporterCourses() {
|
||
var C = S.courses; annoncer('Préparation du fichier');
|
||
fetch(API + '/courses/export?statut=' + C.filtre, { credentials: 'same-origin', redirect: 'manual' }).then(function (rep) {
|
||
if (rep.type === 'opaqueredirect') { sessionExpiree(); throw new Error('session'); }
|
||
if (!rep.ok) throw new Error('Export impossible pour le moment.');
|
||
return rep.blob();
|
||
}).then(function (blob) {
|
||
var url = URL.createObjectURL(blob), a = document.createElement('a');
|
||
a.href = url; a.download = 'Courses-pour-Tunis-' + auj() + '.xlsx'; document.body.appendChild(a); a.click(); a.remove();
|
||
setTimeout(function () { URL.revokeObjectURL(url); }, 4000); flash('Fichier prêt : Courses-pour-Tunis-' + auj() + '.xlsx');
|
||
}).catch(function (e) { if (e.message !== 'session') flash(e.message); });
|
||
}
|
||
function basculerCourse(k, faite) {
|
||
var avant = k.statut; k.statut = faite ? 'faite' : 'a_faire'; rendre();
|
||
api('/courses/' + k.id, { method: 'PATCH', body: { statut: k.statut } }).then(function (r) { k.fait_le = r.fait_le; annoncer(faite ? 'Course faite' : 'Course à faire'); })
|
||
.catch(function (e) { k.statut = avant; rendre(); if (e.message !== 'session') flash('Modification impossible. Réessayez.'); });
|
||
}
|
||
function dialogueCourse(course, mail) {
|
||
var nouveau = !course;
|
||
ouvrir(function (clore) {
|
||
var champ = h('input', { id: 'crs-dem', type: 'text', maxlength: '300', 'data-focus': '', autocomplete: 'off', value: course ? course.demande : (mail && mail.objet_mail) || '' });
|
||
var sens = h('select', { id: 'crs-sens' }, h('option', { value: 'tunis_sfax', text: SENS.tunis_sfax }), h('option', { value: 'sfax_tunis', text: SENS.sfax_tunis }));
|
||
sens.value = course ? course.sens : 'tunis_sfax';
|
||
var err = h('div', { class: 'err', role: 'alert' });
|
||
function enregistrer() {
|
||
var dem = champ.value.trim();
|
||
if (!dem) { err.textContent = 'Décrivez la course : objet ou document à rapporter ou à apporter.'; champ.focus(); return; }
|
||
var req = nouveau ? api('/courses', { method: 'POST', body: Object.assign({ demande: dem, sens: sens.value }, mail || {}) })
|
||
: api('/courses/' + course.id, { method: 'PATCH', body: { demande: dem, sens: sens.value } });
|
||
req.then(function () { clore(); if (S.vue === 'courses') return chargerCourses(); }).then(function () { flash(nouveau ? 'Course ajoutée.' : 'Course modifiée.'); })
|
||
.catch(function (e) { if (e.message !== 'session') err.textContent = 'Enregistrement impossible. Réessayez.'; });
|
||
}
|
||
champ.addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); enregistrer(); } });
|
||
var acts = h('div', { class: 'acts' }, h('button', { type: 'button', class: 'btn-ligne', onclick: clore }, 'Annuler'),
|
||
h('button', { type: 'button', class: 'btn-plein', onclick: enregistrer }, nouveau ? 'Ajouter' : 'Enregistrer'));
|
||
var pied = null;
|
||
if (course) pied = h('div', { class: 'pave' }, h('button', { type: 'button', class: 'btn-danger-ligne', onclick: function () {
|
||
api('/courses/' + course.id, { method: 'DELETE' }).then(function () { clore(); return chargerCourses(); }).then(function () { flash('Course supprimée.'); })
|
||
.catch(function (e) { if (e.message !== 'session') err.textContent = 'Suppression impossible. Réessayez.'; });
|
||
} }, 'Supprimer la course'));
|
||
return h('section', { class: 'boite', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'crs-t' },
|
||
h('h2', { id: 'crs-t' }, nouveau ? 'Nouvelle course pour Tunis' : 'Modifier la course'),
|
||
mail && mail.objet_mail ? h('p', { class: 'note', text: 'Mail source : ' + mail.objet_mail }) : null,
|
||
h('div', { class: 'champ' }, h('label', { for: 'crs-dem' }, 'Demande'), champ),
|
||
h('div', { class: 'champ' }, h('label', { for: 'crs-sens' }, 'Sens'), sens, err), acts, pied);
|
||
});
|
||
}
|
||
function vueCourses() {
|
||
var C = S.courses, frag = document.createDocumentFragment();
|
||
frag.appendChild(h('header', { class: 'entete' }, h('h1', null, 'Courses pour Tunis'),
|
||
h('div', { class: 'entete-actions' },
|
||
h('button', { type: 'button', class: 'btn-ligne', onclick: exporterCourses }, icone('telecharger', 18), 'Exporter en Excel'),
|
||
h('button', { type: 'button', class: 'btn-plein', onclick: function () { dialogueCourse(null, null); } }, 'Ajouter une course'))));
|
||
if (S.notif) frag.appendChild(h('div', { class: 'notif', role: 'status', text: S.notif }));
|
||
if (C.etat === 'erreur') { frag.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Chargement impossible'), h('p', null, 'Les courses n\'ont pas pu être lues.'), h('button', { type: 'button', class: 'btn-plein', onclick: chargerCourses }, 'Réessayer'))); return frag; }
|
||
if (C.etat === 'chargement') { frag.appendChild(h('section', { class: 'carte squelette', 'aria-busy': 'true' }, h('div', { class: 'sq-statut', role: 'status', text: 'Lecture des courses…' }))); return frag; }
|
||
var nb = { a_faire: 0, faite: 0, toutes: C.liste.length };
|
||
C.liste.forEach(function (k) { nb[k.statut] = (nb[k.statut] || 0) + 1; });
|
||
var pc = h('div', { class: 'puces', role: 'group', 'aria-label': 'Afficher' });
|
||
[['a_faire', 'À faire'], ['faite', 'Faites'], ['toutes', 'Toutes']].forEach(function (o) {
|
||
pc.appendChild(h('button', { type: 'button', class: 'puce', 'aria-pressed': C.filtre === o[0] ? 'true' : 'false', onclick: function () { C.filtre = o[0]; rendre(); } }, h('span', { text: o[1] }), h('span', { class: 'n', text: d2(nb[o[0]] || 0) })));
|
||
});
|
||
frag.appendChild(h('section', { class: 'carte repartition', 'aria-label': 'Filtre des courses' }, pc));
|
||
var vis = C.liste.filter(function (k) { return C.filtre === 'toutes' || k.statut === C.filtre; });
|
||
if (!vis.length) {
|
||
frag.appendChild(h('section', { class: 'carte' }, h('div', { class: 'etat' }, icone('courses', 28), h('h2', null, C.liste.length ? 'Rien dans cette liste' : 'Aucune course pour le moment'),
|
||
h('p', null, C.liste.length ? 'Changez de filtre pour voir les autres courses.' : 'Les mails classés Tunis des 14 derniers jours s\'ajoutent ici automatiquement. Vous pouvez aussi ajouter une course à la main.'))));
|
||
return frag;
|
||
}
|
||
var carte = h('section', { class: 'carte', 'aria-label': 'Courses' }), liste = h('div', { role: 'list' });
|
||
vis.forEach(function (k) {
|
||
var coche = h('input', { type: 'checkbox', 'aria-label': (k.statut === 'faite' ? 'Remettre à faire : ' : 'Marquer comme faite : ') + k.demande });
|
||
coche.checked = k.statut === 'faite';
|
||
coche.addEventListener('change', function () { basculerCourse(k, coche.checked); });
|
||
var meta = [SENS[k.sens] || ''];
|
||
if (k.date_mail) meta.push('mail du ' + fr(String(k.date_mail).slice(0, 10)));
|
||
if (k.expediteur) meta.push(nomExp(k.expediteur));
|
||
if (k.statut === 'faite' && k.fait_le) meta.push('faite le ' + fr(String(k.fait_le).slice(0, 10)));
|
||
var actions = h('div', { class: 'course-actions' });
|
||
if (k.message_id) actions.appendChild(h('button', { type: 'button', class: 'btn-petit', 'aria-label': 'Lire le mail de : ' + k.demande, onclick: function () { lireMail({ id: k.message_id, objet: k.objet_mail || k.demande, exp: nomExp(k.expediteur || ''), expBrut: k.expediteur || '', date: k.date_mail || '', cat: '', etiquettes: [] }); } }, 'Lire le mail'));
|
||
actions.appendChild(h('button', { type: 'button', class: 'btn-petit', 'aria-label': 'Modifier : ' + k.demande, onclick: function () { dialogueCourse(k, null); } }, 'Modifier'));
|
||
liste.appendChild(h('div', { class: 'course' + (k.statut === 'faite' ? ' faite' : ''), role: 'listitem' },
|
||
h('label', { class: 'coche' }, coche),
|
||
h('div', { class: 'course-corps' }, h('div', { class: 'dem', text: k.demande }), h('div', { class: 'meta', text: meta.filter(Boolean).join(' · ') })),
|
||
actions));
|
||
});
|
||
carte.appendChild(liste); frag.appendChild(carte); return frag;
|
||
}
|
||
/* ---------- Suivi des demandes ---------- */
|
||
var ETATS_SUIVI = [['attente', 'En attente de réponse'], ['reponse', 'Réponses reçues'], ['a_repondre', 'À répondre'], ['clos', 'Clos']];
|
||
function chargerSuivi() {
|
||
var V = S.suivi; V.etat = 'chargement'; rendre();
|
||
return api('/suivi?jours=' + V.jours).then(function (r) { V.items = r.items || []; V.compte = r.compte || {}; V.envoyesJusqu = r.envoyes_jusqu_au || ''; V.envoyesAJour = r.envoyes_a_jour !== false; V.etat = 'ok'; rendre(); })
|
||
.catch(function (e) { if (e.message === 'session') return; V.etat = 'erreur'; rendre(); });
|
||
}
|
||
function cloreSuivi(it, clore) {
|
||
var req = clore ? api('/suivi/clore', { method: 'POST', body: { cle: it.cle, dernier_id: it.dernier_id } }) : api('/suivi/rouvrir', { method: 'POST', body: { cle: it.cle } });
|
||
req.then(function () { it.clos = clore; var c = S.suivi.compte; c[it.etat] = (c[it.etat] || 0) + (clore ? -1 : 1); c.clos = (c.clos || 0) + (clore ? 1 : -1); rendre(); annoncer(clore ? 'Suivi clos' : 'Suivi rouvert'); })
|
||
.catch(function (e) { if (e.message !== 'session') flash('Modification impossible. Réessayez.'); });
|
||
}
|
||
function dureeLisible(j) { return j <= 0 ? 'aujourd\'hui' : j === 1 ? 'hier' : 'il y a ' + j + ' jours'; }
|
||
function vueSuivi() {
|
||
var V = S.suivi, frag = document.createDocumentFragment();
|
||
frag.appendChild(h('header', { class: 'entete' }, h('h1', null, 'Suivi des demandes')));
|
||
if (S.notif) frag.appendChild(h('div', { class: 'notif', role: 'status', text: S.notif }));
|
||
if (V.etat === 'erreur') { frag.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Lecture du courrier impossible'), h('p', null, 'Le suivi n\'a pas pu être calculé.'), h('button', { type: 'button', class: 'btn-plein', onclick: chargerSuivi }, 'Réessayer'))); return frag; }
|
||
var per = h('div', { class: 'puces', role: 'group', 'aria-label': 'Période' });
|
||
[7, 14, 30].forEach(function (j) { per.appendChild(h('button', { type: 'button', class: 'puce', 'aria-pressed': V.jours === j ? 'true' : 'false', onclick: function () { V.jours = j; chargerSuivi(); } }, h('span', { text: j + ' jours' }))); });
|
||
frag.appendChild(h('section', { class: 'carte repartition', 'aria-label': 'Période du suivi' }, h('h2', null, 'Période'), per));
|
||
if (V.etat === 'chargement') { frag.appendChild(h('section', { class: 'carte squelette', 'aria-busy': 'true' }, h('div', { class: 'sq-statut', role: 'status', text: 'Calcul du suivi sur ' + V.jours + ' jours…' }))); return frag; }
|
||
if (!V.envoyesAJour) frag.appendChild(h('div', { class: 'bandeau', role: 'status' }, h('div', { class: 'txt' }, 'Les messages envoyés ne sont lus que jusqu\'au ' + (V.envoyesJusqu ? fr(V.envoyesJusqu) : 'une date inconnue') + ' : les réponses envoyées depuis ne sont pas prises en compte.')));
|
||
var pc = h('div', { class: 'puces', role: 'group', 'aria-label': 'Afficher' });
|
||
ETATS_SUIVI.forEach(function (o) {
|
||
pc.appendChild(h('button', { type: 'button', class: 'puce', 'aria-pressed': V.filtre === o[0] ? 'true' : 'false', onclick: function () { V.filtre = o[0]; rendre(); } }, h('span', { text: o[1] }), h('span', { class: 'n', text: d2(V.compte[o[0]] || 0) })));
|
||
});
|
||
frag.appendChild(h('section', { class: 'carte repartition', 'aria-label': 'Filtre du suivi' }, h('h2', null, 'Afficher'), pc));
|
||
var vis = V.items.filter(function (i) { return V.filtre === 'clos' ? i.clos : (!i.clos && i.etat === V.filtre); });
|
||
if (!vis.length) {
|
||
frag.appendChild(h('section', { class: 'carte' }, h('div', { class: 'etat' }, icone('suivi', 28), h('h2', null, 'Rien dans cette liste'), h('p', null, 'Aucune demande dans « ' + ETATS_SUIVI.filter(function (o) { return o[0] === V.filtre; })[0][1] + ' » sur ' + V.jours + ' jours.'))));
|
||
return frag;
|
||
}
|
||
var carte = h('section', { class: 'carte', 'aria-label': 'Demandes' }), liste = h('div', { role: 'list' });
|
||
vis.forEach(function (it) {
|
||
var qui = it.etat === 'attente' ? 'À : ' : 'De : ';
|
||
var badges = h('div', { class: 'course-badges' });
|
||
if (it.relancer && !it.clos) badges.appendChild(h('span', { class: 'etq relance', text: 'À relancer' }));
|
||
var actions = h('div', { class: 'course-actions' },
|
||
h('button', { type: 'button', class: 'btn-petit', 'aria-label': 'Lire le mail : ' + it.sujet, onclick: function () { lireMail({ id: it.dernier_id, objet: it.sujet, exp: it.avec, expBrut: it.avec, date: it.date || '', cat: '', etiquettes: [] }); } }, 'Lire le mail'),
|
||
h('button', { type: 'button', class: 'btn-petit', 'aria-label': (it.clos ? 'Rouvrir : ' : 'Clore : ') + it.sujet, onclick: function () { cloreSuivi(it, !it.clos); } }, it.clos ? 'Rouvrir' : 'Clore'));
|
||
liste.appendChild(h('div', { class: 'course', role: 'listitem' },
|
||
h('div', { class: 'course-corps' }, h('div', { class: 'dem', text: it.sujet || '(sans objet)' }),
|
||
h('div', { class: 'meta', text: [qui + (it.avec || 'inconnu'), dureeLisible(it.jours), it.nb > 1 ? it.nb + ' messages' : '1 message'].join(' · ') }), badges),
|
||
actions));
|
||
});
|
||
carte.appendChild(liste); frag.appendChild(carte); return frag;
|
||
}
|
||
/* ---------- À suivre : mails marqués à la main, sans limite de date ---------- */
|
||
/* Le marqueur reste dans Courrier : la messagerie O365 n'est jamais modifiée. */
|
||
function estSuivi(id) { return !!S.suivreSet[id]; }
|
||
function majSuivreSet() {
|
||
var s = {};
|
||
S.asuivre.items.forEach(function (i) { if (i.statut === 'actif') s[i.message_id] = 1; });
|
||
S.suivreSet = s;
|
||
}
|
||
function infoSuivi(m) {
|
||
return { message_id: m.id, expediteur: m.expBrut || m.exp || '', objet: m.objet || '', date_mail: m.date || '', categorie: m.cat || '' };
|
||
}
|
||
function chargerASuivre(silencieux) {
|
||
var V = S.asuivre;
|
||
if (!silencieux) { V.etat = 'chargement'; rendre(); }
|
||
return Promise.all([silencieux ? Promise.resolve() : chargerCats(), api('/a-suivre')]).then(function (rs) {
|
||
V.items = rs[1].items || []; V.compte = rs[1].compte || { actif: 0, termine: 0 }; V.etat = 'ok'; majSuivreSet(); rendre();
|
||
}).catch(function (e) { if (e.message === 'session' || silencieux) return; V.etat = 'erreur'; rendre(); });
|
||
}
|
||
function basculerASuivre(m) {
|
||
var id = m.id, ajout = !estSuivi(id);
|
||
if (ajout) S.suivreSet[id] = 1; else delete S.suivreSet[id];
|
||
rendre();
|
||
var req = ajout ? api('/a-suivre/marquer', { method: 'POST', body: infoSuivi(m) }) : api('/a-suivre/retirer', { method: 'POST', body: { ids: [id] } });
|
||
return req.then(function () {
|
||
flash(ajout ? 'Ajouté à « À suivre ».' : 'Retiré de « À suivre » : le mail reste dans « Terminés ».');
|
||
return chargerASuivre(true);
|
||
}).catch(function (e) {
|
||
if (e.message === 'session') return;
|
||
if (ajout) delete S.suivreSet[id]; else S.suivreSet[id] = 1;
|
||
rendre(); flash('Le suivi n\'a pas pu être enregistré. Réessayez.');
|
||
});
|
||
}
|
||
function retirerDuSuivi(ids, texte) {
|
||
var V = S.asuivre;
|
||
return api('/a-suivre/retirer', { method: 'POST', body: { ids: ids } }).then(function (r) {
|
||
var faits = r.ids || [];
|
||
clearTimeout(V.annulerT);
|
||
V.annuler = faits.length ? { ids: faits, texte: texte } : null;
|
||
if (V.annuler) V.annulerT = setTimeout(function () { V.annuler = null; rendre(); }, 30000);
|
||
annoncer(texte);
|
||
return chargerASuivre(true);
|
||
}).catch(function (e) { if (e.message !== 'session') flash('Le retrait n\'a pas pu être enregistré. Réessayez.'); });
|
||
}
|
||
function remettreAuSuivi(ids, texte) {
|
||
return api('/a-suivre/remettre', { method: 'POST', body: { ids: ids } }).then(function () {
|
||
if (texte) flash(texte);
|
||
return chargerASuivre(true);
|
||
}).catch(function (e) { if (e.message !== 'session') flash('L\'opération n\'a pas pu être enregistrée. Réessayez.'); });
|
||
}
|
||
function supprimerDefinitivement(ids, texte) {
|
||
return api('/a-suivre/supprimer', { method: 'POST', body: { ids: ids } }).then(function () {
|
||
flash(texte); annoncer(texte);
|
||
return chargerASuivre(true);
|
||
}).catch(function (e) { if (e.message !== 'session') flash('La suppression n\'a pas pu être enregistrée. Réessayez.'); });
|
||
}
|
||
function annulerRetrait() {
|
||
var V = S.asuivre, a = V.annuler;
|
||
if (!a) return;
|
||
clearTimeout(V.annulerT); V.annuler = null;
|
||
remettreAuSuivi(a.ids, 'Retrait annulé.');
|
||
}
|
||
function boutonSuivre(m) {
|
||
var on = estSuivi(m.id);
|
||
return h('button', { type: 'button', class: 'btn-icone btn-suivre', 'aria-pressed': on ? 'true' : 'false', 'aria-label': 'À suivre : ' + m.exp + ', ' + (m.objet || 'sans objet'),
|
||
title: on ? 'Retirer de « À suivre »' : 'Ajouter à « À suivre »', onclick: function () { basculerASuivre(m); } }, icone('asuivre'));
|
||
}
|
||
function boutonSuivreLecture(m) {
|
||
var lib = h('span');
|
||
var b = h('button', { type: 'button', class: 'btn-ligne lect-suivre' }, icone('asuivre', 18), lib);
|
||
function etat() { var on = estSuivi(m.id); b.setAttribute('aria-pressed', on ? 'true' : 'false'); lib.textContent = on ? 'Retirer de « À suivre »' : 'Ajouter à « À suivre »'; }
|
||
b.addEventListener('click', function () { var p = basculerASuivre(m); etat(); p.then(etat); });
|
||
etat();
|
||
return b;
|
||
}
|
||
function boutonSuivreRecherche(x) {
|
||
var m = { id: x.message_id, exp: nomExp(x.expediteur), expBrut: x.expediteur, objet: x.objet, date: x.date, cat: '' };
|
||
var on = estSuivi(m.id);
|
||
return h('button', { type: 'button', class: 'btn-petit btn-suivre-txt', 'aria-pressed': on ? 'true' : 'false', 'aria-label': 'À suivre : ' + (x.objet || 'sans objet'),
|
||
onclick: function () { basculerASuivre(m); } }, on ? 'Suivi' : 'À suivre');
|
||
}
|
||
function vueASuivre() {
|
||
var V = S.asuivre, frag = document.createDocumentFragment();
|
||
frag.appendChild(h('header', { class: 'entete' }, h('div', null, h('h1', null, 'À suivre'), h('div', { class: 'maj' }, 'Les mails que vous avez marqués, sans limite de date'))));
|
||
if (S.notif) frag.appendChild(h('div', { class: 'notif', role: 'status', text: S.notif }));
|
||
if (V.etat === 'erreur') {
|
||
frag.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Lecture de la liste impossible'), h('p', null, 'La liste « À suivre » n\'a pas pu être chargée.'), h('button', { type: 'button', class: 'btn-plein', onclick: function () { chargerASuivre(); } }, 'Réessayer')));
|
||
return frag;
|
||
}
|
||
if (V.etat === 'chargement') { frag.appendChild(h('section', { class: 'carte squelette', 'aria-busy': 'true' }, h('div', { class: 'sq-statut', role: 'status', text: 'Chargement de votre liste…' }))); return frag; }
|
||
if (V.annuler) frag.appendChild(h('div', { class: 'bandeau', role: 'status' }, h('div', { class: 'txt', text: V.annuler.texte }), h('div', { class: 'acts' }, h('button', { type: 'button', class: 'btn-ligne', onclick: annulerRetrait }, 'Annuler'))));
|
||
var pc = h('div', { class: 'puces', role: 'group', 'aria-label': 'Afficher' });
|
||
[['actif', 'À suivre'], ['termine', 'Terminés']].forEach(function (o) {
|
||
pc.appendChild(h('button', { type: 'button', class: 'puce', 'aria-pressed': V.filtre === o[0] ? 'true' : 'false', onclick: function () { V.filtre = o[0]; rendre(); } }, h('span', { text: o[1] }), h('span', { class: 'n', text: d2(V.compte[o[0]] || 0) })));
|
||
});
|
||
frag.appendChild(h('section', { class: 'carte repartition', 'aria-label': 'Filtre de la liste' }, h('h2', null, 'Afficher'), pc));
|
||
var actif = V.filtre === 'actif';
|
||
var vis = V.items.filter(function (i) { return i.statut === V.filtre; });
|
||
if (!vis.length) {
|
||
frag.appendChild(h('section', { class: 'carte' }, h('div', { class: 'etat' }, icone('asuivre', 28),
|
||
h('h2', { text: actif ? 'Rien à suivre pour le moment' : 'Aucun mail terminé' }),
|
||
h('p', { text: actif ? 'Utilisez le marque-page d\'une ligne, ou le bouton dans un mail ouvert : le mail restera ici quelle que soit sa date.' : 'Les mails retirés de la liste apparaissent ici ; vous pouvez les remettre à tout moment.' }))));
|
||
return frag;
|
||
}
|
||
var par = {}, ordre = [], rang = {};
|
||
S.cats.forEach(function (c, i) { rang[c.nom] = i; });
|
||
vis.forEach(function (i) { var c = i.categorie || SYSTEME; if (!par[c]) { par[c] = []; ordre.push(c); } par[c].push(i); });
|
||
ordre.sort(function (a, b) { return (a === SYSTEME) - (b === SYSTEME) || par[b].length - par[a].length || (rang[a] === undefined ? 99 : rang[a]) - (rang[b] === undefined ? 99 : rang[b]); });
|
||
ordre.forEach(function (cat) {
|
||
var liste = par[cat], k = couleur(cat);
|
||
var ids = liste.map(function (i) { return i.message_id; });
|
||
var nb = liste.length + (liste.length > 1 ? ' mails' : ' mail');
|
||
var txtTout = actif ? 'Tout retirer' : 'Tout remettre';
|
||
var entete = h('div', { class: 'groupe-tete' }, pastille(k), h('h2', { text: cat }), h('span', { class: 'nb', text: nb }),
|
||
h('button', { type: 'button', class: 'btn-ligne', 'aria-label': txtTout + ' : ' + cat + ', ' + nb, onclick: function () {
|
||
if (actif) retirerDuSuivi(ids, liste.length + (liste.length > 1 ? ' mails retirés' : ' mail retiré') + ' de « ' + cat + ' ».');
|
||
else remettreAuSuivi(ids, liste.length + (liste.length > 1 ? ' mails remis' : ' mail remis') + ' dans « À suivre ».');
|
||
} }, txtTout));
|
||
if (!actif) {
|
||
entete.appendChild(h('button', { type: 'button', class: 'btn-ligne btn-danger', 'aria-label': 'Tout supprimer définitivement : ' + cat + ', ' + nb, onclick: function () {
|
||
if (!window.confirm('Supprimer définitivement ' + (liste.length > 1 ? 'ces ' + liste.length + ' mails' : 'ce mail') + ' de l\'historique « ' + cat + ' » ?\nLes mails eux-mêmes ne sont pas touchés.')) return;
|
||
supprimerDefinitivement(ids, liste.length + (liste.length > 1 ? ' mails supprimés' : ' mail supprimé') + ' de l\'historique.');
|
||
} }, 'Tout supprimer'));
|
||
}
|
||
var corps = h('div', { role: 'list' });
|
||
liste.forEach(function (it) {
|
||
var exp = nomExp(it.expediteur), objet = it.objet || '(sans objet)';
|
||
var quand = it.date_mail ? fr(String(it.date_mail).slice(0, 10)) + ' · ' + heureTunis(it.date_mail) : '';
|
||
var vieux = actif && it.jours >= 7;
|
||
var badges = h('div', { class: 'course-badges' }, h('span', { class: 'etq' + (vieux ? ' relance' : ''), text: actif ? 'Marqué ' + dureeLisible(it.jours) : 'Terminé' }));
|
||
var mm = { id: it.message_id, exp: exp, expBrut: it.expediteur || exp, objet: it.objet || '', date: it.date_mail || '', cat: it.categorie, etiquettes: [] };
|
||
corps.appendChild(h('div', { class: 'course', role: 'listitem' },
|
||
h('div', { class: 'course-corps' }, h('div', { class: 'dem', text: objet }), h('div', { class: 'meta', text: [exp, quand].filter(Boolean).join(' · ') }), badges),
|
||
h('div', { class: 'course-actions' },
|
||
h('button', { type: 'button', class: 'btn-petit', 'aria-label': 'Lire le mail : ' + objet, onclick: function () { lireMail(mm); } }, 'Lire le mail'),
|
||
actif
|
||
? h('button', { type: 'button', class: 'btn-petit', 'aria-label': 'Retirer de la liste : ' + objet, onclick: function () { retirerDuSuivi([it.message_id], 'Mail retiré : ' + objet); } }, 'Retirer')
|
||
: h('button', { type: 'button', class: 'btn-petit', 'aria-label': 'Remettre dans la liste : ' + objet, onclick: function () { remettreAuSuivi([it.message_id], 'Remis dans « À suivre ».'); } }, 'Remettre'),
|
||
actif ? null : h('button', { type: 'button', class: 'btn-petit btn-danger', 'aria-label': 'Supprimer définitivement : ' + objet, onclick: function () { supprimerDefinitivement([it.message_id], 'Mail supprimé de l\'historique.'); } }, 'Supprimer'))));
|
||
});
|
||
var carte = h('section', { class: 'carte groupe-suivi t' + k, 'aria-label': cat });
|
||
carte.appendChild(entete); carte.appendChild(corps); frag.appendChild(carte);
|
||
});
|
||
return frag;
|
||
}
|
||
/* ---------- Recherche ---------- */
|
||
var PERIODES = [['tout', 'Tout le courrier'], ['30', '30 jours'], ['90', '90 jours'], ['annee', 'Cette année']];
|
||
function lancerRecherche() {
|
||
var R = S.recherche, q = R.q.trim();
|
||
if (q.length < 2) { R.etat = 'court'; rendre(); var c0 = document.getElementById('rech-q'); if (c0) c0.focus(); return; }
|
||
var url = '/recherche?q=' + encodeURIComponent(q), a = auj();
|
||
if (R.periode === '30' || R.periode === '90') url += '&depuis=' + versISO(new Date(dateUTC(a).getTime() - (+R.periode) * 86400000));
|
||
if (R.periode === 'annee') url += '&depuis=' + a.slice(0, 4) + '-01-01';
|
||
R.etat = 'chargement'; R.cherche = q; rendre();
|
||
api(url).then(function (r) { R.resultats = r.resultats || []; R.plafond = !!r.plafond; R.etat = 'ok'; rendre(); annoncer(R.resultats.length + (R.resultats.length > 1 ? ' résultats' : ' résultat')); })
|
||
.catch(function (e) { if (e.message === 'session') return; R.etat = 'erreur'; rendre(); });
|
||
}
|
||
function vueRecherche() {
|
||
var R = S.recherche, frag = document.createDocumentFragment();
|
||
frag.appendChild(h('header', { class: 'entete' }, h('h1', null, 'Recherche')));
|
||
var champ = h('input', { id: 'rech-q', type: 'search', maxlength: '100', autocomplete: 'off', enterkeyhint: 'search', value: R.q, placeholder: 'Mot, expéditeur, numéro de marché…' });
|
||
champ.addEventListener('input', function () { R.q = champ.value; });
|
||
var sel = h('select', { id: 'rech-p', 'aria-label': 'Période' });
|
||
PERIODES.forEach(function (o) { var op = h('option', { value: o[0], text: o[1] }); if (R.periode === o[0]) op.selected = true; sel.appendChild(op); });
|
||
sel.addEventListener('change', function () { R.periode = sel.value; });
|
||
var form = h('form', { class: 'carte recherche-form', role: 'search', 'aria-label': 'Rechercher dans le courrier' },
|
||
h('div', { class: 'champ' }, h('label', { for: 'rech-q' }, 'Rechercher'), champ),
|
||
h('div', { class: 'champ' }, h('label', { for: 'rech-p' }, 'Période'), sel),
|
||
h('button', { type: 'submit', class: 'btn-plein' }, 'Rechercher'));
|
||
form.addEventListener('submit', function (e) { e.preventDefault(); lancerRecherche(); });
|
||
frag.appendChild(form);
|
||
if (R.etat === 'repos') { frag.appendChild(h('section', { class: 'carte' }, h('div', { class: 'etat' }, icone('recherche', 28), h('h2', null, 'Retrouvez un mail'), h('p', null, 'Tapez un mot, un nom d\'expéditeur ou un numéro de marché. La recherche ignore les accents et les majuscules.')))); return frag; }
|
||
if (R.etat === 'court') { frag.appendChild(h('div', { class: 'notif', role: 'alert', text: 'Saisissez au moins 2 caractères.' })); return frag; }
|
||
if (R.etat === 'chargement') { frag.appendChild(h('section', { class: 'carte squelette', 'aria-busy': 'true' }, h('div', { class: 'sq-statut', role: 'status', text: 'Recherche de « ' + R.cherche + ' »…' }))); return frag; }
|
||
if (R.etat === 'erreur') { frag.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Recherche impossible'), h('p', null, 'Le service de lecture n\'a pas répondu.'), h('button', { type: 'button', class: 'btn-plein', onclick: lancerRecherche }, 'Réessayer'))); return frag; }
|
||
var avecPj = h('input', { type: 'checkbox', id: 'rech-pj' }); avecPj.checked = R.avecPj;
|
||
avecPj.addEventListener('change', function () { R.avecPj = avecPj.checked; rendre(); var c = document.getElementById('rech-pj'); if (c) c.focus(); });
|
||
var vis = R.resultats.filter(function (x) { return !R.avecPj || x.pj; });
|
||
frag.appendChild(h('section', { class: 'carte repartition', 'aria-label': 'Résultats' },
|
||
h('h2', null, vis.length + (vis.length > 1 ? ' résultats' : ' résultat') + ' pour « ' + R.cherche + ' »'),
|
||
h('label', { class: 'recherche-pj' }, avecPj, h('span', { text: 'Avec pièces jointes seulement' }))));
|
||
if (R.plafond) frag.appendChild(h('div', { class: 'bandeau', role: 'status' }, h('div', { class: 'txt' }, 'Les 100 premiers résultats sont affichés : précisez le mot ou la période pour affiner.')));
|
||
if (!vis.length) { frag.appendChild(h('section', { class: 'carte' }, h('div', { class: 'etat' }, icone('recherche', 28), h('h2', null, 'Aucun mail trouvé'), h('p', null, 'Essayez un autre mot, moins de mots, ou élargissez la période.')))); return frag; }
|
||
var jours = [], par = {};
|
||
vis.forEach(function (x) { var d = String(x.date).slice(0, 10); if (!par[d]) { par[d] = []; jours.push(d); } par[d].push(x); });
|
||
jours.forEach(function (d) {
|
||
var carte = h('section', { class: 'carte', 'aria-label': nomJour(d) + ' ' + fr(d) });
|
||
carte.appendChild(h('div', { class: 'jour-titre' }, h('span', { text: nomJour(d) + ' ' + fr(d) }), h('span', { class: 'nb', text: par[d].length + (par[d].length > 1 ? ' mails' : ' mail') })));
|
||
var liste = h('div', { role: 'list' });
|
||
par[d].forEach(function (x) {
|
||
var meta = [nomExp(x.expediteur), x.dossier].filter(Boolean).join(' · ');
|
||
liste.appendChild(h('div', { class: 'course', role: 'listitem' },
|
||
h('div', { class: 'course-corps' }, h('div', { class: 'dem', text: x.objet || '(sans objet)' }), h('div', { class: 'meta', text: meta + (x.pj ? ' · avec pièce jointe' : '') })),
|
||
h('div', { class: 'course-actions' }, h('button', { type: 'button', class: 'btn-petit', 'aria-label': 'Lire le mail : ' + (x.objet || 'sans objet'), onclick: function () { lireMail({ id: x.message_id, objet: x.objet, exp: nomExp(x.expediteur), expBrut: x.expediteur, date: x.date, cat: '', etiquettes: x.etiquettes || [] }); } }, 'Lire le mail'), boutonSuivreRecherche(x))));
|
||
});
|
||
carte.appendChild(liste); frag.appendChild(carte);
|
||
});
|
||
return frag;
|
||
}
|
||
function vueBientot(k) {
|
||
var t = BIENTOT[k];
|
||
return h('div', null, h('header', { class: 'entete' }, h('h1', null, t[0])),
|
||
h('section', { class: 'carte limite' }, h('div', { class: 'bientot-ecran' }, h('span', { class: 'badge-bientot' }, 'Prochainement'), h('p', { class: 'note', text: t[1] }))));
|
||
}
|
||
function rendre() {
|
||
var pos = document.getElementById('principal').scrollTop;
|
||
var ancre = document.activeElement && document.activeElement.getAttribute && document.activeElement.getAttribute('aria-label');
|
||
rendreNav();
|
||
var p = document.getElementById('principal'); p.textContent = '';
|
||
var v = S.vue === 'tri' ? vueTri() : S.vue === 'categories' ? vueCategories() : S.vue === 'regles' ? vueRegles() : S.vue === 'groupes' ? vueGroupes() : S.vue === 'courses' ? vueCourses() : S.vue === 'suivi' ? vueSuivi() : S.vue === 'asuivre' ? vueASuivre() : S.vue === 'recherche' ? vueRecherche() : vueBientot(S.vue);
|
||
p.appendChild(v); p.scrollTop = pos;
|
||
var titre = S.vue === 'tri' ? 'Tri du jour' : S.vue === 'categories' ? 'Catégories' : S.vue === 'regles' ? 'Règles' : S.vue === 'groupes' ? 'Groupes' : S.vue === 'courses' ? 'Courses pour Tunis' : S.vue === 'suivi' ? 'Suivi des demandes' : S.vue === 'asuivre' ? 'À suivre' : S.vue === 'recherche' ? 'Recherche' : BIENTOT[S.vue][0];
|
||
document.title = titre + ' · Courrier';
|
||
if (ancre && !dialogue) { var r = p.querySelector('[aria-label="' + ancre.replace(/"/g, '\\"') + '"]'); if (r && document.activeElement === document.body) r.focus(); }
|
||
}
|
||
|
||
rendre();
|
||
chargerMails();
|
||
chargerASuivre(true);
|
||
})();
|