Courrier v2.2 (tt-2026-11-072, palier 2) : analyse IA structuree par mail
Fiche unique par mail via PrivAiTe (categorie proposee, confiance, resume, course, demande reelle), stockee sans corps de mail ; mode automatique distinct, desactive par defaut ; bloc Analyse IA dans la lecture (proposition, jamais appliquee sans clic) ; reglages IA dans Regles ; 20 tests (162 verts au total). 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
d1a1f412d3
commit
883b4e1745
5 files changed
+589
-4
No files matched your search
+347
@@ -0,0 +1,347 @@
|
||||
"""Couche IA de Courrier, palier 2 (tt-2026-11-072) : analyse structuree d'un mail.
|
||||
|
||||
Un seul appel a PrivAiTe (alias courrier-main) renvoie une fiche : categorie proposee, resume,
|
||||
course eventuelle (objets et documents a rapporter ou apporter), demande reelle ou simple information.
|
||||
Regles fermes, heritees du palier 1 :
|
||||
- tout passe par ia.appeler_privaite (seul point de sortie vers un modele), refus net si PrivAiTe est injoignable ;
|
||||
- interrupteur ia_actif obligatoire ; mode automatique ia_auto distinct, desactive par defaut ;
|
||||
- rien n'est applique : la categorie reste une suggestion, la course reste une proposition ;
|
||||
- le corps du mail n'est jamais stocke ni journalise : seule la fiche produite est conservee ;
|
||||
- aucun jeton, aucune adresse dans les journaux.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from datetime import date as _date, timedelta
|
||||
from email.utils import parsedate_to_datetime
|
||||
from typing import Any, Dict, List, Optional
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
|
||||
from app import db as _db
|
||||
from app import ia
|
||||
from app.config import get_tunis_now_iso
|
||||
|
||||
log = logging.getLogger("courrier.analyse")
|
||||
|
||||
MAX_RESUME = 600
|
||||
MAX_ITEM = 160
|
||||
MAX_ITEMS = 12
|
||||
SENS_VALIDES = ("tunis_sfax", "sfax_tunis")
|
||||
|
||||
DEFINITIONS = {
|
||||
"Tunis": "mails sur les courses, colis, documents ou personnes a deplacer entre Sfax et Tunis",
|
||||
"Demande FB": "demandes d'achat ou de besoin venant de la direction financiere et budgetaire (FB)",
|
||||
"CI": "mails de la cellule ou du circuit CI (controle interne, commandes internes)",
|
||||
"Câbles": "mails sur les cables, fibres, equipements reseau et leur approvisionnement",
|
||||
"Sans objet": "mails sans action pour Nabil : publicite, informations generales, copie sans suite",
|
||||
}
|
||||
|
||||
|
||||
def _pret(conn) -> None:
|
||||
ia._pret(conn)
|
||||
conn.execute(
|
||||
"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)")
|
||||
|
||||
|
||||
def _reglage(cle: str, db_path: Optional[str] = None) -> bool:
|
||||
conn = _db.get_connection(db_path)
|
||||
try:
|
||||
_pret(conn)
|
||||
r = conn.execute("SELECT valeur FROM reglages WHERE cle=?", (cle,)).fetchone()
|
||||
return bool(r and r[0] == "1")
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _regler(cle: str, actif: bool, db_path: Optional[str] = None) -> None:
|
||||
conn = _db.get_connection(db_path)
|
||||
try:
|
||||
_pret(conn)
|
||||
with conn:
|
||||
conn.execute("INSERT INTO reglages (cle, valeur, le) VALUES (?, ?, ?) "
|
||||
"ON CONFLICT(cle) DO UPDATE SET valeur=excluded.valeur, le=excluded.le",
|
||||
(cle, "1" if actif else "0", get_tunis_now_iso()))
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
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:
|
||||
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. "
|
||||
"Analyse le mail et reponds UNIQUEMENT par un objet JSON sur une ligne, sans texte autour, avec ces cles :\n"
|
||||
'{"categorie": <nom exact parmi la liste>, "confiance": "haute"|"moyenne"|"basse", '
|
||||
'"resume": <2 phrases maximum en francais, faits utiles seulement>, '
|
||||
'"course": null ou {"sens": "tunis_sfax"|"sfax_tunis", "objets": [<objets a rapporter ou apporter>], '
|
||||
'"documents": [<documents a rapporter ou apporter>]}, '
|
||||
'"demande": {"reelle": true|false, "action": <ce que Nabil doit faire, vide si information>, '
|
||||
'"echeance": <JJ/MM/AAAA ou null>}}\n'
|
||||
"Categories :\n" + defs + "\n"
|
||||
"Choisis la categorie la plus probable, meme avec une confiance moyenne ; n'utilise "
|
||||
+ ia.A_CLASSER + " que s'il n'existe vraiment aucun indice. "
|
||||
"Une course existe seulement si le mail demande de rapporter, apporter ou deposer un objet ou un document "
|
||||
"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."
|
||||
)
|
||||
texte = ("Expediteur : " + (expediteur or "(inconnu)") + "\nObjet : " + (objet or "(vide)") + "\n\n"
|
||||
+ (corps or "")[:ia.MAX_TEXTE])
|
||||
return [{"role": "system", "content": consigne}, {"role": "user", "content": texte}]
|
||||
|
||||
|
||||
def _court(v: Any, n: int) -> str:
|
||||
return re.sub(r"\s+", " ", str(v or "")).strip()[:n]
|
||||
|
||||
|
||||
def _liste(v: Any) -> List[str]:
|
||||
if not isinstance(v, list):
|
||||
return []
|
||||
return [x for x in (_court(i, MAX_ITEM) for i in v[:MAX_ITEMS]) if x]
|
||||
|
||||
|
||||
def lire_fiche(reponse: str, categories: List[str]) -> Dict[str, Any]:
|
||||
"""Valide la reponse du modele. Toute anomalie degrade vers une fiche prudente, jamais vers une erreur."""
|
||||
brut = reponse or ""
|
||||
m = re.search(r"\{.*\}", brut, re.S)
|
||||
try:
|
||||
d = json.loads(m.group(0)) if m else {}
|
||||
except ValueError:
|
||||
d = {}
|
||||
if not isinstance(d, dict):
|
||||
d = {}
|
||||
cat = ia.lire_categorie(str(d.get("categorie") or ""), categories)
|
||||
conf = str(d.get("confiance") or "").lower()
|
||||
if conf not in ("haute", "moyenne", "basse"):
|
||||
conf = "basse"
|
||||
if cat == ia.A_CLASSER:
|
||||
conf = "basse"
|
||||
course = None
|
||||
c = d.get("course")
|
||||
if isinstance(c, dict):
|
||||
objets, docs = _liste(c.get("objets")), _liste(c.get("documents"))
|
||||
if objets or docs:
|
||||
sens = str(c.get("sens") or "")
|
||||
course = {"sens": sens if sens in SENS_VALIDES else "tunis_sfax", "objets": objets, "documents": docs}
|
||||
dm = d.get("demande") if isinstance(d.get("demande"), dict) else {}
|
||||
action = _court(dm.get("action"), MAX_ITEM)
|
||||
ech = _court(dm.get("echeance"), 10)
|
||||
if not re.fullmatch(r"\d{2}/\d{2}/\d{4}", ech):
|
||||
ech = ""
|
||||
demande = {"reelle": bool(dm.get("reelle")) and bool(action), "action": action, "echeance": ech or None}
|
||||
return {"categorie": cat, "confiance": conf, "resume": _court(d.get("resume"), MAX_RESUME),
|
||||
"course": course, "demande": demande}
|
||||
|
||||
|
||||
def _categories(db_path: Optional[str] = None) -> List[str]:
|
||||
cats = [c["nom"] if "nom" in c else c.get("name") for c in _db.list_categories(db_path)]
|
||||
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]:
|
||||
"""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)
|
||||
return lire_fiche(rep, cats)
|
||||
|
||||
|
||||
def enregistrer(message_id: str, fiche: Dict[str, Any], objet: str = "", expediteur: str = "",
|
||||
date_mail: str = "", db_path: 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 (?,?,?,?,?,?,?,?,?,?,?) "
|
||||
"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",
|
||||
(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))
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _ligne(r) -> Dict[str, Any]:
|
||||
return {"message_id": r["message_id"], "categorie": r["categorie"], "confiance": r["confiance"],
|
||||
"resume": r["resume"], "course": json.loads(r["course"]) if r["course"] else None,
|
||||
"demande": json.loads(r["demande"]) if r["demande"] else None,
|
||||
"objet": r["objet"], "expediteur": r["expediteur"], "date": r["date_mail"], "le": r["le"],
|
||||
"appliquee": False}
|
||||
|
||||
|
||||
def lire(message_id: str, db_path: Optional[str] = None) -> Optional[Dict[str, Any]]:
|
||||
conn = _db.get_connection(db_path)
|
||||
try:
|
||||
_pret(conn)
|
||||
conn.row_factory = sqlite3.Row
|
||||
r = conn.execute("SELECT * FROM analyses_ia WHERE message_id=?", (message_id,)).fetchone()
|
||||
return _ligne(r) if r else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def lister(jour: Optional[str] = None, depuis: Optional[str] = None, n: int = 100,
|
||||
db_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||
conn = _db.get_connection(db_path)
|
||||
try:
|
||||
_pret(conn)
|
||||
conn.row_factory = sqlite3.Row
|
||||
sql, args = "SELECT * FROM analyses_ia", []
|
||||
if jour:
|
||||
sql += " WHERE date_mail LIKE ?"
|
||||
args.append(jour + "%")
|
||||
elif depuis:
|
||||
sql += " WHERE date_mail >= ?"
|
||||
args.append(depuis)
|
||||
sql += " ORDER BY date_mail DESC, le DESC LIMIT ?"
|
||||
args.append(max(1, min(n, 300)))
|
||||
return [_ligne(r) for r in conn.execute(sql, args).fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
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
|
||||
if not isinstance(d, dict) or not d:
|
||||
return None
|
||||
eh = d.get("en_tetes") or {}
|
||||
|
||||
def h(nom):
|
||||
return str(eh.get(nom) or eh.get(nom.lower()) or "")
|
||||
date = h("Date")
|
||||
try:
|
||||
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 "")}
|
||||
|
||||
|
||||
def analyser_mail(mirror_client, message_id: str, db_path: Optional[str] = None,
|
||||
meta: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||||
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)
|
||||
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)
|
||||
return lire(message_id, db_path)
|
||||
|
||||
|
||||
def traiter_lot(mirror_client, jour: str, maximum: int = 5, db_path: Optional[str] = None) -> Dict[str, int]:
|
||||
"""Analyse les mails du jour qui n'ont pas encore de fiche. Comptes seulement, aucun contenu."""
|
||||
res = {"analyses": 0, "deja": 0, "erreurs": 0, "restant": 0}
|
||||
mails = mirror_client.get_mails_for_day(jour, max_items=60)
|
||||
faits = {a["message_id"] for a in lister(jour=jour, n=300, db_path=db_path)}
|
||||
a_faire = [m for m in mails if m.get("message_id") and m["message_id"] not in faits]
|
||||
res["deja"] = len(mails) - len(a_faire)
|
||||
for m in a_faire[:maximum]:
|
||||
try:
|
||||
analyser_mail(mirror_client, m["message_id"], db_path,
|
||||
{"objet": m.get("objet"), "expediteur": m.get("expediteur"), "date": m.get("date")})
|
||||
res["analyses"] += 1
|
||||
except ia.IAIndisponible:
|
||||
res["erreurs"] += 1
|
||||
break
|
||||
except Exception:
|
||||
res["erreurs"] += 1
|
||||
res["restant"] = max(0, len(a_faire) - res["analyses"] - res["erreurs"])
|
||||
return res
|
||||
|
||||
|
||||
_verrou = threading.Lock()
|
||||
|
||||
|
||||
def demarrer_automatique(mirror_client, intervalle: int = 180) -> None:
|
||||
"""Boucle de fond : tant que ia_actif ET ia_auto sont vrais, analyse les mails du jour par petits lots."""
|
||||
def boucle() -> None:
|
||||
while True:
|
||||
time.sleep(intervalle)
|
||||
try:
|
||||
if auto_actif() and _verrou.acquire(blocking=False):
|
||||
try:
|
||||
r = traiter_lot(mirror_client, get_tunis_now_iso()[:10])
|
||||
if r["analyses"] or r["erreurs"]:
|
||||
log.info("analyse auto : %s", r)
|
||||
finally:
|
||||
_verrou.release()
|
||||
except Exception as e:
|
||||
log.warning("analyse auto : %s", type(e).__name__)
|
||||
threading.Thread(target=boucle, daemon=True, name="courrier-ia-auto").start()
|
||||
|
||||
|
||||
def creer_routeur(mirror_client) -> APIRouter:
|
||||
router = APIRouter(prefix="/ia")
|
||||
|
||||
@router.get("/auto")
|
||||
def etat_auto():
|
||||
return {"auto": _reglage("ia_auto"), "actif": ia.ia_active()}
|
||||
|
||||
@router.put("/auto")
|
||||
def regler_auto(e: ia.IAEtat):
|
||||
_regler("ia_auto", e.actif)
|
||||
return {"auto": _reglage("ia_auto"), "actif": ia.ia_active()}
|
||||
|
||||
@router.get("/analyse")
|
||||
def lire_analyse(id: str = Query(..., min_length=1, max_length=400)):
|
||||
"""Fiche deja produite (aucun appel de modele)."""
|
||||
r = lire(id)
|
||||
if r is None:
|
||||
raise HTTPException(status_code=404, detail="Aucune analyse pour ce mail.")
|
||||
return r
|
||||
|
||||
@router.post("/analyse")
|
||||
def produire_analyse(id: str = Query(..., min_length=1, max_length=400)):
|
||||
if not ia.ia_active():
|
||||
raise HTTPException(status_code=409, detail="L'IA est désactivée.")
|
||||
try:
|
||||
return analyser_mail(mirror_client, id)
|
||||
except LookupError:
|
||||
raise HTTPException(status_code=404, detail="Mail introuvable.")
|
||||
except ia.IAIndisponible as e:
|
||||
raise HTTPException(status_code=503, detail="IA indisponible, aucune analyse : " + str(e) + ".")
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
raise HTTPException(status_code=502, detail="Lecture du mail impossible : miroir indisponible.")
|
||||
|
||||
@router.post("/lot")
|
||||
def produire_lot(date: Optional[str] = None, maximum: int = Query(5, ge=1, le=20)):
|
||||
if not ia.ia_active():
|
||||
raise HTTPException(status_code=409, detail="L'IA est désactivée.")
|
||||
jour = date or get_tunis_now_iso()[:10]
|
||||
if not _verrou.acquire(blocking=False):
|
||||
raise HTTPException(status_code=429, detail="Un lot est déjà en cours.")
|
||||
try:
|
||||
return traiter_lot(mirror_client, jour, maximum)
|
||||
except ia.IAIndisponible as e:
|
||||
raise HTTPException(status_code=503, detail="IA indisponible : " + str(e) + ".")
|
||||
except Exception:
|
||||
raise HTTPException(status_code=502, detail="Lecture du miroir impossible.")
|
||||
finally:
|
||||
_verrou.release()
|
||||
|
||||
@router.get("/analyses")
|
||||
def lister_analyses(date: Optional[str] = None, jours: int = Query(7, ge=1, le=60),
|
||||
n: int = Query(100, ge=1, le=300)):
|
||||
if date:
|
||||
return {"analyses": lister(jour=date, n=n)}
|
||||
debut = (_date.fromisoformat(get_tunis_now_iso()[:10]) - timedelta(days=jours)).isoformat()
|
||||
return {"analyses": lister(depuis=debut, n=n)}
|
||||
|
||||
return router
|
||||
@@ -47,6 +47,7 @@ from app.classifier import (
|
||||
from app import asuivre
|
||||
from app.mirror_client import MirrorClient
|
||||
from app.ia import creer_routeur
|
||||
from app import analyse as _analyse
|
||||
from app.auth import verify_cf_access_jwt
|
||||
|
||||
# --- Schémas Pydantic ---
|
||||
@@ -90,6 +91,7 @@ async def lifespan(app: FastAPI):
|
||||
pass
|
||||
if ENV != "test":
|
||||
mirror_client.demarrer_rafraichissement()
|
||||
_analyse.demarrer_automatique(mirror_client)
|
||||
yield
|
||||
|
||||
app = FastAPI(
|
||||
@@ -678,4 +680,5 @@ def confirm_rule_endpoint(regle_id: int):
|
||||
}
|
||||
|
||||
api.include_router(creer_routeur(mirror_client))
|
||||
api.include_router(_analyse.creer_routeur(mirror_client))
|
||||
app.include_router(api)
|
||||
@@ -368,3 +368,14 @@ h1, h2, h3, p { margin: 0; }
|
||||
.nav-ouverte .nav-bureau { transform: none; visibility: visible; transition: transform var(--ny-duree) var(--ny-courbe); }
|
||||
.nav-voile:not([hidden]) { display: block; position: fixed; inset: 0; z-index: 39; background: color-mix(in srgb, var(--ny-encre) 45%, transparent); }
|
||||
}
|
||||
|
||||
/* Couche IA (tt-2026-11-072) */
|
||||
.lect-ia { margin: var(--ny-e5) 0; padding: 12px 14px; border: 1px solid var(--ny-trait); border-radius: var(--ny-r-l); background: var(--ny-carte); font: 400 14px/20px var(--ny-police); }
|
||||
.lect-ia h3 { margin: 0 0 6px; font: 600 14px/20px var(--ny-police); }
|
||||
.lect-ia p { margin: 4px 0; }
|
||||
.lect-ia-resume { font-weight: 500; }
|
||||
.lect-ia-info { color: var(--ny-encre-3); font-size: 13px; }
|
||||
.carte-ia { margin-bottom: var(--ny-e5); }
|
||||
.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; }
|
||||
+59
-4
@@ -440,6 +440,60 @@
|
||||
.catch(function (e) { if (e.message !== 'session') annoncer(e.message); })
|
||||
.then(function () { bt.disabled = false; });
|
||||
}
|
||||
|
||||
/* ---------- Couche IA (tt-2026-11-072) : proposition seulement, rien n'est appliqué sans clic ---------- */
|
||||
function blocIA(m, r) {
|
||||
var id = r.message_id || m.id;
|
||||
var sect = h('section', { class: 'lect-ia', 'aria-label': 'Analyse IA' });
|
||||
function fiche(f) {
|
||||
sect.textContent = '';
|
||||
sect.appendChild(h('h3', null, 'Analyse IA ', h('span', { class: 'etq', text: 'proposition, rien n\'est appliqué' })));
|
||||
if (f.resume) sect.appendChild(h('p', { class: 'lect-ia-resume', text: f.resume }));
|
||||
var cat = h('p', null, 'Catégorie proposée : ', h('strong', { text: f.categorie }), ' · confiance ' + f.confiance + ' ');
|
||||
if (f.categorie !== m.cat && f.categorie !== 'À classer') cat.appendChild(h('button', { type: 'button', class: 'btn-ligne', onclick: function () { corriger(m, f.categorie); flash('Catégorie appliquée.'); } }, 'Appliquer'));
|
||||
sect.appendChild(cat);
|
||||
if (f.course) {
|
||||
var liste = (f.course.objets || []).concat(f.course.documents || []).join(', ');
|
||||
sect.appendChild(h('p', null, 'Course possible : ', h('strong', { text: liste + ' (' + (SENS[f.course.sens] || f.course.sens) + ')' }), ' ',
|
||||
h('button', { type: 'button', class: 'btn-ligne', onclick: function () { dialogueCourse(null, { propose: liste, sens: f.course.sens, message_id: id, objet_mail: m.objet || r.objet || '', expediteur: m.expBrut || r.de || '', date_mail: m.date || '' }); } }, 'Ajouter aux courses')));
|
||||
}
|
||||
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.' }));
|
||||
}
|
||||
function proposerAnalyse() {
|
||||
sect.textContent = '';
|
||||
var bt = h('button', { type: 'button', class: 'btn-ligne' }, 'Analyser avec l\'IA');
|
||||
var msg = h('span', { class: 'lect-ia-info', role: 'status' });
|
||||
bt.addEventListener('click', function () {
|
||||
bt.disabled = true; msg.textContent = ' Analyse en cours, une dizaine de secondes…';
|
||||
api('/ia/analyse?id=' + encodeURIComponent(id), { method: 'POST' }).then(fiche)
|
||||
.catch(function (e) { if (e.message === 'session') return; bt.disabled = false; msg.textContent = e.message === 'http 503' ? ' IA indisponible pour le moment, aucune analyse faite.' : ' Analyse impossible. Réessayez.'; });
|
||||
});
|
||||
sect.appendChild(bt); sect.appendChild(msg);
|
||||
}
|
||||
api('/ia/analyse?id=' + encodeURIComponent(id)).then(fiche).catch(function (e) {
|
||||
if (e.message === 'session') return;
|
||||
api('/ia/etat').then(function (s) { if (s.actif) proposerAnalyse(); else sect.setAttribute('hidden', ''); }).catch(function () { sect.setAttribute('hidden', ''); });
|
||||
});
|
||||
return sect;
|
||||
}
|
||||
function carteIA() {
|
||||
var carte = h('section', { class: 'carte limite-l carte-ia', 'aria-label': 'Couche IA' });
|
||||
function ligne(titre, aide, etat, cle) {
|
||||
var sw = h('button', { type: 'button', class: 'interrupteur', role: 'switch', 'aria-checked': etat ? 'true' : 'false', 'aria-label': titre,
|
||||
onclick: function () {
|
||||
var v = sw.getAttribute('aria-checked') !== 'true';
|
||||
api('/ia/' + cle, { method: 'PUT', body: { actif: v } }).then(function () { sw.setAttribute('aria-checked', v ? 'true' : 'false'); if (cle === 'etat' && !v) return api('/ia/auto', { method: 'PUT', body: { actif: false } }).then(function () { rendre(); }); })
|
||||
.catch(function (e) { if (e.message !== 'session') annoncer('Réglage impossible.'); });
|
||||
} }, h('span', { class: 'piste' }, h('span', { class: 'bouton' })));
|
||||
return h('div', { class: 'ligne-ia' }, h('div', null, h('b', { text: titre }), h('p', { class: 'lect-ia-info', text: aide })), sw);
|
||||
}
|
||||
Promise.all([api('/ia/etat'), api('/ia/auto')]).then(function (rs) {
|
||||
carte.appendChild(ligne('Analyse par IA', 'À la demande, mail par mail. Le texte passe par le masquage PrivAiTe ; rien n\'est classé sans votre clic.', rs[0].actif, 'etat'));
|
||||
if (rs[0].actif) carte.appendChild(ligne('Analyse automatique du jour', 'Prépare les fiches des nouveaux mails toutes les trois minutes. Les agents peuvent alors les consulter.', rs[1].auto, 'auto'));
|
||||
}).catch(function () { carte.setAttribute('hidden', ''); });
|
||||
return carte;
|
||||
}
|
||||
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 })); });
|
||||
@@ -456,7 +510,7 @@
|
||||
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);
|
||||
cont.appendChild(badges); cont.appendChild(meta); cont.appendChild(blocIA(m, r)); 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'))));
|
||||
}
|
||||
@@ -614,6 +668,7 @@
|
||||
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; }
|
||||
frag.appendChild(carteIA());
|
||||
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')));
|
||||
@@ -711,14 +766,14 @@
|
||||
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 champ = h('input', { id: 'crs-dem', type: 'text', maxlength: '300', 'data-focus': '', autocomplete: 'off', value: course ? course.demande : (mail && (mail.propose || 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';
|
||||
sens.value = course ? course.sens : ((mail && mail.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 || {}) })
|
||||
var req = nouveau ? api('/courses', { method: 'POST', body: Object.assign({}, mail || {}, { demande: dem, sens: sens.value }, { propose: undefined }) })
|
||||
: 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.'; });
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from app import analyse, ia
|
||||
from app.main import mirror_client
|
||||
|
||||
DONNEES = {"message_id": "m-1",
|
||||
"en_tetes": {"Subject": "Colis pour Tunis", "From": "ali@example.tn", "Date": "Thu, 20 Nov 2026 09:00:00 +0100"},
|
||||
"corps_texte": "Merci de rapporter le colis et le bon de livraison. Ali Test 12 345,678 DT"}
|
||||
|
||||
FICHE = {"categorie": "Tunis", "confiance": "haute", "resume": "Colis à rapporter de Tunis.",
|
||||
"course": {"sens": "tunis_sfax", "objets": ["colis"], "documents": ["bon de livraison"]},
|
||||
"demande": {"reelle": True, "action": "Rapporter le colis", "echeance": "25/11/2026"}}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mail(monkeypatch):
|
||||
monkeypatch.setattr(mirror_client, "get_mail", lambda mid: {"donnees": DONNEES})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ia_on(client):
|
||||
client.put("/api/v1/ia/etat", json={"actif": True})
|
||||
|
||||
|
||||
def _rep(fiche=FICHE):
|
||||
return lambda *a, **k: json.dumps(fiche, ensure_ascii=False)
|
||||
|
||||
|
||||
def test_analyse_refusee_si_ia_desactivee(client, mail, monkeypatch):
|
||||
appels = []
|
||||
monkeypatch.setattr(ia, "appeler_privaite", lambda *a, **k: appels.append(1) or "{}")
|
||||
assert client.post("/api/v1/ia/analyse?id=m-1").status_code == 409
|
||||
assert appels == []
|
||||
|
||||
|
||||
def test_analyse_produit_une_fiche_complete(client, mail, ia_on, monkeypatch):
|
||||
monkeypatch.setattr(ia, "appeler_privaite", _rep())
|
||||
j = client.post("/api/v1/ia/analyse?id=m-1").json()
|
||||
assert j["categorie"] == "Tunis" and j["confiance"] == "haute"
|
||||
assert j["course"]["objets"] == ["colis"] and j["demande"]["reelle"] is True
|
||||
assert j["appliquee"] is False
|
||||
|
||||
|
||||
def test_analyse_jamais_appliquee_aucun_classement_ecrit(client, mail, ia_on, monkeypatch):
|
||||
monkeypatch.setattr(ia, "appeler_privaite", _rep())
|
||||
client.post("/api/v1/ia/analyse?id=m-1")
|
||||
assert client.get("/api/v1/classements/m-1").status_code == 404
|
||||
from app import db as _db
|
||||
assert _db.list_courses() == []
|
||||
|
||||
|
||||
def test_analyse_lue_en_cache_sans_appel(client, mail, ia_on, monkeypatch):
|
||||
monkeypatch.setattr(ia, "appeler_privaite", _rep())
|
||||
client.post("/api/v1/ia/analyse?id=m-1")
|
||||
monkeypatch.setattr(ia, "appeler_privaite", lambda *a, **k: pytest.fail("appel inattendu"))
|
||||
assert client.get("/api/v1/ia/analyse?id=m-1").json()["resume"].startswith("Colis")
|
||||
|
||||
|
||||
def test_corps_du_mail_jamais_stocke(client, mail, ia_on, monkeypatch, temp_db):
|
||||
monkeypatch.setattr(ia, "appeler_privaite", _rep())
|
||||
client.post("/api/v1/ia/analyse?id=m-1")
|
||||
import sqlite3
|
||||
brut = b"".join(l.encode() for l in sqlite3.connect(temp_db).iterdump())
|
||||
assert b"12 345,678" not in brut and b"bon de livraison" in brut # seule la fiche est conservee
|
||||
|
||||
|
||||
def test_reponse_non_json_donne_fiche_prudente(client, mail, ia_on, monkeypatch):
|
||||
monkeypatch.setattr(ia, "appeler_privaite", lambda *a, **k: "Je ne sais pas")
|
||||
j = client.post("/api/v1/ia/analyse?id=m-1").json()
|
||||
assert j["categorie"] == "À classer" and j["confiance"] == "basse" and j["course"] is None
|
||||
assert j["demande"]["reelle"] is False
|
||||
|
||||
|
||||
def test_categorie_hors_liste_devient_a_classer():
|
||||
f = analyse.lire_fiche(json.dumps({"categorie": "Urgent", "confiance": "haute"}), ["Tunis", "CI"])
|
||||
assert f["categorie"] == "À classer" and f["confiance"] == "basse"
|
||||
|
||||
|
||||
def test_demande_reelle_exige_une_action():
|
||||
f = analyse.lire_fiche(json.dumps({"categorie": "CI", "demande": {"reelle": True, "action": ""}}), ["CI"])
|
||||
assert f["demande"]["reelle"] is False
|
||||
|
||||
|
||||
def test_echeance_mal_formee_ignoree():
|
||||
f = analyse.lire_fiche(json.dumps({"categorie": "CI", "demande": {"reelle": True, "action": "x", "echeance": "demain"}}), ["CI"])
|
||||
assert f["demande"]["echeance"] is None
|
||||
|
||||
|
||||
def test_course_vide_ou_sens_inconnu():
|
||||
f = analyse.lire_fiche(json.dumps({"categorie": "Tunis", "course": {"objets": [], "documents": []}}), ["Tunis"])
|
||||
assert f["course"] is None
|
||||
g = analyse.lire_fiche(json.dumps({"categorie": "Tunis", "course": {"sens": "ailleurs", "objets": ["x"]}}), ["Tunis"])
|
||||
assert g["course"]["sens"] == "tunis_sfax"
|
||||
|
||||
|
||||
def test_json_entoure_de_texte_est_lu():
|
||||
f = analyse.lire_fiche("Voici : " + json.dumps(FICHE, ensure_ascii=False) + " fin", ["Tunis"])
|
||||
assert f["categorie"] == "Tunis"
|
||||
|
||||
|
||||
def test_refus_net_si_privaite_injoignable(client, mail, ia_on, monkeypatch):
|
||||
def boom(*a, **k):
|
||||
raise httpx.ConnectError("x")
|
||||
monkeypatch.setattr(ia.httpx, "post", boom)
|
||||
monkeypatch.setattr(ia, "_cle", lambda: "k")
|
||||
assert client.post("/api/v1/ia/analyse?id=m-1").status_code == 503
|
||||
assert client.get("/api/v1/ia/analyse?id=m-1").status_code == 404
|
||||
|
||||
|
||||
def test_aucun_appel_hors_privaite(client, mail, ia_on, monkeypatch):
|
||||
urls = []
|
||||
|
||||
class R:
|
||||
status_code = 200
|
||||
|
||||
def json(self):
|
||||
return {"choices": [{"message": {"content": json.dumps(FICHE)}}]}
|
||||
monkeypatch.setattr(ia.httpx, "post", lambda url, **k: urls.append(url) or R())
|
||||
monkeypatch.setattr(ia, "_cle", lambda: "k")
|
||||
client.post("/api/v1/ia/analyse?id=m-1")
|
||||
assert urls and all(u == ia.PRIVAITE_URL for u in urls)
|
||||
|
||||
|
||||
def test_mail_introuvable(client, ia_on, monkeypatch):
|
||||
monkeypatch.setattr(mirror_client, "get_mail", lambda mid: {"donnees": {}})
|
||||
assert client.post("/api/v1/ia/analyse?id=zzz").status_code == 404
|
||||
|
||||
|
||||
def test_lot_analyse_les_non_traites_et_s_arrete_si_privaite_tombe(client, ia_on, monkeypatch):
|
||||
mails = [{"message_id": "a", "objet": "o1", "expediteur": "x", "date": "2026-11-20T08:00:00+01:00"},
|
||||
{"message_id": "b", "objet": "o2", "expediteur": "x", "date": "2026-11-20T09:00:00+01:00"},
|
||||
{"message_id": "c", "objet": "o3", "expediteur": "x", "date": "2026-11-20T10:00:00+01:00"}]
|
||||
monkeypatch.setattr(mirror_client, "get_mails_for_day", lambda d, max_items=60: mails)
|
||||
monkeypatch.setattr(mirror_client, "get_mail", lambda mid: {"donnees": {"message_id": mid, "en_tetes": {"Subject": "s"}, "corps_texte": "t"}})
|
||||
etat = {"n": 0}
|
||||
|
||||
def faux(*a, **k):
|
||||
etat["n"] += 1
|
||||
if etat["n"] == 3:
|
||||
raise ia.IAIndisponible("x")
|
||||
return json.dumps(FICHE)
|
||||
monkeypatch.setattr(ia, "appeler_privaite", faux)
|
||||
r = client.post("/api/v1/ia/lot?date=2026-11-20&maximum=5").json()
|
||||
assert r["analyses"] == 2 and r["erreurs"] == 1
|
||||
assert len(client.get("/api/v1/ia/analyses?date=2026-11-20").json()["analyses"]) == 2
|
||||
|
||||
|
||||
def test_lot_refuse_si_ia_desactivee(client):
|
||||
assert client.post("/api/v1/ia/lot").status_code == 409
|
||||
|
||||
|
||||
def test_mode_auto_desactive_par_defaut_et_bascule(client):
|
||||
assert client.get("/api/v1/ia/auto").json()["auto"] is False
|
||||
assert client.put("/api/v1/ia/auto", json={"actif": True}).json()["auto"] is True
|
||||
|
||||
|
||||
def test_auto_exige_les_deux_interrupteurs(client):
|
||||
client.put("/api/v1/ia/auto", json={"actif": True})
|
||||
assert analyse.auto_actif() is False # ia_actif encore a zero
|
||||
client.put("/api/v1/ia/etat", json={"actif": True})
|
||||
assert analyse.auto_actif() is True
|
||||
|
||||
|
||||
def test_prompt_ne_contient_aucun_jeton_ni_secret():
|
||||
m = analyse.construire_messages("Obj", "a@b.tn", "corps", ["Tunis"])
|
||||
assert "Bearer" not in json.dumps(m) and "Tunis" in m[0]["content"]
|
||||
Reference in new issue
Block a user