Courrier v1.6 (tt-2026-11-069) : Courses pour Tunis, liste a cocher, ajout depuis la lecture, export Excel
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XGaEeWkqZYNP6Wn3mGQsrL
This commit is contained in:
1 parent
ce10cae840
commit
b712ee10cd
8 files changed
+471
-11
No files matched your search
@@ -410,3 +410,96 @@ def set_traite(message_id: str, traite: bool, db_path: Optional[str] = None) ->
|
||||
return get_classement(message_id, db_path)
|
||||
finally:
|
||||
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 delete_course(course_id: int, db_path: Optional[str] = None) -> bool:
|
||||
conn = get_connection(db_path)
|
||||
try:
|
||||
_courses_pret(conn)
|
||||
with conn:
|
||||
return conn.execute("DELETE FROM courses WHERE id = ?", (course_id,)).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()
|
||||
+73
-1
@@ -23,7 +23,13 @@ from app.db import (
|
||||
delete_regle,
|
||||
get_classement,
|
||||
list_classements,
|
||||
set_traite
|
||||
set_traite,
|
||||
list_courses,
|
||||
get_course,
|
||||
add_course,
|
||||
update_course,
|
||||
delete_course,
|
||||
SENS_COURSE
|
||||
)
|
||||
from app.classifier import (
|
||||
classify_mail,
|
||||
@@ -284,6 +290,72 @@ def telecharger_piece(id: str = Query(..., min_length=1, max_length=400), nom: s
|
||||
})
|
||||
|
||||
|
||||
# --- 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", 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}
|
||||
|
||||
|
||||
# --- Classements ---
|
||||
@api.get("/classements")
|
||||
def get_classements(
|
||||
|
||||
@@ -271,3 +271,19 @@ h1, h2, h3, p { margin: 0; }
|
||||
.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; } }
|
||||
+104
-8
@@ -17,19 +17,18 @@
|
||||
telecharger: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4|m7 10 5 5 5-5|M12 15V3', fermer: 'M18 6 6 18|m6 6 12 12', gauche: 'm15 18-6-6 6-6', droite: 'm9 18 6-6-6-6', bas: 'm6 9 6 6 6-6', fleche: 'M5 12h14|m12 5 7 7-7 7'
|
||||
};
|
||||
var NAV = [
|
||||
['tri', 'Tri du jour', true], ['categories', 'Catégories', true], ['groupes', 'Groupes', true], ['regles', 'Règles', true],
|
||||
['recherche', 'Recherche', false], ['courses', 'Courses pour Tunis', false], ['suivi', 'Suivi des demandes', false], ['pj', 'Pièces jointes', false]
|
||||
['tri', 'Tri du jour', true], ['categories', 'Catégories', true], ['groupes', 'Groupes', true], ['courses', 'Courses pour Tunis', true], ['regles', 'Règles', true],
|
||||
['recherche', 'Recherche', false], ['suivi', 'Suivi des demandes', false], ['pj', 'Pièces jointes', false]
|
||||
];
|
||||
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 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' } };
|
||||
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' } };
|
||||
|
||||
/* ---------- Utilitaires ---------- */
|
||||
function auj() { return new Intl.DateTimeFormat('en-CA', { timeZone: TZ }).format(new Date()); }
|
||||
@@ -154,6 +153,7 @@
|
||||
}
|
||||
else if (vue === 'groupes') chargerGroupe();
|
||||
else if (vue === 'regles') chargerRegles();
|
||||
else if (vue === 'courses') chargerCourses();
|
||||
else rendre();
|
||||
document.getElementById('principal').focus();
|
||||
}
|
||||
@@ -284,7 +284,7 @@
|
||||
}
|
||||
var liste = h('div', { class: 'nav-liste' });
|
||||
NAV.forEach(function (n, i) {
|
||||
if (i === 4) liste.appendChild(h('div', { class: 'nav-sep' }, 'Prochainement'));
|
||||
if (i === 5) liste.appendChild(h('div', { class: 'nav-sep' }, 'Prochainement'));
|
||||
liste.appendChild(bouton(n));
|
||||
if (n[2]) mobile.appendChild(bouton(n));
|
||||
});
|
||||
@@ -401,7 +401,7 @@
|
||||
.then(function () { bt.disabled = false; });
|
||||
}
|
||||
function afficherMail(cont, m, r, c) {
|
||||
var badges = h('div', { class: 'lect-badges' }, h('span', { class: 'lect-cat' }, pastille(couleur(m.cat, c && c.id)), m.cat));
|
||||
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); }
|
||||
@@ -414,6 +414,7 @@
|
||||
while (principal.length && /^[\s_\-=]*$/.test(principal[principal.length - 1])) principal.pop();
|
||||
}
|
||||
var corps = principal.join('\n').trim() ? blocsTexte(principal.join('\n')) : h('p', { class: 'lect-vide', text: 'Ce mail ne contient pas de texte à afficher.' });
|
||||
badges.appendChild(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'))));
|
||||
@@ -641,6 +642,101 @@
|
||||
});
|
||||
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?statut=toutes').then(function (r) { C.liste = r.courses || []; C.etat = 'ok'; rendre(); })
|
||||
.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.' : 'Ouvrez un mail et touchez « Ajouter aux courses », ou ajoutez une course ici.'))));
|
||||
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;
|
||||
}
|
||||
function vueBientot(k) {
|
||||
var t = BIENTOT[k];
|
||||
return h('div', null, h('header', { class: 'entete' }, h('h1', null, t[0])),
|
||||
@@ -651,9 +747,9 @@
|
||||
var ancre = document.activeElement && document.activeElement.getAttribute && document.activeElement.getAttribute('aria-label');
|
||||
rendreNav();
|
||||
var p = document.getElementById('principal'); p.textContent = '';
|
||||
var v = S.vue === 'tri' ? vueTri() : S.vue === 'categories' ? vueCategories() : S.vue === 'regles' ? vueRegles() : S.vue === 'groupes' ? vueGroupes() : 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() : vueBientot(S.vue);
|
||||
p.appendChild(v); p.scrollTop = pos;
|
||||
var titre = S.vue === 'tri' ? 'Tri du jour' : S.vue === 'categories' ? 'Catégories' : S.vue === 'regles' ? 'Règles' : S.vue === 'groupes' ? 'Groupes' : 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' : BIENTOT[S.vue][0];
|
||||
document.title = titre + ' · Courrier';
|
||||
if (ancre && !dialogue) { var r = p.querySelector('[aria-label="' + ancre.replace(/"/g, '\\"') + '"]'); if (r && document.activeElement === document.body) r.focus(); }
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
||||
<link rel="stylesheet" href="/static/fonts.css">
|
||||
<link rel="stylesheet" href="/static/nyora.css">
|
||||
<link rel="stylesheet" href="/static/app.css?v=20261118a">
|
||||
<link rel="stylesheet" href="/static/app.css?v=20261118b">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app" class="coque">
|
||||
@@ -20,6 +20,6 @@
|
||||
</div>
|
||||
<div id="calque"></div>
|
||||
<div id="annonce" class="sr" role="status" aria-live="polite"></div>
|
||||
<script src="/static/app.js?v=20261118a"></script>
|
||||
<script src="/static/app.js?v=20261118b"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -4,3 +4,5 @@ pydantic>=2.0.0,<3.0.0
|
||||
httpx>=0.27.0,<1.0.0
|
||||
pyjwt[crypto]>=2.8.0,<3.0.0
|
||||
pytest>=8.0.0,<9.0.0
|
||||
|
||||
openpyxl>=3.1,<4.0.0
|
||||
@@ -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
|
||||
Reference in new issue
Block a user