Compare commits
23
Commits
40d416d551
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
054a4d64e8 | ||
|
|
f87c56fee7 | ||
|
|
028cace645 | ||
|
|
c7c28f4079 | ||
|
|
5d98d08a8b | ||
|
|
883b4e1745 | ||
|
|
d1a1f412d3 | ||
|
|
ea7846ba1c | ||
|
|
a4e7ed1f00 | ||
|
|
4c9f0c55b5 | ||
|
|
303177a8f7 | ||
|
|
32f0348d9c | ||
|
|
9db68e70f3 | ||
|
|
44bfbc3a0c | ||
|
|
b712ee10cd | ||
|
|
ce10cae840 | ||
|
|
a9fbd45081 | ||
|
|
cdf0c87fc3 | ||
|
|
60842e69e0 | ||
|
|
cdb78c3e04 | ||
|
|
71262d927e | ||
|
|
ab51591f54 | ||
|
|
4c751eb766 |
No files matched your search
@@ -26,3 +26,12 @@ Application interne de gestion du courrier électronique de Nabil, alimentée pa
|
|||||||
- `GET/POST/PUT/DELETE /api/v1/categories` : CRUD des catégories.
|
- `GET/POST/PUT/DELETE /api/v1/categories` : CRUD des catégories.
|
||||||
- `GET/POST/PUT/DELETE /api/v1/regles` : CRUD des règles de tri.
|
- `GET/POST/PUT/DELETE /api/v1/regles` : CRUD des règles de tri.
|
||||||
- `POST /api/v1/regles/{id}/confirmer` : Confirmation d'une règle proposée et application aux mails automatiques.
|
- `POST /api/v1/regles/{id}/confirmer` : Confirmation d'une règle proposée et application aux mails automatiques.
|
||||||
|
|
||||||
|
## À suivre (marqueur manuel, sans limite de date)
|
||||||
|
Un mail marqué à la main reste dans l’onglet « À suivre » quelle que soit sa date, groupé par catégorie (couleur propre à chaque catégorie, mails les plus récents en premier). Le marqueur est enregistré dans la base locale de Courrier : O365 et le miroir ne sont jamais modifiés. Chaque entrée garde une copie de l’expéditeur, de l’objet, de la date et de la catégorie, pour rester affichable si le miroir déplace ou purge le mail. Un mail retiré passe en « terminé » (rien n’est supprimé) et peut être remis.
|
||||||
|
- `GET /api/v1/a-suivre?statut=actif|termine|tous` : liste et compteurs.
|
||||||
|
- `POST /api/v1/a-suivre/marquer` : pose le marqueur (un mail déjà actif garde sa date de marquage).
|
||||||
|
- `POST /api/v1/a-suivre/retirer` : retire un ou plusieurs mails (corps : `{"ids": [...]}`), utilisé aussi pour « Tout retirer » d’une catégorie.
|
||||||
|
- `POST /api/v1/a-suivre/remettre` : remet des mails au suivi (annulation ou retour depuis les terminés).
|
||||||
|
- Couleurs : chaque catégorie porte sa couleur (`categories.couleur`, 0 à 12), attribuée à la création et conservée au renommage.
|
||||||
|
- `POST /api/v1/a-suivre/supprimer` : efface définitivement de l’historique des mails déjà terminés (les mails actifs sont ignorés ; O365 n’est jamais modifié).
|
||||||
+625
@@ -0,0 +1,625 @@
|
|||||||
|
"""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)")
|
||||||
|
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:
|
||||||
|
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], contexte: str = "", exemples: 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."
|
||||||
|
)
|
||||||
|
if exemples:
|
||||||
|
consigne += ("\nExemples de choix reels de Nabil sur ses propres mails (objet, expediteur, categorie qu'il a retenue ou refusee). "
|
||||||
|
"Ce ne sont pas des regles a appliquer mot pour mot : un meme expediteur ou un meme objet peut relever d'une autre categorie un autre jour, "
|
||||||
|
"decide d'apres le contenu. Inspire-toi de sa facon de ranger :\n" + exemples + "\n")
|
||||||
|
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}]
|
||||||
|
|
||||||
|
|
||||||
|
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, contexte: str = "") -> Dict[str, Any]:
|
||||||
|
exemples = exemples_nabil(db_path)
|
||||||
|
"""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, contexte, exemples), max_tokens=1200)
|
||||||
|
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, 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, 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, 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, fil))
|
||||||
|
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 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
|
||||||
|
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 ""),
|
||||||
|
"fil": cle_fil(h("Thread-Index"))}
|
||||||
|
|
||||||
|
|
||||||
|
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, 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, m.get("fil"))
|
||||||
|
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()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 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); _decisions_pret(conn)
|
||||||
|
valeur = f["categorie"] if type_ == "categorie" else ", ".join(((f["course"] or {}).get("objets") or []) + ((f["course"] or {}).get("documents") or []))
|
||||||
|
with conn:
|
||||||
|
conn.execute("INSERT INTO decisions_ia (message_id, type, decision, le, valeur, objet, expediteur) VALUES (?, ?, ?, ?, ?, ?, ?) "
|
||||||
|
"ON CONFLICT(message_id, type) DO UPDATE SET decision=excluded.decision, le=excluded.le, "
|
||||||
|
"valeur=excluded.valeur, objet=excluded.objet, expediteur=excluded.expediteur",
|
||||||
|
(message_id, type_, decision, get_tunis_now_iso(), valeur[:200], _court(f["objet"], 200), _court(f["expediteur"], 120)))
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
return resultat
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Apprentissage par exemples : les choix de Nabil guident l'IA, sans aucune regle ----------
|
||||||
|
|
||||||
|
def _decisions_pret(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))")
|
||||||
|
cols = {r[1] for r in conn.execute("PRAGMA table_info(decisions_ia)")}
|
||||||
|
for c in ("valeur", "objet", "expediteur"):
|
||||||
|
if c not in cols:
|
||||||
|
conn.execute("ALTER TABLE decisions_ia ADD COLUMN %s TEXT" % c)
|
||||||
|
|
||||||
|
|
||||||
|
def exemples_nabil(db_path: Optional[str] = None, par_categorie: int = 3, maximum: int = 14, refus: int = 4) -> str:
|
||||||
|
"""Quelques classements manuels recents (au plus 3 par categorie) et quelques refus. Objet et expediteur seulement,
|
||||||
|
jamais le corps ; l'ensemble passe par PrivAiTe comme le reste."""
|
||||||
|
conn = _db.get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_decisions_pret(conn)
|
||||||
|
lignes = conn.execute("SELECT categorie, objet, expediteur FROM classements WHERE source='manuel' "
|
||||||
|
"AND categorie<>'À classer' AND objet<>'' ORDER BY horodatage DESC LIMIT 200").fetchall()
|
||||||
|
compte: Dict[str, int] = {}
|
||||||
|
sortie: List[str] = []
|
||||||
|
for cat, obj, exp in lignes:
|
||||||
|
if compte.get(cat, 0) >= par_categorie or len(sortie) >= maximum:
|
||||||
|
continue
|
||||||
|
compte[cat] = compte.get(cat, 0) + 1
|
||||||
|
sortie.append("- %s | %s => %s" % (_court(obj, 90), _court(exp, 50), cat))
|
||||||
|
for val, obj, exp in conn.execute("SELECT valeur, objet, expediteur FROM decisions_ia WHERE type='categorie' "
|
||||||
|
"AND decision='refuser' AND valeur IS NOT NULL ORDER BY le DESC LIMIT ?", (refus,)):
|
||||||
|
sortie.append("- %s | %s => PAS %s (propose puis refuse)" % (_court(obj, 90), _court(exp, 50), val))
|
||||||
|
return "\n".join(sortie)
|
||||||
|
except sqlite3.OperationalError:
|
||||||
|
return ""
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def stats_acceptation(db_path: Optional[str] = None) -> Dict[str, Any]:
|
||||||
|
conn = _db.get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_decisions_pret(conn)
|
||||||
|
cats: Dict[str, Dict[str, int]] = {}
|
||||||
|
tot = {"acceptees": 0, "refusees": 0}
|
||||||
|
for typ, dec, val, n in conn.execute("SELECT type, decision, COALESCE(valeur,''), COUNT(*) FROM decisions_ia GROUP BY 1,2,3"):
|
||||||
|
cle = val if typ == "categorie" and val else ("Courses" if typ == "course" else "Autres")
|
||||||
|
d = cats.setdefault(cle, {"acceptees": 0, "refusees": 0})
|
||||||
|
k = "acceptees" if dec == "accepter" else "refusees"
|
||||||
|
d[k] += n; tot[k] += n
|
||||||
|
return {"total": tot, "categories": cats}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def briefing(jour: Optional[str] = None, db_path: Optional[str] = None) -> Dict[str, Any]:
|
||||||
|
"""Briefing du matin : uniquement des fiches deja produites et des tables locales, aucun appel de modele.
|
||||||
|
Demandes encore ouvertes = demandes reelles des 7 derniers jours dont le mail n'est pas marque traite."""
|
||||||
|
jour = jour or get_tunis_now_iso()[:10]
|
||||||
|
depuis = (_date.fromisoformat(jour) - timedelta(days=7)).isoformat()
|
||||||
|
conn = _db.get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_pret(conn)
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
traites = {r[0] for r in conn.execute("SELECT message_id FROM classements WHERE traite = 1")}
|
||||||
|
ouvertes, echeances = [], []
|
||||||
|
for r in conn.execute("SELECT * FROM analyses_ia WHERE date_mail >= ? ORDER BY date_mail DESC LIMIT 300", (depuis,)):
|
||||||
|
f = _ligne(r)
|
||||||
|
d = f["demande"] or {}
|
||||||
|
if d.get("reelle") and f["message_id"] not in traites:
|
||||||
|
it = {"message_id": f["message_id"], "objet": f["objet"], "expediteur": f["expediteur"],
|
||||||
|
"date": f["date"], "action": d.get("action"), "echeance": d.get("echeance")}
|
||||||
|
ouvertes.append(it)
|
||||||
|
try:
|
||||||
|
courses = [dict(x) for x in conn.execute("SELECT id, demande, sens, statut FROM courses WHERE statut = 'a_faire' ORDER BY id DESC LIMIT 30")]
|
||||||
|
except sqlite3.OperationalError:
|
||||||
|
courses = []
|
||||||
|
try:
|
||||||
|
suivi = [dict(x) for x in conn.execute("SELECT objet, expediteur, marque_le FROM a_suivre WHERE statut = 'actif' ORDER BY marque_le DESC LIMIT 30")]
|
||||||
|
except sqlite3.OperationalError:
|
||||||
|
suivi = []
|
||||||
|
repart = [dict(x) for x in conn.execute(
|
||||||
|
"SELECT categorie, COUNT(*) AS mails, SUM(traite) AS traites FROM classements WHERE date_mail LIKE ? GROUP BY categorie ORDER BY mails DESC", (jour + "%",))]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
def cle(i):
|
||||||
|
e = i["echeance"] or ""
|
||||||
|
return (e[6:] + e[3:5] + e[:2]) if e else "99999999"
|
||||||
|
ouvertes.sort(key=cle)
|
||||||
|
return {"jour": jour, "demandes_ouvertes": ouvertes, "propositions_a_valider": len(a_valider(14, db_path)),
|
||||||
|
"courses_a_faire": courses, "a_suivre_actifs": suivi, "repartition_du_jour": repart}
|
||||||
|
|
||||||
|
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)}
|
||||||
|
|
||||||
|
@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("/briefing")
|
||||||
|
def briefing_matin(date: Optional[str] = None):
|
||||||
|
return briefing(date)
|
||||||
|
|
||||||
|
@router.get("/stats")
|
||||||
|
def stats_ia():
|
||||||
|
return stats_acceptation()
|
||||||
|
|
||||||
|
@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
|
||||||
|
|
||||||
|
|
||||||
|
def _routeur_regles_auto():
|
||||||
|
from fastapi import APIRouter
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from app import classifier as _c
|
||||||
|
r = APIRouter()
|
||||||
|
|
||||||
|
class Etat(BaseModel):
|
||||||
|
actif: bool
|
||||||
|
|
||||||
|
@r.get("/regles/auto")
|
||||||
|
def lire_regles_auto():
|
||||||
|
return {"actif": _c.regles_auto_actives()}
|
||||||
|
|
||||||
|
@r.put("/regles/auto")
|
||||||
|
def regler_regles_auto(e: Etat):
|
||||||
|
_c.regler_regles_auto(e.actif)
|
||||||
|
return {"actif": _c.regles_auto_actives()}
|
||||||
|
return r
|
||||||
+147
@@ -0,0 +1,147 @@
|
|||||||
|
"""Mails marqués « À suivre ».
|
||||||
|
|
||||||
|
Le marqueur appartient à Courrier : il est enregistré dans la base locale et n’écrit jamais dans O365 ni dans le miroir.
|
||||||
|
Il ne dépend d’aucune date : un mail marqué reste dans la liste jusqu’à ce qu’il soit retiré.
|
||||||
|
Chaque entrée garde une copie de l’expéditeur, de l’objet, de la date et de la catégorie au moment du marquage,
|
||||||
|
pour rester affichable même si le miroir déplace ou purge le mail.
|
||||||
|
"""
|
||||||
|
from datetime import date
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
from app.config import get_tunis_now_iso
|
||||||
|
from app.db import get_connection
|
||||||
|
|
||||||
|
MAX_IDS = 500
|
||||||
|
|
||||||
|
|
||||||
|
def _pret(conn) -> None:
|
||||||
|
conn.execute(
|
||||||
|
"""CREATE TABLE IF NOT EXISTS a_suivre (
|
||||||
|
message_id TEXT PRIMARY KEY,
|
||||||
|
expediteur TEXT,
|
||||||
|
objet TEXT,
|
||||||
|
date_mail TEXT,
|
||||||
|
categorie TEXT NOT NULL DEFAULT 'À classer',
|
||||||
|
marque_le TEXT NOT NULL,
|
||||||
|
statut TEXT NOT NULL DEFAULT 'actif',
|
||||||
|
termine_le TEXT
|
||||||
|
)"""
|
||||||
|
)
|
||||||
|
conn.execute("CREATE INDEX IF NOT EXISTS idx_a_suivre_statut ON a_suivre(statut)")
|
||||||
|
|
||||||
|
|
||||||
|
def _jours_depuis(horodatage: Optional[str]) -> int:
|
||||||
|
try:
|
||||||
|
debut = date.fromisoformat(str(horodatage)[:10])
|
||||||
|
fin = date.fromisoformat(get_tunis_now_iso()[:10])
|
||||||
|
return max(0, (fin - debut).days)
|
||||||
|
except Exception:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
_SELECT = (
|
||||||
|
"SELECT a.message_id, a.expediteur, a.objet, a.date_mail, a.statut, a.marque_le, a.termine_le, "
|
||||||
|
"COALESCE(c.categorie, a.categorie) AS categorie "
|
||||||
|
"FROM a_suivre a LEFT JOIN classements c ON c.message_id = a.message_id"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _vers_dict(r) -> Dict[str, Any]:
|
||||||
|
d = dict(r)
|
||||||
|
d["jours"] = _jours_depuis(d.get("marque_le"))
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def _un(conn, message_id: str) -> Dict[str, Any]:
|
||||||
|
return _vers_dict(conn.execute(_SELECT + " WHERE a.message_id = ?", (message_id,)).fetchone())
|
||||||
|
|
||||||
|
|
||||||
|
def marquer(message_id: str, expediteur: Optional[str] = None, objet: Optional[str] = None,
|
||||||
|
date_mail: Optional[str] = None, categorie: Optional[str] = None,
|
||||||
|
db_path: Optional[str] = None) -> Dict[str, Any]:
|
||||||
|
"""Pose le marqueur (ou le réactive si le mail avait été retiré). Un mail déjà actif garde sa date de marquage."""
|
||||||
|
conn = get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_pret(conn)
|
||||||
|
cat = (categorie or "").strip()
|
||||||
|
if not cat:
|
||||||
|
r = conn.execute("SELECT categorie FROM classements WHERE message_id = ?", (message_id,)).fetchone()
|
||||||
|
cat = r["categorie"] if r else "À classer"
|
||||||
|
maintenant = get_tunis_now_iso()
|
||||||
|
with conn:
|
||||||
|
conn.execute(
|
||||||
|
"""INSERT INTO a_suivre (message_id, expediteur, objet, date_mail, categorie, marque_le, statut, termine_le)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, 'actif', NULL)
|
||||||
|
ON CONFLICT(message_id) DO UPDATE SET
|
||||||
|
expediteur = COALESCE(NULLIF(excluded.expediteur, ''), a_suivre.expediteur),
|
||||||
|
objet = COALESCE(NULLIF(excluded.objet, ''), a_suivre.objet),
|
||||||
|
date_mail = COALESCE(NULLIF(excluded.date_mail, ''), a_suivre.date_mail),
|
||||||
|
categorie = excluded.categorie,
|
||||||
|
marque_le = CASE WHEN a_suivre.statut = 'actif' THEN a_suivre.marque_le ELSE excluded.marque_le END,
|
||||||
|
statut = 'actif',
|
||||||
|
termine_le = NULL""",
|
||||||
|
(message_id, expediteur or "", objet or "", date_mail or "", cat, maintenant),
|
||||||
|
)
|
||||||
|
return _un(conn, message_id)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def lister(statut: Optional[str] = None, db_path: Optional[str] = None) -> Dict[str, Any]:
|
||||||
|
"""Entrées du suivi, les plus récentes en premier (date du mail). La catégorie est la catégorie actuelle du mail."""
|
||||||
|
conn = get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_pret(conn)
|
||||||
|
if statut in ("actif", "termine"):
|
||||||
|
rows = conn.execute(_SELECT + " WHERE a.statut = ?", (statut,)).fetchall()
|
||||||
|
else:
|
||||||
|
rows = conn.execute(_SELECT).fetchall()
|
||||||
|
items = [_vers_dict(r) for r in rows]
|
||||||
|
items.sort(key=lambda i: (i.get("date_mail") or i.get("marque_le") or ""), reverse=True)
|
||||||
|
compte = {"actif": 0, "termine": 0}
|
||||||
|
for r in conn.execute("SELECT statut, COUNT(*) AS n FROM a_suivre GROUP BY statut"):
|
||||||
|
compte[r["statut"]] = r["n"]
|
||||||
|
return {"items": items, "compte": compte}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def changer_statut(ids: List[str], statut: str, db_path: Optional[str] = None) -> List[str]:
|
||||||
|
"""Retire (statut « termine ») ou remet (statut « actif ») des mails. Aucune suppression : la date de marquage est conservée."""
|
||||||
|
if statut not in ("actif", "termine"):
|
||||||
|
raise ValueError("Statut inconnu.")
|
||||||
|
ids = list(dict.fromkeys(i for i in ids if i))[:MAX_IDS]
|
||||||
|
conn = get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_pret(conn)
|
||||||
|
touches: List[str] = []
|
||||||
|
maintenant = get_tunis_now_iso()
|
||||||
|
with conn:
|
||||||
|
for i in ids:
|
||||||
|
cur = conn.execute(
|
||||||
|
"UPDATE a_suivre SET statut = ?, termine_le = ? WHERE message_id = ? AND statut != ?",
|
||||||
|
(statut, maintenant if statut == "termine" else None, i, statut),
|
||||||
|
)
|
||||||
|
if cur.rowcount:
|
||||||
|
touches.append(i)
|
||||||
|
return touches
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def supprimer(ids: List[str], db_path: Optional[str] = None) -> List[str]:
|
||||||
|
"""Efface définitivement de l’historique des mails déjà retirés (statut « termine »).
|
||||||
|
Un mail encore actif n’est jamais supprimé ici : il faut d’abord le retirer. Le mail lui-même (O365, miroir) n’est pas touché."""
|
||||||
|
ids = list(dict.fromkeys(i for i in ids if i))[:MAX_IDS]
|
||||||
|
conn = get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_pret(conn)
|
||||||
|
effaces: List[str] = []
|
||||||
|
with conn:
|
||||||
|
for i in ids:
|
||||||
|
cur = conn.execute("DELETE FROM a_suivre WHERE message_id = ? AND statut = 'termine'", (i,))
|
||||||
|
if cur.rowcount:
|
||||||
|
effaces.append(i)
|
||||||
|
return effaces
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
"""Brouillon de reponse (tt-2026-11-072) : l'IA propose un texte, Nabil le relit, le copie, l'envoie lui-meme.
|
||||||
|
Courrier n'ecrit jamais dans la messagerie et ne conserve pas le brouillon. Meme sortie unique que le reste :
|
||||||
|
PrivAiTe, refus net s'il est injoignable. Le HTML recu du modele est reduit a une liste blanche de balises
|
||||||
|
sans attribut, pour que la copie garde la mise en page (paragraphes, gras, listes) sans rien d'actif."""
|
||||||
|
import re
|
||||||
|
from html import escape
|
||||||
|
from html.parser import HTMLParser
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Query
|
||||||
|
|
||||||
|
from app import ia
|
||||||
|
from app import analyse as _a
|
||||||
|
|
||||||
|
AUTORISEES = {"p", "br", "strong", "b", "em", "i", "u", "ul", "ol", "li"}
|
||||||
|
AUTO_FERMEES = {"br"}
|
||||||
|
|
||||||
|
|
||||||
|
class _Nettoyeur(HTMLParser):
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__(convert_charrefs=True)
|
||||||
|
self.sortie: List[str] = []
|
||||||
|
self.ouvertes: List[str] = []
|
||||||
|
|
||||||
|
def handle_starttag(self, tag, attrs):
|
||||||
|
if tag in AUTORISEES:
|
||||||
|
if tag in AUTO_FERMEES:
|
||||||
|
self.sortie.append("<br>")
|
||||||
|
else:
|
||||||
|
self.sortie.append("<%s>" % tag); self.ouvertes.append(tag)
|
||||||
|
|
||||||
|
def handle_endtag(self, tag):
|
||||||
|
if tag in AUTORISEES and tag not in AUTO_FERMEES and tag in self.ouvertes:
|
||||||
|
while self.ouvertes:
|
||||||
|
t = self.ouvertes.pop()
|
||||||
|
self.sortie.append("</%s>" % t)
|
||||||
|
if t == tag:
|
||||||
|
break
|
||||||
|
|
||||||
|
def handle_data(self, data):
|
||||||
|
self.sortie.append(escape(data, quote=False))
|
||||||
|
|
||||||
|
def fin(self) -> str:
|
||||||
|
while self.ouvertes:
|
||||||
|
self.sortie.append("</%s>" % self.ouvertes.pop())
|
||||||
|
return "".join(self.sortie)
|
||||||
|
|
||||||
|
|
||||||
|
def assainir(html: str) -> str:
|
||||||
|
html = re.sub(r"(?is)<(script|style)\b.*?</\1>", "", html or "")
|
||||||
|
n = _Nettoyeur(); n.feed(html); n.close()
|
||||||
|
return n.fin().strip()
|
||||||
|
|
||||||
|
|
||||||
|
def en_texte(html: str) -> str:
|
||||||
|
t = re.sub(r"(?i)<br\s*/?>", "\n", html)
|
||||||
|
t = re.sub(r"(?i)</(p|li|ul|ol)>", "\n", t)
|
||||||
|
t = re.sub(r"(?i)<li>", "- ", t)
|
||||||
|
t = re.sub(r"<[^>]+>", "", t)
|
||||||
|
from html import unescape
|
||||||
|
return re.sub(r"\n{3,}", "\n\n", unescape(t)).strip()
|
||||||
|
|
||||||
|
|
||||||
|
CONSIGNE = (
|
||||||
|
"Tu rediges, pour Nabil Derouiche, chef de la division Supply Chain de la Direction Regionale de Sfax de Tunisie Telecom, "
|
||||||
|
"un brouillon de reponse a un mail. Ecris en francais correct avec tous les accents, dans un style naturel, direct et "
|
||||||
|
"professionnel, comme un responsable qui repond lui-meme : phrases simples, pas de formules ampoulees, pas de tirets longs, "
|
||||||
|
"pas de listes artificielles de trois elements, aucune mention d'outil, d'IA ou d'assistant. "
|
||||||
|
"Reponds a ce qui est demande, sans rien inventer : si une information manque (date, montant, decision), "
|
||||||
|
"ecris un passage entre crochets [a completer] plutot que de l'imaginer. "
|
||||||
|
"Termine par « Cordialement, » puis « Nabil Derouiche ». "
|
||||||
|
"Format de sortie : UNIQUEMENT du HTML simple (balises p, br, strong, ul, ol, li), sans titre, sans bloc de code, "
|
||||||
|
"sans objet ni en-tete, sans texte autour."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def construire(objet: str, expediteur: str, corps: str, contexte: str = "", consigne_nabil: str = "") -> list:
|
||||||
|
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 auquel repondre :\n" + texte
|
||||||
|
if consigne_nabil:
|
||||||
|
texte += "\n\nIndication de Nabil pour la reponse : " + consigne_nabil[:300]
|
||||||
|
return [{"role": "system", "content": CONSIGNE}, {"role": "user", "content": texte}]
|
||||||
|
|
||||||
|
|
||||||
|
def rediger(objet: str, expediteur: str, corps: str, contexte: str = "", consigne_nabil: str = "") -> dict:
|
||||||
|
rep = ia.appeler_privaite(construire(objet, expediteur, corps, contexte, consigne_nabil), max_tokens=1500)
|
||||||
|
rep = re.sub(r"^```(?:html)?\s*|\s*```$", "", (rep or "").strip())
|
||||||
|
html = assainir(rep if "<" in rep else "<p>" + escape(rep).replace("\n\n", "</p><p>").replace("\n", "<br>") + "</p>")
|
||||||
|
if not html:
|
||||||
|
raise ia.IAIndisponible("reponse vide")
|
||||||
|
sujet = objet or ""
|
||||||
|
if sujet and not re.match(r"(?i)^\s*(re|rép?|reponse)\s*:", sujet):
|
||||||
|
sujet = "RE: " + sujet
|
||||||
|
return {"objet": sujet[:200], "html": html, "texte": en_texte(html)}
|
||||||
|
|
||||||
|
|
||||||
|
def creer_routeur(mirror_client) -> APIRouter:
|
||||||
|
r = APIRouter(prefix="/ia")
|
||||||
|
|
||||||
|
@r.post("/brouillon")
|
||||||
|
def brouillon(id: str = Query(..., min_length=1, max_length=400), indication: Optional[str] = Query(None, max_length=300)):
|
||||||
|
if not ia.ia_active():
|
||||||
|
raise HTTPException(status_code=409, detail="L'IA est désactivée.")
|
||||||
|
try:
|
||||||
|
m = _a._lire_mail(mirror_client, id)
|
||||||
|
if m is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Mail introuvable.")
|
||||||
|
return rediger(m["objet"], m["de"], m["corps"], _a.contexte_fil(m.get("fil"), id), indication or "")
|
||||||
|
except HTTPException:
|
||||||
|
raise
|
||||||
|
except ia.IAIndisponible as e:
|
||||||
|
raise HTTPException(status_code=503, detail="IA indisponible, aucun brouillon : " + str(e) + ".")
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=502, detail="Lecture du mail impossible : miroir indisponible.")
|
||||||
|
return r
|
||||||
+101
-3
@@ -19,6 +19,40 @@ STOPWORDS = {
|
|||||||
"ces", "a", "à", "the", "of", "to", "in", "for", "and", "is", "on", "at", "by"
|
"ces", "a", "à", "the", "of", "to", "in", "for", "and", "is", "on", "at", "by"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
def regles_auto_actives(db_path: Optional[str] = None) -> bool:
|
||||||
|
"""Reglage global : les regles automatiques (mots-cles, expediteur, etiquette) ne decident plus
|
||||||
|
du classement ni des courses tant qu'il est eteint (defaut). Decision de Nabil du 20/11/2026 :
|
||||||
|
un meme expediteur ou un meme objet ne dit pas la meme chose d'un jour a l'autre, c'est le contenu
|
||||||
|
(lu par l'IA, propose puis valide) qui decide."""
|
||||||
|
from app.db import get_connection
|
||||||
|
conn = get_connection(db_path)
|
||||||
|
try:
|
||||||
|
conn.execute("CREATE TABLE IF NOT EXISTS reglages (cle TEXT PRIMARY KEY, valeur TEXT NOT NULL, le TEXT NOT NULL)")
|
||||||
|
r = conn.execute("SELECT valeur FROM reglages WHERE cle='regles_auto'").fetchone()
|
||||||
|
return bool(r and r[0] == "1")
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def regler_regles_auto(actif: bool, db_path: Optional[str] = None) -> None:
|
||||||
|
from app.db import get_connection
|
||||||
|
conn = get_connection(db_path)
|
||||||
|
try:
|
||||||
|
conn.execute("CREATE TABLE IF NOT EXISTS reglages (cle TEXT PRIMARY KEY, valeur TEXT NOT NULL, le TEXT NOT NULL)")
|
||||||
|
with conn:
|
||||||
|
conn.execute("INSERT INTO reglages (cle, valeur, le) VALUES ('regles_auto', ?, ?) "
|
||||||
|
"ON CONFLICT(cle) DO UPDATE SET valeur=excluded.valeur, le=excluded.le",
|
||||||
|
("1" if actif else "0", get_tunis_now_iso()))
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _regles_actives(db_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||||
|
if not regles_auto_actives(db_path):
|
||||||
|
return []
|
||||||
|
return list_regles(statut="active", db_path=db_path)
|
||||||
|
|
||||||
|
|
||||||
def extract_keywords(text: Optional[str]) -> str:
|
def extract_keywords(text: Optional[str]) -> str:
|
||||||
"""Extrait les mots significatifs d'un objet de mail."""
|
"""Extrait les mots significatifs d'un objet de mail."""
|
||||||
if not text:
|
if not text:
|
||||||
@@ -79,7 +113,7 @@ def classify_mail(mail: Dict[str, Any], db_path: Optional[str] = None) -> Dict[s
|
|||||||
# Conserver le classement manuel existant
|
# Conserver le classement manuel existant
|
||||||
return existing
|
return existing
|
||||||
|
|
||||||
rules = list_regles(statut="active", db_path=db_path)
|
rules = _regles_actives(db_path)
|
||||||
categorie = match_mail_to_rules(mail, rules)
|
categorie = match_mail_to_rules(mail, rules)
|
||||||
|
|
||||||
tags = mail.get("etiquettes") or mail.get("tags") or []
|
tags = mail.get("etiquettes") or mail.get("tags") or []
|
||||||
@@ -129,7 +163,7 @@ def manual_classify_and_propose(
|
|||||||
# Proposition d'une règle basée sur l'expéditeur et les mots-clés
|
# Proposition d'une règle basée sur l'expéditeur et les mots-clés
|
||||||
mots = extract_keywords(obj)
|
mots = extract_keywords(obj)
|
||||||
proposed_rule = None
|
proposed_rule = None
|
||||||
if exp or mots:
|
if (exp or mots) and regles_auto_actives(db_path):
|
||||||
proposed_rule = add_regle(
|
proposed_rule = add_regle(
|
||||||
categorie=new_category,
|
categorie=new_category,
|
||||||
expediteur=exp or None,
|
expediteur=exp or None,
|
||||||
@@ -145,7 +179,7 @@ def reclassify_all_non_manual(db_path: Optional[str] = None, date_prefix: Option
|
|||||||
Réévalue et reclasse tous les emails non-manuels enregistrés en base.
|
Réévalue et reclasse tous les emails non-manuels enregistrés en base.
|
||||||
RÈGLE ABSOLUE : Les classements manuels ne sont jamais touchés.
|
RÈGLE ABSOLUE : Les classements manuels ne sont jamais touchés.
|
||||||
"""
|
"""
|
||||||
active_rules = list_regles(statut="active", db_path=db_path)
|
active_rules = _regles_actives(db_path)
|
||||||
all_classements = list_classements(date_prefix=date_prefix, db_path=db_path)
|
all_classements = list_classements(date_prefix=date_prefix, db_path=db_path)
|
||||||
reclassified_count = 0
|
reclassified_count = 0
|
||||||
|
|
||||||
@@ -214,3 +248,67 @@ def confirm_and_apply_rule(regle_id: int, db_path: Optional[str] = None) -> Opti
|
|||||||
|
|
||||||
reclassify_all_non_manual(db_path=db_path)
|
reclassify_all_non_manual(db_path=db_path)
|
||||||
return rule
|
return rule
|
||||||
|
|
||||||
|
|
||||||
|
def classify_batch(mails: List[Dict[str, Any]], db_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||||
|
"""Classe un lot de mails en une seule connexion : règles lues une fois, classements existants lus en une
|
||||||
|
requête, écriture seulement quand un classement change (nouveau mail ou règle modifiée), le tout en une
|
||||||
|
transaction. Un classement manuel n'est jamais écrasé. Même résultat que classify_mail, mail par mail."""
|
||||||
|
from app.db import get_connection
|
||||||
|
from app.config import get_tunis_now_iso
|
||||||
|
|
||||||
|
mails = [m for m in mails if m.get("message_id")]
|
||||||
|
if not mails:
|
||||||
|
return []
|
||||||
|
rules = _regles_actives(db_path)
|
||||||
|
conn = get_connection(db_path)
|
||||||
|
try:
|
||||||
|
ids = [m["message_id"] for m in mails]
|
||||||
|
existants: Dict[str, Dict[str, Any]] = {}
|
||||||
|
for i in range(0, len(ids), 400):
|
||||||
|
lot = ids[i:i + 400]
|
||||||
|
req = ("SELECT message_id, categorie, source, horodatage, traite, expediteur, objet, date_mail, etiquettes "
|
||||||
|
"FROM classements WHERE message_id IN (%s)" % ",".join("?" * len(lot)))
|
||||||
|
for r in conn.execute(req, lot):
|
||||||
|
d = dict(r)
|
||||||
|
d["traite"] = bool(d["traite"])
|
||||||
|
existants[d["message_id"]] = d
|
||||||
|
|
||||||
|
maintenant = get_tunis_now_iso()
|
||||||
|
sortie: List[Dict[str, Any]] = []
|
||||||
|
ecritures = []
|
||||||
|
for m in mails:
|
||||||
|
mid = m["message_id"]
|
||||||
|
ex = existants.get(mid)
|
||||||
|
if ex and ex.get("source") == "manuel":
|
||||||
|
sortie.append(ex)
|
||||||
|
continue
|
||||||
|
categorie = match_mail_to_rules(m, rules)
|
||||||
|
tags = m.get("etiquettes") or m.get("tags") or []
|
||||||
|
tags_json = json.dumps(tags) if isinstance(tags, list) else str(tags)
|
||||||
|
exp = (m.get("expediteur") or m.get("from") or "") or (ex["expediteur"] if ex else "")
|
||||||
|
obj = (m.get("objet") or m.get("subject") or "") or (ex["objet"] if ex else "")
|
||||||
|
date_mail = (m.get("date") or "") or (ex["date_mail"] if ex else "")
|
||||||
|
etiq = tags_json if tags_json != "[]" else ((ex.get("etiquettes") if ex else None) or "[]")
|
||||||
|
if ex and (ex["categorie"], ex["expediteur"], ex["objet"], ex["date_mail"], ex.get("etiquettes") or "[]") == (categorie, exp, obj, date_mail, etiq):
|
||||||
|
sortie.append(ex) # inchangé : aucune écriture
|
||||||
|
continue
|
||||||
|
traite = ex["traite"] if ex else False
|
||||||
|
ecritures.append((mid, categorie, maintenant, 1 if traite else 0, exp, obj, date_mail, etiq))
|
||||||
|
sortie.append({"message_id": mid, "categorie": categorie, "source": "regle", "horodatage": maintenant,
|
||||||
|
"traite": traite, "expediteur": exp, "objet": obj, "date_mail": date_mail, "etiquettes": etiq})
|
||||||
|
if ecritures:
|
||||||
|
with conn:
|
||||||
|
conn.executemany(
|
||||||
|
"""
|
||||||
|
INSERT INTO classements (message_id, categorie, source, horodatage, traite, expediteur, objet, date_mail, etiquettes)
|
||||||
|
VALUES (?, ?, 'regle', ?, ?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT(message_id) DO UPDATE SET
|
||||||
|
categorie = excluded.categorie, source = 'regle', horodatage = excluded.horodatage,
|
||||||
|
expediteur = excluded.expediteur, objet = excluded.objet, date_mail = excluded.date_mail,
|
||||||
|
etiquettes = CASE WHEN excluded.etiquettes != '[]' THEN excluded.etiquettes ELSE classements.etiquettes END
|
||||||
|
WHERE classements.source != 'manuel'
|
||||||
|
""", ecritures)
|
||||||
|
return sortie
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
@@ -13,6 +13,35 @@ def get_connection(db_path: Optional[str] = None) -> sqlite3.Connection:
|
|||||||
conn.execute("PRAGMA foreign_keys=ON")
|
conn.execute("PRAGMA foreign_keys=ON")
|
||||||
return conn
|
return conn
|
||||||
|
|
||||||
|
# Couleur stable par catégorie (jetons --ny-cat-N de l’interface) : 0 = catégorie système, 1 à 5 = catégories d’origine,
|
||||||
|
# 6 à 12 = les autres, chacune sur sa propre couleur tant qu’il en reste (la moins utilisée sinon).
|
||||||
|
COULEURS_ORIGINE = {"À classer": 0, "Tunis": 1, "Demande FB": 2, "CI": 3, "Câbles": 4, "Sans objet": 5}
|
||||||
|
COULEUR_MIN, COULEUR_MAX = 6, 12
|
||||||
|
|
||||||
|
|
||||||
|
def _couleur_libre(conn: sqlite3.Connection, souhaitee: Optional[int] = None) -> int:
|
||||||
|
prises = {r[0] for r in conn.execute("SELECT couleur FROM categories WHERE couleur IS NOT NULL")}
|
||||||
|
if souhaitee is not None and COULEUR_MIN <= souhaitee <= COULEUR_MAX and souhaitee not in prises:
|
||||||
|
return souhaitee
|
||||||
|
for c in range(COULEUR_MIN, COULEUR_MAX + 1):
|
||||||
|
if c not in prises:
|
||||||
|
return c
|
||||||
|
usage = {c: 0 for c in range(COULEUR_MIN, COULEUR_MAX + 1)}
|
||||||
|
for r in conn.execute("SELECT couleur FROM categories WHERE couleur BETWEEN ? AND ?", (COULEUR_MIN, COULEUR_MAX)):
|
||||||
|
usage[r[0]] += 1
|
||||||
|
return min(usage, key=lambda c: (usage[c], c))
|
||||||
|
|
||||||
|
|
||||||
|
def _attribuer_couleurs(conn: sqlite3.Connection) -> None:
|
||||||
|
"""Donne une couleur aux catégories qui n’en ont pas encore. Les catégories existantes gardent leur ancienne teinte quand elle est libre."""
|
||||||
|
for r in conn.execute("SELECT id, name FROM categories WHERE couleur IS NULL ORDER BY id").fetchall():
|
||||||
|
if r["name"] in COULEURS_ORIGINE:
|
||||||
|
c = COULEURS_ORIGINE[r["name"]]
|
||||||
|
else:
|
||||||
|
c = _couleur_libre(conn, 6 + (r["id"] % 3))
|
||||||
|
conn.execute("UPDATE categories SET couleur = ? WHERE id = ?", (c, r["id"]))
|
||||||
|
|
||||||
|
|
||||||
def init_db(db_path: Optional[str] = None) -> None:
|
def init_db(db_path: Optional[str] = None) -> None:
|
||||||
conn = get_connection(db_path)
|
conn = get_connection(db_path)
|
||||||
try:
|
try:
|
||||||
@@ -56,6 +85,10 @@ def init_db(db_path: Optional[str] = None) -> None:
|
|||||||
if "etiquettes" not in cols:
|
if "etiquettes" not in cols:
|
||||||
conn.execute("ALTER TABLE classements ADD COLUMN etiquettes TEXT DEFAULT '[]'")
|
conn.execute("ALTER TABLE classements ADD COLUMN etiquettes TEXT DEFAULT '[]'")
|
||||||
|
|
||||||
|
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")
|
||||||
|
|
||||||
now = get_tunis_now_iso()
|
now = get_tunis_now_iso()
|
||||||
|
|
||||||
# Initialisation idempotente des catégories par défaut
|
# Initialisation idempotente des catégories par défaut
|
||||||
@@ -65,6 +98,8 @@ def init_db(db_path: Optional[str] = None) -> None:
|
|||||||
(cat, now)
|
(cat, now)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
_attribuer_couleurs(conn)
|
||||||
|
|
||||||
# Initialisation idempotente des règles de départ
|
# Initialisation idempotente des règles de départ
|
||||||
for rule in DEFAULT_RULES:
|
for rule in DEFAULT_RULES:
|
||||||
cat = rule["categorie"]
|
cat = rule["categorie"]
|
||||||
@@ -98,7 +133,7 @@ def init_db(db_path: Optional[str] = None) -> None:
|
|||||||
def list_categories(db_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
def list_categories(db_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||||
conn = get_connection(db_path)
|
conn = get_connection(db_path)
|
||||||
try:
|
try:
|
||||||
rows = conn.execute("SELECT id, name, created_at FROM categories ORDER BY id ASC").fetchall()
|
rows = conn.execute("SELECT id, name, couleur, created_at FROM categories ORDER BY id ASC").fetchall()
|
||||||
return [dict(r) for r in rows]
|
return [dict(r) for r in rows]
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
@@ -111,12 +146,13 @@ def add_category(name: str, db_path: Optional[str] = None) -> Dict[str, Any]:
|
|||||||
try:
|
try:
|
||||||
now = get_tunis_now_iso()
|
now = get_tunis_now_iso()
|
||||||
with conn:
|
with conn:
|
||||||
|
couleur = _couleur_libre(conn)
|
||||||
cursor = conn.execute(
|
cursor = conn.execute(
|
||||||
"INSERT INTO categories (name, created_at) VALUES (?, ?)",
|
"INSERT INTO categories (name, couleur, created_at) VALUES (?, ?, ?)",
|
||||||
(name, now)
|
(name, couleur, now)
|
||||||
)
|
)
|
||||||
cat_id = cursor.lastrowid
|
cat_id = cursor.lastrowid
|
||||||
return {"id": cat_id, "name": name, "created_at": now}
|
return {"id": cat_id, "name": name, "couleur": couleur, "created_at": now}
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
@@ -137,7 +173,10 @@ def update_category(cat_id: int, new_name: str, db_path: Optional[str] = None) -
|
|||||||
if ancien and ancien["name"] != new_name: # CASCADE-060
|
if ancien and ancien["name"] != new_name: # CASCADE-060
|
||||||
conn.execute("UPDATE classements SET categorie = ? WHERE categorie = ?", (new_name, ancien["name"]))
|
conn.execute("UPDATE classements SET categorie = ? WHERE categorie = ?", (new_name, ancien["name"]))
|
||||||
conn.execute("UPDATE regles SET categorie = ? WHERE categorie = ?", (new_name, ancien["name"]))
|
conn.execute("UPDATE regles SET categorie = ? WHERE categorie = ?", (new_name, ancien["name"]))
|
||||||
row = conn.execute("SELECT id, name, created_at FROM categories WHERE id = ?", (cat_id,)).fetchone()
|
from app.asuivre import _pret as _pret_suivre
|
||||||
|
_pret_suivre(conn)
|
||||||
|
conn.execute("UPDATE a_suivre SET categorie = ? WHERE categorie = ?", (new_name, ancien["name"]))
|
||||||
|
row = conn.execute("SELECT id, name, couleur, created_at FROM categories WHERE id = ?", (cat_id,)).fetchone()
|
||||||
return dict(row) if row else None
|
return dict(row) if row else None
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
@@ -151,6 +190,9 @@ def delete_category(cat_id: int, db_path: Optional[str] = None) -> bool:
|
|||||||
if cursor.rowcount > 0 and ancien: # CASCADE-060
|
if cursor.rowcount > 0 and ancien: # CASCADE-060
|
||||||
conn.execute("UPDATE classements SET categorie = 'À classer' WHERE categorie = ?", (ancien["name"],))
|
conn.execute("UPDATE classements SET categorie = 'À classer' WHERE categorie = ?", (ancien["name"],))
|
||||||
conn.execute("DELETE FROM regles WHERE categorie = ?", (ancien["name"],))
|
conn.execute("DELETE FROM regles WHERE categorie = ?", (ancien["name"],))
|
||||||
|
from app.asuivre import _pret as _pret_suivre
|
||||||
|
_pret_suivre(conn)
|
||||||
|
conn.execute("UPDATE a_suivre SET categorie = 'À classer' WHERE categorie = ?", (ancien["name"],))
|
||||||
return cursor.rowcount > 0
|
return cursor.rowcount > 0
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
@@ -410,3 +452,165 @@ def set_traite(message_id: str, traite: bool, db_path: Optional[str] = None) ->
|
|||||||
return get_classement(message_id, db_path)
|
return get_classement(message_id, db_path)
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
# --- Courses pour Tunis ---
|
||||||
|
SENS_COURSE = ("tunis_sfax", "sfax_tunis")
|
||||||
|
|
||||||
|
|
||||||
|
def _courses_pret(conn: sqlite3.Connection) -> None:
|
||||||
|
conn.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS courses (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
message_id TEXT,
|
||||||
|
demande TEXT NOT NULL,
|
||||||
|
sens TEXT NOT NULL DEFAULT 'tunis_sfax',
|
||||||
|
objet_mail TEXT,
|
||||||
|
expediteur TEXT,
|
||||||
|
date_mail TEXT,
|
||||||
|
statut TEXT NOT NULL DEFAULT 'a_faire',
|
||||||
|
cree_le TEXT NOT NULL,
|
||||||
|
fait_le TEXT
|
||||||
|
)""")
|
||||||
|
|
||||||
|
|
||||||
|
def list_courses(statut: Optional[str] = None, db_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||||
|
conn = get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_courses_pret(conn)
|
||||||
|
if statut in ("a_faire", "faite"):
|
||||||
|
rows = conn.execute("SELECT * FROM courses WHERE statut = ? ORDER BY cree_le DESC, id DESC", (statut,)).fetchall()
|
||||||
|
else:
|
||||||
|
rows = conn.execute("SELECT * FROM courses ORDER BY (statut = 'faite'), cree_le DESC, id DESC").fetchall()
|
||||||
|
return [dict(r) for r in rows]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_course(course_id: int, db_path: Optional[str] = None) -> Optional[Dict[str, Any]]:
|
||||||
|
conn = get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_courses_pret(conn)
|
||||||
|
r = conn.execute("SELECT * FROM courses WHERE id = ?", (course_id,)).fetchone()
|
||||||
|
return dict(r) if r else None
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def add_course(demande: str, sens: str = "tunis_sfax", message_id: Optional[str] = None, objet_mail: Optional[str] = None,
|
||||||
|
expediteur: Optional[str] = None, date_mail: Optional[str] = None, db_path: Optional[str] = None) -> Dict[str, Any]:
|
||||||
|
conn = get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_courses_pret(conn)
|
||||||
|
with conn:
|
||||||
|
cur = conn.execute(
|
||||||
|
"INSERT INTO courses (message_id, demande, sens, objet_mail, expediteur, date_mail, cree_le) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
(message_id, demande, sens, objet_mail, expediteur, date_mail, get_tunis_now_iso()))
|
||||||
|
new_id = cur.lastrowid
|
||||||
|
r = conn.execute("SELECT * FROM courses WHERE id = ?", (new_id,)).fetchone()
|
||||||
|
return dict(r)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def update_course(course_id: int, demande: Optional[str] = None, sens: Optional[str] = None, statut: Optional[str] = None,
|
||||||
|
db_path: Optional[str] = None) -> Optional[Dict[str, Any]]:
|
||||||
|
conn = get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_courses_pret(conn)
|
||||||
|
actuel = conn.execute("SELECT * FROM courses WHERE id = ?", (course_id,)).fetchone()
|
||||||
|
if not actuel:
|
||||||
|
return None
|
||||||
|
champs, vals = [], []
|
||||||
|
if demande is not None:
|
||||||
|
champs.append("demande = ?"); vals.append(demande)
|
||||||
|
if sens is not None:
|
||||||
|
champs.append("sens = ?"); vals.append(sens)
|
||||||
|
if statut is not None and statut != actuel["statut"]:
|
||||||
|
champs.append("statut = ?"); vals.append(statut)
|
||||||
|
champs.append("fait_le = ?"); vals.append(get_tunis_now_iso() if statut == "faite" else None)
|
||||||
|
if champs:
|
||||||
|
with conn:
|
||||||
|
conn.execute("UPDATE courses SET " + ", ".join(champs) + " WHERE id = ?", (*vals, course_id))
|
||||||
|
return dict(conn.execute("SELECT * FROM courses WHERE id = ?", (course_id,)).fetchone())
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _vues_pret(conn: sqlite3.Connection) -> None:
|
||||||
|
conn.execute("CREATE TABLE IF NOT EXISTS courses_vues (cle TEXT PRIMARY KEY, le TEXT NOT NULL)")
|
||||||
|
|
||||||
|
|
||||||
|
def cles_courses_vues(db_path: Optional[str] = None) -> set:
|
||||||
|
"""Fils deja importes ou supprimes : la synchronisation ne les recree pas."""
|
||||||
|
conn = get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_vues_pret(conn)
|
||||||
|
return {r[0] for r in conn.execute("SELECT cle FROM courses_vues")}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def marquer_courses_vues(cles, db_path: Optional[str] = None) -> None:
|
||||||
|
conn = get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_vues_pret(conn)
|
||||||
|
with conn:
|
||||||
|
for c in cles:
|
||||||
|
if c:
|
||||||
|
conn.execute("INSERT OR IGNORE INTO courses_vues (cle, le) VALUES (?, ?)", (c, get_tunis_now_iso()))
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def delete_course(course_id: int, db_path: Optional[str] = None) -> bool:
|
||||||
|
from app.suivi import sujet_normalise
|
||||||
|
conn = get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_courses_pret(conn)
|
||||||
|
_vues_pret(conn)
|
||||||
|
with conn:
|
||||||
|
r = conn.execute("SELECT demande, objet_mail FROM courses WHERE id = ?", (course_id,)).fetchone()
|
||||||
|
if r is None:
|
||||||
|
return False
|
||||||
|
cle = sujet_normalise(r["objet_mail"] or r["demande"])
|
||||||
|
if cle:
|
||||||
|
conn.execute("INSERT OR IGNORE INTO courses_vues (cle, le) VALUES (?, ?)", (cle, get_tunis_now_iso()))
|
||||||
|
return conn.execute("DELETE FROM courses WHERE id = ?", (course_id,)).rowcount > 0
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
# --- Suivi des demandes : fils clos ---
|
||||||
|
def _suivi_pret(conn: sqlite3.Connection) -> None:
|
||||||
|
conn.execute("CREATE TABLE IF NOT EXISTS suivi_clos (cle TEXT PRIMARY KEY, dernier_id TEXT NOT NULL, clos_le TEXT NOT NULL)")
|
||||||
|
|
||||||
|
|
||||||
|
def list_suivi_clos(db_path: Optional[str] = None) -> Dict[str, str]:
|
||||||
|
conn = get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_suivi_pret(conn)
|
||||||
|
return {r["cle"]: r["dernier_id"] for r in conn.execute("SELECT cle, dernier_id FROM suivi_clos").fetchall()}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def clore_suivi(cle: str, dernier_id: str, db_path: Optional[str] = None) -> None:
|
||||||
|
conn = get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_suivi_pret(conn)
|
||||||
|
with conn:
|
||||||
|
conn.execute("INSERT INTO suivi_clos (cle, dernier_id, clos_le) VALUES (?, ?, ?) ON CONFLICT(cle) DO UPDATE SET dernier_id = excluded.dernier_id, clos_le = excluded.clos_le",
|
||||||
|
(cle, dernier_id, get_tunis_now_iso()))
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def rouvrir_suivi(cle: str, db_path: Optional[str] = None) -> bool:
|
||||||
|
conn = get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_suivi_pret(conn)
|
||||||
|
with conn:
|
||||||
|
return conn.execute("DELETE FROM suivi_clos WHERE cle = ?", (cle,)).rowcount > 0
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
"""Export XLSX des courses pour Tunis : une feuille claire, titres en majuscules sans accents."""
|
||||||
|
import io
|
||||||
|
import zipfile
|
||||||
|
from typing import List, Dict, Any
|
||||||
|
|
||||||
|
from openpyxl import Workbook
|
||||||
|
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||||
|
from openpyxl.utils import get_column_letter
|
||||||
|
|
||||||
|
AUTEUR = "Nabil.Derouiche"
|
||||||
|
SENS_LIBELLE = {"tunis_sfax": "Tunis vers Sfax", "sfax_tunis": "Sfax vers Tunis"}
|
||||||
|
STATUT_LIBELLE = {"a_faire": "A faire", "faite": "Faite"}
|
||||||
|
ENTETES = ["N°", "DEMANDE", "SENS", "DATE DU MAIL", "EXPEDITEUR", "OBJET DU MAIL", "STATUT", "REALISEE LE"]
|
||||||
|
LARGEURS = [6, 46, 17, 14, 30, 46, 11, 14]
|
||||||
|
|
||||||
|
|
||||||
|
def _jj_mm_aaaa(iso: str) -> str:
|
||||||
|
j = (iso or "")[:10]
|
||||||
|
p = j.split("-")
|
||||||
|
return f"{p[2]}/{p[1]}/{p[0]}" if len(p) == 3 and len(j) == 10 else ""
|
||||||
|
|
||||||
|
|
||||||
|
def construire_xlsx(courses: List[Dict[str, Any]], libelle_filtre: str, aujourdhui_iso: str) -> bytes:
|
||||||
|
wb = Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = "COURSES"
|
||||||
|
wb.properties.creator = AUTEUR
|
||||||
|
wb.properties.lastModifiedBy = AUTEUR
|
||||||
|
wb.properties.title = "Courses pour Tunis"
|
||||||
|
police = "Calibri"
|
||||||
|
fin = Side(style="thin", color="B7C0CC")
|
||||||
|
bord = Border(left=fin, right=fin, top=fin, bottom=fin)
|
||||||
|
ws["A1"] = "COURSES POUR TUNIS"
|
||||||
|
ws["A1"].font = Font(name=police, size=16, bold=True, color="1F3A5F")
|
||||||
|
ws.merge_cells("A1:H1")
|
||||||
|
ws["A2"] = f"Etat au {_jj_mm_aaaa(aujourdhui_iso)} - {libelle_filtre} - {len(courses)} ligne(s)"
|
||||||
|
ws["A2"].font = Font(name=police, size=11, color="44546A")
|
||||||
|
ws.merge_cells("A2:H2")
|
||||||
|
for i, t in enumerate(ENTETES, 1):
|
||||||
|
c = ws.cell(row=4, column=i, value=t)
|
||||||
|
c.font = Font(name=police, size=11, bold=True, color="FFFFFF")
|
||||||
|
c.fill = PatternFill("solid", fgColor="1F3A5F")
|
||||||
|
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||||
|
c.border = bord
|
||||||
|
ws.row_dimensions[4].height = 24
|
||||||
|
for n, k in enumerate(courses, 1):
|
||||||
|
ligne = [n, k.get("demande") or "", SENS_LIBELLE.get(k.get("sens"), ""), _jj_mm_aaaa(k.get("date_mail") or ""),
|
||||||
|
k.get("expediteur") or "", k.get("objet_mail") or "", STATUT_LIBELLE.get(k.get("statut"), ""),
|
||||||
|
_jj_mm_aaaa(k.get("fait_le") or "")]
|
||||||
|
r = 4 + n
|
||||||
|
for i, v in enumerate(ligne, 1):
|
||||||
|
c = ws.cell(row=r, column=i, value=v)
|
||||||
|
c.font = Font(name=police, size=11, bold=(i == 2), color=("5B6B7F" if k.get("statut") == "faite" else "1B2430"))
|
||||||
|
c.alignment = Alignment(vertical="top", wrap_text=True, horizontal=("center" if i in (1, 4, 7, 8) else "left"))
|
||||||
|
c.border = bord
|
||||||
|
if k.get("statut") == "faite":
|
||||||
|
c.fill = PatternFill("solid", fgColor="EEF3EE")
|
||||||
|
for i, w in enumerate(LARGEURS, 1):
|
||||||
|
ws.column_dimensions[get_column_letter(i)].width = w
|
||||||
|
ws.freeze_panes = "A5"
|
||||||
|
if courses:
|
||||||
|
ws.auto_filter.ref = f"A4:H{4 + len(courses)}"
|
||||||
|
ws.page_setup.orientation = "landscape"
|
||||||
|
ws.page_setup.paperSize = ws.PAPERSIZE_A4
|
||||||
|
ws.page_setup.fitToWidth = 1
|
||||||
|
ws.page_setup.fitToHeight = 0
|
||||||
|
ws.sheet_properties.pageSetUpPr.fitToPage = True
|
||||||
|
ws.print_title_rows = "4:4"
|
||||||
|
buf = io.BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
return _proprietes_neutres(buf.getvalue())
|
||||||
|
|
||||||
|
|
||||||
|
APP_XML = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||||||
|
'<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" '
|
||||||
|
'xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">'
|
||||||
|
'<Application>Microsoft Excel</Application></Properties>')
|
||||||
|
|
||||||
|
|
||||||
|
def _proprietes_neutres(brut: bytes) -> bytes:
|
||||||
|
"""Réécrit les propriétés applicatives du classeur : aucune trace de l'outil de génération."""
|
||||||
|
sortie = io.BytesIO()
|
||||||
|
with zipfile.ZipFile(io.BytesIO(brut)) as src, zipfile.ZipFile(sortie, "w", zipfile.ZIP_DEFLATED) as dst:
|
||||||
|
for item in src.infolist():
|
||||||
|
data = src.read(item.filename)
|
||||||
|
if item.filename == "docProps/app.xml":
|
||||||
|
data = APP_XML.encode("utf-8")
|
||||||
|
dst.writestr(item, data)
|
||||||
|
return sortie.getvalue()
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
"""Couche IA de Courrier (tt-2026-11-072) : suggestion de categorie.
|
||||||
|
|
||||||
|
Regles fermes :
|
||||||
|
- interrupteur desactive par defaut (reglage en base, pas de variable qui l'allume en douce) ;
|
||||||
|
- le texte d'un mail ne part que vers PrivAiTe (alias courrier-main), jamais directement vers un modele ;
|
||||||
|
- PrivAiTe injoignable ou en erreur : refus net (503), aucun contournement ;
|
||||||
|
- la suggestion est proposee, jamais appliquee : aucun classement n'est ecrit ;
|
||||||
|
- aucun contenu de mail dans les journaux (seulement des comptes et des codes).
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
from typing import Any, Dict, Optional
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from fastapi import APIRouter, HTTPException, Query
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from app.config import get_tunis_now_iso
|
||||||
|
from app import db as _db
|
||||||
|
|
||||||
|
log = logging.getLogger("courrier.ia")
|
||||||
|
|
||||||
|
PRIVAITE_URL = os.getenv("PRIVAITE_URL", "http://100.94.90.119:8401/v1/chat/completions")
|
||||||
|
PRIVAITE_KEY_PATH = os.getenv("PRIVAITE_KEY_PATH", "/app/secrets/privaite.key")
|
||||||
|
IA_MODELE = os.getenv("IA_MODELE", "courrier-main")
|
||||||
|
IA_DELAI_S = float(os.getenv("IA_DELAI_S", "40"))
|
||||||
|
MAX_TEXTE = 3000
|
||||||
|
A_CLASSER = "À classer"
|
||||||
|
|
||||||
|
|
||||||
|
class IAIndisponible(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _pret(conn) -> None:
|
||||||
|
conn.execute("CREATE TABLE IF NOT EXISTS reglages (cle TEXT PRIMARY KEY, valeur TEXT NOT NULL, le TEXT NOT NULL)")
|
||||||
|
conn.execute("CREATE TABLE IF NOT EXISTS suggestions_ia (message_id TEXT PRIMARY KEY, categorie TEXT NOT NULL, le TEXT NOT NULL)")
|
||||||
|
|
||||||
|
|
||||||
|
def ia_active(db_path: Optional[str] = None) -> bool:
|
||||||
|
conn = _db.get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_pret(conn)
|
||||||
|
r = conn.execute("SELECT valeur FROM reglages WHERE cle='ia_actif'").fetchone()
|
||||||
|
return bool(r and r[0] == "1")
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def regler_ia(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 ('ia_actif', ?, ?) "
|
||||||
|
"ON CONFLICT(cle) DO UPDATE SET valeur=excluded.valeur, le=excluded.le",
|
||||||
|
("1" if actif else "0", get_tunis_now_iso()))
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _cle() -> str:
|
||||||
|
try:
|
||||||
|
with open(PRIVAITE_KEY_PATH, "r", encoding="utf-8") as f:
|
||||||
|
k = f.read().strip()
|
||||||
|
except OSError:
|
||||||
|
raise IAIndisponible("cle PrivAiTe absente")
|
||||||
|
if not k:
|
||||||
|
raise IAIndisponible("cle PrivAiTe vide")
|
||||||
|
return k
|
||||||
|
|
||||||
|
|
||||||
|
def appeler_privaite(messages, max_tokens: int = 600) -> str:
|
||||||
|
"""Seul point de sortie vers un modele : PrivAiTe. Toute erreur = IAIndisponible, sans repli."""
|
||||||
|
try:
|
||||||
|
r = httpx.post(PRIVAITE_URL, timeout=IA_DELAI_S,
|
||||||
|
headers={"Authorization": "Bearer " + _cle()},
|
||||||
|
json={"model": IA_MODELE, "messages": messages, "max_tokens": max_tokens, "temperature": 0})
|
||||||
|
except httpx.HTTPError as e:
|
||||||
|
log.warning("PrivAiTe injoignable (%s)", type(e).__name__)
|
||||||
|
raise IAIndisponible("PrivAiTe injoignable")
|
||||||
|
if r.status_code != 200:
|
||||||
|
log.warning("PrivAiTe a repondu %s", r.status_code)
|
||||||
|
raise IAIndisponible("PrivAiTe a refuse la requete")
|
||||||
|
try:
|
||||||
|
texte = str(r.json()["choices"][0]["message"]["content"] or "")
|
||||||
|
except (KeyError, IndexError, ValueError, TypeError):
|
||||||
|
raise IAIndisponible("reponse PrivAiTe illisible")
|
||||||
|
if not texte.strip():
|
||||||
|
# Modele de raisonnement : un budget de jetons trop court se voit comme une reponse vide, jamais comme une analyse.
|
||||||
|
raise IAIndisponible("reponse vide (budget de reflexion depasse)")
|
||||||
|
return texte
|
||||||
|
|
||||||
|
|
||||||
|
def construire_messages(objet: str, corps: str, categories) -> list:
|
||||||
|
liste = ", ".join(categories)
|
||||||
|
consigne = ("Tu classes un mail dans UNE categorie parmi : " + liste + ". "
|
||||||
|
"Reponds uniquement par le nom exact de la categorie, sans autre mot. "
|
||||||
|
"Si aucune ne convient clairement, reponds : " + A_CLASSER + ".")
|
||||||
|
texte = "Objet : " + (objet or "(vide)") + "\n\n" + (corps or "")[:MAX_TEXTE]
|
||||||
|
return [{"role": "system", "content": consigne}, {"role": "user", "content": texte}]
|
||||||
|
|
||||||
|
|
||||||
|
def lire_categorie(reponse: str, categories) -> str:
|
||||||
|
"""Valide la reponse du modele contre la liste : tout le reste devient « À classer »."""
|
||||||
|
rep = re.sub(r"[\s\"'.*`]+", " ", reponse or "").strip().lower()
|
||||||
|
for c in categories:
|
||||||
|
if rep == c.lower():
|
||||||
|
return c
|
||||||
|
return A_CLASSER
|
||||||
|
|
||||||
|
|
||||||
|
def suggerer(objet: str, corps: str, db_path: Optional[str] = None) -> Dict[str, Any]:
|
||||||
|
if not ia_active(db_path):
|
||||||
|
raise HTTPException(status_code=409, detail="L'IA est désactivée.")
|
||||||
|
cats = [c["nom"] if "nom" in c else c.get("name") for c in _db.list_categories(db_path)]
|
||||||
|
cats = [c for c in cats if c and c != A_CLASSER]
|
||||||
|
try:
|
||||||
|
rep = appeler_privaite(construire_messages(objet, corps, cats))
|
||||||
|
except IAIndisponible as e:
|
||||||
|
raise HTTPException(status_code=503, detail="IA indisponible, aucune suggestion : " + str(e) + ".")
|
||||||
|
return {"categorie": lire_categorie(rep, cats), "source": "ia", "appliquee": False}
|
||||||
|
|
||||||
|
|
||||||
|
class IAEtat(BaseModel):
|
||||||
|
actif: bool
|
||||||
|
|
||||||
|
|
||||||
|
def creer_routeur(mirror_client) -> APIRouter:
|
||||||
|
router = APIRouter(prefix="/ia")
|
||||||
|
|
||||||
|
@router.get("/etat")
|
||||||
|
def etat():
|
||||||
|
return {"actif": ia_active(), "modele": IA_MODELE}
|
||||||
|
|
||||||
|
@router.put("/etat")
|
||||||
|
def modifier_etat(e: IAEtat):
|
||||||
|
regler_ia(e.actif)
|
||||||
|
return {"actif": ia_active(), "modele": IA_MODELE}
|
||||||
|
|
||||||
|
@router.get("/suggestion")
|
||||||
|
def suggestion(id: str = Query(..., min_length=1, max_length=400)):
|
||||||
|
"""Propose une categorie pour un mail. N'ecrit aucun classement."""
|
||||||
|
if not ia_active():
|
||||||
|
raise HTTPException(status_code=409, detail="L'IA est désactivée.")
|
||||||
|
try:
|
||||||
|
res = mirror_client.get_mail(id)
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=502, detail="Lecture du mail impossible : miroir indisponible.")
|
||||||
|
d = res.get("donnees") if isinstance(res, dict) else None
|
||||||
|
if not isinstance(d, dict) or not d:
|
||||||
|
raise HTTPException(status_code=404, detail="Mail introuvable.")
|
||||||
|
eh = d.get("en_tetes") or {}
|
||||||
|
objet = str(eh.get("Subject") or eh.get("subject") or "")
|
||||||
|
out = suggerer(objet, str(d.get("corps_texte") or ""))
|
||||||
|
conn = _db.get_connection()
|
||||||
|
try:
|
||||||
|
_pret(conn)
|
||||||
|
with conn:
|
||||||
|
conn.execute("INSERT INTO suggestions_ia (message_id, categorie, le) VALUES (?, ?, ?) "
|
||||||
|
"ON CONFLICT(message_id) DO UPDATE SET categorie=excluded.categorie, le=excluded.le",
|
||||||
|
(id, out["categorie"], get_tunis_now_iso()))
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
return out
|
||||||
|
|
||||||
|
return router
|
||||||
+395
-4
@@ -1,12 +1,16 @@
|
|||||||
|
import base64
|
||||||
|
import os
|
||||||
|
import re
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
|
from urllib.parse import quote
|
||||||
from typing import Optional, List, Dict, Any
|
from typing import Optional, List, Dict, Any
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from fastapi import FastAPI, APIRouter, Depends, HTTPException, Query, Request
|
from fastapi import FastAPI, APIRouter, Depends, HTTPException, Query, Request
|
||||||
from fastapi.responses import FileResponse
|
from fastapi.responses import FileResponse, Response
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
from app.config import get_tunis_now_iso
|
from app.config import get_tunis_now_iso, ENV
|
||||||
from app.db import (
|
from app.db import (
|
||||||
init_db,
|
init_db,
|
||||||
list_categories,
|
list_categories,
|
||||||
@@ -20,15 +24,30 @@ from app.db import (
|
|||||||
delete_regle,
|
delete_regle,
|
||||||
get_classement,
|
get_classement,
|
||||||
list_classements,
|
list_classements,
|
||||||
set_traite
|
set_traite,
|
||||||
|
list_courses,
|
||||||
|
cles_courses_vues,
|
||||||
|
marquer_courses_vues,
|
||||||
|
get_course,
|
||||||
|
add_course,
|
||||||
|
update_course,
|
||||||
|
delete_course,
|
||||||
|
SENS_COURSE,
|
||||||
|
list_suivi_clos,
|
||||||
|
clore_suivi,
|
||||||
|
rouvrir_suivi
|
||||||
)
|
)
|
||||||
from app.classifier import (
|
from app.classifier import (
|
||||||
classify_mail,
|
classify_mail,
|
||||||
|
classify_batch,
|
||||||
manual_classify_and_propose,
|
manual_classify_and_propose,
|
||||||
confirm_and_apply_rule,
|
confirm_and_apply_rule,
|
||||||
reclassify_today_mails
|
reclassify_today_mails
|
||||||
)
|
)
|
||||||
|
from app import asuivre
|
||||||
from app.mirror_client import MirrorClient
|
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
|
from app.auth import verify_cf_access_jwt
|
||||||
|
|
||||||
# --- Schémas Pydantic ---
|
# --- Schémas Pydantic ---
|
||||||
@@ -70,6 +89,11 @@ async def lifespan(app: FastAPI):
|
|||||||
reclassify_today_mails(mirror_client=mirror_client)
|
reclassify_today_mails(mirror_client=mirror_client)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
if ENV != "test":
|
||||||
|
mirror_client.demarrer_rafraichissement()
|
||||||
|
_analyse.demarrer_automatique(mirror_client)
|
||||||
|
from app import sauvegarde as _sauvegarde
|
||||||
|
_sauvegarde.demarrer()
|
||||||
yield
|
yield
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
@@ -95,6 +119,8 @@ async def en_tetes_securite(request: Request, call_next):
|
|||||||
reponse.headers["Referrer-Policy"] = "no-referrer"
|
reponse.headers["Referrer-Policy"] = "no-referrer"
|
||||||
if request.url.path == "/" or request.url.path.startswith("/api/"):
|
if request.url.path == "/" or request.url.path.startswith("/api/"):
|
||||||
reponse.headers["Cache-Control"] = "no-store"
|
reponse.headers["Cache-Control"] = "no-store"
|
||||||
|
elif request.url.path.startswith("/static/") or request.url.path in ("/favicon.ico", "/apple-touch-icon.png"):
|
||||||
|
reponse.headers["Cache-Control"] = "no-cache"
|
||||||
return reponse
|
return reponse
|
||||||
|
|
||||||
@app.get("/", include_in_schema=False)
|
@app.get("/", include_in_schema=False)
|
||||||
@@ -147,9 +173,12 @@ def get_mails_du_jour(date: Optional[str] = None, n: int = 50):
|
|||||||
"miroir_erreur": str(e)
|
"miroir_erreur": str(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
classes = {c["message_id"]: c for c in classify_batch(mails)}
|
||||||
classified_results = []
|
classified_results = []
|
||||||
for m in mails:
|
for m in mails:
|
||||||
c = classify_mail(m)
|
c = classes.get(m.get("message_id"))
|
||||||
|
if c is None:
|
||||||
|
continue
|
||||||
classified_results.append({
|
classified_results.append({
|
||||||
"message_id": m["message_id"],
|
"message_id": m["message_id"],
|
||||||
"date": m.get("date"),
|
"date": m.get("date"),
|
||||||
@@ -165,6 +194,355 @@ def get_mails_du_jour(date: Optional[str] = None, n: int = 50):
|
|||||||
"mails": classified_results
|
"mails": classified_results
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@api.get("/mails/periode")
|
||||||
|
def get_mails_periode(jours: int = 7):
|
||||||
|
"""Mails des N derniers jours (1 à 30), classés, pour la vue par groupe. Lecture seule."""
|
||||||
|
from datetime import date as _date, timedelta
|
||||||
|
jours = max(1, min(int(jours), 30))
|
||||||
|
fin = _date.fromisoformat(get_tunis_now_iso()[:10])
|
||||||
|
debut = (fin - timedelta(days=jours - 1)).isoformat()
|
||||||
|
try:
|
||||||
|
mails = mirror_client.get_mails_since(debut, max_items=min(150 * jours, 800))
|
||||||
|
except Exception as e:
|
||||||
|
return {"debut": debut, "fin": fin.isoformat(), "count": 0, "mails": [], "miroir_erreur": str(e)}
|
||||||
|
classes = {c["message_id"]: c for c in classify_batch(mails)}
|
||||||
|
resultats = []
|
||||||
|
for m in mails:
|
||||||
|
c = classes.get(m.get("message_id"))
|
||||||
|
if c is None:
|
||||||
|
continue
|
||||||
|
resultats.append({
|
||||||
|
"message_id": m["message_id"], "date": m.get("date"), "expediteur": m.get("expediteur"),
|
||||||
|
"objet": m.get("objet"), "etiquettes": m.get("etiquettes", []), "classement": c,
|
||||||
|
})
|
||||||
|
return {"debut": debut, "fin": fin.isoformat(), "count": len(resultats), "mails": resultats}
|
||||||
|
|
||||||
|
# --- Lecture d'un mail (texte seul, lecture seule) ---
|
||||||
|
MAX_CORPS_LECTURE = 200_000
|
||||||
|
MAX_PIECE = 25 * 1024 * 1024
|
||||||
|
# Extensions exécutables ou actives : jamais servies (le mail est un contenu non fiable).
|
||||||
|
EXT_REFUSEES = {"exe", "msi", "bat", "cmd", "com", "scr", "pif", "vbs", "vbe", "js", "jse", "wsf", "wsh", "ps1", "psm1",
|
||||||
|
"jar", "lnk", "hta", "cpl", "reg", "dll", "sys", "iso", "img", "html", "htm", "xhtml", "svg",
|
||||||
|
"docm", "xlsm", "pptm", "dotm", "xlam", "appx", "apk", "sh", "py", "app", "dmg", "chm"}
|
||||||
|
|
||||||
|
|
||||||
|
def _extension(nom: str) -> str:
|
||||||
|
return nom.rsplit(".", 1)[-1].lower().strip() if "." in nom else ""
|
||||||
|
|
||||||
|
|
||||||
|
def _nom_sur(nom: str) -> str:
|
||||||
|
nom = re.sub(r"[\\/\x00-\x1f\x7f\"]", "_", nom.replace("\\", "/").split("/")[-1]).strip(" .")
|
||||||
|
return (nom or "piece-jointe")[:150]
|
||||||
|
|
||||||
|
|
||||||
|
def _entete(en_tetes: Dict[str, Any], nom: str) -> str:
|
||||||
|
for k, v in (en_tetes or {}).items():
|
||||||
|
if str(k).lower() == nom.lower() and v:
|
||||||
|
return str(v)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
@api.get("/mail")
|
||||||
|
def lire_mail(id: str = Query(..., min_length=1, max_length=400)):
|
||||||
|
"""Contenu d'un mail du miroir : en-têtes utiles, texte et liste des pièces jointes. Aucune écriture,
|
||||||
|
aucun contenu de mail dans les journaux. Le miroir ne fournit pas de lien vers Outlook."""
|
||||||
|
try:
|
||||||
|
res = mirror_client.get_mail(id)
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=502, detail="Lecture du mail impossible : miroir indisponible.")
|
||||||
|
d = res.get("donnees") if isinstance(res, dict) else None
|
||||||
|
if not isinstance(d, dict) or not d:
|
||||||
|
raise HTTPException(status_code=404, detail="Mail introuvable.")
|
||||||
|
eh = d.get("en_tetes") or {}
|
||||||
|
corps = str(d.get("corps_texte") or "")
|
||||||
|
pj = []
|
||||||
|
for p in d.get("pieces_jointes") or []:
|
||||||
|
if isinstance(p, dict):
|
||||||
|
pj.append({
|
||||||
|
"nom": str(p.get("filename") or p.get("nom") or "(sans nom)"),
|
||||||
|
"type": str(p.get("content_type") or p.get("type") or ""),
|
||||||
|
"taille": int(p.get("size") or p.get("taille") or 0),
|
||||||
|
"bloquee": _extension(str(p.get("filename") or p.get("nom") or "")) in EXT_REFUSEES,
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
"message_id": d.get("message_id") or id,
|
||||||
|
"dossier": d.get("dossier"),
|
||||||
|
"de": _entete(eh, "From"), "a": _entete(eh, "To"), "cc": _entete(eh, "Cc"),
|
||||||
|
"date": _entete(eh, "Date"), "objet": _entete(eh, "Subject"),
|
||||||
|
"corps": corps[:MAX_CORPS_LECTURE], "tronque": len(corps) > MAX_CORPS_LECTURE,
|
||||||
|
"pieces_jointes": pj, "taille_octets": d.get("taille_octets"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@api.get("/mail/piece")
|
||||||
|
def telecharger_piece(id: str = Query(..., min_length=1, max_length=400), nom: str = Query(..., min_length=1, max_length=260)):
|
||||||
|
"""Télécharge une pièce jointe : toujours en téléchargement (jamais affichée), extensions actives refusées,
|
||||||
|
plafond de taille, aucune écriture, aucun contenu dans les journaux."""
|
||||||
|
if _extension(nom) in EXT_REFUSEES:
|
||||||
|
raise HTTPException(status_code=403, detail="Type de fichier bloqué par sécurité.")
|
||||||
|
try:
|
||||||
|
res = mirror_client.get_attachment(id, nom)
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=502, detail="Pièce jointe indisponible : miroir injoignable.")
|
||||||
|
d = res.get("donnees") if isinstance(res, dict) else None
|
||||||
|
b64 = d.get("contenu_base64") if isinstance(d, dict) else None
|
||||||
|
if not b64:
|
||||||
|
raise HTTPException(status_code=404, detail="Pièce jointe introuvable.")
|
||||||
|
if len(b64) * 3 // 4 > MAX_PIECE or int(d.get("taille") or 0) > MAX_PIECE:
|
||||||
|
raise HTTPException(status_code=413, detail="Pièce jointe trop volumineuse (25 Mo maximum).")
|
||||||
|
try:
|
||||||
|
brut = base64.b64decode(b64)
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=502, detail="Pièce jointe illisible.")
|
||||||
|
propre = _nom_sur(nom)
|
||||||
|
ascii_nom = propre.encode("ascii", "replace").decode().replace("?", "_")
|
||||||
|
return Response(content=brut, media_type="application/octet-stream", headers={
|
||||||
|
"Content-Disposition": f"attachment; filename=\"{ascii_nom}\"; filename*=UTF-8''{quote(propre)}",
|
||||||
|
"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff",
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
# --- Recherche ---
|
||||||
|
def _dossier_court(dossier: str) -> str:
|
||||||
|
d = re.sub(r"^Boîte de réception(-00 \d{4})?-?", "", dossier or "")
|
||||||
|
d = re.sub(r"^[^\w]+", "", d).strip()
|
||||||
|
return d or ("Boîte de réception" if (dossier or "").startswith("Boîte de réception") else (dossier or ""))
|
||||||
|
|
||||||
|
|
||||||
|
@api.get("/recherche")
|
||||||
|
def rechercher_mails(q: str = Query(..., min_length=2, max_length=100),
|
||||||
|
depuis: Optional[str] = Query(None, pattern=r"^\d{4}-\d{2}-\d{2}$"),
|
||||||
|
jusqu_a: Optional[str] = Query(None, pattern=r"^\d{4}-\d{2}-\d{2}$"),
|
||||||
|
n: int = Query(100, ge=1, le=100)):
|
||||||
|
"""Recherche plein texte dans tout le miroir (insensible à la casse et aux accents). Lecture seule ;
|
||||||
|
la requête n'est jamais écrite dans les journaux."""
|
||||||
|
from datetime import date, timedelta
|
||||||
|
terme = re.sub(r"[\x00-\x1f\x7f]", " ", q).strip()
|
||||||
|
if len(terme) < 2:
|
||||||
|
raise HTTPException(status_code=422, detail="Saisissez au moins 2 caractères.")
|
||||||
|
jusque = None
|
||||||
|
if jusqu_a:
|
||||||
|
try:
|
||||||
|
jusque = (date.fromisoformat(jusqu_a) + timedelta(days=1)).isoformat()
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(status_code=422, detail="Date de fin invalide.")
|
||||||
|
try:
|
||||||
|
brut = mirror_client.rechercher(terme, depuis, jusque, n)
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=502, detail="Recherche impossible : miroir indisponible.")
|
||||||
|
res = []
|
||||||
|
for r in brut:
|
||||||
|
res.append({
|
||||||
|
"message_id": r.get("message_id"), "date": r.get("date_reception") or r.get("date") or "",
|
||||||
|
"expediteur": r.get("expediteur") or "", "objet": r.get("sujet") or r.get("titre") or r.get("objet_original") or "",
|
||||||
|
"dossier": _dossier_court(r.get("dossier") or ""), "pj": bool(r.get("has_attachments")), "etiquettes": r.get("etiquettes") or [],
|
||||||
|
})
|
||||||
|
res.sort(key=lambda x: x["date"], reverse=True)
|
||||||
|
return {"total": len(res), "plafond": len(res) >= n, "resultats": res}
|
||||||
|
|
||||||
|
|
||||||
|
# --- Suivi des demandes ---
|
||||||
|
MON_ADRESSE = os.environ.get("MON_ADRESSE", "nabil.derouiche@")
|
||||||
|
|
||||||
|
|
||||||
|
class SuiviClore(BaseModel):
|
||||||
|
cle: str = Field(..., min_length=1, max_length=400)
|
||||||
|
dernier_id: str = Field(..., min_length=1, max_length=400)
|
||||||
|
|
||||||
|
|
||||||
|
class SuiviRouvrir(BaseModel):
|
||||||
|
cle: str = Field(..., min_length=1, max_length=400)
|
||||||
|
|
||||||
|
|
||||||
|
@api.get("/suivi")
|
||||||
|
def lire_suivi(jours: int = Query(14, ge=1, le=60)):
|
||||||
|
"""Suivi des demandes par fil de discussion : en attente de réponse, réponses reçues, demandes à traiter."""
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
from app.suivi import calculer_suivi
|
||||||
|
maintenant = datetime.now(ZoneInfo("Africa/Tunis"))
|
||||||
|
debut = (maintenant - timedelta(days=jours)).strftime("%Y-%m-%d")
|
||||||
|
try:
|
||||||
|
recus = mirror_client.get_mails_since(debut, max_items=800)
|
||||||
|
tous_envoyes = mirror_client.get_sent_mails()
|
||||||
|
envoyes = [m for m in tous_envoyes if (m.get("date") or "")[:10] >= debut]
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=502, detail="Lecture du courrier momentanément indisponible.")
|
||||||
|
vus, tous = set(), []
|
||||||
|
for m in recus + envoyes:
|
||||||
|
if m.get("message_id") not in vus:
|
||||||
|
vus.add(m.get("message_id")); tous.append(m)
|
||||||
|
items = calculer_suivi(tous, MON_ADRESSE, maintenant, list_suivi_clos())
|
||||||
|
compte = {k: sum(1 for i in items if i["etat"] == k and not i["clos"]) for k in ("attente", "reponse", "a_repondre")}
|
||||||
|
compte["clos"] = sum(1 for i in items if i["clos"])
|
||||||
|
derniere = max(((x.get("date") or "")[:10] for x in tous_envoyes), default="")
|
||||||
|
seuil = (maintenant - timedelta(days=2)).strftime("%Y-%m-%d")
|
||||||
|
return {"jours": jours, "items": items, "compte": compte, "envoyes_jusqu_au": derniere, "envoyes_a_jour": bool(derniere) and derniere >= seuil}
|
||||||
|
|
||||||
|
|
||||||
|
@api.post("/suivi/clore")
|
||||||
|
def suivi_clore(c: SuiviClore):
|
||||||
|
clore_suivi(c.cle, c.dernier_id)
|
||||||
|
return {"clos": c.cle}
|
||||||
|
|
||||||
|
|
||||||
|
@api.post("/suivi/rouvrir")
|
||||||
|
def suivi_rouvrir(c: SuiviRouvrir):
|
||||||
|
rouvrir_suivi(c.cle)
|
||||||
|
return {"rouvert": c.cle}
|
||||||
|
|
||||||
|
|
||||||
|
# --- Courses pour Tunis ---
|
||||||
|
class CourseIn(BaseModel):
|
||||||
|
demande: str = Field(..., min_length=1, max_length=300)
|
||||||
|
sens: str = "tunis_sfax"
|
||||||
|
message_id: Optional[str] = Field(None, max_length=400)
|
||||||
|
objet_mail: Optional[str] = Field(None, max_length=500)
|
||||||
|
expediteur: Optional[str] = Field(None, max_length=300)
|
||||||
|
date_mail: Optional[str] = Field(None, max_length=40)
|
||||||
|
|
||||||
|
|
||||||
|
class CourseUp(BaseModel):
|
||||||
|
demande: Optional[str] = Field(None, min_length=1, max_length=300)
|
||||||
|
sens: Optional[str] = None
|
||||||
|
statut: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
def _verifier_course(sens: Optional[str], statut: Optional[str] = None):
|
||||||
|
if sens is not None and sens not in SENS_COURSE:
|
||||||
|
raise HTTPException(status_code=422, detail="Sens invalide.")
|
||||||
|
if statut is not None and statut not in ("a_faire", "faite"):
|
||||||
|
raise HTTPException(status_code=422, detail="Statut invalide.")
|
||||||
|
|
||||||
|
|
||||||
|
@api.get("/courses")
|
||||||
|
def lister_courses(statut: Optional[str] = Query(None, pattern="^(a_faire|faite|toutes)$")):
|
||||||
|
return {"courses": list_courses(statut)}
|
||||||
|
|
||||||
|
|
||||||
|
@api.get("/courses/export")
|
||||||
|
def exporter_courses(statut: Optional[str] = Query(None, pattern="^(a_faire|faite|toutes)$")):
|
||||||
|
from app.export_courses import construire_xlsx
|
||||||
|
libelle = {"a_faire": "A faire", "faite": "Faites"}.get(statut or "", "Toutes les courses")
|
||||||
|
maintenant = get_tunis_now_iso()
|
||||||
|
contenu = construire_xlsx(list_courses(statut), libelle, maintenant)
|
||||||
|
nom = f"Courses-pour-Tunis-{maintenant[:10]}.xlsx"
|
||||||
|
return Response(content=contenu, media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
headers={"Content-Disposition": f'attachment; filename="{nom}"', "Cache-Control": "no-store"})
|
||||||
|
|
||||||
|
|
||||||
|
@api.post("/courses/synchroniser")
|
||||||
|
def synchroniser_courses(jours: int = Query(14, ge=1, le=30)):
|
||||||
|
"""Cree une course par fil classe Tunis, seulement si les regles automatiques sont reactivees (eteintes par defaut)."""
|
||||||
|
from app.classifier import regles_auto_actives
|
||||||
|
if not regles_auto_actives():
|
||||||
|
return {"ajoutees": 0, "courses": [], "regles_auto": False}
|
||||||
|
from datetime import date as _date, timedelta
|
||||||
|
from app.suivi import sujet_normalise
|
||||||
|
fin = _date.fromisoformat(get_tunis_now_iso()[:10])
|
||||||
|
debut = (fin - timedelta(days=jours - 1)).isoformat()
|
||||||
|
try:
|
||||||
|
mails = mirror_client.get_mails_since(debut, max_items=min(150 * jours, 800))
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=502, detail="Miroir indisponible.")
|
||||||
|
classes = {c["message_id"]: c for c in classify_batch(mails)}
|
||||||
|
existantes = list_courses(None)
|
||||||
|
ids = {k["message_id"] for k in existantes if k.get("message_id")}
|
||||||
|
cles = cles_courses_vues() | {sujet_normalise(k.get("objet_mail") or k["demande"]) for k in existantes}
|
||||||
|
ajoutees = []
|
||||||
|
for m in sorted(mails, key=lambda x: x.get("date") or ""):
|
||||||
|
mid = m.get("message_id")
|
||||||
|
c = classes.get(mid)
|
||||||
|
if not mid or c is None or c.get("categorie") != "Tunis" or mid in ids:
|
||||||
|
continue
|
||||||
|
objet = (m.get("objet") or "").strip()
|
||||||
|
cle = sujet_normalise(objet)
|
||||||
|
if not cle or cle in cles:
|
||||||
|
continue
|
||||||
|
sens = "sfax_tunis" if re.search(r"sfax\s*(?:vers|->|\u2192|/)\s*tunis", objet, re.IGNORECASE) else "tunis_sfax"
|
||||||
|
demande = re.sub(r"\s+", " ", re.sub(r"^((re|tr|fw|fwd)\s*:\s*)+", "", objet, flags=re.IGNORECASE)).strip()[:300] or objet[:300]
|
||||||
|
ajoutees.append(add_course(demande, sens, mid, objet[:500], (m.get("expediteur") or "")[:300], (m.get("date") or "")[:40]))
|
||||||
|
cles.add(cle)
|
||||||
|
marquer_courses_vues(cles)
|
||||||
|
return {"ajoutees": len(ajoutees), "courses": ajoutees}
|
||||||
|
|
||||||
|
|
||||||
|
@api.post("/courses", status_code=201)
|
||||||
|
def creer_course(c: CourseIn):
|
||||||
|
_verifier_course(c.sens)
|
||||||
|
demande = c.demande.strip()
|
||||||
|
if not demande:
|
||||||
|
raise HTTPException(status_code=422, detail="Demande vide.")
|
||||||
|
return add_course(demande, c.sens, c.message_id, c.objet_mail, c.expediteur, c.date_mail)
|
||||||
|
|
||||||
|
|
||||||
|
@api.patch("/courses/{course_id}")
|
||||||
|
def modifier_course(course_id: int, c: CourseUp):
|
||||||
|
_verifier_course(c.sens, c.statut)
|
||||||
|
if c.demande is not None and not c.demande.strip():
|
||||||
|
raise HTTPException(status_code=422, detail="Demande vide.")
|
||||||
|
r = update_course(course_id, c.demande.strip() if c.demande is not None else None, c.sens, c.statut)
|
||||||
|
if r is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Course introuvable.")
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
@api.delete("/courses/{course_id}")
|
||||||
|
def supprimer_course(course_id: int):
|
||||||
|
if not delete_course(course_id):
|
||||||
|
raise HTTPException(status_code=404, detail="Course introuvable.")
|
||||||
|
return {"supprimee": course_id}
|
||||||
|
|
||||||
|
|
||||||
|
# --- À suivre : mails marqués à la main, sans limite de date ---
|
||||||
|
class SuivreMarque(BaseModel):
|
||||||
|
message_id: str = Field(..., min_length=1, max_length=400)
|
||||||
|
expediteur: Optional[str] = Field(None, max_length=500)
|
||||||
|
objet: Optional[str] = Field(None, max_length=1000)
|
||||||
|
date_mail: Optional[str] = Field(None, max_length=64)
|
||||||
|
categorie: Optional[str] = Field(None, max_length=100)
|
||||||
|
|
||||||
|
|
||||||
|
class SuivreIds(BaseModel):
|
||||||
|
ids: List[str] = Field(..., min_length=1, max_length=500)
|
||||||
|
|
||||||
|
|
||||||
|
def _ids_valides(ids: List[str]) -> List[str]:
|
||||||
|
propres = [i for i in ids if isinstance(i, str) and 0 < len(i) <= 400]
|
||||||
|
if not propres:
|
||||||
|
raise HTTPException(status_code=422, detail="Aucun identifiant de mail valide.")
|
||||||
|
return propres
|
||||||
|
|
||||||
|
|
||||||
|
@api.get("/a-suivre")
|
||||||
|
def lire_a_suivre(statut: str = Query("tous", pattern="^(actif|termine|tous)$")):
|
||||||
|
"""Mails marqués « À suivre », du plus récent au plus ancien. Le marqueur reste dans Courrier : O365 n'est jamais modifié."""
|
||||||
|
return asuivre.lister(None if statut == "tous" else statut)
|
||||||
|
|
||||||
|
|
||||||
|
@api.post("/a-suivre/marquer")
|
||||||
|
def marquer_a_suivre(m: SuivreMarque):
|
||||||
|
return asuivre.marquer(m.message_id, m.expediteur, m.objet, m.date_mail, m.categorie)
|
||||||
|
|
||||||
|
|
||||||
|
@api.post("/a-suivre/retirer")
|
||||||
|
def retirer_a_suivre(r: SuivreIds):
|
||||||
|
"""Retire un ou plusieurs mails du suivi : ils passent en « terminés », rien n'est supprimé."""
|
||||||
|
return {"ids": asuivre.changer_statut(_ids_valides(r.ids), "termine")}
|
||||||
|
|
||||||
|
|
||||||
|
@api.post("/a-suivre/supprimer")
|
||||||
|
def supprimer_a_suivre(r: SuivreIds):
|
||||||
|
"""Efface de l'historique des mails déjà terminés (ajout par erreur, nettoyage). Les mails actifs sont ignorés ; O365 n'est jamais modifié."""
|
||||||
|
return {"ids": asuivre.supprimer(_ids_valides(r.ids))}
|
||||||
|
|
||||||
|
|
||||||
|
@api.post("/a-suivre/remettre")
|
||||||
|
def remettre_a_suivre(r: SuivreIds):
|
||||||
|
"""Remet au suivi des mails retirés (annulation ou retour depuis les terminés) en gardant leur date de marquage."""
|
||||||
|
return {"ids": asuivre.changer_statut(_ids_valides(r.ids), "actif")}
|
||||||
|
|
||||||
|
|
||||||
# --- Classements ---
|
# --- Classements ---
|
||||||
@api.get("/classements")
|
@api.get("/classements")
|
||||||
def get_classements(
|
def get_classements(
|
||||||
@@ -306,4 +684,17 @@ def confirm_rule_endpoint(regle_id: int):
|
|||||||
"message": "Règle confirmée et appliquée aux classements automatiques."
|
"message": "Règle confirmée et appliquée aux classements automatiques."
|
||||||
}
|
}
|
||||||
|
|
||||||
|
api.include_router(creer_routeur(mirror_client))
|
||||||
|
api.include_router(_analyse.creer_routeur(mirror_client))
|
||||||
|
api.include_router(_analyse._routeur_regles_auto())
|
||||||
|
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))
|
||||||
|
|
||||||
|
|
||||||
|
@api.get("/sauvegardes")
|
||||||
|
def lire_sauvegardes():
|
||||||
|
from app import sauvegarde as _s
|
||||||
|
return {"sauvegardes": _s.liste()[:14]}
|
||||||
app.include_router(api)
|
app.include_router(api)
|
||||||
+145
-25
@@ -1,4 +1,6 @@
|
|||||||
import json
|
import json
|
||||||
|
import threading
|
||||||
|
from datetime import date, timedelta
|
||||||
import time
|
import time
|
||||||
from collections import deque
|
from collections import deque
|
||||||
from typing import Optional, Dict, Any, List
|
from typing import Optional, Dict, Any, List
|
||||||
@@ -8,6 +10,9 @@ import urllib.error
|
|||||||
from app.config import MIRROR_URL, read_mirror_token
|
from app.config import MIRROR_URL, read_mirror_token
|
||||||
|
|
||||||
class MirrorClient:
|
class MirrorClient:
|
||||||
|
# Le miroir renvoie au plus 100 mails par lecture : toutes les vues partagent donc une seule clé de cache.
|
||||||
|
MIRROR_MAX_LATEST = 100
|
||||||
|
|
||||||
def __init__(self, base_url: Optional[str] = None, token: Optional[str] = None, cache_ttl_seconds: int = 60):
|
def __init__(self, base_url: Optional[str] = None, token: Optional[str] = None, cache_ttl_seconds: int = 60):
|
||||||
self.base_url = (base_url or MIRROR_URL).rstrip("/")
|
self.base_url = (base_url or MIRROR_URL).rstrip("/")
|
||||||
self._token = token or read_mirror_token()
|
self._token = token or read_mirror_token()
|
||||||
@@ -16,6 +21,10 @@ class MirrorClient:
|
|||||||
self._cache: Dict[str, tuple[float, Any]] = {}
|
self._cache: Dict[str, tuple[float, Any]] = {}
|
||||||
self._call_times: deque = deque()
|
self._call_times: deque = deque()
|
||||||
self._request_counter = 0
|
self._request_counter = 0
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._refresh_started = False
|
||||||
|
self._fen_cache: Dict[tuple, tuple] = {}
|
||||||
|
self.fenetre_ttl = 600
|
||||||
|
|
||||||
def _check_rate_limit(self) -> None:
|
def _check_rate_limit(self) -> None:
|
||||||
"""Applique strictement la limite de 60 requêtes par minute."""
|
"""Applique strictement la limite de 60 requêtes par minute."""
|
||||||
@@ -70,12 +79,21 @@ class MirrorClient:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise ConnectionError(f"Échec initialisation session MCP miroir: {e}")
|
raise ConnectionError(f"Échec initialisation session MCP miroir: {e}")
|
||||||
|
|
||||||
def call_tool(self, tool_name: str, arguments: Optional[Dict[str, Any]] = None, use_cache: bool = True) -> Any:
|
def call_tool(self, tool_name: str, arguments: Optional[Dict[str, Any]] = None, use_cache: bool = True, force: bool = False) -> Any:
|
||||||
|
"""Appel d'un outil du miroir : cache d'abord (sauf force), réseau sérialisé par un verrou
|
||||||
|
(la tâche de fond et les requêtes ne partagent jamais la session en même temps)."""
|
||||||
arguments = arguments or {}
|
arguments = arguments or {}
|
||||||
cache_key = f"{tool_name}:{json.dumps(arguments, sort_keys=True)}"
|
cache_key = f"{tool_name}:{json.dumps(arguments, sort_keys=True)}"
|
||||||
|
if use_cache and not force and cache_key in self._cache:
|
||||||
|
ts, val = self._cache[cache_key]
|
||||||
|
if time.time() - ts < self.cache_ttl:
|
||||||
|
return val
|
||||||
|
with self._lock:
|
||||||
|
return self._appel_reseau(tool_name, arguments, use_cache, cache_key, force)
|
||||||
|
|
||||||
|
def _appel_reseau(self, tool_name: str, arguments: Dict[str, Any], use_cache: bool, cache_key: str, force: bool) -> Any:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
if use_cache and cache_key in self._cache:
|
if use_cache and not force and cache_key in self._cache:
|
||||||
ts, val = self._cache[cache_key]
|
ts, val = self._cache[cache_key]
|
||||||
if now - ts < self.cache_ttl:
|
if now - ts < self.cache_ttl:
|
||||||
return val
|
return val
|
||||||
@@ -104,7 +122,9 @@ class MirrorClient:
|
|||||||
with urllib.request.urlopen(req, timeout=20) as resp:
|
with urllib.request.urlopen(req, timeout=20) as resp:
|
||||||
raw_body = resp.read().decode("utf-8")
|
raw_body = resp.read().decode("utf-8")
|
||||||
except urllib.error.HTTPError as e:
|
except urllib.error.HTTPError as e:
|
||||||
if e.code == 400 and not self.session_id:
|
# 404 = session MCP inconnue du miroir (redémarrage du miroir) : on en rouvre une et on rejoue l’appel une fois.
|
||||||
|
if (e.code == 400 and not self.session_id) or e.code == 404:
|
||||||
|
self.session_id = None
|
||||||
self._initialize_session()
|
self._initialize_session()
|
||||||
req = urllib.request.Request(self.base_url, headers=self._get_headers(), data=data_bytes)
|
req = urllib.request.Request(self.base_url, headers=self._get_headers(), data=data_bytes)
|
||||||
with urllib.request.urlopen(req, timeout=20) as resp:
|
with urllib.request.urlopen(req, timeout=20) as resp:
|
||||||
@@ -161,7 +181,7 @@ class MirrorClient:
|
|||||||
"""Récupère les derniers emails (mirror_mail_latest)."""
|
"""Récupère les derniers emails (mirror_mail_latest)."""
|
||||||
res = self.call_tool("mirror_mail_latest", {
|
res = self.call_tool("mirror_mail_latest", {
|
||||||
"folder": folder,
|
"folder": folder,
|
||||||
"n": n,
|
"n": min(n, self.MIRROR_MAX_LATEST),
|
||||||
"inclure_exclus": inclure_exclus
|
"inclure_exclus": inclure_exclus
|
||||||
})
|
})
|
||||||
if isinstance(res, dict) and "donnees" in res:
|
if isinstance(res, dict) and "donnees" in res:
|
||||||
@@ -194,25 +214,125 @@ class MirrorClient:
|
|||||||
res = self.call_tool("mirror_mail_get", {"message_id": message_id})
|
res = self.call_tool("mirror_mail_get", {"message_id": message_id})
|
||||||
return res if isinstance(res, dict) else {"raw": res}
|
return res if isinstance(res, dict) else {"raw": res}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _norm(m: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"message_id": m.get("message_id") or m.get("id") or m.get("hash"),
|
||||||
|
"date": m.get("date") or m.get("date_reception") or m.get("date_heure") or "",
|
||||||
|
"expediteur": m.get("from") or m.get("expediteur") or "",
|
||||||
|
"objet": m.get("sujet") or m.get("subject") or m.get("objet") or "",
|
||||||
|
"etiquettes": m.get("tags") or m.get("etiquettes") or [],
|
||||||
|
"apercu": m.get("snippet") or m.get("apercu") or "",
|
||||||
|
"dossier": m.get("dossier") or "",
|
||||||
|
"destinataires": m.get("destinataires") or "",
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _jour_suivant(jour: str) -> str:
|
||||||
|
return (date.fromisoformat(jour) + timedelta(days=1)).isoformat()
|
||||||
|
|
||||||
|
def _liste(self, res: Any) -> List[Dict[str, Any]]:
|
||||||
|
if isinstance(res, dict):
|
||||||
|
res = res.get("donnees")
|
||||||
|
return res if isinstance(res, list) else []
|
||||||
|
|
||||||
|
def mails_fenetre(self, debut: str, fin: str) -> List[Dict[str, Any]]:
|
||||||
|
"""Mails reçus de debut (inclus) à fin (exclu), AAAA-MM-JJ, au-delà des 100 derniers.
|
||||||
|
Recherche par fenêtres de dates (le miroir plafonne à 100 résultats) : une fenêtre pleine est coupée en deux.
|
||||||
|
La recherche « e » couvre presque tout ; les mails sans objet, qu'elle manque, viennent de l'étiquette sans_objet."""
|
||||||
|
cle = (debut, fin)
|
||||||
|
hit = self._fen_cache.get(cle)
|
||||||
|
if hit and time.time() - hit[0] < self.fenetre_ttl:
|
||||||
|
return hit[1]
|
||||||
|
d0, d1 = date.fromisoformat(debut), date.fromisoformat(fin)
|
||||||
|
if d1 <= d0:
|
||||||
|
return []
|
||||||
|
rows = self._liste(self.call_tool("mirror_mail_search", {"q": "e", "since": debut, "until": fin, "n": self.MIRROR_MAX_LATEST, "inclure_exclus": False}, use_cache=False))
|
||||||
|
if len(rows) >= self.MIRROR_MAX_LATEST and (d1 - d0).days > 1:
|
||||||
|
milieu = (d0 + timedelta(days=(d1 - d0).days // 2)).isoformat()
|
||||||
|
out = self.mails_fenetre(debut, milieu) + self.mails_fenetre(milieu, fin)
|
||||||
|
else:
|
||||||
|
out = list(rows)
|
||||||
|
out += self._liste(self.call_tool("mirror_mail_by_tag", {"etiquette": "sans_objet", "periode": f"{debut}..{(d1 - timedelta(days=1)).isoformat()}", "n": self.MIRROR_MAX_LATEST, "inclure_exclus": False}, use_cache=False))
|
||||||
|
vus, uniques = set(), []
|
||||||
|
for m in out:
|
||||||
|
mid = m.get("message_id")
|
||||||
|
if mid and mid not in vus:
|
||||||
|
vus.add(mid)
|
||||||
|
uniques.append(m)
|
||||||
|
if len(self._fen_cache) > 64:
|
||||||
|
self._fen_cache.clear()
|
||||||
|
self._fen_cache[cle] = (time.time(), uniques)
|
||||||
|
return uniques
|
||||||
|
|
||||||
|
def _mails_depuis(self, debut: str, max_items: int) -> List[Dict[str, Any]]:
|
||||||
|
"""Derniers mails (cache partagé) complétés par des fenêtres de dates quand la lecture de 100 ne remonte pas jusqu'à debut."""
|
||||||
|
brut = self.get_latest_mails(folder="*", n=max_items)
|
||||||
|
out = [self._norm(m) for m in brut if (self._norm(m)["date"][:10] >= debut)]
|
||||||
|
if len(brut) >= self.MIRROR_MAX_LATEST:
|
||||||
|
plus_ancien = min((self._norm(m)["date"][:10] for m in brut if self._norm(m)["date"]), default="")
|
||||||
|
if plus_ancien and plus_ancien > debut:
|
||||||
|
vus = {m["message_id"] for m in out}
|
||||||
|
etendu = False
|
||||||
|
try:
|
||||||
|
for m in self.mails_fenetre(debut, self._jour_suivant(plus_ancien)):
|
||||||
|
n = self._norm(m)
|
||||||
|
if n["message_id"] not in vus and n["date"][:10] >= debut:
|
||||||
|
vus.add(n["message_id"])
|
||||||
|
out.append(n)
|
||||||
|
etendu = True
|
||||||
|
if etendu:
|
||||||
|
out.sort(key=lambda m: m["date"], reverse=True)
|
||||||
|
except Exception:
|
||||||
|
pass # le miroir reste lisible sur les 100 derniers même si la recherche échoue
|
||||||
|
return out
|
||||||
|
|
||||||
|
def get_sent_mails(self, n: int = 100) -> List[Dict[str, Any]]:
|
||||||
|
"""Derniers messages envoyés (dossier « Messages envoyés » du miroir), normalisés."""
|
||||||
|
res = self.call_tool("mirror_mail_latest", {"folder": "Messages envoyés", "n": min(n, self.MIRROR_MAX_LATEST), "inclure_exclus": False})
|
||||||
|
return [self._norm(m) for m in self._liste(res)]
|
||||||
|
|
||||||
|
def rechercher(self, q: str, since: Optional[str] = None, until: Optional[str] = None, n: int = 100) -> List[Dict[str, Any]]:
|
||||||
|
"""Recherche plein texte du miroir (mirror_mail_search), tous dossiers, mails bruts."""
|
||||||
|
args: Dict[str, Any] = {"q": q, "n": min(n, self.MIRROR_MAX_LATEST), "inclure_exclus": False}
|
||||||
|
if since:
|
||||||
|
args["since"] = since
|
||||||
|
if until:
|
||||||
|
args["until"] = until
|
||||||
|
return self._liste(self.call_tool("mirror_mail_search", args))
|
||||||
|
|
||||||
|
def get_attachment(self, message_id: str, filename: str) -> Dict[str, Any]:
|
||||||
|
"""Pièce jointe d'un mail (mirror_mail_attachment), jamais mise en cache (contenu volumineux)."""
|
||||||
|
res = self.call_tool("mirror_mail_attachment", {"message_id": message_id, "filename": filename}, use_cache=False)
|
||||||
|
return res if isinstance(res, dict) else {"raw": res}
|
||||||
|
|
||||||
def get_mails_for_day(self, date_str: str, max_items: int = 50) -> List[Dict[str, Any]]:
|
def get_mails_for_day(self, date_str: str, max_items: int = 50) -> List[Dict[str, Any]]:
|
||||||
"""
|
"""Mails d'un jour donné (AAAA-MM-JJ)."""
|
||||||
Récupère les emails correspondant à un jour donné (date_str: AAAA-MM-JJ).
|
if not date_str:
|
||||||
Utilise mirror_mail_latest avec un nombre suffisant de messages puis filtre par date.
|
return [self._norm(m) for m in self.get_latest_mails(folder="*", n=max_items)]
|
||||||
"""
|
return [m for m in self._mails_depuis(date_str, max_items) if date_str in m["date"]]
|
||||||
raw_mails = self.get_latest_mails(folder="*", n=max_items)
|
|
||||||
filtered = []
|
def get_mails_since(self, debut: str, max_items: int = 400) -> List[Dict[str, Any]]:
|
||||||
for m in raw_mails:
|
"""Mails dont la date est >= debut (AAAA-MM-JJ)."""
|
||||||
# Vérifier la présence du message_id ou id
|
return self._mails_depuis(debut, max_items)[:max_items]
|
||||||
mid = m.get("message_id") or m.get("id") or m.get("hash")
|
|
||||||
d_mail = m.get("date") or m.get("date_reception") or m.get("date_heure") or ""
|
def rafraichir_derniers(self) -> None:
|
||||||
if date_str in d_mail or not date_str:
|
"""Relit les derniers mails en ignorant le cache (même clé que les vues)."""
|
||||||
m_normalized = {
|
self.call_tool("mirror_mail_latest", {"folder": "*", "n": self.MIRROR_MAX_LATEST, "inclure_exclus": False}, force=True)
|
||||||
"message_id": mid,
|
|
||||||
"date": d_mail,
|
def demarrer_rafraichissement(self, intervalle: int = 45) -> None:
|
||||||
"expediteur": m.get("from") or m.get("expediteur") or "",
|
"""Préchauffe le cache puis le rafraîchit en tâche de fond (1 lecture toutes les 45 s, loin des 60 par minute),
|
||||||
"objet": m.get("sujet") or m.get("subject") or m.get("objet") or "",
|
pour que l'ouverture d'une vue n'attende jamais le miroir. Idempotent."""
|
||||||
"etiquettes": m.get("tags") or m.get("etiquettes") or [],
|
if self._refresh_started:
|
||||||
"apercu": m.get("snippet") or m.get("apercu") or ""
|
return
|
||||||
}
|
self._refresh_started = True
|
||||||
filtered.append(m_normalized)
|
|
||||||
return filtered
|
def boucle() -> None:
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
self.rafraichir_derniers()
|
||||||
|
except Exception:
|
||||||
|
pass # le cache expire seul et la requête suivante relira le miroir
|
||||||
|
time.sleep(intervalle)
|
||||||
|
|
||||||
|
threading.Thread(target=boucle, name="miroir-rafraichissement", daemon=True).start()
|
||||||
+108
@@ -0,0 +1,108 @@
|
|||||||
|
"""Resume d'une piece jointe a la demande (tt-2026-11-072). Le texte est extrait ici, localement, puis envoye au seul
|
||||||
|
modele autorise via PrivAiTe (pseudonymisation). Ni le contenu, ni le resume ne sont conserves ; refus net si l'IA est
|
||||||
|
desactivee ou PrivAiTe injoignable ; types actifs et fichiers trop gros refuses ; scans sans texte signales."""
|
||||||
|
import base64
|
||||||
|
import io
|
||||||
|
import re
|
||||||
|
import zipfile
|
||||||
|
from typing import Optional
|
||||||
|
from xml.etree import ElementTree
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Query
|
||||||
|
|
||||||
|
from app import ia
|
||||||
|
|
||||||
|
MAX_OCTETS = 8 * 1024 * 1024
|
||||||
|
MAX_TEXTE = 12000
|
||||||
|
TEXTE = {"txt", "csv", "md", "log"}
|
||||||
|
|
||||||
|
|
||||||
|
class SansTexte(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _ext(nom: str) -> str:
|
||||||
|
return nom.rsplit(".", 1)[-1].lower() if "." in nom else ""
|
||||||
|
|
||||||
|
|
||||||
|
def extraire_texte(nom: str, brut: bytes) -> str:
|
||||||
|
e = _ext(nom)
|
||||||
|
if e in TEXTE:
|
||||||
|
t = brut.decode("utf-8", "replace")
|
||||||
|
elif e == "docx":
|
||||||
|
try:
|
||||||
|
with zipfile.ZipFile(io.BytesIO(brut)) as z:
|
||||||
|
racine = ElementTree.fromstring(z.read("word/document.xml"))
|
||||||
|
except Exception:
|
||||||
|
raise SansTexte("document illisible")
|
||||||
|
t = "\n".join("".join(x.text or "" for x in p.iter("{http://schemas.openxmlformats.org/wordprocessingml/2006/main}t"))
|
||||||
|
for p in racine.iter("{http://schemas.openxmlformats.org/wordprocessingml/2006/main}p"))
|
||||||
|
elif e == "xlsx":
|
||||||
|
try:
|
||||||
|
import openpyxl
|
||||||
|
wb = openpyxl.load_workbook(io.BytesIO(brut), read_only=True, data_only=True)
|
||||||
|
lignes = []
|
||||||
|
for ws in wb.worksheets[:3]:
|
||||||
|
lignes.append("# " + ws.title)
|
||||||
|
for i, row in enumerate(ws.iter_rows(values_only=True)):
|
||||||
|
if i >= 80:
|
||||||
|
break
|
||||||
|
lignes.append(" | ".join("" if c is None else str(c) for c in row))
|
||||||
|
t = "\n".join(lignes)
|
||||||
|
except Exception:
|
||||||
|
raise SansTexte("classeur illisible")
|
||||||
|
elif e == "pdf":
|
||||||
|
try:
|
||||||
|
from pypdf import PdfReader
|
||||||
|
t = "\n".join((p.extract_text() or "") for p in PdfReader(io.BytesIO(brut)).pages[:15])
|
||||||
|
except Exception:
|
||||||
|
raise SansTexte("PDF illisible")
|
||||||
|
else:
|
||||||
|
raise SansTexte("type non pris en charge (PDF, Word, Excel, texte)")
|
||||||
|
t = re.sub(r"[ \t]+", " ", t)
|
||||||
|
t = re.sub(r"\n{3,}", "\n\n", t).strip()
|
||||||
|
if len(t) < 40:
|
||||||
|
raise SansTexte("aucun texte lisible (probablement un scan)")
|
||||||
|
return t[:MAX_TEXTE]
|
||||||
|
|
||||||
|
|
||||||
|
CONSIGNE = ("Tu resumes une piece jointe pour un responsable achats. En francais, 4 a 6 lignes maximum : nature du document, "
|
||||||
|
"points essentiels, montants, quantites, dates et echeances, action attendue s'il y en a une. Ne fais aucune "
|
||||||
|
"supposition : si une information manque, ne l'invente pas. Pas de formule d'introduction.")
|
||||||
|
|
||||||
|
|
||||||
|
def resumer_texte(texte: str) -> str:
|
||||||
|
return ia.appeler_privaite([{"role": "system", "content": CONSIGNE}, {"role": "user", "content": texte}], max_tokens=1200).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def creer_routeur(mirror_client) -> APIRouter:
|
||||||
|
router = APIRouter(prefix="/ia")
|
||||||
|
|
||||||
|
@router.post("/piece")
|
||||||
|
def resumer_piece(id: str = Query(..., min_length=1, max_length=400), nom: str = Query(..., min_length=1, max_length=260)):
|
||||||
|
if not ia.ia_active():
|
||||||
|
raise HTTPException(status_code=409, detail="L'IA est désactivée.")
|
||||||
|
try:
|
||||||
|
res = mirror_client.get_attachment(id, nom)
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=502, detail="Pièce jointe indisponible : miroir injoignable.")
|
||||||
|
d = res.get("donnees") if isinstance(res, dict) else None
|
||||||
|
b64 = d.get("contenu_base64") if isinstance(d, dict) else None
|
||||||
|
if not b64:
|
||||||
|
raise HTTPException(status_code=404, detail="Pièce jointe introuvable.")
|
||||||
|
if len(b64) * 3 // 4 > MAX_OCTETS:
|
||||||
|
raise HTTPException(status_code=413, detail="Pièce jointe trop volumineuse pour un résumé (8 Mo maximum).")
|
||||||
|
try:
|
||||||
|
brut = base64.b64decode(b64)
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=502, detail="Pièce jointe illisible.")
|
||||||
|
try:
|
||||||
|
texte = extraire_texte(nom, brut)
|
||||||
|
except SansTexte as e:
|
||||||
|
raise HTTPException(status_code=422, detail="Résumé impossible : " + str(e) + ".")
|
||||||
|
try:
|
||||||
|
return {"nom": nom, "resume": resumer_texte(texte), "extrait_chars": len(texte)}
|
||||||
|
except ia.IAIndisponible as e:
|
||||||
|
raise HTTPException(status_code=503, detail="IA indisponible, aucun résumé : " + str(e) + ".")
|
||||||
|
|
||||||
|
return router
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
"""Sauvegarde quotidienne de la base de Courrier (classements manuels, courses, a suivre, fiches IA).
|
||||||
|
Copie coherente par l'API de sauvegarde SQLite, une par jour, quatorze jours conservees."""
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
from app import config
|
||||||
|
from app.config import get_tunis_now_iso
|
||||||
|
|
||||||
|
log = logging.getLogger("courrier.sauvegarde")
|
||||||
|
CONSERVES = 14
|
||||||
|
|
||||||
|
|
||||||
|
def _dossier(db_path: Optional[str] = None) -> str:
|
||||||
|
d = os.path.join(os.path.dirname(db_path or config.DB_PATH), "sauvegardes")
|
||||||
|
os.makedirs(d, exist_ok=True)
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def liste(db_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||||
|
d = _dossier(db_path)
|
||||||
|
out = []
|
||||||
|
for nom in sorted(os.listdir(d), reverse=True):
|
||||||
|
if nom.startswith("courrier-") and nom.endswith(".db"):
|
||||||
|
out.append({"nom": nom, "jour": nom[9:19], "octets": os.path.getsize(os.path.join(d, nom))})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def sauvegarder(db_path: Optional[str] = None, force: bool = False) -> Optional[str]:
|
||||||
|
"""Une sauvegarde par jour. Retourne le nom du fichier cree, ou None s'il existe deja."""
|
||||||
|
src = db_path or config.DB_PATH
|
||||||
|
jour = get_tunis_now_iso()[:10]
|
||||||
|
d = _dossier(src)
|
||||||
|
cible = os.path.join(d, "courrier-%s.db" % jour)
|
||||||
|
if os.path.exists(cible) and not force:
|
||||||
|
return None
|
||||||
|
tmp = cible + ".tmp"
|
||||||
|
a = sqlite3.connect(src); b = sqlite3.connect(tmp)
|
||||||
|
try:
|
||||||
|
a.backup(b)
|
||||||
|
finally:
|
||||||
|
b.close(); a.close()
|
||||||
|
os.replace(tmp, cible)
|
||||||
|
os.chmod(cible, 0o640)
|
||||||
|
for ancien in liste(src)[CONSERVES:]:
|
||||||
|
try:
|
||||||
|
os.remove(os.path.join(d, ancien["nom"]))
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
return os.path.basename(cible)
|
||||||
|
|
||||||
|
|
||||||
|
def demarrer(intervalle: int = 3600) -> None:
|
||||||
|
def boucle() -> None:
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
n = sauvegarder()
|
||||||
|
if n:
|
||||||
|
log.info("sauvegarde %s", n)
|
||||||
|
except Exception:
|
||||||
|
log.warning("sauvegarde impossible")
|
||||||
|
time.sleep(intervalle)
|
||||||
|
threading.Thread(target=boucle, name="sauvegarde-courrier", daemon=True).start()
|
||||||
+212
-12
@@ -7,12 +7,11 @@ button:disabled { cursor: default; }
|
|||||||
h1, h2, h3, p { margin: 0; }
|
h1, h2, h3, p { margin: 0; }
|
||||||
|
|
||||||
.coque { display: grid; grid-template-columns: 232px minmax(0, 1fr); min-height: 100vh; }
|
.coque { display: grid; grid-template-columns: 232px minmax(0, 1fr); min-height: 100vh; }
|
||||||
.nav-bureau { background: var(--ny-carte); border-right: 1px solid var(--ny-trait); padding: var(--ny-e6) var(--ny-e4); display: flex; flex-direction: column; gap: var(--ny-e6); position: sticky; top: 0; height: 100vh; }
|
.nav-bureau { background: var(--ny-carte); border-right: 1px solid var(--ny-trait); padding: var(--ny-e6) var(--ny-e4); display: flex; flex-direction: column; gap: var(--ny-e6); position: sticky; top: 0; height: 100vh; overflow-y: auto; overflow-x: hidden; }
|
||||||
.marque { padding: 0 var(--ny-e2); display: flex; flex-direction: column; gap: 2px; }
|
.marque { padding: 0 var(--ny-e2); display: flex; flex-direction: column; gap: 2px; }
|
||||||
.marque b { font: var(--ny-t2); }
|
.marque b { font: var(--ny-t2); }
|
||||||
.marque span { font: var(--ny-t4); color: var(--ny-encre-3); }
|
.marque span { font: var(--ny-t4); color: var(--ny-encre-3); }
|
||||||
.nav-liste { display: flex; flex-direction: column; gap: var(--ny-e1); }
|
.nav-liste { display: flex; flex-direction: column; gap: var(--ny-e1); }
|
||||||
.nav-mobile .nav-sep { display: none; }
|
|
||||||
.nav-sep { font: var(--ny-t4); color: var(--ny-encre-3); padding: var(--ny-e2) var(--ny-e3) 0; }
|
.nav-sep { font: var(--ny-t4); color: var(--ny-encre-3); padding: var(--ny-e2) var(--ny-e3) 0; }
|
||||||
.nav-btn { min-height: var(--ny-cible); display: flex; align-items: center; gap: var(--ny-e3); padding: 0 var(--ny-e3); border: none; border-radius: var(--ny-r-s); background: transparent; color: var(--ny-encre-2); font: 500 15px/20px var(--ny-police); text-align: left; transition: background var(--ny-duree) var(--ny-courbe); }
|
.nav-btn { min-height: var(--ny-cible); display: flex; align-items: center; gap: var(--ny-e3); padding: 0 var(--ny-e3); border: none; border-radius: var(--ny-r-s); background: transparent; color: var(--ny-encre-2); font: 500 15px/20px var(--ny-police); text-align: left; transition: background var(--ny-duree) var(--ny-courbe); }
|
||||||
.nav-btn:hover { background: var(--ny-accent-teinte); }
|
.nav-btn:hover { background: var(--ny-accent-teinte); }
|
||||||
@@ -50,7 +49,7 @@ h1, h2, h3, p { margin: 0; }
|
|||||||
.btn-danger-ligne:hover { background: var(--ny-erreur-fond); }
|
.btn-danger-ligne:hover { background: var(--ny-erreur-fond); }
|
||||||
|
|
||||||
.carte { background: var(--ny-carte); border: 1px solid var(--ny-trait); border-radius: var(--ny-r-l); overflow: hidden; }
|
.carte { background: var(--ny-carte); border: 1px solid var(--ny-trait); border-radius: var(--ny-r-l); overflow: hidden; }
|
||||||
.repartition { padding: var(--ny-e4) var(--ny-e5); display: flex; flex-direction: column; gap: var(--ny-e3); }
|
.repartition { flex: none; min-height: max-content; padding: var(--ny-e4) var(--ny-e5); display: flex; flex-direction: column; gap: var(--ny-e3); }
|
||||||
.repartition h2 { font: 600 15px/20px var(--ny-police); color: var(--ny-encre-2); }
|
.repartition h2 { font: 600 15px/20px var(--ny-police); color: var(--ny-encre-2); }
|
||||||
.puces { display: flex; flex-wrap: wrap; gap: var(--ny-e2); }
|
.puces { display: flex; flex-wrap: wrap; gap: var(--ny-e2); }
|
||||||
.puce { min-height: var(--ny-cible); padding: 0 var(--ny-e3) 0 10px; display: inline-flex; align-items: center; gap: 7px; border-radius: var(--ny-r-pastille); border: 1px solid var(--ny-trait-controle); background: var(--ny-carte); font: 500 15px/20px var(--ny-police); white-space: nowrap; }
|
.puce { min-height: var(--ny-cible); padding: 0 var(--ny-e3) 0 10px; display: inline-flex; align-items: center; gap: 7px; border-radius: var(--ny-r-pastille); border: 1px solid var(--ny-trait-controle); background: var(--ny-carte); font: 500 15px/20px var(--ny-police); white-space: nowrap; }
|
||||||
@@ -65,18 +64,29 @@ h1, h2, h3, p { margin: 0; }
|
|||||||
.barre > div { height: 100%; background: var(--ny-accent); transition: width var(--ny-duree) var(--ny-courbe); }
|
.barre > div { height: 100%; background: var(--ny-accent); transition: width var(--ny-duree) var(--ny-courbe); }
|
||||||
.avancement b { font: 600 13px/18px var(--ny-police-chiffres); color: var(--ny-encre); }
|
.avancement b { font: 600 13px/18px var(--ny-police-chiffres); color: var(--ny-encre); }
|
||||||
|
|
||||||
|
/* Étiquettes du miroir et vue par groupe */
|
||||||
|
.etqs { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 4px; }
|
||||||
|
.etq { display: inline-flex; align-items: center; min-height: 20px; padding: 0 8px; border-radius: var(--ny-r-pastille); border: 1px solid var(--ny-trait); background: var(--ny-carte-2); color: var(--ny-encre-2); font: 500 12px/16px var(--ny-police); }
|
||||||
|
.objet.sans { font-style: italic; }
|
||||||
|
.titre-groupe { font: 600 17px/24px var(--ny-police); color: var(--ny-encre); }
|
||||||
|
.jour-titre { display: flex; align-items: baseline; justify-content: space-between; gap: var(--ny-e3); padding: var(--ny-e3) var(--ny-e5); background: var(--ny-carte-2); border-bottom: 1px solid var(--ny-trait); font: 600 14px/20px var(--ny-police); color: var(--ny-encre-2); }
|
||||||
|
|
||||||
/* Pastille de catégorie */
|
/* Pastille de catégorie */
|
||||||
.pt { width: 10px; height: 10px; border-radius: var(--ny-r-pastille); flex: none; box-sizing: border-box; background: var(--ny-cat-vide); }
|
.pt { width: 10px; height: 10px; border-radius: var(--ny-r-pastille); flex: none; box-sizing: border-box; background: var(--ny-cat-vide); }
|
||||||
.pt.c1 { background: var(--ny-cat-1); } .pt.c2 { background: var(--ny-cat-2); } .pt.c3 { background: var(--ny-cat-3); } .pt.c4 { background: var(--ny-cat-4); }
|
.pt.c1 { background: var(--ny-cat-1); } .pt.c2 { background: var(--ny-cat-2); } .pt.c3 { background: var(--ny-cat-3); } .pt.c4 { background: var(--ny-cat-4); }
|
||||||
.pt.c5 { background: var(--ny-cat-5); } .pt.c6 { background: var(--ny-cat-6); } .pt.c7 { background: var(--ny-cat-7); } .pt.c8 { background: var(--ny-cat-8); }
|
.pt.c5 { background: var(--ny-cat-5); } .pt.c6 { background: var(--ny-cat-6); } .pt.c7 { background: var(--ny-cat-7); } .pt.c8 { background: var(--ny-cat-8); }
|
||||||
|
.pt.c9 { background: var(--ny-cat-9); } .pt.c10 { background: var(--ny-cat-10); } .pt.c11 { background: var(--ny-cat-11); } .pt.c12 { background: var(--ny-cat-12); }
|
||||||
.pt.c0 { background: transparent; border: 1.5px dashed var(--ny-cat-vide); }
|
.pt.c0 { background: transparent; border: 1.5px dashed var(--ny-cat-vide); }
|
||||||
.pt.tous { background: var(--ny-encre-2); }
|
.pt.tous { background: var(--ny-encre-2); }
|
||||||
.puce[aria-pressed="true"] .pt.c0 { border-color: var(--ny-encre-inverse); }
|
.puce[aria-pressed="true"] .pt.c0 { border-color: var(--ny-encre-inverse); }
|
||||||
.puce.t1 { background: var(--ny-cat-1-fond); border-color: var(--ny-cat-1-trait); } .puce.t2 { background: var(--ny-cat-2-fond); border-color: var(--ny-cat-2-trait); }
|
.puce.t1 { background: var(--ny-cat-1-fond); border-color: var(--ny-cat-1-trait); } .puce.t2 { background: var(--ny-cat-2-fond); border-color: var(--ny-cat-2-trait); }
|
||||||
.puce.t3 { background: var(--ny-cat-3-fond); border-color: var(--ny-cat-3-trait); } .puce.t4 { background: var(--ny-cat-4-fond); border-color: var(--ny-cat-4-trait); }
|
.puce.t3 { background: var(--ny-cat-3-fond); border-color: var(--ny-cat-3-trait); } .puce.t4 { background: var(--ny-cat-4-fond); border-color: var(--ny-cat-4-trait); }
|
||||||
.puce.t5 { background: var(--ny-cat-5-fond); border-color: var(--ny-cat-5-trait); } .puce.t6 { background: var(--ny-cat-6-fond); border-color: var(--ny-cat-6-trait); }
|
.puce.t5 { background: var(--ny-cat-5-fond); border-color: var(--ny-cat-5-trait); } .puce.t6 { background: var(--ny-cat-6-fond); border-color: var(--ny-cat-6-trait); }
|
||||||
|
.puce.t9 { background: var(--ny-cat-9-fond); border-color: var(--ny-cat-9-trait); } .puce.t10 { background: var(--ny-cat-10-fond); border-color: var(--ny-cat-10-trait); }
|
||||||
|
.puce.t11 { background: var(--ny-cat-11-fond); border-color: var(--ny-cat-11-trait); } .puce.t12 { background: var(--ny-cat-12-fond); border-color: var(--ny-cat-12-trait); }
|
||||||
.puce.t7 { background: var(--ny-cat-7-fond); border-color: var(--ny-cat-7-trait); } .puce.t8 { background: var(--ny-cat-8-fond); border-color: var(--ny-cat-8-trait); }
|
.puce.t7 { background: var(--ny-cat-7-fond); border-color: var(--ny-cat-7-trait); } .puce.t8 { background: var(--ny-cat-8-fond); border-color: var(--ny-cat-8-trait); }
|
||||||
.puce[aria-pressed="true"].t1, .puce[aria-pressed="true"].t2, .puce[aria-pressed="true"].t3, .puce[aria-pressed="true"].t4,
|
.puce[aria-pressed="true"].t1, .puce[aria-pressed="true"].t2, .puce[aria-pressed="true"].t3, .puce[aria-pressed="true"].t4,
|
||||||
|
.puce[aria-pressed="true"].t9, .puce[aria-pressed="true"].t10, .puce[aria-pressed="true"].t11, .puce[aria-pressed="true"].t12,
|
||||||
.puce[aria-pressed="true"].t5, .puce[aria-pressed="true"].t6, .puce[aria-pressed="true"].t7, .puce[aria-pressed="true"].t8 { background: var(--ny-encre); border-color: var(--ny-encre); }
|
.puce[aria-pressed="true"].t5, .puce[aria-pressed="true"].t6, .puce[aria-pressed="true"].t7, .puce[aria-pressed="true"].t8 { background: var(--ny-encre); border-color: var(--ny-encre); }
|
||||||
|
|
||||||
/* Bandeau de règle et notification */
|
/* Bandeau de règle et notification */
|
||||||
@@ -87,7 +97,7 @@ h1, h2, h3, p { margin: 0; }
|
|||||||
.notif { padding: var(--ny-e3) var(--ny-e5); border-radius: var(--ny-r-m); border: 1px solid var(--ny-trait); background: var(--ny-carte); box-shadow: var(--ny-ombre-2); font: 500 15px/22px var(--ny-police); animation: ny-apparition var(--ny-duree) var(--ny-courbe); }
|
.notif { padding: var(--ny-e3) var(--ny-e5); border-radius: var(--ny-r-m); border: 1px solid var(--ny-trait); background: var(--ny-carte); box-shadow: var(--ny-ombre-2); font: 500 15px/22px var(--ny-police); animation: ny-apparition var(--ny-duree) var(--ny-courbe); }
|
||||||
|
|
||||||
/* Liste du tri */
|
/* Liste du tri */
|
||||||
.liste-entete, .ligne { display: grid; grid-template-columns: 44px minmax(0, 1.1fr) minmax(0, 1.6fr) 64px 110px 200px; gap: var(--ny-e3); align-items: center; padding: 0 var(--ny-e5) 0 var(--ny-e2); }
|
.liste-entete, .ligne { display: grid; grid-template-columns: 44px minmax(0, 1.1fr) minmax(0, 1.6fr) 64px 110px 200px 44px; gap: var(--ny-e3); align-items: center; padding: 0 var(--ny-e5) 0 var(--ny-e2); }
|
||||||
.liste-entete { min-height: 40px; background: var(--ny-carte-2); border-bottom: 1px solid var(--ny-trait); font: var(--ny-t4); color: var(--ny-encre-2); }
|
.liste-entete { min-height: 40px; background: var(--ny-carte-2); border-bottom: 1px solid var(--ny-trait); font: var(--ny-t4); color: var(--ny-encre-2); }
|
||||||
.ligne { min-height: 64px; border-bottom: 1px solid var(--ny-trait); }
|
.ligne { min-height: 64px; border-bottom: 1px solid var(--ny-trait); }
|
||||||
.ligne:last-child { border-bottom: none; }
|
.ligne:last-child { border-bottom: none; }
|
||||||
@@ -173,17 +183,12 @@ h1, h2, h3, p { margin: 0; }
|
|||||||
.bientot-ecran { padding: var(--ny-e8) var(--ny-e6); display: flex; flex-direction: column; gap: var(--ny-e2); align-items: flex-start; }
|
.bientot-ecran { padding: var(--ny-e8) var(--ny-e6); display: flex; flex-direction: column; gap: var(--ny-e2); align-items: flex-start; }
|
||||||
.badge-bientot { display: inline-flex; padding: 0 10px; min-height: 24px; align-items: center; border: 1px dashed var(--ny-trait-controle); border-radius: var(--ny-r-pastille); font: 600 13px/18px var(--ny-police); color: var(--ny-encre-2); }
|
.badge-bientot { display: inline-flex; padding: 0 10px; min-height: 24px; align-items: center; border: 1px dashed var(--ny-trait-controle); border-radius: var(--ny-r-pastille); font: 600 13px/18px var(--ny-police); color: var(--ny-encre-2); }
|
||||||
|
|
||||||
.nav-mobile { display: none; }
|
|
||||||
|
|
||||||
@media (max-width: 760px) {
|
@media (max-width: 760px) {
|
||||||
.coque { grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(0, 1fr) auto; height: 100dvh; min-height: 0; }
|
.coque { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); height: 100dvh; min-height: 0; }
|
||||||
.nav-bureau { display: none; }
|
.principal { padding: var(--ny-e4) var(--ny-e4) calc(var(--ny-e4) + env(safe-area-inset-bottom, 0px)); gap: var(--ny-e3); overflow-y: auto; }
|
||||||
.principal { padding: var(--ny-e4); gap: var(--ny-e3); overflow-y: auto; }
|
.principal > * { flex-shrink: 0; }
|
||||||
.entete h1 { font: var(--ny-t2); }
|
.entete h1 { font: var(--ny-t2); }
|
||||||
.nav-mobile { display: grid; grid-template-columns: repeat(3, 1fr); background: var(--ny-carte); border-top: 1px solid var(--ny-trait); padding: 4px 8px 16px; }
|
|
||||||
.nav-mobile .nav-btn { min-height: 56px; flex-direction: column; justify-content: center; gap: 4px; padding: 0; text-align: center; font: 500 13px/18px var(--ny-police); }
|
|
||||||
.nav-mobile .nav-btn[aria-current="page"] { font-weight: 600; }
|
|
||||||
.nav-mobile .nav-btn svg { width: 22px; height: 22px; }
|
|
||||||
.jour { width: 100%; }
|
.jour { width: 100%; }
|
||||||
.jour-carte { flex: 1; justify-content: center; }
|
.jour-carte { flex: 1; justify-content: center; }
|
||||||
.liste-entete { display: none; }
|
.liste-entete { display: none; }
|
||||||
@@ -207,3 +212,198 @@ h1, h2, h3, p { margin: 0; }
|
|||||||
.sq-ligne { grid-template-columns: 44px minmax(0, 1fr) 138px; }
|
.sq-ligne { grid-template-columns: 44px minmax(0, 1fr) 138px; }
|
||||||
.sq-ligne span:nth-child(3), .sq-ligne span:nth-child(4), .sq-ligne span:nth-child(5) { display: none; }
|
.sq-ligne span:nth-child(3), .sq-ligne span:nth-child(4), .sq-ligne span:nth-child(5) { display: none; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---------- Lecture d'un mail ---------- */
|
||||||
|
.lire { display: block; width: 100%; min-height: var(--ny-cible); padding: 0; border: none; border-radius: var(--ny-r-s); background: transparent; color: inherit; font: inherit; text-align: left; cursor: pointer; }
|
||||||
|
.lire > span { display: block; min-width: 0; }
|
||||||
|
.lire:hover .objet { color: var(--ny-accent); text-decoration: underline; text-underline-offset: 3px; }
|
||||||
|
.voile:has(> .boite.lecture) { padding: var(--ny-e6); }
|
||||||
|
.boite.lecture { max-width: 780px; max-height: 100%; padding: 0; gap: 0; overflow: hidden; display: flex; flex-direction: column; }
|
||||||
|
.lect-tete { display: flex; align-items: flex-start; gap: var(--ny-e3); padding: var(--ny-e5) var(--ny-e6) var(--ny-e4); border-bottom: 1px solid var(--ny-trait); background: var(--ny-carte); }
|
||||||
|
.lect-tete h2 { flex: 1; min-width: 0; margin: 0; font: 600 22px/30px var(--ny-police); color: var(--ny-encre); overflow-wrap: anywhere; }
|
||||||
|
.lect-tete .btn-icone { flex: none; }
|
||||||
|
.lect-scroll { flex: 1; min-height: 0; overflow-y: auto; padding: var(--ny-e5) var(--ny-e6) var(--ny-e8); }
|
||||||
|
.lect-badges { display: flex; flex-wrap: wrap; align-items: center; gap: var(--ny-e2); margin-bottom: var(--ny-e4); }
|
||||||
|
.lect-cat { display: inline-flex; align-items: center; gap: 6px; min-height: 28px; padding: 0 10px; border-radius: var(--ny-r-pastille); border: 1px solid var(--ny-trait); background: var(--ny-carte-2); color: var(--ny-encre); font: 600 13px/18px var(--ny-police); }
|
||||||
|
.lect-meta { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 6px var(--ny-e4); margin: 0 0 var(--ny-e5); padding-bottom: var(--ny-e5); border-bottom: 1px solid var(--ny-trait); font: 400 15px/22px var(--ny-police); }
|
||||||
|
.lect-meta dt { color: var(--ny-encre-3); font-weight: 500; }
|
||||||
|
.lect-meta dd { margin: 0; min-width: 0; overflow-wrap: anywhere; color: var(--ny-encre); }
|
||||||
|
.lect-meta .qui { display: block; }
|
||||||
|
.lect-meta .nom { font-weight: 600; }
|
||||||
|
.lect-meta .adr { color: var(--ny-encre-3); }
|
||||||
|
.lect-meta .btn-petit.plus { min-height: 32px; padding: 0 var(--ny-e2); margin-left: calc(var(--ny-e2) * -1); }
|
||||||
|
.lect-texte { max-width: 60ch; font: 400 17px/1.65 var(--ny-police); color: var(--ny-encre); }
|
||||||
|
.lect-texte p { margin: 0 0 1em; overflow-wrap: anywhere; }
|
||||||
|
.lect-texte blockquote { margin: 0 0 1em; padding: 2px 0 2px var(--ny-e4); border-left: 3px solid var(--ny-trait); color: var(--ny-encre-2); overflow-wrap: anywhere; }
|
||||||
|
.lect-texte a { text-decoration: underline; text-underline-offset: 3px; overflow-wrap: anywhere; }
|
||||||
|
.lect-vide { color: var(--ny-encre-3); font-style: italic; }
|
||||||
|
.lect-histo { margin-top: var(--ny-e4); padding-top: var(--ny-e2); border-top: 1px solid var(--ny-trait); }
|
||||||
|
.lect-histo summary { display: flex; align-items: center; min-height: var(--ny-cible); color: var(--ny-accent); font: 600 15px/20px var(--ny-police); cursor: pointer; }
|
||||||
|
.lect-histo .lect-texte { font-size: 15px; color: var(--ny-encre-2); padding-top: var(--ny-e2); }
|
||||||
|
.lect-pj { margin-top: var(--ny-e6); padding-top: var(--ny-e4); border-top: 1px solid var(--ny-trait); }
|
||||||
|
.lect-pj h3 { margin: 0 0 var(--ny-e2); font: 600 15px/20px var(--ny-police); color: var(--ny-encre); }
|
||||||
|
.lect-pj ul { list-style: none; margin: 0; padding: 0; display: grid; gap: var(--ny-e2); }
|
||||||
|
.lect-pj li { display: flex; align-items: center; gap: var(--ny-e3); min-height: var(--ny-cible); padding: 6px var(--ny-e3); border: 1px solid var(--ny-trait); border-radius: var(--ny-r-m); background: var(--ny-carte-2); color: var(--ny-encre-2); }
|
||||||
|
.lect-pj .nom { flex: 1; min-width: 0; font: 500 15px/20px var(--ny-police); color: var(--ny-encre); }
|
||||||
|
.lect-pj .info { flex: none; font: 400 13px/18px var(--ny-police); color: var(--ny-encre-3); }
|
||||||
|
.lect-note { margin: var(--ny-e5) 0 0; font: 400 13px/18px var(--ny-police); color: var(--ny-encre-3); }
|
||||||
|
.lect-etat { display: flex; flex-direction: column; gap: var(--ny-e3); }
|
||||||
|
.lect-etat p { margin: 0; font: 500 15px/22px var(--ny-police); color: var(--ny-encre-2); }
|
||||||
|
.lect-sq { display: block; height: 14px; border-radius: var(--ny-r-s); background: var(--ny-trait); }
|
||||||
|
.lect-sq.court { width: 60%; }
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.voile:has(> .boite.lecture) { padding: 0; }
|
||||||
|
.boite.lecture { max-width: none; height: 100%; max-height: none; border: none; border-radius: 0; box-shadow: none; }
|
||||||
|
.lect-tete { padding: var(--ny-e3) var(--ny-e4); }
|
||||||
|
.lect-tete h2 { font: 600 19px/26px var(--ny-police); padding-top: 9px; }
|
||||||
|
.lect-scroll { padding: var(--ny-e4) var(--ny-e4) var(--ny-e8); }
|
||||||
|
.lect-texte { font-size: 17px; }
|
||||||
|
.lect-meta { grid-template-columns: minmax(0, 1fr); gap: 0; }
|
||||||
|
.lect-meta dt { margin-top: var(--ny-e2); font-size: 13px; line-height: 18px; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Pièces jointes : téléchargement */
|
||||||
|
.lect-pj li .btn-icone { flex: none; }
|
||||||
|
.lect-pj .info.bloquee { color: var(--ny-erreur, var(--ny-encre-2)); font-weight: 600; }
|
||||||
|
.lect-sig { margin-top: var(--ny-e4); }
|
||||||
|
.lect-sig ul { list-style: none; margin: var(--ny-e2) 0 0; padding: 0; display: grid; gap: var(--ny-e2); }
|
||||||
|
.lect-sig li { display: flex; align-items: center; gap: var(--ny-e3); min-height: var(--ny-cible); padding: 6px var(--ny-e3); color: var(--ny-encre-2); }
|
||||||
|
|
||||||
|
/* Courses pour Tunis */
|
||||||
|
.entete-actions { display: flex; gap: var(--ny-e3); flex-wrap: wrap; }
|
||||||
|
.btn-ligne svg { margin-right: var(--ny-e2); vertical-align: -3px; }
|
||||||
|
.lect-course { margin-left: auto; }
|
||||||
|
.course { display: flex; align-items: center; gap: var(--ny-e3); padding: var(--ny-e3) var(--ny-e4); border-top: 1px solid var(--ny-trait); }
|
||||||
|
.course:first-child { border-top: none; }
|
||||||
|
.course .coche { width: var(--ny-cible); height: var(--ny-cible); flex: none; display: flex; align-items: center; justify-content: center; }
|
||||||
|
.course .coche input { width: 22px; height: 22px; margin: 0; accent-color: var(--ny-accent); }
|
||||||
|
.course-corps { flex: 1; min-width: 0; }
|
||||||
|
.course .dem { font: 600 16px/24px var(--ny-police); color: var(--ny-encre); overflow-wrap: anywhere; }
|
||||||
|
.course .meta { font: 400 14px/20px var(--ny-police); color: var(--ny-encre-2); }
|
||||||
|
.course.faite .dem { text-decoration: line-through; color: var(--ny-encre-2); font-weight: 500; }
|
||||||
|
.course-actions { display: flex; gap: var(--ny-e2); flex: none; flex-wrap: wrap; justify-content: flex-end; }
|
||||||
|
.champ select { min-height: var(--ny-cible); padding: 0 var(--ny-e3); border: 1px solid var(--ny-trait-controle); border-radius: var(--ny-r-s); background: var(--ny-carte); font: 400 16px/24px var(--ny-police); }
|
||||||
|
@media (max-width: 640px) { .course { flex-wrap: wrap; } .course-actions { width: 100%; justify-content: flex-start; padding-left: calc(var(--ny-cible) + var(--ny-e3)); } .lect-course { margin-left: 0; } }
|
||||||
|
|
||||||
|
/* Suivi des demandes */
|
||||||
|
.course-badges { display: flex; gap: var(--ny-e2); flex-wrap: wrap; margin-top: var(--ny-e1, 4px); }
|
||||||
|
.course-badges:empty { display: none; }
|
||||||
|
.etq.relance { background: var(--ny-attention-fond, var(--ny-carte-2)); color: var(--ny-attention, var(--ny-encre)); font-weight: 600; }
|
||||||
|
|
||||||
|
/* Recherche */
|
||||||
|
.recherche-form { display: grid; grid-template-columns: 1fr auto auto; gap: var(--ny-e3); align-items: end; padding: var(--ny-e4); }
|
||||||
|
.recherche-form .champ input[type=search] { min-height: var(--ny-cible); padding: 0 var(--ny-e3); border: 1px solid var(--ny-trait-controle); border-radius: var(--ny-r-s); background: var(--ny-carte); font: 400 16px/24px var(--ny-police); width: 100%; box-sizing: border-box; }
|
||||||
|
.recherche-pj { display: flex; align-items: center; gap: var(--ny-e3); min-height: var(--ny-cible); font: 500 15px/20px var(--ny-police); }
|
||||||
|
.recherche-pj input { width: 22px; height: 22px; margin: 0; accent-color: var(--ny-accent); }
|
||||||
|
@media (max-width: 640px) { .recherche-form { grid-template-columns: 1fr; } }
|
||||||
|
|
||||||
|
/* À suivre : une couleur propre à chaque catégorie, reprise dans toute l'application */
|
||||||
|
.t0 { --g: var(--ny-cat-vide); --gf: var(--ny-carte-2); --gt: var(--ny-trait); }
|
||||||
|
.t1 { --g: var(--ny-cat-1); --gf: var(--ny-cat-1-fond); --gt: var(--ny-cat-1-trait); }
|
||||||
|
.t2 { --g: var(--ny-cat-2); --gf: var(--ny-cat-2-fond); --gt: var(--ny-cat-2-trait); }
|
||||||
|
.t3 { --g: var(--ny-cat-3); --gf: var(--ny-cat-3-fond); --gt: var(--ny-cat-3-trait); }
|
||||||
|
.t4 { --g: var(--ny-cat-4); --gf: var(--ny-cat-4-fond); --gt: var(--ny-cat-4-trait); }
|
||||||
|
.t5 { --g: var(--ny-cat-5); --gf: var(--ny-cat-5-fond); --gt: var(--ny-cat-5-trait); }
|
||||||
|
.t6 { --g: var(--ny-cat-6); --gf: var(--ny-cat-6-fond); --gt: var(--ny-cat-6-trait); }
|
||||||
|
.t7 { --g: var(--ny-cat-7); --gf: var(--ny-cat-7-fond); --gt: var(--ny-cat-7-trait); }
|
||||||
|
.t8 { --g: var(--ny-cat-8); --gf: var(--ny-cat-8-fond); --gt: var(--ny-cat-8-trait); }
|
||||||
|
.t9 { --g: var(--ny-cat-9); --gf: var(--ny-cat-9-fond); --gt: var(--ny-cat-9-trait); }
|
||||||
|
.t10 { --g: var(--ny-cat-10); --gf: var(--ny-cat-10-fond); --gt: var(--ny-cat-10-trait); }
|
||||||
|
.t11 { --g: var(--ny-cat-11); --gf: var(--ny-cat-11-fond); --gt: var(--ny-cat-11-trait); }
|
||||||
|
.t12 { --g: var(--ny-cat-12); --gf: var(--ny-cat-12-fond); --gt: var(--ny-cat-12-trait); }
|
||||||
|
.groupe-suivi { border-left: 8px solid var(--g); }
|
||||||
|
.groupe-tete { display: flex; align-items: center; gap: var(--ny-e3); flex-wrap: wrap; min-height: 56px; padding: var(--ny-e2) var(--ny-e4); background: var(--gf); border-bottom: 1px solid var(--gt); }
|
||||||
|
.groupe-tete .pt { width: 14px; height: 14px; }
|
||||||
|
.groupe-tete h2 { font: 600 17px/24px var(--ny-police); color: var(--ny-encre); }
|
||||||
|
.groupe-tete .nb { font: 500 14px/20px var(--ny-police-chiffres); color: var(--ny-encre-2); }
|
||||||
|
.groupe-tete .btn-ligne { margin-left: auto; }
|
||||||
|
.groupe-suivi .course:first-child { border-top: none; }
|
||||||
|
.btn-suivre[aria-pressed="true"], .lect-suivre[aria-pressed="true"] { background: var(--ny-accent-teinte); border-color: var(--ny-accent); color: var(--ny-accent); }
|
||||||
|
.btn-suivre[aria-pressed="true"] svg, .lect-suivre[aria-pressed="true"] svg { fill: currentColor; }
|
||||||
|
.btn-suivre-txt[aria-pressed="true"] { font-weight: 700; }
|
||||||
|
.lect-suivre { margin-left: auto; }
|
||||||
|
.lect-suivre + .lect-course { margin-left: 0; }
|
||||||
|
.nav-n { margin-left: auto; min-width: 22px; padding: 0 7px; border-radius: var(--ny-r-pastille); background: var(--ny-accent); color: var(--ny-encre-inverse); font: 600 12px/20px var(--ny-police-chiffres); text-align: center; }
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.groupe-suivi { border-left-width: 6px; }
|
||||||
|
/* Le marque-page se range sous la case « traité » : la largeur du texte des lignes ne change pas. */
|
||||||
|
.ligne { row-gap: 0; }
|
||||||
|
.ligne > .coche { grid-column: 1; grid-row: 1; }
|
||||||
|
.ligne > .btn-suivre { grid-column: 1; grid-row: 2; }
|
||||||
|
.ligne > .m-corps { grid-column: 2; grid-row: 1 / span 2; }
|
||||||
|
.ligne > .sel { grid-column: 3; grid-row: 1 / span 2; align-self: center; }
|
||||||
|
}
|
||||||
|
/* Suppression définitive dans « Terminés » : rouge discret, en contour */
|
||||||
|
.btn-petit.btn-danger, .btn-ligne.btn-danger { background: transparent; color: var(--ny-erreur); border: 1px solid var(--ny-erreur); }
|
||||||
|
.btn-petit.btn-danger:hover, .btn-ligne.btn-danger:hover { background: var(--ny-erreur); color: var(--ny-encre-inverse); }
|
||||||
|
|
||||||
|
/* ---------- Barre latérale réductible (portable, tablette) et tiroir (téléphone), tt-2026-11-079 ---------- */
|
||||||
|
.barre-mobile, .nav-voile { display: none; }
|
||||||
|
.nav-tete { display: flex; align-items: center; justify-content: space-between; gap: var(--ny-e2); min-height: var(--ny-cible); }
|
||||||
|
.nav-tete .marque { min-width: 0; }
|
||||||
|
.btn-panneau { position: relative; flex: none; width: var(--ny-cible); height: var(--ny-cible); display: inline-flex; align-items: center; justify-content: center; border: none; border-radius: var(--ny-r-m); background: transparent; color: var(--ny-encre-2); transition: background var(--ny-duree) var(--ny-courbe), color var(--ny-duree) var(--ny-courbe); }
|
||||||
|
.btn-panneau:hover { background: var(--ny-accent-teinte); color: var(--ny-accent); }
|
||||||
|
.btn-panneau:active { background: var(--ny-accent-teinte-2); }
|
||||||
|
.btn-panneau svg { width: 22px; height: 22px; }
|
||||||
|
.nav-btn { position: relative; }
|
||||||
|
.nav-txt { white-space: nowrap; }
|
||||||
|
.nav-point { position: absolute; top: 8px; right: 8px; width: 10px; height: 10px; border: 2px solid var(--ny-carte); border-radius: var(--ny-r-pastille); background: var(--ny-accent); box-sizing: content-box; }
|
||||||
|
.nav-point[hidden] { display: none; }
|
||||||
|
.coque.nav-anim { transition: grid-template-columns var(--ny-duree) var(--ny-courbe); }
|
||||||
|
|
||||||
|
@media (min-width: 761px) {
|
||||||
|
.coque.nav-reduite { grid-template-columns: 72px minmax(0, 1fr); }
|
||||||
|
.nav-reduite .nav-bureau { padding-left: var(--ny-e3); padding-right: var(--ny-e3); }
|
||||||
|
.nav-reduite .nav-tete { justify-content: center; }
|
||||||
|
.nav-reduite .marque, .nav-reduite .pied-nyora { display: none; }
|
||||||
|
.nav-reduite .nav-btn { justify-content: center; padding: 0; }
|
||||||
|
.nav-reduite .nav-txt { position: absolute; width: 1px; height: 1px; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); }
|
||||||
|
.nav-reduite .nav-n { position: absolute; top: 0; right: 0; margin: 0; }
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.barre-mobile { display: flex; align-items: center; gap: var(--ny-e2); min-height: 56px; padding: 0 var(--ny-e2); background: var(--ny-carte); border-bottom: 1px solid var(--ny-trait); }
|
||||||
|
.barre-titre { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font: var(--ny-t2); color: var(--ny-encre); }
|
||||||
|
.nav-bureau { position: fixed; top: 0; bottom: 0; left: 0; z-index: 40; width: min(86vw, 320px); height: 100dvh; padding: var(--ny-e3) var(--ny-e4) calc(var(--ny-e4) + env(safe-area-inset-bottom, 0px)); box-shadow: var(--ny-ombre-2); transform: translateX(-100%); visibility: hidden; transition: transform var(--ny-duree) var(--ny-courbe), visibility 0s linear var(--ny-duree); }
|
||||||
|
.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; }
|
||||||
|
|
||||||
|
.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; }
|
||||||
|
|
||||||
|
.lect-reponse { margin-top: 10px; padding-top: 8px; border-top: 1px solid var(--ny-trait); display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
.champ-indication { width: 100%; min-height: var(--ny-cible, 44px); padding: 0 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; }
|
||||||
|
.brouillon { padding: 12px 14px; border: 1px solid var(--ny-trait); border-radius: var(--ny-r-m, 8px); background: var(--ny-carte); color: var(--ny-encre); font: 400 15px/1.55 Calibri, "Segoe UI", sans-serif; }
|
||||||
|
.brouillon p { margin: 0 0 10px; }
|
||||||
|
.brouillon-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||||
|
.lect-ia-refs { margin: 6px 0; }
|
||||||
|
|
||||||
|
.ligne-valider { touch-action: pan-y; }
|
||||||
|
.ligne-valider.balaye-ok { background: var(--ny-accent-teinte); }
|
||||||
|
.ligne-valider.balaye-non { background: var(--ny-erreur-fond); }
|
||||||
|
|
||||||
|
.resume-pj { flex-basis: 100%; margin: 4px 0 0; white-space: pre-wrap; }
|
||||||
|
.lect-pj li { flex-wrap: wrap; }
|
||||||
+938
-37
File diff suppressed because it is too large.
Load diff
+15
-4
@@ -10,16 +10,27 @@
|
|||||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
||||||
<link rel="stylesheet" href="/static/fonts.css">
|
<link rel="stylesheet" href="/static/fonts.css">
|
||||||
<link rel="stylesheet" href="/static/nyora.css">
|
<link rel="stylesheet" href="/static/nyora.css">
|
||||||
<link rel="stylesheet" href="/static/app.css">
|
<link rel="stylesheet" href="/static/app.css?v=20261121c">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app" class="coque">
|
<div id="app" class="coque">
|
||||||
<nav id="nav-bureau" class="nav-bureau" aria-label="Navigation principale"></nav>
|
<header id="barre-mobile" class="barre-mobile">
|
||||||
|
<button type="button" id="nav-ouvrir" class="btn-panneau" aria-controls="nav-bureau" aria-expanded="false" aria-label="Ouvrir le menu"></button>
|
||||||
|
<span id="barre-titre" class="barre-titre">Courrier</span>
|
||||||
|
</header>
|
||||||
|
<div id="nav-voile" class="nav-voile" hidden></div>
|
||||||
|
<nav id="nav-bureau" class="nav-bureau" aria-label="Navigation principale">
|
||||||
|
<div class="nav-tete">
|
||||||
|
<div class="marque"><b>Courrier</b><span>Lecture seule</span></div>
|
||||||
|
<button type="button" id="nav-bascule" class="btn-panneau" aria-controls="nav-bureau" aria-expanded="true" aria-label="Réduire la barre latérale" title="Réduire la barre latérale"></button>
|
||||||
|
</div>
|
||||||
|
<div id="nav-corps" class="nav-liste"></div>
|
||||||
|
<div class="pied-nyora">Nyora</div>
|
||||||
|
</nav>
|
||||||
<main id="principal" class="principal" tabindex="-1"></main>
|
<main id="principal" class="principal" tabindex="-1"></main>
|
||||||
<nav id="nav-mobile" class="nav-mobile" aria-label="Navigation principale"></nav>
|
|
||||||
</div>
|
</div>
|
||||||
<div id="calque"></div>
|
<div id="calque"></div>
|
||||||
<div id="annonce" class="sr" role="status" aria-live="polite"></div>
|
<div id="annonce" class="sr" role="status" aria-live="polite"></div>
|
||||||
<script src="/static/app.js"></script>
|
<script src="/static/app.js?v=20261121c"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -14,6 +14,10 @@
|
|||||||
--ny-cat-6: #33408F; --ny-cat-6-fond: #ECEEF8; --ny-cat-6-trait: #C3C8E6;
|
--ny-cat-6: #33408F; --ny-cat-6-fond: #ECEEF8; --ny-cat-6-trait: #C3C8E6;
|
||||||
--ny-cat-7: #8C5A3A; --ny-cat-7-fond: #F6EFEA; --ny-cat-7-trait: #E0CBBC;
|
--ny-cat-7: #8C5A3A; --ny-cat-7-fond: #F6EFEA; --ny-cat-7-trait: #E0CBBC;
|
||||||
--ny-cat-8: #9A8BC4; --ny-cat-8-fond: #F2F0F9; --ny-cat-8-trait: #D6D0EA;
|
--ny-cat-8: #9A8BC4; --ny-cat-8-fond: #F2F0F9; --ny-cat-8-trait: #D6D0EA;
|
||||||
|
--ny-cat-9: #2E7D4F; --ny-cat-9-fond: #E7F4EC; --ny-cat-9-trait: #B7DCC6;
|
||||||
|
--ny-cat-10: #B03A5B; --ny-cat-10-fond: #FBEBF0; --ny-cat-10-trait: #E8BBC9;
|
||||||
|
--ny-cat-11: #C25E1C; --ny-cat-11-fond: #FCEFE3; --ny-cat-11-trait: #F0CFB0;
|
||||||
|
--ny-cat-12: #6B7B1C; --ny-cat-12-fond: #F2F5DF; --ny-cat-12-trait: #D5DEA4;
|
||||||
--ny-cat-vide: #56636F;
|
--ny-cat-vide: #56636F;
|
||||||
--ny-police: "Atkinson Hyperlegible Next", "Segoe UI", system-ui, sans-serif;
|
--ny-police: "Atkinson Hyperlegible Next", "Segoe UI", system-ui, sans-serif;
|
||||||
--ny-police-chiffres: "Atkinson Hyperlegible Mono", ui-monospace, monospace;
|
--ny-police-chiffres: "Atkinson Hyperlegible Mono", ui-monospace, monospace;
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
"""Suivi des demandes : calcul par fil de discussion à partir des mails lus (aucune écriture dans la messagerie)."""
|
||||||
|
import re
|
||||||
|
from datetime import datetime
|
||||||
|
from email.utils import getaddresses
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
PREFIXES = re.compile(r"^\s*((re|tr|fw|fwd|rép|rep|réf|ref|ré|aw|sv)\s*:\s*)+", re.IGNORECASE)
|
||||||
|
RELANCE_JOURS = 3
|
||||||
|
AUTOMATIQUE = re.compile(r"no[-_.]?reply|do[-_.]?not[-_.]?reply|mailer-daemon|postmaster|notification", re.IGNORECASE)
|
||||||
|
|
||||||
|
|
||||||
|
def sujet_normalise(sujet: str) -> str:
|
||||||
|
return re.sub(r"\s+", " ", PREFIXES.sub("", sujet or "")).strip().lower()
|
||||||
|
|
||||||
|
|
||||||
|
def _dt(iso: str) -> Optional[datetime]:
|
||||||
|
try:
|
||||||
|
return datetime.fromisoformat(iso)
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _avec(texte: str) -> str:
|
||||||
|
adresses = [a for a in getaddresses([texte or ""]) if a[0] or a[1]]
|
||||||
|
if not adresses:
|
||||||
|
return ""
|
||||||
|
nom = adresses[0][0].strip().strip('"') or adresses[0][1]
|
||||||
|
return nom + (f" +{len(adresses) - 1}" if len(adresses) > 1 else "")
|
||||||
|
|
||||||
|
|
||||||
|
def calculer_suivi(mails: List[Dict[str, Any]], mon_adresse: str, maintenant: datetime, clos: Dict[str, str]) -> List[Dict[str, Any]]:
|
||||||
|
"""mails : mails normalisés (reçus et envoyés, sans doublon). clos : {clé de fil: id du dernier message au moment de la clôture}.
|
||||||
|
États : attente (j'ai écrit en dernier), reponse (quelqu'un a répondu à un message que j'ai écrit), a_repondre (demande reçue sans réponse de ma part)."""
|
||||||
|
mon = (mon_adresse or "").lower()
|
||||||
|
fils: Dict[str, List[Dict[str, Any]]] = {}
|
||||||
|
for m in mails:
|
||||||
|
cle = sujet_normalise(m.get("objet"))
|
||||||
|
d = _dt(m.get("date") or "")
|
||||||
|
if not cle or d is None or not m.get("message_id"):
|
||||||
|
continue
|
||||||
|
if AUTOMATIQUE.search(m.get("expediteur") or ""):
|
||||||
|
continue
|
||||||
|
fils.setdefault(cle, []).append(dict(m, _d=d, _moi=mon in (m.get("expediteur") or "").lower()))
|
||||||
|
sortie = []
|
||||||
|
for cle, msgs in fils.items():
|
||||||
|
msgs.sort(key=lambda x: x["_d"])
|
||||||
|
dernier = msgs[-1]
|
||||||
|
if dernier["_moi"]:
|
||||||
|
autres = [a for a in getaddresses([dernier.get("destinataires") or ""]) if a[1] and mon not in a[1].lower()]
|
||||||
|
if not autres:
|
||||||
|
continue # message adressé à moi seul : rien à attendre
|
||||||
|
etat, avec = "attente", _avec(dernier.get("destinataires"))
|
||||||
|
else:
|
||||||
|
if mon not in (dernier.get("destinataires") or "").lower():
|
||||||
|
continue # en copie seulement : rien à répondre
|
||||||
|
etat = "reponse" if any(x["_moi"] for x in msgs[:-1]) else "a_repondre"
|
||||||
|
avec = _avec(dernier.get("expediteur"))
|
||||||
|
jours = max(0, (maintenant - dernier["_d"]).days) if dernier["_d"].tzinfo else 0
|
||||||
|
sortie.append({
|
||||||
|
"cle": cle, "sujet": PREFIXES.sub("", dernier.get("objet") or "").strip() or dernier.get("objet") or "",
|
||||||
|
"avec": avec, "dernier_id": dernier["message_id"], "date": dernier.get("date"), "jours": jours, "etat": etat,
|
||||||
|
"relancer": etat == "attente" and jours >= RELANCE_JOURS, "nb": len(msgs),
|
||||||
|
"clos": clos.get(cle) == dernier["message_id"],
|
||||||
|
})
|
||||||
|
ordre = {"attente": 0, "reponse": 1, "a_repondre": 2}
|
||||||
|
sortie.sort(key=lambda x: (ordre[x["etat"]], x["date"] or "") if x["etat"] == "attente" else (ordre[x["etat"]], _inverse(x["date"])))
|
||||||
|
return sortie
|
||||||
|
|
||||||
|
|
||||||
|
def _inverse(date: Optional[str]) -> str:
|
||||||
|
return "".join(chr(0x10FFFF - ord(c)) for c in (date or ""))
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
[pytest]
|
||||||
|
markers =
|
||||||
|
regles_off: moteur de regles automatiques laisse eteint (defaut reel)
|
||||||
@@ -4,3 +4,6 @@ pydantic>=2.0.0,<3.0.0
|
|||||||
httpx>=0.27.0,<1.0.0
|
httpx>=0.27.0,<1.0.0
|
||||||
pyjwt[crypto]>=2.8.0,<3.0.0
|
pyjwt[crypto]>=2.8.0,<3.0.0
|
||||||
pytest>=8.0.0,<9.0.0
|
pytest>=8.0.0,<9.0.0
|
||||||
|
|
||||||
|
openpyxl>=3.1,<4.0.0
|
||||||
|
pypdf>=4.0,<6.0.0
|
||||||
@@ -50,3 +50,12 @@ def client(valid_jwt_token, temp_db, monkeypatch):
|
|||||||
with TestClient(app) as c:
|
with TestClient(app) as c:
|
||||||
c.headers.update({"Cf-Access-Jwt-Assertion": valid_jwt_token})
|
c.headers.update({"Cf-Access-Jwt-Assertion": valid_jwt_token})
|
||||||
yield c
|
yield c
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _regles_auto_pour_tests_historiques(request, monkeypatch):
|
||||||
|
"""Les tests historiques verifient le moteur de regles : ils le tiennent allume.
|
||||||
|
Le reglage reel est eteint par defaut (test_regles_auto_off.py, marqueur regles_off)."""
|
||||||
|
if request.node.get_closest_marker("regles_off"):
|
||||||
|
return
|
||||||
|
monkeypatch.setattr("app.classifier.regles_auto_actives", lambda db_path=None: True)
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
"""Onglet « À suivre » : marqueur manuel, sans limite de date, réversible, et couleur propre à chaque catégorie."""
|
||||||
|
import sqlite3
|
||||||
|
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.db import init_db, add_category, list_categories, update_category, delete_category
|
||||||
|
from app.main import app
|
||||||
|
|
||||||
|
M1 = {"message_id": "m-1", "expediteur": "Ali <ali@exemple.tn>", "objet": "Courses Tunis", "date_mail": "2026-10-02T09:00:00+01:00", "categorie": "Tunis"}
|
||||||
|
M2 = {"message_id": "m-2", "expediteur": "Sana <sana@exemple.tn>", "objet": "Marché RLA", "date_mail": "2026-11-18T14:30:00+01:00", "categorie": "RLA"}
|
||||||
|
M3 = {"message_id": "m-3", "expediteur": "Omar <omar@exemple.tn>", "objet": "Câbles", "date_mail": "2026-11-10T08:00:00+01:00", "categorie": "Câbles"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_exige_le_jeton():
|
||||||
|
c = TestClient(app)
|
||||||
|
assert c.get("/api/v1/a-suivre").status_code == 401
|
||||||
|
assert c.post("/api/v1/a-suivre/marquer", json=M1).status_code == 401
|
||||||
|
assert c.post("/api/v1/a-suivre/retirer", json={"ids": ["m-1"]}).status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_marquer_garde_la_copie_et_ne_depend_pas_de_la_date(client):
|
||||||
|
r = client.post("/api/v1/a-suivre/marquer", json=M1)
|
||||||
|
assert r.status_code == 200
|
||||||
|
d = r.json()
|
||||||
|
assert d["statut"] == "actif" and d["objet"] == "Courses Tunis" and d["categorie"] == "Tunis" and d["jours"] == 0
|
||||||
|
liste = client.get("/api/v1/a-suivre?statut=actif").json()
|
||||||
|
assert [i["message_id"] for i in liste["items"]] == ["m-1"] # mail du 02/10 toujours là
|
||||||
|
assert liste["compte"] == {"actif": 1, "termine": 0}
|
||||||
|
|
||||||
|
|
||||||
|
def test_double_marquage_garde_la_date_de_marquage(client):
|
||||||
|
a = client.post("/api/v1/a-suivre/marquer", json=M1).json()
|
||||||
|
b = client.post("/api/v1/a-suivre/marquer", json=M1).json()
|
||||||
|
assert a["marque_le"] == b["marque_le"]
|
||||||
|
assert len(client.get("/api/v1/a-suivre").json()["items"]) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_les_plus_recents_en_premier(client):
|
||||||
|
for m in (M1, M2, M3):
|
||||||
|
client.post("/api/v1/a-suivre/marquer", json=m)
|
||||||
|
ordre = [i["message_id"] for i in client.get("/api/v1/a-suivre?statut=actif").json()["items"]]
|
||||||
|
assert ordre == ["m-2", "m-3", "m-1"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_retirer_ne_supprime_rien_et_se_defait(client):
|
||||||
|
for m in (M1, M2):
|
||||||
|
client.post("/api/v1/a-suivre/marquer", json=m)
|
||||||
|
r = client.post("/api/v1/a-suivre/retirer", json={"ids": ["m-1", "m-1", "inconnu"]}).json()
|
||||||
|
assert r["ids"] == ["m-1"]
|
||||||
|
assert client.get("/api/v1/a-suivre?statut=actif").json()["compte"] == {"actif": 1, "termine": 1}
|
||||||
|
term = client.get("/api/v1/a-suivre?statut=termine").json()["items"]
|
||||||
|
assert [i["message_id"] for i in term] == ["m-1"] and term[0]["termine_le"]
|
||||||
|
avant = term[0]["marque_le"]
|
||||||
|
r = client.post("/api/v1/a-suivre/remettre", json={"ids": ["m-1"]}).json()
|
||||||
|
assert r["ids"] == ["m-1"]
|
||||||
|
back = [i for i in client.get("/api/v1/a-suivre?statut=actif").json()["items"] if i["message_id"] == "m-1"][0]
|
||||||
|
assert back["marque_le"] == avant and back["termine_le"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_remarquer_un_mail_retire_le_reactive(client):
|
||||||
|
client.post("/api/v1/a-suivre/marquer", json=M1)
|
||||||
|
client.post("/api/v1/a-suivre/retirer", json={"ids": ["m-1"]})
|
||||||
|
client.post("/api/v1/a-suivre/marquer", json=M1)
|
||||||
|
assert client.get("/api/v1/a-suivre").json()["compte"] == {"actif": 1, "termine": 0}
|
||||||
|
|
||||||
|
|
||||||
|
def test_retirer_toute_une_categorie_en_un_appel(client):
|
||||||
|
for i in range(5):
|
||||||
|
client.post("/api/v1/a-suivre/marquer", json={**M1, "message_id": f"t-{i}", "date_mail": f"2026-11-0{i+1}T09:00:00+01:00"})
|
||||||
|
client.post("/api/v1/a-suivre/marquer", json=M2)
|
||||||
|
ids = [i["message_id"] for i in client.get("/api/v1/a-suivre?statut=actif").json()["items"] if i["categorie"] == "Tunis"]
|
||||||
|
assert len(ids) == 5
|
||||||
|
assert len(client.post("/api/v1/a-suivre/retirer", json={"ids": ids}).json()["ids"]) == 5
|
||||||
|
assert client.get("/api/v1/a-suivre").json()["compte"] == {"actif": 1, "termine": 5}
|
||||||
|
|
||||||
|
|
||||||
|
def test_la_categorie_affichee_est_la_categorie_actuelle(client):
|
||||||
|
client.post("/api/v1/a-suivre/marquer", json=M1)
|
||||||
|
client.post("/api/v1/classements/m-1", json={"categorie": "CI", "mail_info": {"message_id": "m-1", "expediteur": "Ali", "objet": "Courses Tunis", "date": "2026-10-02T09:00:00+01:00"}})
|
||||||
|
assert client.get("/api/v1/a-suivre").json()["items"][0]["categorie"] == "CI"
|
||||||
|
|
||||||
|
|
||||||
|
def test_categorie_inconnue_devient_a_classer(client):
|
||||||
|
d = client.post("/api/v1/a-suivre/marquer", json={"message_id": "x-1", "objet": "Sans info"}).json()
|
||||||
|
assert d["categorie"] == "À classer"
|
||||||
|
|
||||||
|
|
||||||
|
def test_renommer_une_categorie_met_a_jour_les_copies(client, temp_db):
|
||||||
|
cat = add_category("Projet X", temp_db)
|
||||||
|
client.post("/api/v1/a-suivre/marquer", json={**M1, "categorie": "Projet X", "message_id": "p-1"})
|
||||||
|
update_category(cat["id"], "Projet Y", temp_db)
|
||||||
|
assert client.get("/api/v1/a-suivre").json()["items"][0]["categorie"] == "Projet Y"
|
||||||
|
delete_category(cat["id"], temp_db)
|
||||||
|
assert client.get("/api/v1/a-suivre").json()["items"][0]["categorie"] == "À classer"
|
||||||
|
|
||||||
|
|
||||||
|
def test_validation(client):
|
||||||
|
assert client.post("/api/v1/a-suivre/marquer", json={}).status_code == 422
|
||||||
|
assert client.post("/api/v1/a-suivre/retirer", json={"ids": []}).status_code == 422
|
||||||
|
assert client.post("/api/v1/a-suivre/retirer", json={"ids": [""]}).status_code == 422
|
||||||
|
assert client.get("/api/v1/a-suivre?statut=nimporte").status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_chaque_categorie_a_sa_propre_couleur(temp_db):
|
||||||
|
for n in ("RLA", "Box 5G", "Pb Stock", "Pb PO", "Drapeau", "Projet X", "Projet Y"):
|
||||||
|
add_category(n, temp_db)
|
||||||
|
couleurs = {c["name"]: c["couleur"] for c in list_categories(temp_db)}
|
||||||
|
assert couleurs["À classer"] == 0 and couleurs["Tunis"] == 1 and couleurs["Sans objet"] == 5
|
||||||
|
perso = [couleurs[n] for n in ("RLA", "Box 5G", "Pb Stock", "Pb PO", "Drapeau", "Projet X", "Projet Y")]
|
||||||
|
assert len(set(perso)) == 7 and all(6 <= c <= 12 for c in perso)
|
||||||
|
# une couleur ne change jamais quand on renomme
|
||||||
|
cat = [c for c in list_categories(temp_db) if c["name"] == "RLA"][0]
|
||||||
|
update_category(cat["id"], "RLA 2026", temp_db)
|
||||||
|
assert [c for c in list_categories(temp_db) if c["name"] == "RLA 2026"][0]["couleur"] == cat["couleur"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_migration_d_une_base_existante_sans_couleur(tmp_path):
|
||||||
|
chemin = str(tmp_path / "ancienne.db")
|
||||||
|
c = sqlite3.connect(chemin)
|
||||||
|
c.execute("CREATE TABLE categories (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL, created_at TEXT NOT NULL)")
|
||||||
|
for i, n in ((1, "Tunis"), (6, "À classer"), (73, "Box 5G"), (74, "Pb Stock"), (99, "RLA"), (142, "Pb PO"), (143, "Drapeau")):
|
||||||
|
c.execute("INSERT INTO categories (id, name, created_at) VALUES (?, ?, 'x')", (i, n))
|
||||||
|
c.commit(); c.close()
|
||||||
|
init_db(chemin)
|
||||||
|
couleurs = {x["name"]: x["couleur"] for x in list_categories(chemin)}
|
||||||
|
assert couleurs["RLA"] == 6 and couleurs["Box 5G"] == 7 and couleurs["Pb Stock"] == 8 # teintes habituelles conservées
|
||||||
|
perso = [couleurs[n] for n in ("RLA", "Box 5G", "Pb Stock", "Pb PO", "Drapeau")]
|
||||||
|
assert len(set(perso)) == 5 # plus aucune collision
|
||||||
|
init_db(chemin) # idempotent
|
||||||
|
assert {x["name"]: x["couleur"] for x in list_categories(chemin)} == couleurs
|
||||||
|
|
||||||
|
def test_supprimer_termine_seulement(client):
|
||||||
|
for i in ("m1", "m2", "m3"):
|
||||||
|
client.post("/api/v1/a-suivre/marquer", json={"message_id": i, "objet": i})
|
||||||
|
client.post("/api/v1/a-suivre/retirer", json={"ids": ["m1", "m2"]})
|
||||||
|
r = client.post("/api/v1/a-suivre/supprimer", json={"ids": ["m1", "m3"]})
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert r.json()["ids"] == ["m1"] # m3 est actif : jamais supprimé
|
||||||
|
tout = client.get("/api/v1/a-suivre?statut=tous").json()
|
||||||
|
assert sorted(i["message_id"] for i in tout["items"]) == ["m2", "m3"]
|
||||||
|
assert tout["compte"] == {"actif": 1, "termine": 1}
|
||||||
|
|
||||||
|
|
||||||
|
def test_supprimer_puis_remarquer(client):
|
||||||
|
client.post("/api/v1/a-suivre/marquer", json={"message_id": "x", "objet": "x"})
|
||||||
|
client.post("/api/v1/a-suivre/retirer", json={"ids": ["x"]})
|
||||||
|
client.post("/api/v1/a-suivre/supprimer", json={"ids": ["x"]})
|
||||||
|
assert client.post("/api/v1/a-suivre/marquer", json={"message_id": "x", "objet": "x"}).json()["statut"] == "actif"
|
||||||
|
|
||||||
|
|
||||||
|
def test_supprimer_validation(client):
|
||||||
|
assert client.post("/api/v1/a-suivre/supprimer", json={"ids": []}).status_code == 422
|
||||||
@@ -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,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"]
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
from app import analyse as a
|
||||||
|
|
||||||
|
|
||||||
|
def _f(act, ech):
|
||||||
|
return {"categorie": "À classer", "confiance": "basse", "resume": "x", "course": None,
|
||||||
|
"demande": {"reelle": True, "action": act, "echeance": ech}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_briefing_demandes_ouvertes_triees(temp_db):
|
||||||
|
a.enregistrer("a", _f("Repondre", "30/11/2026"), "oa", "e@x", "2026-11-20T08:00:00", temp_db)
|
||||||
|
a.enregistrer("b", _f("Signer", "25/11/2026"), "ob", "e@x", "2026-11-20T09:00:00", temp_db)
|
||||||
|
r = a.briefing("2026-11-21", temp_db)
|
||||||
|
assert [i["message_id"] for i in r["demandes_ouvertes"]] == ["b", "a"]
|
||||||
|
assert r["courses_a_faire"] == [] and r["a_suivre_actifs"] == []
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import pytest
|
||||||
|
from app import brouillon as b, ia
|
||||||
|
|
||||||
|
|
||||||
|
def test_assainir_garde_la_mise_en_page_et_retire_le_dangereux():
|
||||||
|
h = b.assainir('<p onclick="x()">Bonjour <strong>Samia</strong></p><script>alert(1)</script><a href="http://x">lien</a><ul><li>un</li></ul>')
|
||||||
|
assert h == "<p>Bonjour <strong>Samia</strong></p>lien<ul><li>un</li></ul>"
|
||||||
|
assert "onclick" not in h and "script" not in h and "href" not in h
|
||||||
|
|
||||||
|
|
||||||
|
def test_assainir_ferme_les_balises_et_echappe():
|
||||||
|
assert b.assainir("<p>a < b <strong>gras") == "<p>a < b <strong>gras</strong></p>"
|
||||||
|
|
||||||
|
|
||||||
|
def test_texte_brut():
|
||||||
|
assert b.en_texte("<p>Bonjour,</p><p>Merci.<br>A bientot</p><ul><li>un</li></ul>") == "Bonjour,\nMerci.\nA bientot\n- un"
|
||||||
|
|
||||||
|
|
||||||
|
def test_rediger_via_privaite_seulement(monkeypatch):
|
||||||
|
vus = {}
|
||||||
|
def faux(messages, max_tokens=30):
|
||||||
|
vus["m"] = messages
|
||||||
|
return "```html\n<p>Bonjour,</p><p>C'est note.</p><p>Cordialement,<br>Nabil Derouiche</p>\n```"
|
||||||
|
monkeypatch.setattr(ia, "appeler_privaite", faux)
|
||||||
|
r = b.rediger("PO 123", "x@tt.tn", "Merci de confirmer", "- ctx", "dire oui")
|
||||||
|
assert r["objet"] == "RE: PO 123" and "<p>Bonjour,</p>" in r["html"] and "```" not in r["html"]
|
||||||
|
assert "Contexte du fil" in vus["m"][1]["content"] and "dire oui" in vus["m"][1]["content"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_refus_net_si_privaite_injoignable(monkeypatch):
|
||||||
|
def casse(messages, max_tokens=30):
|
||||||
|
raise ia.IAIndisponible("PrivAiTe injoignable")
|
||||||
|
monkeypatch.setattr(ia, "appeler_privaite", casse)
|
||||||
|
with pytest.raises(ia.IAIndisponible):
|
||||||
|
b.rediger("o", "e", "c")
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import io
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from openpyxl import load_workbook
|
||||||
|
|
||||||
|
from app.main import app
|
||||||
|
|
||||||
|
STATIC = Path(__file__).resolve().parent.parent / "app" / "static"
|
||||||
|
BASE = {"demande": "Rapporter 20 cartes SIM", "sens": "tunis_sfax", "message_id": "m-9", "objet_mail": "RE: Cartes SIM",
|
||||||
|
"expediteur": "Ali <ali@exemple.tn>", "date_mail": "2026-11-17T09:41:00+01:00"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_courses_exigent_le_jeton():
|
||||||
|
c = TestClient(app)
|
||||||
|
assert c.get("/api/v1/courses").status_code == 401
|
||||||
|
assert c.get("/api/v1/courses/export").status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_creation_liste_modification_suppression(client):
|
||||||
|
r = client.post("/api/v1/courses", json=BASE)
|
||||||
|
assert r.status_code == 201
|
||||||
|
k = r.json()
|
||||||
|
assert k["statut"] == "a_faire" and k["sens"] == "tunis_sfax" and k["fait_le"] is None and k["message_id"] == "m-9"
|
||||||
|
assert [x["id"] for x in client.get("/api/v1/courses?statut=a_faire").json()["courses"]] == [k["id"]]
|
||||||
|
assert client.get("/api/v1/courses?statut=faite").json()["courses"] == []
|
||||||
|
p = client.patch(f"/api/v1/courses/{k['id']}", json={"statut": "faite"}).json()
|
||||||
|
assert p["statut"] == "faite" and p["fait_le"]
|
||||||
|
p = client.patch(f"/api/v1/courses/{k['id']}", json={"statut": "a_faire", "demande": "Rapporter 25 cartes SIM", "sens": "sfax_tunis"}).json()
|
||||||
|
assert p["fait_le"] is None and p["demande"] == "Rapporter 25 cartes SIM" and p["sens"] == "sfax_tunis"
|
||||||
|
assert client.delete(f"/api/v1/courses/{k['id']}").status_code == 200
|
||||||
|
assert client.get("/api/v1/courses").json()["courses"] == []
|
||||||
|
assert client.delete(f"/api/v1/courses/{k['id']}").status_code == 404
|
||||||
|
assert client.patch("/api/v1/courses/999", json={"statut": "faite"}).status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("corps", [{"demande": ""}, {"demande": " "}, {"demande": "x", "sens": "paris"}, {}])
|
||||||
|
def test_creation_invalide(client, corps):
|
||||||
|
assert client.post("/api/v1/courses", json=corps).status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_modification_invalide(client):
|
||||||
|
k = client.post("/api/v1/courses", json=BASE).json()
|
||||||
|
assert client.patch(f"/api/v1/courses/{k['id']}", json={"statut": "zzz"}).status_code == 422
|
||||||
|
assert client.patch(f"/api/v1/courses/{k['id']}", json={"demande": " "}).status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_les_faites_passent_en_dernier_dans_toutes(client):
|
||||||
|
a = client.post("/api/v1/courses", json=dict(BASE, demande="A")).json()
|
||||||
|
b = client.post("/api/v1/courses", json=dict(BASE, demande="B")).json()
|
||||||
|
client.patch(f"/api/v1/courses/{b['id']}", json={"statut": "faite"})
|
||||||
|
assert [x["demande"] for x in client.get("/api/v1/courses?statut=toutes").json()["courses"]] == ["A", "B"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_export_xlsx_clair_et_sans_trace_d_outil(client):
|
||||||
|
a = client.post("/api/v1/courses", json=BASE).json()
|
||||||
|
client.post("/api/v1/courses", json=dict(BASE, demande="Apporter le cheque", sens="sfax_tunis"))
|
||||||
|
client.patch(f"/api/v1/courses/{a['id']}", json={"statut": "faite"})
|
||||||
|
r = client.get("/api/v1/courses/export?statut=toutes")
|
||||||
|
assert r.status_code == 200 and "attachment" in r.headers["content-disposition"] and r.headers["content-disposition"].endswith('.xlsx"')
|
||||||
|
wb = load_workbook(io.BytesIO(r.content))
|
||||||
|
ws = wb["COURSES"]
|
||||||
|
assert wb.properties.creator == "Nabil.Derouiche" and wb.properties.lastModifiedBy == "Nabil.Derouiche"
|
||||||
|
assert ws["A1"].value == "COURSES POUR TUNIS" and ws["B4"].value == "DEMANDE" and ws["H4"].value == "REALISEE LE"
|
||||||
|
titres = [ws.cell(row=4, column=i).value for i in range(1, 9)]
|
||||||
|
assert all(t == t.upper() and t.isascii() or t == "N°" for t in titres)
|
||||||
|
assert ws.max_row == 6
|
||||||
|
ligne = {ws.cell(row=r, column=2).value: [ws.cell(row=r, column=i).value for i in range(1, 9)] for r in (5, 6)}
|
||||||
|
assert ligne["Rapporter 20 cartes SIM"][2] == "Tunis vers Sfax" and ligne["Rapporter 20 cartes SIM"][3] == "17/11/2026"
|
||||||
|
assert ligne["Rapporter 20 cartes SIM"][6] == "Faite" and ligne["Rapporter 20 cartes SIM"][7]
|
||||||
|
assert ws.freeze_panes == "A5" and ws.page_setup.orientation == "landscape"
|
||||||
|
brut = r.content
|
||||||
|
import zipfile
|
||||||
|
z = zipfile.ZipFile(io.BytesIO(brut))
|
||||||
|
texte = (z.read("docProps/core.xml") + z.read("docProps/app.xml")).decode("utf-8", "ignore").lower()
|
||||||
|
assert "openpyxl" not in texte
|
||||||
|
|
||||||
|
|
||||||
|
def test_export_suit_le_filtre(client):
|
||||||
|
client.post("/api/v1/courses", json=dict(BASE, demande="Une"))
|
||||||
|
k = client.post("/api/v1/courses", json=dict(BASE, demande="Deux")).json()
|
||||||
|
client.patch(f"/api/v1/courses/{k['id']}", json={"statut": "faite"})
|
||||||
|
ws = load_workbook(io.BytesIO(client.get("/api/v1/courses/export?statut=a_faire").content))["COURSES"]
|
||||||
|
assert ws.max_row == 5 and ws["B5"].value == "Une"
|
||||||
|
assert client.get("/api/v1/courses/export?statut=nimporte").status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_interface_courses():
|
||||||
|
js = (STATIC / "app.js").read_text(encoding="utf-8")
|
||||||
|
assert "vueCourses" in js and "dialogueCourse" in js and "Ajouter aux courses" in js and "innerHTML" not in js
|
||||||
|
assert "['courses', 'Courses pour Tunis', true]" in js
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
from app.main import app, mirror_client
|
||||||
|
|
||||||
|
|
||||||
|
def _m(i, objet, date="2026-11-17T09:00:00+01:00"):
|
||||||
|
return {"message_id": i, "objet": objet, "expediteur": "a@b.tn", "date": date, "etiquettes": ["tunis"], "resume": ""}
|
||||||
|
|
||||||
|
|
||||||
|
def test_sync_cree_une_course_par_fil_tunis(client, monkeypatch):
|
||||||
|
mails = [_m("a1", "Cartes SIM pour Tunis"), _m("a2", "RE: Cartes SIM pour Tunis", "2026-11-17T10:00:00+01:00"),
|
||||||
|
_m("a3", "Colis Sfax vers Tunis urgent"), {**_m("a4", "Facture quelconque"), "etiquettes": []}]
|
||||||
|
monkeypatch.setattr(mirror_client, "get_mails_since", lambda debut, max_items=800: mails)
|
||||||
|
r = client.post("/api/v1/courses/synchroniser").json()
|
||||||
|
assert r["ajoutees"] == 2
|
||||||
|
sens = {k["demande"]: k["sens"] for k in client.get("/api/v1/courses").json()["courses"]}
|
||||||
|
assert sens == {"Cartes SIM pour Tunis": "tunis_sfax", "Colis Sfax vers Tunis urgent": "sfax_tunis"}
|
||||||
|
assert client.post("/api/v1/courses/synchroniser").json()["ajoutees"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_course_supprimee_n_est_pas_recreee(client, monkeypatch):
|
||||||
|
monkeypatch.setattr(mirror_client, "get_mails_since", lambda debut, max_items=800: [_m("b1", "Dossier pour Tunis")])
|
||||||
|
k = client.post("/api/v1/courses/synchroniser").json()["courses"][0]
|
||||||
|
assert client.delete(f"/api/v1/courses/{k['id']}").status_code == 200
|
||||||
|
assert client.post("/api/v1/courses/synchroniser").json()["ajoutees"] == 0
|
||||||
|
assert client.get("/api/v1/courses").json()["courses"] == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_sync_miroir_indisponible_et_jeton(client, monkeypatch):
|
||||||
|
def casse(*a, **k):
|
||||||
|
raise RuntimeError("x")
|
||||||
|
monkeypatch.setattr(mirror_client, "get_mails_since", casse)
|
||||||
|
assert client.post("/api/v1/courses/synchroniser").status_code == 502
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import pytest
|
||||||
|
from app import analyse as a
|
||||||
|
from app.classifier import manual_classify_and_propose
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.regles_off
|
||||||
|
|
||||||
|
|
||||||
|
def _f(cat, resume="R."):
|
||||||
|
return {"categorie": cat, "confiance": "haute", "resume": resume, "course": None,
|
||||||
|
"demande": {"reelle": False, "action": "", "echeance": ""}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_exemples_max_par_categorie_et_pas_de_corps(temp_db):
|
||||||
|
for i in range(5):
|
||||||
|
manual_classify_and_propose("t%d" % i, "Tunis", {"expediteur": "a@b", "objet": "Course %d" % i}, db_path=temp_db)
|
||||||
|
manual_classify_and_propose("p1", "Pb PO", {"expediteur": "c@d", "objet": "PO 1"}, db_path=temp_db)
|
||||||
|
ex = a.exemples_nabil(temp_db)
|
||||||
|
assert ex.count("=> Tunis") == 3 and "=> Pb PO" in ex
|
||||||
|
|
||||||
|
|
||||||
|
def test_refus_devient_contre_exemple_et_stats(temp_db):
|
||||||
|
a.enregistrer("m1", _f("Box 5G"), "Rapport regional", "x@tt.tn", "2026-11-21T09:00:00", temp_db)
|
||||||
|
a.decider("m1", "categorie", "refuser", temp_db)
|
||||||
|
assert "PAS Box 5G" in a.exemples_nabil(temp_db)
|
||||||
|
a.enregistrer("m2", _f("CI"), "Travaux", "x@tt.tn", "2026-11-21T09:00:00", temp_db)
|
||||||
|
a.decider("m2", "categorie", "accepter", temp_db)
|
||||||
|
st = a.stats_acceptation(temp_db)
|
||||||
|
assert st["total"] == {"acceptees": 1, "refusees": 1}
|
||||||
|
assert st["categories"]["CI"]["acceptees"] == 1 and st["categories"]["Box 5G"]["refusees"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_inclut_exemples_sans_imposer_de_regle():
|
||||||
|
m = a.construire_messages("o", "e", "c", ["Tunis"], "", "- x | y => Tunis")
|
||||||
|
assert "Exemples de choix reels" in m[0]["content"] and "autre categorie un autre jour" in m[0]["content"]
|
||||||
|
assert "Exemples de choix reels" not in a.construire_messages("o", "e", "c", ["Tunis"])[0]["content"]
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import json
|
||||||
|
from app.mirror_client import MirrorClient
|
||||||
|
|
||||||
|
|
||||||
|
def mail(i, jour, hh="10:00:00", tags=None):
|
||||||
|
return {"message_id": f"m{i}", "dossier": "Boîte de réception", "date_reception": f"{jour}T{hh}+01:00",
|
||||||
|
"expediteur": "a@b.c", "sujet": f"s{i}", "etiquettes": tags or []}
|
||||||
|
|
||||||
|
|
||||||
|
class Faux(MirrorClient):
|
||||||
|
"""Miroir simulé : 300 mails, 10 par jour du 01/11 au 30/11 ; latest plafonné à 100, search à 100."""
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__(base_url="http://x", token="t")
|
||||||
|
self.appels = []
|
||||||
|
self.tous = [mail(i, f"2026-11-{1 + i // 10:02d}", f"{(i % 10) + 8:02d}:00:00") for i in range(300)]
|
||||||
|
self.tous.append(mail(999, "2026-11-05", "09:00:00", ["sans_objet"]))
|
||||||
|
self.tous[-1]["sujet"] = ""
|
||||||
|
|
||||||
|
def call_tool(self, nom, args=None, use_cache=True, force=False):
|
||||||
|
args = args or {}
|
||||||
|
self.appels.append((nom, dict(args)))
|
||||||
|
n = min(args.get("n", 10), 100)
|
||||||
|
if nom == "mirror_mail_latest":
|
||||||
|
return {"donnees": sorted(self.tous, key=lambda m: m["date_reception"], reverse=True)[:n]}
|
||||||
|
if nom == "mirror_mail_search":
|
||||||
|
d, f = args["since"], args["until"]
|
||||||
|
r = [m for m in self.tous if d <= m["date_reception"][:10] < f and m["sujet"]]
|
||||||
|
return {"donnees": sorted(r, key=lambda m: m["date_reception"], reverse=True)[:n]}
|
||||||
|
if nom == "mirror_mail_by_tag":
|
||||||
|
d, f = args["periode"].split("..")
|
||||||
|
r = [m for m in self.tous if d <= m["date_reception"][:10] <= f and args["etiquette"] in m["etiquettes"]]
|
||||||
|
return {"donnees": r[:n]}
|
||||||
|
return {"donnees": []}
|
||||||
|
|
||||||
|
|
||||||
|
def test_periode_courte_sans_recherche():
|
||||||
|
c = Faux()
|
||||||
|
r = c.get_mails_since("2026-11-26")
|
||||||
|
assert len(r) == 50 or len(r) > 0
|
||||||
|
assert all(a[0] == "mirror_mail_latest" for a in c.appels)
|
||||||
|
|
||||||
|
|
||||||
|
def test_periode_longue_complete():
|
||||||
|
c = Faux()
|
||||||
|
r = c.get_mails_since("2026-11-01", max_items=800)
|
||||||
|
ids = {m["message_id"] for m in r}
|
||||||
|
assert len(ids) == len(r) == 301
|
||||||
|
assert "m999" in ids # mail sans objet récupéré par l'étiquette
|
||||||
|
assert [m["date"] for m in r] == sorted((m["date"] for m in r), reverse=True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_fenetre_pleine_coupee_en_deux():
|
||||||
|
c = Faux()
|
||||||
|
c.mails_fenetre("2026-11-01", "2026-11-30")
|
||||||
|
recherches = [a for a in c.appels if a[0] == "mirror_mail_search"]
|
||||||
|
assert len(recherches) > 1
|
||||||
|
assert all(a[1]["n"] == 100 for a in recherches)
|
||||||
|
|
||||||
|
|
||||||
|
def test_cache_fenetre():
|
||||||
|
c = Faux()
|
||||||
|
c.mails_fenetre("2026-11-01", "2026-11-12")
|
||||||
|
n1 = len(c.appels)
|
||||||
|
c.mails_fenetre("2026-11-01", "2026-11-12")
|
||||||
|
assert len(c.appels) == n1
|
||||||
|
|
||||||
|
|
||||||
|
def test_echec_recherche_garde_les_100_derniers():
|
||||||
|
c = Faux()
|
||||||
|
base = c.call_tool
|
||||||
|
def casse(nom, args=None, use_cache=True, force=False):
|
||||||
|
if nom == "mirror_mail_search":
|
||||||
|
raise ConnectionError("miroir")
|
||||||
|
return base(nom, args, use_cache, force)
|
||||||
|
c.call_tool = casse
|
||||||
|
r = c.get_mails_since("2026-11-01", max_items=800)
|
||||||
|
assert len(r) == 100
|
||||||
|
|
||||||
|
|
||||||
|
def test_jour_ancien():
|
||||||
|
c = Faux()
|
||||||
|
r = c.get_mails_for_day("2026-11-03", max_items=100)
|
||||||
|
assert len(r) == 10 and all("2026-11-03" in m["date"] for m in r)
|
||||||
@@ -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"]
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from app.main import app
|
||||||
|
|
||||||
|
STATIC = Path(__file__).resolve().parent.parent / "app" / "static"
|
||||||
|
|
||||||
|
|
||||||
|
def test_periode_exige_jeton():
|
||||||
|
assert TestClient(app).get("/api/v1/mails/periode?jours=7").status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_vue_groupes_presente():
|
||||||
|
js = (STATIC / "app.js").read_text(encoding="utf-8")
|
||||||
|
assert "vueGroupes" in js and "/mails/periode" in js and "etiquettes" in js
|
||||||
|
assert "innerHTML" not in js
|
||||||
|
|
||||||
|
|
||||||
|
def test_statiques_sans_cache_navigateur():
|
||||||
|
r = TestClient(app).get("/static/app.css")
|
||||||
|
assert r.headers["cache-control"] == "no-cache"
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app import ia
|
||||||
|
from app.main import app, mirror_client
|
||||||
|
|
||||||
|
DONNEES = {"message_id": "m-1", "en_tetes": {"Subject": "Colis pour Tunis"},
|
||||||
|
"corps_texte": "Merci de rapporter le colis. Ali Test 12 345,678 DT"}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def mail(monkeypatch):
|
||||||
|
monkeypatch.setattr(mirror_client, "get_mail", lambda mid: {"donnees": DONNEES})
|
||||||
|
|
||||||
|
|
||||||
|
def test_ia_desactivee_par_defaut(client):
|
||||||
|
assert client.get("/api/v1/ia/etat").json()["actif"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_suggestion_refusee_si_ia_desactivee(client, mail, monkeypatch):
|
||||||
|
appels = []
|
||||||
|
monkeypatch.setattr(ia, "appeler_privaite", lambda *a, **k: appels.append(1) or "Tunis")
|
||||||
|
assert client.get("/api/v1/ia/suggestion?id=m-1").status_code == 409
|
||||||
|
assert appels == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_interrupteur_se_bascule(client):
|
||||||
|
assert client.put("/api/v1/ia/etat", json={"actif": True}).json()["actif"] is True
|
||||||
|
assert client.put("/api/v1/ia/etat", json={"actif": False}).json()["actif"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_suggestion_proposee_jamais_appliquee(client, mail, monkeypatch):
|
||||||
|
client.put("/api/v1/ia/etat", json={"actif": True})
|
||||||
|
monkeypatch.setattr(ia, "appeler_privaite", lambda *a, **k: "Tunis")
|
||||||
|
j = client.get("/api/v1/ia/suggestion?id=m-1").json()
|
||||||
|
assert j == {"categorie": "Tunis", "source": "ia", "appliquee": False}
|
||||||
|
assert client.get("/api/v1/classements/m-1").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_reponse_hors_liste_devient_a_classer(client, mail, monkeypatch):
|
||||||
|
client.put("/api/v1/ia/etat", json={"actif": True})
|
||||||
|
monkeypatch.setattr(ia, "appeler_privaite", lambda *a, **k: "Je pense que c'est urgent")
|
||||||
|
assert client.get("/api/v1/ia/suggestion?id=m-1").json()["categorie"] == "À classer"
|
||||||
|
|
||||||
|
|
||||||
|
def test_refus_net_si_privaite_injoignable(client, mail, monkeypatch):
|
||||||
|
client.put("/api/v1/ia/etat", json={"actif": True})
|
||||||
|
def boom(*a, **k):
|
||||||
|
raise httpx.ConnectError("x")
|
||||||
|
monkeypatch.setattr(ia.httpx, "post", boom)
|
||||||
|
monkeypatch.setattr(ia, "_cle", lambda: "k")
|
||||||
|
r = client.get("/api/v1/ia/suggestion?id=m-1")
|
||||||
|
assert r.status_code == 503
|
||||||
|
|
||||||
|
|
||||||
|
def test_aucun_appel_direct_hors_privaite(client, mail, monkeypatch):
|
||||||
|
client.put("/api/v1/ia/etat", json={"actif": True})
|
||||||
|
urls = []
|
||||||
|
def faux(url, **k):
|
||||||
|
urls.append(url)
|
||||||
|
raise httpx.ConnectError("x")
|
||||||
|
monkeypatch.setattr(ia.httpx, "post", faux)
|
||||||
|
monkeypatch.setattr(ia, "_cle", lambda: "k")
|
||||||
|
client.get("/api/v1/ia/suggestion?id=m-1")
|
||||||
|
assert urls == [ia.PRIVAITE_URL] and "8401" in urls[0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_aucun_contenu_de_mail_dans_les_journaux(client, mail, monkeypatch, caplog):
|
||||||
|
client.put("/api/v1/ia/etat", json={"actif": True})
|
||||||
|
class R:
|
||||||
|
status_code = 500
|
||||||
|
monkeypatch.setattr(ia.httpx, "post", lambda *a, **k: R())
|
||||||
|
monkeypatch.setattr(ia, "_cle", lambda: "k")
|
||||||
|
with caplog.at_level("DEBUG"):
|
||||||
|
client.get("/api/v1/ia/suggestion?id=m-1")
|
||||||
|
assert "Ali Test" not in caplog.text and "12 345" not in caplog.text and "Colis" not in caplog.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_suggestion_exige_le_jeton_access():
|
||||||
|
assert TestClient(app).get("/api/v1/ia/suggestion?id=m-1").status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_cle_absente_refus_net(client, mail, monkeypatch):
|
||||||
|
client.put("/api/v1/ia/etat", json={"actif": True})
|
||||||
|
monkeypatch.setattr(ia, "PRIVAITE_KEY_PATH", "/nonexistent/k")
|
||||||
|
assert client.get("/api/v1/ia/suggestion?id=m-1").status_code == 503
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.main import app, mirror_client, MAX_CORPS_LECTURE
|
||||||
|
|
||||||
|
STATIC = Path(__file__).resolve().parent.parent / "app" / "static"
|
||||||
|
|
||||||
|
DONNEES = {
|
||||||
|
"message_id": "m-1", "dossier": "Boîte de réception",
|
||||||
|
"en_tetes": {"From": "Ali Ben Salah <ali@exemple.tn>", "To": "Nabil <nabil@exemple.tn>, autre@exemple.tn",
|
||||||
|
"cc": "copie@exemple.tn", "Subject": "Demande de prix", "Date": "Tue, 17 Nov 2026 09:41:00 +0100"},
|
||||||
|
"corps_texte": "Bonjour,\n\nMerci de confirmer.\n\nCordialement",
|
||||||
|
"pieces_jointes": [{"filename": "offre.pdf", "content_type": "application/pdf", "size": 20480}],
|
||||||
|
"taille_octets": 4096,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_lecture_exige_le_jeton():
|
||||||
|
assert TestClient(app).get("/api/v1/mail?id=m-1").status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_lecture_renvoie_les_champs_utiles(client, monkeypatch):
|
||||||
|
monkeypatch.setattr(mirror_client, "get_mail", lambda mid: {"donnees": DONNEES})
|
||||||
|
r = client.get("/api/v1/mail?id=m-1")
|
||||||
|
assert r.status_code == 200
|
||||||
|
j = r.json()
|
||||||
|
assert j["de"].startswith("Ali Ben Salah") and "autre@exemple.tn" in j["a"] and j["cc"] == "copie@exemple.tn"
|
||||||
|
assert j["objet"] == "Demande de prix" and j["corps"].startswith("Bonjour,") and j["tronque"] is False
|
||||||
|
assert j["pieces_jointes"] == [{"nom": "offre.pdf", "type": "application/pdf", "taille": 20480, "bloquee": False}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_lecture_plafonne_un_corps_tres_long(client, monkeypatch):
|
||||||
|
gros = dict(DONNEES, corps_texte="x" * (MAX_CORPS_LECTURE + 500))
|
||||||
|
monkeypatch.setattr(mirror_client, "get_mail", lambda mid: {"donnees": gros})
|
||||||
|
j = client.get("/api/v1/mail?id=m-1").json()
|
||||||
|
assert j["tronque"] is True and len(j["corps"]) == MAX_CORPS_LECTURE
|
||||||
|
|
||||||
|
|
||||||
|
def test_lecture_mail_introuvable_et_miroir_indisponible(client, monkeypatch):
|
||||||
|
monkeypatch.setattr(mirror_client, "get_mail", lambda mid: {"erreur": "inconnu"})
|
||||||
|
assert client.get("/api/v1/mail?id=zzz").status_code == 404
|
||||||
|
|
||||||
|
def panne(mid):
|
||||||
|
raise ConnectionError("miroir hors service")
|
||||||
|
monkeypatch.setattr(mirror_client, "get_mail", panne)
|
||||||
|
r = client.get("/api/v1/mail?id=m-1")
|
||||||
|
assert r.status_code == 502 and "miroir hors service" not in r.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_lecture_ne_touche_aucun_classement(client, monkeypatch, temp_db):
|
||||||
|
from app.db import list_classements
|
||||||
|
monkeypatch.setattr(mirror_client, "get_mail", lambda mid: {"donnees": DONNEES})
|
||||||
|
avant = list_classements(db_path=temp_db)
|
||||||
|
client.get("/api/v1/mail?id=m-1")
|
||||||
|
assert list_classements(db_path=temp_db) == avant
|
||||||
|
|
||||||
|
|
||||||
|
def test_panneau_de_lecture_dans_la_page():
|
||||||
|
js = (STATIC / "app.js").read_text(encoding="utf-8")
|
||||||
|
assert "function lireMail" in js and "'/mail?id='" in js
|
||||||
|
assert "noopener noreferrer" in js and "innerHTML" not in js
|
||||||
|
assert "Afficher l\\'historique de la conversation" in js
|
||||||
|
|
||||||
|
|
||||||
|
def test_style_de_lecture_colonne_lisible_et_police_locale():
|
||||||
|
css = (STATIC / "app.css").read_text(encoding="utf-8")
|
||||||
|
assert ".lect-texte" in css and "max-width: 60ch" in css and "font: 400 17px/1.65 var(--ny-police)" in css
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""Reprise automatique de la session MCP quand le miroir redémarre (404 sur l’ancienne session)."""
|
||||||
|
import json
|
||||||
|
import threading
|
||||||
|
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||||
|
|
||||||
|
from app.mirror_client import MirrorClient
|
||||||
|
|
||||||
|
|
||||||
|
class _FauxMiroir(BaseHTTPRequestHandler):
|
||||||
|
session_valide = "session-A"
|
||||||
|
appels = []
|
||||||
|
|
||||||
|
def log_message(self, *a):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def do_POST(self):
|
||||||
|
corps = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
||||||
|
sid = self.headers.get("mcp-session-id")
|
||||||
|
type(self).appels.append((corps["method"], sid))
|
||||||
|
if corps["method"] == "initialize":
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("mcp-session-id", type(self).session_valide)
|
||||||
|
self.send_header("Content-Type", "application/json")
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(json.dumps({"jsonrpc": "2.0", "id": corps["id"], "result": {}}).encode())
|
||||||
|
return
|
||||||
|
if sid != type(self).session_valide:
|
||||||
|
self.send_response(404)
|
||||||
|
self.end_headers()
|
||||||
|
return
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("Content-Type", "application/json")
|
||||||
|
self.end_headers()
|
||||||
|
texte = json.dumps({"ok": True})
|
||||||
|
self.wfile.write(json.dumps({"jsonrpc": "2.0", "id": corps["id"],
|
||||||
|
"result": {"content": [{"type": "text", "text": texte}]}}).encode())
|
||||||
|
|
||||||
|
|
||||||
|
def test_session_expiree_est_rouverte():
|
||||||
|
_FauxMiroir.appels = []
|
||||||
|
_FauxMiroir.session_valide = "session-A"
|
||||||
|
srv = HTTPServer(("127.0.0.1", 0), _FauxMiroir)
|
||||||
|
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||||
|
try:
|
||||||
|
c = MirrorClient(base_url=f"http://127.0.0.1:{srv.server_port}/mcp", token="t", cache_ttl_seconds=0)
|
||||||
|
assert c.call_tool("mirror_status", {}) == {"ok": True}
|
||||||
|
_FauxMiroir.session_valide = "session-B" # le miroir a redémarré
|
||||||
|
assert c.call_tool("mirror_status", {}) == {"ok": True}
|
||||||
|
assert c.session_id == "session-B"
|
||||||
|
finally:
|
||||||
|
srv.shutdown()
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
STATIC = Path(__file__).resolve().parent.parent / "app" / "static"
|
||||||
|
|
||||||
|
|
||||||
|
def _js():
|
||||||
|
return (STATIC / "app.js").read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def test_tri_du_jour_du_plus_recent_au_plus_ancien():
|
||||||
|
"""Les mails du jour sont triés par date décroissante (b comparé à a)."""
|
||||||
|
js = _js()
|
||||||
|
assert "S.mails = (r.mails || []).map(normaliser).sort(function (a, b) { return String(b.date).localeCompare(String(a.date)); });" in js
|
||||||
|
assert "String(a.date).localeCompare(String(b.date))" not in js
|
||||||
|
|
||||||
|
|
||||||
|
def test_repartition_du_jour_par_nombre_de_mails_decroissant():
|
||||||
|
"""Tous reste en tête, puis catégories par nombre de mails décroissant, égalité = ordre d'origine."""
|
||||||
|
js = _js()
|
||||||
|
assert "return y.n - x.n || x.rang - y.rang;" in js
|
||||||
|
assert js.index("nom: 'Tous'") < js.index("y.n - x.n")
|
||||||
|
|
||||||
|
|
||||||
|
def test_groupes_categories_meme_classement():
|
||||||
|
js = _js()
|
||||||
|
assert "(cc[y.c.nom] || 0) - (cc[x.c.nom] || 0) || x.rang - y.rang" in js
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from app.classifier import classify_batch, classify_mail
|
||||||
|
from app.db import save_classement_manuel, get_classement, add_regle
|
||||||
|
from app.mirror_client import MirrorClient
|
||||||
|
|
||||||
|
STATIC = Path(__file__).resolve().parent.parent / "app" / "static"
|
||||||
|
|
||||||
|
|
||||||
|
def _mail(i, objet="Bonjour", tags=None, exp="a@b.tn"):
|
||||||
|
return {"message_id": "m%d" % i, "date": "2026-11-17T09:%02d:00+01:00" % i, "expediteur": exp,
|
||||||
|
"objet": objet, "etiquettes": tags or []}
|
||||||
|
|
||||||
|
|
||||||
|
def test_lot_equivalent_au_classement_mail_par_mail(temp_db):
|
||||||
|
mails = [_mail(1, tags=["tunis"]), _mail(2, objet=""), _mail(3), _mail(4, tags=["sans_objet"])]
|
||||||
|
lot = classify_batch(mails, db_path=temp_db)
|
||||||
|
seuls = [classify_mail(m, db_path=temp_db) for m in mails]
|
||||||
|
assert [(c["message_id"], c["categorie"], c["source"]) for c in lot] == [(c["message_id"], c["categorie"], c["source"]) for c in seuls]
|
||||||
|
|
||||||
|
|
||||||
|
def test_lot_sans_ecriture_si_inchange(temp_db):
|
||||||
|
mails = [_mail(i) for i in range(1, 6)]
|
||||||
|
premier = classify_batch(mails, db_path=temp_db)
|
||||||
|
time.sleep(1.1)
|
||||||
|
second = classify_batch(mails, db_path=temp_db)
|
||||||
|
assert [c["horodatage"] for c in premier] == [c["horodatage"] for c in second]
|
||||||
|
|
||||||
|
|
||||||
|
def test_lot_ne_touche_pas_au_classement_manuel(temp_db):
|
||||||
|
classify_batch([_mail(1, tags=["tunis"])], db_path=temp_db)
|
||||||
|
save_classement_manuel("m1", "CI", expediteur="a@b.tn", objet="Bonjour", date_mail="2026-11-17T09:01:00+01:00", db_path=temp_db)
|
||||||
|
res = classify_batch([_mail(1, tags=["tunis"])], db_path=temp_db)
|
||||||
|
assert res[0]["categorie"] == "CI" and res[0]["source"] == "manuel"
|
||||||
|
assert get_classement("m1", temp_db)["categorie"] == "CI"
|
||||||
|
|
||||||
|
|
||||||
|
def test_lot_conserve_traite_quand_la_regle_change(temp_db):
|
||||||
|
classify_batch([_mail(1)], db_path=temp_db)
|
||||||
|
from app.db import get_connection
|
||||||
|
with get_connection(temp_db) as conn:
|
||||||
|
conn.execute("UPDATE classements SET traite = 1 WHERE message_id = 'm1'")
|
||||||
|
add_regle(categorie="CI", expediteur="a@b.tn", mot_cle=None, statut="active", db_path=temp_db)
|
||||||
|
res = classify_batch([_mail(1)], db_path=temp_db)
|
||||||
|
assert res[0]["categorie"] == "CI" and res[0]["traite"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_lot_ignore_un_mail_sans_identifiant(temp_db):
|
||||||
|
assert classify_batch([{"expediteur": "x"}], db_path=temp_db) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_lecture_miroir_une_seule_cle_et_rafraichissement_force(monkeypatch):
|
||||||
|
appels = []
|
||||||
|
c = MirrorClient(base_url="http://x/mcp", token="t")
|
||||||
|
monkeypatch.setattr(c, "call_tool", lambda nom, args=None, use_cache=True, force=False: appels.append((nom, dict(args or {}), force)) or [])
|
||||||
|
c.get_latest_mails(folder="*", n=200)
|
||||||
|
c.get_latest_mails(folder="*", n=400)
|
||||||
|
c.rafraichir_derniers()
|
||||||
|
assert appels[0][1] == appels[1][1] == appels[2][1]
|
||||||
|
assert appels[0][1]["n"] == 100 and appels[2][2] is True and appels[0][2] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_onglet_tri_rouvert_sans_rechargement_sous_30_secondes():
|
||||||
|
js = (STATIC / "app.js").read_text(encoding="utf-8")
|
||||||
|
assert "S.chargeJour === S.jour && Date.now() - S.chargeA < 30000" in js
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import base64
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.main import app, mirror_client, MAX_PIECE, _nom_sur
|
||||||
|
|
||||||
|
STATIC = Path(__file__).resolve().parent.parent / "app" / "static"
|
||||||
|
|
||||||
|
|
||||||
|
def fausse(contenu=b"%PDF-1.4 test", nom="offre.pdf", taille=None):
|
||||||
|
return lambda mid, f: {"donnees": {"message_id": mid, "nom": nom, "type_mime": "application/pdf",
|
||||||
|
"taille": taille if taille is not None else len(contenu),
|
||||||
|
"encodage": "base64", "contenu_base64": base64.b64encode(contenu).decode()}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_piece_exige_le_jeton():
|
||||||
|
assert TestClient(app).get("/api/v1/mail/piece?id=m-1&nom=offre.pdf").status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_piece_telechargee_toujours_en_piece_jointe(client, monkeypatch):
|
||||||
|
monkeypatch.setattr(mirror_client, "get_attachment", fausse())
|
||||||
|
r = client.get("/api/v1/mail/piece?id=m-1&nom=offre.pdf")
|
||||||
|
assert r.status_code == 200 and r.content == b"%PDF-1.4 test"
|
||||||
|
assert r.headers["content-type"].startswith("application/octet-stream")
|
||||||
|
assert r.headers["content-disposition"].startswith("attachment;")
|
||||||
|
assert r.headers["x-content-type-options"] == "nosniff" and r.headers["cache-control"] == "no-store"
|
||||||
|
|
||||||
|
|
||||||
|
def test_piece_nom_accentue_dans_l_entete(client, monkeypatch):
|
||||||
|
monkeypatch.setattr(mirror_client, "get_attachment", fausse(nom="Offre financière.pdf"))
|
||||||
|
r = client.get("/api/v1/mail/piece", params={"id": "m-1", "nom": "Offre financière.pdf"})
|
||||||
|
assert "filename*=UTF-8''Offre%20financi%C3%A8re.pdf" in r.headers["content-disposition"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("nom", ["setup.exe", "page.HTML", "macro.xlsm", "script.js", "image.svg", "a.b.bat"])
|
||||||
|
def test_extensions_actives_refusees_sans_appel_miroir(client, monkeypatch, nom):
|
||||||
|
def boom(*a): raise AssertionError("le miroir ne doit pas etre appele")
|
||||||
|
monkeypatch.setattr(mirror_client, "get_attachment", boom)
|
||||||
|
assert client.get("/api/v1/mail/piece", params={"id": "m-1", "nom": nom}).status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_piece_trop_volumineuse(client, monkeypatch):
|
||||||
|
monkeypatch.setattr(mirror_client, "get_attachment", fausse(taille=MAX_PIECE + 1))
|
||||||
|
assert client.get("/api/v1/mail/piece?id=m-1&nom=gros.pdf").status_code == 413
|
||||||
|
|
||||||
|
|
||||||
|
def test_piece_introuvable_et_miroir_indisponible(client, monkeypatch):
|
||||||
|
monkeypatch.setattr(mirror_client, "get_attachment", lambda mid, f: {"donnees": {}})
|
||||||
|
assert client.get("/api/v1/mail/piece?id=m-1&nom=x.pdf").status_code == 404
|
||||||
|
def casse(mid, f): raise ConnectionError("x")
|
||||||
|
monkeypatch.setattr(mirror_client, "get_attachment", casse)
|
||||||
|
assert client.get("/api/v1/mail/piece?id=m-1&nom=x.pdf").status_code == 502
|
||||||
|
|
||||||
|
|
||||||
|
def test_nom_nettoye():
|
||||||
|
assert _nom_sur('../../etc/pass"wd.pdf') == "pass_wd.pdf"
|
||||||
|
assert _nom_sur("..") == "piece-jointe"
|
||||||
|
|
||||||
|
|
||||||
|
def test_indicateur_bloquee_dans_la_lecture(client, monkeypatch):
|
||||||
|
d = {"message_id": "m-1", "en_tetes": {}, "corps_texte": "x",
|
||||||
|
"pieces_jointes": [{"filename": "a.exe", "content_type": "application/x", "size": 5},
|
||||||
|
{"filename": "b.pdf", "content_type": "application/pdf", "size": 5}]}
|
||||||
|
monkeypatch.setattr(mirror_client, "get_mail", lambda mid: {"donnees": d})
|
||||||
|
pj = client.get("/api/v1/mail?id=m-1").json()["pieces_jointes"]
|
||||||
|
assert [p["bloquee"] for p in pj] == [True, False]
|
||||||
|
|
||||||
|
|
||||||
|
def test_interface_telechargement_sans_innerhtml():
|
||||||
|
js = (STATIC / "app.js").read_text(encoding="utf-8")
|
||||||
|
assert "telechargerPiece" in js and "/mail/piece?id=" in js and "innerHTML" not in js
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import io
|
||||||
|
import zipfile
|
||||||
|
import pytest
|
||||||
|
from app import piece_ia as p
|
||||||
|
|
||||||
|
|
||||||
|
def _docx(txt):
|
||||||
|
b = io.BytesIO()
|
||||||
|
with zipfile.ZipFile(b, "w") as z:
|
||||||
|
z.writestr("word/document.xml", '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>' + txt + "</w:t></w:r></w:p></w:body></w:document>")
|
||||||
|
return b.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def test_texte_et_docx():
|
||||||
|
long = "Bon de commande numero 4500123 pour la livraison de dix ordinateurs avant le 30/11/2026."
|
||||||
|
assert "4500123" in p.extraire_texte("a.txt", long.encode())
|
||||||
|
assert "4500123" in p.extraire_texte("a.docx", _docx(long))
|
||||||
|
|
||||||
|
|
||||||
|
def test_type_inconnu_et_vide():
|
||||||
|
with pytest.raises(p.SansTexte):
|
||||||
|
p.extraire_texte("a.exe", b"x" * 100)
|
||||||
|
with pytest.raises(p.SansTexte):
|
||||||
|
p.extraire_texte("a.txt", b"court")
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.main import app, mirror_client, _dossier_court
|
||||||
|
|
||||||
|
STATIC = Path(__file__).resolve().parent.parent / "app" / "static"
|
||||||
|
|
||||||
|
|
||||||
|
def brut(i, jour, sujet="Offre", dossier="Boîte de réception", pj=False):
|
||||||
|
return {"message_id": f"m{i}", "date_reception": f"2026-11-{jour:02d}T09:00:00+01:00", "expediteur": "Ali <ali@exemple.tn>",
|
||||||
|
"sujet": sujet, "dossier": dossier, "has_attachments": pj, "etiquettes": ["sfax"]}
|
||||||
|
|
||||||
|
|
||||||
|
def test_recherche_exige_le_jeton():
|
||||||
|
assert TestClient(app).get("/api/v1/recherche?q=offre").status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("q", ["", "a", " a "])
|
||||||
|
def test_recherche_trop_courte(client, q):
|
||||||
|
assert client.get("/api/v1/recherche", params={"q": q}).status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_recherche_resultats_tries_par_date(client, monkeypatch):
|
||||||
|
vus = {}
|
||||||
|
def faux(q, since=None, until=None, n=100):
|
||||||
|
vus.update(q=q, since=since, until=until, n=n)
|
||||||
|
return [brut(1, 10), brut(2, 15, pj=True), brut(3, 12, dossier="Boîte de réception-00 2026-🌍 DR Zone Sud-📍 Kebili")]
|
||||||
|
monkeypatch.setattr(mirror_client, "rechercher", faux)
|
||||||
|
j = client.get("/api/v1/recherche", params={"q": " offre\x00 prix ", "depuis": "2026-11-01", "jusqu_a": "2026-11-30"}).json()
|
||||||
|
assert vus == {"q": "offre prix", "since": "2026-11-01", "until": "2026-12-01", "n": 100}
|
||||||
|
assert [r["message_id"] for r in j["resultats"]] == ["m2", "m3", "m1"]
|
||||||
|
assert j["resultats"][0]["pj"] is True and j["resultats"][1]["dossier"] == "DR Zone Sud-📍 Kebili"
|
||||||
|
assert j["total"] == 3 and j["plafond"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_recherche_plafond(client, monkeypatch):
|
||||||
|
monkeypatch.setattr(mirror_client, "rechercher", lambda q, since=None, until=None, n=100: [brut(i, 10) for i in range(5)])
|
||||||
|
assert client.get("/api/v1/recherche?q=offre&n=5").json()["plafond"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_recherche_dates_invalides_et_miroir_indisponible(client, monkeypatch):
|
||||||
|
assert client.get("/api/v1/recherche?q=offre&depuis=hier").status_code == 422
|
||||||
|
assert client.get("/api/v1/recherche?q=offre&jusqu_a=2026-13-45").status_code == 422
|
||||||
|
def casse(*a, **k): raise ConnectionError("x")
|
||||||
|
monkeypatch.setattr(mirror_client, "rechercher", casse)
|
||||||
|
assert client.get("/api/v1/recherche?q=offre").status_code == 502
|
||||||
|
|
||||||
|
|
||||||
|
def test_dossier_court():
|
||||||
|
assert _dossier_court("Boîte de réception") == "Boîte de réception"
|
||||||
|
assert _dossier_court("Boîte de réception-00 2026-🌍 DR Zone Sud-📍 Kebili") == "DR Zone Sud-📍 Kebili"
|
||||||
|
assert _dossier_court("Messages envoyés") == "Messages envoyés"
|
||||||
|
assert _dossier_court("Boîte de réception-00 2026-📎FB") == "FB"
|
||||||
|
|
||||||
|
|
||||||
|
def test_interface_recherche():
|
||||||
|
js = (STATIC / "app.js").read_text(encoding="utf-8")
|
||||||
|
assert "vueRecherche" in js and "lancerRecherche" in js and "innerHTML" not in js
|
||||||
|
assert "['recherche', 'Recherche', true]" in js and "['pj'," not in js
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import pytest
|
||||||
|
from app import classifier as c
|
||||||
|
from app.db import add_regle, get_classement
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.regles_off
|
||||||
|
|
||||||
|
|
||||||
|
def _mail(mid="m1", objet="Course Tunis demain", exp="collegue@tt.tn"):
|
||||||
|
return {"message_id": mid, "objet": objet, "expediteur": exp, "apercu": "", "etiquettes": ["tunis"]}
|
||||||
|
|
||||||
|
|
||||||
|
def test_defaut_eteint(temp_db):
|
||||||
|
assert c.regles_auto_actives(temp_db) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_aucune_regle_ne_classe(temp_db):
|
||||||
|
add_regle(categorie="Tunis", expediteur="collegue@tt.tn", mot_cle="tunis", statut="active", db_path=temp_db)
|
||||||
|
r = c.classify_mail(_mail(), db_path=temp_db)
|
||||||
|
assert r["categorie"] == "À classer"
|
||||||
|
|
||||||
|
|
||||||
|
def test_reactivation_reversible(temp_db):
|
||||||
|
add_regle(categorie="Tunis", expediteur=None, mot_cle="tunis", statut="active", db_path=temp_db)
|
||||||
|
c.regler_regles_auto(True, temp_db)
|
||||||
|
assert c.classify_mail(_mail("m2"), db_path=temp_db)["categorie"] == "Tunis"
|
||||||
|
c.regler_regles_auto(False, temp_db)
|
||||||
|
assert c.classify_mail(_mail("m3"), db_path=temp_db)["categorie"] == "À classer"
|
||||||
|
|
||||||
|
|
||||||
|
def test_correction_manuelle_ne_propose_pas_de_regle(temp_db):
|
||||||
|
cl, regle = c.manual_classify_and_propose("m4", "Tunis", {"expediteur": "a@b.tn", "objet": "Course Tunis"}, db_path=temp_db)
|
||||||
|
assert cl["source"] == "manuel" and regle is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_manuel_jamais_ecrase(temp_db):
|
||||||
|
c.manual_classify_and_propose("m5", "Pb PO", {"expediteur": "a@b.tn", "objet": "x"}, db_path=temp_db)
|
||||||
|
assert c.classify_mail(_mail("m5"), db_path=temp_db)["categorie"] == "Pb PO"
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
from app import sauvegarde as s
|
||||||
|
from app.db import init_db
|
||||||
|
|
||||||
|
|
||||||
|
def _base(tmp_path):
|
||||||
|
p = str(tmp_path / "courrier.db")
|
||||||
|
init_db(p)
|
||||||
|
return p
|
||||||
|
|
||||||
|
|
||||||
|
def test_une_par_jour_et_rotation(tmp_path):
|
||||||
|
db = _base(tmp_path)
|
||||||
|
assert s.sauvegarder(db) is not None
|
||||||
|
assert s.sauvegarder(db) is None
|
||||||
|
d = s._dossier(db)
|
||||||
|
for i in range(20):
|
||||||
|
open(os.path.join(d, "courrier-2020-01-%02d.db" % (i + 1)), "w").write("x")
|
||||||
|
s.sauvegarder(db, force=True)
|
||||||
|
assert len(s.liste(db)) == s.CONSERVES
|
||||||
|
assert s.liste(db)[0]["jour"] >= "2026"
|
||||||
|
|
||||||
|
|
||||||
|
def test_copie_lisible(tmp_path):
|
||||||
|
db = _base(tmp_path)
|
||||||
|
n = s.sauvegarder(db)
|
||||||
|
c = sqlite3.connect(os.path.join(s._dossier(db), n))
|
||||||
|
assert c.execute("select count(*) from sqlite_master").fetchone()[0] > 0
|
||||||
|
c.close()
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.main import app, mirror_client
|
||||||
|
from app.suivi import calculer_suivi, sujet_normalise
|
||||||
|
|
||||||
|
STATIC = Path(__file__).resolve().parent.parent / "app" / "static"
|
||||||
|
MOI = "Nabil.Derouiche <Nabil.Derouiche@tunisietelecom.tn>"
|
||||||
|
AUTRE = "Ali Ben Salah <ali@exemple.tn>"
|
||||||
|
NOW = datetime(2026, 11, 18, 10, 0, tzinfo=timezone(timedelta(hours=1)))
|
||||||
|
|
||||||
|
|
||||||
|
def mail(i, jour, objet, exp, dest, hh="09:00:00"):
|
||||||
|
return {"message_id": f"m{i}", "date": f"2026-11-{jour:02d}T{hh}+01:00", "objet": objet, "expediteur": exp, "destinataires": dest, "etiquettes": []}
|
||||||
|
|
||||||
|
|
||||||
|
def etats(mails, clos=None):
|
||||||
|
return {i["cle"]: i for i in calculer_suivi(mails, "nabil.derouiche@", NOW, clos or {})}
|
||||||
|
|
||||||
|
|
||||||
|
def test_sujet_normalise():
|
||||||
|
assert sujet_normalise("RE: TR: Fwd : Demande de prix ") == "demande de prix"
|
||||||
|
assert sujet_normalise("") == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_en_attente_et_relance():
|
||||||
|
e = etats([mail(1, 12, "Demande de prix", MOI, AUTRE)])
|
||||||
|
i = e["demande de prix"]
|
||||||
|
assert i["etat"] == "attente" and i["jours"] == 6 and i["relancer"] is True and i["avec"] == "Ali Ben Salah"
|
||||||
|
e = etats([mail(1, 17, "Demande de prix", MOI, AUTRE)])
|
||||||
|
assert e["demande de prix"]["relancer"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_reponse_recue_et_a_repondre():
|
||||||
|
fil = [mail(1, 12, "Offre", MOI, AUTRE), mail(2, 14, "RE: Offre", AUTRE, MOI)]
|
||||||
|
assert etats(fil)["offre"]["etat"] == "reponse"
|
||||||
|
assert etats([mail(3, 15, "Question", AUTRE, MOI)])["question"]["etat"] == "a_repondre"
|
||||||
|
|
||||||
|
|
||||||
|
def test_copie_seulement_ignore():
|
||||||
|
assert etats([mail(4, 15, "Info", AUTRE, "autre@exemple.tn, copie@exemple.tn")]) == {}
|
||||||
|
|
||||||
|
|
||||||
|
def test_ma_reponse_ferme_la_demande_recue():
|
||||||
|
fil = [mail(5, 15, "Question", AUTRE, MOI), mail(6, 16, "RE: Question", MOI, AUTRE)]
|
||||||
|
assert etats(fil)["question"]["etat"] == "attente"
|
||||||
|
|
||||||
|
|
||||||
|
def test_clos_tient_jusqu_au_nouveau_message():
|
||||||
|
fil = [mail(7, 12, "Sujet", MOI, AUTRE)]
|
||||||
|
assert etats(fil, {"sujet": "m7"})["sujet"]["clos"] is True
|
||||||
|
fil.append(mail(8, 16, "RE: Sujet", AUTRE, MOI))
|
||||||
|
assert etats(fil, {"sujet": "m7"})["sujet"]["clos"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_sujet_vide_ignore_et_ordre():
|
||||||
|
fil = [mail(9, 10, "", MOI, AUTRE), mail(10, 16, "B", MOI, AUTRE), mail(11, 11, "A", MOI, AUTRE), mail(12, 15, "C", AUTRE, MOI), mail(13, 16, "D", AUTRE, MOI)]
|
||||||
|
sortie = calculer_suivi(fil, "nabil.derouiche@", NOW, {})
|
||||||
|
assert [i["sujet"] for i in sortie] == ["A", "B", "D", "C"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_suivi_exige_le_jeton():
|
||||||
|
assert TestClient(app).get("/api/v1/suivi").status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_endpoint_suivi_et_cloture(client, monkeypatch):
|
||||||
|
jour = datetime.now(timezone(timedelta(hours=1))) - timedelta(days=5)
|
||||||
|
iso = jour.strftime("%Y-%m-%dT09:00:00+01:00")
|
||||||
|
envoye = {"message_id": "e1", "date": iso, "objet": "Besoin cables", "expediteur": MOI, "destinataires": AUTRE, "etiquettes": []}
|
||||||
|
monkeypatch.setattr(mirror_client, "get_mails_since", lambda debut, max_items=800: [])
|
||||||
|
monkeypatch.setattr(mirror_client, "get_sent_mails", lambda n=100: [envoye])
|
||||||
|
j = client.get("/api/v1/suivi?jours=14").json()
|
||||||
|
assert j["compte"] == {"attente": 1, "reponse": 0, "a_repondre": 0, "clos": 0}
|
||||||
|
assert j["items"][0]["relancer"] is True
|
||||||
|
assert client.post("/api/v1/suivi/clore", json={"cle": "besoin cables", "dernier_id": "e1"}).status_code == 200
|
||||||
|
j = client.get("/api/v1/suivi?jours=14").json()
|
||||||
|
assert j["compte"]["attente"] == 0 and j["compte"]["clos"] == 1 and j["items"][0]["clos"] is True
|
||||||
|
client.post("/api/v1/suivi/rouvrir", json={"cle": "besoin cables"})
|
||||||
|
assert client.get("/api/v1/suivi?jours=14").json()["compte"]["attente"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_suivi_miroir_indisponible(client, monkeypatch):
|
||||||
|
def casse(*a, **k): raise ConnectionError("x")
|
||||||
|
monkeypatch.setattr(mirror_client, "get_mails_since", casse)
|
||||||
|
assert client.get("/api/v1/suivi").status_code == 502
|
||||||
|
|
||||||
|
|
||||||
|
def test_interface_suivi():
|
||||||
|
js = (STATIC / "app.js").read_text(encoding="utf-8")
|
||||||
|
assert "vueSuivi" in js and "chargerSuivi" in js and "innerHTML" not in js
|
||||||
|
|
||||||
|
|
||||||
|
def test_envois_automatiques_et_a_soi_meme_ignores():
|
||||||
|
fil = [mail(20, 15, "Rappel perso", MOI, MOI), mail(21, 15, "Alerte", "noreply@exemple.tn", MOI), mail(22, 15, "Vrai besoin", MOI, AUTRE)]
|
||||||
|
assert set(etats(fil)) == {"vrai besoin"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_fraicheur_des_messages_envoyes(client, monkeypatch):
|
||||||
|
ancien = {"message_id": "e0", "date": "2026-11-01T09:00:00+01:00", "objet": "Vieux", "expediteur": MOI, "destinataires": AUTRE, "etiquettes": []}
|
||||||
|
monkeypatch.setattr(mirror_client, "get_mails_since", lambda debut, max_items=800: [])
|
||||||
|
monkeypatch.setattr(mirror_client, "get_sent_mails", lambda n=100: [ancien])
|
||||||
|
j = client.get("/api/v1/suivi").json()
|
||||||
|
assert j["envoyes_a_jour"] is False and j["envoyes_jusqu_au"] == "2026-11-01"
|
||||||
@@ -67,3 +67,17 @@ def test_renommage_et_suppression_en_cascade(client):
|
|||||||
def test_renommage_doublon_refuse(client):
|
def test_renommage_doublon_refuse(client):
|
||||||
cid = client.post("/api/v1/categories", json={"name": "Zeta"}).json()["id"]
|
cid = client.post("/api/v1/categories", json={"name": "Zeta"}).json()["id"]
|
||||||
assert client.put(f"/api/v1/categories/{cid}", json={"name": "Tunis"}).status_code == 400
|
assert client.put(f"/api/v1/categories/{cid}", json={"name": "Tunis"}).status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_barre_laterale_reductible_et_tiroir():
|
||||||
|
"""tt-2026-11-079 : bouton masquer/afficher la barre latérale (portable, tablette) et tiroir sur téléphone."""
|
||||||
|
html = (STATIC / "index.html").read_text(encoding="utf-8")
|
||||||
|
css = (STATIC / "app.css").read_text(encoding="utf-8")
|
||||||
|
js = (STATIC / "app.js").read_text(encoding="utf-8")
|
||||||
|
assert html.count("<nav") == 1 and "nav-mobile" not in html + css + js
|
||||||
|
for ident in ["nav-bascule", "nav-ouvrir", "nav-voile", "nav-corps", "barre-mobile", "barre-titre"]:
|
||||||
|
assert f'id="{ident}"' in html, ident
|
||||||
|
assert 'aria-expanded="true"' in html and 'aria-label="Ouvrir le menu"' in html
|
||||||
|
assert ".nav-reduite" in css and ".nav-ouverte" in css and "min-width: 761px" in css
|
||||||
|
assert "courrier.nav" in js and "matchMedia('(max-width: 760px)')" in js and "'Escape'" in js
|
||||||
|
assert "panneau:" in js
|
||||||
Reference in new issue
Block a user