072: file A valider, contexte de fil (Thread-Index), fil dans la lecture, filtre informations dans Suivi
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XGaEeTZLvHXfYPUNWkgYoi
This commit is contained in:
1 parent
5d98d08a8b
commit
c7c28f4079
5 files changed
+337
-16
No files matched your search
+162
-10
@@ -48,6 +48,10 @@ def _pret(conn) -> None:
|
||||
"CREATE TABLE IF NOT EXISTS analyses_ia ("
|
||||
"message_id TEXT PRIMARY KEY, categorie TEXT NOT NULL, confiance TEXT NOT NULL, resume TEXT NOT NULL, "
|
||||
"course TEXT, demande TEXT, objet TEXT, expediteur TEXT, date_mail TEXT, le TEXT NOT NULL, modele TEXT NOT NULL)")
|
||||
cols = {r[1] for r in conn.execute("PRAGMA table_info(analyses_ia)")}
|
||||
if "fil" not in cols:
|
||||
conn.execute("ALTER TABLE analyses_ia ADD COLUMN fil TEXT")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_analyses_fil ON analyses_ia (fil)")
|
||||
|
||||
|
||||
def _reglage(cle: str, db_path: Optional[str] = None) -> bool:
|
||||
@@ -76,7 +80,7 @@ def auto_actif(db_path: Optional[str] = None) -> bool:
|
||||
return ia.ia_active(db_path) and _reglage("ia_auto", db_path)
|
||||
|
||||
|
||||
def construire_messages(objet: str, expediteur: str, corps: str, categories: List[str]) -> list:
|
||||
def construire_messages(objet: str, expediteur: str, corps: str, categories: List[str], contexte: str = "") -> list:
|
||||
defs = "\n".join("- " + c + " : " + DEFINITIONS.get(c, "categorie de Nabil") for c in categories)
|
||||
consigne = (
|
||||
"Tu aides un responsable de la division Supply Chain de Tunisie Telecom (Sfax) a trier son courrier. "
|
||||
@@ -94,8 +98,14 @@ def construire_messages(objet: str, expediteur: str, corps: str, categories: Lis
|
||||
"entre Sfax et Tunis. Une demande est reelle seulement si quelqu'un attend une action ou une reponse de Nabil. "
|
||||
"N'invente rien : si l'information est absente, laisse vide ou null."
|
||||
)
|
||||
if contexte:
|
||||
consigne += ("\nLe mail fait partie d'une conversation : un contexte (resumes des mails precedents du meme fil, "
|
||||
"et categorie choisie par Nabil quand elle existe) est fourni. Utilise-le : un fil deja range par Nabil "
|
||||
"garde sa categorie, et un mail de suite sans nouvelle demande n'est pas une nouvelle course.")
|
||||
texte = ("Expediteur : " + (expediteur or "(inconnu)") + "\nObjet : " + (objet or "(vide)") + "\n\n"
|
||||
+ (corps or "")[:ia.MAX_TEXTE])
|
||||
if contexte:
|
||||
texte = "Contexte du fil :\n" + contexte + "\n\nMail a analyser :\n" + texte
|
||||
return [{"role": "system", "content": consigne}, {"role": "user", "content": texte}]
|
||||
|
||||
|
||||
@@ -147,30 +157,41 @@ def _categories(db_path: Optional[str] = None) -> List[str]:
|
||||
return [c for c in cats if c and c != ia.A_CLASSER]
|
||||
|
||||
|
||||
def analyser(objet: str, expediteur: str, corps: str, db_path: Optional[str] = None) -> Dict[str, Any]:
|
||||
def analyser(objet: str, expediteur: str, corps: str, db_path: Optional[str] = None, contexte: str = "") -> Dict[str, Any]:
|
||||
"""Appelle PrivAiTe. Leve IAIndisponible si le service ne repond pas (aucun repli)."""
|
||||
cats = _categories(db_path)
|
||||
rep = ia.appeler_privaite(construire_messages(objet, expediteur, corps, cats), max_tokens=450)
|
||||
rep = ia.appeler_privaite(construire_messages(objet, expediteur, corps, cats, contexte), max_tokens=450)
|
||||
return lire_fiche(rep, cats)
|
||||
|
||||
|
||||
def cle_fil(thread_index: str) -> Optional[str]:
|
||||
"""Cle de conversation Exchange : les 22 premiers octets de Thread-Index sont communs a tout le fil,
|
||||
meme quand l'objet change. Vide si l'en-tete est absent ou illisible."""
|
||||
import base64
|
||||
try:
|
||||
brut = base64.b64decode((thread_index or "").strip() + "=" * (-len(thread_index.strip()) % 4))
|
||||
except Exception:
|
||||
return None
|
||||
return brut[:22].hex() if len(brut) >= 22 else None
|
||||
|
||||
|
||||
def enregistrer(message_id: str, fiche: Dict[str, Any], objet: str = "", expediteur: str = "",
|
||||
date_mail: str = "", db_path: Optional[str] = None) -> None:
|
||||
date_mail: str = "", db_path: Optional[str] = None, fil: Optional[str] = None) -> None:
|
||||
conn = _db.get_connection(db_path)
|
||||
try:
|
||||
_pret(conn)
|
||||
with conn:
|
||||
conn.execute(
|
||||
"INSERT INTO analyses_ia (message_id, categorie, confiance, resume, course, demande, objet, "
|
||||
"expediteur, date_mail, le, modele) VALUES (?,?,?,?,?,?,?,?,?,?,?) "
|
||||
"expediteur, date_mail, le, modele, fil) VALUES (?,?,?,?,?,?,?,?,?,?,?,?) "
|
||||
"ON CONFLICT(message_id) DO UPDATE SET categorie=excluded.categorie, confiance=excluded.confiance, "
|
||||
"resume=excluded.resume, course=excluded.course, demande=excluded.demande, le=excluded.le, "
|
||||
"modele=excluded.modele",
|
||||
"modele=excluded.modele, fil=COALESCE(excluded.fil, fil)",
|
||||
(message_id, fiche["categorie"], fiche["confiance"], fiche["resume"],
|
||||
json.dumps(fiche["course"], ensure_ascii=False) if fiche["course"] else None,
|
||||
json.dumps(fiche["demande"], ensure_ascii=False),
|
||||
_court(objet, 200), _court(expediteur, 120), _court(date_mail, 40),
|
||||
get_tunis_now_iso(), ia.IA_MODELE))
|
||||
get_tunis_now_iso(), ia.IA_MODELE, fil))
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@@ -214,6 +235,36 @@ def lister(jour: Optional[str] = None, depuis: Optional[str] = None, n: int = 10
|
||||
conn.close()
|
||||
|
||||
|
||||
def membres_fil(fil: Optional[str], message_id: str = "", db_path: Optional[str] = None, n: int = 8) -> List[Dict[str, Any]]:
|
||||
"""Autres mails deja analyses du meme fil, du plus ancien au plus recent, avec la categorie choisie par Nabil."""
|
||||
if not fil:
|
||||
return []
|
||||
conn = _db.get_connection(db_path)
|
||||
try:
|
||||
_pret(conn)
|
||||
conn.row_factory = sqlite3.Row
|
||||
lignes = conn.execute("SELECT * FROM analyses_ia WHERE fil=? AND message_id<>? ORDER BY date_mail DESC LIMIT ?",
|
||||
(fil, message_id, max(1, min(n, 20)))).fetchall()
|
||||
sortie = []
|
||||
for r in reversed(lignes):
|
||||
f = _ligne(r)
|
||||
c = conn.execute("SELECT categorie, source FROM classements WHERE message_id=?", (r["message_id"],)).fetchone()
|
||||
f["choix_nabil"] = c[0] if c and c[1] == "manuel" else None
|
||||
sortie.append(f)
|
||||
return sortie
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def contexte_fil(fil: Optional[str], message_id: str, db_path: Optional[str] = None) -> str:
|
||||
lignes = []
|
||||
for f in membres_fil(fil, message_id, db_path, 5):
|
||||
lignes.append("- " + (f["date"] or "")[:10] + " | " + _court(f["objet"], 100) + " | "
|
||||
+ ("categorie choisie par Nabil : " + f["choix_nabil"] if f["choix_nabil"] else "categorie proposee : " + f["categorie"])
|
||||
+ " | " + _court(f["resume"], 220))
|
||||
return "\n".join(lignes)
|
||||
|
||||
|
||||
def _lire_mail(mirror_client, message_id: str):
|
||||
res = mirror_client.get_mail(message_id)
|
||||
d = res.get("donnees") if isinstance(res, dict) else None
|
||||
@@ -228,7 +279,8 @@ def _lire_mail(mirror_client, message_id: str):
|
||||
date = parsedate_to_datetime(date).astimezone(ZoneInfo("Africa/Tunis")).isoformat()
|
||||
except Exception:
|
||||
pass
|
||||
return {"objet": h("Subject"), "de": h("From"), "date": date, "corps": str(d.get("corps_texte") or "")}
|
||||
return {"objet": h("Subject"), "de": h("From"), "date": date, "corps": str(d.get("corps_texte") or ""),
|
||||
"fil": cle_fil(h("Thread-Index"))}
|
||||
|
||||
|
||||
def analyser_mail(mirror_client, message_id: str, db_path: Optional[str] = None,
|
||||
@@ -236,10 +288,10 @@ def analyser_mail(mirror_client, message_id: str, db_path: Optional[str] = None,
|
||||
m = _lire_mail(mirror_client, message_id)
|
||||
if m is None:
|
||||
raise LookupError("mail introuvable")
|
||||
fiche = analyser(m["objet"], m["de"], m["corps"], db_path)
|
||||
fiche = analyser(m["objet"], m["de"], m["corps"], db_path, contexte_fil(m.get("fil"), message_id, db_path))
|
||||
meta = meta or {}
|
||||
enregistrer(message_id, fiche, meta.get("objet") or m["objet"], meta.get("expediteur") or m["de"],
|
||||
meta.get("date") or m["date"], db_path)
|
||||
meta.get("date") or m["date"], db_path, m.get("fil"))
|
||||
return lire(message_id, db_path)
|
||||
|
||||
|
||||
@@ -285,6 +337,81 @@ def demarrer_automatique(mirror_client, intervalle: int = 180) -> None:
|
||||
threading.Thread(target=boucle, daemon=True, name="courrier-ia-auto").start()
|
||||
|
||||
|
||||
|
||||
# ---------- File « A valider » : propositions de l'IA que Nabil accepte ou refuse ----------
|
||||
|
||||
def _pret_decisions(conn) -> None:
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS decisions_ia (message_id TEXT NOT NULL, type TEXT NOT NULL, "
|
||||
"decision TEXT NOT NULL, le TEXT NOT NULL, PRIMARY KEY (message_id, type))")
|
||||
|
||||
|
||||
def a_valider(jours: int = 14, db_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||
"""Propositions en attente : une categorie differente du classement actuel (jamais sur un classement
|
||||
manuel), une course possible pas encore creee. Une proposition deja acceptee ou refusee ne revient pas."""
|
||||
depuis = (_date.fromisoformat(get_tunis_now_iso()[:10]) - timedelta(days=max(1, min(jours, 60)))).isoformat()
|
||||
conn = _db.get_connection(db_path)
|
||||
try:
|
||||
_pret(conn); _pret_decisions(conn)
|
||||
conn.row_factory = sqlite3.Row
|
||||
decides = {(r[0], r[1]) for r in conn.execute("SELECT message_id, type FROM decisions_ia")}
|
||||
cl = {r[0]: (r[1], r[2]) for r in conn.execute("SELECT message_id, categorie, source FROM classements")}
|
||||
try:
|
||||
courses = {r[0] for r in conn.execute("SELECT message_id FROM courses WHERE message_id IS NOT NULL")}
|
||||
except sqlite3.OperationalError:
|
||||
courses = set()
|
||||
lignes = conn.execute("SELECT * FROM analyses_ia WHERE date_mail >= ? ORDER BY date_mail DESC LIMIT 300",
|
||||
(depuis,)).fetchall()
|
||||
sortie: List[Dict[str, Any]] = []
|
||||
for r in lignes:
|
||||
f = _ligne(r); mid = f["message_id"]
|
||||
base = {"message_id": mid, "objet": f["objet"], "expediteur": f["expediteur"], "date": f["date"],
|
||||
"resume": f["resume"], "confiance": f["confiance"]}
|
||||
actuelle, source = cl.get(mid, ("À classer", "regle"))
|
||||
if (mid, "categorie") not in decides and source != "manuel" and f["categorie"] not in ("À classer", actuelle):
|
||||
sortie.append(dict(base, type="categorie", actuelle=actuelle, propose=f["categorie"]))
|
||||
c = f["course"]
|
||||
if c and (mid, "course") not in decides and mid not in courses:
|
||||
liste = ", ".join((c.get("objets") or []) + (c.get("documents") or []))
|
||||
if liste:
|
||||
sortie.append(dict(base, type="course", propose=liste, sens=c.get("sens") or "tunis_sfax"))
|
||||
return sortie
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def decider(message_id: str, type_: str, decision: str, db_path: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""Accepter applique la proposition (classement manuel ou course) ; refuser la ferme. Toujours un clic."""
|
||||
if type_ not in ("categorie", "course") or decision not in ("accepter", "refuser"):
|
||||
raise ValueError("decision invalide")
|
||||
f = lire(message_id, db_path)
|
||||
if not f:
|
||||
raise LookupError("analyse introuvable")
|
||||
resultat: Dict[str, Any] = {"ok": True}
|
||||
if decision == "accepter":
|
||||
if type_ == "categorie":
|
||||
from app.classifier import manual_classify_and_propose
|
||||
manual_classify_and_propose(message_id, f["categorie"], {"expediteur": f["expediteur"], "objet": f["objet"],
|
||||
"date": f["date"]}, db_path=db_path)
|
||||
else:
|
||||
c = f["course"] or {}
|
||||
liste = ", ".join((c.get("objets") or []) + (c.get("documents") or []))
|
||||
if not liste:
|
||||
raise LookupError("pas de course proposee")
|
||||
resultat["course"] = _db.add_course(liste[:300], c.get("sens") or "tunis_sfax", message_id,
|
||||
(f["objet"] or "")[:500], (f["expediteur"] or "")[:300],
|
||||
(f["date"] or "")[:40], db_path=db_path)
|
||||
conn = _db.get_connection(db_path)
|
||||
try:
|
||||
_pret_decisions(conn)
|
||||
with conn:
|
||||
conn.execute("INSERT INTO decisions_ia (message_id, type, decision, le) VALUES (?, ?, ?, ?) "
|
||||
"ON CONFLICT(message_id, type) DO UPDATE SET decision=excluded.decision, le=excluded.le",
|
||||
(message_id, type_, decision, get_tunis_now_iso()))
|
||||
finally:
|
||||
conn.close()
|
||||
return resultat
|
||||
|
||||
|
||||
def creer_routeur(mirror_client) -> APIRouter:
|
||||
router = APIRouter(prefix="/ia")
|
||||
|
||||
@@ -344,6 +471,31 @@ def creer_routeur(mirror_client) -> APIRouter:
|
||||
debut = (_date.fromisoformat(get_tunis_now_iso()[:10]) - timedelta(days=jours)).isoformat()
|
||||
return {"analyses": lister(depuis=debut, n=n)}
|
||||
|
||||
@router.get("/fil")
|
||||
def lire_fil(id: str = Query(..., min_length=1, max_length=400)):
|
||||
f = lire(id)
|
||||
conn = _db.get_connection()
|
||||
try:
|
||||
_pret(conn)
|
||||
r = conn.execute("SELECT fil FROM analyses_ia WHERE message_id=?", (id,)).fetchone()
|
||||
finally:
|
||||
conn.close()
|
||||
fil = r[0] if r else None
|
||||
return {"fil": bool(fil), "mails": membres_fil(fil, id, None, 12)}
|
||||
|
||||
@router.get("/a-valider")
|
||||
def liste_a_valider(jours: int = Query(14, ge=1, le=60)):
|
||||
return {"items": a_valider(jours)}
|
||||
|
||||
@router.post("/decision")
|
||||
def decision_ia(corps: Dict[str, Any]):
|
||||
try:
|
||||
return decider(str(corps.get("message_id") or ""), str(corps.get("type") or ""), str(corps.get("decision") or ""))
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=422, detail="Decision invalide.")
|
||||
except LookupError:
|
||||
raise HTTPException(status_code=404, detail="Proposition introuvable.")
|
||||
|
||||
return router
|
||||
|
||||
|
||||
|
||||
@@ -379,3 +379,17 @@ h1, h2, h3, p { margin: 0; }
|
||||
.ligne-ia { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 14px; }
|
||||
.ligne-ia + .ligne-ia { border-top: 1px solid var(--ny-trait); }
|
||||
.ligne-ia p { margin: 2px 0 0; }
|
||||
|
||||
.liste-valider { padding: 4px 0; }
|
||||
.ligne-valider { display: flex; gap: 16px; align-items: flex-start; justify-content: space-between; padding: 12px 16px; border-bottom: 1px solid var(--ny-trait); }
|
||||
.ligne-valider:last-child { border-bottom: 0; }
|
||||
.lv-texte { min-width: 0; flex: 1; font: 400 14px/20px var(--ny-police); }
|
||||
.lv-texte b { font-weight: 600; }
|
||||
.lv-texte p { margin: 2px 0; overflow-wrap: anywhere; }
|
||||
.lv-objet { color: var(--ny-texte-2, inherit); }
|
||||
.lv-actions { display: flex; gap: 8px; flex-shrink: 0; }
|
||||
@media (max-width: 640px) { .ligne-valider { flex-direction: column; } .lv-actions { width: 100%; } .lv-actions button { flex: 1; } }
|
||||
|
||||
.lect-ia-fil { margin-top: 8px; font: 400 13px/19px var(--ny-police); }
|
||||
.lect-ia-fil summary { cursor: pointer; font-weight: 600; }
|
||||
.lect-ia-fil p { margin: 6px 0 6px 12px; }
|
||||
+62
-6
@@ -12,6 +12,7 @@
|
||||
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',
|
||||
avalider: 'M22 11.08V12a10 10 0 1 1-5.93-9.14|m9 11 3 3L22 4',
|
||||
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',
|
||||
@@ -19,13 +20,13 @@
|
||||
panneau: 'M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z|M9 3v18'
|
||||
};
|
||||
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]
|
||||
['tri', 'Tri du jour', true], ['avalider', 'À valider', 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: '' } };
|
||||
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: {}, avalider: { items: [], etat: 'chargement', ia: true }, 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()); }
|
||||
@@ -156,6 +157,7 @@
|
||||
else if (vue === 'courses') chargerCourses();
|
||||
else if (vue === 'suivi') chargerSuivi();
|
||||
else if (vue === 'asuivre') chargerASuivre();
|
||||
else if (vue === 'avalider') chargerAValider();
|
||||
else if (vue === 'recherche') { rendre(); var ch = document.getElementById('rech-q'); if (ch) ch.focus(); return; }
|
||||
else rendre();
|
||||
document.getElementById('principal').focus();
|
||||
@@ -327,7 +329,8 @@
|
||||
NAV.forEach(function (n) {
|
||||
corps.appendChild(h('button', { type: 'button', class: 'nav-btn', title: reduite ? n[1] : null, 'aria-current': S.vue === n[0] ? 'page' : null, onclick: function () { fermerMenu(false); allerA(n[0]); } },
|
||||
icone(n[0]), h('span', { class: 'nav-txt' }, n[1]),
|
||||
n[0] === 'asuivre' && nb > 0 ? h('span', { class: 'nav-n', text: String(nb) }) : null));
|
||||
n[0] === 'asuivre' && nb > 0 ? h('span', { class: 'nav-n', text: String(nb) }) : null,
|
||||
n[0] === 'avalider' && S.avalider.items.length > 0 ? h('span', { class: 'nav-n', text: String(S.avalider.items.length) }) : null));
|
||||
});
|
||||
var pt = document.getElementById('nav-point');
|
||||
if (pt) pt.hidden = !(nb > 0);
|
||||
@@ -459,6 +462,12 @@
|
||||
}
|
||||
if (f.demande && f.demande.reelle) sect.appendChild(h('p', null, 'À faire : ', h('strong', { text: f.demande.action + (f.demande.echeance ? ' · avant le ' + f.demande.echeance : '') })));
|
||||
else if (f.demande) sect.appendChild(h('p', { class: 'lect-ia-info', text: 'Information : aucune action attendue.' }));
|
||||
api('/ia/fil?id=' + encodeURIComponent(id)).then(function (r) {
|
||||
var ms = r.mails || []; if (!ms.length) return;
|
||||
var det = h('details', { class: 'lect-ia-fil' }, h('summary', { text: 'Dans ce fil : ' + ms.length + ' autre' + (ms.length > 1 ? 's' : '') + ' mail' + (ms.length > 1 ? 's' : '') + ' analysé' + (ms.length > 1 ? 's' : '') }));
|
||||
ms.forEach(function (x) { det.appendChild(h('p', null, h('b', { text: (x.date || '').slice(0, 10).split('-').reverse().join('/') + ' · ' + (x.objet || '(sans objet)') }), x.choix_nabil ? ' · rangé par vous en ' + x.choix_nabil : '', h('br'), x.resume || '')); });
|
||||
sect.appendChild(det);
|
||||
}).catch(function () { /* pas de fil connu */ });
|
||||
}
|
||||
function proposerAnalyse() {
|
||||
sect.textContent = '';
|
||||
@@ -838,7 +847,9 @@
|
||||
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(); })
|
||||
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();
|
||||
return api('/ia/analyses?jours=' + V.jours + '&n=300').then(function (a) { var m = {}; (a.analyses || []).forEach(function (x) { m[x.message_id] = x; }); V.ia = m; rendre(); }).catch(function () { /* IA absente : le suivi reste complet */ });
|
||||
})
|
||||
.catch(function (e) { if (e.message === 'session') return; V.etat = 'erreur'; rendre(); });
|
||||
}
|
||||
function cloreSuivi(it, clore) {
|
||||
@@ -862,7 +873,11 @@
|
||||
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); });
|
||||
var iaMap = V.ia || {}, nbIA = Object.keys(iaMap).length;
|
||||
if (nbIA) frag.appendChild(h('section', { class: 'carte repartition', 'aria-label': 'Lecture par l\'IA' }, h('div', { class: 'ligne-ia' }, h('div', null, h('b', { text: 'Masquer les simples informations' }), h('p', { class: 'lect-ia-info', text: 'Cache les fils que l\'IA a lus comme sans action attendue. Les fils non analysés restent affichés.' })),
|
||||
h('button', { type: 'button', class: 'interrupteur', role: 'switch', 'aria-checked': V.masquerInfo ? 'true' : 'false', 'aria-label': 'Masquer les simples informations', onclick: function () { V.masquerInfo = !V.masquerInfo; rendre(); } }, h('span', { class: 'piste' }, h('span', { class: 'bouton' }))))));
|
||||
function lectureIA(i) { var a = iaMap[i.dernier_id]; return a && a.demande ? a.demande : null; }
|
||||
var vis = V.items.filter(function (i) { return V.filtre === 'clos' ? i.clos : (!i.clos && i.etat === V.filtre); }).filter(function (i) { var d = lectureIA(i); return !(V.masquerInfo && d && d.reelle === false); });
|
||||
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;
|
||||
@@ -872,6 +887,8 @@
|
||||
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 dIA = lectureIA(it);
|
||||
if (dIA) badges.appendChild(h('span', { class: 'etq', text: dIA.reelle ? 'Demande réelle' + (dIA.action ? ' : ' + dIA.action : '') : 'Information' }));
|
||||
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'));
|
||||
@@ -962,6 +979,44 @@
|
||||
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 chargerAValider(silencieux) {
|
||||
var V = S.avalider;
|
||||
if (!silencieux) { V.etat = 'chargement'; rendre(); }
|
||||
return api('/ia/a-valider').then(function (r) { V.items = r.items || []; V.etat = 'ok'; rendreNav(); if (!silencieux) rendre(); })
|
||||
.catch(function (e) { if (e.message === 'session' || silencieux) return; V.etat = 'erreur'; rendre(); });
|
||||
}
|
||||
function deciderIA(it, decision) {
|
||||
var V = S.avalider, avant = V.items.slice();
|
||||
V.items = V.items.filter(function (x) { return !(x.message_id === it.message_id && x.type === it.type); }); rendreNav(); rendre();
|
||||
api('/ia/decision', { method: 'POST', body: { message_id: it.message_id, type: it.type, decision: decision } }).then(function () {
|
||||
flash(decision === 'refuser' ? 'Proposition refusée.' : it.type === 'course' ? 'Course ajoutée.' : 'Catégorie appliquée : ' + it.propose + '.');
|
||||
if (it.type === 'course' && decision === 'accepter') S.courses.etat = 'chargement';
|
||||
}).catch(function (e) { if (e.message === 'session') return; V.items = avant; rendreNav(); rendre(); flash('Action impossible. Réessayez.'); });
|
||||
}
|
||||
function vueAValider() {
|
||||
var V = S.avalider, frag = document.createDocumentFragment();
|
||||
frag.appendChild(h('header', { class: 'entete' }, h('h1', null, 'À valider'),
|
||||
h('div', { class: 'entete-actions' }, h('span', { class: 'lect-ia-info', text: 'Propositions de l\'IA lues dans le contenu des mails. Rien n\'est appliqué sans votre clic.' }))));
|
||||
if (S.notif) frag.appendChild(h('div', { class: 'notif', role: 'status', text: S.notif }));
|
||||
if (V.etat === 'chargement') { frag.appendChild(h('section', { class: 'carte squelette', 'aria-busy': 'true' }, h('div', { class: 'sq-statut', role: 'status', text: 'Lecture des propositions…' }))); return frag; }
|
||||
if (V.etat === 'erreur') { frag.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Chargement impossible'), h('button', { type: 'button', class: 'btn-plein', onclick: function () { chargerAValider(); } }, 'Réessayer'))); return frag; }
|
||||
if (!V.items.length) {
|
||||
frag.appendChild(h('section', { class: 'carte limite-l' }, h('p', null, 'Aucune proposition en attente.'), h('p', { class: 'lect-ia-info', text: 'Les propositions apparaissent quand l\'IA est activée (Règles) et qu\'elle a analysé des mails.' })));
|
||||
return frag;
|
||||
}
|
||||
var liste = h('section', { class: 'carte limite-l liste-valider', 'aria-label': 'Propositions' });
|
||||
V.items.forEach(function (it) {
|
||||
var titre = it.type === 'course' ? 'Course possible : ' + it.propose + ' (' + (SENS[it.sens] || it.sens) + ')' : 'Classer en ' + it.propose + (it.actuelle && it.actuelle !== 'À classer' ? ' (actuellement ' + it.actuelle + ')' : '');
|
||||
liste.appendChild(h('article', { class: 'ligne-valider' },
|
||||
h('div', { class: 'lv-texte' }, h('b', { text: titre }), h('p', { class: 'lv-objet', text: (it.objet || '(sans objet)') + ' · ' + (it.expediteur || '').replace(/<.*>/, '').trim() }), it.resume ? h('p', { class: 'lect-ia-info', text: it.resume }) : null),
|
||||
h('div', { class: 'lv-actions' },
|
||||
h('button', { type: 'button', class: 'btn-plein', onclick: function () { deciderIA(it, 'accepter'); } }, it.type === 'course' ? 'Ajouter' : 'Accepter'),
|
||||
h('button', { type: 'button', class: 'btn-ligne', onclick: function () { deciderIA(it, 'refuser'); } }, 'Refuser'))));
|
||||
});
|
||||
frag.appendChild(liste);
|
||||
return frag;
|
||||
}
|
||||
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'))));
|
||||
@@ -1090,7 +1145,7 @@
|
||||
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);
|
||||
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 === 'avalider' ? vueAValider() : 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';
|
||||
@@ -1125,4 +1180,5 @@
|
||||
rendre();
|
||||
chargerMails();
|
||||
chargerASuivre(true);
|
||||
chargerAValider(true);
|
||||
})();
|
||||
@@ -0,0 +1,58 @@
|
||||
import pytest
|
||||
from app import analyse as a
|
||||
from app.classifier import manual_classify_and_propose
|
||||
from app.config import get_tunis_now_iso
|
||||
from app.db import list_courses, get_classement
|
||||
|
||||
pytestmark = pytest.mark.regles_off
|
||||
|
||||
|
||||
def _fiche(cat="Pb PO", course=None):
|
||||
return {"categorie": cat, "confiance": "haute", "resume": "Resume.", "course": course,
|
||||
"demande": {"reelle": False, "action": "", "echeance": ""}}
|
||||
|
||||
|
||||
def _maintenant():
|
||||
return get_tunis_now_iso()[:19]
|
||||
|
||||
|
||||
def test_proposition_categorie_puis_acceptation(temp_db):
|
||||
a.enregistrer("m1", _fiche(), "PO 123", "x@tt.tn", _maintenant(), temp_db)
|
||||
items = a.a_valider(db_path=temp_db)
|
||||
assert [(i["type"], i["propose"]) for i in items] == [("categorie", "Pb PO")]
|
||||
a.decider("m1", "categorie", "accepter", temp_db)
|
||||
c = get_classement("m1", temp_db)
|
||||
assert c["categorie"] == "Pb PO" and c["source"] == "manuel"
|
||||
assert a.a_valider(db_path=temp_db) == []
|
||||
|
||||
|
||||
def test_refus_ne_revient_pas(temp_db):
|
||||
a.enregistrer("m2", _fiche("Box 5G"), "Box", "x@tt.tn", _maintenant(), temp_db)
|
||||
a.decider("m2", "categorie", "refuser", temp_db)
|
||||
assert a.a_valider(db_path=temp_db) == []
|
||||
assert get_classement("m2", temp_db) is None or get_classement("m2", temp_db)["categorie"] == "À classer"
|
||||
|
||||
|
||||
def test_classement_manuel_jamais_propose(temp_db):
|
||||
manual_classify_and_propose("m3", "Tunis", {"expediteur": "a@b", "objet": "x"}, db_path=temp_db)
|
||||
a.enregistrer("m3", _fiche("Pb PO"), "x", "a@b", _maintenant(), temp_db)
|
||||
assert a.a_valider(db_path=temp_db) == []
|
||||
|
||||
|
||||
def test_course_acceptee_creee_une_fois(temp_db):
|
||||
course = {"objets": ["dossier signé"], "documents": [], "sens": "sfax_tunis"}
|
||||
a.enregistrer("m4", _fiche("À classer", course), "Dossier", "x@tt.tn", _maintenant(), temp_db)
|
||||
items = a.a_valider(db_path=temp_db)
|
||||
assert [(i["type"], i["sens"]) for i in items] == [("course", "sfax_tunis")]
|
||||
r = a.decider("m4", "course", "accepter", temp_db)
|
||||
assert r["course"]["message_id"] == "m4"
|
||||
assert len([k for k in list_courses(None, db_path=temp_db) if k["message_id"] == "m4"]) == 1
|
||||
assert a.a_valider(db_path=temp_db) == []
|
||||
|
||||
|
||||
def test_decision_invalide(temp_db):
|
||||
a.enregistrer("m5", _fiche(), "x", "x", _maintenant(), temp_db)
|
||||
with pytest.raises(ValueError):
|
||||
a.decider("m5", "autre", "accepter", temp_db)
|
||||
with pytest.raises(LookupError):
|
||||
a.decider("inconnu", "categorie", "accepter", temp_db)
|
||||
@@ -0,0 +1,41 @@
|
||||
import base64
|
||||
import pytest
|
||||
from app import analyse as a
|
||||
from app.classifier import manual_classify_and_propose
|
||||
|
||||
pytestmark = pytest.mark.regles_off
|
||||
|
||||
|
||||
def _ti(prefix: bytes, suffix: bytes = b"") -> str:
|
||||
return base64.b64encode(prefix.ljust(22, b"\0") + suffix).decode()
|
||||
|
||||
|
||||
def test_cle_fil_commune_malgre_suffixe_different():
|
||||
assert a.cle_fil(_ti(b"abc", b"12345")) == a.cle_fil(_ti(b"abc", b"zzzzzz"))
|
||||
assert a.cle_fil(_ti(b"abc")) != a.cle_fil(_ti(b"abd"))
|
||||
|
||||
|
||||
def test_cle_fil_illisible():
|
||||
assert a.cle_fil("") is None and a.cle_fil("!!!") is None
|
||||
|
||||
|
||||
def _fiche(cat="Tunis", resume="R."):
|
||||
return {"categorie": cat, "confiance": "haute", "resume": resume, "course": None,
|
||||
"demande": {"reelle": False, "action": "", "echeance": ""}}
|
||||
|
||||
|
||||
def test_contexte_fil_reprend_le_choix_de_nabil(temp_db):
|
||||
fil = a.cle_fil(_ti(b"fil1"))
|
||||
a.enregistrer("m1", _fiche("Tunis", "Course demandee pour lundi."), "Course Tunis", "x", "2026-11-18T10:00:00", temp_db, fil)
|
||||
manual_classify_and_propose("m1", "Tunis", {"expediteur": "x", "objet": "Course Tunis"}, db_path=temp_db)
|
||||
a.enregistrer("m2", _fiche("Sans objet"), "Re: autre objet", "x", "2026-11-19T10:00:00", temp_db, fil)
|
||||
ctx = a.contexte_fil(fil, "m2", temp_db)
|
||||
assert "categorie choisie par Nabil : Tunis" in ctx and "Course demandee pour lundi." in ctx
|
||||
assert a.contexte_fil(fil, "m1", temp_db).count("\n") == 0
|
||||
assert a.contexte_fil(None, "m2", temp_db) == ""
|
||||
|
||||
|
||||
def test_prompt_mentionne_le_contexte():
|
||||
m = a.construire_messages("o", "e", "corps", ["Tunis"], "- ctx")
|
||||
assert "Contexte du fil" in m[1]["content"] and "conversation" in m[0]["content"]
|
||||
assert "Contexte du fil" not in a.construire_messages("o", "e", "corps", ["Tunis"])[1]["content"]
|
||||
Reference in new issue
Block a user