feat: onglet À suivre (marqueur manuel sans limite de date, groupes par catégorie, retrait réversible) et couleur propre à chaque catégorie

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XGaEeUbVSdKNfpFRgWfCXa
This commit is contained in:
Claude committed 2026-11-19 23:51:57 +01:00
1 parent 4c9f0c55b5
commit a4e7ed1f00
9 files changed
+556 -17

No files matched your search

+8
View File
@@ -26,3 +26,11 @@ 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/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.
## À 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.
+129
View File
@@ -0,0 +1,129 @@
"""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()
+47 -5
View File
@@ -13,6 +13,35 @@ def get_connection(db_path: Optional[str] = None) -> sqlite3.Connection:
conn.execute("PRAGMA foreign_keys=ON")
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:
conn = get_connection(db_path)
try:
@@ -56,6 +85,10 @@ def init_db(db_path: Optional[str] = None) -> None:
if "etiquettes" not in cols:
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()
# Initialisation idempotente des catégories par défaut
@@ -65,6 +98,8 @@ def init_db(db_path: Optional[str] = None) -> None:
(cat, now)
)
_attribuer_couleurs(conn)
# Initialisation idempotente des règles de départ
for rule in DEFAULT_RULES:
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]]:
conn = get_connection(db_path)
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]
finally:
conn.close()
@@ -111,12 +146,13 @@ def add_category(name: str, db_path: Optional[str] = None) -> Dict[str, Any]:
try:
now = get_tunis_now_iso()
with conn:
couleur = _couleur_libre(conn)
cursor = conn.execute(
"INSERT INTO categories (name, created_at) VALUES (?, ?)",
(name, now)
"INSERT INTO categories (name, couleur, created_at) VALUES (?, ?, ?)",
(name, couleur, now)
)
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:
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
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()
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
finally:
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
conn.execute("UPDATE classements SET categorie = 'À classer' 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
finally:
conn.close()
+44
View File
@@ -44,6 +44,7 @@ from app.classifier import (
confirm_and_apply_rule,
reclassify_today_mails
)
from app import asuivre
from app.mirror_client import MirrorClient
from app.ia import creer_routeur
from app.auth import verify_cf_access_jwt
@@ -486,6 +487,49 @@ def supprimer_course(course_id: int):
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/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 ---
@api.get("/classements")
def get_classements(
+44 -1
View File
@@ -76,14 +76,18 @@ h1, h2, h3, p { margin: 0; }
.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.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.tous { background: var(--ny-encre-2); }
.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.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.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[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); }
/* Bandeau de règle et notification */
@@ -94,7 +98,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); }
/* 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); }
.ligne { min-height: 64px; border-bottom: 1px solid var(--ny-trait); }
.ligne:last-child { border-bottom: none; }
@@ -299,3 +303,42 @@ h1, h2, h3, p { margin: 0; }
.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) {
.nav-mobile .nav-btn { position: relative; }
.nav-mobile .nav-n { position: absolute; top: 2px; left: calc(50% + 8px); margin: 0; }
.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; }
}
+148 -9
View File
@@ -12,18 +12,19 @@
recherche: 'm21 21-4.34-4.34|M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16',
courses: 'M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z|M12 13a3 3 0 1 0 0-6 3 3 0 0 0 0 6',
suivi: 'M12 6v6l4 2|M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0',
asuivre: 'm19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z',
pj: 'm21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48',
groupes: 'M3 7h7v7H3z|M14 7h7v7h-7z|M3 17h18',
telecharger: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4|m7 10 5 5 5-5|M12 15V3', fermer: 'M18 6 6 18|m6 6 12 12', gauche: 'm15 18-6-6 6-6', droite: 'm9 18 6-6-6-6', bas: 'm6 9 6 6 6-6', fleche: 'M5 12h14|m12 5 7 7-7 7'
};
var NAV = [
['tri', 'Tri du jour', true], ['categories', 'Catégories', true], ['groupes', 'Groupes', true], ['recherche', 'Recherche', true], ['courses', 'Courses pour Tunis', true], ['suivi', 'Suivi des demandes', true], ['regles', 'Règles', true]
['tri', 'Tri du jour', true], ['asuivre', 'À suivre', true], ['categories', 'Catégories', true], ['groupes', 'Groupes', true], ['recherche', 'Recherche', true], ['courses', 'Courses pour Tunis', true], ['suivi', 'Suivi des demandes', true], ['regles', 'Règles', true]
];
var BIENTOT = {};
var COULEUR_NOM = { 'Tunis': 1, 'Demande FB': 2, 'CI': 3, 'Câbles': 4, 'Sans objet': 5, 'À classer': 0 };
var SYSTEME = 'À classer';
var S = { chargeA: 0, chargeJour: '', vue: 'tri', jour: auj(), filtre: null, cats: [], mails: [], etat: 'chargement', banniere: null, notif: null, regles: [], reglesEtat: 'ok', miroirErreur: false, majHeure: '', groupe: { jours: 7, cat: null, etq: null, mails: [], etat: 'chargement' }, courses: { liste: [], filtre: 'a_faire', etat: 'chargement' }, suivi: { items: [], jours: 14, filtre: 'attente', compte: {}, etat: 'chargement' }, recherche: { q: '', periode: 'tout', avecPj: false, etat: 'repos', resultats: [], plafond: false, cherche: '' } };
var S = { chargeA: 0, chargeJour: '', vue: 'tri', jour: auj(), filtre: null, cats: [], mails: [], etat: 'chargement', banniere: null, notif: null, regles: [], reglesEtat: 'ok', miroirErreur: false, majHeure: '', groupe: { jours: 7, cat: null, etq: null, mails: [], etat: 'chargement' }, courses: { liste: [], filtre: 'a_faire', etat: 'chargement' }, asuivre: { items: [], compte: { actif: 0, termine: 0 }, filtre: 'actif', etat: 'chargement', annuler: null }, suivreSet: {}, suivi: { items: [], jours: 14, filtre: 'attente', compte: {}, etat: 'chargement' }, recherche: { q: '', periode: 'tout', avecPj: false, etat: 'repos', resultats: [], plafond: false, cherche: '' } };
/* ---------- Utilitaires ---------- */
function auj() { return new Intl.DateTimeFormat('en-CA', { timeZone: TZ }).format(new Date()); }
@@ -39,6 +40,9 @@
return new Intl.DateTimeFormat('fr-FR', { hour: '2-digit', minute: '2-digit', hour12: false, timeZone: TZ }).format(d);
}
function couleur(nom, id) {
/* Chaque catégorie a sa couleur, enregistrée avec elle (jamais deux catégories sur la même teinte). */
var cat = S.cats.find(function (x) { return x.nom === nom; });
if (cat && typeof cat.couleur === 'number') return cat.couleur;
if (Object.prototype.hasOwnProperty.call(COULEUR_NOM, nom)) return COULEUR_NOM[nom];
return 6 + ((id || 0) % 3);
}
@@ -101,7 +105,7 @@
}
function chargerCats() {
return api('/categories').then(function (r) {
var l = (r.categories || []).map(function (c) { return { id: c.id, nom: c.name }; });
var l = (r.categories || []).map(function (c) { return { id: c.id, nom: c.name, couleur: c.couleur }; });
l.sort(function (a, b) { return (a.nom === SYSTEME) - (b.nom === SYSTEME) || a.id - b.id; });
S.cats = l;
});
@@ -150,6 +154,7 @@
else if (vue === 'regles') chargerRegles();
else if (vue === 'courses') chargerCourses();
else if (vue === 'suivi') chargerSuivi();
else if (vue === 'asuivre') chargerASuivre();
else if (vue === 'recherche') { rendre(); var ch = document.getElementById('rech-q'); if (ch) ch.focus(); return; }
else rendre();
document.getElementById('principal').focus();
@@ -277,7 +282,7 @@
var bureau = document.getElementById('nav-bureau'), mobile = document.getElementById('nav-mobile');
bureau.textContent = ''; mobile.textContent = '';
function bouton(n) {
return h('button', { type: 'button', class: 'nav-btn', 'aria-current': S.vue === n[0] ? 'page' : null, onclick: function () { allerA(n[0]); } }, icone(n[0]), h('span', null, n[1]));
return h('button', { type: 'button', class: 'nav-btn', 'aria-current': S.vue === n[0] ? 'page' : null, onclick: function () { allerA(n[0]); } }, icone(n[0]), h('span', null, n[1]), n[0] === 'asuivre' && S.asuivre.compte.actif > 0 ? h('span', { class: 'nav-n', text: String(S.asuivre.compte.actif) }) : null);
}
var liste = h('div', { class: 'nav-liste' });
NAV.forEach(function (n, i) {
@@ -410,6 +415,7 @@
while (principal.length && /^[\s_\-=]*$/.test(principal[principal.length - 1])) principal.pop();
}
var corps = principal.join('\n').trim() ? blocsTexte(principal.join('\n')) : h('p', { class: 'lect-vide', text: 'Ce mail ne contient pas de texte à afficher.' });
badges.appendChild(boutonSuivreLecture(m));
badges.appendChild(h('button', { type: 'button', class: 'btn-ligne lect-course', onclick: function () { dialogueCourse(null, { message_id: r.message_id || m.id, objet_mail: m.objet || r.objet || '', expediteur: m.expBrut || r.de || '', date_mail: m.date || '' }); } }, icone('courses', 18), 'Ajouter aux courses'));
cont.appendChild(badges); cont.appendChild(meta); cont.appendChild(corps);
if (histo && histo.join('\n').trim()) {
@@ -492,7 +498,8 @@
h('button', { type: 'button', class: 'lire', 'aria-label': libLire, onclick: function () { lireMail(m); } },
h('span', { class: 'exp coupe', title: m.expBrut, text: m.exp }), h('span', { class: 'objet coupe' + (m.objet ? '' : ' sans'), text: objetAff }),
h('span', { class: 'm-meta' }, h('span', { class: 'heure', text: heureTunis(m.date) }), ' · ', h('span', { class: 'o' + (orig === 'manuel' ? ' manuel' : ''), text: orig }))), reperes(m)),
selecteur(m));
selecteur(m),
boutonSuivre(m));
}
function vueTri() {
var frag = document.createDocumentFragment();
@@ -532,7 +539,7 @@
var visibles = tous.filter(function (m) { return !S.filtre || m.cat === S.filtre; });
var liste = h('div', { role: 'list' });
var carte = h('section', { class: 'carte', 'aria-label': 'Mails du jour' });
carte.appendChild(h('div', { class: 'liste-entete', 'aria-hidden': 'true' }, h('span'), h('span', null, 'Expéditeur'), h('span', null, 'Objet'), h('span', null, 'Heure'), h('span', null, 'Origine'), h('span', null, 'Catégorie')));
carte.appendChild(h('div', { class: 'liste-entete', 'aria-hidden': 'true' }, h('span'), h('span', null, 'Expéditeur'), h('span', null, 'Objet'), h('span', null, 'Heure'), h('span', null, 'Origine'), h('span', null, 'Catégorie'), h('span')));
visibles.forEach(function (m) { liste.appendChild(ligneMail(m)); });
carte.appendChild(liste);
if (tous.length === 0) carte.appendChild(h('div', { class: 'etat' }, icone('tri', 28), h('h2', null, 'Aucun mail ce jour'), h('p', null, 'Rien n\'est arrivé le ' + fr(S.jour) + '.')));
@@ -781,6 +788,137 @@
});
carte.appendChild(liste); frag.appendChild(carte); return frag;
}
/* ---------- À suivre : mails marqués à la main, sans limite de date ---------- */
/* Le marqueur reste dans Courrier : la messagerie O365 n'est jamais modifiée. */
function estSuivi(id) { return !!S.suivreSet[id]; }
function majSuivreSet() {
var s = {};
S.asuivre.items.forEach(function (i) { if (i.statut === 'actif') s[i.message_id] = 1; });
S.suivreSet = s;
}
function infoSuivi(m) {
return { message_id: m.id, expediteur: m.expBrut || m.exp || '', objet: m.objet || '', date_mail: m.date || '', categorie: m.cat || '' };
}
function chargerASuivre(silencieux) {
var V = S.asuivre;
if (!silencieux) { V.etat = 'chargement'; rendre(); }
return Promise.all([silencieux ? Promise.resolve() : chargerCats(), api('/a-suivre')]).then(function (rs) {
V.items = rs[1].items || []; V.compte = rs[1].compte || { actif: 0, termine: 0 }; V.etat = 'ok'; majSuivreSet(); rendre();
}).catch(function (e) { if (e.message === 'session' || silencieux) return; V.etat = 'erreur'; rendre(); });
}
function basculerASuivre(m) {
var id = m.id, ajout = !estSuivi(id);
if (ajout) S.suivreSet[id] = 1; else delete S.suivreSet[id];
rendre();
var req = ajout ? api('/a-suivre/marquer', { method: 'POST', body: infoSuivi(m) }) : api('/a-suivre/retirer', { method: 'POST', body: { ids: [id] } });
return req.then(function () {
flash(ajout ? 'Ajouté à « À suivre ».' : 'Retiré de « À suivre » : le mail reste dans « Terminés ».');
return chargerASuivre(true);
}).catch(function (e) {
if (e.message === 'session') return;
if (ajout) delete S.suivreSet[id]; else S.suivreSet[id] = 1;
rendre(); flash('Le suivi n\'a pas pu être enregistré. Réessayez.');
});
}
function retirerDuSuivi(ids, texte) {
var V = S.asuivre;
return api('/a-suivre/retirer', { method: 'POST', body: { ids: ids } }).then(function (r) {
var faits = r.ids || [];
clearTimeout(V.annulerT);
V.annuler = faits.length ? { ids: faits, texte: texte } : null;
if (V.annuler) V.annulerT = setTimeout(function () { V.annuler = null; rendre(); }, 30000);
annoncer(texte);
return chargerASuivre(true);
}).catch(function (e) { if (e.message !== 'session') flash('Le retrait n\'a pas pu être enregistré. Réessayez.'); });
}
function remettreAuSuivi(ids, texte) {
return api('/a-suivre/remettre', { method: 'POST', body: { ids: ids } }).then(function () {
if (texte) flash(texte);
return chargerASuivre(true);
}).catch(function (e) { if (e.message !== 'session') flash('L\'opération n\'a pas pu être enregistrée. Réessayez.'); });
}
function annulerRetrait() {
var V = S.asuivre, a = V.annuler;
if (!a) return;
clearTimeout(V.annulerT); V.annuler = null;
remettreAuSuivi(a.ids, 'Retrait annulé.');
}
function boutonSuivre(m) {
var on = estSuivi(m.id);
return h('button', { type: 'button', class: 'btn-icone btn-suivre', 'aria-pressed': on ? 'true' : 'false', 'aria-label': 'À suivre : ' + m.exp + ', ' + (m.objet || 'sans objet'),
title: on ? 'Retirer de « À suivre »' : 'Ajouter à « À suivre »', onclick: function () { basculerASuivre(m); } }, icone('asuivre'));
}
function boutonSuivreLecture(m) {
var lib = h('span');
var b = h('button', { type: 'button', class: 'btn-ligne lect-suivre' }, icone('asuivre', 18), lib);
function etat() { var on = estSuivi(m.id); b.setAttribute('aria-pressed', on ? 'true' : 'false'); lib.textContent = on ? 'Retirer de « À suivre »' : 'Ajouter à « À suivre »'; }
b.addEventListener('click', function () { var p = basculerASuivre(m); etat(); p.then(etat); });
etat();
return b;
}
function boutonSuivreRecherche(x) {
var m = { id: x.message_id, exp: nomExp(x.expediteur), expBrut: x.expediteur, objet: x.objet, date: x.date, cat: '' };
var on = estSuivi(m.id);
return h('button', { type: 'button', class: 'btn-petit btn-suivre-txt', 'aria-pressed': on ? 'true' : 'false', 'aria-label': 'À suivre : ' + (x.objet || 'sans objet'),
onclick: function () { basculerASuivre(m); } }, on ? 'Suivi' : 'À suivre');
}
function vueASuivre() {
var V = S.asuivre, frag = document.createDocumentFragment();
frag.appendChild(h('header', { class: 'entete' }, h('div', null, h('h1', null, 'À suivre'), h('div', { class: 'maj' }, 'Les mails que vous avez marqués, sans limite de date'))));
if (S.notif) frag.appendChild(h('div', { class: 'notif', role: 'status', text: S.notif }));
if (V.etat === 'erreur') {
frag.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Lecture de la liste impossible'), h('p', null, 'La liste « À suivre » n\'a pas pu être chargée.'), h('button', { type: 'button', class: 'btn-plein', onclick: function () { chargerASuivre(); } }, 'Réessayer')));
return frag;
}
if (V.etat === 'chargement') { frag.appendChild(h('section', { class: 'carte squelette', 'aria-busy': 'true' }, h('div', { class: 'sq-statut', role: 'status', text: 'Chargement de votre liste…' }))); return frag; }
if (V.annuler) frag.appendChild(h('div', { class: 'bandeau', role: 'status' }, h('div', { class: 'txt', text: V.annuler.texte }), h('div', { class: 'acts' }, h('button', { type: 'button', class: 'btn-ligne', onclick: annulerRetrait }, 'Annuler'))));
var pc = h('div', { class: 'puces', role: 'group', 'aria-label': 'Afficher' });
[['actif', 'À suivre'], ['termine', 'Terminés']].forEach(function (o) {
pc.appendChild(h('button', { type: 'button', class: 'puce', 'aria-pressed': V.filtre === o[0] ? 'true' : 'false', onclick: function () { V.filtre = o[0]; rendre(); } }, h('span', { text: o[1] }), h('span', { class: 'n', text: d2(V.compte[o[0]] || 0) })));
});
frag.appendChild(h('section', { class: 'carte repartition', 'aria-label': 'Filtre de la liste' }, h('h2', null, 'Afficher'), pc));
var actif = V.filtre === 'actif';
var vis = V.items.filter(function (i) { return i.statut === V.filtre; });
if (!vis.length) {
frag.appendChild(h('section', { class: 'carte' }, h('div', { class: 'etat' }, icone('asuivre', 28),
h('h2', { text: actif ? 'Rien à suivre pour le moment' : 'Aucun mail terminé' }),
h('p', { text: actif ? 'Utilisez le marque-page d\'une ligne, ou le bouton dans un mail ouvert : le mail restera ici quelle que soit sa date.' : 'Les mails retirés de la liste apparaissent ici ; vous pouvez les remettre à tout moment.' }))));
return frag;
}
var par = {}, ordre = [], rang = {};
S.cats.forEach(function (c, i) { rang[c.nom] = i; });
vis.forEach(function (i) { var c = i.categorie || SYSTEME; if (!par[c]) { par[c] = []; ordre.push(c); } par[c].push(i); });
ordre.sort(function (a, b) { return (a === SYSTEME) - (b === SYSTEME) || par[b].length - par[a].length || (rang[a] === undefined ? 99 : rang[a]) - (rang[b] === undefined ? 99 : rang[b]); });
ordre.forEach(function (cat) {
var liste = par[cat], k = couleur(cat);
var ids = liste.map(function (i) { return i.message_id; });
var nb = liste.length + (liste.length > 1 ? ' mails' : ' mail');
var txtTout = actif ? 'Tout retirer' : 'Tout remettre';
var entete = h('div', { class: 'groupe-tete' }, pastille(k), h('h2', { text: cat }), h('span', { class: 'nb', text: nb }),
h('button', { type: 'button', class: 'btn-ligne', 'aria-label': txtTout + ' : ' + cat + ', ' + nb, onclick: function () {
if (actif) retirerDuSuivi(ids, liste.length + (liste.length > 1 ? ' mails retirés' : ' mail retiré') + ' de « ' + cat + ' ».');
else remettreAuSuivi(ids, liste.length + (liste.length > 1 ? ' mails remis' : ' mail remis') + ' dans « À suivre ».');
} }, txtTout));
var corps = h('div', { role: 'list' });
liste.forEach(function (it) {
var exp = nomExp(it.expediteur), objet = it.objet || '(sans objet)';
var quand = it.date_mail ? fr(String(it.date_mail).slice(0, 10)) + ' · ' + heureTunis(it.date_mail) : '';
var vieux = actif && it.jours >= 7;
var badges = h('div', { class: 'course-badges' }, h('span', { class: 'etq' + (vieux ? ' relance' : ''), text: actif ? 'Marqué ' + dureeLisible(it.jours) : 'Terminé' }));
var mm = { id: it.message_id, exp: exp, expBrut: it.expediteur || exp, objet: it.objet || '', date: it.date_mail || '', cat: it.categorie, etiquettes: [] };
corps.appendChild(h('div', { class: 'course', role: 'listitem' },
h('div', { class: 'course-corps' }, h('div', { class: 'dem', text: objet }), h('div', { class: 'meta', text: [exp, quand].filter(Boolean).join(' · ') }), badges),
h('div', { class: 'course-actions' },
h('button', { type: 'button', class: 'btn-petit', 'aria-label': 'Lire le mail : ' + objet, onclick: function () { lireMail(mm); } }, 'Lire le mail'),
actif
? h('button', { type: 'button', class: 'btn-petit', 'aria-label': 'Retirer de la liste : ' + objet, onclick: function () { retirerDuSuivi([it.message_id], 'Mail retiré : ' + objet); } }, 'Retirer')
: h('button', { type: 'button', class: 'btn-petit', 'aria-label': 'Remettre dans la liste : ' + objet, onclick: function () { remettreAuSuivi([it.message_id], 'Remis dans « À suivre ».'); } }, 'Remettre'))));
});
var carte = h('section', { class: 'carte groupe-suivi t' + k, 'aria-label': cat });
carte.appendChild(entete); carte.appendChild(corps); frag.appendChild(carte);
});
return frag;
}
/* ---------- Recherche ---------- */
var PERIODES = [['tout', 'Tout le courrier'], ['30', '30 jours'], ['90', '90 jours'], ['annee', 'Cette année']];
function lancerRecherche() {
@@ -829,7 +967,7 @@
var meta = [nomExp(x.expediteur), x.dossier].filter(Boolean).join(' · ');
liste.appendChild(h('div', { class: 'course', role: 'listitem' },
h('div', { class: 'course-corps' }, h('div', { class: 'dem', text: x.objet || '(sans objet)' }), h('div', { class: 'meta', text: meta + (x.pj ? ' · avec pièce jointe' : '') })),
h('div', { class: 'course-actions' }, h('button', { type: 'button', class: 'btn-petit', 'aria-label': 'Lire le mail : ' + (x.objet || 'sans objet'), onclick: function () { lireMail({ id: x.message_id, objet: x.objet, exp: nomExp(x.expediteur), expBrut: x.expediteur, date: x.date, cat: '', etiquettes: x.etiquettes || [] }); } }, 'Lire le mail'))));
h('div', { class: 'course-actions' }, h('button', { type: 'button', class: 'btn-petit', 'aria-label': 'Lire le mail : ' + (x.objet || 'sans objet'), onclick: function () { lireMail({ id: x.message_id, objet: x.objet, exp: nomExp(x.expediteur), expBrut: x.expediteur, date: x.date, cat: '', etiquettes: x.etiquettes || [] }); } }, 'Lire le mail'), boutonSuivreRecherche(x))));
});
carte.appendChild(liste); frag.appendChild(carte);
});
@@ -845,13 +983,14 @@
var ancre = document.activeElement && document.activeElement.getAttribute && document.activeElement.getAttribute('aria-label');
rendreNav();
var p = document.getElementById('principal'); p.textContent = '';
var v = S.vue === 'tri' ? vueTri() : S.vue === 'categories' ? vueCategories() : S.vue === 'regles' ? vueRegles() : S.vue === 'groupes' ? vueGroupes() : S.vue === 'courses' ? vueCourses() : S.vue === 'suivi' ? vueSuivi() : S.vue === 'recherche' ? vueRecherche() : vueBientot(S.vue);
var v = S.vue === 'tri' ? vueTri() : S.vue === 'categories' ? vueCategories() : S.vue === 'regles' ? vueRegles() : S.vue === 'groupes' ? vueGroupes() : S.vue === 'courses' ? vueCourses() : S.vue === 'suivi' ? vueSuivi() : S.vue === 'asuivre' ? vueASuivre() : S.vue === 'recherche' ? vueRecherche() : vueBientot(S.vue);
p.appendChild(v); p.scrollTop = pos;
var titre = S.vue === 'tri' ? 'Tri du jour' : S.vue === 'categories' ? 'Catégories' : S.vue === 'regles' ? 'Règles' : S.vue === 'groupes' ? 'Groupes' : S.vue === 'courses' ? 'Courses pour Tunis' : S.vue === 'suivi' ? 'Suivi des demandes' : S.vue === 'recherche' ? 'Recherche' : BIENTOT[S.vue][0];
var titre = S.vue === 'tri' ? 'Tri du jour' : S.vue === 'categories' ? 'Catégories' : S.vue === 'regles' ? 'Règles' : S.vue === 'groupes' ? 'Groupes' : S.vue === 'courses' ? 'Courses pour Tunis' : S.vue === 'suivi' ? 'Suivi des demandes' : S.vue === 'asuivre' ? 'À suivre' : S.vue === 'recherche' ? 'Recherche' : BIENTOT[S.vue][0];
document.title = titre + ' · Courrier';
if (ancre && !dialogue) { var r = p.querySelector('[aria-label="' + ancre.replace(/"/g, '\\"') + '"]'); if (r && document.activeElement === document.body) r.focus(); }
}
rendre();
chargerMails();
chargerASuivre(true);
})();
+2 -2
View File
@@ -10,7 +10,7 @@
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
<link rel="stylesheet" href="/static/fonts.css">
<link rel="stylesheet" href="/static/nyora.css">
<link rel="stylesheet" href="/static/app.css?v=20261118f">
<link rel="stylesheet" href="/static/app.css?v=20261119a">
</head>
<body>
<div id="app" class="coque">
@@ -20,6 +20,6 @@
</div>
<div id="calque"></div>
<div id="annonce" class="sr" role="status" aria-live="polite"></div>
<script src="/static/app.js?v=20261118f"></script>
<script src="/static/app.js?v=20261119a"></script>
</body>
</html>
+4
View File
@@ -14,6 +14,10 @@
--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-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-police: "Atkinson Hyperlegible Next", "Segoe UI", system-ui, sans-serif;
--ny-police-chiffres: "Atkinson Hyperlegible Mono", ui-monospace, monospace;
+130
View File
@@ -0,0 +1,130 @@
"""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