Courrier v1.7 (tt-2026-11-070) : suivi des demandes par fil de discussion, clore et rouvrir, avertissement de fraicheur
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XGaEeWkqZYNP6Wn3mGQsrL
This commit is contained in:
1 parent
b712ee10cd
commit
44bfbc3a0c
8 files changed
+336
-10
No files matched your search
@@ -503,3 +503,38 @@ def delete_course(course_id: int, db_path: Optional[str] = None) -> bool:
|
||||
return conn.execute("DELETE FROM courses WHERE id = ?", (course_id,)).rowcount > 0
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# --- Suivi des demandes : fils clos ---
|
||||
def _suivi_pret(conn: sqlite3.Connection) -> None:
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS suivi_clos (cle TEXT PRIMARY KEY, dernier_id TEXT NOT NULL, clos_le TEXT NOT NULL)")
|
||||
|
||||
|
||||
def list_suivi_clos(db_path: Optional[str] = None) -> Dict[str, str]:
|
||||
conn = get_connection(db_path)
|
||||
try:
|
||||
_suivi_pret(conn)
|
||||
return {r["cle"]: r["dernier_id"] for r in conn.execute("SELECT cle, dernier_id FROM suivi_clos").fetchall()}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def clore_suivi(cle: str, dernier_id: str, db_path: Optional[str] = None) -> None:
|
||||
conn = get_connection(db_path)
|
||||
try:
|
||||
_suivi_pret(conn)
|
||||
with conn:
|
||||
conn.execute("INSERT INTO suivi_clos (cle, dernier_id, clos_le) VALUES (?, ?, ?) ON CONFLICT(cle) DO UPDATE SET dernier_id = excluded.dernier_id, clos_le = excluded.clos_le",
|
||||
(cle, dernier_id, get_tunis_now_iso()))
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def rouvrir_suivi(cle: str, db_path: Optional[str] = None) -> bool:
|
||||
conn = get_connection(db_path)
|
||||
try:
|
||||
_suivi_pret(conn)
|
||||
with conn:
|
||||
return conn.execute("DELETE FROM suivi_clos WHERE cle = ?", (cle,)).rowcount > 0
|
||||
finally:
|
||||
conn.close()
|
||||
+56
-1
@@ -1,4 +1,5 @@
|
||||
import base64
|
||||
import os
|
||||
import re
|
||||
from contextlib import asynccontextmanager
|
||||
from urllib.parse import quote
|
||||
@@ -29,7 +30,10 @@ from app.db import (
|
||||
add_course,
|
||||
update_course,
|
||||
delete_course,
|
||||
SENS_COURSE
|
||||
SENS_COURSE,
|
||||
list_suivi_clos,
|
||||
clore_suivi,
|
||||
rouvrir_suivi
|
||||
)
|
||||
from app.classifier import (
|
||||
classify_mail,
|
||||
@@ -290,6 +294,57 @@ def telecharger_piece(id: str = Query(..., min_length=1, max_length=400), nom: s
|
||||
})
|
||||
|
||||
|
||||
# --- Suivi des demandes ---
|
||||
MON_ADRESSE = os.environ.get("MON_ADRESSE", "nabil.derouiche@")
|
||||
|
||||
|
||||
class SuiviClore(BaseModel):
|
||||
cle: str = Field(..., min_length=1, max_length=400)
|
||||
dernier_id: str = Field(..., min_length=1, max_length=400)
|
||||
|
||||
|
||||
class SuiviRouvrir(BaseModel):
|
||||
cle: str = Field(..., min_length=1, max_length=400)
|
||||
|
||||
|
||||
@api.get("/suivi")
|
||||
def lire_suivi(jours: int = Query(14, ge=1, le=60)):
|
||||
"""Suivi des demandes par fil de discussion : en attente de réponse, réponses reçues, demandes à traiter."""
|
||||
from datetime import datetime, timedelta
|
||||
from zoneinfo import ZoneInfo
|
||||
from app.suivi import calculer_suivi
|
||||
maintenant = datetime.now(ZoneInfo("Africa/Tunis"))
|
||||
debut = (maintenant - timedelta(days=jours)).strftime("%Y-%m-%d")
|
||||
try:
|
||||
recus = mirror_client.get_mails_since(debut, max_items=800)
|
||||
tous_envoyes = mirror_client.get_sent_mails()
|
||||
envoyes = [m for m in tous_envoyes if (m.get("date") or "")[:10] >= debut]
|
||||
except Exception:
|
||||
raise HTTPException(status_code=502, detail="Lecture du courrier momentanément indisponible.")
|
||||
vus, tous = set(), []
|
||||
for m in recus + envoyes:
|
||||
if m.get("message_id") not in vus:
|
||||
vus.add(m.get("message_id")); tous.append(m)
|
||||
items = calculer_suivi(tous, MON_ADRESSE, maintenant, list_suivi_clos())
|
||||
compte = {k: sum(1 for i in items if i["etat"] == k and not i["clos"]) for k in ("attente", "reponse", "a_repondre")}
|
||||
compte["clos"] = sum(1 for i in items if i["clos"])
|
||||
derniere = max(((x.get("date") or "")[:10] for x in tous_envoyes), default="")
|
||||
seuil = (maintenant - timedelta(days=2)).strftime("%Y-%m-%d")
|
||||
return {"jours": jours, "items": items, "compte": compte, "envoyes_jusqu_au": derniere, "envoyes_a_jour": bool(derniere) and derniere >= seuil}
|
||||
|
||||
|
||||
@api.post("/suivi/clore")
|
||||
def suivi_clore(c: SuiviClore):
|
||||
clore_suivi(c.cle, c.dernier_id)
|
||||
return {"clos": c.cle}
|
||||
|
||||
|
||||
@api.post("/suivi/rouvrir")
|
||||
def suivi_rouvrir(c: SuiviRouvrir):
|
||||
rouvrir_suivi(c.cle)
|
||||
return {"rouvert": c.cle}
|
||||
|
||||
|
||||
# --- Courses pour Tunis ---
|
||||
class CourseIn(BaseModel):
|
||||
demande: str = Field(..., min_length=1, max_length=300)
|
||||
|
||||
@@ -221,6 +221,8 @@ class MirrorClient:
|
||||
"objet": m.get("sujet") or m.get("subject") or m.get("objet") or "",
|
||||
"etiquettes": m.get("tags") or m.get("etiquettes") or [],
|
||||
"apercu": m.get("snippet") or m.get("apercu") or "",
|
||||
"dossier": m.get("dossier") or "",
|
||||
"destinataires": m.get("destinataires") or "",
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
@@ -283,6 +285,11 @@ class MirrorClient:
|
||||
pass # le miroir reste lisible sur les 100 derniers même si la recherche échoue
|
||||
return out
|
||||
|
||||
def get_sent_mails(self, n: int = 100) -> List[Dict[str, Any]]:
|
||||
"""Derniers messages envoyés (dossier « Messages envoyés » du miroir), normalisés."""
|
||||
res = self.call_tool("mirror_mail_latest", {"folder": "Messages envoyés", "n": min(n, self.MIRROR_MAX_LATEST), "inclure_exclus": False})
|
||||
return [self._norm(m) for m in self._liste(res)]
|
||||
|
||||
def get_attachment(self, message_id: str, filename: str) -> Dict[str, Any]:
|
||||
"""Pièce jointe d'un mail (mirror_mail_attachment), jamais mise en cache (contenu volumineux)."""
|
||||
res = self.call_tool("mirror_mail_attachment", {"message_id": message_id, "filename": filename}, use_cache=False)
|
||||
|
||||
@@ -287,3 +287,8 @@ h1, h2, h3, p { margin: 0; }
|
||||
.course-actions { display: flex; gap: var(--ny-e2); flex: none; flex-wrap: wrap; justify-content: flex-end; }
|
||||
.champ select { min-height: var(--ny-cible); padding: 0 var(--ny-e3); border: 1px solid var(--ny-trait-controle); border-radius: var(--ny-r-s); background: var(--ny-carte); font: 400 16px/24px var(--ny-police); }
|
||||
@media (max-width: 640px) { .course { flex-wrap: wrap; } .course-actions { width: 100%; justify-content: flex-start; padding-left: calc(var(--ny-cible) + var(--ny-e3)); } .lect-course { margin-left: 0; } }
|
||||
|
||||
/* Suivi des demandes */
|
||||
.course-badges { display: flex; gap: var(--ny-e2); flex-wrap: wrap; margin-top: var(--ny-e1, 4px); }
|
||||
.course-badges:empty { display: none; }
|
||||
.etq.relance { background: var(--ny-attention-fond, var(--ny-carte-2)); color: var(--ny-attention, var(--ny-encre)); font-weight: 600; }
|
||||
+55
-7
@@ -17,18 +17,17 @@
|
||||
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], ['categories', 'Catégories', true], ['groupes', 'Groupes', true], ['courses', 'Courses pour Tunis', true], ['regles', 'Règles', true],
|
||||
['recherche', 'Recherche', false], ['suivi', 'Suivi des demandes', false], ['pj', 'Pièces jointes', false]
|
||||
['tri', 'Tri du jour', true], ['categories', 'Catégories', true], ['groupes', 'Groupes', true], ['courses', 'Courses pour Tunis', true], ['suivi', 'Suivi des demandes', true], ['regles', 'Règles', true],
|
||||
['recherche', 'Recherche', false], ['pj', 'Pièces jointes', false]
|
||||
];
|
||||
var BIENTOT = {
|
||||
recherche: ['Recherche', 'Retrouver un mail par expéditeur, objet ou date, dans tout le courrier lu.'],
|
||||
suivi: ['Suivi des demandes', 'Suivre les demandes envoyées et celles qui attendent une réponse.'],
|
||||
pj: ['Pièces jointes', 'Lister et rechercher les pièces jointes des mails.']
|
||||
};
|
||||
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' } };
|
||||
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' }, suivi: { items: [], jours: 14, filtre: 'attente', compte: {}, etat: 'chargement' } };
|
||||
|
||||
/* ---------- Utilitaires ---------- */
|
||||
function auj() { return new Intl.DateTimeFormat('en-CA', { timeZone: TZ }).format(new Date()); }
|
||||
@@ -154,6 +153,7 @@
|
||||
else if (vue === 'groupes') chargerGroupe();
|
||||
else if (vue === 'regles') chargerRegles();
|
||||
else if (vue === 'courses') chargerCourses();
|
||||
else if (vue === 'suivi') chargerSuivi();
|
||||
else rendre();
|
||||
document.getElementById('principal').focus();
|
||||
}
|
||||
@@ -284,7 +284,7 @@
|
||||
}
|
||||
var liste = h('div', { class: 'nav-liste' });
|
||||
NAV.forEach(function (n, i) {
|
||||
if (i === 5) liste.appendChild(h('div', { class: 'nav-sep' }, 'Prochainement'));
|
||||
if (i === 6) liste.appendChild(h('div', { class: 'nav-sep' }, 'Prochainement'));
|
||||
liste.appendChild(bouton(n));
|
||||
if (n[2]) mobile.appendChild(bouton(n));
|
||||
});
|
||||
@@ -737,6 +737,54 @@
|
||||
});
|
||||
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;
|
||||
}
|
||||
function vueBientot(k) {
|
||||
var t = BIENTOT[k];
|
||||
return h('div', null, h('header', { class: 'entete' }, h('h1', null, t[0])),
|
||||
@@ -747,9 +795,9 @@
|
||||
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() : vueBientot(S.vue);
|
||||
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() : 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' : BIENTOT[S.vue][0];
|
||||
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' : 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(); }
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
||||
<link rel="stylesheet" href="/static/fonts.css">
|
||||
<link rel="stylesheet" href="/static/nyora.css">
|
||||
<link rel="stylesheet" href="/static/app.css?v=20261118b">
|
||||
<link rel="stylesheet" href="/static/app.css?v=20261118d">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app" class="coque">
|
||||
@@ -20,6 +20,6 @@
|
||||
</div>
|
||||
<div id="calque"></div>
|
||||
<div id="annonce" class="sr" role="status" aria-live="polite"></div>
|
||||
<script src="/static/app.js?v=20261118b"></script>
|
||||
<script src="/static/app.js?v=20261118d"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Suivi des demandes : calcul par fil de discussion à partir des mails lus (aucune écriture dans la messagerie)."""
|
||||
import re
|
||||
from datetime import datetime
|
||||
from email.utils import getaddresses
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
PREFIXES = re.compile(r"^\s*((re|tr|fw|fwd|rép|rep|réf|ref|ré|aw|sv)\s*:\s*)+", re.IGNORECASE)
|
||||
RELANCE_JOURS = 3
|
||||
AUTOMATIQUE = re.compile(r"no[-_.]?reply|do[-_.]?not[-_.]?reply|mailer-daemon|postmaster|notification", re.IGNORECASE)
|
||||
|
||||
|
||||
def sujet_normalise(sujet: str) -> str:
|
||||
return re.sub(r"\s+", " ", PREFIXES.sub("", sujet or "")).strip().lower()
|
||||
|
||||
|
||||
def _dt(iso: str) -> Optional[datetime]:
|
||||
try:
|
||||
return datetime.fromisoformat(iso)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _avec(texte: str) -> str:
|
||||
adresses = [a for a in getaddresses([texte or ""]) if a[0] or a[1]]
|
||||
if not adresses:
|
||||
return ""
|
||||
nom = adresses[0][0].strip().strip('"') or adresses[0][1]
|
||||
return nom + (f" +{len(adresses) - 1}" if len(adresses) > 1 else "")
|
||||
|
||||
|
||||
def calculer_suivi(mails: List[Dict[str, Any]], mon_adresse: str, maintenant: datetime, clos: Dict[str, str]) -> List[Dict[str, Any]]:
|
||||
"""mails : mails normalisés (reçus et envoyés, sans doublon). clos : {clé de fil: id du dernier message au moment de la clôture}.
|
||||
États : attente (j'ai écrit en dernier), reponse (quelqu'un a répondu à un message que j'ai écrit), a_repondre (demande reçue sans réponse de ma part)."""
|
||||
mon = (mon_adresse or "").lower()
|
||||
fils: Dict[str, List[Dict[str, Any]]] = {}
|
||||
for m in mails:
|
||||
cle = sujet_normalise(m.get("objet"))
|
||||
d = _dt(m.get("date") or "")
|
||||
if not cle or d is None or not m.get("message_id"):
|
||||
continue
|
||||
if AUTOMATIQUE.search(m.get("expediteur") or ""):
|
||||
continue
|
||||
fils.setdefault(cle, []).append(dict(m, _d=d, _moi=mon in (m.get("expediteur") or "").lower()))
|
||||
sortie = []
|
||||
for cle, msgs in fils.items():
|
||||
msgs.sort(key=lambda x: x["_d"])
|
||||
dernier = msgs[-1]
|
||||
if dernier["_moi"]:
|
||||
autres = [a for a in getaddresses([dernier.get("destinataires") or ""]) if a[1] and mon not in a[1].lower()]
|
||||
if not autres:
|
||||
continue # message adressé à moi seul : rien à attendre
|
||||
etat, avec = "attente", _avec(dernier.get("destinataires"))
|
||||
else:
|
||||
if mon not in (dernier.get("destinataires") or "").lower():
|
||||
continue # en copie seulement : rien à répondre
|
||||
etat = "reponse" if any(x["_moi"] for x in msgs[:-1]) else "a_repondre"
|
||||
avec = _avec(dernier.get("expediteur"))
|
||||
jours = max(0, (maintenant - dernier["_d"]).days) if dernier["_d"].tzinfo else 0
|
||||
sortie.append({
|
||||
"cle": cle, "sujet": PREFIXES.sub("", dernier.get("objet") or "").strip() or dernier.get("objet") or "",
|
||||
"avec": avec, "dernier_id": dernier["message_id"], "date": dernier.get("date"), "jours": jours, "etat": etat,
|
||||
"relancer": etat == "attente" and jours >= RELANCE_JOURS, "nb": len(msgs),
|
||||
"clos": clos.get(cle) == dernier["message_id"],
|
||||
})
|
||||
ordre = {"attente": 0, "reponse": 1, "a_repondre": 2}
|
||||
sortie.sort(key=lambda x: (ordre[x["etat"]], x["date"] or "") if x["etat"] == "attente" else (ordre[x["etat"]], _inverse(x["date"])))
|
||||
return sortie
|
||||
|
||||
|
||||
def _inverse(date: Optional[str]) -> str:
|
||||
return "".join(chr(0x10FFFF - ord(c)) for c in (date or ""))
|
||||
@@ -0,0 +1,105 @@
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import app, mirror_client
|
||||
from app.suivi import calculer_suivi, sujet_normalise
|
||||
|
||||
STATIC = Path(__file__).resolve().parent.parent / "app" / "static"
|
||||
MOI = "Nabil.Derouiche <Nabil.Derouiche@tunisietelecom.tn>"
|
||||
AUTRE = "Ali Ben Salah <ali@exemple.tn>"
|
||||
NOW = datetime(2026, 11, 18, 10, 0, tzinfo=timezone(timedelta(hours=1)))
|
||||
|
||||
|
||||
def mail(i, jour, objet, exp, dest, hh="09:00:00"):
|
||||
return {"message_id": f"m{i}", "date": f"2026-11-{jour:02d}T{hh}+01:00", "objet": objet, "expediteur": exp, "destinataires": dest, "etiquettes": []}
|
||||
|
||||
|
||||
def etats(mails, clos=None):
|
||||
return {i["cle"]: i for i in calculer_suivi(mails, "nabil.derouiche@", NOW, clos or {})}
|
||||
|
||||
|
||||
def test_sujet_normalise():
|
||||
assert sujet_normalise("RE: TR: Fwd : Demande de prix ") == "demande de prix"
|
||||
assert sujet_normalise("") == ""
|
||||
|
||||
|
||||
def test_en_attente_et_relance():
|
||||
e = etats([mail(1, 12, "Demande de prix", MOI, AUTRE)])
|
||||
i = e["demande de prix"]
|
||||
assert i["etat"] == "attente" and i["jours"] == 6 and i["relancer"] is True and i["avec"] == "Ali Ben Salah"
|
||||
e = etats([mail(1, 17, "Demande de prix", MOI, AUTRE)])
|
||||
assert e["demande de prix"]["relancer"] is False
|
||||
|
||||
|
||||
def test_reponse_recue_et_a_repondre():
|
||||
fil = [mail(1, 12, "Offre", MOI, AUTRE), mail(2, 14, "RE: Offre", AUTRE, MOI)]
|
||||
assert etats(fil)["offre"]["etat"] == "reponse"
|
||||
assert etats([mail(3, 15, "Question", AUTRE, MOI)])["question"]["etat"] == "a_repondre"
|
||||
|
||||
|
||||
def test_copie_seulement_ignore():
|
||||
assert etats([mail(4, 15, "Info", AUTRE, "autre@exemple.tn, copie@exemple.tn")]) == {}
|
||||
|
||||
|
||||
def test_ma_reponse_ferme_la_demande_recue():
|
||||
fil = [mail(5, 15, "Question", AUTRE, MOI), mail(6, 16, "RE: Question", MOI, AUTRE)]
|
||||
assert etats(fil)["question"]["etat"] == "attente"
|
||||
|
||||
|
||||
def test_clos_tient_jusqu_au_nouveau_message():
|
||||
fil = [mail(7, 12, "Sujet", MOI, AUTRE)]
|
||||
assert etats(fil, {"sujet": "m7"})["sujet"]["clos"] is True
|
||||
fil.append(mail(8, 16, "RE: Sujet", AUTRE, MOI))
|
||||
assert etats(fil, {"sujet": "m7"})["sujet"]["clos"] is False
|
||||
|
||||
|
||||
def test_sujet_vide_ignore_et_ordre():
|
||||
fil = [mail(9, 10, "", MOI, AUTRE), mail(10, 16, "B", MOI, AUTRE), mail(11, 11, "A", MOI, AUTRE), mail(12, 15, "C", AUTRE, MOI), mail(13, 16, "D", AUTRE, MOI)]
|
||||
sortie = calculer_suivi(fil, "nabil.derouiche@", NOW, {})
|
||||
assert [i["sujet"] for i in sortie] == ["A", "B", "D", "C"]
|
||||
|
||||
|
||||
def test_suivi_exige_le_jeton():
|
||||
assert TestClient(app).get("/api/v1/suivi").status_code == 401
|
||||
|
||||
|
||||
def test_endpoint_suivi_et_cloture(client, monkeypatch):
|
||||
jour = datetime.now(timezone(timedelta(hours=1))) - timedelta(days=5)
|
||||
iso = jour.strftime("%Y-%m-%dT09:00:00+01:00")
|
||||
envoye = {"message_id": "e1", "date": iso, "objet": "Besoin cables", "expediteur": MOI, "destinataires": AUTRE, "etiquettes": []}
|
||||
monkeypatch.setattr(mirror_client, "get_mails_since", lambda debut, max_items=800: [])
|
||||
monkeypatch.setattr(mirror_client, "get_sent_mails", lambda n=100: [envoye])
|
||||
j = client.get("/api/v1/suivi?jours=14").json()
|
||||
assert j["compte"] == {"attente": 1, "reponse": 0, "a_repondre": 0, "clos": 0}
|
||||
assert j["items"][0]["relancer"] is True
|
||||
assert client.post("/api/v1/suivi/clore", json={"cle": "besoin cables", "dernier_id": "e1"}).status_code == 200
|
||||
j = client.get("/api/v1/suivi?jours=14").json()
|
||||
assert j["compte"]["attente"] == 0 and j["compte"]["clos"] == 1 and j["items"][0]["clos"] is True
|
||||
client.post("/api/v1/suivi/rouvrir", json={"cle": "besoin cables"})
|
||||
assert client.get("/api/v1/suivi?jours=14").json()["compte"]["attente"] == 1
|
||||
|
||||
|
||||
def test_suivi_miroir_indisponible(client, monkeypatch):
|
||||
def casse(*a, **k): raise ConnectionError("x")
|
||||
monkeypatch.setattr(mirror_client, "get_mails_since", casse)
|
||||
assert client.get("/api/v1/suivi").status_code == 502
|
||||
|
||||
|
||||
def test_interface_suivi():
|
||||
js = (STATIC / "app.js").read_text(encoding="utf-8")
|
||||
assert "vueSuivi" in js and "chargerSuivi" in js and "innerHTML" not in js
|
||||
|
||||
|
||||
def test_envois_automatiques_et_a_soi_meme_ignores():
|
||||
fil = [mail(20, 15, "Rappel perso", MOI, MOI), mail(21, 15, "Alerte", "noreply@exemple.tn", MOI), mail(22, 15, "Vrai besoin", MOI, AUTRE)]
|
||||
assert set(etats(fil)) == {"vrai besoin"}
|
||||
|
||||
|
||||
def test_fraicheur_des_messages_envoyes(client, monkeypatch):
|
||||
ancien = {"message_id": "e0", "date": "2026-11-01T09:00:00+01:00", "objet": "Vieux", "expediteur": MOI, "destinataires": AUTRE, "etiquettes": []}
|
||||
monkeypatch.setattr(mirror_client, "get_mails_since", lambda debut, max_items=800: [])
|
||||
monkeypatch.setattr(mirror_client, "get_sent_mails", lambda n=100: [ancien])
|
||||
j = client.get("/api/v1/suivi").json()
|
||||
assert j["envoyes_a_jour"] is False and j["envoyes_jusqu_au"] == "2026-11-01"
|
||||
Reference in new issue
Block a user