diff --git a/app/analyse.py b/app/analyse.py index 0bc50cc..1099a00 100644 --- a/app/analyse.py +++ b/app/analyse.py @@ -80,8 +80,10 @@ 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], contexte: str = "", exemples: str = "") -> list: - defs = "\n".join("- " + c + " : " + DEFINITIONS.get(c, "categorie de Nabil") for c in categories) +def construire_messages(objet: str, expediteur: str, corps: str, categories: List[str], contexte: str = "", exemples: str = "", + definitions: Optional[Dict[str, str]] = None) -> list: + definitions = definitions or {} + defs = "\n".join("- " + c + " : " + (definitions.get(c) or 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" @@ -161,6 +163,10 @@ def _categories(db_path: Optional[str] = None) -> List[str]: return [c for c in cats if c and c != ia.A_CLASSER] +def _definitions(db_path: Optional[str] = None) -> Dict[str, str]: + return {c.get("name"): c.get("definition") for c in _db.list_categories(db_path) if c.get("definition")} + + class ReponseIllisible(Exception): """Le modele a repondu sans fiche JSON exploitable : rien n'est enregistre, le mail sera reessaye.""" @@ -179,7 +185,8 @@ def analyser(objet: str, expediteur: str, corps: str, db_path: Optional[str] = N reponse ne contient pas de fiche : une fiche vide ne doit jamais etre enregistree comme une vraie analyse.""" exemples = exemples_nabil(db_path) cats = _categories(db_path) - rep = ia.appeler_privaite(construire_messages(objet, expediteur, corps, cats, contexte, exemples), max_tokens=1200, delai=75) + rep = ia.appeler_privaite(construire_messages(objet, expediteur, corps, cats, contexte, exemples, _definitions(db_path)), + max_tokens=1200, delai=75) if not _fiche_presente(rep): raise ReponseIllisible() return lire_fiche(rep, cats) diff --git a/app/db.py b/app/db.py index 3c4d2ea..0b84b3b 100644 --- a/app/db.py +++ b/app/db.py @@ -88,6 +88,8 @@ def init_db(db_path: Optional[str] = None) -> None: cols_cat = [r["name"] for r in conn.execute("PRAGMA table_info(categories)").fetchall()] if "couleur" not in cols_cat: conn.execute("ALTER TABLE categories ADD COLUMN couleur INTEGER") + if "definition" not in cols_cat: + conn.execute("ALTER TABLE categories ADD COLUMN definition TEXT") now = get_tunis_now_iso() @@ -133,11 +135,27 @@ def init_db(db_path: Optional[str] = None) -> None: def list_categories(db_path: Optional[str] = None) -> List[Dict[str, Any]]: conn = get_connection(db_path) try: - rows = conn.execute("SELECT id, name, couleur, created_at FROM categories ORDER BY id ASC").fetchall() + cols = {r[1] for r in conn.execute("PRAGMA table_info(categories)")} + sel = "definition" if "definition" in cols else "NULL AS definition" + rows = conn.execute("SELECT id, name, couleur, created_at, " + sel + " FROM categories ORDER BY id ASC").fetchall() return [dict(r) for r in rows] finally: conn.close() +def set_definition(cat_id: int, texte: str, db_path: Optional[str] = None) -> bool: + """Ce que Nabil dit d'une categorie : lu par l'IA pour proposer un classement (jamais une regle).""" + conn = get_connection(db_path) + try: + with conn: + cols = {r[1] for r in conn.execute("PRAGMA table_info(categories)")} + if "definition" not in cols: + conn.execute("ALTER TABLE categories ADD COLUMN definition TEXT") + cur = conn.execute("UPDATE categories SET definition = ? WHERE id = ?", ((texte or "").strip()[:400] or None, cat_id)) + return cur.rowcount > 0 + finally: + conn.close() + + def add_category(name: str, db_path: Optional[str] = None) -> Dict[str, Any]: name = name.strip() if not name: diff --git a/app/fils.py b/app/fils.py new file mode 100644 index 0000000..d5edd84 --- /dev/null +++ b/app/fils.py @@ -0,0 +1,78 @@ +"""Cle de fil (Thread-Index Exchange) des mails du suivi (audit du 21/11/2026). + +Le suivi regroupait par objet normalise : deux conversations au meme objet generique (« Rappel », « Demande ») +fusionnaient. Les listes du miroir ne donnent pas de cle de conversation ; seule la lecture complete d'un mail +la fournit, et le miroir limite les lectures. Les cles sont donc lues en arriere-plan, seulement pour les objets +partages par plusieurs mails, 20 au plus par passage, et gardees en base (une lecture par mail, une seule fois).""" +import threading +import time +from typing import Dict, Iterable, Optional + +from app import db as _db + +_verrou = threading.Lock() + + +def _pret(conn) -> None: + conn.execute("CREATE TABLE IF NOT EXISTS fils_mail (message_id TEXT PRIMARY KEY, fil TEXT, le TEXT NOT NULL)") + + +def connus(ids: Iterable[str], db_path: Optional[str] = None) -> Dict[str, Optional[str]]: + ids = [i for i in ids if i] + if not ids: + return {} + conn = _db.get_connection(db_path) + try: + _pret(conn) + out: Dict[str, Optional[str]] = {} + for i in range(0, len(ids), 400): + lot = ids[i:i + 400] + q = ",".join("?" * len(lot)) + for mid, fil in conn.execute("SELECT message_id, fil FROM fils_mail WHERE message_id IN (" + q + ")", lot): + out[mid] = fil + try: + for mid, fil in conn.execute("SELECT message_id, fil FROM analyses_ia WHERE fil IS NOT NULL AND message_id IN (" + q + ")", lot): + out.setdefault(mid, fil) + except Exception: + pass + return out + finally: + conn.close() + + +def _noter(mid: str, fil: Optional[str], db_path: Optional[str] = None) -> None: + from app.config import get_tunis_now_iso + conn = _db.get_connection(db_path) + try: + _pret(conn) + with conn: + conn.execute("INSERT OR REPLACE INTO fils_mail (message_id, fil, le) VALUES (?, ?, ?)", (mid, fil, get_tunis_now_iso())) + finally: + conn.close() + + +def completer_en_fond(mirror_client, ids: Iterable[str], maximum: int = 20) -> None: + """Lit en arriere-plan la cle de fil des mails qui n'en ont pas encore. Jamais deux passages a la fois.""" + manquants = [i for i in ids if i] + deja = connus(manquants) + manquants = [i for i in manquants if i not in deja][:maximum] + if not manquants or not _verrou.acquire(blocking=False): + return + + def tache(): + from app.analyse import cle_fil + try: + for mid in manquants: + try: + res = mirror_client.get_mail(mid) + d = res.get("donnees") if isinstance(res, dict) else None + eh = (d or {}).get("en_tetes") or {} + ti = str(eh.get("Thread-Index") or eh.get("thread-index") or "") + _noter(mid, cle_fil(ti) if ti else None) + except Exception: + pass + time.sleep(1.5) + finally: + _verrou.release() + + threading.Thread(target=tache, daemon=True, name="courrier-fils").start() diff --git a/app/main.py b/app/main.py index 3b7745f..2e5a3f0 100644 --- a/app/main.py +++ b/app/main.py @@ -372,7 +372,16 @@ def lire_suivi(jours: int = Query(14, ge=1, le=60)): 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()) + from app import fils as _fils + from app.suivi import sujet_normalise + par_objet: Dict[str, List[str]] = {} + for x in tous: + par_objet.setdefault(sujet_normalise(x.get("objet")), []).append(x.get("message_id")) + partages = [i for ids in par_objet.values() if len(ids) > 1 for i in ids] + cles = _fils.connus(partages) + if ENV != "test": + _fils.completer_en_fond(mirror_client, partages) + items = calculer_suivi(tous, MON_ADRESSE, maintenant, list_suivi_clos(), cles) 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="") @@ -597,8 +606,25 @@ def _refuser_categorie_systeme(cat_id: int): @api.get("/categories") def list_cats(): - """Liste les catégories disponibles.""" - return {"categories": list_categories()} + """Liste les catégories disponibles, avec la définition que lit l'IA (celle de Nabil, sinon celle par défaut).""" + cats = list_categories() + for c in cats: + c["definition_ia"] = c.get("definition") or _analyse.DEFINITIONS.get(c.get("name") or "") or "" + return {"categories": cats} + + +class DefinitionIn(BaseModel): + definition: str = Field("", max_length=400) + + +@api.put("/categories/{cat_id}/definition") +def definir_cat(cat_id: int, req: DefinitionIn): + """Définition d'une catégorie en mots de Nabil, utilisée par l'IA pour proposer (jamais pour classer seule).""" + _refuser_categorie_systeme(cat_id) + from app.db import set_definition + if not set_definition(cat_id, req.definition): + raise HTTPException(status_code=404, detail="Catégorie introuvable") + return {"ok": True} @api.post("/categories", status_code=201) def create_cat(req: CategoryCreate): @@ -691,6 +717,8 @@ from app import brouillon as _brouillon api.include_router(_brouillon.creer_routeur(mirror_client)) from app import piece_ia as _piece_ia api.include_router(_piece_ia.creer_routeur(mirror_client)) +from app import rla as _rla +api.include_router(_rla.creer_routeur()) @api.get("/sauvegardes") diff --git a/app/rla.py b/app/rla.py new file mode 100644 index 0000000..263a14c --- /dev/null +++ b/app/rla.py @@ -0,0 +1,96 @@ +"""Lien entre un mail et les marches RLA (table 1048 de Baserow, recapitulatif de tous les marches). + +Lecture seule : Courrier ne fait que des GET, avec le jeton de la sphere RLA (secrets/baserow_rla.key). +Une reference d'AO (« AO 58/2024 », « Marche n° 58/2024 ») ou un numero de PO (po_an1 a po_an3) trouve dans +le mail renvoie la fiche du marche. Table gardee 10 minutes en memoire ; Baserow injoignable = liste vide.""" +import os +import re +import threading +import time +from typing import Any, Dict, List + +import httpx +from fastapi import APIRouter, Query + +BASEROW_URL = os.getenv("BASEROW_URL", "https://baserow.bolbol.tn") +TABLE_RECAP = int(os.getenv("RLA_TABLE_RECAP", "1048")) +CLE_PATH = os.getenv("RLA_KEY_PATH", "/app/secrets/baserow_rla.key") +TTL = 600 +_cache: Dict[str, Any] = {"t": 0.0, "rows": []} +_verrou = threading.Lock() + +_AO = re.compile(r"(?i)\b(?:AO|AOI|march[eé])\D{0,8}?(\d{1,4})\s*/\s*(20\d{2})\b") +_PO = re.compile(r"(? str: + try: + return open(CLE_PATH, encoding="utf-8").read().strip() + except OSError: + return "" + + +def _texte(v: Any) -> str: + if isinstance(v, dict): + return str(v.get("value") or "") + if isinstance(v, list): + return ", ".join(_texte(x) for x in v) + return "" if v is None else str(v) + + +def marches() -> List[Dict[str, Any]]: + with _verrou: + if time.time() - _cache["t"] < TTL and _cache["rows"]: + return _cache["rows"] + k = _cle() + if not k: + return [] + rows: List[Dict[str, Any]] = [] + url = BASEROW_URL + "/api/database/rows/table/%d/?user_field_names=true&size=200" % TABLE_RECAP + try: + while url and len(rows) < 2000: + r = httpx.get(url, headers={"Authorization": "Token " + k}, timeout=15) + if r.status_code != 200: + return _cache["rows"] + d = r.json() + rows += d.get("results") or [] + url = d.get("next") + except httpx.HTTPError: + return _cache["rows"] + _cache.update(t=time.time(), rows=rows) + return rows + + +def _fiche(r: Dict[str, Any]) -> Dict[str, Any]: + return {"marche": _texte(r.get("id_marche")), "entrepreneur": _texte(r.get("entrepreneur")), + "region": _texte(r.get("region_csc") or r.get("region")), "projet": _texte(r.get("projet")), + "actif": bool(r.get("Actif")), "fin_marche": _texte(r.get("date_fin_marche")), + "annee": _texte(r.get("annee_contractuelle")), "jours_restants_po": _texte(r.get("jours_restants_po")), + "taux_fin": _texte(r.get("taux_fin")), "taux_phy": _texte(r.get("taux_phy")), + "note": _texte(r.get("Notes"))[:240]} + + +def trouver(texte: str, rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + aos = {(int(n), a) for n, a in _AO.findall(texte or "")} + pos = set(_PO.findall(texte or "")) + out, vus = [], set() + for r in rows: + ref = _AO.search(_texte(r.get("reference")) or _texte(r.get("id_marche"))) + par_ao = bool(ref and (int(ref.group(1)), ref.group(2)) in aos) + par_po = bool(pos & {_texte(r.get(c)).strip() for c in ("po_an1", "po_an2", "po_an3")}) + if (par_ao or par_po) and r.get("id") not in vus: + vus.add(r.get("id")) + out.append(dict(_fiche(r), par="PO" if par_po and not par_ao else "AO")) + return out[:8] + + +def creer_routeur() -> APIRouter: + router = APIRouter() + + @router.get("/rla") + def lien_rla(texte: str = Query(..., min_length=3, max_length=6000)): + """Marchés RLA cités dans un texte (objet, résumé, début du corps). Lecture seule.""" + rows = marches() + return {"marches": trouver(texte, rows), "disponible": bool(rows)} + + return router diff --git a/app/sauvegarde.py b/app/sauvegarde.py index 2f7dc95..098f89e 100644 --- a/app/sauvegarde.py +++ b/app/sauvegarde.py @@ -41,6 +41,8 @@ def sauvegarder(db_path: Optional[str] = None, force: bool = False) -> Optional[ a = sqlite3.connect(src); b = sqlite3.connect(tmp) try: a.backup(b) + # Sauvegarde autonome : un seul fichier, sans annexes -wal/-shm (copiee telle quelle vers le NAS). + b.execute("PRAGMA journal_mode=DELETE") finally: b.close(); a.close() os.replace(tmp, cible) diff --git a/app/static/app.css b/app/static/app.css index e73c8d2..9354ab9 100644 --- a/app/static/app.css +++ b/app/static/app.css @@ -407,3 +407,10 @@ h1, h2, h3, p { margin: 0; } .resume-pj { flex-basis: 100%; margin: 4px 0 0; white-space: pre-wrap; } .lect-pj li { flex-wrap: wrap; } + +.champ-def { width: 100%; padding: 8px 12px; border: 1px solid var(--ny-trait); border-radius: var(--ny-r-m, 8px); font: 400 14px/20px var(--ny-police); background: var(--ny-carte); color: inherit; box-sizing: border-box; resize: vertical; } +.a-definir { color: var(--ny-attention); font-weight: 400; } + +.carte-rla { margin: 6px 0; padding: 8px 12px; border: 1px solid var(--ny-trait); border-radius: var(--ny-r-m, 8px); background: var(--ny-carte-2); } +.carte-rla p { margin: 2px 0; } +.carte-rla .etiq { margin-left: 8px; } diff --git a/app/static/app.js b/app/static/app.js index 8d7115b..a9a0716 100644 --- a/app/static/app.js +++ b/app/static/app.js @@ -108,7 +108,7 @@ } function chargerCats() { return api('/categories').then(function (r) { - var l = (r.categories || []).map(function (c) { return { id: c.id, nom: c.name, couleur: c.couleur }; }); + var l = (r.categories || []).map(function (c) { return { id: c.id, nom: c.name, couleur: c.couleur, definition: c.definition || '', defIA: c.definition_ia || '' }; }); l.sort(function (a, b) { return (a.nom === SYSTEME) - (b.nom === SYSTEME) || a.id - b.id; }); S.cats = l; }); @@ -234,13 +234,17 @@ ouvrir(function (clore) { var champ = h('input', { id: 'cat-nom', type: 'text', maxlength: '100', 'data-focus': '', autocomplete: 'off', value: cat ? cat.nom : '' }); if (systeme) { champ.setAttribute('readonly', ''); } + var def = h('textarea', { id: 'cat-def', rows: '3', maxlength: '400', class: 'champ-def', placeholder: 'Par exemple : mails sur les ruptures et écarts de stock dans les magasins de la région' }); + def.value = cat ? (cat.definition || cat.defIA || '') : ''; var err = h('div', { class: 'err', role: 'alert' }); function enregistrer() { var nom = champ.value.trim(); if (!nom) { err.textContent = 'Saisissez un nom de catégorie.'; champ.focus(); return; } if (S.cats.some(function (c) { return c.nom.toLowerCase() === nom.toLowerCase() && (!cat || c.id !== cat.id); })) { err.textContent = 'Cette catégorie existe déjà.'; champ.focus(); return; } - var req = nouveau ? api('/categories', { method: 'POST', body: { name: nom } }) : api('/categories/' + cat.id, { method: 'PUT', body: { name: nom } }); - req.then(function () { clore(); return chargerMails(); }).then(function () { flash(nouveau ? 'Catégorie ajoutée.' : 'Catégorie renommée.'); }) + var texte = def.value.trim(), avant = cat ? (cat.definition || cat.defIA || '') : ''; + var req = (nouveau ? api('/categories', { method: 'POST', body: { name: nom } }) : (nom !== cat.nom ? api('/categories/' + cat.id, { method: 'PUT', body: { name: nom } }) : Promise.resolve(cat))) + .then(function (c) { var id = (c && c.id) || (cat && cat.id); return texte !== avant && id ? api('/categories/' + id + '/definition', { method: 'PUT', body: { definition: texte } }) : null; }); + req.then(function () { clore(); return chargerMails(); }).then(function () { flash(nouveau ? 'Catégorie ajoutée.' : 'Catégorie enregistrée.'); }) .catch(function (e) { if (e.message !== 'session') err.textContent = 'Enregistrement impossible. Réessayez.'; }); } champ.addEventListener('keydown', function (e) { if (e.key === 'Enter' && !systeme) { e.preventDefault(); enregistrer(); } }); @@ -251,7 +255,10 @@ return h('section', { class: 'boite', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'dlg-t' }, h('h2', { id: 'dlg-t' }, nouveau ? 'Nouvelle catégorie' : systeme ? SYSTEME : 'Modifier la catégorie'), systeme ? h('p', null, '« À classer » reçoit les mails qu\'aucune règle ne reconnaît. Elle ne peut être ni renommée ni supprimée.') : null, - h('div', { class: 'champ' }, h('label', { for: 'cat-nom' }, 'Nom'), champ, err), acts, pied); + h('div', { class: 'champ' }, h('label', { for: 'cat-nom' }, 'Nom'), champ), + systeme ? null : h('div', { class: 'champ' }, h('label', { for: 'cat-def' }, 'Ce que contient cette catégorie'), def, + h('p', { class: 'lect-ia-info', text: 'L\'IA lit cette phrase pour vous proposer un classement. Décrivez le contenu des mails, pas des mots-clés : rien n\'est classé sans votre validation.' })), + err, acts, pied); }); } function dialogueSuppression(cat) { @@ -498,6 +505,7 @@ cadre.appendChild(champ); cadre.appendChild(bt); cadre.appendChild(msg); return cadre; } + function dateFr(iso) { var x = /^(\d{4})-(\d{2})-(\d{2})/.exec(iso || ''); return x ? x[3] + '/' + x[2] + '/' + x[1] : (iso || ''); } function blocIA(m, r) { var id = r.message_id || m.id; var sect = h('section', { class: 'lect-ia', 'aria-label': 'Analyse IA' }); @@ -515,6 +523,19 @@ }); sect.appendChild(lr); } + var zoneRla = h('div', { class: 'lect-rla' }); + sect.appendChild(zoneRla); + var texteRla = ((m.objet || r.objet || '') + ' ' + (f.resume || '') + ' ' + String(r.corps || '').slice(0, 4000)).slice(0, 5900); + if (/\b(AO|AOI|march)|\d{7}/i.test(texteRla)) { + api('/rla?texte=' + encodeURIComponent(texteRla)).then(function (x) { + (x.marches || []).forEach(function (k) { + var etat = k.actif ? 'actif' : 'clos'; + var det = [k.entrepreneur, k.region, k.projet, k.annee, k.fin_marche ? 'fin ' + dateFr(k.fin_marche) : '', k.taux_fin ? 'avancement financier ' + String(k.taux_fin).replace('.', ',') + ' %' : '', k.taux_phy ? 'physique ' + String(k.taux_phy).replace('.', ',') + ' %' : ''].filter(Boolean).join(' · '); + zoneRla.appendChild(h('div', { class: 'carte-rla' }, h('p', null, h('strong', { text: 'Marché RLA ' + k.marche }), h('span', { class: 'etiq ' + (k.actif ? 'active' : 'propose'), text: etat })), + h('p', { class: 'lect-ia-info', text: det }), k.note ? h('p', { class: 'lect-ia-info', text: k.note }) : null)); + }); + }).catch(function () { /* Baserow injoignable : rien n'est affiché */ }); + } 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); @@ -741,7 +762,8 @@ var compte = {}; S.mails.forEach(function (m) { compte[m.cat] = (compte[m.cat] || 0) + 1; }); var carte = h('section', { class: 'carte limite', 'aria-label': 'Catégories' }); S.cats.forEach(function (c) { - carte.appendChild(h('div', { class: 'rang' }, pastille(couleur(c.nom, c.id)), h('span', { class: 'nom', text: c.nom }), + carte.appendChild(h('div', { class: 'rang' }, pastille(couleur(c.nom, c.id)), h('span', { class: 'nom' }, c.nom, + c.nom !== SYSTEME && !c.defIA ? h('small', { class: 'a-definir', text: ' · définition à écrire' }) : null), h('span', { class: 'nb' }, h('b', { text: d2(compte[c.nom] || 0) }), ' ce jour'), h('button', { type: 'button', class: 'btn-petit', 'aria-label': (c.nom === SYSTEME ? 'Détails de ' : 'Modifier ') + c.nom, onclick: function () { dialogueCategorie(c); } }, c.nom === SYSTEME ? 'Détails' : 'Modifier'))); }); diff --git a/app/static/index.html b/app/static/index.html index 283462f..0a1072a 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -10,7 +10,7 @@ - +
@@ -31,6 +31,6 @@
- + diff --git a/app/suivi.py b/app/suivi.py index 4844848..aa38a04 100644 --- a/app/suivi.py +++ b/app/suivi.py @@ -28,10 +28,12 @@ def _avec(texte: str) -> str: 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]]: +def calculer_suivi(mails: List[Dict[str, Any]], mon_adresse: str, maintenant: datetime, clos: Dict[str, str], + fils: Optional[Dict[str, Optional[str]]] = None) -> 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() + cles_fil = fils or {} fils: Dict[str, List[Dict[str, Any]]] = {} for m in mails: cle = sujet_normalise(m.get("objet")) @@ -41,6 +43,18 @@ def calculer_suivi(mails: List[Dict[str, Any]], mon_adresse: str, maintenant: da if AUTOMATIQUE.search(m.get("expediteur") or ""): continue fils.setdefault(cle, []).append(dict(m, _d=d, _moi=mon in (m.get("expediteur") or "").lower())) + # Meme objet mais conversations distinctes (cle Thread-Index connue pour TOUS les mails du groupe et differente) : + # un fil par conversation. Une cle manquante laisse le regroupement par objet, comme avant. + if cles_fil: + decoupes: Dict[str, List[Dict[str, Any]]] = {} + for cle, msgs in fils.items(): + ks = [cles_fil.get(x["message_id"]) for x in msgs] + if len(msgs) > 1 and all(ks) and len(set(ks)) > 1: + for x, k in zip(msgs, ks): + decoupes.setdefault(cle + " #" + k[:10], []).append(x) + else: + decoupes[cle] = msgs + fils = decoupes sortie = [] for cle, msgs in fils.items(): msgs.sort(key=lambda x: x["_d"]) diff --git a/tests/test_definitions_categories.py b/tests/test_definitions_categories.py new file mode 100644 index 0000000..45d2d35 --- /dev/null +++ b/tests/test_definitions_categories.py @@ -0,0 +1,23 @@ +import pytest +from app import analyse as a, db, ia + +pytestmark = pytest.mark.regles_off + + +def test_definition_de_nabil_dans_la_consigne(temp_db, monkeypatch): + c = db.add_category("Pb Stock", temp_db) + assert db.set_definition(c["id"], "ruptures et écarts de stock dans les magasins", temp_db) + vu = {} + def faux(messages, max_tokens=600, delai=None): + vu["s"] = messages[0]["content"] + return '{"categorie": "Pb Stock", "confiance": "haute", "resume": "x", "course": null, "demande": {"reelle": false, "action": "", "echeance": null}}' + monkeypatch.setattr(ia, "appeler_privaite", faux) + f = a.analyser("Rupture toner", "x@tt.tn", "Le magasin de Gabes est en rupture.", temp_db) + assert "Pb Stock : ruptures et écarts de stock dans les magasins" in vu["s"] + assert f["categorie"] == "Pb Stock" + + +def test_definition_par_defaut_sans_saisie(temp_db): + cats = {c["name"]: c for c in db.list_categories(temp_db)} + assert cats["Tunis"].get("definition") is None + assert "Sfax et Tunis" in a.DEFINITIONS["Tunis"] diff --git a/tests/test_rla.py b/tests/test_rla.py new file mode 100644 index 0000000..4fae17e --- /dev/null +++ b/tests/test_rla.py @@ -0,0 +1,16 @@ +from app import rla + +ROWS = [{"id": 3, "id_marche": "AO 58/2024 : Lot01", "reference": "AO 58/2024", "entrepreneur": "YASMINE TELECOMS", + "region_csc": "ULS Gabes", "projet": "Raccordement", "Actif": True, "po_an1": "1084054", "po_an2": "1090840", + "date_fin_marche": "2027-06-25", "annee_contractuelle": {"value": "2ème année"}}, + {"id": 9, "id_marche": "AO 19/2026 : Lot01", "reference": "AO 19/2026", "entrepreneur": "X", "Actif": True}] + + +def test_reference_ao_et_po(): + assert [m["marche"] for m in rla.trouver("Objet : avancement du marché n° 58/2024 lot 1", ROWS)] == ["AO 58/2024 : Lot01"] + t = rla.trouver("Merci de valider le BC 1090840", ROWS) + assert t and t[0]["par"] == "PO" and t[0]["annee"] == "2ème année" + + +def test_pas_de_faux_lien(): + assert rla.trouver("AO 58/2025 et le 21/11/2026, tel 74123456", ROWS) == [] diff --git a/tests/test_suivi_fils.py b/tests/test_suivi_fils.py new file mode 100644 index 0000000..0908376 --- /dev/null +++ b/tests/test_suivi_fils.py @@ -0,0 +1,27 @@ +from datetime import datetime +from zoneinfo import ZoneInfo +from app.suivi import calculer_suivi + +MOI = "nabil.derouiche@" +N = datetime(2026, 11, 21, 10, 0, tzinfo=ZoneInfo("Africa/Tunis")) + + +def _m(i, de, a, d, objet="Rappel"): + return {"message_id": i, "objet": objet, "expediteur": de, "destinataires": a, "date": d} + + +MAILS = [_m("1", "Ali ", "nabil.derouiche@tt.tn", "2026-11-18T09:00:00+01:00"), + _m("2", "Sami ", "nabil.derouiche@tt.tn", "2026-11-19T09:00:00+01:00")] + + +def test_meme_objet_sans_cle_reste_un_fil(): + assert len(calculer_suivi(MAILS, MOI, N, {})) == 1 + + +def test_meme_objet_deux_conversations_separees(): + items = calculer_suivi(MAILS, MOI, N, {}, {"1": "aaaaaaaaaaaa", "2": "bbbbbbbbbbbb"}) + assert len(items) == 2 and {i["avec"] for i in items} == {"Ali", "Sami"} + + +def test_cle_partielle_garde_le_regroupement(): + assert len(calculer_suivi(MAILS, MOI, N, {}, {"1": "aaaaaaaaaaaa"})) == 1