diff --git a/app/classifier.py b/app/classifier.py index 55616ce..52cf302 100644 --- a/app/classifier.py +++ b/app/classifier.py @@ -38,6 +38,10 @@ def match_mail_to_rules(mail: Dict[str, Any], rules: List[Dict[str, Any]]) -> st mail_snip = (mail.get("apercu") or mail.get("snippet") or "").lower() mail_tags = [t.strip().lower() for t in (mail.get("etiquettes") or mail.get("tags") or [])] + # OBJET-VIDE-060 : règle de départ « objet vide » -> Sans objet (le miroir fournit « sujet » vide) + if not mail_obj.strip(): + return "Sans objet" + for rule in rules: if rule.get("statut") != "active": continue diff --git a/app/db.py b/app/db.py index a7ad6bd..db0177e 100644 --- a/app/db.py +++ b/app/db.py @@ -127,12 +127,16 @@ def update_category(cat_id: int, new_name: str, db_path: Optional[str] = None) - conn = get_connection(db_path) try: with conn: + ancien = conn.execute("SELECT name FROM categories WHERE id = ?", (cat_id,)).fetchone() cursor = conn.execute( "UPDATE categories SET name = ? WHERE id = ?", (new_name, cat_id) ) if cursor.rowcount == 0: return None + if ancien and ancien["name"] != new_name: # CASCADE-060 + conn.execute("UPDATE classements 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() return dict(row) if row else None finally: @@ -142,7 +146,11 @@ def delete_category(cat_id: int, db_path: Optional[str] = None) -> bool: conn = get_connection(db_path) try: with conn: + ancien = conn.execute("SELECT name FROM categories WHERE id = ?", (cat_id,)).fetchone() cursor = conn.execute("DELETE FROM categories WHERE id = ?", (cat_id,)) + if cursor.rowcount > 0 and ancien: # CASCADE-060 + conn.execute("UPDATE classements SET categorie = 'À classer' WHERE categorie = ?", (ancien["name"],)) + conn.execute("DELETE FROM regles WHERE categorie = ?", (ancien["name"],)) return cursor.rowcount > 0 finally: conn.close() diff --git a/app/mirror_client.py b/app/mirror_client.py index e7a0350..e3ed9d3 100644 --- a/app/mirror_client.py +++ b/app/mirror_client.py @@ -210,7 +210,7 @@ class MirrorClient: "message_id": mid, "date": d_mail, "expediteur": m.get("from") or m.get("expediteur") or "", - "objet": m.get("subject") or m.get("objet") 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 "" } diff --git a/tests/test_mirror_champs.py b/tests/test_mirror_champs.py new file mode 100644 index 0000000..eb010c8 --- /dev/null +++ b/tests/test_mirror_champs.py @@ -0,0 +1,14 @@ +from app.mirror_client import MirrorClient + + +def test_sujet_reel_du_miroir_est_lu(monkeypatch): + """Le miroir expose le sujet sous la clé « sujet » (régression : objets tous vides en production).""" + brut = [{"message_id": "m1", "date_reception": "2026-11-17T09:00:00+01:00", "expediteur": "\"A\" ", + "sujet": "RE: AO 55/2026 Modernisation", "titre": "RE: AO 55/2026 Modernisation", "etiquettes": ["sfax"]}, + {"message_id": "m2", "date_reception": "2026-11-17T10:00:00+01:00", "expediteur": "B ", "sujet": "", "etiquettes": []}] + c = MirrorClient() + monkeypatch.setattr(c, "get_latest_mails", lambda folder="*", n=20, inclure_exclus=False: brut) + mails = c.get_mails_for_day("2026-11-17") + assert mails[0]["objet"] == "RE: AO 55/2026 Modernisation" + assert mails[1]["objet"] == "" + assert mails[0]["date"].startswith("2026-11-17") diff --git a/tests/test_objet_vide.py b/tests/test_objet_vide.py new file mode 100644 index 0000000..c7ca58d --- /dev/null +++ b/tests/test_objet_vide.py @@ -0,0 +1,10 @@ +from app.classifier import match_mail_to_rules + + +def test_objet_vide_va_dans_sans_objet(): + assert match_mail_to_rules({"expediteur": "x@y.tn", "objet": "", "etiquettes": []}, []) == "Sans objet" + assert match_mail_to_rules({"expediteur": "x@y.tn", "objet": " ", "etiquettes": ["sfax"]}, []) == "Sans objet" + + +def test_objet_renseigne_reste_a_classer_sans_regle(): + assert match_mail_to_rules({"expediteur": "x@y.tn", "objet": "AO 55/2026", "etiquettes": []}, []) == "À classer" diff --git a/tests/test_ui.py b/tests/test_ui.py new file mode 100644 index 0000000..8c0f478 --- /dev/null +++ b/tests/test_ui.py @@ -0,0 +1,69 @@ +import re +from pathlib import Path +from fastapi.testclient import TestClient +from app.main import app + +STATIC = Path(__file__).resolve().parent.parent / "app" / "static" + + +def test_page_servie_sans_jeton(): + """L'HTML est servi sans jeton (Cloudflare Access protège l'hôte) ; /api reste protégé.""" + c = TestClient(app) + r = c.get("/") + assert r.status_code == 200 + assert "Courrier" in r.text + assert 'lang="fr"' in r.text + assert r.headers["cache-control"] == "no-store" + assert "default-src 'self'" in r.headers["content-security-policy"] + assert c.get("/api/v1/categories").status_code in (401, 503) + + +def test_statiques_et_polices_locales(): + c = TestClient(app) + for chemin, type_ in [("/static/app.js", "javascript"), ("/static/app.css", "css"), ("/static/nyora.css", "css"), ("/static/fonts/next-400.woff2", "font")]: + r = c.get(chemin) + assert r.status_code == 200, chemin + assert type_ in r.headers["content-type"] or type_ == "font" + assert c.get("/static/../main.py").status_code in (400, 404) + + +def test_aucune_requete_externe_ni_couleur_en_dur(): + """Aucune URL externe ; aucune couleur hexadécimale hors du fichier de jetons.""" + for nom in ["index.html", "app.css", "app.js", "fonts.css", "nyora.css"]: + t = (STATIC / nom).read_text(encoding="utf-8") + urls = [u for u in re.findall(r"https?://[^\s\"')]+", t) if "www.w3.org" not in u] + assert not urls, (nom, urls) + for nom in ["app.css", "app.js", "fonts.css"]: + t = (STATIC / nom).read_text(encoding="utf-8") + assert not re.search(r"#[0-9A-Fa-f]{3,8}\b", t), nom + assert not re.search(r"\brgba?\(", t), nom + + +def test_aucun_innerhtml(): + assert "innerHTML" not in (STATIC / "app.js").read_text(encoding="utf-8") + + +def test_a_classer_protegee(client): + cats = client.get("/api/v1/categories").json()["categories"] + ac = [c for c in cats if c["name"] == "À classer"][0] + assert client.put(f"/api/v1/categories/{ac['id']}", json={"name": "Autre"}).status_code == 400 + assert client.delete(f"/api/v1/categories/{ac['id']}").status_code == 400 + + +def test_renommage_et_suppression_en_cascade(client): + from app.db import get_connection + cid = client.post("/api/v1/categories", json={"name": "Projet X"}).json()["id"] + client.post("/api/v1/regles", json={"categorie": "Projet X", "expediteur": "a@b.tn", "statut": "active"}) + client.post("/api/v1/classements/m1", json={"categorie": "Projet X", "mail_info": {"expediteur": "a@b.tn", "objet": "o", "date": "2026-11-17T09:00:00+01:00"}}) + assert client.put(f"/api/v1/categories/{cid}", json={"name": "Projet Y"}).status_code == 200 + assert client.get("/api/v1/classements/m1").json()["categorie"] == "Projet Y" + assert any(r["categorie"] == "Projet Y" for r in client.get("/api/v1/regles").json()["regles"]) + assert client.delete(f"/api/v1/categories/{cid}").status_code == 200 + assert client.get("/api/v1/classements/m1").json()["categorie"] == "À classer" + assert not any(r["categorie"] == "Projet Y" for r in client.get("/api/v1/regles").json()["regles"]) + assert client.put(f"/api/v1/categories/{cid}", json={"name": "Tunis"}).status_code in (400, 404) + + +def test_renommage_doublon_refuse(client): + 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