feat: brouillon de reponse copiable, briefing, balayage mobile, resume de pieces jointes, apprentissage par exemples, sauvegarde quotidienne, vue Aujourd'hui, references PO/AO, correctif reponses vides des modeles de raisonnement
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XGaEeTZLvHXfYPUNWkgYoi
This commit is contained in:
1 parent
f87c56fee7
commit
054a4d64e8
15 files changed
+721
-19
No files matched your search
+112
-6
@@ -80,7 +80,7 @@ def auto_actif(db_path: Optional[str] = None) -> bool:
|
|||||||
return ia.ia_active(db_path) and _reglage("ia_auto", db_path)
|
return ia.ia_active(db_path) and _reglage("ia_auto", db_path)
|
||||||
|
|
||||||
|
|
||||||
def construire_messages(objet: str, expediteur: str, corps: str, categories: List[str], contexte: str = "") -> list:
|
def construire_messages(objet: str, expediteur: str, corps: str, categories: List[str], contexte: str = "", exemples: str = "") -> list:
|
||||||
defs = "\n".join("- " + c + " : " + DEFINITIONS.get(c, "categorie de Nabil") for c in categories)
|
defs = "\n".join("- " + c + " : " + DEFINITIONS.get(c, "categorie de Nabil") for c in categories)
|
||||||
consigne = (
|
consigne = (
|
||||||
"Tu aides un responsable de la division Supply Chain de Tunisie Telecom (Sfax) a trier son courrier. "
|
"Tu aides un responsable de la division Supply Chain de Tunisie Telecom (Sfax) a trier son courrier. "
|
||||||
@@ -98,6 +98,10 @@ def construire_messages(objet: str, expediteur: str, corps: str, categories: Lis
|
|||||||
"entre Sfax et Tunis. Une demande est reelle seulement si quelqu'un attend une action ou une reponse de Nabil. "
|
"entre Sfax et Tunis. Une demande est reelle seulement si quelqu'un attend une action ou une reponse de Nabil. "
|
||||||
"N'invente rien : si l'information est absente, laisse vide ou null."
|
"N'invente rien : si l'information est absente, laisse vide ou null."
|
||||||
)
|
)
|
||||||
|
if exemples:
|
||||||
|
consigne += ("\nExemples de choix reels de Nabil sur ses propres mails (objet, expediteur, categorie qu'il a retenue ou refusee). "
|
||||||
|
"Ce ne sont pas des regles a appliquer mot pour mot : un meme expediteur ou un meme objet peut relever d'une autre categorie un autre jour, "
|
||||||
|
"decide d'apres le contenu. Inspire-toi de sa facon de ranger :\n" + exemples + "\n")
|
||||||
if contexte:
|
if contexte:
|
||||||
consigne += ("\nLe mail fait partie d'une conversation : un contexte (resumes des mails precedents du meme fil, "
|
consigne += ("\nLe mail fait partie d'une conversation : un contexte (resumes des mails precedents du meme fil, "
|
||||||
"et categorie choisie par Nabil quand elle existe) est fourni. Utilise-le : un fil deja range par Nabil "
|
"et categorie choisie par Nabil quand elle existe) est fourni. Utilise-le : un fil deja range par Nabil "
|
||||||
@@ -158,9 +162,10 @@ def _categories(db_path: Optional[str] = None) -> List[str]:
|
|||||||
|
|
||||||
|
|
||||||
def analyser(objet: str, expediteur: str, corps: str, db_path: Optional[str] = None, contexte: str = "") -> Dict[str, Any]:
|
def analyser(objet: str, expediteur: str, corps: str, db_path: Optional[str] = None, contexte: str = "") -> Dict[str, Any]:
|
||||||
|
exemples = exemples_nabil(db_path)
|
||||||
"""Appelle PrivAiTe. Leve IAIndisponible si le service ne repond pas (aucun repli)."""
|
"""Appelle PrivAiTe. Leve IAIndisponible si le service ne repond pas (aucun repli)."""
|
||||||
cats = _categories(db_path)
|
cats = _categories(db_path)
|
||||||
rep = ia.appeler_privaite(construire_messages(objet, expediteur, corps, cats, contexte), max_tokens=450)
|
rep = ia.appeler_privaite(construire_messages(objet, expediteur, corps, cats, contexte, exemples), max_tokens=1200)
|
||||||
return lire_fiche(rep, cats)
|
return lire_fiche(rep, cats)
|
||||||
|
|
||||||
|
|
||||||
@@ -402,16 +407,109 @@ def decider(message_id: str, type_: str, decision: str, db_path: Optional[str] =
|
|||||||
(f["date"] or "")[:40], db_path=db_path)
|
(f["date"] or "")[:40], db_path=db_path)
|
||||||
conn = _db.get_connection(db_path)
|
conn = _db.get_connection(db_path)
|
||||||
try:
|
try:
|
||||||
_pret_decisions(conn)
|
_pret_decisions(conn); _decisions_pret(conn)
|
||||||
|
valeur = f["categorie"] if type_ == "categorie" else ", ".join(((f["course"] or {}).get("objets") or []) + ((f["course"] or {}).get("documents") or []))
|
||||||
with conn:
|
with conn:
|
||||||
conn.execute("INSERT INTO decisions_ia (message_id, type, decision, le) VALUES (?, ?, ?, ?) "
|
conn.execute("INSERT INTO decisions_ia (message_id, type, decision, le, valeur, objet, expediteur) VALUES (?, ?, ?, ?, ?, ?, ?) "
|
||||||
"ON CONFLICT(message_id, type) DO UPDATE SET decision=excluded.decision, le=excluded.le",
|
"ON CONFLICT(message_id, type) DO UPDATE SET decision=excluded.decision, le=excluded.le, "
|
||||||
(message_id, type_, decision, get_tunis_now_iso()))
|
"valeur=excluded.valeur, objet=excluded.objet, expediteur=excluded.expediteur",
|
||||||
|
(message_id, type_, decision, get_tunis_now_iso(), valeur[:200], _court(f["objet"], 200), _court(f["expediteur"], 120)))
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
return resultat
|
return resultat
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Apprentissage par exemples : les choix de Nabil guident l'IA, sans aucune regle ----------
|
||||||
|
|
||||||
|
def _decisions_pret(conn) -> None:
|
||||||
|
conn.execute("CREATE TABLE IF NOT EXISTS decisions_ia (message_id TEXT NOT NULL, type TEXT NOT NULL, "
|
||||||
|
"decision TEXT NOT NULL, le TEXT NOT NULL, PRIMARY KEY (message_id, type))")
|
||||||
|
cols = {r[1] for r in conn.execute("PRAGMA table_info(decisions_ia)")}
|
||||||
|
for c in ("valeur", "objet", "expediteur"):
|
||||||
|
if c not in cols:
|
||||||
|
conn.execute("ALTER TABLE decisions_ia ADD COLUMN %s TEXT" % c)
|
||||||
|
|
||||||
|
|
||||||
|
def exemples_nabil(db_path: Optional[str] = None, par_categorie: int = 3, maximum: int = 14, refus: int = 4) -> str:
|
||||||
|
"""Quelques classements manuels recents (au plus 3 par categorie) et quelques refus. Objet et expediteur seulement,
|
||||||
|
jamais le corps ; l'ensemble passe par PrivAiTe comme le reste."""
|
||||||
|
conn = _db.get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_decisions_pret(conn)
|
||||||
|
lignes = conn.execute("SELECT categorie, objet, expediteur FROM classements WHERE source='manuel' "
|
||||||
|
"AND categorie<>'À classer' AND objet<>'' ORDER BY horodatage DESC LIMIT 200").fetchall()
|
||||||
|
compte: Dict[str, int] = {}
|
||||||
|
sortie: List[str] = []
|
||||||
|
for cat, obj, exp in lignes:
|
||||||
|
if compte.get(cat, 0) >= par_categorie or len(sortie) >= maximum:
|
||||||
|
continue
|
||||||
|
compte[cat] = compte.get(cat, 0) + 1
|
||||||
|
sortie.append("- %s | %s => %s" % (_court(obj, 90), _court(exp, 50), cat))
|
||||||
|
for val, obj, exp in conn.execute("SELECT valeur, objet, expediteur FROM decisions_ia WHERE type='categorie' "
|
||||||
|
"AND decision='refuser' AND valeur IS NOT NULL ORDER BY le DESC LIMIT ?", (refus,)):
|
||||||
|
sortie.append("- %s | %s => PAS %s (propose puis refuse)" % (_court(obj, 90), _court(exp, 50), val))
|
||||||
|
return "\n".join(sortie)
|
||||||
|
except sqlite3.OperationalError:
|
||||||
|
return ""
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def stats_acceptation(db_path: Optional[str] = None) -> Dict[str, Any]:
|
||||||
|
conn = _db.get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_decisions_pret(conn)
|
||||||
|
cats: Dict[str, Dict[str, int]] = {}
|
||||||
|
tot = {"acceptees": 0, "refusees": 0}
|
||||||
|
for typ, dec, val, n in conn.execute("SELECT type, decision, COALESCE(valeur,''), COUNT(*) FROM decisions_ia GROUP BY 1,2,3"):
|
||||||
|
cle = val if typ == "categorie" and val else ("Courses" if typ == "course" else "Autres")
|
||||||
|
d = cats.setdefault(cle, {"acceptees": 0, "refusees": 0})
|
||||||
|
k = "acceptees" if dec == "accepter" else "refusees"
|
||||||
|
d[k] += n; tot[k] += n
|
||||||
|
return {"total": tot, "categories": cats}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def briefing(jour: Optional[str] = None, db_path: Optional[str] = None) -> Dict[str, Any]:
|
||||||
|
"""Briefing du matin : uniquement des fiches deja produites et des tables locales, aucun appel de modele.
|
||||||
|
Demandes encore ouvertes = demandes reelles des 7 derniers jours dont le mail n'est pas marque traite."""
|
||||||
|
jour = jour or get_tunis_now_iso()[:10]
|
||||||
|
depuis = (_date.fromisoformat(jour) - timedelta(days=7)).isoformat()
|
||||||
|
conn = _db.get_connection(db_path)
|
||||||
|
try:
|
||||||
|
_pret(conn)
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
traites = {r[0] for r in conn.execute("SELECT message_id FROM classements WHERE traite = 1")}
|
||||||
|
ouvertes, echeances = [], []
|
||||||
|
for r in conn.execute("SELECT * FROM analyses_ia WHERE date_mail >= ? ORDER BY date_mail DESC LIMIT 300", (depuis,)):
|
||||||
|
f = _ligne(r)
|
||||||
|
d = f["demande"] or {}
|
||||||
|
if d.get("reelle") and f["message_id"] not in traites:
|
||||||
|
it = {"message_id": f["message_id"], "objet": f["objet"], "expediteur": f["expediteur"],
|
||||||
|
"date": f["date"], "action": d.get("action"), "echeance": d.get("echeance")}
|
||||||
|
ouvertes.append(it)
|
||||||
|
try:
|
||||||
|
courses = [dict(x) for x in conn.execute("SELECT id, demande, sens, statut FROM courses WHERE statut = 'a_faire' ORDER BY id DESC LIMIT 30")]
|
||||||
|
except sqlite3.OperationalError:
|
||||||
|
courses = []
|
||||||
|
try:
|
||||||
|
suivi = [dict(x) for x in conn.execute("SELECT objet, expediteur, marque_le FROM a_suivre WHERE statut = 'actif' ORDER BY marque_le DESC LIMIT 30")]
|
||||||
|
except sqlite3.OperationalError:
|
||||||
|
suivi = []
|
||||||
|
repart = [dict(x) for x in conn.execute(
|
||||||
|
"SELECT categorie, COUNT(*) AS mails, SUM(traite) AS traites FROM classements WHERE date_mail LIKE ? GROUP BY categorie ORDER BY mails DESC", (jour + "%",))]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
def cle(i):
|
||||||
|
e = i["echeance"] or ""
|
||||||
|
return (e[6:] + e[3:5] + e[:2]) if e else "99999999"
|
||||||
|
ouvertes.sort(key=cle)
|
||||||
|
return {"jour": jour, "demandes_ouvertes": ouvertes, "propositions_a_valider": len(a_valider(14, db_path)),
|
||||||
|
"courses_a_faire": courses, "a_suivre_actifs": suivi, "repartition_du_jour": repart}
|
||||||
|
|
||||||
def creer_routeur(mirror_client) -> APIRouter:
|
def creer_routeur(mirror_client) -> APIRouter:
|
||||||
router = APIRouter(prefix="/ia")
|
router = APIRouter(prefix="/ia")
|
||||||
|
|
||||||
@@ -483,6 +581,14 @@ def creer_routeur(mirror_client) -> APIRouter:
|
|||||||
fil = r[0] if r else None
|
fil = r[0] if r else None
|
||||||
return {"fil": bool(fil), "mails": membres_fil(fil, id, None, 12)}
|
return {"fil": bool(fil), "mails": membres_fil(fil, id, None, 12)}
|
||||||
|
|
||||||
|
@router.get("/briefing")
|
||||||
|
def briefing_matin(date: Optional[str] = None):
|
||||||
|
return briefing(date)
|
||||||
|
|
||||||
|
@router.get("/stats")
|
||||||
|
def stats_ia():
|
||||||
|
return stats_acceptation()
|
||||||
|
|
||||||
@router.get("/a-valider")
|
@router.get("/a-valider")
|
||||||
def liste_a_valider(jours: int = Query(14, ge=1, le=60)):
|
def liste_a_valider(jours: int = Query(14, ge=1, le=60)):
|
||||||
return {"items": a_valider(jours)}
|
return {"items": a_valider(jours)}
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
"""Brouillon de reponse (tt-2026-11-072) : l'IA propose un texte, Nabil le relit, le copie, l'envoie lui-meme.
|
||||||
|
Courrier n'ecrit jamais dans la messagerie et ne conserve pas le brouillon. Meme sortie unique que le reste :
|
||||||
|
PrivAiTe, refus net s'il est injoignable. Le HTML recu du modele est reduit a une liste blanche de balises
|
||||||
|
sans attribut, pour que la copie garde la mise en page (paragraphes, gras, listes) sans rien d'actif."""
|
||||||
|
import re
|
||||||
|
from html import escape
|
||||||
|
from html.parser import HTMLParser
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Query
|
||||||
|
|
||||||
|
from app import ia
|
||||||
|
from app import analyse as _a
|
||||||
|
|
||||||
|
AUTORISEES = {"p", "br", "strong", "b", "em", "i", "u", "ul", "ol", "li"}
|
||||||
|
AUTO_FERMEES = {"br"}
|
||||||
|
|
||||||
|
|
||||||
|
class _Nettoyeur(HTMLParser):
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__(convert_charrefs=True)
|
||||||
|
self.sortie: List[str] = []
|
||||||
|
self.ouvertes: List[str] = []
|
||||||
|
|
||||||
|
def handle_starttag(self, tag, attrs):
|
||||||
|
if tag in AUTORISEES:
|
||||||
|
if tag in AUTO_FERMEES:
|
||||||
|
self.sortie.append("<br>")
|
||||||
|
else:
|
||||||
|
self.sortie.append("<%s>" % tag); self.ouvertes.append(tag)
|
||||||
|
|
||||||
|
def handle_endtag(self, tag):
|
||||||
|
if tag in AUTORISEES and tag not in AUTO_FERMEES and tag in self.ouvertes:
|
||||||
|
while self.ouvertes:
|
||||||
|
t = self.ouvertes.pop()
|
||||||
|
self.sortie.append("</%s>" % t)
|
||||||
|
if t == tag:
|
||||||
|
break
|
||||||
|
|
||||||
|
def handle_data(self, data):
|
||||||
|
self.sortie.append(escape(data, quote=False))
|
||||||
|
|
||||||
|
def fin(self) -> str:
|
||||||
|
while self.ouvertes:
|
||||||
|
self.sortie.append("</%s>" % self.ouvertes.pop())
|
||||||
|
return "".join(self.sortie)
|
||||||
|
|
||||||
|
|
||||||
|
def assainir(html: str) -> str:
|
||||||
|
html = re.sub(r"(?is)<(script|style)\b.*?</\1>", "", html or "")
|
||||||
|
n = _Nettoyeur(); n.feed(html); n.close()
|
||||||
|
return n.fin().strip()
|
||||||
|
|
||||||
|
|
||||||
|
def en_texte(html: str) -> str:
|
||||||
|
t = re.sub(r"(?i)<br\s*/?>", "\n", html)
|
||||||
|
t = re.sub(r"(?i)</(p|li|ul|ol)>", "\n", t)
|
||||||
|
t = re.sub(r"(?i)<li>", "- ", t)
|
||||||
|
t = re.sub(r"<[^>]+>", "", t)
|
||||||
|
from html import unescape
|
||||||
|
return re.sub(r"\n{3,}", "\n\n", unescape(t)).strip()
|
||||||
|
|
||||||
|
|
||||||
|
CONSIGNE = (
|
||||||
|
"Tu rediges, pour Nabil Derouiche, chef de la division Supply Chain de la Direction Regionale de Sfax de Tunisie Telecom, "
|
||||||
|
"un brouillon de reponse a un mail. Ecris en francais correct avec tous les accents, dans un style naturel, direct et "
|
||||||
|
"professionnel, comme un responsable qui repond lui-meme : phrases simples, pas de formules ampoulees, pas de tirets longs, "
|
||||||
|
"pas de listes artificielles de trois elements, aucune mention d'outil, d'IA ou d'assistant. "
|
||||||
|
"Reponds a ce qui est demande, sans rien inventer : si une information manque (date, montant, decision), "
|
||||||
|
"ecris un passage entre crochets [a completer] plutot que de l'imaginer. "
|
||||||
|
"Termine par « Cordialement, » puis « Nabil Derouiche ». "
|
||||||
|
"Format de sortie : UNIQUEMENT du HTML simple (balises p, br, strong, ul, ol, li), sans titre, sans bloc de code, "
|
||||||
|
"sans objet ni en-tete, sans texte autour."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def construire(objet: str, expediteur: str, corps: str, contexte: str = "", consigne_nabil: str = "") -> list:
|
||||||
|
texte = "Expediteur : " + (expediteur or "(inconnu)") + "\nObjet : " + (objet or "(vide)") + "\n\n" + (corps or "")[:ia.MAX_TEXTE]
|
||||||
|
if contexte:
|
||||||
|
texte = "Contexte du fil :\n" + contexte + "\n\nMail auquel repondre :\n" + texte
|
||||||
|
if consigne_nabil:
|
||||||
|
texte += "\n\nIndication de Nabil pour la reponse : " + consigne_nabil[:300]
|
||||||
|
return [{"role": "system", "content": CONSIGNE}, {"role": "user", "content": texte}]
|
||||||
|
|
||||||
|
|
||||||
|
def rediger(objet: str, expediteur: str, corps: str, contexte: str = "", consigne_nabil: str = "") -> dict:
|
||||||
|
rep = ia.appeler_privaite(construire(objet, expediteur, corps, contexte, consigne_nabil), max_tokens=1500)
|
||||||
|
rep = re.sub(r"^```(?:html)?\s*|\s*```$", "", (rep or "").strip())
|
||||||
|
html = assainir(rep if "<" in rep else "<p>" + escape(rep).replace("\n\n", "</p><p>").replace("\n", "<br>") + "</p>")
|
||||||
|
if not html:
|
||||||
|
raise ia.IAIndisponible("reponse vide")
|
||||||
|
sujet = objet or ""
|
||||||
|
if sujet and not re.match(r"(?i)^\s*(re|rép?|reponse)\s*:", sujet):
|
||||||
|
sujet = "RE: " + sujet
|
||||||
|
return {"objet": sujet[:200], "html": html, "texte": en_texte(html)}
|
||||||
|
|
||||||
|
|
||||||
|
def creer_routeur(mirror_client) -> APIRouter:
|
||||||
|
r = APIRouter(prefix="/ia")
|
||||||
|
|
||||||
|
@r.post("/brouillon")
|
||||||
|
def brouillon(id: str = Query(..., min_length=1, max_length=400), indication: Optional[str] = Query(None, max_length=300)):
|
||||||
|
if not ia.ia_active():
|
||||||
|
raise HTTPException(status_code=409, detail="L'IA est désactivée.")
|
||||||
|
try:
|
||||||
|
m = _a._lire_mail(mirror_client, id)
|
||||||
|
if m is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Mail introuvable.")
|
||||||
|
return rediger(m["objet"], m["de"], m["corps"], _a.contexte_fil(m.get("fil"), id), indication or "")
|
||||||
|
except HTTPException:
|
||||||
|
raise
|
||||||
|
except ia.IAIndisponible as e:
|
||||||
|
raise HTTPException(status_code=503, detail="IA indisponible, aucun brouillon : " + str(e) + ".")
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=502, detail="Lecture du mail impossible : miroir indisponible.")
|
||||||
|
return r
|
||||||
@@ -71,7 +71,7 @@ def _cle() -> str:
|
|||||||
return k
|
return k
|
||||||
|
|
||||||
|
|
||||||
def appeler_privaite(messages, max_tokens: int = 30) -> str:
|
def appeler_privaite(messages, max_tokens: int = 600) -> str:
|
||||||
"""Seul point de sortie vers un modele : PrivAiTe. Toute erreur = IAIndisponible, sans repli."""
|
"""Seul point de sortie vers un modele : PrivAiTe. Toute erreur = IAIndisponible, sans repli."""
|
||||||
try:
|
try:
|
||||||
r = httpx.post(PRIVAITE_URL, timeout=IA_DELAI_S,
|
r = httpx.post(PRIVAITE_URL, timeout=IA_DELAI_S,
|
||||||
@@ -84,9 +84,13 @@ def appeler_privaite(messages, max_tokens: int = 30) -> str:
|
|||||||
log.warning("PrivAiTe a repondu %s", r.status_code)
|
log.warning("PrivAiTe a repondu %s", r.status_code)
|
||||||
raise IAIndisponible("PrivAiTe a refuse la requete")
|
raise IAIndisponible("PrivAiTe a refuse la requete")
|
||||||
try:
|
try:
|
||||||
return str(r.json()["choices"][0]["message"]["content"] or "")
|
texte = str(r.json()["choices"][0]["message"]["content"] or "")
|
||||||
except (KeyError, IndexError, ValueError, TypeError):
|
except (KeyError, IndexError, ValueError, TypeError):
|
||||||
raise IAIndisponible("reponse PrivAiTe illisible")
|
raise IAIndisponible("reponse PrivAiTe illisible")
|
||||||
|
if not texte.strip():
|
||||||
|
# Modele de raisonnement : un budget de jetons trop court se voit comme une reponse vide, jamais comme une analyse.
|
||||||
|
raise IAIndisponible("reponse vide (budget de reflexion depasse)")
|
||||||
|
return texte
|
||||||
|
|
||||||
|
|
||||||
def construire_messages(objet: str, corps: str, categories) -> list:
|
def construire_messages(objet: str, corps: str, categories) -> list:
|
||||||
|
|||||||
+12
@@ -92,6 +92,8 @@ async def lifespan(app: FastAPI):
|
|||||||
if ENV != "test":
|
if ENV != "test":
|
||||||
mirror_client.demarrer_rafraichissement()
|
mirror_client.demarrer_rafraichissement()
|
||||||
_analyse.demarrer_automatique(mirror_client)
|
_analyse.demarrer_automatique(mirror_client)
|
||||||
|
from app import sauvegarde as _sauvegarde
|
||||||
|
_sauvegarde.demarrer()
|
||||||
yield
|
yield
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
@@ -685,4 +687,14 @@ def confirm_rule_endpoint(regle_id: int):
|
|||||||
api.include_router(creer_routeur(mirror_client))
|
api.include_router(creer_routeur(mirror_client))
|
||||||
api.include_router(_analyse.creer_routeur(mirror_client))
|
api.include_router(_analyse.creer_routeur(mirror_client))
|
||||||
api.include_router(_analyse._routeur_regles_auto())
|
api.include_router(_analyse._routeur_regles_auto())
|
||||||
|
from app import brouillon as _brouillon
|
||||||
|
api.include_router(_brouillon.creer_routeur(mirror_client))
|
||||||
|
from app import piece_ia as _piece_ia
|
||||||
|
api.include_router(_piece_ia.creer_routeur(mirror_client))
|
||||||
|
|
||||||
|
|
||||||
|
@api.get("/sauvegardes")
|
||||||
|
def lire_sauvegardes():
|
||||||
|
from app import sauvegarde as _s
|
||||||
|
return {"sauvegardes": _s.liste()[:14]}
|
||||||
app.include_router(api)
|
app.include_router(api)
|
||||||
+108
@@ -0,0 +1,108 @@
|
|||||||
|
"""Resume d'une piece jointe a la demande (tt-2026-11-072). Le texte est extrait ici, localement, puis envoye au seul
|
||||||
|
modele autorise via PrivAiTe (pseudonymisation). Ni le contenu, ni le resume ne sont conserves ; refus net si l'IA est
|
||||||
|
desactivee ou PrivAiTe injoignable ; types actifs et fichiers trop gros refuses ; scans sans texte signales."""
|
||||||
|
import base64
|
||||||
|
import io
|
||||||
|
import re
|
||||||
|
import zipfile
|
||||||
|
from typing import Optional
|
||||||
|
from xml.etree import ElementTree
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Query
|
||||||
|
|
||||||
|
from app import ia
|
||||||
|
|
||||||
|
MAX_OCTETS = 8 * 1024 * 1024
|
||||||
|
MAX_TEXTE = 12000
|
||||||
|
TEXTE = {"txt", "csv", "md", "log"}
|
||||||
|
|
||||||
|
|
||||||
|
class SansTexte(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _ext(nom: str) -> str:
|
||||||
|
return nom.rsplit(".", 1)[-1].lower() if "." in nom else ""
|
||||||
|
|
||||||
|
|
||||||
|
def extraire_texte(nom: str, brut: bytes) -> str:
|
||||||
|
e = _ext(nom)
|
||||||
|
if e in TEXTE:
|
||||||
|
t = brut.decode("utf-8", "replace")
|
||||||
|
elif e == "docx":
|
||||||
|
try:
|
||||||
|
with zipfile.ZipFile(io.BytesIO(brut)) as z:
|
||||||
|
racine = ElementTree.fromstring(z.read("word/document.xml"))
|
||||||
|
except Exception:
|
||||||
|
raise SansTexte("document illisible")
|
||||||
|
t = "\n".join("".join(x.text or "" for x in p.iter("{http://schemas.openxmlformats.org/wordprocessingml/2006/main}t"))
|
||||||
|
for p in racine.iter("{http://schemas.openxmlformats.org/wordprocessingml/2006/main}p"))
|
||||||
|
elif e == "xlsx":
|
||||||
|
try:
|
||||||
|
import openpyxl
|
||||||
|
wb = openpyxl.load_workbook(io.BytesIO(brut), read_only=True, data_only=True)
|
||||||
|
lignes = []
|
||||||
|
for ws in wb.worksheets[:3]:
|
||||||
|
lignes.append("# " + ws.title)
|
||||||
|
for i, row in enumerate(ws.iter_rows(values_only=True)):
|
||||||
|
if i >= 80:
|
||||||
|
break
|
||||||
|
lignes.append(" | ".join("" if c is None else str(c) for c in row))
|
||||||
|
t = "\n".join(lignes)
|
||||||
|
except Exception:
|
||||||
|
raise SansTexte("classeur illisible")
|
||||||
|
elif e == "pdf":
|
||||||
|
try:
|
||||||
|
from pypdf import PdfReader
|
||||||
|
t = "\n".join((p.extract_text() or "") for p in PdfReader(io.BytesIO(brut)).pages[:15])
|
||||||
|
except Exception:
|
||||||
|
raise SansTexte("PDF illisible")
|
||||||
|
else:
|
||||||
|
raise SansTexte("type non pris en charge (PDF, Word, Excel, texte)")
|
||||||
|
t = re.sub(r"[ \t]+", " ", t)
|
||||||
|
t = re.sub(r"\n{3,}", "\n\n", t).strip()
|
||||||
|
if len(t) < 40:
|
||||||
|
raise SansTexte("aucun texte lisible (probablement un scan)")
|
||||||
|
return t[:MAX_TEXTE]
|
||||||
|
|
||||||
|
|
||||||
|
CONSIGNE = ("Tu resumes une piece jointe pour un responsable achats. En francais, 4 a 6 lignes maximum : nature du document, "
|
||||||
|
"points essentiels, montants, quantites, dates et echeances, action attendue s'il y en a une. Ne fais aucune "
|
||||||
|
"supposition : si une information manque, ne l'invente pas. Pas de formule d'introduction.")
|
||||||
|
|
||||||
|
|
||||||
|
def resumer_texte(texte: str) -> str:
|
||||||
|
return ia.appeler_privaite([{"role": "system", "content": CONSIGNE}, {"role": "user", "content": texte}], max_tokens=1200).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def creer_routeur(mirror_client) -> APIRouter:
|
||||||
|
router = APIRouter(prefix="/ia")
|
||||||
|
|
||||||
|
@router.post("/piece")
|
||||||
|
def resumer_piece(id: str = Query(..., min_length=1, max_length=400), nom: str = Query(..., min_length=1, max_length=260)):
|
||||||
|
if not ia.ia_active():
|
||||||
|
raise HTTPException(status_code=409, detail="L'IA est désactivée.")
|
||||||
|
try:
|
||||||
|
res = mirror_client.get_attachment(id, nom)
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=502, detail="Pièce jointe indisponible : miroir injoignable.")
|
||||||
|
d = res.get("donnees") if isinstance(res, dict) else None
|
||||||
|
b64 = d.get("contenu_base64") if isinstance(d, dict) else None
|
||||||
|
if not b64:
|
||||||
|
raise HTTPException(status_code=404, detail="Pièce jointe introuvable.")
|
||||||
|
if len(b64) * 3 // 4 > MAX_OCTETS:
|
||||||
|
raise HTTPException(status_code=413, detail="Pièce jointe trop volumineuse pour un résumé (8 Mo maximum).")
|
||||||
|
try:
|
||||||
|
brut = base64.b64decode(b64)
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=502, detail="Pièce jointe illisible.")
|
||||||
|
try:
|
||||||
|
texte = extraire_texte(nom, brut)
|
||||||
|
except SansTexte as e:
|
||||||
|
raise HTTPException(status_code=422, detail="Résumé impossible : " + str(e) + ".")
|
||||||
|
try:
|
||||||
|
return {"nom": nom, "resume": resumer_texte(texte), "extrait_chars": len(texte)}
|
||||||
|
except ia.IAIndisponible as e:
|
||||||
|
raise HTTPException(status_code=503, detail="IA indisponible, aucun résumé : " + str(e) + ".")
|
||||||
|
|
||||||
|
return router
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
"""Sauvegarde quotidienne de la base de Courrier (classements manuels, courses, a suivre, fiches IA).
|
||||||
|
Copie coherente par l'API de sauvegarde SQLite, une par jour, quatorze jours conservees."""
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
from app import config
|
||||||
|
from app.config import get_tunis_now_iso
|
||||||
|
|
||||||
|
log = logging.getLogger("courrier.sauvegarde")
|
||||||
|
CONSERVES = 14
|
||||||
|
|
||||||
|
|
||||||
|
def _dossier(db_path: Optional[str] = None) -> str:
|
||||||
|
d = os.path.join(os.path.dirname(db_path or config.DB_PATH), "sauvegardes")
|
||||||
|
os.makedirs(d, exist_ok=True)
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def liste(db_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||||
|
d = _dossier(db_path)
|
||||||
|
out = []
|
||||||
|
for nom in sorted(os.listdir(d), reverse=True):
|
||||||
|
if nom.startswith("courrier-") and nom.endswith(".db"):
|
||||||
|
out.append({"nom": nom, "jour": nom[9:19], "octets": os.path.getsize(os.path.join(d, nom))})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def sauvegarder(db_path: Optional[str] = None, force: bool = False) -> Optional[str]:
|
||||||
|
"""Une sauvegarde par jour. Retourne le nom du fichier cree, ou None s'il existe deja."""
|
||||||
|
src = db_path or config.DB_PATH
|
||||||
|
jour = get_tunis_now_iso()[:10]
|
||||||
|
d = _dossier(src)
|
||||||
|
cible = os.path.join(d, "courrier-%s.db" % jour)
|
||||||
|
if os.path.exists(cible) and not force:
|
||||||
|
return None
|
||||||
|
tmp = cible + ".tmp"
|
||||||
|
a = sqlite3.connect(src); b = sqlite3.connect(tmp)
|
||||||
|
try:
|
||||||
|
a.backup(b)
|
||||||
|
finally:
|
||||||
|
b.close(); a.close()
|
||||||
|
os.replace(tmp, cible)
|
||||||
|
os.chmod(cible, 0o640)
|
||||||
|
for ancien in liste(src)[CONSERVES:]:
|
||||||
|
try:
|
||||||
|
os.remove(os.path.join(d, ancien["nom"]))
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
return os.path.basename(cible)
|
||||||
|
|
||||||
|
|
||||||
|
def demarrer(intervalle: int = 3600) -> None:
|
||||||
|
def boucle() -> None:
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
n = sauvegarder()
|
||||||
|
if n:
|
||||||
|
log.info("sauvegarde %s", n)
|
||||||
|
except Exception:
|
||||||
|
log.warning("sauvegarde impossible")
|
||||||
|
time.sleep(intervalle)
|
||||||
|
threading.Thread(target=boucle, name="sauvegarde-courrier", daemon=True).start()
|
||||||
@@ -393,3 +393,17 @@ h1, h2, h3, p { margin: 0; }
|
|||||||
.lect-ia-fil { margin-top: 8px; font: 400 13px/19px var(--ny-police); }
|
.lect-ia-fil { margin-top: 8px; font: 400 13px/19px var(--ny-police); }
|
||||||
.lect-ia-fil summary { cursor: pointer; font-weight: 600; }
|
.lect-ia-fil summary { cursor: pointer; font-weight: 600; }
|
||||||
.lect-ia-fil p { margin: 6px 0 6px 12px; }
|
.lect-ia-fil p { margin: 6px 0 6px 12px; }
|
||||||
|
|
||||||
|
.lect-reponse { margin-top: 10px; padding-top: 8px; border-top: 1px solid var(--ny-trait); display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
.champ-indication { width: 100%; min-height: var(--ny-cible, 44px); padding: 0 12px; border: 1px solid var(--ny-trait); border-radius: var(--ny-r-m, 8px); font: 400 14px/20px var(--ny-police); background: var(--ny-carte); color: inherit; box-sizing: border-box; }
|
||||||
|
.brouillon { padding: 12px 14px; border: 1px solid var(--ny-trait); border-radius: var(--ny-r-m, 8px); background: var(--ny-carte); color: var(--ny-encre); font: 400 15px/1.55 Calibri, "Segoe UI", sans-serif; }
|
||||||
|
.brouillon p { margin: 0 0 10px; }
|
||||||
|
.brouillon-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||||
|
.lect-ia-refs { margin: 6px 0; }
|
||||||
|
|
||||||
|
.ligne-valider { touch-action: pan-y; }
|
||||||
|
.ligne-valider.balaye-ok { background: var(--ny-accent-teinte); }
|
||||||
|
.ligne-valider.balaye-non { background: var(--ny-erreur-fond); }
|
||||||
|
|
||||||
|
.resume-pj { flex-basis: 100%; margin: 4px 0 0; white-space: pre-wrap; }
|
||||||
|
.lect-pj li { flex-wrap: wrap; }
|
||||||
+146
-9
@@ -12,6 +12,7 @@
|
|||||||
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',
|
||||||
|
aujourdhui: 'M8 2v4|M16 2v4|M3 10h18|M5 4h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z',
|
||||||
avalider: 'M22 11.08V12a10 10 0 1 1-5.93-9.14|m9 11 3 3L22 4',
|
avalider: 'M22 11.08V12a10 10 0 1 1-5.93-9.14|m9 11 3 3L22 4',
|
||||||
asuivre: 'm19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z',
|
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',
|
||||||
@@ -20,13 +21,13 @@
|
|||||||
panneau: 'M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z|M9 3v18'
|
panneau: 'M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z|M9 3v18'
|
||||||
};
|
};
|
||||||
var NAV = [
|
var NAV = [
|
||||||
['tri', 'Tri du jour', true], ['avalider', 'À valider', 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]
|
['tri', 'Tri du jour', true], ['aujourdhui', 'Aujourd\'hui', true], ['avalider', 'À valider', true], ['asuivre', 'À suivre', true], ['categories', 'Catégories', true], ['groupes', 'Groupes', true], ['recherche', 'Recherche', true], ['courses', 'Courses pour Tunis', true], ['suivi', 'Suivi des demandes', true], ['regles', 'Règles', true]
|
||||||
];
|
];
|
||||||
var BIENTOT = {};
|
var BIENTOT = {};
|
||||||
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 = { 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: {}, avalider: { items: [], etat: 'chargement', ia: true }, suivi: { items: [], jours: 14, filtre: 'attente', compte: {}, etat: 'chargement' }, recherche: { q: '', periode: 'tout', avecPj: false, etat: 'repos', resultats: [], plafond: false, cherche: '' } };
|
var S = { chargeA: 0, chargeJour: '', vue: 'tri', jour: auj(), filtre: null, cats: [], mails: [], etat: 'chargement', banniere: null, notif: null, regles: [], reglesEtat: 'ok', miroirErreur: false, majHeure: '', groupe: { jours: 7, cat: null, etq: null, mails: [], etat: 'chargement' }, courses: { liste: [], filtre: 'a_faire', etat: 'chargement' }, asuivre: { items: [], compte: { actif: 0, termine: 0 }, filtre: 'actif', etat: 'chargement', annuler: null }, suivreSet: {}, avalider: { items: [], etat: 'chargement', ia: true }, aujourdhui: { etat: 'chargement', demandes: [], relances: [], courses: [] }, 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()); }
|
||||||
@@ -158,6 +159,7 @@
|
|||||||
else if (vue === 'suivi') chargerSuivi();
|
else if (vue === 'suivi') chargerSuivi();
|
||||||
else if (vue === 'asuivre') chargerASuivre();
|
else if (vue === 'asuivre') chargerASuivre();
|
||||||
else if (vue === 'avalider') chargerAValider();
|
else if (vue === 'avalider') chargerAValider();
|
||||||
|
else if (vue === 'aujourdhui') chargerAujourdhui();
|
||||||
else if (vue === 'recherche') { rendre(); var ch = document.getElementById('rech-q'); if (ch) ch.focus(); return; }
|
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();
|
||||||
@@ -445,6 +447,57 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* ---------- Couche IA (tt-2026-11-072) : proposition seulement, rien n'est appliqué sans clic ---------- */
|
/* ---------- Couche IA (tt-2026-11-072) : proposition seulement, rien n'est appliqué sans clic ---------- */
|
||||||
|
|
||||||
|
/* ---------- Brouillon de réponse : proposé, relu, copié avec sa mise en page ; Courrier n'envoie rien ---------- */
|
||||||
|
var BALISES_OK = { P: 1, BR: 1, STRONG: 1, B: 1, EM: 1, I: 1, U: 1, UL: 1, OL: 1, LI: 1 };
|
||||||
|
function noeudsSurs(html, parent) {
|
||||||
|
var doc = new DOMParser().parseFromString('<body>' + html + '</body>', 'text/html');
|
||||||
|
(function copie(src, dst) {
|
||||||
|
Array.prototype.forEach.call(src.childNodes, function (n) {
|
||||||
|
if (n.nodeType === 3) dst.appendChild(document.createTextNode(n.nodeValue));
|
||||||
|
else if (n.nodeType === 1 && BALISES_OK[n.tagName]) { var e = document.createElement(n.tagName.toLowerCase()); dst.appendChild(e); copie(n, e); }
|
||||||
|
});
|
||||||
|
})(doc.body, parent);
|
||||||
|
}
|
||||||
|
function copierMiseEnPage(zone, html, texte, fini) {
|
||||||
|
function repli() {
|
||||||
|
try {
|
||||||
|
var sel = window.getSelection(), rg = document.createRange(); rg.selectNodeContents(zone); sel.removeAllRanges(); sel.addRange(rg);
|
||||||
|
var ok = document.execCommand('copy'); sel.removeAllRanges(); fini(ok);
|
||||||
|
} catch (e) { fini(false); }
|
||||||
|
}
|
||||||
|
if (navigator.clipboard && window.ClipboardItem) {
|
||||||
|
navigator.clipboard.write([new ClipboardItem({ 'text/html': new Blob([html], { type: 'text/html' }), 'text/plain': new Blob([texte], { type: 'text/plain' }) })]).then(function () { fini(true); }, repli);
|
||||||
|
} else repli();
|
||||||
|
}
|
||||||
|
function blocReponse(m, r, id) {
|
||||||
|
var cadre = h('div', { class: 'lect-reponse' });
|
||||||
|
var champ = h('input', { type: 'text', maxlength: '300', class: 'champ-indication', 'aria-label': 'Indication pour la réponse (facultatif)', placeholder: 'Indication facultative : par exemple, accepter pour jeudi' });
|
||||||
|
var bt = h('button', { type: 'button', class: 'btn-ligne' }, 'Proposer une réponse');
|
||||||
|
var msg = h('span', { class: 'lect-ia-info', role: 'status' });
|
||||||
|
function afficher(b) {
|
||||||
|
cadre.textContent = '';
|
||||||
|
var zone = h('div', { class: 'brouillon', tabindex: '0', 'aria-label': 'Brouillon de réponse' });
|
||||||
|
noeudsSurs(b.html, zone);
|
||||||
|
var etat = h('span', { class: 'lect-ia-info', role: 'status' });
|
||||||
|
var cp = h('button', { type: 'button', class: 'btn-plein' }, 'Copier la réponse');
|
||||||
|
cp.addEventListener('click', function () { copierMiseEnPage(zone, b.html, b.texte, function (ok) { etat.textContent = ok ? ' Copié avec la mise en page. Collez dans votre message.' : ' Copie impossible : sélectionnez le texte à la main.'; }); });
|
||||||
|
var co = h('button', { type: 'button', class: 'btn-ligne' }, 'Copier l\'objet');
|
||||||
|
co.addEventListener('click', function () { try { navigator.clipboard.writeText(b.objet).then(function () { etat.textContent = ' Objet copié.'; }, function () { etat.textContent = ' Copie impossible.'; }); } catch (e) { etat.textContent = ' Copie impossible.'; } });
|
||||||
|
var rf = h('button', { type: 'button', class: 'btn-ligne', onclick: function () { cadre.textContent = ''; cadre.appendChild(champ); cadre.appendChild(bt); cadre.appendChild(msg); msg.textContent = ''; } }, 'Refaire');
|
||||||
|
cadre.appendChild(h('p', { class: 'lect-ia-info', text: 'Brouillon à relire : rien n\'est envoyé, Courrier n\'écrit pas dans votre messagerie.' }));
|
||||||
|
cadre.appendChild(h('p', null, h('b', { text: 'Objet : ' }), b.objet));
|
||||||
|
cadre.appendChild(zone);
|
||||||
|
cadre.appendChild(h('div', { class: 'brouillon-actions' }, cp, co, rf, etat));
|
||||||
|
}
|
||||||
|
bt.addEventListener('click', function () {
|
||||||
|
bt.disabled = true; msg.textContent = ' Rédaction en cours, une quinzaine de secondes…';
|
||||||
|
api('/ia/brouillon?id=' + encodeURIComponent(id) + (champ.value.trim() ? '&indication=' + encodeURIComponent(champ.value.trim()) : ''), { method: 'POST' }).then(afficher)
|
||||||
|
.catch(function (e) { if (e.message === 'session') return; bt.disabled = false; msg.textContent = e.message === 'http 503' ? ' IA indisponible pour le moment, aucun brouillon.' : ' Brouillon impossible. Réessayez.'; });
|
||||||
|
});
|
||||||
|
cadre.appendChild(champ); cadre.appendChild(bt); cadre.appendChild(msg);
|
||||||
|
return cadre;
|
||||||
|
}
|
||||||
function blocIA(m, r) {
|
function blocIA(m, r) {
|
||||||
var id = r.message_id || m.id;
|
var id = r.message_id || m.id;
|
||||||
var sect = h('section', { class: 'lect-ia', 'aria-label': 'Analyse IA' });
|
var sect = h('section', { class: 'lect-ia', 'aria-label': 'Analyse IA' });
|
||||||
@@ -452,6 +505,16 @@
|
|||||||
sect.textContent = '';
|
sect.textContent = '';
|
||||||
sect.appendChild(h('h3', null, 'Analyse IA ', h('span', { class: 'etq', text: 'proposition, rien n\'est appliqué' })));
|
sect.appendChild(h('h3', null, 'Analyse IA ', h('span', { class: 'etq', text: 'proposition, rien n\'est appliqué' })));
|
||||||
if (f.resume) sect.appendChild(h('p', { class: 'lect-ia-resume', text: f.resume }));
|
if (f.resume) sect.appendChild(h('p', { class: 'lect-ia-resume', text: f.resume }));
|
||||||
|
var refs = [], vus = {};
|
||||||
|
((m.objet || r.objet || '') + ' ' + (f.resume || '')).replace(/\b(PO\s?\d{6,8}(?:\/\d+)?|AO\s?\d{1,4}\/\d{4}|March[ée]\s*(?:N°\s*)?\d{1,4}\/\d{4})/gi, function (x) { var k = x.replace(/\s+/g, ' ').trim(); if (!vus[k.toLowerCase()]) { vus[k.toLowerCase()] = 1; refs.push(k); } return x; });
|
||||||
|
if (refs.length) {
|
||||||
|
var lr = h('p', { class: 'lect-ia-refs' }, 'Références : ');
|
||||||
|
refs.slice(0, 4).forEach(function (k) {
|
||||||
|
lr.appendChild(h('button', { type: 'button', class: 'btn-petit', title: 'Chercher tous les mails sur ' + k, onclick: function () { fermer(true); S.recherche.q = k; allerA('recherche'); lancerRecherche(); } }, k));
|
||||||
|
lr.appendChild(document.createTextNode(' '));
|
||||||
|
});
|
||||||
|
sect.appendChild(lr);
|
||||||
|
}
|
||||||
var cat = h('p', null, 'Catégorie proposée : ', h('strong', { text: f.categorie }), ' · confiance ' + f.confiance + ' ');
|
var cat = h('p', null, 'Catégorie proposée : ', h('strong', { text: f.categorie }), ' · confiance ' + f.confiance + ' ');
|
||||||
if (f.categorie !== m.cat && f.categorie !== 'À classer') cat.appendChild(h('button', { type: 'button', class: 'btn-ligne', onclick: function () { corriger(m, f.categorie); flash('Catégorie appliquée.'); } }, 'Appliquer'));
|
if (f.categorie !== m.cat && f.categorie !== 'À classer') cat.appendChild(h('button', { type: 'button', class: 'btn-ligne', onclick: function () { corriger(m, f.categorie); flash('Catégorie appliquée.'); } }, 'Appliquer'));
|
||||||
sect.appendChild(cat);
|
sect.appendChild(cat);
|
||||||
@@ -462,6 +525,7 @@
|
|||||||
}
|
}
|
||||||
if (f.demande && f.demande.reelle) sect.appendChild(h('p', null, 'À faire : ', h('strong', { text: f.demande.action + (f.demande.echeance ? ' · avant le ' + f.demande.echeance : '') })));
|
if (f.demande && f.demande.reelle) sect.appendChild(h('p', null, 'À faire : ', h('strong', { text: f.demande.action + (f.demande.echeance ? ' · avant le ' + f.demande.echeance : '') })));
|
||||||
else if (f.demande) sect.appendChild(h('p', { class: 'lect-ia-info', text: 'Information : aucune action attendue.' }));
|
else if (f.demande) sect.appendChild(h('p', { class: 'lect-ia-info', text: 'Information : aucune action attendue.' }));
|
||||||
|
sect.appendChild(blocReponse(m, r, id));
|
||||||
api('/ia/fil?id=' + encodeURIComponent(id)).then(function (r) {
|
api('/ia/fil?id=' + encodeURIComponent(id)).then(function (r) {
|
||||||
var ms = r.mails || []; if (!ms.length) return;
|
var ms = r.mails || []; if (!ms.length) return;
|
||||||
var det = h('details', { class: 'lect-ia-fil' }, h('summary', { text: 'Dans ce fil : ' + ms.length + ' autre' + (ms.length > 1 ? 's' : '') + ' mail' + (ms.length > 1 ? 's' : '') + ' analysé' + (ms.length > 1 ? 's' : '') }));
|
var det = h('details', { class: 'lect-ia-fil' }, h('summary', { text: 'Dans ce fil : ' + ms.length + ' autre' + (ms.length > 1 ? 's' : '') + ' mail' + (ms.length > 1 ? 's' : '') + ' analysé' + (ms.length > 1 ? 's' : '') }));
|
||||||
@@ -500,6 +564,13 @@
|
|||||||
Promise.all([api('/ia/etat'), api('/ia/auto')]).then(function (rs) {
|
Promise.all([api('/ia/etat'), api('/ia/auto')]).then(function (rs) {
|
||||||
carte.appendChild(ligne('Analyse par IA', 'À la demande, mail par mail. Le texte passe par le masquage PrivAiTe ; rien n\'est classé sans votre clic.', rs[0].actif, 'etat'));
|
carte.appendChild(ligne('Analyse par IA', 'À la demande, mail par mail. Le texte passe par le masquage PrivAiTe ; rien n\'est classé sans votre clic.', rs[0].actif, 'etat'));
|
||||||
if (rs[0].actif) carte.appendChild(ligne('Analyse automatique du jour', 'Prépare les fiches des nouveaux mails toutes les trois minutes. Les agents peuvent alors les consulter.', rs[1].auto, 'auto'));
|
if (rs[0].actif) carte.appendChild(ligne('Analyse automatique du jour', 'Prépare les fiches des nouveaux mails toutes les trois minutes. Les agents peuvent alors les consulter.', rs[1].auto, 'auto'));
|
||||||
|
return api('/ia/stats').then(function (st) {
|
||||||
|
var t = st.total || { acceptees: 0, refusees: 0 }, n = t.acceptees + t.refusees; if (!n) return;
|
||||||
|
var bloc = h('div', { class: 'stats-ia' }, h('b', { text: 'Qualité des propositions' }),
|
||||||
|
h('p', { class: 'lect-ia-info', text: t.acceptees + ' acceptée' + (t.acceptees > 1 ? 's' : '') + ', ' + t.refusees + ' refusée' + (t.refusees > 1 ? 's' : '') + ' (' + Math.round(100 * t.acceptees / n) + ' % d\'acceptation). Vos choix guident aussi les analyses suivantes.' }));
|
||||||
|
Object.keys(st.categories || {}).sort().forEach(function (c) { var d = st.categories[c]; bloc.appendChild(h('p', { class: 'lect-ia-info', text: c + ' : ' + d.acceptees + ' acceptée' + (d.acceptees > 1 ? 's' : '') + ', ' + d.refusees + ' refusée' + (d.refusees > 1 ? 's' : '') })); });
|
||||||
|
carte.appendChild(bloc);
|
||||||
|
}).catch(function () { /* statistiques absentes : sans gravité */ });
|
||||||
}).catch(function () { carte.setAttribute('hidden', ''); });
|
}).catch(function () { carte.setAttribute('hidden', ''); });
|
||||||
return carte;
|
return carte;
|
||||||
}
|
}
|
||||||
@@ -537,8 +608,21 @@
|
|||||||
bt.addEventListener('click', function () { telechargerPiece(r.message_id || m.id, p, bt); });
|
bt.addEventListener('click', function () { telechargerPiece(r.message_id || m.id, p, bt); });
|
||||||
action = bt;
|
action = bt;
|
||||||
}
|
}
|
||||||
ul.appendChild(h('li', null, icone('pj', 18), h('span', { class: 'nom coupe', title: p.nom, text: p.nom }),
|
var li = 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));
|
h('span', { class: 'info', text: extDe(p) + tailleLisible(p.taille) }), action);
|
||||||
|
if (!p.bloquee && /\.(pdf|docx|xlsx|txt|csv)$/i.test(p.nom || '')) {
|
||||||
|
var rs = h('button', { type: 'button', class: 'btn-ligne btn-resume' }, 'Résumer');
|
||||||
|
var zone = h('p', { class: 'lect-ia-info resume-pj', role: 'status' });
|
||||||
|
rs.addEventListener('click', function () {
|
||||||
|
rs.disabled = true; zone.textContent = 'Lecture de la pièce jointe…';
|
||||||
|
api('/ia/piece?id=' + encodeURIComponent(r.message_id || m.id) + '&nom=' + encodeURIComponent(p.nom), { method: 'POST' })
|
||||||
|
.then(function (x) { zone.textContent = x.resume; rs.style.display = 'none'; })
|
||||||
|
.catch(function (e) { if (e.message === 'session') return; rs.disabled = false;
|
||||||
|
zone.textContent = e.message === 'http 409' ? 'IA désactivée (Règles).' : e.message === 'http 503' ? 'IA indisponible, aucun résumé.' : e.message === 'http 422' ? 'Résumé impossible : pas de texte lisible (scan ?) ou type non pris en charge.' : e.message === 'http 413' ? 'Pièce trop volumineuse pour un résumé.' : 'Résumé impossible. Réessayez.'; });
|
||||||
|
});
|
||||||
|
li.appendChild(rs); li.appendChild(zone);
|
||||||
|
}
|
||||||
|
ul.appendChild(li);
|
||||||
});
|
});
|
||||||
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));
|
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));
|
||||||
}
|
}
|
||||||
@@ -1004,10 +1088,28 @@
|
|||||||
return chargerAValider();
|
return chargerAValider();
|
||||||
}).catch(function (e) { V.analyse = false; if (e.message === 'session') return; rendre(); flash(e.message === 'http 409' ? 'L\'IA est désactivée : activez-la dans Règles.' : e.message === 'http 503' ? 'IA indisponible pour le moment.' : 'Analyse impossible. Réessayez.'); });
|
}).catch(function (e) { V.analyse = false; if (e.message === 'session') return; rendre(); flash(e.message === 'http 409' ? 'L\'IA est désactivée : activez-la dans Règles.' : e.message === 'http 503' ? 'IA indisponible pour le moment.' : 'Analyse impossible. Réessayez.'); });
|
||||||
}
|
}
|
||||||
|
/* Balayage tactile : vers la droite = accepter, vers la gauche = refuser. Les boutons restent la voie principale. */
|
||||||
|
function balayage(el, decider) {
|
||||||
|
var x0 = null, y0 = 0, dx = 0, SEUIL = 110;
|
||||||
|
el.addEventListener('touchstart', function (e) { var t = e.touches[0]; x0 = t.clientX; y0 = t.clientY; dx = 0; el.style.transition = 'none'; }, { passive: true });
|
||||||
|
el.addEventListener('touchmove', function (e) {
|
||||||
|
if (x0 === null) return;
|
||||||
|
var t = e.touches[0]; dx = t.clientX - x0;
|
||||||
|
if (Math.abs(t.clientY - y0) > Math.abs(dx)) { x0 = null; el.style.transform = ''; return; }
|
||||||
|
el.style.transform = 'translateX(' + Math.max(-160, Math.min(160, dx)) + 'px)';
|
||||||
|
el.classList.toggle('balaye-ok', dx > 40); el.classList.toggle('balaye-non', dx < -40);
|
||||||
|
}, { passive: true });
|
||||||
|
function fin() {
|
||||||
|
if (x0 === null) { el.style.transform = ''; el.classList.remove('balaye-ok', 'balaye-non'); return; }
|
||||||
|
var d = dx; x0 = null; el.style.transition = 'transform .15s'; el.style.transform = ''; el.classList.remove('balaye-ok', 'balaye-non');
|
||||||
|
if (d > SEUIL) decider('accepter'); else if (d < -SEUIL) decider('refuser');
|
||||||
|
}
|
||||||
|
el.addEventListener('touchend', fin); el.addEventListener('touchcancel', fin);
|
||||||
|
}
|
||||||
function vueAValider() {
|
function vueAValider() {
|
||||||
var V = S.avalider, frag = document.createDocumentFragment();
|
var V = S.avalider, frag = document.createDocumentFragment();
|
||||||
frag.appendChild(h('header', { class: 'entete' }, h('h1', null, 'À valider'),
|
frag.appendChild(h('header', { class: 'entete' }, h('h1', null, 'À valider'),
|
||||||
h('div', { class: 'entete-actions' }, h('span', { class: 'lect-ia-info', text: 'Propositions de l\'IA lues dans le contenu des mails. Rien n\'est appliqué sans votre clic.' }),
|
h('div', { class: 'entete-actions' }, h('span', { class: 'lect-ia-info', text: 'Propositions de l\'IA lues dans le contenu des mails. Rien n\'est appliqué sans votre action : boutons, ou balayage sur téléphone (droite accepte, gauche refuse).' }),
|
||||||
h('button', { type: 'button', class: 'btn-ligne', disabled: V.analyse ? 'disabled' : null, onclick: analyserLeJour }, V.analyse ? 'Analyse en cours…' : 'Analyser les mails du jour'))));
|
h('button', { type: 'button', class: 'btn-ligne', disabled: V.analyse ? 'disabled' : null, onclick: analyserLeJour }, V.analyse ? 'Analyse en cours…' : 'Analyser les mails du jour'))));
|
||||||
if (S.notif) frag.appendChild(h('div', { class: 'notif', role: 'status', text: S.notif }));
|
if (S.notif) frag.appendChild(h('div', { class: 'notif', role: 'status', text: S.notif }));
|
||||||
if (V.etat === 'chargement') { frag.appendChild(h('section', { class: 'carte squelette', 'aria-busy': 'true' }, h('div', { class: 'sq-statut', role: 'status', text: 'Lecture des propositions…' }))); return frag; }
|
if (V.etat === 'chargement') { frag.appendChild(h('section', { class: 'carte squelette', 'aria-busy': 'true' }, h('div', { class: 'sq-statut', role: 'status', text: 'Lecture des propositions…' }))); return frag; }
|
||||||
@@ -1019,15 +1121,50 @@
|
|||||||
var liste = h('section', { class: 'carte limite-l liste-valider', 'aria-label': 'Propositions' });
|
var liste = h('section', { class: 'carte limite-l liste-valider', 'aria-label': 'Propositions' });
|
||||||
V.items.forEach(function (it) {
|
V.items.forEach(function (it) {
|
||||||
var titre = it.type === 'course' ? 'Course possible : ' + it.propose + ' (' + (SENS[it.sens] || it.sens) + ')' : 'Classer en ' + it.propose + (it.actuelle && it.actuelle !== 'À classer' ? ' (actuellement ' + it.actuelle + ')' : '');
|
var titre = it.type === 'course' ? 'Course possible : ' + it.propose + ' (' + (SENS[it.sens] || it.sens) + ')' : 'Classer en ' + it.propose + (it.actuelle && it.actuelle !== 'À classer' ? ' (actuellement ' + it.actuelle + ')' : '');
|
||||||
liste.appendChild(h('article', { class: 'ligne-valider' },
|
var carte = h('article', { class: 'ligne-valider' },
|
||||||
h('div', { class: 'lv-texte' }, h('b', { text: titre }), h('p', { class: 'lv-objet', text: (it.objet || '(sans objet)') + ' · ' + (it.expediteur || '').replace(/<.*>/, '').trim() }), it.resume ? h('p', { class: 'lect-ia-info', text: it.resume }) : null),
|
h('div', { class: 'lv-texte' }, h('b', { text: titre }), h('p', { class: 'lv-objet', text: (it.objet || '(sans objet)') + ' · ' + (it.expediteur || '').replace(/<.*>/, '').trim() }), it.resume ? h('p', { class: 'lect-ia-info', text: it.resume }) : null),
|
||||||
h('div', { class: 'lv-actions' },
|
h('div', { class: 'lv-actions' },
|
||||||
h('button', { type: 'button', class: 'btn-plein', onclick: function () { deciderIA(it, 'accepter'); } }, it.type === 'course' ? 'Ajouter' : 'Accepter'),
|
h('button', { type: 'button', class: 'btn-plein', onclick: function () { deciderIA(it, 'accepter'); } }, it.type === 'course' ? 'Ajouter' : 'Accepter'),
|
||||||
h('button', { type: 'button', class: 'btn-ligne', onclick: function () { deciderIA(it, 'refuser'); } }, 'Refuser'))));
|
h('button', { type: 'button', class: 'btn-ligne', onclick: function () { deciderIA(it, 'refuser'); } }, 'Refuser')));
|
||||||
|
balayage(carte, function (sens) { deciderIA(it, sens); });
|
||||||
|
liste.appendChild(carte);
|
||||||
});
|
});
|
||||||
frag.appendChild(liste);
|
frag.appendChild(liste);
|
||||||
return frag;
|
return frag;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---------- Aujourd'hui : ce qui attend une action, par échéance ---------- */
|
||||||
|
function echeanceISO(t) { var m = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec((t || '').trim()); return m ? m[3] + '-' + m[2] + '-' + m[1] : ''; }
|
||||||
|
function chargerAujourdhui() {
|
||||||
|
var V = S.aujourdhui; V.etat = 'chargement'; rendre();
|
||||||
|
return Promise.all([api('/ia/analyses?jours=14&n=300').catch(function () { return { analyses: [] }; }),
|
||||||
|
api('/suivi?jours=14').catch(function () { return { items: [] }; }), api('/courses?statut=a_faire').catch(function () { return { courses: [] }; })]).then(function (rs) {
|
||||||
|
V.demandes = (rs[0].analyses || []).filter(function (a) { return a.demande && a.demande.reelle; }).map(function (a) { return { id: a.message_id, objet: a.objet, action: a.demande.action, ech: echeanceISO(a.demande.echeance), exp: a.expediteur }; })
|
||||||
|
.sort(function (x, y) { return (x.ech || '9999') < (y.ech || '9999') ? -1 : (x.ech || '9999') > (y.ech || '9999') ? 1 : 0; });
|
||||||
|
V.relances = (rs[1].items || []).filter(function (i) { return i.relancer && !i.clos; });
|
||||||
|
V.courses = rs[2].courses || []; V.etat = 'ok'; rendre();
|
||||||
|
}).catch(function (e) { if (e.message === 'session') return; V.etat = 'erreur'; rendre(); });
|
||||||
|
}
|
||||||
|
function vueAujourdhui() {
|
||||||
|
var V = S.aujourdhui, frag = document.createDocumentFragment(), auj0 = auj();
|
||||||
|
frag.appendChild(h('header', { class: 'entete' }, h('h1', null, 'Aujourd\'hui')));
|
||||||
|
if (V.etat === 'chargement') { frag.appendChild(h('section', { class: 'carte squelette', 'aria-busy': 'true' }, h('div', { class: 'sq-statut', role: 'status', text: 'Préparation de la journée…' }))); return frag; }
|
||||||
|
if (V.etat === 'erreur') { frag.appendChild(h('div', { class: 'erreur', role: 'alert' }, h('h2', null, 'Chargement impossible'), h('button', { type: 'button', class: 'btn-plein', onclick: chargerAujourdhui }, 'Réessayer'))); return frag; }
|
||||||
|
function carte(titre, vide, lignes) {
|
||||||
|
var c = h('section', { class: 'carte limite-l', 'aria-label': titre }, h('h2', null, titre));
|
||||||
|
if (!lignes.length) c.appendChild(h('p', { class: 'lect-ia-info', text: vide })); else lignes.forEach(function (l) { c.appendChild(l); });
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
var dem = V.demandes.map(function (d) {
|
||||||
|
var etat = !d.ech ? '' : d.ech < auj0 ? 'En retard · ' + fr(d.ech) : d.ech === auj0 ? 'Aujourd\'hui' : 'Avant le ' + fr(d.ech);
|
||||||
|
return h('div', { class: 'ligne-valider' }, h('div', { class: 'lv-texte' }, h('b', { text: d.action || d.objet }), h('p', { class: 'lv-objet', text: (d.objet || '') + ' · ' + (d.exp || '').replace(/<.*>/, '').trim() }), etat ? h('span', { class: 'etq' + (d.ech < auj0 ? ' relance' : ''), text: etat }) : null),
|
||||||
|
h('div', { class: 'lv-actions' }, h('button', { type: 'button', class: 'btn-ligne', onclick: function () { lireMail({ id: d.id, objet: d.objet, exp: d.exp, expBrut: d.exp, date: '', cat: '', etiquettes: [] }); } }, 'Lire')));
|
||||||
|
});
|
||||||
|
frag.appendChild(carte('Demandes à traiter', 'Aucune demande réelle repérée par l\'IA. Analysez vos mails dans « À valider » pour la remplir.', dem));
|
||||||
|
frag.appendChild(carte('À relancer', 'Aucune relance due.', V.relances.map(function (i) { return h('div', { class: 'ligne-valider' }, h('div', { class: 'lv-texte' }, h('b', { text: i.sujet || '(sans objet)' }), h('p', { class: 'lv-objet', text: 'À : ' + (i.avec || 'inconnu') + ' · ' + dureeLisible(i.jours) })), h('div', { class: 'lv-actions' }, h('button', { type: 'button', class: 'btn-ligne', onclick: function () { lireMail({ id: i.dernier_id, objet: i.sujet, exp: i.avec, expBrut: i.avec, date: '', cat: '', etiquettes: [] }); } }, 'Lire'))); })));
|
||||||
|
frag.appendChild(carte('Courses pour Tunis à faire', 'Aucune course en attente.', V.courses.map(function (k) { return h('div', { class: 'ligne-valider' }, h('div', { class: 'lv-texte' }, h('b', { text: k.demande }), h('p', { class: 'lv-objet', text: SENS[k.sens] || k.sens }))); })));
|
||||||
|
return frag;
|
||||||
|
}
|
||||||
function vueASuivre() {
|
function vueASuivre() {
|
||||||
var V = S.asuivre, frag = document.createDocumentFragment();
|
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'))));
|
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'))));
|
||||||
@@ -1156,9 +1293,9 @@
|
|||||||
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() : S.vue === 'groupes' ? vueGroupes() : S.vue === 'courses' ? vueCourses() : S.vue === 'suivi' ? vueSuivi() : S.vue === 'asuivre' ? vueASuivre() : S.vue === 'avalider' ? vueAValider() : S.vue === 'recherche' ? vueRecherche() : vueBientot(S.vue);
|
var v = S.vue === 'tri' ? vueTri() : S.vue === 'categories' ? vueCategories() : S.vue === 'regles' ? vueRegles() : S.vue === 'groupes' ? vueGroupes() : S.vue === 'courses' ? vueCourses() : S.vue === 'suivi' ? vueSuivi() : S.vue === 'asuivre' ? vueASuivre() : S.vue === 'avalider' ? vueAValider() : S.vue === 'aujourdhui' ? vueAujourdhui() : 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 === 'avalider' ? 'À valider' : 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];
|
var titre = S.vue === 'tri' ? 'Tri du jour' : S.vue === 'avalider' ? 'À valider' : S.vue === 'aujourdhui' ? 'Aujourd\'hui' : 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';
|
||||||
document.getElementById('barre-titre').textContent = titre;
|
document.getElementById('barre-titre').textContent = titre;
|
||||||
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(); }
|
||||||
|
|||||||
@@ -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?v=20261121a">
|
<link rel="stylesheet" href="/static/app.css?v=20261121c">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app" class="coque">
|
<div id="app" class="coque">
|
||||||
@@ -31,6 +31,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?v=20261121a"></script>
|
<script src="/static/app.js?v=20261121c"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -6,3 +6,4 @@ 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
|
openpyxl>=3.1,<4.0.0
|
||||||
|
pypdf>=4.0,<6.0.0
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
from app import analyse as a
|
||||||
|
|
||||||
|
|
||||||
|
def _f(act, ech):
|
||||||
|
return {"categorie": "À classer", "confiance": "basse", "resume": "x", "course": None,
|
||||||
|
"demande": {"reelle": True, "action": act, "echeance": ech}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_briefing_demandes_ouvertes_triees(temp_db):
|
||||||
|
a.enregistrer("a", _f("Repondre", "30/11/2026"), "oa", "e@x", "2026-11-20T08:00:00", temp_db)
|
||||||
|
a.enregistrer("b", _f("Signer", "25/11/2026"), "ob", "e@x", "2026-11-20T09:00:00", temp_db)
|
||||||
|
r = a.briefing("2026-11-21", temp_db)
|
||||||
|
assert [i["message_id"] for i in r["demandes_ouvertes"]] == ["b", "a"]
|
||||||
|
assert r["courses_a_faire"] == [] and r["a_suivre_actifs"] == []
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import pytest
|
||||||
|
from app import brouillon as b, ia
|
||||||
|
|
||||||
|
|
||||||
|
def test_assainir_garde_la_mise_en_page_et_retire_le_dangereux():
|
||||||
|
h = b.assainir('<p onclick="x()">Bonjour <strong>Samia</strong></p><script>alert(1)</script><a href="http://x">lien</a><ul><li>un</li></ul>')
|
||||||
|
assert h == "<p>Bonjour <strong>Samia</strong></p>lien<ul><li>un</li></ul>"
|
||||||
|
assert "onclick" not in h and "script" not in h and "href" not in h
|
||||||
|
|
||||||
|
|
||||||
|
def test_assainir_ferme_les_balises_et_echappe():
|
||||||
|
assert b.assainir("<p>a < b <strong>gras") == "<p>a < b <strong>gras</strong></p>"
|
||||||
|
|
||||||
|
|
||||||
|
def test_texte_brut():
|
||||||
|
assert b.en_texte("<p>Bonjour,</p><p>Merci.<br>A bientot</p><ul><li>un</li></ul>") == "Bonjour,\nMerci.\nA bientot\n- un"
|
||||||
|
|
||||||
|
|
||||||
|
def test_rediger_via_privaite_seulement(monkeypatch):
|
||||||
|
vus = {}
|
||||||
|
def faux(messages, max_tokens=30):
|
||||||
|
vus["m"] = messages
|
||||||
|
return "```html\n<p>Bonjour,</p><p>C'est note.</p><p>Cordialement,<br>Nabil Derouiche</p>\n```"
|
||||||
|
monkeypatch.setattr(ia, "appeler_privaite", faux)
|
||||||
|
r = b.rediger("PO 123", "x@tt.tn", "Merci de confirmer", "- ctx", "dire oui")
|
||||||
|
assert r["objet"] == "RE: PO 123" and "<p>Bonjour,</p>" in r["html"] and "```" not in r["html"]
|
||||||
|
assert "Contexte du fil" in vus["m"][1]["content"] and "dire oui" in vus["m"][1]["content"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_refus_net_si_privaite_injoignable(monkeypatch):
|
||||||
|
def casse(messages, max_tokens=30):
|
||||||
|
raise ia.IAIndisponible("PrivAiTe injoignable")
|
||||||
|
monkeypatch.setattr(ia, "appeler_privaite", casse)
|
||||||
|
with pytest.raises(ia.IAIndisponible):
|
||||||
|
b.rediger("o", "e", "c")
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import pytest
|
||||||
|
from app import analyse as a
|
||||||
|
from app.classifier import manual_classify_and_propose
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.regles_off
|
||||||
|
|
||||||
|
|
||||||
|
def _f(cat, resume="R."):
|
||||||
|
return {"categorie": cat, "confiance": "haute", "resume": resume, "course": None,
|
||||||
|
"demande": {"reelle": False, "action": "", "echeance": ""}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_exemples_max_par_categorie_et_pas_de_corps(temp_db):
|
||||||
|
for i in range(5):
|
||||||
|
manual_classify_and_propose("t%d" % i, "Tunis", {"expediteur": "a@b", "objet": "Course %d" % i}, db_path=temp_db)
|
||||||
|
manual_classify_and_propose("p1", "Pb PO", {"expediteur": "c@d", "objet": "PO 1"}, db_path=temp_db)
|
||||||
|
ex = a.exemples_nabil(temp_db)
|
||||||
|
assert ex.count("=> Tunis") == 3 and "=> Pb PO" in ex
|
||||||
|
|
||||||
|
|
||||||
|
def test_refus_devient_contre_exemple_et_stats(temp_db):
|
||||||
|
a.enregistrer("m1", _f("Box 5G"), "Rapport regional", "x@tt.tn", "2026-11-21T09:00:00", temp_db)
|
||||||
|
a.decider("m1", "categorie", "refuser", temp_db)
|
||||||
|
assert "PAS Box 5G" in a.exemples_nabil(temp_db)
|
||||||
|
a.enregistrer("m2", _f("CI"), "Travaux", "x@tt.tn", "2026-11-21T09:00:00", temp_db)
|
||||||
|
a.decider("m2", "categorie", "accepter", temp_db)
|
||||||
|
st = a.stats_acceptation(temp_db)
|
||||||
|
assert st["total"] == {"acceptees": 1, "refusees": 1}
|
||||||
|
assert st["categories"]["CI"]["acceptees"] == 1 and st["categories"]["Box 5G"]["refusees"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_inclut_exemples_sans_imposer_de_regle():
|
||||||
|
m = a.construire_messages("o", "e", "c", ["Tunis"], "", "- x | y => Tunis")
|
||||||
|
assert "Exemples de choix reels" in m[0]["content"] and "autre categorie un autre jour" in m[0]["content"]
|
||||||
|
assert "Exemples de choix reels" not in a.construire_messages("o", "e", "c", ["Tunis"])[0]["content"]
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import io
|
||||||
|
import zipfile
|
||||||
|
import pytest
|
||||||
|
from app import piece_ia as p
|
||||||
|
|
||||||
|
|
||||||
|
def _docx(txt):
|
||||||
|
b = io.BytesIO()
|
||||||
|
with zipfile.ZipFile(b, "w") as z:
|
||||||
|
z.writestr("word/document.xml", '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>' + txt + "</w:t></w:r></w:p></w:body></w:document>")
|
||||||
|
return b.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def test_texte_et_docx():
|
||||||
|
long = "Bon de commande numero 4500123 pour la livraison de dix ordinateurs avant le 30/11/2026."
|
||||||
|
assert "4500123" in p.extraire_texte("a.txt", long.encode())
|
||||||
|
assert "4500123" in p.extraire_texte("a.docx", _docx(long))
|
||||||
|
|
||||||
|
|
||||||
|
def test_type_inconnu_et_vide():
|
||||||
|
with pytest.raises(p.SansTexte):
|
||||||
|
p.extraire_texte("a.exe", b"x" * 100)
|
||||||
|
with pytest.raises(p.SansTexte):
|
||||||
|
p.extraire_texte("a.txt", b"court")
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
from app import sauvegarde as s
|
||||||
|
from app.db import init_db
|
||||||
|
|
||||||
|
|
||||||
|
def _base(tmp_path):
|
||||||
|
p = str(tmp_path / "courrier.db")
|
||||||
|
init_db(p)
|
||||||
|
return p
|
||||||
|
|
||||||
|
|
||||||
|
def test_une_par_jour_et_rotation(tmp_path):
|
||||||
|
db = _base(tmp_path)
|
||||||
|
assert s.sauvegarder(db) is not None
|
||||||
|
assert s.sauvegarder(db) is None
|
||||||
|
d = s._dossier(db)
|
||||||
|
for i in range(20):
|
||||||
|
open(os.path.join(d, "courrier-2020-01-%02d.db" % (i + 1)), "w").write("x")
|
||||||
|
s.sauvegarder(db, force=True)
|
||||||
|
assert len(s.liste(db)) == s.CONSERVES
|
||||||
|
assert s.liste(db)[0]["jour"] >= "2026"
|
||||||
|
|
||||||
|
|
||||||
|
def test_copie_lisible(tmp_path):
|
||||||
|
db = _base(tmp_path)
|
||||||
|
n = s.sauvegarder(db)
|
||||||
|
c = sqlite3.connect(os.path.join(s._dossier(db), n))
|
||||||
|
assert c.execute("select count(*) from sqlite_master").fetchone()[0] > 0
|
||||||
|
c.close()
|
||||||
Reference in new issue
Block a user