Définition de chaque catégorie écrite par Nabil (écran Catégories), lue par l'IA ; suivi découpé par clé Thread-Index pour les objets partagés (lue en arrière-plan, gardée en base) ; fiches des marchés RLA (table 1048, lecture seule) affichées depuis les références AO et numéros de PO ; sauvegarde quotidienne en un seul fichier, copiée chaque nuit vers le NAS. 199 tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XGaEeTZLvHXfYPUNWkgYoi
97 lines
3.7 KiB
Python
97 lines
3.7 KiB
Python
"""Lien entre un mail et les marches RLA (table 1048 de Baserow, recapitulatif de tous les marches).
|
|
|
|
Lecture seule : Courrier ne fait que des GET, avec le jeton de la sphere RLA (secrets/baserow_rla.key).
|
|
Une reference d'AO (« AO 58/2024 », « Marche n° 58/2024 ») ou un numero de PO (po_an1 a po_an3) trouve dans
|
|
le mail renvoie la fiche du marche. Table gardee 10 minutes en memoire ; Baserow injoignable = liste vide."""
|
|
import os
|
|
import re
|
|
import threading
|
|
import time
|
|
from typing import Any, Dict, List
|
|
|
|
import httpx
|
|
from fastapi import APIRouter, Query
|
|
|
|
BASEROW_URL = os.getenv("BASEROW_URL", "https://baserow.bolbol.tn")
|
|
TABLE_RECAP = int(os.getenv("RLA_TABLE_RECAP", "1048"))
|
|
CLE_PATH = os.getenv("RLA_KEY_PATH", "/app/secrets/baserow_rla.key")
|
|
TTL = 600
|
|
_cache: Dict[str, Any] = {"t": 0.0, "rows": []}
|
|
_verrou = threading.Lock()
|
|
|
|
_AO = re.compile(r"(?i)\b(?:AO|AOI|march[eé])\D{0,8}?(\d{1,4})\s*/\s*(20\d{2})\b")
|
|
_PO = re.compile(r"(?<!\d)(\d{7})(?!\d)")
|
|
|
|
|
|
def _cle() -> str:
|
|
try:
|
|
return open(CLE_PATH, encoding="utf-8").read().strip()
|
|
except OSError:
|
|
return ""
|
|
|
|
|
|
def _texte(v: Any) -> str:
|
|
if isinstance(v, dict):
|
|
return str(v.get("value") or "")
|
|
if isinstance(v, list):
|
|
return ", ".join(_texte(x) for x in v)
|
|
return "" if v is None else str(v)
|
|
|
|
|
|
def marches() -> List[Dict[str, Any]]:
|
|
with _verrou:
|
|
if time.time() - _cache["t"] < TTL and _cache["rows"]:
|
|
return _cache["rows"]
|
|
k = _cle()
|
|
if not k:
|
|
return []
|
|
rows: List[Dict[str, Any]] = []
|
|
url = BASEROW_URL + "/api/database/rows/table/%d/?user_field_names=true&size=200" % TABLE_RECAP
|
|
try:
|
|
while url and len(rows) < 2000:
|
|
r = httpx.get(url, headers={"Authorization": "Token " + k}, timeout=15)
|
|
if r.status_code != 200:
|
|
return _cache["rows"]
|
|
d = r.json()
|
|
rows += d.get("results") or []
|
|
url = d.get("next")
|
|
except httpx.HTTPError:
|
|
return _cache["rows"]
|
|
_cache.update(t=time.time(), rows=rows)
|
|
return rows
|
|
|
|
|
|
def _fiche(r: Dict[str, Any]) -> Dict[str, Any]:
|
|
return {"marche": _texte(r.get("id_marche")), "entrepreneur": _texte(r.get("entrepreneur")),
|
|
"region": _texte(r.get("region_csc") or r.get("region")), "projet": _texte(r.get("projet")),
|
|
"actif": bool(r.get("Actif")), "fin_marche": _texte(r.get("date_fin_marche")),
|
|
"annee": _texte(r.get("annee_contractuelle")), "jours_restants_po": _texte(r.get("jours_restants_po")),
|
|
"taux_fin": _texte(r.get("taux_fin")), "taux_phy": _texte(r.get("taux_phy")),
|
|
"note": _texte(r.get("Notes"))[:240]}
|
|
|
|
|
|
def trouver(texte: str, rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
aos = {(int(n), a) for n, a in _AO.findall(texte or "")}
|
|
pos = set(_PO.findall(texte or ""))
|
|
out, vus = [], set()
|
|
for r in rows:
|
|
ref = _AO.search(_texte(r.get("reference")) or _texte(r.get("id_marche")))
|
|
par_ao = bool(ref and (int(ref.group(1)), ref.group(2)) in aos)
|
|
par_po = bool(pos & {_texte(r.get(c)).strip() for c in ("po_an1", "po_an2", "po_an3")})
|
|
if (par_ao or par_po) and r.get("id") not in vus:
|
|
vus.add(r.get("id"))
|
|
out.append(dict(_fiche(r), par="PO" if par_po and not par_ao else "AO"))
|
|
return out[:8]
|
|
|
|
|
|
def creer_routeur() -> APIRouter:
|
|
router = APIRouter()
|
|
|
|
@router.get("/rla")
|
|
def lien_rla(texte: str = Query(..., min_length=3, max_length=6000)):
|
|
"""Marchés RLA cités dans un texte (objet, résumé, début du corps). Lecture seule."""
|
|
rows = marches()
|
|
return {"marches": trouver(texte, rows), "disponible": bool(rows)}
|
|
|
|
return router
|