Compare commits
16
Commits
40d416d551
...
main
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é).
|
||||||
+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()
|
||||||
@@ -214,3 +214,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 = list_regles(statut="active", db_path=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,164 @@
|
|||||||
|
"""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 = 30) -> 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:
|
||||||
|
return str(r.json()["choices"][0]["message"]["content"] or "")
|
||||||
|
except (KeyError, IndexError, ValueError, TypeError):
|
||||||
|
raise IAIndisponible("reponse PrivAiTe illisible")
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
+376
-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,29 @@ 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.auth import verify_cf_access_jwt
|
from app.auth import verify_cf_access_jwt
|
||||||
|
|
||||||
# --- Schémas Pydantic ---
|
# --- Schémas Pydantic ---
|
||||||
@@ -70,6 +88,8 @@ 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()
|
||||||
yield
|
yield
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
@@ -95,6 +115,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 +169,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 +190,352 @@ 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 de discussion classe Tunis. Un fil supprime ou deja importe n'est pas recree."""
|
||||||
|
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 +677,5 @@ 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))
|
||||||
app.include_router(api)
|
app.include_router(api)
|
||||||
+142
-22
@@ -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}
|
||||||
|
|
||||||
def get_mails_for_day(self, date_str: str, max_items: int = 50) -> List[Dict[str, Any]]:
|
@staticmethod
|
||||||
"""
|
def _norm(m: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
Récupère les emails correspondant à un jour donné (date_str: AAAA-MM-JJ).
|
return {
|
||||||
Utilise mirror_mail_latest avec un nombre suffisant de messages puis filtre par date.
|
"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 "",
|
||||||
raw_mails = self.get_latest_mails(folder="*", n=max_items)
|
|
||||||
filtered = []
|
|
||||||
for m in raw_mails:
|
|
||||||
# Vérifier la présence du message_id ou id
|
|
||||||
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 ""
|
|
||||||
if date_str in d_mail or not date_str:
|
|
||||||
m_normalized = {
|
|
||||||
"message_id": mid,
|
|
||||||
"date": d_mail,
|
|
||||||
"expediteur": m.get("from") or m.get("expediteur") or "",
|
"expediteur": m.get("from") or m.get("expediteur") or "",
|
||||||
"objet": m.get("sujet") or 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 [],
|
"etiquettes": m.get("tags") or m.get("etiquettes") or [],
|
||||||
"apercu": m.get("snippet") or m.get("apercu") or ""
|
"apercu": m.get("snippet") or m.get("apercu") or "",
|
||||||
|
"dossier": m.get("dossier") or "",
|
||||||
|
"destinataires": m.get("destinataires") or "",
|
||||||
}
|
}
|
||||||
filtered.append(m_normalized)
|
|
||||||
return filtered
|
@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]]:
|
||||||
|
"""Mails d'un jour donné (AAAA-MM-JJ)."""
|
||||||
|
if not date_str:
|
||||||
|
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"]]
|
||||||
|
|
||||||
|
def get_mails_since(self, debut: str, max_items: int = 400) -> List[Dict[str, Any]]:
|
||||||
|
"""Mails dont la date est >= debut (AAAA-MM-JJ)."""
|
||||||
|
return self._mails_depuis(debut, max_items)[:max_items]
|
||||||
|
|
||||||
|
def rafraichir_derniers(self) -> None:
|
||||||
|
"""Relit les derniers mails en ignorant le cache (même clé que les vues)."""
|
||||||
|
self.call_tool("mirror_mail_latest", {"folder": "*", "n": self.MIRROR_MAX_LATEST, "inclure_exclus": False}, force=True)
|
||||||
|
|
||||||
|
def demarrer_rafraichissement(self, intervalle: int = 45) -> None:
|
||||||
|
"""Préchauffe le cache puis le rafraîchit en tâche de fond (1 lecture toutes les 45 s, loin des 60 par minute),
|
||||||
|
pour que l'ouverture d'une vue n'attende jamais le miroir. Idempotent."""
|
||||||
|
if self._refresh_started:
|
||||||
|
return
|
||||||
|
self._refresh_started = True
|
||||||
|
|
||||||
|
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()
|
||||||
+141
-3
@@ -50,7 +50,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 +65,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 +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); }
|
.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; }
|
||||||
@@ -179,8 +190,9 @@ h1, h2, h3, p { margin: 0; }
|
|||||||
.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: minmax(0, 1fr) auto; height: 100dvh; min-height: 0; }
|
||||||
.nav-bureau { display: none; }
|
.nav-bureau { display: none; }
|
||||||
.principal { padding: var(--ny-e4); 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 { display: grid; grid-template-columns: repeat(4, 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 { 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[aria-current="page"] { font-weight: 600; }
|
||||||
.nav-mobile .nav-btn svg { width: 22px; height: 22px; }
|
.nav-mobile .nav-btn svg { width: 22px; height: 22px; }
|
||||||
@@ -207,3 +219,129 @@ 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) {
|
||||||
|
.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; }
|
||||||
|
}
|
||||||
|
/* 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); }
|
||||||
+604
-26
@@ -12,23 +12,19 @@
|
|||||||
recherche: 'm21 21-4.34-4.34|M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16',
|
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',
|
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',
|
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',
|
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',
|
||||||
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'
|
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 = [
|
var NAV = [
|
||||||
['tri', 'Tri du jour', true], ['categories', 'Catégories', 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]
|
||||||
['recherche', 'Recherche', false], ['courses', 'Courses pour Tunis', false], ['suivi', 'Suivi des demandes', false], ['pj', 'Pièces jointes', false]
|
|
||||||
];
|
];
|
||||||
var BIENTOT = {
|
var BIENTOT = {};
|
||||||
recherche: ['Recherche', 'Retrouver un mail par expéditeur, objet ou date, dans tout le courrier lu.'],
|
|
||||||
courses: ['Courses pour Tunis', 'Préparer les courses à partir des mails classés « Tunis ».'],
|
|
||||||
suivi: ['Suivi des demandes', 'Suivre les demandes envoyées et celles qui attendent une réponse.'],
|
|
||||||
pj: ['Pièces jointes', 'Lister et rechercher les pièces jointes des mails.']
|
|
||||||
};
|
|
||||||
var COULEUR_NOM = { 'Tunis': 1, 'Demande FB': 2, 'CI': 3, 'Câbles': 4, 'Sans objet': 5, 'À classer': 0 };
|
var COULEUR_NOM = { 'Tunis': 1, 'Demande FB': 2, 'CI': 3, 'Câbles': 4, 'Sans objet': 5, 'À classer': 0 };
|
||||||
var SYSTEME = 'À classer';
|
var SYSTEME = 'À classer';
|
||||||
|
|
||||||
var S = { vue: 'tri', jour: auj(), filtre: null, cats: [], mails: [], etat: 'chargement', banniere: null, notif: null, regles: [], reglesEtat: 'ok', miroirErreur: false, majHeure: '' };
|
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 ---------- */
|
/* ---------- Utilitaires ---------- */
|
||||||
function auj() { return new Intl.DateTimeFormat('en-CA', { timeZone: TZ }).format(new Date()); }
|
function auj() { return new Intl.DateTimeFormat('en-CA', { timeZone: TZ }).format(new Date()); }
|
||||||
@@ -44,6 +40,9 @@
|
|||||||
return new Intl.DateTimeFormat('fr-FR', { hour: '2-digit', minute: '2-digit', hour12: false, timeZone: TZ }).format(d);
|
return new Intl.DateTimeFormat('fr-FR', { hour: '2-digit', minute: '2-digit', hour12: false, timeZone: TZ }).format(d);
|
||||||
}
|
}
|
||||||
function couleur(nom, id) {
|
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];
|
if (Object.prototype.hasOwnProperty.call(COULEUR_NOM, nom)) return COULEUR_NOM[nom];
|
||||||
return 6 + ((id || 0) % 3);
|
return 6 + ((id || 0) % 3);
|
||||||
}
|
}
|
||||||
@@ -106,7 +105,7 @@
|
|||||||
}
|
}
|
||||||
function chargerCats() {
|
function chargerCats() {
|
||||||
return api('/categories').then(function (r) {
|
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; });
|
l.sort(function (a, b) { return (a.nom === SYSTEME) - (b.nom === SYSTEME) || a.id - b.id; });
|
||||||
S.cats = l;
|
S.cats = l;
|
||||||
});
|
});
|
||||||
@@ -118,11 +117,20 @@
|
|||||||
if (jour !== S.jour) return;
|
if (jour !== S.jour) return;
|
||||||
var r = rs[1];
|
var r = rs[1];
|
||||||
S.miroirErreur = !!r.miroir_erreur;
|
S.miroirErreur = !!r.miroir_erreur;
|
||||||
S.mails = (r.mails || []).map(normaliser).sort(function (a, b) { return String(a.date).localeCompare(String(b.date)); });
|
S.mails = (r.mails || []).map(normaliser).sort(function (a, b) { return String(b.date).localeCompare(String(a.date)); });
|
||||||
S.etat = 'ok'; S.majHeure = heureTunis(new Date().toISOString());
|
S.etat = 'ok'; S.majHeure = heureTunis(new Date().toISOString()); S.chargeA = Date.now(); S.chargeJour = jour;
|
||||||
rendre();
|
rendre();
|
||||||
}).catch(function (e) { if (e.message === 'session') return; if (jour !== S.jour) return; S.etat = 'erreur'; rendre(); });
|
}).catch(function (e) { if (e.message === 'session') return; if (jour !== S.jour) return; S.etat = 'erreur'; rendre(); });
|
||||||
}
|
}
|
||||||
|
function chargerGroupe() {
|
||||||
|
var G = S.groupe, jours = G.jours;
|
||||||
|
G.etat = 'chargement'; rendre();
|
||||||
|
return Promise.all([chargerCats(), api('/mails/periode?jours=' + jours)]).then(function (rs) {
|
||||||
|
if (jours !== G.jours) return;
|
||||||
|
G.mails = (rs[1].mails || []).map(normaliser).sort(function (a, b) { return String(b.date).localeCompare(String(a.date)); });
|
||||||
|
G.miroirErreur = !!rs[1].miroir_erreur; G.etat = 'ok'; rendre();
|
||||||
|
}).catch(function (e) { if (e.message === 'session') return; if (jours !== G.jours) return; G.etat = 'erreur'; rendre(); });
|
||||||
|
}
|
||||||
function chargerRegles() {
|
function chargerRegles() {
|
||||||
S.reglesEtat = 'chargement'; rendre();
|
S.reglesEtat = 'chargement'; rendre();
|
||||||
return Promise.all([chargerCats(), api('/regles')]).then(function (rs) {
|
return Promise.all([chargerCats(), api('/regles')]).then(function (rs) {
|
||||||
@@ -139,8 +147,15 @@
|
|||||||
}
|
}
|
||||||
function allerA(vue) {
|
function allerA(vue) {
|
||||||
S.vue = vue; S.banniere = null;
|
S.vue = vue; S.banniere = null;
|
||||||
if (vue === 'tri' || vue === 'categories') chargerMails();
|
if (vue === 'tri' || vue === 'categories') {
|
||||||
|
if (S.etat === 'ok' && S.chargeJour === S.jour && Date.now() - S.chargeA < 30000) rendre(); else chargerMails();
|
||||||
|
}
|
||||||
|
else if (vue === 'groupes') chargerGroupe();
|
||||||
else if (vue === 'regles') chargerRegles();
|
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();
|
else rendre();
|
||||||
document.getElementById('principal').focus();
|
document.getElementById('principal').focus();
|
||||||
}
|
}
|
||||||
@@ -157,7 +172,7 @@
|
|||||||
.then(function (r) {
|
.then(function (r) {
|
||||||
var rp = r.regle_proposee;
|
var rp = r.regle_proposee;
|
||||||
if (rp && rp.id) {
|
if (rp && rp.id) {
|
||||||
var autres = S.mails.filter(function (x) { return x.exp === m.exp && x.id !== m.id && x.source !== 'manuel' && x.cat !== cat; }).length;
|
var autres = (S.vue === 'groupes' ? S.groupe.mails : S.mails).filter(function (x) { return x.exp === m.exp && x.id !== m.id && x.source !== 'manuel' && x.cat !== cat; }).length;
|
||||||
S.banniere = { id: rp.id, exp: m.exp, cat: cat, autres: autres }; rendre();
|
S.banniere = { id: rp.id, exp: m.exp, cat: cat, autres: autres }; rendre();
|
||||||
}
|
}
|
||||||
}).catch(function (e) { if (e.message === 'session') return; m.cat = avant.cat; m.source = avant.source; rendre(); flash('La correction n\'a pas été enregistrée. Réessayez.'); });
|
}).catch(function (e) { if (e.message === 'session') return; m.cat = avant.cat; m.source = avant.source; rendre(); flash('La correction n\'a pas été enregistrée. Réessayez.'); });
|
||||||
@@ -193,7 +208,7 @@
|
|||||||
voile.addEventListener('keydown', function (e) {
|
voile.addEventListener('keydown', function (e) {
|
||||||
if (e.key === 'Escape') { e.preventDefault(); fermer(); return; }
|
if (e.key === 'Escape') { e.preventDefault(); fermer(); return; }
|
||||||
if (e.key === 'Tab') {
|
if (e.key === 'Tab') {
|
||||||
var f = boite.querySelectorAll('button,input,select,[href]'); if (!f.length) return;
|
var f = boite.querySelectorAll('button:not([hidden]),input,select,[href],summary,[tabindex="0"]'); if (!f.length) return;
|
||||||
var a = f[0], z = f[f.length - 1];
|
var a = f[0], z = f[f.length - 1];
|
||||||
if (e.shiftKey && document.activeElement === a) { e.preventDefault(); z.focus(); }
|
if (e.shiftKey && document.activeElement === a) { e.preventDefault(); z.focus(); }
|
||||||
else if (!e.shiftKey && document.activeElement === z) { e.preventDefault(); a.focus(); }
|
else if (!e.shiftKey && document.activeElement === z) { e.preventDefault(); a.focus(); }
|
||||||
@@ -267,11 +282,10 @@
|
|||||||
var bureau = document.getElementById('nav-bureau'), mobile = document.getElementById('nav-mobile');
|
var bureau = document.getElementById('nav-bureau'), mobile = document.getElementById('nav-mobile');
|
||||||
bureau.textContent = ''; mobile.textContent = '';
|
bureau.textContent = ''; mobile.textContent = '';
|
||||||
function bouton(n) {
|
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' });
|
var liste = h('div', { class: 'nav-liste' });
|
||||||
NAV.forEach(function (n, i) {
|
NAV.forEach(function (n, i) {
|
||||||
if (i === 3) liste.appendChild(h('div', { class: 'nav-sep' }, 'Prochainement'));
|
|
||||||
liste.appendChild(bouton(n));
|
liste.appendChild(bouton(n));
|
||||||
if (n[2]) mobile.appendChild(bouton(n));
|
if (n[2]) mobile.appendChild(bouton(n));
|
||||||
});
|
});
|
||||||
@@ -297,23 +311,195 @@
|
|||||||
noms.forEach(function (n) { var o = h('option', { value: n }, n); if (n === m.cat) o.selected = true; sel.appendChild(o); });
|
noms.forEach(function (n) { var o = h('option', { value: n }, n); if (n === m.cat) o.selected = true; sel.appendChild(o); });
|
||||||
return h('div', { class: 'sel' }, pastille(couleur(m.cat, c && c.id)), sel, h('span', { class: 'chev' }, icone('bas')));
|
return h('div', { class: 'sel' }, pastille(couleur(m.cat, c && c.id)), sel, h('span', { class: 'chev' }, icone('bas')));
|
||||||
}
|
}
|
||||||
|
/* ---------- Lecture d'un mail (texte seul, lecture seule) ---------- */
|
||||||
|
var RUPT_FORT = /^\s*(?:-{3,}\s*(?:Original Message|Message d.origine)|Le\s.{5,140}\sa\s+écrit\s?:|On\s.{5,140}\swrote:)/i;
|
||||||
|
var RUPT_ENTETE = /^\s*(?:De|From)\s?:/i;
|
||||||
|
var SUITE_ENTETE = /^\s*(?:Envoy[ée]|Sent|Date|Objet|Subject|À|To)\s?:/i;
|
||||||
|
var URL_RE = /(https?:\/\/[^\s<>"')\]]*[^\s<>"')\].,;:!?])/g;
|
||||||
|
function debutHistorique(l) {
|
||||||
|
for (var i = 1; i < l.length; i++) {
|
||||||
|
if (RUPT_FORT.test(l[i])) return i;
|
||||||
|
if (RUPT_ENTETE.test(l[i])) { for (var k = i + 1; k <= i + 4 && k < l.length; k++) if (SUITE_ENTETE.test(l[k])) return i; }
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
function avecLiens(el, ligne) {
|
||||||
|
ligne.split(URL_RE).forEach(function (t, i) {
|
||||||
|
if (!t) return;
|
||||||
|
if (i % 2 === 1) el.appendChild(h('a', { href: t, target: '_blank', rel: 'noopener noreferrer nofollow', text: t }));
|
||||||
|
else el.appendChild(document.createTextNode(t));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function blocsTexte(texte) {
|
||||||
|
var sortie = h('div', { class: 'lect-texte' }), para = [], cit = false;
|
||||||
|
function vider() {
|
||||||
|
if (!para.length) return;
|
||||||
|
var el = h(cit ? 'blockquote' : 'p');
|
||||||
|
para.forEach(function (l, i) { if (i) el.appendChild(h('br')); avecLiens(el, l); });
|
||||||
|
sortie.appendChild(el); para = [];
|
||||||
|
}
|
||||||
|
texte.split('\n').forEach(function (l) {
|
||||||
|
if (!l.trim()) { vider(); return; }
|
||||||
|
var estCit = /^\s*>/.test(l);
|
||||||
|
if (estCit !== cit) vider();
|
||||||
|
cit = estCit;
|
||||||
|
para.push(estCit ? l.replace(/^(\s*>)+\s?/, '') : l);
|
||||||
|
});
|
||||||
|
vider();
|
||||||
|
return sortie;
|
||||||
|
}
|
||||||
|
function decouperAdresses(s) { return String(s || '').split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/).map(function (x) { return x.trim(); }).filter(Boolean); }
|
||||||
|
function pastilleAdresse(a) {
|
||||||
|
var m = a.match(/^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/), nom = m ? m[1].trim() : '', adr = m ? m[2].trim() : a.trim();
|
||||||
|
return h('span', { class: 'qui' }, nom ? h('span', { class: 'nom', text: nom }) : null, nom ? ' ' : null, h('span', { class: nom ? 'adr' : 'nom', text: nom ? '<' + adr + '>' : adr }));
|
||||||
|
}
|
||||||
|
function listeAdresses(s) {
|
||||||
|
var l = decouperAdresses(s);
|
||||||
|
if (!l.length) return null;
|
||||||
|
var dd = h('dd', { class: 'adrs' });
|
||||||
|
l.forEach(function (a, i) { var e = pastilleAdresse(a); if (i >= 3) e.setAttribute('hidden', ''); dd.appendChild(e); });
|
||||||
|
if (l.length > 3) {
|
||||||
|
var b = h('button', { type: 'button', class: 'btn-petit plus' }, '+ ' + (l.length - 3) + (l.length - 3 > 1 ? ' autres' : ' autre'));
|
||||||
|
b.addEventListener('click', function () {
|
||||||
|
dd.querySelectorAll('[hidden]').forEach(function (x) { x.removeAttribute('hidden'); }); b.remove();
|
||||||
|
var z = document.querySelector('.lect-scroll'); if (z) z.focus();
|
||||||
|
});
|
||||||
|
dd.appendChild(b);
|
||||||
|
}
|
||||||
|
return dd;
|
||||||
|
}
|
||||||
|
function tailleLisible(n) {
|
||||||
|
n = Number(n) || 0;
|
||||||
|
if (n < 1024) return n + ' o';
|
||||||
|
if (n < 1048576) return (n / 1024).toFixed(n < 10240 ? 1 : 0).replace('.', ',') + ' Ko';
|
||||||
|
return (n / 1048576).toFixed(1).replace('.', ',') + ' Mo';
|
||||||
|
}
|
||||||
|
function dateLongue(v) {
|
||||||
|
var iso = String(v || '').slice(0, 10);
|
||||||
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(iso)) return String(v || '');
|
||||||
|
return nomJour(iso).toLowerCase() + ' ' + fr(iso) + ' à ' + heureTunis(v);
|
||||||
|
}
|
||||||
|
function estSignature(p) {
|
||||||
|
return /^image\//.test(p.type || '') && Number(p.taille) < 20480 && !p.bloquee;
|
||||||
|
}
|
||||||
|
function telechargerPiece(id, p, bt) {
|
||||||
|
bt.disabled = true; annoncer('Téléchargement de ' + p.nom + ' en cours');
|
||||||
|
fetch(API + '/mail/piece?id=' + encodeURIComponent(id) + '&nom=' + encodeURIComponent(p.nom), { credentials: 'same-origin', redirect: 'manual' })
|
||||||
|
.then(function (rep) {
|
||||||
|
if (rep.type === 'opaqueredirect') { sessionExpiree(); throw new Error('session'); }
|
||||||
|
if (rep.status === 403) throw new Error('Ce type de fichier est bloqué par sécurité.');
|
||||||
|
if (rep.status === 413) throw new Error('Pièce jointe trop volumineuse (25 Mo maximum).');
|
||||||
|
if (!rep.ok) throw new Error('Pièce jointe indisponible pour le moment.');
|
||||||
|
return rep.blob();
|
||||||
|
})
|
||||||
|
.then(function (blob) {
|
||||||
|
var url = URL.createObjectURL(blob), a = document.createElement('a');
|
||||||
|
a.href = url; a.download = p.nom; document.body.appendChild(a); a.click(); a.remove();
|
||||||
|
setTimeout(function () { URL.revokeObjectURL(url); }, 4000);
|
||||||
|
annoncer(p.nom + ' téléchargé');
|
||||||
|
})
|
||||||
|
.catch(function (e) { if (e.message !== 'session') annoncer(e.message); })
|
||||||
|
.then(function () { bt.disabled = false; });
|
||||||
|
}
|
||||||
|
function afficherMail(cont, m, r, c) {
|
||||||
|
var badges = h('div', { class: 'lect-badges' }, m.cat ? h('span', { class: 'lect-cat' }, pastille(couleur(m.cat, c && c.id)), m.cat) : null);
|
||||||
|
(m.etiquettes || []).forEach(function (t) { badges.appendChild(h('span', { class: 'etq', text: t })); });
|
||||||
|
var meta = h('dl', { class: 'lect-meta' });
|
||||||
|
function ligne(lib, dd) { if (!dd) return; meta.appendChild(h('dt', { text: lib })); meta.appendChild(dd); }
|
||||||
|
ligne('De', listeAdresses(r.de || m.expBrut)); ligne('À', listeAdresses(r.a)); ligne('Cc', listeAdresses(r.cc));
|
||||||
|
ligne('Date', h('dd', { text: dateLongue(m.date || r.date) }));
|
||||||
|
var lignes = String(r.corps || '').replace(/\r\n?/g, '\n').replace(/ /g, ' ').split('\n');
|
||||||
|
var cut = debutHistorique(lignes), principal = lignes, histo = null;
|
||||||
|
if (cut > 0) {
|
||||||
|
principal = lignes.slice(0, cut); histo = lignes.slice(cut);
|
||||||
|
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()) {
|
||||||
|
cont.appendChild(h('details', { class: 'lect-histo' }, h('summary', null, 'Afficher l\'historique de la conversation'), blocsTexte(histo.join('\n'))));
|
||||||
|
}
|
||||||
|
if (r.tronque) cont.appendChild(h('p', { class: 'lect-note', text: 'Le texte est très long : seul le début est affiché.' }));
|
||||||
|
var pj = r.pieces_jointes || [];
|
||||||
|
var signature = pj.filter(estSignature), utiles = pj.filter(function (p) { return !estSignature(p); });
|
||||||
|
function extDe(p) { var e = String(p.nom || '').indexOf('.') > -1 ? String(p.nom).split('.').pop().toUpperCase() : ''; return e && e.length <= 5 ? e + ' · ' : ''; }
|
||||||
|
if (utiles.length) {
|
||||||
|
var ul = h('ul');
|
||||||
|
utiles.forEach(function (p) {
|
||||||
|
var action;
|
||||||
|
if (p.bloquee) action = h('span', { class: 'info bloquee', text: 'Bloquée par sécurité' });
|
||||||
|
else {
|
||||||
|
var bt = h('button', { type: 'button', class: 'btn-icone', 'aria-label': 'Télécharger ' + p.nom, title: 'Télécharger' }, icone('telecharger'));
|
||||||
|
bt.addEventListener('click', function () { telechargerPiece(r.message_id || m.id, p, bt); });
|
||||||
|
action = bt;
|
||||||
|
}
|
||||||
|
ul.appendChild(h('li', null, icone('pj', 18), h('span', { class: 'nom coupe', title: p.nom, text: p.nom }),
|
||||||
|
h('span', { class: 'info', text: extDe(p) + tailleLisible(p.taille) }), action));
|
||||||
|
});
|
||||||
|
cont.appendChild(h('section', { class: 'lect-pj', 'aria-labelledby': 'lect-pj-t' }, h('h3', { id: 'lect-pj-t', text: 'Pièces jointes (' + utiles.length + ')' }), ul));
|
||||||
|
}
|
||||||
|
if (signature.length) {
|
||||||
|
var us = h('ul');
|
||||||
|
signature.forEach(function (p) { us.appendChild(h('li', null, icone('pj', 18), h('span', { class: 'nom coupe', title: p.nom, text: p.nom }), h('span', { class: 'info', text: tailleLisible(p.taille) }))); });
|
||||||
|
cont.appendChild(h('details', { class: 'lect-histo lect-sig' }, h('summary', null, 'Images intégrées au message (' + signature.length + ')'), us));
|
||||||
|
}
|
||||||
|
cont.appendChild(h('p', { class: 'lect-note', text: 'Lecture seule : le mail n\'est pas modifié dans votre messagerie.' }));
|
||||||
|
}
|
||||||
|
function lireMail(m) {
|
||||||
|
var c = S.cats.find(function (x) { return x.nom === m.cat; });
|
||||||
|
ouvrir(function (clore) {
|
||||||
|
var defil = h('div', { class: 'lect-scroll', tabindex: '0', 'data-focus': '', role: 'region', 'aria-label': 'Contenu du mail' });
|
||||||
|
var boite = h('section', { class: 'boite lecture', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'lect-t' },
|
||||||
|
h('div', { class: 'lect-tete' }, h('h2', { id: 'lect-t', text: m.objet || '(sans objet)' }),
|
||||||
|
h('button', { type: 'button', class: 'btn-icone', 'aria-label': 'Fermer la lecture', onclick: clore }, icone('fermer'))),
|
||||||
|
defil);
|
||||||
|
function charger() {
|
||||||
|
defil.textContent = ''; defil.setAttribute('aria-busy', 'true'); defil.focus();
|
||||||
|
defil.appendChild(h('div', { class: 'lect-etat', role: 'status' }, h('p', { text: 'Ouverture du mail…' }), h('span', { class: 'lect-sq' }), h('span', { class: 'lect-sq court' }), h('span', { class: 'lect-sq' })));
|
||||||
|
api('/mail?id=' + encodeURIComponent(m.id)).then(function (r) {
|
||||||
|
if (!document.body.contains(boite)) return;
|
||||||
|
defil.removeAttribute('aria-busy'); defil.textContent = '';
|
||||||
|
afficherMail(defil, m, r, c);
|
||||||
|
}).catch(function (e) {
|
||||||
|
if (e.message === 'session' || !document.body.contains(boite)) return;
|
||||||
|
defil.removeAttribute('aria-busy'); defil.textContent = '';
|
||||||
|
defil.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Lecture du mail impossible'),
|
||||||
|
h('p', null, 'Le service de lecture n\'a pas répondu. Le mail reste intact dans votre messagerie.'),
|
||||||
|
h('button', { type: 'button', class: 'btn-plein', onclick: charger }, 'Réessayer')));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
charger();
|
||||||
|
return boite;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function reperes(m) {
|
||||||
|
if (!m.etiquettes || !m.etiquettes.length) return null;
|
||||||
|
var d = h('div', { class: 'etqs', 'aria-label': 'Étiquettes du miroir' });
|
||||||
|
m.etiquettes.forEach(function (t) { d.appendChild(h('span', { class: 'etq', text: t })); });
|
||||||
|
return d;
|
||||||
|
}
|
||||||
function ligneMail(m) {
|
function ligneMail(m) {
|
||||||
var orig = m.source === 'manuel' ? 'manuel' : (m.cat === SYSTEME ? 'sans règle' : 'règle');
|
var orig = m.source === 'manuel' ? 'manuel' : (m.cat === SYSTEME ? 'sans règle' : 'règle');
|
||||||
var origCls = orig === 'manuel' ? ' manuel' : orig === 'sans règle' ? ' sansregle' : '';
|
var origCls = orig === 'manuel' ? ' manuel' : orig === 'sans règle' ? ' sansregle' : '';
|
||||||
var objetAff = m.objet || '(sans objet)';
|
var objetAff = m.objet || '(sans objet)';
|
||||||
var etq = 'Traité : ' + m.exp + ', ' + (m.objet || 'sans objet');
|
var etq = 'Traité : ' + m.exp + ', ' + (m.objet || 'sans objet');
|
||||||
|
var libLire = 'Lire le mail de ' + m.exp + ' : ' + (m.objet || 'sans objet');
|
||||||
var cb = h('input', { type: 'checkbox', 'aria-label': etq, onchange: function (e) { basculerTraite(m, e.target.checked); } });
|
var cb = h('input', { type: 'checkbox', 'aria-label': etq, onchange: function (e) { basculerTraite(m, e.target.checked); } });
|
||||||
cb.checked = m.traite;
|
cb.checked = m.traite;
|
||||||
return h('div', { class: 'ligne' + (m.traite ? ' fait' : ''), role: 'listitem' },
|
return h('div', { class: 'ligne' + (m.traite ? ' fait' : ''), role: 'listitem' },
|
||||||
h('label', { class: 'coche' }, cb),
|
h('label', { class: 'coche' }, cb),
|
||||||
h('div', { class: 'corps d' }, h('div', { class: 'exp coupe', title: m.expBrut, text: m.exp })),
|
h('div', { class: 'corps d' }, h('div', { class: 'exp coupe', title: m.expBrut, text: m.exp })),
|
||||||
h('div', { class: 'corps d' }, h('div', { class: 'objet coupe' + (m.objet ? '' : ' sans'), text: objetAff })),
|
h('div', { class: 'corps d' }, h('button', { type: 'button', class: 'lire', 'aria-label': libLire, onclick: function () { lireMail(m); } }, h('span', { class: 'objet coupe' + (m.objet ? '' : ' sans'), text: objetAff })), reperes(m)),
|
||||||
h('div', { class: 'heure d', text: heureTunis(m.date) }),
|
h('div', { class: 'heure d', text: heureTunis(m.date) }),
|
||||||
h('div', { class: 'd' }, h('span', { class: 'origine' + origCls, text: orig })),
|
h('div', { class: 'd' }, h('span', { class: 'origine' + origCls, text: orig })),
|
||||||
h('div', { class: 'm-corps' },
|
h('div', { class: 'm-corps' },
|
||||||
h('div', { class: 'exp coupe', title: m.expBrut, text: m.exp }), h('div', { class: 'objet coupe' + (m.objet ? '' : ' sans'), text: objetAff }),
|
h('button', { type: 'button', class: 'lire', 'aria-label': libLire, onclick: function () { lireMail(m); } },
|
||||||
h('div', { class: 'm-meta' }, h('span', { class: 'heure', text: heureTunis(m.date) }), ' · ', h('span', { class: 'o' + (orig === 'manuel' ? ' manuel' : ''), text: orig }))),
|
h('span', { class: 'exp coupe', title: m.expBrut, text: m.exp }), h('span', { class: 'objet coupe' + (m.objet ? '' : ' sans'), text: objetAff }),
|
||||||
selecteur(m));
|
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),
|
||||||
|
boutonSuivre(m));
|
||||||
}
|
}
|
||||||
function vueTri() {
|
function vueTri() {
|
||||||
var frag = document.createDocumentFragment();
|
var frag = document.createDocumentFragment();
|
||||||
@@ -333,7 +519,7 @@
|
|||||||
var tous = S.mails, nbT = tous.filter(function (m) { return m.traite; }).length;
|
var tous = S.mails, nbT = tous.filter(function (m) { return m.traite; }).length;
|
||||||
var compte = {}; tous.forEach(function (m) { compte[m.cat] = (compte[m.cat] || 0) + 1; });
|
var compte = {}; tous.forEach(function (m) { compte[m.cat] = (compte[m.cat] || 0) + 1; });
|
||||||
var puces = h('div', { class: 'puces', role: 'group', 'aria-label': 'Filtrer par catégorie' });
|
var puces = h('div', { class: 'puces', role: 'group', 'aria-label': 'Filtrer par catégorie' });
|
||||||
var defs = [{ nom: 'Tous', c: -1, n: tous.length, filtre: null }].concat(S.cats.map(function (c) { return { nom: c.nom, c: couleur(c.nom, c.id), n: compte[c.nom] || 0, filtre: c.nom }; }));
|
var defs = [{ nom: 'Tous', c: -1, n: tous.length, filtre: null }].concat(S.cats.map(function (c, i) { return { nom: c.nom, c: couleur(c.nom, c.id), n: compte[c.nom] || 0, filtre: c.nom, rang: i }; }).sort(function (x, y) { return y.n - x.n || x.rang - y.rang; }));
|
||||||
defs.forEach(function (p) {
|
defs.forEach(function (p) {
|
||||||
var actif = S.filtre === p.filtre;
|
var actif = S.filtre === p.filtre;
|
||||||
puces.appendChild(h('button', { type: 'button', 'aria-pressed': actif ? 'true' : 'false', class: 'puce' + (p.c === 0 ? ' vide' : '') + (p.c > 0 ? ' t' + p.c : ''), onclick: function () { S.filtre = actif ? null : p.filtre; rendre(); } },
|
puces.appendChild(h('button', { type: 'button', 'aria-pressed': actif ? 'true' : 'false', class: 'puce' + (p.c === 0 ? ' vide' : '') + (p.c > 0 ? ' t' + p.c : ''), onclick: function () { S.filtre = actif ? null : p.filtre; rendre(); } },
|
||||||
@@ -353,7 +539,7 @@
|
|||||||
var visibles = tous.filter(function (m) { return !S.filtre || m.cat === S.filtre; });
|
var visibles = tous.filter(function (m) { return !S.filtre || m.cat === S.filtre; });
|
||||||
var liste = h('div', { role: 'list' });
|
var liste = h('div', { role: 'list' });
|
||||||
var carte = h('section', { class: 'carte', 'aria-label': 'Mails du jour' });
|
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)); });
|
visibles.forEach(function (m) { liste.appendChild(ligneMail(m)); });
|
||||||
carte.appendChild(liste);
|
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) + '.')));
|
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) + '.')));
|
||||||
@@ -409,6 +595,397 @@
|
|||||||
frag.appendChild(h('p', { class: 'note' }, 'Une règle activée s\'applique aux mails du jour qui n\'ont pas été corrigés à la main.'));
|
frag.appendChild(h('p', { class: 'note' }, 'Une règle activée s\'applique aux mails du jour qui n\'ont pas été corrigés à la main.'));
|
||||||
return frag;
|
return frag;
|
||||||
}
|
}
|
||||||
|
function vueGroupes() {
|
||||||
|
var G = S.groupe, frag = document.createDocumentFragment();
|
||||||
|
frag.appendChild(h('header', { class: 'entete' }, h('div', null, h('h1', null, 'Groupes'), h('div', { class: 'maj' }, 'Un seul groupe, sur plusieurs jours · heure de Tunis'))));
|
||||||
|
if (S.notif) frag.appendChild(h('div', { class: 'notif', role: 'status', text: S.notif }));
|
||||||
|
var per = h('div', { class: 'puces', role: 'group', 'aria-label': 'Période' });
|
||||||
|
[[7, '7 jours'], [30, '30 jours']].forEach(function (p) {
|
||||||
|
per.appendChild(h('button', { type: 'button', class: 'puce', 'aria-pressed': G.jours === p[0] ? 'true' : 'false', onclick: function () { if (G.jours !== p[0]) { G.jours = p[0]; chargerGroupe(); } } }, h('span', { text: p[1] })));
|
||||||
|
});
|
||||||
|
frag.appendChild(h('section', { class: 'carte repartition', 'aria-label': 'Choisir un groupe' }, h('h2', null, 'Période'), per));
|
||||||
|
if (G.etat === 'erreur') {
|
||||||
|
frag.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Lecture du courrier impossible'), h('p', null, 'Le service de lecture n\'a pas répondu.'), h('button', { type: 'button', class: 'btn-plein', onclick: chargerGroupe }, 'Réessayer')));
|
||||||
|
return frag;
|
||||||
|
}
|
||||||
|
if (G.etat === 'chargement') { frag.appendChild(h('section', { class: 'carte squelette', 'aria-busy': 'true' }, h('div', { class: 'sq-statut', role: 'status', text: 'Lecture des ' + G.jours + ' derniers jours…' }))); return frag; }
|
||||||
|
if (G.miroirErreur) frag.appendChild(h('div', { class: 'bandeau', role: 'status' }, h('div', { class: 'txt' }, 'Lecture du courrier momentanément indisponible')));
|
||||||
|
var cc = {}, ce = {};
|
||||||
|
G.mails.forEach(function (m) { cc[m.cat] = (cc[m.cat] || 0) + 1; (m.etiquettes || []).forEach(function (t) { ce[t] = (ce[t] || 0) + 1; }); });
|
||||||
|
var pc = h('div', { class: 'puces', role: 'group', 'aria-label': 'Catégorie' });
|
||||||
|
S.cats.map(function (c, i) { return { c: c, rang: i }; }).sort(function (x, y) { return (cc[y.c.nom] || 0) - (cc[x.c.nom] || 0) || x.rang - y.rang; }).forEach(function (o) {
|
||||||
|
var c = o.c, k = couleur(c.nom, c.id), actif = G.cat === c.nom;
|
||||||
|
pc.appendChild(h('button', { type: 'button', 'aria-pressed': actif ? 'true' : 'false', class: 'puce' + (k === 0 ? ' vide' : '') + (k > 0 ? ' t' + k : ''), onclick: function () { G.cat = actif ? null : c.nom; rendre(); } },
|
||||||
|
h('span', { class: 'pt c' + k, 'aria-hidden': 'true' }), h('span', { text: c.nom }), h('span', { class: 'n', text: d2(cc[c.nom] || 0) })));
|
||||||
|
});
|
||||||
|
var pe = h('div', { class: 'puces', role: 'group', 'aria-label': 'Étiquette du miroir' });
|
||||||
|
Object.keys(ce).sort(function (a, b) { return ce[b] - ce[a] || a.localeCompare(b); }).forEach(function (t) {
|
||||||
|
var actif = G.etq === t;
|
||||||
|
pe.appendChild(h('button', { type: 'button', 'aria-pressed': actif ? 'true' : 'false', class: 'puce', onclick: function () { G.etq = actif ? null : t; rendre(); } }, h('span', { text: t }), h('span', { class: 'n', text: d2(ce[t]) })));
|
||||||
|
});
|
||||||
|
frag.appendChild(h('section', { class: 'carte repartition', 'aria-label': 'Groupes' }, h('h2', null, 'Catégorie'), pc, h('h2', null, 'Étiquette du miroir'), pe));
|
||||||
|
if (!G.cat && !G.etq) {
|
||||||
|
frag.appendChild(h('section', { class: 'carte' }, h('div', { class: 'etat' }, icone('groupes', 28), h('h2', null, 'Choisissez un groupe'), h('p', null, G.mails.length + ' mails sur ' + G.jours + ' jours. Touchez une catégorie ou une étiquette pour ne voir que celle-ci.'))));
|
||||||
|
return frag;
|
||||||
|
}
|
||||||
|
var vis = G.mails.filter(function (m) { return (!G.cat || m.cat === G.cat) && (!G.etq || (m.etiquettes || []).indexOf(G.etq) !== -1); });
|
||||||
|
var titreG = [G.cat, G.etq].filter(Boolean).join(' + ');
|
||||||
|
if (!vis.length) {
|
||||||
|
frag.appendChild(h('section', { class: 'carte' }, h('div', { class: 'etat-filtre' }, 'Aucun mail dans « ' + titreG + ' » sur ' + G.jours + ' jours.', h('button', { type: 'button', class: 'btn-lien', onclick: function () { G.cat = null; G.etq = null; rendre(); } }, 'Changer de groupe'))));
|
||||||
|
return frag;
|
||||||
|
}
|
||||||
|
frag.appendChild(h('h2', { class: 'titre-groupe', text: titreG + ' · ' + vis.length + (vis.length > 1 ? ' mails' : ' mail') }));
|
||||||
|
var jours = [], par = {};
|
||||||
|
vis.forEach(function (m) { var j = String(m.date).slice(0, 10); if (!par[j]) { par[j] = []; jours.push(j); } par[j].push(m); });
|
||||||
|
jours.forEach(function (j) {
|
||||||
|
var carte = h('section', { class: 'carte', 'aria-label': nomJour(j) + ' ' + fr(j) });
|
||||||
|
carte.appendChild(h('div', { class: 'jour-titre' }, h('span', { text: nomJour(j) + ' ' + fr(j) }), h('span', { class: 'nb', text: par[j].length + (par[j].length > 1 ? ' mails' : ' mail') })));
|
||||||
|
var liste = h('div', { role: 'list' }); par[j].forEach(function (m) { liste.appendChild(ligneMail(m)); });
|
||||||
|
carte.appendChild(liste); frag.appendChild(carte);
|
||||||
|
});
|
||||||
|
return frag;
|
||||||
|
}
|
||||||
|
/* ---------- Courses pour Tunis ---------- */
|
||||||
|
var SENS = { tunis_sfax: 'Tunis vers Sfax', sfax_tunis: 'Sfax vers Tunis' };
|
||||||
|
function chargerCourses() {
|
||||||
|
var C = S.courses; C.etat = 'chargement'; rendre();
|
||||||
|
return api('/courses/synchroniser', { method: 'POST' }).catch(function (e) { if (e.message === 'session') throw e; return null; }).then(function (sy) { return api('/courses?statut=toutes').then(function (r) { C.liste = r.courses || []; C.etat = 'ok'; rendre(); if (sy && sy.ajoutees) flash(sy.ajoutees === 1 ? '1 course ajoutée depuis vos mails Tunis.' : sy.ajoutees + ' courses ajoutées depuis vos mails Tunis.'); }); })
|
||||||
|
.catch(function (e) { if (e.message === 'session') return; C.etat = 'erreur'; rendre(); });
|
||||||
|
}
|
||||||
|
function exporterCourses() {
|
||||||
|
var C = S.courses; annoncer('Préparation du fichier');
|
||||||
|
fetch(API + '/courses/export?statut=' + C.filtre, { credentials: 'same-origin', redirect: 'manual' }).then(function (rep) {
|
||||||
|
if (rep.type === 'opaqueredirect') { sessionExpiree(); throw new Error('session'); }
|
||||||
|
if (!rep.ok) throw new Error('Export impossible pour le moment.');
|
||||||
|
return rep.blob();
|
||||||
|
}).then(function (blob) {
|
||||||
|
var url = URL.createObjectURL(blob), a = document.createElement('a');
|
||||||
|
a.href = url; a.download = 'Courses-pour-Tunis-' + auj() + '.xlsx'; document.body.appendChild(a); a.click(); a.remove();
|
||||||
|
setTimeout(function () { URL.revokeObjectURL(url); }, 4000); flash('Fichier prêt : Courses-pour-Tunis-' + auj() + '.xlsx');
|
||||||
|
}).catch(function (e) { if (e.message !== 'session') flash(e.message); });
|
||||||
|
}
|
||||||
|
function basculerCourse(k, faite) {
|
||||||
|
var avant = k.statut; k.statut = faite ? 'faite' : 'a_faire'; rendre();
|
||||||
|
api('/courses/' + k.id, { method: 'PATCH', body: { statut: k.statut } }).then(function (r) { k.fait_le = r.fait_le; annoncer(faite ? 'Course faite' : 'Course à faire'); })
|
||||||
|
.catch(function (e) { k.statut = avant; rendre(); if (e.message !== 'session') flash('Modification impossible. Réessayez.'); });
|
||||||
|
}
|
||||||
|
function dialogueCourse(course, mail) {
|
||||||
|
var nouveau = !course;
|
||||||
|
ouvrir(function (clore) {
|
||||||
|
var champ = h('input', { id: 'crs-dem', type: 'text', maxlength: '300', 'data-focus': '', autocomplete: 'off', value: course ? course.demande : (mail && mail.objet_mail) || '' });
|
||||||
|
var sens = h('select', { id: 'crs-sens' }, h('option', { value: 'tunis_sfax', text: SENS.tunis_sfax }), h('option', { value: 'sfax_tunis', text: SENS.sfax_tunis }));
|
||||||
|
sens.value = course ? course.sens : 'tunis_sfax';
|
||||||
|
var err = h('div', { class: 'err', role: 'alert' });
|
||||||
|
function enregistrer() {
|
||||||
|
var dem = champ.value.trim();
|
||||||
|
if (!dem) { err.textContent = 'Décrivez la course : objet ou document à rapporter ou à apporter.'; champ.focus(); return; }
|
||||||
|
var req = nouveau ? api('/courses', { method: 'POST', body: Object.assign({ demande: dem, sens: sens.value }, mail || {}) })
|
||||||
|
: api('/courses/' + course.id, { method: 'PATCH', body: { demande: dem, sens: sens.value } });
|
||||||
|
req.then(function () { clore(); if (S.vue === 'courses') return chargerCourses(); }).then(function () { flash(nouveau ? 'Course ajoutée.' : 'Course modifiée.'); })
|
||||||
|
.catch(function (e) { if (e.message !== 'session') err.textContent = 'Enregistrement impossible. Réessayez.'; });
|
||||||
|
}
|
||||||
|
champ.addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); enregistrer(); } });
|
||||||
|
var acts = h('div', { class: 'acts' }, h('button', { type: 'button', class: 'btn-ligne', onclick: clore }, 'Annuler'),
|
||||||
|
h('button', { type: 'button', class: 'btn-plein', onclick: enregistrer }, nouveau ? 'Ajouter' : 'Enregistrer'));
|
||||||
|
var pied = null;
|
||||||
|
if (course) pied = h('div', { class: 'pave' }, h('button', { type: 'button', class: 'btn-danger-ligne', onclick: function () {
|
||||||
|
api('/courses/' + course.id, { method: 'DELETE' }).then(function () { clore(); return chargerCourses(); }).then(function () { flash('Course supprimée.'); })
|
||||||
|
.catch(function (e) { if (e.message !== 'session') err.textContent = 'Suppression impossible. Réessayez.'; });
|
||||||
|
} }, 'Supprimer la course'));
|
||||||
|
return h('section', { class: 'boite', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'crs-t' },
|
||||||
|
h('h2', { id: 'crs-t' }, nouveau ? 'Nouvelle course pour Tunis' : 'Modifier la course'),
|
||||||
|
mail && mail.objet_mail ? h('p', { class: 'note', text: 'Mail source : ' + mail.objet_mail }) : null,
|
||||||
|
h('div', { class: 'champ' }, h('label', { for: 'crs-dem' }, 'Demande'), champ),
|
||||||
|
h('div', { class: 'champ' }, h('label', { for: 'crs-sens' }, 'Sens'), sens, err), acts, pied);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function vueCourses() {
|
||||||
|
var C = S.courses, frag = document.createDocumentFragment();
|
||||||
|
frag.appendChild(h('header', { class: 'entete' }, h('h1', null, 'Courses pour Tunis'),
|
||||||
|
h('div', { class: 'entete-actions' },
|
||||||
|
h('button', { type: 'button', class: 'btn-ligne', onclick: exporterCourses }, icone('telecharger', 18), 'Exporter en Excel'),
|
||||||
|
h('button', { type: 'button', class: 'btn-plein', onclick: function () { dialogueCourse(null, null); } }, 'Ajouter une course'))));
|
||||||
|
if (S.notif) frag.appendChild(h('div', { class: 'notif', role: 'status', text: S.notif }));
|
||||||
|
if (C.etat === 'erreur') { frag.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Chargement impossible'), h('p', null, 'Les courses n\'ont pas pu être lues.'), h('button', { type: 'button', class: 'btn-plein', onclick: chargerCourses }, 'Réessayer'))); return frag; }
|
||||||
|
if (C.etat === 'chargement') { frag.appendChild(h('section', { class: 'carte squelette', 'aria-busy': 'true' }, h('div', { class: 'sq-statut', role: 'status', text: 'Lecture des courses…' }))); return frag; }
|
||||||
|
var nb = { a_faire: 0, faite: 0, toutes: C.liste.length };
|
||||||
|
C.liste.forEach(function (k) { nb[k.statut] = (nb[k.statut] || 0) + 1; });
|
||||||
|
var pc = h('div', { class: 'puces', role: 'group', 'aria-label': 'Afficher' });
|
||||||
|
[['a_faire', 'À faire'], ['faite', 'Faites'], ['toutes', 'Toutes']].forEach(function (o) {
|
||||||
|
pc.appendChild(h('button', { type: 'button', class: 'puce', 'aria-pressed': C.filtre === o[0] ? 'true' : 'false', onclick: function () { C.filtre = o[0]; rendre(); } }, h('span', { text: o[1] }), h('span', { class: 'n', text: d2(nb[o[0]] || 0) })));
|
||||||
|
});
|
||||||
|
frag.appendChild(h('section', { class: 'carte repartition', 'aria-label': 'Filtre des courses' }, pc));
|
||||||
|
var vis = C.liste.filter(function (k) { return C.filtre === 'toutes' || k.statut === C.filtre; });
|
||||||
|
if (!vis.length) {
|
||||||
|
frag.appendChild(h('section', { class: 'carte' }, h('div', { class: 'etat' }, icone('courses', 28), h('h2', null, C.liste.length ? 'Rien dans cette liste' : 'Aucune course pour le moment'),
|
||||||
|
h('p', null, C.liste.length ? 'Changez de filtre pour voir les autres courses.' : 'Les mails classés Tunis des 14 derniers jours s\'ajoutent ici automatiquement. Vous pouvez aussi ajouter une course à la main.'))));
|
||||||
|
return frag;
|
||||||
|
}
|
||||||
|
var carte = h('section', { class: 'carte', 'aria-label': 'Courses' }), liste = h('div', { role: 'list' });
|
||||||
|
vis.forEach(function (k) {
|
||||||
|
var coche = h('input', { type: 'checkbox', 'aria-label': (k.statut === 'faite' ? 'Remettre à faire : ' : 'Marquer comme faite : ') + k.demande });
|
||||||
|
coche.checked = k.statut === 'faite';
|
||||||
|
coche.addEventListener('change', function () { basculerCourse(k, coche.checked); });
|
||||||
|
var meta = [SENS[k.sens] || ''];
|
||||||
|
if (k.date_mail) meta.push('mail du ' + fr(String(k.date_mail).slice(0, 10)));
|
||||||
|
if (k.expediteur) meta.push(nomExp(k.expediteur));
|
||||||
|
if (k.statut === 'faite' && k.fait_le) meta.push('faite le ' + fr(String(k.fait_le).slice(0, 10)));
|
||||||
|
var actions = h('div', { class: 'course-actions' });
|
||||||
|
if (k.message_id) actions.appendChild(h('button', { type: 'button', class: 'btn-petit', 'aria-label': 'Lire le mail de : ' + k.demande, onclick: function () { lireMail({ id: k.message_id, objet: k.objet_mail || k.demande, exp: nomExp(k.expediteur || ''), expBrut: k.expediteur || '', date: k.date_mail || '', cat: '', etiquettes: [] }); } }, 'Lire le mail'));
|
||||||
|
actions.appendChild(h('button', { type: 'button', class: 'btn-petit', 'aria-label': 'Modifier : ' + k.demande, onclick: function () { dialogueCourse(k, null); } }, 'Modifier'));
|
||||||
|
liste.appendChild(h('div', { class: 'course' + (k.statut === 'faite' ? ' faite' : ''), role: 'listitem' },
|
||||||
|
h('label', { class: 'coche' }, coche),
|
||||||
|
h('div', { class: 'course-corps' }, h('div', { class: 'dem', text: k.demande }), h('div', { class: 'meta', text: meta.filter(Boolean).join(' · ') })),
|
||||||
|
actions));
|
||||||
|
});
|
||||||
|
carte.appendChild(liste); frag.appendChild(carte); return frag;
|
||||||
|
}
|
||||||
|
/* ---------- Suivi des demandes ---------- */
|
||||||
|
var ETATS_SUIVI = [['attente', 'En attente de réponse'], ['reponse', 'Réponses reçues'], ['a_repondre', 'À répondre'], ['clos', 'Clos']];
|
||||||
|
function chargerSuivi() {
|
||||||
|
var V = S.suivi; V.etat = 'chargement'; rendre();
|
||||||
|
return api('/suivi?jours=' + V.jours).then(function (r) { V.items = r.items || []; V.compte = r.compte || {}; V.envoyesJusqu = r.envoyes_jusqu_au || ''; V.envoyesAJour = r.envoyes_a_jour !== false; V.etat = 'ok'; rendre(); })
|
||||||
|
.catch(function (e) { if (e.message === 'session') return; V.etat = 'erreur'; rendre(); });
|
||||||
|
}
|
||||||
|
function cloreSuivi(it, clore) {
|
||||||
|
var req = clore ? api('/suivi/clore', { method: 'POST', body: { cle: it.cle, dernier_id: it.dernier_id } }) : api('/suivi/rouvrir', { method: 'POST', body: { cle: it.cle } });
|
||||||
|
req.then(function () { it.clos = clore; var c = S.suivi.compte; c[it.etat] = (c[it.etat] || 0) + (clore ? -1 : 1); c.clos = (c.clos || 0) + (clore ? 1 : -1); rendre(); annoncer(clore ? 'Suivi clos' : 'Suivi rouvert'); })
|
||||||
|
.catch(function (e) { if (e.message !== 'session') flash('Modification impossible. Réessayez.'); });
|
||||||
|
}
|
||||||
|
function dureeLisible(j) { return j <= 0 ? 'aujourd\'hui' : j === 1 ? 'hier' : 'il y a ' + j + ' jours'; }
|
||||||
|
function vueSuivi() {
|
||||||
|
var V = S.suivi, frag = document.createDocumentFragment();
|
||||||
|
frag.appendChild(h('header', { class: 'entete' }, h('h1', null, 'Suivi des demandes')));
|
||||||
|
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 du courrier impossible'), h('p', null, 'Le suivi n\'a pas pu être calculé.'), h('button', { type: 'button', class: 'btn-plein', onclick: chargerSuivi }, 'Réessayer'))); return frag; }
|
||||||
|
var per = h('div', { class: 'puces', role: 'group', 'aria-label': 'Période' });
|
||||||
|
[7, 14, 30].forEach(function (j) { per.appendChild(h('button', { type: 'button', class: 'puce', 'aria-pressed': V.jours === j ? 'true' : 'false', onclick: function () { V.jours = j; chargerSuivi(); } }, h('span', { text: j + ' jours' }))); });
|
||||||
|
frag.appendChild(h('section', { class: 'carte repartition', 'aria-label': 'Période du suivi' }, h('h2', null, 'Période'), per));
|
||||||
|
if (V.etat === 'chargement') { frag.appendChild(h('section', { class: 'carte squelette', 'aria-busy': 'true' }, h('div', { class: 'sq-statut', role: 'status', text: 'Calcul du suivi sur ' + V.jours + ' jours…' }))); return frag; }
|
||||||
|
if (!V.envoyesAJour) frag.appendChild(h('div', { class: 'bandeau', role: 'status' }, h('div', { class: 'txt' }, 'Les messages envoyés ne sont lus que jusqu\'au ' + (V.envoyesJusqu ? fr(V.envoyesJusqu) : 'une date inconnue') + ' : les réponses envoyées depuis ne sont pas prises en compte.')));
|
||||||
|
var pc = h('div', { class: 'puces', role: 'group', 'aria-label': 'Afficher' });
|
||||||
|
ETATS_SUIVI.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 du suivi' }, h('h2', null, 'Afficher'), pc));
|
||||||
|
var vis = V.items.filter(function (i) { return V.filtre === 'clos' ? i.clos : (!i.clos && i.etat === V.filtre); });
|
||||||
|
if (!vis.length) {
|
||||||
|
frag.appendChild(h('section', { class: 'carte' }, h('div', { class: 'etat' }, icone('suivi', 28), h('h2', null, 'Rien dans cette liste'), h('p', null, 'Aucune demande dans « ' + ETATS_SUIVI.filter(function (o) { return o[0] === V.filtre; })[0][1] + ' » sur ' + V.jours + ' jours.'))));
|
||||||
|
return frag;
|
||||||
|
}
|
||||||
|
var carte = h('section', { class: 'carte', 'aria-label': 'Demandes' }), liste = h('div', { role: 'list' });
|
||||||
|
vis.forEach(function (it) {
|
||||||
|
var qui = it.etat === 'attente' ? 'À : ' : 'De : ';
|
||||||
|
var badges = h('div', { class: 'course-badges' });
|
||||||
|
if (it.relancer && !it.clos) badges.appendChild(h('span', { class: 'etq relance', text: 'À relancer' }));
|
||||||
|
var actions = h('div', { class: 'course-actions' },
|
||||||
|
h('button', { type: 'button', class: 'btn-petit', 'aria-label': 'Lire le mail : ' + it.sujet, onclick: function () { lireMail({ id: it.dernier_id, objet: it.sujet, exp: it.avec, expBrut: it.avec, date: it.date || '', cat: '', etiquettes: [] }); } }, 'Lire le mail'),
|
||||||
|
h('button', { type: 'button', class: 'btn-petit', 'aria-label': (it.clos ? 'Rouvrir : ' : 'Clore : ') + it.sujet, onclick: function () { cloreSuivi(it, !it.clos); } }, it.clos ? 'Rouvrir' : 'Clore'));
|
||||||
|
liste.appendChild(h('div', { class: 'course', role: 'listitem' },
|
||||||
|
h('div', { class: 'course-corps' }, h('div', { class: 'dem', text: it.sujet || '(sans objet)' }),
|
||||||
|
h('div', { class: 'meta', text: [qui + (it.avec || 'inconnu'), dureeLisible(it.jours), it.nb > 1 ? it.nb + ' messages' : '1 message'].join(' · ') }), badges),
|
||||||
|
actions));
|
||||||
|
});
|
||||||
|
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 supprimerDefinitivement(ids, texte) {
|
||||||
|
return api('/a-suivre/supprimer', { method: 'POST', body: { ids: ids } }).then(function () {
|
||||||
|
flash(texte); annoncer(texte);
|
||||||
|
return chargerASuivre(true);
|
||||||
|
}).catch(function (e) { if (e.message !== 'session') flash('La suppression 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));
|
||||||
|
if (!actif) {
|
||||||
|
entete.appendChild(h('button', { type: 'button', class: 'btn-ligne btn-danger', 'aria-label': 'Tout supprimer définitivement : ' + cat + ', ' + nb, onclick: function () {
|
||||||
|
if (!window.confirm('Supprimer définitivement ' + (liste.length > 1 ? 'ces ' + liste.length + ' mails' : 'ce mail') + ' de l\'historique « ' + cat + ' » ?\nLes mails eux-mêmes ne sont pas touchés.')) return;
|
||||||
|
supprimerDefinitivement(ids, liste.length + (liste.length > 1 ? ' mails supprimés' : ' mail supprimé') + ' de l\'historique.');
|
||||||
|
} }, 'Tout supprimer'));
|
||||||
|
}
|
||||||
|
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'),
|
||||||
|
actif ? null : h('button', { type: 'button', class: 'btn-petit btn-danger', 'aria-label': 'Supprimer définitivement : ' + objet, onclick: function () { supprimerDefinitivement([it.message_id], 'Mail supprimé de l\'historique.'); } }, 'Supprimer'))));
|
||||||
|
});
|
||||||
|
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() {
|
||||||
|
var R = S.recherche, q = R.q.trim();
|
||||||
|
if (q.length < 2) { R.etat = 'court'; rendre(); var c0 = document.getElementById('rech-q'); if (c0) c0.focus(); return; }
|
||||||
|
var url = '/recherche?q=' + encodeURIComponent(q), a = auj();
|
||||||
|
if (R.periode === '30' || R.periode === '90') url += '&depuis=' + versISO(new Date(dateUTC(a).getTime() - (+R.periode) * 86400000));
|
||||||
|
if (R.periode === 'annee') url += '&depuis=' + a.slice(0, 4) + '-01-01';
|
||||||
|
R.etat = 'chargement'; R.cherche = q; rendre();
|
||||||
|
api(url).then(function (r) { R.resultats = r.resultats || []; R.plafond = !!r.plafond; R.etat = 'ok'; rendre(); annoncer(R.resultats.length + (R.resultats.length > 1 ? ' résultats' : ' résultat')); })
|
||||||
|
.catch(function (e) { if (e.message === 'session') return; R.etat = 'erreur'; rendre(); });
|
||||||
|
}
|
||||||
|
function vueRecherche() {
|
||||||
|
var R = S.recherche, frag = document.createDocumentFragment();
|
||||||
|
frag.appendChild(h('header', { class: 'entete' }, h('h1', null, 'Recherche')));
|
||||||
|
var champ = h('input', { id: 'rech-q', type: 'search', maxlength: '100', autocomplete: 'off', enterkeyhint: 'search', value: R.q, placeholder: 'Mot, expéditeur, numéro de marché…' });
|
||||||
|
champ.addEventListener('input', function () { R.q = champ.value; });
|
||||||
|
var sel = h('select', { id: 'rech-p', 'aria-label': 'Période' });
|
||||||
|
PERIODES.forEach(function (o) { var op = h('option', { value: o[0], text: o[1] }); if (R.periode === o[0]) op.selected = true; sel.appendChild(op); });
|
||||||
|
sel.addEventListener('change', function () { R.periode = sel.value; });
|
||||||
|
var form = h('form', { class: 'carte recherche-form', role: 'search', 'aria-label': 'Rechercher dans le courrier' },
|
||||||
|
h('div', { class: 'champ' }, h('label', { for: 'rech-q' }, 'Rechercher'), champ),
|
||||||
|
h('div', { class: 'champ' }, h('label', { for: 'rech-p' }, 'Période'), sel),
|
||||||
|
h('button', { type: 'submit', class: 'btn-plein' }, 'Rechercher'));
|
||||||
|
form.addEventListener('submit', function (e) { e.preventDefault(); lancerRecherche(); });
|
||||||
|
frag.appendChild(form);
|
||||||
|
if (R.etat === 'repos') { frag.appendChild(h('section', { class: 'carte' }, h('div', { class: 'etat' }, icone('recherche', 28), h('h2', null, 'Retrouvez un mail'), h('p', null, 'Tapez un mot, un nom d\'expéditeur ou un numéro de marché. La recherche ignore les accents et les majuscules.')))); return frag; }
|
||||||
|
if (R.etat === 'court') { frag.appendChild(h('div', { class: 'notif', role: 'alert', text: 'Saisissez au moins 2 caractères.' })); return frag; }
|
||||||
|
if (R.etat === 'chargement') { frag.appendChild(h('section', { class: 'carte squelette', 'aria-busy': 'true' }, h('div', { class: 'sq-statut', role: 'status', text: 'Recherche de « ' + R.cherche + ' »…' }))); return frag; }
|
||||||
|
if (R.etat === 'erreur') { frag.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Recherche impossible'), h('p', null, 'Le service de lecture n\'a pas répondu.'), h('button', { type: 'button', class: 'btn-plein', onclick: lancerRecherche }, 'Réessayer'))); return frag; }
|
||||||
|
var avecPj = h('input', { type: 'checkbox', id: 'rech-pj' }); avecPj.checked = R.avecPj;
|
||||||
|
avecPj.addEventListener('change', function () { R.avecPj = avecPj.checked; rendre(); var c = document.getElementById('rech-pj'); if (c) c.focus(); });
|
||||||
|
var vis = R.resultats.filter(function (x) { return !R.avecPj || x.pj; });
|
||||||
|
frag.appendChild(h('section', { class: 'carte repartition', 'aria-label': 'Résultats' },
|
||||||
|
h('h2', null, vis.length + (vis.length > 1 ? ' résultats' : ' résultat') + ' pour « ' + R.cherche + ' »'),
|
||||||
|
h('label', { class: 'recherche-pj' }, avecPj, h('span', { text: 'Avec pièces jointes seulement' }))));
|
||||||
|
if (R.plafond) frag.appendChild(h('div', { class: 'bandeau', role: 'status' }, h('div', { class: 'txt' }, 'Les 100 premiers résultats sont affichés : précisez le mot ou la période pour affiner.')));
|
||||||
|
if (!vis.length) { frag.appendChild(h('section', { class: 'carte' }, h('div', { class: 'etat' }, icone('recherche', 28), h('h2', null, 'Aucun mail trouvé'), h('p', null, 'Essayez un autre mot, moins de mots, ou élargissez la période.')))); return frag; }
|
||||||
|
var jours = [], par = {};
|
||||||
|
vis.forEach(function (x) { var d = String(x.date).slice(0, 10); if (!par[d]) { par[d] = []; jours.push(d); } par[d].push(x); });
|
||||||
|
jours.forEach(function (d) {
|
||||||
|
var carte = h('section', { class: 'carte', 'aria-label': nomJour(d) + ' ' + fr(d) });
|
||||||
|
carte.appendChild(h('div', { class: 'jour-titre' }, h('span', { text: nomJour(d) + ' ' + fr(d) }), h('span', { class: 'nb', text: par[d].length + (par[d].length > 1 ? ' mails' : ' mail') })));
|
||||||
|
var liste = h('div', { role: 'list' });
|
||||||
|
par[d].forEach(function (x) {
|
||||||
|
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'), boutonSuivreRecherche(x))));
|
||||||
|
});
|
||||||
|
carte.appendChild(liste); frag.appendChild(carte);
|
||||||
|
});
|
||||||
|
return frag;
|
||||||
|
}
|
||||||
function vueBientot(k) {
|
function vueBientot(k) {
|
||||||
var t = BIENTOT[k];
|
var t = BIENTOT[k];
|
||||||
return h('div', null, h('header', { class: 'entete' }, h('h1', null, t[0])),
|
return h('div', null, h('header', { class: 'entete' }, h('h1', null, t[0])),
|
||||||
@@ -419,13 +996,14 @@
|
|||||||
var ancre = document.activeElement && document.activeElement.getAttribute && document.activeElement.getAttribute('aria-label');
|
var ancre = document.activeElement && document.activeElement.getAttribute && document.activeElement.getAttribute('aria-label');
|
||||||
rendreNav();
|
rendreNav();
|
||||||
var p = document.getElementById('principal'); p.textContent = '';
|
var p = document.getElementById('principal'); p.textContent = '';
|
||||||
var v = S.vue === 'tri' ? vueTri() : S.vue === 'categories' ? vueCategories() : S.vue === 'regles' ? vueRegles() : 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;
|
p.appendChild(v); p.scrollTop = pos;
|
||||||
var titre = S.vue === 'tri' ? 'Tri du jour' : S.vue === 'categories' ? 'Catégories' : S.vue === 'regles' ? 'Règles' : 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';
|
document.title = titre + ' · Courrier';
|
||||||
if (ancre && !dialogue) { var r = p.querySelector('[aria-label="' + ancre.replace(/"/g, '\\"') + '"]'); if (r && document.activeElement === document.body) r.focus(); }
|
if (ancre && !dialogue) { var r = p.querySelector('[aria-label="' + ancre.replace(/"/g, '\\"') + '"]'); if (r && document.activeElement === document.body) r.focus(); }
|
||||||
}
|
}
|
||||||
|
|
||||||
rendre();
|
rendre();
|
||||||
chargerMails();
|
chargerMails();
|
||||||
|
chargerASuivre(true);
|
||||||
})();
|
})();
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
<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=20261120a">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app" class="coque">
|
<div id="app" class="coque">
|
||||||
@@ -20,6 +20,6 @@
|
|||||||
</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=20261120a"></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 ""))
|
||||||
@@ -4,3 +4,5 @@ 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
|
||||||
@@ -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,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,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,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,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,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"
|
||||||
Reference in new issue
Block a user