Compare commits
19
Commits
@@ -82,3 +82,29 @@ Le favicon (`public/favicon.svg`, décliné en `favicon-32.png`, `favicon-16.png
|
||||
|
||||
1. **Texte sombre sur l'accent safran, jamais blanc.** `--accent`/`--on-accent` : le blanc sur `#f5b342` échoue le contrôle AA (décision DS du 20/07/2026). `--on-accent` est toujours une couleur sombre (`#1a2238` clair, `#111520` sombre). Vérifié au pixel sur la variante `posture` de `Chip.vue`.
|
||||
2. **`--nav-text-on-primary` reste une valeur littérale**, pas un alias — voir l'explication détaillée dans la section tokens ci-dessus. Si un nouveau composant a besoin de texte de contraste sur un fond bleu nuit, vérifie d'abord si ce fond est `--nav-primary` (translucide) ou `--nav-primary-solid` (opaque) avant de choisir la variable de texte : elles n'ont pas la même réponse en mode sombre.
|
||||
|
||||
## Navigation par échelles S / M / XL (B10, 02/10/2026)
|
||||
|
||||
**Source unique : `utils/echelles.ts`.** Chaque échelle porte ses `onglets` (`libelle`, `to`, `actif(route)`) ; `ORDRE_ECHELLES` fixe l'ordre S → M → XL ; `echelleDeRoute(route)` rend le groupe et l'onglet courants, ou `null` hors groupe (Manifeste, À propos, Proposer, Signaler, fiche, `/rag`). Aucun libellé d'échelle ni d'onglet ne se recopie dans un composant : ajouter un onglet = une ligne dans ce fichier, et `scripts/test-echelles-nav.mjs` (une ligne de cas).
|
||||
|
||||
| Échelle | Accroche | Onglets |
|
||||
|---|---|---|
|
||||
| S | Partir de soi | Jobs (`/trouver-du-taf`) · Outils (`/outils`) |
|
||||
| M | La communauté | Écosystème d'entraide (`/`) · Réseaux AEP (`/agences`) · Codev (`/codev*`) |
|
||||
| XL | Contribuer | Recherche média (`/media`) · Publications (`/media?tab=projets`) |
|
||||
|
||||
**Seuils** (CSS des composants, pas de breakpoint Tailwind : 1280 et 1440 n'en sont pas) :
|
||||
|
||||
| Largeur | En-tête | Sous l'en-tête |
|
||||
|---|---|---|
|
||||
| ≥ 1440 | logo complet · trois groupes · Manifeste · À propos · Soutenir (contour safran) · + Proposer (plein safran) · sombre | — |
|
||||
| 1280-1439 | idem, logo réduit au bloc « AEP » | — |
|
||||
| 1024-1279 | logo complet · groupe courant seul · Manifeste · + Proposer · sombre · « Menu » | — |
|
||||
| 768-1023 | logo réduit · groupe courant seul · Manifeste · + Proposer · sombre · « Menu » | — |
|
||||
| < 768 | logo complet · sombre · + (icône) · ☰ | `FilEchelle` (28 px), sauf hors groupe |
|
||||
|
||||
**Composants** : `NavEchelles.vue` (barre ; chaque groupe est un `<ul>` étiqueté par son accroche via `aria-labelledby`, onglet courant en `aria-current="page"`), `NavTiroir.vue` (menu < 1280 : `role="dialog"`, voile, Échap, focus piégé et rendu à l'élément d'ouverture, fermeture au changement de route et au passage à ≥ 1280), `FilEchelle.vue` (< 768, monté dans `app.vue` entre `<header>` et le conteneur de page, **jamais dedans** : `/` y est en `overflow-hidden`). Le lien de don vit dans `utils/liens.ts` (`SOUTENIR_URL`).
|
||||
|
||||
**Texte atténué** : `color-mix(in srgb, var(--text) 78 %, transparent)`, pas `--text-muted` (3,7:1 sur blanc, sous AA à 0,8 rem) ni `opacity` (qui éteindrait aussi l'anneau de focus).
|
||||
|
||||
**Signaler** n'est plus dans la barre d'ordinateur : il reste dans le tiroir, dans chaque fiche, et en pied d'À propos.
|
||||
|
||||
@@ -204,6 +204,8 @@ cout_eur = ((tokens_in × 0.02 + tokens_out × 0.04) / 1_000_000) × 0.93
|
||||
|
||||
Le filtre NocoDB par date (`gte,YYYY-MM-DD`) n'est pas supporté en v0.301.5. Contournement : récupération de tous les records stats_usage (limit=1000) et filtre JavaScript par mois/année.
|
||||
|
||||
**Côté chatbot (AF5, 29/09)** : `server/utils/circuitBreaker.ts` n'appliquait pas ce contournement. Il envoyait `where=(timestamp,gte,…)&fields=cout_eur,timestamp` et recevait un 422 à chaque appel : fail-open silencieux, budget jamais vérifié depuis la V2. Il suit désormais le worker : **aucune colonne nommée dans la requête** (ni `where`, ni `fields`, ni `sort`), lecture paginée (`limit`/`offset` 1000), mois filtré en JS sur `timestamp`, sinon `CreatedAt`, sinon `created_at`. Chaque lecture écrit au journal `[circuitBreaker] budget lu : X € / 20 € (n lignes AAAA-MM sur N lues)` ; un échec écrit `budget NON vérifié`. Test : `node scripts/test-circuit-breaker.mjs` (faux NocoDB qui rejette en 422 toute colonne absente). Seule `/api/chatbot` vérifie le budget ; `-reseaux` et `-taff` ne le lisent ni ne l'écrivent (asymétrie pré-existante), et les appels servis par un tier gratuit s'inscrivent à 0 €.
|
||||
|
||||
---
|
||||
|
||||
## 7. Infrastructure
|
||||
@@ -330,3 +332,91 @@ Pattern à généraliser :
|
||||
4. Normalize(tags) → taxonomie contrôlée
|
||||
5. Log(usage) → stats_usage
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 11. B5 (2026-09-27) — Formulaire assoupli + pipe adapté (fusion, pas réécriture)
|
||||
|
||||
Ce qui suit documente les écarts posés par le batch B5 (décisions de la
|
||||
maîtrise d'œuvre du 27/09). Les sections 1 à 10 ci-dessus restent la
|
||||
référence de fond (taxonomie, système prompt d'origine, circuit breaker) ;
|
||||
cette section documente ce qui a changé dans `worker/enrich.js` et le pipe
|
||||
de soumission (`server/api/submit/`).
|
||||
|
||||
### 11.1 Mapping soumission libre → colonnes NocoDB existantes (M1)
|
||||
|
||||
Le formulaire `/proposer` assoupli (`components/FormLibre.vue`,
|
||||
`utils/submitLibre.ts`) écrit dans la table orgas existante, **aucune colonne
|
||||
nouvelle** :
|
||||
|
||||
| Champ formulaire | Colonne NocoDB | Règle |
|
||||
|---|---|---|
|
||||
| 1er lien de la liste | `url` | `null` si aucun lien |
|
||||
| texte « pourquoi » + tous les liens | `description_user` | `{texte}\n\nLiens :\n{lien1}\n{lien2}...` — et si aucun type suggéré, la ligne `Type : non précisé` est préfixée en tête |
|
||||
| — | `nom` | hostname du 1er lien, ou 60 premiers caractères du texte si aucun lien, préfixé `[à qualifier] ` |
|
||||
| chip type suggéré | `submission_type` | valeur choisie (`ecosysteme`/`reseau`/`job`/`outil`) ; si aucune chip → `ecosysteme` par défaut (voir ligne `Type : non précisé` ci-dessus) |
|
||||
| chip « Références » | *(table `ressources_references`, pas orgas)* | `titre`/`auteur` placeholders, `description` = texte + liens, comme les autres |
|
||||
| email (optionnel) | `submitted_by_email` | — |
|
||||
|
||||
**À faire au déploiement** : ajouter l'option `libre` à la liste de valeurs
|
||||
acceptées par `submission_type` si l'on veut un jour distinguer une
|
||||
soumission libre d'une soumission via un des 5 formulaires détaillés — non
|
||||
fait ici pour ne pas tester un ALTER contre la prod sans l'avoir vérifié.
|
||||
|
||||
### 11.2 Worker — écarts (M2)
|
||||
|
||||
| Sujet | NAV V2 (§1-10 ci-dessus) | AEP B5 |
|
||||
|---|---|---|
|
||||
| LLM | Mistral Nemo, appel direct | **Bifrost** (`${BIFROST_URL}/v1/chat/completions`, header `x-bf-vk`), modèle `WORKER_MODEL` (défaut `groq/openai/gpt-oss-20b` depuis le 28/09, voir §11.3) |
|
||||
| Scrape | crawl4ai (Python, `AsyncHTTPCrawlerStrategy`) | **fetch natif Node 22** — timeout 8 s, corps plafonné 500 Ko, extraction titre + meta description + `og:*` + texte visible tronqué à 4000 caractères, `User-Agent: AEP/2.0 contact@trans-former.fr` |
|
||||
| Notification | Resend (email Jules) | **ntfy** (`POST https://ntfy.sh/$NTFY_TOPIC`) — le message ne contient JAMAIS l'email ni le texte libre du contributeur, seulement id NocoDB / nom suggéré / type / confiance |
|
||||
| Seuil « 5 fiches pending » | Email si ≥ 5 en attente | **Retiré** (décision MOE : volume faible, une notif par fiche traitée suffit — à réactiver si le volume monte) |
|
||||
| Sortie JSON du LLM | `description_enrichie, points_cles, tags_fonction, echelle, territoire, localisation_ville, confiance` | `{nom, description, type_suggere, ville, tags[], confiance}` — le worker écrit ensuite dans les colonnes existantes (`description_enrichie`, `tags_fonction`, `localisation_ville`) |
|
||||
| Écriture de `nom` | jamais réécrit | réécrit **seulement** si le nom actuel commence par `[à qualifier]` (placeholder posé par le formulaire assoupli) |
|
||||
| Écriture de `submission_type` | jamais réécrit | réécrit **seulement** si `description_user` commence par `Type : non précisé` (l'utilisateur n'a pas choisi de chip) et que le type suggéré par le LLM est valide |
|
||||
| Prix des tokens | fixe (prix Mistral Nemo) | variables `WORKER_PRICE_IN_USD_PER_M` / `WORKER_PRICE_OUT_USD_PER_M`, défaut **0** (tier Groq du tier RAPIDE Bifrost, gratuit) |
|
||||
| Lock | `/tmp/nav-worker.lock` | `/tmp/aep-worker.lock` (configurable `WORKER_LOCK_FILE`) |
|
||||
| Chemin VPS | `/opt/nav-carte/worker/` | `/opt/aep-worker/` (voir `deploy/aep-worker/README.md`) |
|
||||
| Timer | 5 min | 15 min (`deploy/aep-worker/aep-worker.timer`) |
|
||||
|
||||
Le mode `--dry-run` (`node enrich.js --dry-run`) lit
|
||||
`worker/fixtures/dry-run-rows.json` au lieu de NocoDB, n'écrit rien, et par
|
||||
défaut mock aussi le scrape et l'appel Bifrost (`DRY_RUN_LIVE=1` pour
|
||||
forcer de vrais appels réseau sans jamais toucher NocoDB).
|
||||
|
||||
### 11.3 Modèles Groq retirés — bascule sur gpt-oss (2026-09-28)
|
||||
|
||||
Groq ne sert plus `llama-3.1-8b-instant` ni `llama-3.3-70b-versatile`
|
||||
(404 `model_not_found` via Bifrost, constaté au test M3 du 28/09).
|
||||
|
||||
| Consommateur | Avant | Après | Où |
|
||||
|---|---|---|---|
|
||||
| Worker (`worker/enrich.js`) | `groq/llama-3.1-8b-instant` | `groq/openai/gpt-oss-20b` | prod : `WORKER_MODEL` dans `/opt/aep/.env` depuis le 28/09 ; défaut du code aligné |
|
||||
| Chatbots, tier RAPIDE | `groq/llama-3.1-8b-instant` | `groq/openai/gpt-oss-20b` | `server/utils/bifrost.ts`, replis inchangés |
|
||||
| Chatbots, tier APPROFONDI | `groq/llama-3.3-70b-versatile` | `groq/openai/gpt-oss-120b` | `server/utils/bifrost.ts`, replis inchangés |
|
||||
| RAG Pensées (LightRAG) | `gemini-oai/models/gemini-2.5-flash-lite` | inchangé | `/opt/lightrag/.env`, hors de ce routage |
|
||||
|
||||
Entre le retrait et ce correctif, chaque appel chatbot partait sur le
|
||||
premier repli Gemini (`stats_usage` depuis le 23/09 environ) : service
|
||||
rendu, modèle primaire jamais servi.
|
||||
|
||||
**gpt-oss est un modèle à raisonnement.** Deux conséquences :
|
||||
- la réponse porte `choices[0].message.reasoning` à côté de `content`. Les
|
||||
trois routes (`chatbot`, `chatbot-reseaux`, `chatbot-taff`) et le worker ne
|
||||
lisent que `content` (JSON), `usage` et `extra_fields` : le champ est
|
||||
ignoré, rien n'en dépend. `chatbot-pensees` lit la réponse de LightRAG
|
||||
(`response`, `references`), pas celle de Bifrost ;
|
||||
- les tokens de raisonnement sont décomptés de `max_tokens`. Si le
|
||||
fournisseur rend un JSON tronqué en HTTP 200, Bifrost ne bascule pas et
|
||||
l'usager lit « Je n'ai pas pu analyser ta demande » (s'il le rejette en
|
||||
400, le repli Gemini prend le relais : dégradé, pas cassé). Les routes chatbot ajoutent donc
|
||||
`REASONING_MARGIN_TOKENS` (800) à leur budget de contenu (600 ou 700), et
|
||||
`bifrostContent()` écrit un avertissement au journal quand
|
||||
`finish_reason` vaut `length`. Le worker garde `max_tokens: 800` (sortie
|
||||
courte, M3 passé en 1,6 s) ; à relever si `tokens_out` approche 800 dans
|
||||
`stats_usage`.
|
||||
|
||||
**Non testé depuis Windows** (Bifrost écoute sur le loopback du VPS). Test
|
||||
réel au checkpoint : un appel par route, relever `extra_fields` (modèle
|
||||
réellement servi), `usage.completion_tokens`, `finish_reason`, et le
|
||||
modèle inscrit dans `stats_usage` pour `/api/chatbot`.
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
<template>
|
||||
<div class="flex flex-col h-screen overflow-hidden" :class="{ dark: isDark }" style="background: var(--nav-bg);">
|
||||
|
||||
<!-- ═══════════════════════════════════════ TOP NAV GLOBAL -->
|
||||
<!-- ═══════════════════════════════════════ TOP NAV GLOBAL (B10 : échelles S / M / XL) -->
|
||||
<header
|
||||
class="flex items-center justify-between px-4 py-2.5 shrink-0 relative z-[9999] shadow-sm gap-3"
|
||||
class="app-header flex items-center px-4 shrink-0 relative z-[9999] shadow-sm gap-3"
|
||||
style="background: var(--nav-surface); border-bottom: 1px solid var(--nav-bg-alt);"
|
||||
>
|
||||
<!-- Logo -->
|
||||
<!-- Logo : texte complet sauf 768-1023 et 1280-1439 (place des onglets) -->
|
||||
<a href="/" class="logo-link flex items-center gap-2 hover:opacity-90 transition-opacity shrink-0" title="Architecture d'Écologie Politique">
|
||||
<div
|
||||
class="h-8 px-2 rounded-lg flex items-center justify-center shrink-0"
|
||||
@@ -20,112 +20,38 @@
|
||||
</div>
|
||||
</a>
|
||||
|
||||
<!-- ── Onglets desktop (≥1024px) — remplace la barre de recherche ── -->
|
||||
<nav class="hidden lg:flex flex-1 justify-center items-end gap-0 mx-6" aria-label="Navigation projets">
|
||||
<NuxtLink
|
||||
to="/outils"
|
||||
class="nav-tab"
|
||||
:class="{ 'nav-tab--active': route.path === '/outils' }"
|
||||
>
|
||||
Outils
|
||||
</NuxtLink>
|
||||
<NuxtLink
|
||||
to="/"
|
||||
class="nav-tab"
|
||||
:class="{ 'nav-tab--active': route.path === '/' }"
|
||||
>
|
||||
Écosystème Entraide
|
||||
</NuxtLink>
|
||||
<NuxtLink
|
||||
to="/agences"
|
||||
class="nav-tab"
|
||||
:class="{ 'nav-tab--active': route.path === '/agences' }"
|
||||
>
|
||||
Réseaux AEP
|
||||
</NuxtLink>
|
||||
<NuxtLink
|
||||
to="/trouver-du-taf"
|
||||
class="nav-tab"
|
||||
:class="{ 'nav-tab--active': route.path === '/trouver-du-taf' }"
|
||||
>
|
||||
Jobs
|
||||
</NuxtLink>
|
||||
<NuxtLink
|
||||
to="/codev"
|
||||
class="nav-tab"
|
||||
:class="{ 'nav-tab--active': route.path.startsWith('/codev') }"
|
||||
>
|
||||
Codev
|
||||
</NuxtLink>
|
||||
<NuxtLink
|
||||
to="/media"
|
||||
class="nav-tab"
|
||||
:class="{ 'nav-tab--active': route.path.startsWith('/media') }"
|
||||
>
|
||||
recherche-média
|
||||
</NuxtLink>
|
||||
</nav>
|
||||
|
||||
<!-- ── Barre recherche mobile (640px–1024px) — masquée < 640px car accessible dans la sheet -->
|
||||
<div class="hidden sm:flex lg:hidden flex-1 mx-2">
|
||||
<label class="flex items-center gap-2 w-full px-3 py-1.5 rounded-xl border" style="background: var(--nav-bg); border-color: var(--nav-bg-alt);">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="color: var(--nav-text-muted); flex-shrink: 0;">
|
||||
<circle cx="11" cy="11" r="8"/>
|
||||
<line x1="21" y1="21" x2="16.65" y2="16.65"/>
|
||||
</svg>
|
||||
<input
|
||||
v-model="headerSearch"
|
||||
type="search"
|
||||
placeholder="Rechercher…"
|
||||
class="flex-1 bg-transparent border-0 outline-none text-sm"
|
||||
style="color: var(--nav-text); font-family: var(--nav-font);"
|
||||
autocomplete="off"
|
||||
@input="onHeaderSearch"
|
||||
@keydown.enter="onHeaderSearch"
|
||||
/>
|
||||
<button
|
||||
v-if="headerSearch"
|
||||
type="button"
|
||||
@click.stop="clearHeaderSearch"
|
||||
class="flex-shrink-0"
|
||||
style="color: var(--nav-text-muted);"
|
||||
aria-label="Effacer la recherche"
|
||||
>
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
|
||||
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
|
||||
</svg>
|
||||
</button>
|
||||
</label>
|
||||
</div>
|
||||
<!-- Échelles : trois groupes ≥ 1280, groupe courant 768-1279, rien < 768 (fil d'échelle) -->
|
||||
<NavEchelles />
|
||||
<div class="flex-1 md:hidden" aria-hidden="true" />
|
||||
|
||||
<!-- Actions droite -->
|
||||
<div class="flex items-center gap-2 shrink-0">
|
||||
<NuxtLink
|
||||
to="/manifeste"
|
||||
class="px-3 py-1.5 rounded-lg text-sm font-medium transition-all hover:opacity-80 hidden md:inline-flex items-center gap-1"
|
||||
:style="route.path === '/manifeste' ? 'color: var(--nav-primary-solid); font-weight: 700;' : 'color: var(--nav-text-muted);'"
|
||||
class="header-lien hidden md:inline-flex"
|
||||
:aria-current="route.path === '/manifeste' ? 'page' : undefined"
|
||||
>
|
||||
Manifeste
|
||||
</NuxtLink>
|
||||
<NuxtLink
|
||||
to="/a-propos"
|
||||
class="px-3 py-1.5 rounded-lg text-sm font-medium transition-all hover:opacity-80 hidden md:inline-flex items-center gap-1"
|
||||
style="color: var(--nav-text-muted);"
|
||||
class="header-lien header-xl"
|
||||
:aria-current="route.path === '/a-propos' ? 'page' : undefined"
|
||||
>
|
||||
À propos
|
||||
</NuxtLink>
|
||||
<NuxtLink
|
||||
to="/signaler"
|
||||
class="px-3 py-1.5 rounded-lg text-sm font-medium transition-all hover:opacity-80 hidden lg:inline-flex items-center gap-1"
|
||||
style="color: var(--nav-text-muted);"
|
||||
<a
|
||||
:href="SOUTENIR_URL"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="header-soutenir header-xl"
|
||||
>
|
||||
Signaler
|
||||
</NuxtLink>
|
||||
<!-- Proposer une ressource (5 onglets) -->
|
||||
Soutenir
|
||||
</a>
|
||||
<!-- Proposer une ressource -->
|
||||
<NuxtLink
|
||||
to="/proposer"
|
||||
class="px-3 py-1.5 rounded-lg text-sm font-semibold transition-all hover:opacity-80 hidden sm:inline-flex items-center gap-1"
|
||||
style="background: var(--nav-accent); color: var(--nav-text);"
|
||||
class="header-proposer hidden md:inline-flex"
|
||||
>
|
||||
+ Proposer
|
||||
</NuxtLink>
|
||||
@@ -153,71 +79,51 @@
|
||||
<!-- Mobile : proposer icône -->
|
||||
<NuxtLink
|
||||
to="/proposer"
|
||||
class="sm:hidden p-2 rounded-lg"
|
||||
style="background: var(--nav-accent); color: var(--nav-text);"
|
||||
class="md:hidden p-2 rounded-lg"
|
||||
style="background: var(--accent); color: var(--on-accent);"
|
||||
title="Proposer une ressource"
|
||||
aria-label="Proposer"
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>
|
||||
</svg>
|
||||
</NuxtLink>
|
||||
|
||||
<!-- Hamburger mobile (lg:hidden) — toujours en dernier à droite -->
|
||||
<div class="lg:hidden relative">
|
||||
<button
|
||||
@click="hamburgerOpen = !hamburgerOpen"
|
||||
class="p-2 rounded-lg transition-all hover:opacity-80"
|
||||
style="background: var(--nav-bg-alt); color: var(--nav-text-muted);"
|
||||
:aria-label="hamburgerOpen ? 'Fermer le menu' : 'Menu'"
|
||||
:aria-expanded="hamburgerOpen"
|
||||
>
|
||||
<svg v-if="!hamburgerOpen" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" aria-hidden="true">
|
||||
<line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/>
|
||||
</svg>
|
||||
<svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" aria-hidden="true">
|
||||
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
|
||||
</svg>
|
||||
</button>
|
||||
<div
|
||||
v-if="hamburgerOpen"
|
||||
class="absolute right-0 top-full mt-1 rounded-lg shadow-lg min-w-[210px] py-1"
|
||||
style="background: var(--nav-surface); border: 1px solid var(--nav-bg-alt); z-index: 9999;"
|
||||
@click="hamburgerOpen = false"
|
||||
>
|
||||
<NuxtLink to="/outils" class="block px-4 py-2.5 text-sm font-medium transition-opacity hover:opacity-70" :style="route.path === '/outils' ? 'color: var(--nav-primary-solid); font-weight: 700;' : 'color: var(--nav-text);'">Outils</NuxtLink>
|
||||
<NuxtLink to="/" class="block px-4 py-2.5 text-sm font-medium transition-opacity hover:opacity-70" :style="route.path === '/' ? 'color: var(--nav-primary-solid); font-weight: 700;' : 'color: var(--nav-text);'">Écosystème Entraide</NuxtLink>
|
||||
<NuxtLink to="/agences" class="block px-4 py-2.5 text-sm transition-opacity hover:opacity-70" :style="route.path === '/agences' ? 'color: var(--nav-primary-solid); font-weight: 700;' : 'color: var(--nav-text);'">Réseaux AEP</NuxtLink>
|
||||
<NuxtLink to="/trouver-du-taf" class="block px-4 py-2.5 text-sm transition-opacity hover:opacity-70" :style="route.path === '/trouver-du-taf' ? 'color: var(--nav-primary-solid); font-weight: 700;' : 'color: var(--nav-text);'">Jobs</NuxtLink>
|
||||
<NuxtLink to="/rag" class="block px-4 py-2.5 text-sm transition-opacity hover:opacity-70" style="color: var(--nav-text);">recherche-média</NuxtLink>
|
||||
<NuxtLink to="/codev" class="block px-4 py-2.5 text-sm transition-opacity hover:opacity-70" :style="route.path.startsWith('/codev') ? 'color: var(--nav-primary-solid); font-weight: 700;' : 'color: var(--nav-text);'">Codev</NuxtLink>
|
||||
<div style="height: 1px; background: var(--nav-bg-alt); margin: 4px 0;"></div>
|
||||
<NuxtLink to="/manifeste" class="block px-4 py-2.5 text-sm transition-opacity hover:opacity-70" :style="route.path === '/manifeste' ? 'color: var(--nav-primary-solid); font-weight: 700;' : 'color: var(--nav-text-muted);'">Manifeste</NuxtLink>
|
||||
<NuxtLink to="/a-propos" class="block px-4 py-2.5 text-sm transition-opacity hover:opacity-70" style="color: var(--nav-text-muted);">À propos</NuxtLink>
|
||||
<a href="https://liberapay.com/trans-former.fr/donate" target="_blank" rel="noopener noreferrer" class="block px-4 py-2.5 text-sm transition-opacity hover:opacity-70" style="color: var(--nav-text-muted);">Soutenir →</a>
|
||||
<NuxtLink to="/signaler" class="block px-4 py-2.5 text-sm transition-opacity hover:opacity-70" style="color: var(--nav-text-muted);">Signaler</NuxtLink>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Menu (< 1280) : ouvre le tiroir ; le mot est écrit à partir de 768 -->
|
||||
<button
|
||||
type="button"
|
||||
class="header-menu"
|
||||
aria-label="Ouvrir le menu"
|
||||
aria-haspopup="dialog"
|
||||
:aria-expanded="menuOpen"
|
||||
@click="menuOpen = true"
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" aria-hidden="true">
|
||||
<line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/>
|
||||
</svg>
|
||||
<span class="header-menu__mot" aria-hidden="true">Menu</span>
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Fil d'échelle (< 768) : dans le flux de la colonne, hors du conteneur de page -->
|
||||
<FilEchelle />
|
||||
|
||||
<!-- Contenu page (flex-1 pour remplir l'espace) -->
|
||||
<div class="flex-1" :class="route.path === '/' ? 'overflow-hidden' : 'overflow-y-auto'">
|
||||
<div class="flex-1 min-h-0" :class="route.path === '/' ? 'overflow-hidden' : 'overflow-y-auto'">
|
||||
<NuxtPage />
|
||||
</div>
|
||||
|
||||
<!-- Bandeau bas — transparence IA + soutien + compteurs semaine -->
|
||||
<BandeauBas />
|
||||
|
||||
<NavTiroir :open="menuOpen" @close="menuOpen = false" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
const router = useRouter()
|
||||
import { SOUTENIR_URL } from '~/utils/liens'
|
||||
|
||||
const route = useRoute()
|
||||
|
||||
const hamburgerOpen = ref(false)
|
||||
watch(() => route.path, () => { hamburgerOpen.value = false })
|
||||
const menuOpen = ref(false)
|
||||
|
||||
// ── Dark mode ─────────────────────────────────────────────────────────────
|
||||
const isDark = ref(false)
|
||||
@@ -240,40 +146,14 @@ function toggleDark() {
|
||||
localStorage.setItem('aep_theme', 'light')
|
||||
}
|
||||
}
|
||||
|
||||
// ── Barre de recherche header mobile ─────────────────────────────────────
|
||||
const headerSearch = ref((route.query.q as string) ?? '')
|
||||
|
||||
// Sync depuis URL quand la route change
|
||||
watch(() => route.query.q, (v) => {
|
||||
headerSearch.value = (v as string) ?? ''
|
||||
})
|
||||
|
||||
function onHeaderSearch() {
|
||||
const q = headerSearch.value.trim()
|
||||
if (route.path === '/') {
|
||||
router.replace({ query: q ? { ...route.query, q } : { ...route.query, q: undefined } })
|
||||
} else if (q) {
|
||||
router.push({ path: '/', query: { q } })
|
||||
}
|
||||
}
|
||||
|
||||
function clearHeaderSearch() {
|
||||
headerSearch.value = ''
|
||||
if (route.path === '/') {
|
||||
const q = { ...route.query }
|
||||
delete q.q
|
||||
router.replace({ query: Object.keys(q).length ? q : undefined })
|
||||
}
|
||||
}
|
||||
|
||||
// ── Fiche aléatoire ───────────────────────────────────────────────────────
|
||||
function goRandom() {
|
||||
router.push({ path: '/', query: { random: '1' } })
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
/* ── En-tête ──────────────────────────────────────────────────────────── */
|
||||
.app-header {
|
||||
min-height: 52px;
|
||||
}
|
||||
|
||||
/* ── Logo header (texte 2 lignes) ─────────────────────────────────────── */
|
||||
.logo-text {
|
||||
line-height: 1.05;
|
||||
@@ -288,39 +168,96 @@ function goRandom() {
|
||||
@media (min-width: 1024px) {
|
||||
.logo-line-1, .logo-line-2 { font-size: 0.85rem; }
|
||||
}
|
||||
/* Le groupe courant (768-1023) et les trois groupes (1280-1439) prennent la place du texte */
|
||||
@media (min-width: 768px) and (max-width: 1023px), (min-width: 1280px) and (max-width: 1439px) {
|
||||
.logo-text { display: none; }
|
||||
}
|
||||
|
||||
/* ── Onglets header desktop ───────────────────────────────────────────── */
|
||||
.nav-tab {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
flex-direction: column;
|
||||
/* ── Liens et boutons de droite ───────────────────────────────────────── */
|
||||
.header-lien {
|
||||
align-items: center;
|
||||
padding: 6px 16px 8px;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 500;
|
||||
color: var(--nav-text-muted);
|
||||
padding: 6px 8px;
|
||||
border-radius: var(--radius-md);
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: var(--fw-medium);
|
||||
white-space: nowrap;
|
||||
text-decoration: none;
|
||||
transition: color 0.15s;
|
||||
border-bottom: 2px solid transparent;
|
||||
gap: 2px;
|
||||
color: color-mix(in srgb, var(--text) 78%, transparent);
|
||||
}
|
||||
.header-lien:hover,
|
||||
.header-lien[aria-current="page"] {
|
||||
color: var(--text);
|
||||
}
|
||||
.header-lien[aria-current="page"] {
|
||||
font-weight: var(--fw-bold);
|
||||
}
|
||||
|
||||
.nav-tab:hover {
|
||||
color: var(--nav-text);
|
||||
.header-soutenir {
|
||||
align-items: center;
|
||||
padding: 5px 10px;
|
||||
border: 1.5px solid var(--accent);
|
||||
border-radius: var(--radius-md);
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: var(--fw-semibold);
|
||||
white-space: nowrap;
|
||||
text-decoration: none;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.nav-tab--active {
|
||||
color: var(--nav-text);
|
||||
border-bottom-color: var(--nav-primary-solid);
|
||||
font-weight: 600;
|
||||
.header-proposer {
|
||||
align-items: center;
|
||||
padding: 6px 11px;
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--accent);
|
||||
color: var(--on-accent);
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: var(--fw-semibold);
|
||||
white-space: nowrap;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.nav-tab-badge {
|
||||
font-size: 0.6rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--nav-text-muted);
|
||||
opacity: 0.65;
|
||||
.header-soutenir:hover,
|
||||
.header-proposer:hover {
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.header-lien:focus-visible,
|
||||
.header-soutenir:focus-visible,
|
||||
.header-proposer:focus-visible,
|
||||
.header-menu:focus-visible {
|
||||
outline: 2px solid var(--focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* À propos et Soutenir : barre complète seulement (≥ 1280), sinon dans le tiroir */
|
||||
.header-xl { display: none; }
|
||||
@media (min-width: 1280px) {
|
||||
.header-xl { display: inline-flex; }
|
||||
}
|
||||
|
||||
.header-menu {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 8px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--bg-alt);
|
||||
color: var(--text);
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: var(--fw-semibold);
|
||||
cursor: pointer;
|
||||
}
|
||||
.header-menu__mot { display: none; }
|
||||
@media (min-width: 768px) {
|
||||
.header-menu {
|
||||
padding: 5px 10px;
|
||||
border-color: var(--border);
|
||||
background: transparent;
|
||||
}
|
||||
.header-menu__mot { display: inline; }
|
||||
}
|
||||
@media (min-width: 1280px) {
|
||||
.header-menu { display: none; }
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,488 +0,0 @@
|
||||
<template>
|
||||
<!-- ═══════════════════════════════════════ BANDEAU BAS ═══════════════════ -->
|
||||
<!-- DESKTOP uniquement (≥1024px) — mobile a le FAB séparé -->
|
||||
<footer
|
||||
v-if="!isMobile"
|
||||
ref="bandeauEl"
|
||||
class="bandeau-bas shrink-0"
|
||||
:class="{ 'bandeau-collapsed': isCollapsed }"
|
||||
aria-label="Informations projet AEP"
|
||||
@mouseenter="onMouseEnter"
|
||||
@mouseleave="onMouseLeave"
|
||||
>
|
||||
<!-- Contenu plein -->
|
||||
<div class="bandeau-inner" :class="{ 'bandeau-inner--hidden': isCollapsed }">
|
||||
|
||||
<!-- ── GAUCHE : Transparence IA ──────────────────────────────────────── -->
|
||||
<div class="bandeau-col">
|
||||
<p class="bandeau-label">Transparence IA</p>
|
||||
<template v-if="stats">
|
||||
<p class="bandeau-value">
|
||||
Coût IA ce mois : <strong>{{ stats.cout_mois_eur.toFixed(2) }} €</strong>
|
||||
·
|
||||
Tokens : <strong>{{ stats.tokens_mois.toLocaleString('fr-FR') }}</strong>
|
||||
</p>
|
||||
<!-- Jauge -->
|
||||
<div class="jauge-track" aria-label="Budget IA consommé" role="progressbar" :aria-valuenow="jaugePct" aria-valuemin="0" aria-valuemax="100">
|
||||
<div class="jauge-fill" :style="{ width: jaugePct + '%' }" />
|
||||
</div>
|
||||
<p class="bandeau-sub">
|
||||
{{ stats.requetes_mois }} requête{{ stats.requetes_mois !== 1 ? 's' : '' }} ce mois
|
||||
</p>
|
||||
</template>
|
||||
<template v-else-if="loading">
|
||||
<p class="bandeau-sub">Chargement…</p>
|
||||
</template>
|
||||
<template v-else>
|
||||
<p class="bandeau-sub">Données indisponibles</p>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- ── MILIEU : CTA Soutien ──────────────────────────────────────────── -->
|
||||
<div class="bandeau-col bandeau-col--center">
|
||||
<div class="soutenir-wrap">
|
||||
<button
|
||||
class="btn-soutenir"
|
||||
type="button"
|
||||
@click="modalOpen = true"
|
||||
@mouseenter="tooltipVisible = true"
|
||||
@mouseleave="tooltipVisible = false"
|
||||
@focus="tooltipVisible = true"
|
||||
@blur="tooltipVisible = false"
|
||||
aria-label="Soutenir le projet AEP sur Liberapay"
|
||||
>
|
||||
Soutenir le projet
|
||||
</button>
|
||||
<!-- Tooltip au hover -->
|
||||
<div v-if="tooltipVisible" class="soutenir-tooltip" role="tooltip">
|
||||
1 € = 30 fiches mises en ligne
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── DROITE : Compteurs semaine ────────────────────────────────────── -->
|
||||
<div class="bandeau-col bandeau-col--right">
|
||||
<p class="bandeau-label">Cette semaine</p>
|
||||
<template v-if="stats">
|
||||
<p class="bandeau-value">
|
||||
{{ stats.fiches_semaine }} fiche{{ stats.fiches_semaine !== 1 ? 's' : '' }} ajoutée{{ stats.fiches_semaine !== 1 ? 's' : '' }}
|
||||
</p>
|
||||
<p class="bandeau-sub">
|
||||
{{ stats.requetes_chatbot_semaine }} requête{{ stats.requetes_chatbot_semaine !== 1 ? 's' : '' }} chatbot
|
||||
</p>
|
||||
</template>
|
||||
<template v-else>
|
||||
<p class="bandeau-sub">—</p>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Barre fine (état collapsed) -->
|
||||
<div class="bandeau-thin" :class="{ 'bandeau-thin--visible': isCollapsed }">
|
||||
<span class="bandeau-thin-label">AEP · Transparence IA</span>
|
||||
</div>
|
||||
|
||||
<!-- ── MODAL Liberapay ───────────────────────────────────────────────── -->
|
||||
<Teleport to="body">
|
||||
<Transition name="backdrop">
|
||||
<div
|
||||
v-if="modalOpen"
|
||||
class="modal-backdrop"
|
||||
@click="modalOpen = false"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</Transition>
|
||||
<Transition name="modal">
|
||||
<div
|
||||
v-if="modalOpen"
|
||||
class="modal-box"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Soutenir AEP sur Liberapay"
|
||||
>
|
||||
<button
|
||||
class="modal-close"
|
||||
type="button"
|
||||
@click="modalOpen = false"
|
||||
aria-label="Fermer"
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" aria-hidden="true">
|
||||
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
|
||||
</svg>
|
||||
</button>
|
||||
<h2 class="modal-title">Soutenir AEP</h2>
|
||||
<p class="modal-desc">
|
||||
AEP est un outil libre, sans publicité, financé par les dons.
|
||||
1 € finance environ 30 fiches mises en ligne.
|
||||
</p>
|
||||
<div class="modal-widget">
|
||||
<iframe
|
||||
src="https://liberapay.com/trans-former.fr/widgets/button.html"
|
||||
width="95"
|
||||
height="22"
|
||||
style="border: 0;"
|
||||
title="Faire un don sur Liberapay"
|
||||
/>
|
||||
</div>
|
||||
<a
|
||||
href="https://liberapay.com/trans-former.fr/donate"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="modal-link"
|
||||
>
|
||||
Faire un don sur Liberapay →
|
||||
</a>
|
||||
</div>
|
||||
</Transition>
|
||||
</Teleport>
|
||||
|
||||
</footer>
|
||||
|
||||
<!-- Mobile (< 1024px) : pas de FAB — Soutenir est dans le menu hamburger -->
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
interface Stats {
|
||||
cout_mois_eur: number
|
||||
budget_mois: number
|
||||
tokens_mois: number
|
||||
co2_kg: number
|
||||
requetes_mois: number
|
||||
fiches_semaine: number
|
||||
requetes_chatbot_semaine: number
|
||||
}
|
||||
|
||||
const stats = ref<Stats | null>(null)
|
||||
const loading = ref(true)
|
||||
const modalOpen = ref(false)
|
||||
const tooltipVisible = ref(false)
|
||||
|
||||
// Desktop — replié par défaut, déploie au hover, replie immédiatement à la sortie
|
||||
const bandeauEl = ref<HTMLElement | null>(null)
|
||||
const isCollapsed = ref(true) // replié par défaut
|
||||
|
||||
const REFRESH_MS = 5 * 60 * 1000 // 5 minutes
|
||||
|
||||
// Détection mobile côté client
|
||||
const isMobile = ref(false)
|
||||
|
||||
onMounted(() => {
|
||||
isMobile.value = window.innerWidth < 1024
|
||||
|
||||
const handleResize = () => {
|
||||
isMobile.value = window.innerWidth < 1024
|
||||
}
|
||||
window.addEventListener('resize', handleResize)
|
||||
onUnmounted(() => window.removeEventListener('resize', handleResize))
|
||||
|
||||
fetchStats()
|
||||
const interval = setInterval(fetchStats, REFRESH_MS)
|
||||
onUnmounted(() => clearInterval(interval))
|
||||
})
|
||||
|
||||
function onMouseEnter() {
|
||||
isCollapsed.value = false
|
||||
}
|
||||
|
||||
function onMouseLeave() {
|
||||
// Repli immédiat — pas de timer
|
||||
isCollapsed.value = true
|
||||
}
|
||||
|
||||
async function fetchStats() {
|
||||
try {
|
||||
const res = await $fetch<Stats>('/api/stats')
|
||||
stats.value = res
|
||||
} catch {
|
||||
stats.value = null
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const jaugePct = computed(() => {
|
||||
if (!stats.value) return 0
|
||||
return Math.min(100, Math.round((stats.value.cout_mois_eur / stats.value.budget_mois) * 100))
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* ── Bandeau bas ─────────────────────────────────────────────────────────── */
|
||||
.bandeau-bas {
|
||||
background: rgba(26, 34, 56, 0.7); /* opacité 70% */
|
||||
color: var(--nav-text-on-primary);
|
||||
font-family: var(--nav-font, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif);
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
||||
transition: min-height 0.25s ease;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.bandeau-collapsed {
|
||||
min-height: 32px !important;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.bandeau-inner {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding: 10px 20px;
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
min-height: 64px;
|
||||
transition: opacity 0.2s ease, max-height 0.3s ease;
|
||||
max-height: 200px;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.bandeau-inner--hidden {
|
||||
opacity: 0;
|
||||
max-height: 0;
|
||||
overflow: hidden;
|
||||
padding-top: 0;
|
||||
padding-bottom: 0;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/* Barre fine (collapsed) */
|
||||
.bandeau-thin {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.2s ease;
|
||||
}
|
||||
|
||||
.bandeau-thin--visible {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.bandeau-thin-label {
|
||||
font-size: 0.65rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
/* ── Colonnes ────────────────────────────────────────────────────────────── */
|
||||
.bandeau-col {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.bandeau-col--center {
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: 0 0 auto;
|
||||
padding-top: 8px; /* décaler légèrement vers le bas pour mieux centrer dans la hauteur */
|
||||
}
|
||||
|
||||
.bandeau-col--right {
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
/* ── Typo ────────────────────────────────────────────────────────────────── */
|
||||
.bandeau-label {
|
||||
font-size: 0.65rem;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.07em;
|
||||
opacity: 0.65;
|
||||
margin: 0;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.bandeau-value {
|
||||
font-size: 0.775rem;
|
||||
font-weight: 500;
|
||||
color: var(--nav-text-on-primary);
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.bandeau-value strong {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.bandeau-sub {
|
||||
font-size: 0.68rem;
|
||||
opacity: 0.7;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
/* ── Jauge budget ────────────────────────────────────────────────────────── */
|
||||
.jauge-track {
|
||||
width: 100%;
|
||||
max-width: 180px;
|
||||
height: 4px;
|
||||
border-radius: 2px;
|
||||
background: rgba(255, 255, 255, 0.18);
|
||||
overflow: hidden;
|
||||
margin: 3px 0;
|
||||
}
|
||||
|
||||
.jauge-fill {
|
||||
height: 100%;
|
||||
border-radius: 2px;
|
||||
background: var(--nav-accent);
|
||||
transition: width 0.6s ease;
|
||||
}
|
||||
|
||||
/* ── Bouton soutenir + tooltip ───────────────────────────────────────────── */
|
||||
.soutenir-wrap {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.btn-soutenir {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 7px 16px;
|
||||
border-radius: 8px;
|
||||
border: none;
|
||||
background: var(--nav-accent);
|
||||
color: var(--nav-text);
|
||||
font-size: 0.8rem;
|
||||
font-weight: 700;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition: opacity 0.15s, transform 0.1s;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.btn-soutenir:hover { opacity: 0.88; transform: translateY(-1px); }
|
||||
.btn-soutenir:active { opacity: 1; transform: translateY(0); }
|
||||
|
||||
.soutenir-tooltip {
|
||||
position: absolute;
|
||||
bottom: calc(100% + 8px);
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
background: var(--nav-primary-solid, #1a2238);
|
||||
color: var(--nav-text-on-primary);
|
||||
font-size: 0.72rem;
|
||||
font-weight: 600;
|
||||
padding: 5px 10px;
|
||||
border-radius: 6px;
|
||||
white-space: nowrap;
|
||||
pointer-events: none;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.soutenir-tooltip::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
border: 5px solid transparent;
|
||||
border-top-color: var(--nav-primary-solid, #1a2238);
|
||||
}
|
||||
|
||||
/* ── Modal ───────────────────────────────────────────────────────────────── */
|
||||
.modal-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 2000;
|
||||
background: rgba(26, 34, 56, 0.55);
|
||||
}
|
||||
|
||||
.modal-box {
|
||||
position: fixed;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
z-index: 2001;
|
||||
background: var(--nav-surface, #ffffff);
|
||||
border-radius: 16px;
|
||||
padding: 28px 24px 24px;
|
||||
width: min(380px, 90vw);
|
||||
box-shadow: 0 8px 40px rgba(26, 34, 56, 0.22);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.modal-close {
|
||||
position: absolute;
|
||||
top: 14px;
|
||||
right: 14px;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 8px;
|
||||
border: none;
|
||||
background: var(--nav-bg-alt, #eee9df);
|
||||
color: var(--nav-text-muted, rgba(26,34,56,0.55));
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
.modal-close:hover { background: var(--nav-bg, #f8f6f1); }
|
||||
|
||||
.modal-title {
|
||||
font-size: 1.05rem;
|
||||
font-weight: 700;
|
||||
color: var(--nav-text, #1a2238);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.modal-desc {
|
||||
font-size: 0.85rem;
|
||||
color: var(--nav-text-muted, rgba(26,34,56,0.55));
|
||||
line-height: 1.6;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.modal-widget {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 12px 0;
|
||||
}
|
||||
|
||||
.modal-link {
|
||||
display: block;
|
||||
text-align: center;
|
||||
font-size: 0.8rem;
|
||||
color: var(--nav-primary-solid, #1a2238);
|
||||
text-decoration: underline;
|
||||
transition: opacity 0.15s;
|
||||
}
|
||||
.modal-link:hover { opacity: 0.7; }
|
||||
|
||||
/* ── Transitions ─────────────────────────────────────────────────────────── */
|
||||
.backdrop-enter-active, .backdrop-leave-active { transition: opacity 0.2s ease; }
|
||||
.backdrop-enter-from, .backdrop-leave-to { opacity: 0; }
|
||||
|
||||
.modal-enter-active, .modal-leave-active { transition: opacity 0.2s ease, transform 0.2s ease; }
|
||||
.modal-enter-from, .modal-leave-to { opacity: 0; transform: translate(-50%, -48%); }
|
||||
|
||||
.sheet-enter-active, .sheet-leave-active { transition: transform 0.3s cubic-bezier(0.32, 0.72, 0, 1); }
|
||||
.sheet-enter-from, .sheet-leave-to { transform: translateY(100%); }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.btn-soutenir { transition: none; }
|
||||
.jauge-fill { transition: none; }
|
||||
.modal-enter-active, .modal-leave-active { transition: none; }
|
||||
.backdrop-enter-active, .backdrop-leave-active { transition: none; }
|
||||
.sheet-enter-active, .sheet-leave-active { transition: none; }
|
||||
.bandeau-bas { transition: none; }
|
||||
.bandeau-inner { transition: none; }
|
||||
}
|
||||
</style>
|
||||
@@ -54,7 +54,6 @@
|
||||
<div v-if="messages.length === 0" class="onboarding-bubble">
|
||||
<p>Explore les 120 structures de la carte par la conversation. Je peux t'aider à trouver des collectifs, agences ou réseaux selon ta situation, ta pratique ou tes inspirations du moment.</p>
|
||||
<p class="example">Exemple : "Je cherche des acteurs de la rénovation de maisons individuelles en France, plutôt en milieu rural, avec des approches biosourcées ou low-tech."</p>
|
||||
<p style="margin-top: 8px; font-size: 0.72rem; opacity: 0.6;">Propulsé par Mistral FR - serveur européen souverain, zéro rétention.</p>
|
||||
</div>
|
||||
|
||||
<!-- Messages -->
|
||||
|
||||
@@ -69,7 +69,6 @@
|
||||
<div ref="messagesContainer" class="flex-1 overflow-y-auto px-4 py-4 flex flex-col gap-3">
|
||||
<!-- Message onboarding (avant la première question) -->
|
||||
<div v-if="messages.length === 0" class="onboarding-bubble">
|
||||
<p>Ce chatbot fonctionne sur un serveur européen souverain (Mistral FR, zéro rétention), conçu sobre en énergie.</p>
|
||||
<p>Pour m'aider à te répondre efficacement, formule ta requête ainsi :</p>
|
||||
<ul>
|
||||
<li>• Besoin : [ce que tu cherches]</li>
|
||||
|
||||
+31
-24
@@ -77,8 +77,12 @@ const emit = defineEmits<{
|
||||
}
|
||||
}
|
||||
|
||||
.chip:hover {
|
||||
transform: translateY(-1px);
|
||||
/* Survol : uniquement sur pointeur capable de survol. Sur tactile, :hover
|
||||
reste collé après un tap (chip « allumé » sans être actif). */
|
||||
@media (hover: hover) {
|
||||
.chip:hover {
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
}
|
||||
|
||||
.chip:focus-visible {
|
||||
@@ -92,19 +96,21 @@ const emit = defineEmits<{
|
||||
color: var(--text);
|
||||
background: transparent;
|
||||
}
|
||||
.chip--echelle:hover {
|
||||
background: var(--primary-hover);
|
||||
border-color: var(--primary-hover);
|
||||
color: var(--on-primary);
|
||||
@media (hover: hover) {
|
||||
.chip--echelle:hover {
|
||||
background: var(--primary-hover);
|
||||
border-color: var(--primary-hover);
|
||||
color: var(--on-primary);
|
||||
}
|
||||
}
|
||||
/* Actif = fond PLEIN. --primary est translucide dans le thème AEP
|
||||
(rgba(26,34,56,.6) : 4,16:1 sur le fond de page, sous AA) ; le couple
|
||||
--nav-primary-solid / --nav-text-on-primary (≈14,6:1) reste lisible aussi
|
||||
en sombre. Le survol d'un chip actif ne change pas de fond. */
|
||||
.chip--echelle.chip--active {
|
||||
background: var(--primary);
|
||||
border-color: var(--primary);
|
||||
color: var(--on-primary);
|
||||
}
|
||||
.chip--echelle.chip--active:hover {
|
||||
background: var(--primary-hover);
|
||||
border-color: var(--primary-hover);
|
||||
background: var(--nav-primary-solid);
|
||||
border-color: var(--nav-primary-solid);
|
||||
color: var(--nav-text-on-primary);
|
||||
}
|
||||
|
||||
/* ── Fonction/hashtag : pleine bleu, inactif = bg-alt ────────────────────── */
|
||||
@@ -113,16 +119,15 @@ const emit = defineEmits<{
|
||||
background: var(--bg-alt);
|
||||
color: var(--text);
|
||||
}
|
||||
.chip--fonction:hover {
|
||||
background: var(--primary-hover);
|
||||
color: var(--on-primary);
|
||||
@media (hover: hover) {
|
||||
.chip--fonction:hover {
|
||||
background: var(--primary-hover);
|
||||
color: var(--on-primary);
|
||||
}
|
||||
}
|
||||
.chip--fonction.chip--active {
|
||||
background: var(--primary);
|
||||
color: var(--on-primary);
|
||||
}
|
||||
.chip--fonction.chip--active:hover {
|
||||
background: var(--primary-hover);
|
||||
background: var(--nav-primary-solid);
|
||||
color: var(--nav-text-on-primary);
|
||||
}
|
||||
|
||||
/* ── Posture (préparée pour plus tard) : outline safran ──────────────────── */
|
||||
@@ -131,9 +136,11 @@ const emit = defineEmits<{
|
||||
color: var(--text);
|
||||
background: transparent;
|
||||
}
|
||||
.chip--posture:hover {
|
||||
background: var(--accent);
|
||||
color: var(--on-accent);
|
||||
@media (hover: hover) {
|
||||
.chip--posture:hover {
|
||||
background: var(--accent);
|
||||
color: var(--on-accent);
|
||||
}
|
||||
}
|
||||
.chip--posture.chip--active {
|
||||
background: var(--accent);
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
<template>
|
||||
<section class="echelle-tete" :class="{ 'echelle-tete--compact': compact }" :aria-label="`Échelle ${e.id} : ${e.titre}`">
|
||||
<p class="echelle-tete__kicker">
|
||||
<span class="echelle-tete__badge" aria-hidden="true">{{ e.id }}</span>
|
||||
<span class="echelle-tete__titre">{{ e.titre }}<span v-if="e.sousTitre" class="echelle-tete__sous-titre">{{ ' ' + e.sousTitre }}</span></span>
|
||||
</p>
|
||||
<ul class="echelle-tete__mots">
|
||||
<li v-for="m in e.mots" :key="m">{{ m }}</li>
|
||||
</ul>
|
||||
<p class="echelle-tete__phrase">{{ e.phrase }}</p>
|
||||
<slot />
|
||||
<p v-if="contribuer" class="echelle-tete__contribuer">
|
||||
<span>{{ ECHELLES_CADRE_COURT }}</span>
|
||||
<NuxtLink :to="`/proposer?categorie=${e.categorieProposer}`" @click="$emit('navigate')">Proposer une ressource →</NuxtLink>
|
||||
</p>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ECHELLES, type EchelleId } from '~/utils/echelles'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
echelle: EchelleId
|
||||
/** Variante resserrée, pour une popup ou un en-tête centré. */
|
||||
compact?: boolean
|
||||
/** Affiche la ligne « on pose l'infrastructure, le collectif nourrit ». */
|
||||
contribuer?: boolean
|
||||
}>(), { compact: false, contribuer: true })
|
||||
|
||||
defineEmits<{ navigate: [] }>()
|
||||
|
||||
const e = computed(() => ECHELLES[props.echelle])
|
||||
const ECHELLES_CADRE_COURT = 'Chaque section est ouverte aux contributions.'
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.echelle-tete {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-sm);
|
||||
margin: 0 0 var(--space-md);
|
||||
}
|
||||
|
||||
.echelle-tete__kicker {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: var(--space-sm);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.echelle-tete__badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 2rem;
|
||||
padding: 0.1rem 0.5rem;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--accent);
|
||||
color: var(--on-accent);
|
||||
font-weight: var(--fw-bold);
|
||||
font-size: var(--fs-sm);
|
||||
letter-spacing: 0.04em;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.echelle-tete__titre {
|
||||
font-size: var(--fs-lg);
|
||||
font-weight: var(--fw-bold);
|
||||
color: var(--text);
|
||||
line-height: var(--lh-tight);
|
||||
}
|
||||
|
||||
.echelle-tete__sous-titre {
|
||||
font-weight: var(--fw-regular);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.echelle-tete__mots {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.15rem 0;
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text);
|
||||
line-height: var(--lh-base);
|
||||
}
|
||||
.echelle-tete__mots li:not(:last-child)::after {
|
||||
content: '·';
|
||||
margin: 0 0.5rem;
|
||||
color: var(--accent);
|
||||
font-weight: var(--fw-bold);
|
||||
}
|
||||
|
||||
.echelle-tete__phrase {
|
||||
margin: 0;
|
||||
font-size: var(--fs-sm);
|
||||
font-style: italic;
|
||||
color: var(--text-muted);
|
||||
line-height: var(--lh-base);
|
||||
}
|
||||
|
||||
.echelle-tete__contribuer {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.25rem 0.75rem;
|
||||
font-size: var(--fs-xs);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.echelle-tete__contribuer a {
|
||||
color: var(--link);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
.echelle-tete__contribuer a:hover { color: var(--link-hover); }
|
||||
|
||||
.echelle-tete--compact { text-align: left; }
|
||||
.echelle-tete--compact .echelle-tete__titre { font-size: var(--fs-base); }
|
||||
</style>
|
||||
@@ -150,19 +150,19 @@ function toggle(tag: string) {
|
||||
|
||||
.fiches-panel__grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
grid-template-columns: repeat(1, minmax(0, 1fr));
|
||||
gap: var(--space-sm);
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.fiches-panel__grid {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 1280px) {
|
||||
.fiches-panel__grid {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
<!--
|
||||
FilEchelle — B10-M4
|
||||
< 768 px : une ligne de 28 px sous la barre, « S · Partir de soi · Outils · Jobs » :
|
||||
l'échelle courante, l'onglet courant, puis ses voisins du groupe (liens).
|
||||
Absente sur les pages hors groupe (Manifeste, À propos, Proposer, Signaler, fiche).
|
||||
Montée dans le flux de la colonne d'app.vue, AVANT le conteneur de page : la carte
|
||||
de / perd ces 28 px à vue, jamais en dessous de la ligne de flottaison.
|
||||
-->
|
||||
<template>
|
||||
<nav v-if="courant" class="fil-echelle" :class="{ 'fil-echelle--long': voisins.length > 1 }" aria-label="Échelle courante">
|
||||
<span class="fil-echelle__pastille">{{ courant.echelle }}</span>
|
||||
<span class="fil-echelle__titre">{{ ECHELLES[courant.echelle].titre }}</span>
|
||||
<span class="fil-echelle__sep" aria-hidden="true">·</span>
|
||||
<span class="fil-echelle__courant" aria-current="page">{{ courant.onglet.libelle }}</span>
|
||||
<template v-for="o in voisins" :key="o.to">
|
||||
<span class="fil-echelle__sep" aria-hidden="true">·</span>
|
||||
<NuxtLink :to="o.to" class="fil-echelle__lien">{{ o.libelle }}</NuxtLink>
|
||||
</template>
|
||||
</nav>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ECHELLES, echelleDeRoute } from '~/utils/echelles'
|
||||
|
||||
const route = useRoute()
|
||||
const courant = computed(() => echelleDeRoute(route))
|
||||
const voisins = computed(() =>
|
||||
courant.value ? ECHELLES[courant.value.echelle].onglets.filter((o) => o !== courant.value!.onglet) : [],
|
||||
)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.fil-echelle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
height: 28px;
|
||||
padding: 0 var(--space-sm);
|
||||
gap: 5px;
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
white-space: nowrap;
|
||||
font-size: 0.72rem;
|
||||
line-height: 1;
|
||||
background: var(--surface);
|
||||
border-bottom: 1px solid var(--bg-alt);
|
||||
color: color-mix(in srgb, var(--text) 78%, transparent);
|
||||
}
|
||||
|
||||
.fil-echelle::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.fil-echelle__pastille {
|
||||
padding: 2px 5px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--accent);
|
||||
color: var(--on-accent);
|
||||
font-weight: var(--fw-bold);
|
||||
}
|
||||
|
||||
.fil-echelle__courant {
|
||||
font-weight: var(--fw-bold);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.fil-echelle__lien {
|
||||
color: inherit;
|
||||
text-decoration: underline;
|
||||
text-decoration-color: var(--border);
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
|
||||
.fil-echelle__lien:focus-visible {
|
||||
outline: 2px solid var(--focus-ring);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
/* Groupe à trois onglets (M) sous 400 px : l'accroche se replie sur sa pastille
|
||||
(lue quand même par les lecteurs d'écran), sinon « Codev » sort de l'écran. */
|
||||
@media (max-width: 399px) {
|
||||
.fil-echelle--long .fil-echelle__titre {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0 0 0 0);
|
||||
}
|
||||
.fil-echelle--long .fil-echelle__titre + .fil-echelle__sep {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.fil-echelle {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,310 @@
|
||||
<template>
|
||||
<form @submit.prevent="submit" class="proposer-form proposer-form--libre" novalidate>
|
||||
<div class="field-group" :class="{ 'field-error': errors.texte }">
|
||||
<label id="libre-liens-label">Tes liens <span class="label-hint">(1 ou plusieurs — sites, PDF, articles...)</span></label>
|
||||
<div class="liens-list" role="group" aria-labelledby="libre-liens-label">
|
||||
<div v-for="(lien, i) in liens" :key="i" class="lien-row">
|
||||
<input
|
||||
:id="`libre-lien-${i}`"
|
||||
v-model="liens[i]"
|
||||
type="url"
|
||||
inputmode="url"
|
||||
placeholder="https://..."
|
||||
autocomplete="off"
|
||||
@blur="validateAll(false)"
|
||||
/>
|
||||
<button
|
||||
v-if="liens.length > 1"
|
||||
type="button"
|
||||
class="lien-remove"
|
||||
:aria-label="`Retirer ce lien`"
|
||||
@click="removeLien(i)"
|
||||
>×</button>
|
||||
</div>
|
||||
</div>
|
||||
<button v-if="liens.length < 10" type="button" class="btn-add-lien" @click="addLien">+ un autre lien</button>
|
||||
<span v-if="errors.texte" id="libre-texte-error" class="error-msg" role="alert">{{ errors.texte }}</span>
|
||||
</div>
|
||||
|
||||
<div class="field-group">
|
||||
<label for="libre-texte">Pourquoi c'est utile, pour toi ? <span class="label-hint">(pas de format imposé)</span></label>
|
||||
<textarea
|
||||
id="libre-texte"
|
||||
v-model="texte"
|
||||
rows="4"
|
||||
placeholder="Dis-le avec tes mots : ce que ça t'a apporté, pourquoi tu le partages..."
|
||||
:aria-describedby="errors.texte ? 'libre-texte-error' : undefined"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="field-group">
|
||||
<label id="libre-type-label">Type suggéré <span class="label-hint">(optionnel — un ou deux si tu hésites)</span></label>
|
||||
<ChipGroup aria-label="Type suggéré" aria-describedby="libre-type-hint">
|
||||
<Chip
|
||||
v-for="t in TYPES_SUGGERES"
|
||||
:key="t"
|
||||
:label="TYPES_SUGGERES_LABELS[t]"
|
||||
variant="fonction"
|
||||
:active="typeSuggere === t || typeSecondaire === t"
|
||||
:class="{ 'chip--secondaire': typeSecondaire === t }"
|
||||
@toggle="toggleType(t)"
|
||||
/>
|
||||
</ChipGroup>
|
||||
<span id="libre-type-hint" class="label-hint">
|
||||
Écosystème : {{ TYPES_SUGGERES_HINTS.ecosysteme }} · Réseau : {{ TYPES_SUGGERES_HINTS.reseau }} · Jobs : {{ TYPES_SUGGERES_HINTS.jobs }} · Outils : {{ TYPES_SUGGERES_HINTS.outils }} · Références : {{ TYPES_SUGGERES_HINTS.references }}
|
||||
</span>
|
||||
<!-- Distinction non visuelle premier choix / second choix pour lecteurs d'écran :
|
||||
les deux chips actifs partagent le même aria-pressed, sans quoi rien ne dit
|
||||
lequel est principal. -->
|
||||
<span class="sr-only" aria-live="polite">
|
||||
<template v-if="typeSuggere && typeSecondaire">
|
||||
Principal : {{ TYPES_SUGGERES_LABELS[typeSuggere] }} · second choix : {{ TYPES_SUGGERES_LABELS[typeSecondaire] }}
|
||||
</template>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="field-group" :class="{ 'field-error': errors.submitted_by_email }">
|
||||
<label for="libre-email">Ton email <span class="label-hint">(optionnel — pour qu'on te tienne au courant)</span></label>
|
||||
<input
|
||||
id="libre-email"
|
||||
v-model="email"
|
||||
type="email"
|
||||
placeholder="ton@email.fr"
|
||||
autocomplete="email"
|
||||
@blur="validateAll(false)"
|
||||
/>
|
||||
<span v-if="errors.submitted_by_email" class="error-msg" role="alert">{{ errors.submitted_by_email }}</span>
|
||||
</div>
|
||||
|
||||
<!-- Honeypot anti-spam : caché visuellement et aux lecteurs d'écran, un bot le remplit. -->
|
||||
<div class="hp-field" aria-hidden="true">
|
||||
<label for="libre-site-web">Site web</label>
|
||||
<input id="libre-site-web" v-model="siteWeb" type="text" tabindex="-1" autocomplete="off" />
|
||||
</div>
|
||||
|
||||
<div v-if="serverError" class="server-error" role="alert" aria-live="assertive">
|
||||
<strong>Erreur :</strong> {{ serverError }}
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="btn-primary" :disabled="submitting">
|
||||
{{ submitting ? 'Envoi en cours...' : 'Proposer →' }}
|
||||
</button>
|
||||
</div>
|
||||
<p class="form-note">Ta proposition sera examinée par l'équipe avant publication.</p>
|
||||
</form>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { LibreSubmitSchema, TYPES_SUGGERES, TYPES_SUGGERES_LABELS, TYPES_SUGGERES_HINTS, type TypeSuggere } from '~/utils/submitLibre'
|
||||
|
||||
const props = defineProps<{ presetType?: TypeSuggere }>()
|
||||
const emit = defineEmits<{ success: [] }>()
|
||||
|
||||
const liens = reactive<string[]>([''])
|
||||
const texte = ref('')
|
||||
const email = ref('')
|
||||
const typeSuggere = ref<TypeSuggere | undefined>(props.presetType)
|
||||
// Deuxième chip optionnelle (B5-M2b) — pour les indécis entre deux types.
|
||||
const typeSecondaire = ref<TypeSuggere | undefined>()
|
||||
const siteWeb = ref('') // honeypot
|
||||
|
||||
const errors = reactive<Record<string, string>>({})
|
||||
const submitting = ref(false)
|
||||
const serverError = ref('')
|
||||
|
||||
function addLien() {
|
||||
if (liens.length < 10) liens.push('')
|
||||
}
|
||||
|
||||
function removeLien(i: number) {
|
||||
liens.splice(i, 1)
|
||||
if (liens.length === 0) liens.push('')
|
||||
}
|
||||
|
||||
/**
|
||||
* Deux chips maximum. Premier clic = principal, deuxième = secondaire.
|
||||
* Décocher le principal alors qu'un secondaire existe promeut ce dernier.
|
||||
* Troisième clic sur un chip inactif quand deux sont déjà actifs : remplace
|
||||
* le secondaire par le nouveau chip (choix le plus simple — pas de file d'attente).
|
||||
*/
|
||||
function toggleType(t: TypeSuggere) {
|
||||
if (typeSuggere.value === t) {
|
||||
typeSuggere.value = typeSecondaire.value
|
||||
typeSecondaire.value = undefined
|
||||
return
|
||||
}
|
||||
if (typeSecondaire.value === t) {
|
||||
typeSecondaire.value = undefined
|
||||
return
|
||||
}
|
||||
if (typeSuggere.value === undefined) {
|
||||
typeSuggere.value = t
|
||||
} else if (typeSecondaire.value === undefined) {
|
||||
typeSecondaire.value = t
|
||||
} else {
|
||||
typeSecondaire.value = t
|
||||
}
|
||||
}
|
||||
|
||||
function currentPayload() {
|
||||
return {
|
||||
liens: liens.map((l) => l.trim()).filter(Boolean),
|
||||
texte: texte.value,
|
||||
submitted_by_email: email.value || undefined,
|
||||
type_suggere: typeSuggere.value,
|
||||
type_secondaire: typeSecondaire.value,
|
||||
site_web: siteWeb.value,
|
||||
}
|
||||
}
|
||||
|
||||
function validateAll(scrollToError = true): boolean {
|
||||
const result = LibreSubmitSchema.safeParse(currentPayload())
|
||||
if (!result.success) {
|
||||
const flat = result.error.flatten().fieldErrors
|
||||
Object.keys(errors).forEach((k) => delete errors[k])
|
||||
Object.assign(errors, Object.fromEntries(Object.entries(flat).map(([k, v]) => [k, v?.[0] ?? ''])))
|
||||
if (scrollToError) {
|
||||
nextTick(() => {
|
||||
document.querySelector('.field-error')?.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
})
|
||||
}
|
||||
return false
|
||||
}
|
||||
Object.keys(errors).forEach((k) => delete errors[k])
|
||||
return true
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
serverError.value = ''
|
||||
if (!validateAll(true)) return
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
await $fetch('/api/submit', {
|
||||
method: 'POST',
|
||||
body: { mode: 'libre', ...currentPayload() },
|
||||
})
|
||||
emit('success')
|
||||
} catch (e: any) {
|
||||
const status = e?.status ?? e?.statusCode
|
||||
if (status === 429) {
|
||||
serverError.value = 'Tu as déjà soumis 3 fiches aujourd\'hui. Réessaie demain.'
|
||||
} else if (status === 422 && e?.data) {
|
||||
Object.assign(errors, Object.fromEntries(Object.entries(e.data as Record<string, string[]>).map(([k, v]) => [k, Array.isArray(v) ? v[0] : String(v)])))
|
||||
serverError.value = 'Vérifie les erreurs ci-dessus.'
|
||||
} else {
|
||||
serverError.value = 'Une erreur s\'est produite. Réessaie dans quelques instants.'
|
||||
}
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@import './form-styles.css';
|
||||
|
||||
.liens-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.375rem;
|
||||
}
|
||||
.lien-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.lien-row input {
|
||||
flex: 1;
|
||||
padding: 0.625rem 0.875rem;
|
||||
border: 1px solid rgba(26, 34, 56, 0.2);
|
||||
border-radius: 8px;
|
||||
font-size: 0.9rem;
|
||||
color: var(--nav-text);
|
||||
background: var(--nav-surface);
|
||||
font-family: inherit;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.lien-row input:focus {
|
||||
outline: none;
|
||||
border-color: var(--nav-primary-solid);
|
||||
box-shadow: 0 0 0 2px rgba(245, 179, 66, 0.4);
|
||||
}
|
||||
.lien-remove {
|
||||
flex-shrink: 0;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border: 1px solid rgba(26, 34, 56, 0.2);
|
||||
background: transparent;
|
||||
border-radius: 6px;
|
||||
color: var(--nav-text-muted);
|
||||
font-size: 1.1rem;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
.lien-remove:hover {
|
||||
border-color: #c0392b;
|
||||
color: #c0392b;
|
||||
}
|
||||
.btn-add-lien {
|
||||
align-self: flex-start;
|
||||
margin-top: 0.5rem;
|
||||
padding: 0.4rem 0.75rem;
|
||||
background: transparent;
|
||||
border: 1px dashed rgba(26, 34, 56, 0.3);
|
||||
border-radius: 6px;
|
||||
font-size: 0.8rem;
|
||||
color: var(--nav-text-muted);
|
||||
cursor: pointer;
|
||||
font-family: inherit;
|
||||
}
|
||||
.btn-add-lien:hover {
|
||||
border-color: var(--nav-primary-solid);
|
||||
color: var(--nav-text);
|
||||
}
|
||||
|
||||
.hp-field {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0 0 0 0);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0 0 0 0);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* ── B5-M2c : distinction principal / second choix ──
|
||||
Le principal actif (fond plein, ≈14,6:1) et le survol gardé par
|
||||
@media (hover: hover) viennent de Chip.vue depuis AF5 : les surcharges
|
||||
locales de AF4 (principal plein, survol collant neutralisé sur tactile)
|
||||
ont été retirées. */
|
||||
|
||||
/* Chip secondaire (deuxième choix) : contour au lieu de plein, pour ne
|
||||
jamais se confondre avec le principal — ni à l'œil ni au clic. Texte
|
||||
--nav-text sur le fond de page : contraste très large (>10:1), stable
|
||||
dans tous les états. */
|
||||
.field-group :deep(.chip--secondaire.chip--active) {
|
||||
background: transparent !important;
|
||||
border-color: var(--nav-primary-solid) !important;
|
||||
color: var(--nav-text) !important;
|
||||
}
|
||||
/* Survol du secondaire : pointeur capable de survol seulement, comme Chip.vue
|
||||
(sur tactile, :hover reste collé après un tap). */
|
||||
@media (hover: hover) {
|
||||
.field-group :deep(.chip--secondaire.chip--active:hover) {
|
||||
background: rgba(var(--nav-primary-raw), 0.08) !important;
|
||||
border-color: var(--nav-primary-solid) !important;
|
||||
color: var(--nav-text) !important;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<div class="media-tab-projets" style="padding: 1.5rem; overflow-y: auto;">
|
||||
<div style="max-width: 70ch; margin-bottom: 1.5rem;">
|
||||
<h2 style="font-weight: 700; font-size: 1.1rem; margin-bottom: 0.5rem; color: var(--nav-text);">PFE engagés</h2>
|
||||
<h2 style="font-weight: 700; font-size: 1.1rem; margin-bottom: 0.5rem; color: var(--nav-text);">Publications</h2>
|
||||
<p style="font-size: 0.9rem; line-height: 1.6; color: var(--nav-text);">
|
||||
Mutualiser le savoir. Voici les PFE engagés publiés en ligne dont nous avons connaissance.
|
||||
Partage-nous le lien de ton travail si tu veux participer à cette initiative.
|
||||
|
||||
@@ -275,6 +275,7 @@
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex-1 overflow-y-auto px-5 py-4" style="color:var(--nav-text);font-size:0.875rem;line-height:1.6;">
|
||||
<EchelleTete echelle="XL" compact @navigate="ragInfoOpen = false" />
|
||||
<p class="mb-3">Une bibliothèque parlante des pensées écologiques, organisée pour aider à créer une pensée complexe et nuancée, à soutenir l'écriture de nouveaux récits, des alternatives concrètes et des projets collectifs.</p>
|
||||
<p class="mb-4" style="color:var(--nav-text-muted);font-size:0.8rem;">Projet open source, ouvert à toutes et à tous - <a href="https://bonpote.com/la-carte-des-pensees-ecologiques/" target="_blank" rel="noopener" style="text-decoration:underline;">article + carte FRACAS Bonpote V2</a>.</p>
|
||||
<div class="flex flex-col gap-3">
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
|
||||
<div class="mission-body">
|
||||
<h2 id="mission-title" class="mission-title">{{ title }}</h2>
|
||||
<EchelleTete v-if="echelle" :echelle="echelle" compact @navigate="close" />
|
||||
<slot>
|
||||
<p class="mission-text">
|
||||
L'architecture est l'une des professions les plus complexes qui soit ; elle croise droit, technique, esthétique, économie, social, écologie — tout à la fois, tout simultanément, souvent sans filet. Paradoxalement, c'est aussi l'une des moins structurées sur le plan de l'entraide : peu de transmission horizontale, beaucoup d'isolement, une culture du chacun-pour-soi héritée d'une formation qui prépare à la compétition plus qu'à la coopération. On sort de l'école seul·e. On s'installe seul·e. On réinvente ce que d'autres ont déjà traversé.
|
||||
@@ -52,11 +53,15 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { EchelleId } from '~/utils/echelles'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue: boolean
|
||||
title?: string
|
||||
ctaLabel?: string
|
||||
storageKey?: string
|
||||
/** Tête d'échelle du deck (S / M / XL) affichée sous le titre. Absente sur /agences tant que l'arbitrage n° 1 n'est pas rendu. */
|
||||
echelle?: EchelleId
|
||||
}>(), {
|
||||
title: "L'écosystème d'entraide architecte",
|
||||
ctaLabel: 'Explorer la carte',
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
<!--
|
||||
NavEchelles — B10-M2
|
||||
Barre des trois échelles S / M / XL, lue depuis utils/echelles.ts (source unique).
|
||||
≥ 1280 px : les trois groupes ; 768-1279 px : le seul groupe de la page courante ;
|
||||
< 768 px : rien (FilEchelle + NavTiroir prennent le relais).
|
||||
Chaque groupe = <ul> étiqueté par son accroche (pastille + titre de l'échelle).
|
||||
-->
|
||||
<template>
|
||||
<nav class="nav-echelles" aria-label="Échelles">
|
||||
<div
|
||||
v-for="id in ORDRE_ECHELLES"
|
||||
:key="id"
|
||||
class="nav-echelles__grp"
|
||||
:class="{ 'nav-echelles__grp--courant': courant?.echelle === id }"
|
||||
>
|
||||
<span :id="`nav-echelle-${id}`" class="nav-echelles__kick">
|
||||
<span class="nav-echelles__pastille">{{ id }}</span>{{ ECHELLES[id].titre }}
|
||||
</span>
|
||||
<ul class="nav-echelles__tabs" :aria-labelledby="`nav-echelle-${id}`">
|
||||
<li v-for="o in ECHELLES[id].onglets" :key="o.to">
|
||||
<NuxtLink
|
||||
:to="o.to"
|
||||
class="nav-echelles__tab"
|
||||
:class="{ 'nav-echelles__tab--actif': o.actif(route) }"
|
||||
:aria-current="o.actif(route) ? 'page' : undefined"
|
||||
>{{ o.libelle }}</NuxtLink>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ECHELLES, ORDRE_ECHELLES, echelleDeRoute } from '~/utils/echelles'
|
||||
|
||||
const route = useRoute()
|
||||
const courant = computed(() => echelleDeRoute(route))
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.nav-echelles {
|
||||
display: none;
|
||||
align-self: stretch;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
gap: var(--space-lg);
|
||||
}
|
||||
|
||||
.nav-echelles__grp {
|
||||
position: relative;
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
justify-content: flex-end;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.nav-echelles__kick {
|
||||
padding: 0 var(--space-xs);
|
||||
font-size: 0.66rem;
|
||||
font-weight: var(--fw-semibold);
|
||||
letter-spacing: 0.04em;
|
||||
line-height: 1.3;
|
||||
white-space: nowrap;
|
||||
color: color-mix(in srgb, var(--text) 78%, transparent);
|
||||
}
|
||||
|
||||
.nav-echelles__grp--courant .nav-echelles__kick {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.nav-echelles__pastille {
|
||||
display: inline-block;
|
||||
margin-right: 5px;
|
||||
padding: 0 5px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--accent);
|
||||
color: var(--on-accent);
|
||||
font-weight: var(--fw-bold);
|
||||
}
|
||||
|
||||
.nav-echelles__tabs {
|
||||
display: flex;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.nav-echelles__tab {
|
||||
display: inline-block;
|
||||
padding: 4px 9px 9px;
|
||||
font-size: 0.8rem;
|
||||
font-weight: var(--fw-medium);
|
||||
white-space: nowrap;
|
||||
text-decoration: none;
|
||||
color: color-mix(in srgb, var(--text) 78%, transparent);
|
||||
border-bottom: 2px solid transparent;
|
||||
transition: color var(--dur-fast) var(--ease-out);
|
||||
}
|
||||
|
||||
.nav-echelles__tab:hover {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.nav-echelles__tab:focus-visible {
|
||||
outline: 2px solid var(--focus-ring);
|
||||
outline-offset: -2px;
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.nav-echelles__tab--actif {
|
||||
color: var(--text);
|
||||
font-weight: var(--fw-semibold);
|
||||
border-bottom-color: var(--nav-primary-solid);
|
||||
}
|
||||
|
||||
/* 768-1279 : le seul groupe courant, aligné à gauche après le logo */
|
||||
@media (min-width: 768px) {
|
||||
.nav-echelles {
|
||||
display: flex;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
.nav-echelles__grp--courant {
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
|
||||
/* ≥ 1280 : les trois groupes, centrés, séparés par un filet */
|
||||
@media (min-width: 1280px) {
|
||||
.nav-echelles {
|
||||
justify-content: center;
|
||||
}
|
||||
.nav-echelles__grp {
|
||||
display: flex;
|
||||
}
|
||||
.nav-echelles__grp + .nav-echelles__grp::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: calc(var(--space-lg) / -2);
|
||||
top: 10px;
|
||||
bottom: 10px;
|
||||
border-left: 1px solid var(--border);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.nav-echelles__tab { transition: none; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,313 @@
|
||||
<!--
|
||||
NavTiroir — B10-M3
|
||||
Menu < 1280 px : tiroir pleine hauteur à droite, voile, Échap, focus piégé,
|
||||
focus rendu à l'élément qui l'a ouvert. Les trois échelles dans l'ordre de la
|
||||
barre (utils/echelles.ts), puis Manifeste, À propos, Signaler, et Soutenir.
|
||||
Se ferme seul au changement de route et si la fenêtre passe à ≥ 1280 px.
|
||||
-->
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<Transition name="nav-tiroir">
|
||||
<div v-if="open" class="nav-tiroir" @keydown="onKeydown">
|
||||
<div class="nav-tiroir__voile" aria-hidden="true" @click="fermer" />
|
||||
<div
|
||||
ref="panneau"
|
||||
class="nav-tiroir__panneau"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="nav-tiroir-titre"
|
||||
>
|
||||
<div class="nav-tiroir__tete">
|
||||
<h2 id="nav-tiroir-titre" class="nav-tiroir__titre">Menu</h2>
|
||||
<button type="button" class="nav-tiroir__fermer" aria-label="Fermer le menu" @click="fermer">
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" aria-hidden="true">
|
||||
<line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<nav class="nav-tiroir__corps" aria-label="Échelles et pages">
|
||||
<p class="nav-tiroir__cadre">{{ ECHELLES_CADRE_COURT }}</p>
|
||||
|
||||
<div v-for="id in ORDRE_ECHELLES" :key="id" class="nav-tiroir__grp">
|
||||
<span :id="`nav-tiroir-echelle-${id}`" class="nav-tiroir__kick">
|
||||
<span class="nav-tiroir__pastille">{{ id }}</span>{{ ECHELLES[id].titre }}
|
||||
</span>
|
||||
<ul class="nav-tiroir__liste" :aria-labelledby="`nav-tiroir-echelle-${id}`">
|
||||
<li v-for="o in ECHELLES[id].onglets" :key="o.to">
|
||||
<NuxtLink
|
||||
:to="o.to"
|
||||
class="nav-tiroir__lien"
|
||||
:class="{ 'nav-tiroir__lien--actif': o.actif(route) }"
|
||||
:aria-current="o.actif(route) ? 'page' : undefined"
|
||||
@click="fermer"
|
||||
>{{ o.libelle }}</NuxtLink>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<hr class="nav-tiroir__sep" />
|
||||
|
||||
<ul class="nav-tiroir__liste">
|
||||
<li v-for="p in PAGES" :key="p.to">
|
||||
<NuxtLink
|
||||
:to="p.to"
|
||||
class="nav-tiroir__second"
|
||||
:aria-current="route.path === p.to ? 'page' : undefined"
|
||||
@click="fermer"
|
||||
>{{ p.libelle }}</NuxtLink>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<a :href="SOUTENIR_URL" target="_blank" rel="noopener noreferrer" class="nav-tiroir__soutenir">Soutenir</a>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ECHELLES, ECHELLES_CADRE_COURT, ORDRE_ECHELLES } from '~/utils/echelles'
|
||||
import { SOUTENIR_URL } from '~/utils/liens'
|
||||
|
||||
const props = defineProps<{ open: boolean }>()
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
|
||||
const PAGES = [
|
||||
{ libelle: 'Manifeste', to: '/manifeste' },
|
||||
{ libelle: 'À propos', to: '/a-propos' },
|
||||
{ libelle: 'Signaler', to: '/signaler' },
|
||||
]
|
||||
|
||||
const route = useRoute()
|
||||
const panneau = ref<HTMLElement | null>(null)
|
||||
let retourFocus: HTMLElement | null = null
|
||||
|
||||
function fermer() {
|
||||
emit('close')
|
||||
}
|
||||
|
||||
function focusables(): HTMLElement[] {
|
||||
if (!panneau.value) return []
|
||||
return [...panneau.value.querySelectorAll<HTMLElement>('a[href], button:not([disabled])')]
|
||||
}
|
||||
|
||||
function onKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
fermer()
|
||||
return
|
||||
}
|
||||
if (e.key !== 'Tab') return
|
||||
const els = focusables()
|
||||
if (!els.length) return
|
||||
const premier = els[0]
|
||||
const dernier = els[els.length - 1]
|
||||
if (e.shiftKey && document.activeElement === premier) {
|
||||
e.preventDefault()
|
||||
dernier.focus()
|
||||
} else if (!e.shiftKey && document.activeElement === dernier) {
|
||||
e.preventDefault()
|
||||
premier.focus()
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.open, async (ouvert) => {
|
||||
if (ouvert) {
|
||||
retourFocus = document.activeElement as HTMLElement | null
|
||||
await nextTick()
|
||||
focusables()[0]?.focus()
|
||||
} else if (retourFocus) {
|
||||
// Le bouton d'ouverture peut ne plus être visible (fenêtre élargie) : focus() est alors sans effet.
|
||||
retourFocus.focus()
|
||||
retourFocus = null
|
||||
}
|
||||
})
|
||||
|
||||
watch(() => route.fullPath, () => { if (props.open) fermer() })
|
||||
|
||||
let mq: MediaQueryList | null = null
|
||||
function onLarge(e: MediaQueryListEvent) { if (e.matches && props.open) fermer() }
|
||||
onMounted(() => {
|
||||
mq = window.matchMedia('(min-width: 1280px)')
|
||||
mq.addEventListener('change', onLarge)
|
||||
})
|
||||
onBeforeUnmount(() => mq?.removeEventListener('change', onLarge))
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.nav-tiroir {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 10000;
|
||||
}
|
||||
|
||||
.nav-tiroir__voile {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: rgba(var(--nav-primary-raw), 0.35);
|
||||
}
|
||||
|
||||
.nav-tiroir__panneau {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
width: min(320px, 88vw);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
box-shadow: var(--shadow-lg);
|
||||
}
|
||||
|
||||
.nav-tiroir__tete {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-shrink: 0;
|
||||
padding: var(--space-xs) var(--space-sm) var(--space-xs) var(--space-md);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.nav-tiroir__titre {
|
||||
margin: 0;
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: var(--fw-semibold);
|
||||
}
|
||||
|
||||
.nav-tiroir__fermer {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border: 0;
|
||||
border-radius: var(--radius-md);
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.nav-tiroir__corps {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: var(--space-sm) var(--space-md) var(--space-lg);
|
||||
}
|
||||
|
||||
.nav-tiroir__cadre {
|
||||
margin: 0 0 var(--space-xs);
|
||||
font-size: var(--fs-xs);
|
||||
line-height: var(--lh-base);
|
||||
color: color-mix(in srgb, var(--text) 78%, transparent);
|
||||
}
|
||||
|
||||
.nav-tiroir__grp {
|
||||
margin-top: var(--space-sm);
|
||||
}
|
||||
|
||||
.nav-tiroir__kick {
|
||||
display: block;
|
||||
margin-bottom: var(--space-2xs);
|
||||
font-size: 0.72rem;
|
||||
font-weight: var(--fw-bold);
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: color-mix(in srgb, var(--text) 78%, transparent);
|
||||
}
|
||||
|
||||
.nav-tiroir__pastille {
|
||||
display: inline-block;
|
||||
margin-right: 6px;
|
||||
padding: 0 5px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--accent);
|
||||
color: var(--on-accent);
|
||||
}
|
||||
|
||||
.nav-tiroir__liste {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.nav-tiroir__lien,
|
||||
.nav-tiroir__second {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-height: 44px;
|
||||
padding: 0 var(--space-xs);
|
||||
border-radius: var(--radius-md);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.nav-tiroir__lien {
|
||||
font-size: var(--fs-base);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.nav-tiroir__lien--actif {
|
||||
background: var(--bg-alt);
|
||||
font-weight: var(--fw-semibold);
|
||||
}
|
||||
|
||||
.nav-tiroir__second {
|
||||
font-size: var(--fs-sm);
|
||||
color: color-mix(in srgb, var(--text) 78%, transparent);
|
||||
}
|
||||
|
||||
.nav-tiroir__lien:focus-visible,
|
||||
.nav-tiroir__second:focus-visible,
|
||||
.nav-tiroir__soutenir:focus-visible,
|
||||
.nav-tiroir__fermer:focus-visible {
|
||||
outline: 2px solid var(--focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.nav-tiroir__sep {
|
||||
margin: var(--space-sm) 0;
|
||||
border: 0;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.nav-tiroir__soutenir {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 44px;
|
||||
margin-top: var(--space-sm);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--accent);
|
||||
color: var(--on-accent);
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: var(--fw-semibold);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.nav-tiroir-enter-active,
|
||||
.nav-tiroir-leave-active {
|
||||
transition: opacity var(--dur-base) var(--ease-out);
|
||||
}
|
||||
.nav-tiroir-enter-active .nav-tiroir__panneau,
|
||||
.nav-tiroir-leave-active .nav-tiroir__panneau {
|
||||
transition: transform var(--dur-base) var(--ease-out);
|
||||
}
|
||||
.nav-tiroir-enter-from,
|
||||
.nav-tiroir-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
.nav-tiroir-enter-from .nav-tiroir__panneau,
|
||||
.nav-tiroir-leave-to .nav-tiroir__panneau {
|
||||
transform: translateX(100%);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.nav-tiroir-enter-active,
|
||||
.nav-tiroir-leave-active,
|
||||
.nav-tiroir-enter-active .nav-tiroir__panneau,
|
||||
.nav-tiroir-leave-active .nav-tiroir__panneau {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,90 @@
|
||||
# Déploiement aep-worker (B5-M2)
|
||||
|
||||
Ce dossier n'a **rien été exécuté ni copié sur le VPS** par la session B5 — code
|
||||
seulement, comme demandé. Étapes exactes pour la session qui déploiera.
|
||||
|
||||
## 0. Pré-requis avant de commencer
|
||||
|
||||
- [ ] **Backup NocoDB < 24 h** avant le premier passage du worker (il écrit en base).
|
||||
- [ ] Vérifier que `/opt/aep/.env` contient déjà : `NOCODB_URL`, `NOCODB_TOKEN`,
|
||||
`NOCODB_BASE`, `NOCODB_TABLE_ORGAS`, `NOCODB_TABLE_STATS`, `BIFROST_URL`,
|
||||
`BIFROST_VK`, `NTFY_TOPIC` (et optionnellement `WORKER_MODEL`,
|
||||
`WORKER_LIMIT`, `BUDGET_MAX_EUR`). Ne PAS créer de nouveau fichier .env —
|
||||
celui-ci existe déjà en prod (mission dit de le lire, pas de le chercher
|
||||
dans ce repo).
|
||||
- [ ] Confirmer que `/opt/nav-carte` (l'ancien worker) est bien absent — il l'était
|
||||
au 27/09 selon B0. Sinon, l'arrêter/purger avant d'activer celui-ci pour
|
||||
éviter un double traitement des mêmes fiches pending.
|
||||
|
||||
## 1. Copier le code
|
||||
|
||||
```bash
|
||||
ssh vps
|
||||
mkdir -p /opt/aep-worker
|
||||
exit
|
||||
# depuis le poste de dev, après avoir buildé/vérifié la branche :
|
||||
scp -r worker/enrich.js worker/package.json worker/fixtures vps:/opt/aep-worker/
|
||||
ssh vps "cd /opt/aep-worker && npm install --omit=dev"
|
||||
```
|
||||
|
||||
(`npm install` : le worker n'a plus de dépendance à `dotenv` côté prod puisque
|
||||
`EnvironmentFile=` du service systemd charge déjà `/opt/aep/.env` — le
|
||||
`package.json` du worker peut être simplifié à cette occasion, ou laissé tel
|
||||
quel si `dotenv` sert encore pour un lancement manuel en local.)
|
||||
|
||||
## 2. Poser les unités systemd
|
||||
|
||||
```bash
|
||||
scp deploy/aep-worker/aep-worker.service deploy/aep-worker/aep-worker.timer \
|
||||
vps:/tmp/
|
||||
ssh vps
|
||||
sudo mv /tmp/aep-worker.service /tmp/aep-worker.timer /etc/systemd/system/
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now aep-worker.timer
|
||||
```
|
||||
|
||||
## 3. Vérifier
|
||||
|
||||
```bash
|
||||
systemctl status aep-worker.timer
|
||||
systemctl list-timers | grep aep-worker
|
||||
|
||||
# Lancer un passage manuel (sans attendre les 15 min) :
|
||||
sudo systemctl start aep-worker.service
|
||||
journalctl -u aep-worker.service -n 100 --no-pager
|
||||
```
|
||||
|
||||
Logs attendus : `=== Worker AEP enrichissement démarré ===`, un compte de
|
||||
fiches pending, puis soit `Rien à traiter.` soit le détail par fiche
|
||||
(scrape/Bifrost/ntfy).
|
||||
|
||||
## 4. Test bout-en-bout (M3, session suivante)
|
||||
|
||||
1. Soumettre une vraie ressource de test via `/proposer` (formulaire assoupli).
|
||||
2. Vérifier le 201 + le record `pending`/`ai_processed=false` dans NocoDB.
|
||||
3. Vérifier la notif ntfy de soumission (topic `NTFY_TOPIC`).
|
||||
4. Lancer le worker (`systemctl start aep-worker.service` ou attendre le
|
||||
timer) → vérifier `moderation_status=ai_processed`, `description_enrichie`,
|
||||
`tags_fonction`, `ai_raw_output` remplis, et la notif ntfy « Fiche enrichie ».
|
||||
5. Modérer dans NocoDB UI (`ai_processed` → `approved`) → vérifier l'affichage
|
||||
sur le front.
|
||||
6. **Supprimer les records de test** dans NocoDB (orgas + stats_usage) une
|
||||
fois la preuve faite.
|
||||
7. Mettre à jour `PIPE-IA-DOC.md`, `Onglets/Proposer.md`, `PILOTE - AEP.md`
|
||||
dans le vault avec le résultat réel (pas seulement ce README).
|
||||
|
||||
## Anti-chevauchement
|
||||
|
||||
Lock fichier PID : `/tmp/aep-worker.lock` (configurable via `WORKER_LOCK_FILE`
|
||||
dans `.env` si besoin). Nettoyé en fin de run normal, et automatiquement si le
|
||||
PID contenu dans le lock n'est plus vivant (voir `acquireLock()` dans
|
||||
`enrich.js`) — pas d'intervention manuelle attendue, sauf lock resté après un
|
||||
crash dur du process (`kill -9` externe) : dans ce cas `rm /tmp/aep-worker.lock`
|
||||
suffit.
|
||||
|
||||
## Écarts par rapport à la version NAV V2 (PIPE-IA-DOC.md)
|
||||
|
||||
Voir l'en-tête de commentaire de `worker/enrich.js` et `PIPE-IA-DOC.md` §11 —
|
||||
LLM Bifrost au lieu de Mistral direct, scrape fetch natif au lieu de crawl4ai,
|
||||
notification ntfy au lieu de Resend, écriture `nom`/`submission_type` par le
|
||||
worker seulement quand le formulaire assoupli a laissé un placeholder.
|
||||
@@ -0,0 +1,11 @@
|
||||
[Unit]
|
||||
Description=AEP — Worker enrichissement IA (scrape léger + Bifrost)
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
WorkingDirectory=/opt/aep-worker
|
||||
EnvironmentFile=/opt/aep/.env
|
||||
ExecStart=/usr/bin/node enrich.js
|
||||
TimeoutStartSec=300
|
||||
@@ -0,0 +1,9 @@
|
||||
[Unit]
|
||||
Description=Timer 15 min — worker enrichissement IA AEP
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*:0/15
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -3,6 +3,7 @@ export default defineNuxtConfig({
|
||||
|
||||
app: {
|
||||
head: {
|
||||
htmlAttrs: { lang: 'fr' },
|
||||
link: [
|
||||
{ rel: 'icon', type: 'image/svg+xml', href: '/favicon.svg' },
|
||||
{ rel: 'icon', type: 'image/png', sizes: '32x32', href: '/favicon-32.png' },
|
||||
|
||||
+18
-65
@@ -27,14 +27,6 @@
|
||||
Ce site tourne sur un VPS - un serveur privé loué en Europe - construit entièrement avec des logiciels open source, quasi gratuits. Pas de services Google, pas d'Amazon, pas de Microsoft dans la chaîne. C'est un choix délibéré : contrôler son infrastructure, c'est contrôler ses données.
|
||||
</p>
|
||||
<div class="badges-row">
|
||||
<div class="badge">
|
||||
<span class="badge-icon" aria-hidden="true">
|
||||
<!-- Mistral logo placeholder -->
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4l3 3"/></svg>
|
||||
</span>
|
||||
<span class="badge-label">IA souveraine</span>
|
||||
<span class="badge-detail">Mistral AI, Paris - conforme RGPD ; pas de collecte ni de profiling ; aucun transfert hors UE</span>
|
||||
</div>
|
||||
<div class="badge">
|
||||
<span class="badge-icon" aria-hidden="true">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
|
||||
@@ -103,22 +95,8 @@
|
||||
L'IA est un outil. La question, c'est au service de quoi. Oui, elle est énergivore - et il faut l'assumer. Mais si c'est au service de l'émancipation, du collectif, de transformer nos infrastructures sociétales, alors on dit oui - en sachant que c'est une étape transitoire. L'infrastructure de l'IA elle-même peut évoluer : devenir plus locale, plus sobre, plus souveraine. C'est dans cette direction qu'on regarde.
|
||||
</p>
|
||||
|
||||
<div class="ia-grid">
|
||||
<div class="ia-card">
|
||||
<div class="ia-card-label">Enrichissement des fiches</div>
|
||||
<div class="ia-card-model">Mistral Nemo</div>
|
||||
<div class="ia-card-cost">~0,00003 €/fiche</div>
|
||||
</div>
|
||||
<div class="ia-card">
|
||||
<div class="ia-card-label">Chatbot de recherche</div>
|
||||
<div class="ia-card-model">Mistral Small</div>
|
||||
<div class="ia-card-cost">~0,003 €/requête</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul class="ia-details">
|
||||
<li>10 € / mois investis au départ par le collectif - vos dons constituent la réserve pour faire vivre le projet et financer ses recherches</li>
|
||||
<li>Coût visible en direct dans le bandeau bas de la carte</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@@ -207,6 +185,12 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- B10-M5 : Signaler a quitté la barre d'ordinateur ; il reste ici, dans le menu et dans chaque fiche -->
|
||||
<p class="section-text apropos-pied">
|
||||
Une fiche fausse, un lien mort, un contenu à retirer ?
|
||||
<NuxtLink to="/signaler">Signaler un problème</NuxtLink>
|
||||
</p>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -292,6 +276,18 @@ function copyApiUrl() {
|
||||
margin: 0 0 1rem;
|
||||
}
|
||||
|
||||
.apropos-pied {
|
||||
padding-top: var(--space-md);
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.apropos-pied a {
|
||||
color: var(--text);
|
||||
font-weight: var(--fw-semibold);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
|
||||
.section-intro {
|
||||
color: var(--nav-text-muted);
|
||||
margin-bottom: 1.25rem;
|
||||
@@ -398,49 +394,6 @@ function copyApiUrl() {
|
||||
|
||||
/* ── IA grid ─────────────────────────────────────────────────────────────────── */
|
||||
|
||||
.ia-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.ia-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.ia-card {
|
||||
background: var(--nav-surface);
|
||||
border: 1px solid rgba(26, 34, 56, 0.1);
|
||||
border-radius: 10px;
|
||||
padding: 1rem 1.125rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.ia-card-label {
|
||||
font-size: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--nav-text-muted);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.ia-card-model {
|
||||
font-size: 1rem;
|
||||
font-weight: 700;
|
||||
color: var(--nav-text);
|
||||
}
|
||||
|
||||
.ia-card-cost {
|
||||
font-size: 0.825rem;
|
||||
color: var(--nav-text-muted);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.ia-details {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
|
||||
@@ -484,6 +484,7 @@
|
||||
title="Réseaux AEP — l'architecture qui s'engage"
|
||||
ctaLabel="Explorer les 120 réseaux"
|
||||
storageKey="aep_reseaux_seen"
|
||||
echelle="M"
|
||||
>
|
||||
<p class="mission-text">
|
||||
Cette carte rassemble <strong>120 réseaux, collectifs et agences</strong> qui pratiquent une architecture engagée — écologique, politique, biorégionale. Ce ne sont pas seulement des agences « vertes » : ce sont celles et ceux qui assument des positions, refusent des projets, expérimentent des modèles de gouvernance, mettent leurs ressources et leurs savoirs en commun.
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
<div class="lock-header">
|
||||
<h1>Co-développement</h1>
|
||||
<p class="lock-subtitle">Entraide entre pairs</p>
|
||||
<EchelleTete echelle="M" compact :contribuer="false" class="lock-echelle" />
|
||||
<p class="lock-intro">Cet espace est un cercle. Pour entrer, il y a un mot.</p>
|
||||
</div>
|
||||
|
||||
@@ -104,6 +105,13 @@ async function submit() {
|
||||
margin: 0 0 1rem;
|
||||
}
|
||||
|
||||
.lock-echelle {
|
||||
text-align: left;
|
||||
padding: var(--space-md);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--bg-alt);
|
||||
}
|
||||
|
||||
.lock-intro {
|
||||
font-size: 0.9rem;
|
||||
color: var(--nav-text-muted, #6b7280);
|
||||
|
||||
@@ -391,6 +391,7 @@
|
||||
<MissionPopup
|
||||
:modelValue="missionOpen"
|
||||
@update:modelValue="missionOpen = $event"
|
||||
echelle="M"
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
+7
-40
@@ -1,56 +1,23 @@
|
||||
<template>
|
||||
<!-- B10-M5 : plus de sous-onglets ici, la nav XL porte « Recherche média » et « Publications » (?tab=projets) -->
|
||||
<div class="media-page" style="background: var(--nav-bg);">
|
||||
<nav class="subtabs" style="display:flex; gap:0; border-bottom: 1px solid var(--nav-bg-alt); background: var(--nav-surface); padding: 0 1rem;">
|
||||
<button
|
||||
:class="['subtab-btn', { active: tab === 'visuel' }]"
|
||||
@click="tab = 'visuel'"
|
||||
>
|
||||
📚 bibliothèque des pensées écologiques
|
||||
</button>
|
||||
<button
|
||||
:class="['subtab-btn', { active: tab === 'projets' }]"
|
||||
@click="tab = 'projets'"
|
||||
>
|
||||
📐 Projets
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<MediaTabVisuel v-if="tab === 'visuel'" />
|
||||
<MediaTabProjets v-else-if="tab === 'projets'" />
|
||||
<MediaTabProjets v-else />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
const tab = ref<'visuel' | 'projets'>(
|
||||
(['visuel', 'projets'].includes(route.query.tab as string)
|
||||
? route.query.tab as 'visuel' | 'projets'
|
||||
: 'visuel')
|
||||
)
|
||||
|
||||
watch(tab, (newTab) => {
|
||||
router.replace({ query: { ...route.query, tab: newTab } })
|
||||
// Lu à chaque changement de ?tab= (un lien /media → /media?tab=projets ne remonte pas la page).
|
||||
const tab = ref<'visuel' | 'projets'>(route.query.tab === 'projets' ? 'projets' : 'visuel')
|
||||
watch(() => route.query.tab, (t) => {
|
||||
tab.value = t === 'projets' ? 'projets' : 'visuel'
|
||||
})
|
||||
|
||||
useHead({ title: 'AEP - Media' })
|
||||
useHead(() => ({ title: tab.value === 'projets' ? 'AEP - Publications' : 'AEP - Recherche média' }))
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.media-page { display: flex; flex-direction: column; height: 100%; overflow: hidden; }
|
||||
.subtabs { display: flex; gap: 0; flex-shrink: 0; }
|
||||
.subtab-btn {
|
||||
padding: 10px 18px;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
background: none;
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
cursor: pointer;
|
||||
color: var(--nav-text-muted);
|
||||
transition: color 0.15s, border-color 0.15s;
|
||||
}
|
||||
.subtab-btn:hover { color: var(--nav-text); }
|
||||
.subtab-btn.active { color: var(--nav-primary-solid); border-bottom-color: var(--nav-primary-solid); font-weight: 600; }
|
||||
</style>
|
||||
|
||||
+2
-1
@@ -9,6 +9,7 @@
|
||||
</div>
|
||||
<div>
|
||||
<h1 class="outils-header__title">Outils</h1>
|
||||
<EchelleTete echelle="S" :contribuer="false" />
|
||||
<p class="outils-header__intro">
|
||||
En tant qu'architecte, on jongle avec une multitude d'outils — simulation, dessin,
|
||||
calcul, recherche, partage. Les mutualiser, se conseiller dessus, savoir lequel
|
||||
@@ -326,7 +327,7 @@ const fmhyGuide = [
|
||||
{ nom: 'DeepSeek', url: 'https://chat.deepseek.com/', desc: 'modèle de pointe, usage illimité gratuit' },
|
||||
{ nom: 'Qwen Studio', url: 'https://chat.qwen.ai/', desc: 'chat IA (Qwen) illimité gratuit' },
|
||||
{ nom: 'Google AI Studio', url: 'https://aistudio.google.com/', desc: 'Gemini en accès généreux gratuit' },
|
||||
{ nom: 'Mistral Le Chat', url: 'https://chat.mistral.ai/', desc: 'LLM français, souverain, gratuit' },
|
||||
{ nom: 'Mistral Le Chat', url: 'https://chat.mistral.ai/', desc: 'LLM français, gratuit' },
|
||||
{ nom: 'LM Studio', url: 'https://lmstudio.ai/', desc: 'faire tourner des modèles en local, sans cloud' },
|
||||
{ nom: 'Jan', url: 'https://jan.ai/', desc: 'application desktop libre pour IA locale' },
|
||||
{ nom: 'Open WebUI', url: 'https://openwebui.com/', desc: 'interface web auto-hébergeable pour modèles locaux' }
|
||||
|
||||
+73
-19
@@ -6,8 +6,8 @@
|
||||
<div class="proposer-header">
|
||||
<h1>Proposer une ressource</h1>
|
||||
<p class="proposer-subtitle">
|
||||
Tu connais quelque chose d'utile qui n'est pas encore référencé sur AEP ?
|
||||
Choisis la catégorie ci-dessous et soumets-le — on valide sous 7 jours.
|
||||
Colle un lien (ou plusieurs), dis en quelques mots pourquoi c'est utile — on s'occupe du reste.
|
||||
On valide manuellement avant publication.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -20,23 +20,42 @@
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<div class="tabs-bar">
|
||||
<button
|
||||
v-for="tab in TABS"
|
||||
:key="tab.id"
|
||||
type="button"
|
||||
class="tab-btn"
|
||||
:class="{ 'tab-btn--active': activeTab === tab.id }"
|
||||
@click="activeTab = tab.id"
|
||||
>{{ tab.label }}</button>
|
||||
</div>
|
||||
<FormLibre :preset-type="presetType" @success="onSuccess" />
|
||||
|
||||
<div class="tab-content">
|
||||
<FormEcosysteme v-if="activeTab === 'ecosysteme'" @success="onSuccess" />
|
||||
<FormReseau v-else-if="activeTab === 'reseau'" @success="onSuccess" />
|
||||
<FormJobs v-else-if="activeTab === 'jobs'" @success="onSuccess" />
|
||||
<FormOutils v-else-if="activeTab === 'outils'" @success="onSuccess" />
|
||||
<FormReferences v-else-if="activeTab === 'references'" @success="onSuccess" />
|
||||
<div class="mode-detaille">
|
||||
<button
|
||||
type="button"
|
||||
class="mode-detaille-toggle"
|
||||
:aria-expanded="detailleOuvert"
|
||||
aria-controls="mode-detaille-panel"
|
||||
@click="detailleOuvert = !detailleOuvert"
|
||||
>
|
||||
{{ detailleOuvert ? '− Fermer le mode détaillé' : '+ Mode détaillé (formulaires par catégorie)' }}
|
||||
</button>
|
||||
|
||||
<div v-if="detailleOuvert" id="mode-detaille-panel" class="mode-detaille-panel">
|
||||
<p class="mode-detaille-hint">
|
||||
Pour aller plus loin qu'un lien + quelques mots : échelle, fonctions, ville... un formulaire par catégorie.
|
||||
</p>
|
||||
<div class="tabs-bar">
|
||||
<button
|
||||
v-for="tab in TABS"
|
||||
:key="tab.id"
|
||||
type="button"
|
||||
class="tab-btn"
|
||||
:class="{ 'tab-btn--active': activeTab === tab.id }"
|
||||
@click="activeTab = tab.id"
|
||||
>{{ tab.label }}</button>
|
||||
</div>
|
||||
|
||||
<div class="tab-content">
|
||||
<FormEcosysteme v-if="activeTab === 'ecosysteme'" @success="onSuccess" />
|
||||
<FormReseau v-else-if="activeTab === 'reseau'" @success="onSuccess" />
|
||||
<FormJobs v-else-if="activeTab === 'jobs'" @success="onSuccess" />
|
||||
<FormOutils v-else-if="activeTab === 'outils'" @success="onSuccess" />
|
||||
<FormReferences v-else-if="activeTab === 'references'" @success="onSuccess" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
@@ -44,6 +63,8 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { TYPES_SUGGERES, type TypeSuggere } from '~/utils/submitLibre'
|
||||
|
||||
const TABS = [
|
||||
{ id: 'ecosysteme', label: 'Écosystème / Entraide' },
|
||||
{ id: 'reseau', label: 'Réseau AEP' },
|
||||
@@ -52,7 +73,15 @@ const TABS = [
|
||||
{ id: 'references', label: 'Références (bibliothèque)' },
|
||||
] as const
|
||||
|
||||
const activeTab = ref<string>('ecosysteme')
|
||||
// ?categorie=outils (lien « Proposer une ressource » des têtes d'échelle) présélectionne
|
||||
// le chip du formulaire assoupli ET l'onglet du mode détaillé si l'un ou l'autre est ouvert.
|
||||
const route = useRoute()
|
||||
const categorie = String(route.query.categorie ?? '')
|
||||
const presetType = computed<TypeSuggere | undefined>(() =>
|
||||
(TYPES_SUGGERES as readonly string[]).includes(categorie) ? (categorie as TypeSuggere) : undefined,
|
||||
)
|
||||
const activeTab = ref<string>(TABS.some(t => t.id === categorie) ? categorie : 'ecosysteme')
|
||||
const detailleOuvert = ref(false)
|
||||
const success = ref(false)
|
||||
|
||||
function onSuccess() {
|
||||
@@ -62,6 +91,7 @@ function onSuccess() {
|
||||
function reset() {
|
||||
success.value = false
|
||||
activeTab.value = 'ecosysteme'
|
||||
detailleOuvert.value = false
|
||||
}
|
||||
|
||||
useHead({ title: 'Proposer une ressource — AEP' })
|
||||
@@ -103,6 +133,30 @@ useHead({ title: 'Proposer une ressource — AEP' })
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.mode-detaille {
|
||||
margin-top: 2rem;
|
||||
border-top: 1px solid var(--nav-bg-alt);
|
||||
padding-top: 1.25rem;
|
||||
}
|
||||
.mode-detaille-toggle {
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--nav-text-muted);
|
||||
font-size: 0.85rem;
|
||||
cursor: pointer;
|
||||
font-family: inherit;
|
||||
padding: 0.25rem 0;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
.mode-detaille-toggle:hover { color: var(--nav-text); }
|
||||
.mode-detaille-panel { margin-top: 1rem; }
|
||||
.mode-detaille-hint {
|
||||
font-size: 0.8rem;
|
||||
color: var(--nav-text-muted);
|
||||
margin: 0 0 1rem;
|
||||
}
|
||||
|
||||
.tabs-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
<div class="taff-header">
|
||||
<div class="taff-header-inner">
|
||||
<h1 class="taff-title">Trouver du taf en archi</h1>
|
||||
<EchelleTete echelle="S" :contribuer="false" class="taff-echelle-tete" />
|
||||
<p class="taff-subtitle">
|
||||
Annuaire critique des plateformes de mise en relation et d'appels d'offres,
|
||||
pour les <strong>architectes indépendants</strong> — 70 % de la profession et sa part la plus précaire économiquement.
|
||||
@@ -296,7 +297,7 @@
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<p class="taff-chat-footer-note">Propulsé par Mistral · 20 questions/jour</p>
|
||||
<p class="taff-chat-footer-note">20 questions/jour</p>
|
||||
</div>
|
||||
</Transition>
|
||||
</Teleport>
|
||||
@@ -649,6 +650,10 @@ const parsedDescription = computed(() => {
|
||||
|
||||
.taff-header { padding: 2.5rem 1.5rem 1.5rem; border-bottom: 1px solid var(--nav-bg-alt); text-align: center; }
|
||||
.taff-header-inner { max-width: 680px; margin: 0 auto; }
|
||||
/* En-tête Jobs centré : la tête d'échelle suit. */
|
||||
.taff-echelle-tete { text-align: center; margin-bottom: var(--space-md); }
|
||||
.taff-echelle-tete :deep(.echelle-tete__kicker),
|
||||
.taff-echelle-tete :deep(.echelle-tete__mots) { justify-content: center; }
|
||||
.taff-title { font-size: 1.875rem; font-weight: 800; color: var(--nav-text); margin-bottom: 0.5rem; letter-spacing: -0.02em; }
|
||||
.taff-subtitle { font-size: 0.9375rem; color: var(--nav-text-muted); line-height: 1.6; margin-bottom: 0.625rem; }
|
||||
.taff-cible { font-size: 0.875rem; color: var(--nav-text-muted); line-height: 1.55; margin-bottom: 1rem; font-style: italic; }
|
||||
|
||||
@@ -9,11 +9,12 @@
|
||||
"note_doublons_en_fr": "3 livres avec version EN aussi indexee dans le RAG pour cross-language queries : carson-mer-autour-de-nous-fr/EN, graeber-wengrow-aurore-fr/EN, saito-capital-anthropocene/EN. JSON conserve la version FR.",
|
||||
"note_v2_1": "Phase 6 refonte Bonpote-aligned : 11 ecoles (fusion Marxismes-ecologiques -> Ecosocialisme, Marx+Saito migres), palette pastel, positions x_hint/y_hint Bonpote-aligned, labels affiches renommes (eco-anarchisme -> Eco-anarchisme, technocritique, ethique-env singulier)",
|
||||
"updated": "2026-05-14",
|
||||
"auteurs_ingeres_count": 80,
|
||||
"auteurs_ingeres_count": 91,
|
||||
"note_v3_0": "Phase 8.A sync corpus unifie : ~140 auteurs Bonpote integres, flag ingere:true/false selon LightRAG VPS. Auteurs non-ingeres = entrees minimales (bio provisoire, livres_rag vide), a enrichir lors de PRG-4/PRG-5.",
|
||||
"note_v3_1": "Phase 8.D transposition 1:1 Bonpote V2 : positions+couleurs Bonpote-aligned via OCR vision Sonnet, blur Voronoi, grisage auteurs non-ingeres",
|
||||
"note_v4_0": "Phase 8.G J+8 : corpus 226 docs / 62 auteurs ingeres. Noeuds-ecoles, popup info RAG, lien Bonpote, chatbots Nebius DeepSeek-V3.2.",
|
||||
"note_v4_1": "Phase 8.G J+8 fin batch : corpus 277 docs / 99 auteurs LightRAG. Mise a jour livres_rag depuis mapping heuristique ID -> slug. Modele ingestion : Qwen3-235B."
|
||||
"note_v4_1": "Phase 8.G J+8 fin batch : corpus 277 docs / 99 auteurs LightRAG. Mise a jour livres_rag depuis mapping heuristique ID -> slug. Modele ingestion : Qwen3-235B.",
|
||||
"note_2026_09_28": "Correction attribution : harvey-brief-history-neoliberalism était dupliqué (heritage du mapping heuristique v4.1) entre hal-harvey (capitalisme-vert, non ingéré) et david-harvey (eco-anarchisme, poster Bonpote). Doublon retiré chez hal-harvey, livre conservé uniquement chez david-harvey (ecoles inchangées, alignées sur le poster Bonpote). auteurs_ingeres_count recalculé par script depuis le contenu JSON (flags ingere:true sur les 171 auteurs) : 91 - remplace la valeur 80 ci-dessus, déjà obsolète avant cette correction (note_v4_1 annonçait 99 côté VPS ; écart à réconcilier séparément, hors périmètre). corpus_ingere (277) et livres_count (64) non recalculés : ils référencent l'état LightRAG VPS, non reproductibles depuis ce JSON seul (mapping heuristique partiel vers livres_rag, cf note_v4_1)."
|
||||
},
|
||||
"ecoles": [
|
||||
{
|
||||
@@ -408,8 +409,13 @@
|
||||
]
|
||||
}
|
||||
],
|
||||
"theses_cles_attendues": [],
|
||||
"bio_courte_provisoire": "Théoricien·ne présent·e sur le poster Bonpote (eco-anarchisme), non ingéré·e dans le RAG ATIS.",
|
||||
"theses_cles": [
|
||||
"Accumulation par dépossession",
|
||||
"Le néolibéralisme comme restauration du pouvoir de classe",
|
||||
"Droit à la ville et production capitaliste de l'espace"
|
||||
],
|
||||
"bio_courte": "Géographe marxiste britannique. A Brief History of Neoliberalism (2005) analyse le tournant néolibéral comme projet politique de restauration du pouvoir de la classe possédante, plus que comme doctrine économique neutre.",
|
||||
"note_correction": "Attribution corrigée le 2026-09-28 : le livre était associé par erreur à Hal Harvey (capitalisme-vert, poster Bonpote non ingéré) au lieu de David Harvey.",
|
||||
"ingere": true
|
||||
},
|
||||
{
|
||||
@@ -2124,19 +2130,11 @@
|
||||
"capitalisme-vert"
|
||||
],
|
||||
"ecole_principale": "capitalisme-vert",
|
||||
"livres_rag": [
|
||||
{
|
||||
"slug": "harvey-brief-history-neoliberalism",
|
||||
"titre": "brief history neoliberalism",
|
||||
"annee": 0,
|
||||
"couches": [
|
||||
"fond"
|
||||
]
|
||||
}
|
||||
],
|
||||
"livres_rag": [],
|
||||
"theses_cles_attendues": [],
|
||||
"bio_courte_provisoire": "Théoricien·ne présent·e sur le poster Bonpote (capitalisme-vert), non ingéré·e dans le RAG ATIS.",
|
||||
"ingere": true
|
||||
"note_correction": "Le livre harvey-brief-history-neoliberalism, attribué par erreur, a été retiré le 2026-09-28 (voir entrée david-harvey).",
|
||||
"ingere": false
|
||||
},
|
||||
{
|
||||
"id": "laurence-tubiana",
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"children": [
|
||||
{ "name": "ChatGPT (OpenAI)", "url": "https://chat.openai.com/", "desc": "LLM généraliste, référence." },
|
||||
{ "name": "Claude (Anthropic)", "url": "https://claude.ai/", "desc": "Excellent pour rédaction longue et analyse de documents." },
|
||||
{ "name": "Mistral Le Chat", "url": "https://chat.mistral.ai/", "desc": "LLM français, souverain, gratuit." },
|
||||
{ "name": "Mistral Le Chat", "url": "https://chat.mistral.ai/", "desc": "LLM français, gratuit." },
|
||||
{ "name": "Perplexity", "url": "https://www.perplexity.ai/", "desc": "Moteur de recherche IA avec sources citées." },
|
||||
{ "name": "Hugging Face", "url": "https://huggingface.co/", "desc": "Hub de modèles open source. Indispensable." },
|
||||
{ "name": "LM Studio", "url": "https://lmstudio.ai/", "desc": "Faire tourner des LLM localement, sans cloud." }
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Test du circuit breaker budget (server/utils/circuitBreaker.ts), AF5.
|
||||
* Charge le VRAI module TS via jiti (comme test-submit-libre.mjs).
|
||||
*
|
||||
* Le faux NocoDB ci-dessous se comporte comme le vrai sur le point qui a cassé :
|
||||
* toute colonne nommée dans `where`, `fields` ou `sort` et absente du schéma
|
||||
* renvoie un 422. Réintroduire un filtre sur un champ absent fait donc échouer
|
||||
* le cas « schéma sans timestamp ».
|
||||
* Usage : node scripts/test-circuit-breaker.mjs
|
||||
*/
|
||||
|
||||
import { createJiti } from 'jiti'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url))
|
||||
const jiti = createJiti(import.meta.url)
|
||||
|
||||
const { checkBudget, BUDGET_MAX_EUR } = await jiti.import(
|
||||
join(__dirname, '..', 'server', 'utils', 'circuitBreaker.ts'),
|
||||
)
|
||||
|
||||
const NOW = new Date('2026-09-29T10:00:00Z')
|
||||
|
||||
/** Colonnes référencées par une requête NocoDB v2 (where, fields, sort). */
|
||||
function colonnesReferencees(query) {
|
||||
const cols = []
|
||||
if (query.where) {
|
||||
for (const m of String(query.where).matchAll(/\(([^,()]+),/g)) cols.push(m[1].trim())
|
||||
}
|
||||
if (query.fields) cols.push(...String(query.fields).split(',').map((s) => s.trim()))
|
||||
if (query.sort) cols.push(...String(query.sort).split(',').map((s) => s.trim().replace(/^-/, '')))
|
||||
return cols.filter(Boolean)
|
||||
}
|
||||
|
||||
/** Faux NocoDB : schéma de colonnes + lignes ; 422 sur colonne inconnue ; pagination limit/offset. */
|
||||
function fauxNocodb({ schema, rows, panne = false }) {
|
||||
const appels = []
|
||||
const fetchJson = async (url, { headers, query }) => {
|
||||
appels.push({ url, query })
|
||||
if (panne) throw Object.assign(new Error('[GET] 500 Internal Server Error'), { statusCode: 500 })
|
||||
if (headers['xc-token'] !== 'tok') throw Object.assign(new Error('401'), { statusCode: 401 })
|
||||
const inconnues = colonnesReferencees(query).filter((c) => !schema.includes(c))
|
||||
if (inconnues.length) {
|
||||
throw Object.assign(new Error(`[GET] 422 Field '${inconnues[0]}' not found`), { statusCode: 422 })
|
||||
}
|
||||
const limit = Number(query.limit ?? 25)
|
||||
const offset = Number(query.offset ?? 0)
|
||||
const list = rows.slice(offset, offset + limit)
|
||||
return { list, pageInfo: { isLastPage: offset + limit >= rows.length } }
|
||||
}
|
||||
return { fetchJson, appels }
|
||||
}
|
||||
|
||||
const base = { nocodbUrl: 'http://noco', nocodbToken: 'tok', statsTableId: 'mbbq7n47ixy19mc', now: NOW }
|
||||
|
||||
// Schéma supposé de la prod : pas de colonne `timestamp`, date système `CreatedAt`.
|
||||
const SCHEMA_SANS_TS = ['Id', 'model', 'endpoint', 'tokens_in', 'tokens_out', 'cout_eur', 'orga_id', 'CreatedAt', 'UpdatedAt']
|
||||
const SCHEMA_AVEC_TS = [...SCHEMA_SANS_TS, 'timestamp']
|
||||
|
||||
const results = []
|
||||
function check(name, cond, detail = '') {
|
||||
results.push({ name, ok: !!cond, detail })
|
||||
}
|
||||
|
||||
// Journal capturé pour vérifier la ligne de budget
|
||||
const logs = []
|
||||
const origInfo = console.info
|
||||
const origWarn = console.warn
|
||||
console.info = (...a) => logs.push(['info', a.join(' ')])
|
||||
console.warn = (...a) => logs.push(['warn', a.join(' ')])
|
||||
|
||||
try {
|
||||
// 0. Le faux NocoDB rejette bien l'ancienne requête (sinon le test ne prouverait rien)
|
||||
{
|
||||
const { fetchJson } = fauxNocodb({ schema: SCHEMA_SANS_TS, rows: [] })
|
||||
let status = null
|
||||
try {
|
||||
await fetchJson('x', {
|
||||
headers: { 'xc-token': 'tok' },
|
||||
query: { where: '(timestamp,gte,2026-09-01T00:00:00.000Z)', limit: 1000, fields: 'cout_eur,timestamp' },
|
||||
})
|
||||
} catch (e) {
|
||||
status = e.statusCode
|
||||
}
|
||||
check('faux NocoDB : ancienne requête (where/fields sur timestamp) → 422', status === 422, `statut ${status}`)
|
||||
}
|
||||
|
||||
// 1. Schéma sans timestamp : lu, mois courant seul, aucune colonne nommée
|
||||
{
|
||||
const rows = [
|
||||
{ Id: 1, cout_eur: 0.5, CreatedAt: '2026-09-03T08:00:00.000Z' },
|
||||
{ Id: 2, cout_eur: '1.25', CreatedAt: '2026-09-28 22:10:00+00:00' },
|
||||
{ Id: 3, cout_eur: 7, CreatedAt: '2026-08-31T23:59:00.000Z' }, // mois précédent
|
||||
{ Id: 4, cout_eur: null, CreatedAt: '2026-09-10T00:00:00.000Z' },
|
||||
]
|
||||
const { fetchJson, appels } = fauxNocodb({ schema: SCHEMA_SANS_TS, rows })
|
||||
logs.length = 0
|
||||
const s = await checkBudget({ ...base, fetchJson })
|
||||
check('sans timestamp : budget vérifié (pas de 422)', s.verified === true, JSON.stringify(s))
|
||||
check('sans timestamp : cumul = 1,75 € (août exclu)', Math.abs(s.cumulEur - 1.75) < 1e-9, `cumul ${s.cumulEur}`)
|
||||
check('sans timestamp : 3 lignes du mois sur 4', s.lignesMois === 3 && s.lignesLues === 4)
|
||||
check('aucune colonne nommée dans la requête', appels.every((a) => colonnesReferencees(a.query).length === 0),
|
||||
JSON.stringify(appels.map((a) => a.query)))
|
||||
const ligne = logs.find(([niv, t]) => niv === 'info' && t.includes('[circuitBreaker] budget lu'))
|
||||
check('journal : ligne « budget lu » avec le cumul', ligne && ligne[1].includes('1.7500 €'), ligne?.[1] ?? 'absente')
|
||||
}
|
||||
|
||||
// 2. Schéma avec timestamp : timestamp prioritaire sur CreatedAt (ordre du worker)
|
||||
{
|
||||
const rows = [
|
||||
{ Id: 1, cout_eur: 2, timestamp: '2026-09-15T12:00:00.000Z', CreatedAt: '2026-08-15T12:00:00.000Z' },
|
||||
{ Id: 2, cout_eur: 3, timestamp: '2026-08-15T12:00:00.000Z', CreatedAt: '2026-09-15T12:00:00.000Z' },
|
||||
]
|
||||
const { fetchJson } = fauxNocodb({ schema: SCHEMA_AVEC_TS, rows })
|
||||
const s = await checkBudget({ ...base, fetchJson })
|
||||
check('avec timestamp : timestamp prioritaire (cumul 2 €)', s.verified && s.cumulEur === 2, `cumul ${s.cumulEur}`)
|
||||
}
|
||||
|
||||
// 3. Lignes sans aucune date : ignorées et comptées
|
||||
{
|
||||
const rows = [{ Id: 1, cout_eur: 9 }, { Id: 2, cout_eur: 1, CreatedAt: '2026-09-02T00:00:00Z' }]
|
||||
const { fetchJson } = fauxNocodb({ schema: SCHEMA_SANS_TS, rows })
|
||||
logs.length = 0
|
||||
const s = await checkBudget({ ...base, fetchJson })
|
||||
check('sans date : ignorée, comptée', s.cumulEur === 1 && s.lignesSansDate === 1)
|
||||
check('journal : lignes sans date signalées', logs.some(([, t]) => t.includes('1 sans date ignorées')))
|
||||
}
|
||||
|
||||
// 3bis. Aucune ligne datée : jamais « 0 € vérifié »
|
||||
{
|
||||
const rows = [{ Id: 1, cout_eur: 30 }, { Id: 2, cout_eur: 1 }]
|
||||
const { fetchJson } = fauxNocodb({ schema: ['Id', 'cout_eur'], rows })
|
||||
logs.length = 0
|
||||
const s = await checkBudget({ ...base, fetchJson })
|
||||
check('aucune date : verified=false, pas 0 € vérifié', s.verified === false && s.lignesSansDate === 2)
|
||||
check('aucune date : avertissement « NON vérifié »', logs.some(([niv, t]) => niv === 'warn' && t.includes('NON vérifié')))
|
||||
}
|
||||
|
||||
// 4. Pagination : 2 500 lignes du mois à 0,01 € → 25 € → bloqué
|
||||
{
|
||||
const rows = Array.from({ length: 2500 }, (_, i) => ({ Id: i + 1, cout_eur: 0.01, CreatedAt: '2026-09-20T00:00:00Z' }))
|
||||
const { fetchJson, appels } = fauxNocodb({ schema: SCHEMA_SANS_TS, rows })
|
||||
logs.length = 0
|
||||
const s = await checkBudget({ ...base, fetchJson })
|
||||
check('pagination : 2 500 lignes lues en 3 pages', s.lignesLues === 2500 && appels.length === 3, `${s.lignesLues} lignes, ${appels.length} appels`)
|
||||
check(`seuil : 25 € ≥ ${BUDGET_MAX_EUR} € → blocked`, s.blocked === true && s.warning === true)
|
||||
check('journal : BLOQUÉ', logs.some(([, t]) => t.includes('BLOQUÉ')))
|
||||
}
|
||||
|
||||
// 5. Alerte entre 18 et 20 €
|
||||
{
|
||||
const rows = [{ Id: 1, cout_eur: 18.5, CreatedAt: '2026-09-20T00:00:00Z' }]
|
||||
const { fetchJson } = fauxNocodb({ schema: SCHEMA_SANS_TS, rows })
|
||||
const s = await checkBudget({ ...base, fetchJson })
|
||||
check('18,5 € → warning sans blocage', s.warning === true && s.blocked === false)
|
||||
}
|
||||
|
||||
// 6. Panne NocoDB : fail-open, mais verified=false et avertissement au journal
|
||||
{
|
||||
const { fetchJson } = fauxNocodb({ schema: SCHEMA_SANS_TS, rows: [], panne: true })
|
||||
logs.length = 0
|
||||
const s = await checkBudget({ ...base, fetchJson })
|
||||
check('panne : fail-open, verified=false', s.blocked === false && s.verified === false)
|
||||
check('panne : avertissement « NON vérifié »', logs.some(([niv, t]) => niv === 'warn' && t.includes('NON vérifié')))
|
||||
}
|
||||
} finally {
|
||||
console.info = origInfo
|
||||
console.warn = origWarn
|
||||
}
|
||||
|
||||
let failed = 0
|
||||
for (const r of results) {
|
||||
if (!r.ok) failed++
|
||||
console.log(`${r.ok ? 'ok ' : 'FAIL'} ${r.name}${r.ok ? '' : ` → ${r.detail}`}`)
|
||||
}
|
||||
console.log(failed ? `\nÉCHEC — ${failed}/${results.length} tests en échec` : `\nPASS — ${results.length}/${results.length} tests passés`)
|
||||
process.exit(failed ? 1 : 0)
|
||||
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Test des données de nav S / M / XL (B10-M1).
|
||||
* Charge le VRAI fichier utils/echelles.ts via jiti (même patron que test-submit-libre.mjs) :
|
||||
* chaque route → bon groupe et bon onglet actif, un seul onglet actif par route.
|
||||
* Usage : node scripts/test-echelles-nav.mjs
|
||||
*/
|
||||
|
||||
import { createJiti } from 'jiti'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url))
|
||||
const jiti = createJiti(import.meta.url)
|
||||
|
||||
const { ECHELLES, ORDRE_ECHELLES, ECHELLES_CADRE_COURT, echelleDeRoute } = await jiti.import(
|
||||
join(__dirname, '..', 'utils', 'echelles.ts'),
|
||||
)
|
||||
|
||||
const cases = [
|
||||
// [path, query, groupe attendu, onglet attendu]
|
||||
['/trouver-du-taf', {}, 'S', 'Jobs'],
|
||||
['/outils', {}, 'S', 'Outils'],
|
||||
['/', {}, 'M', "Écosystème d'entraide"],
|
||||
['/', { vue: 'fiches' }, 'M', "Écosystème d'entraide"],
|
||||
['/agences', {}, 'M', 'Réseaux AEP'],
|
||||
['/agences', { vue: 'fiches' }, 'M', 'Réseaux AEP'],
|
||||
['/codev', {}, 'M', 'Codev'],
|
||||
['/codev/demo', {}, 'M', 'Codev'],
|
||||
['/codev/carto', {}, 'M', 'Codev'],
|
||||
['/media', {}, 'XL', 'Recherche média'],
|
||||
['/media', { tab: 'visuel' }, 'XL', 'Recherche média'],
|
||||
['/media', { tab: 'projets' }, 'XL', 'Publications'],
|
||||
['/manifeste', {}, null, null],
|
||||
['/a-propos', {}, null, null],
|
||||
['/proposer', {}, null, null],
|
||||
['/signaler', {}, null, null],
|
||||
['/fiche/42', {}, null, null],
|
||||
['/outilsXYZ', {}, null, null],
|
||||
['/codevelopper', {}, null, null],
|
||||
]
|
||||
|
||||
let fail = 0
|
||||
for (const [path, query, groupe, onglet] of cases) {
|
||||
const route = { path, query }
|
||||
const r = echelleDeRoute(route)
|
||||
const gotG = r?.echelle ?? null
|
||||
const gotO = r?.onglet.libelle ?? null
|
||||
// Un seul onglet actif sur tout le site pour une route donnée.
|
||||
const actifs = ORDRE_ECHELLES.flatMap((id) => ECHELLES[id].onglets.filter((o) => o.actif(route)))
|
||||
const ok = gotG === groupe && gotO === onglet && actifs.length === (groupe ? 1 : 0)
|
||||
if (!ok) fail++
|
||||
console.log(`${ok ? 'OK ' : 'FAIL'} ${path}${Object.keys(query).length ? '?' + new URLSearchParams(query) : ''} → ${gotG ?? '∅'} / ${gotO ?? '∅'} (actifs : ${actifs.length})`)
|
||||
}
|
||||
|
||||
// Ordre et contenu des groupes (directive Jules du 29/09 + arbitrage 1A).
|
||||
const attendu = {
|
||||
S: ['Jobs', 'Outils'],
|
||||
M: ["Écosystème d'entraide", 'Réseaux AEP', 'Codev'],
|
||||
XL: ['Recherche média', 'Publications'],
|
||||
}
|
||||
for (const id of ORDRE_ECHELLES) {
|
||||
const got = ECHELLES[id].onglets.map((o) => o.libelle)
|
||||
const ok = JSON.stringify(got) === JSON.stringify(attendu[id])
|
||||
if (!ok) fail++
|
||||
console.log(`${ok ? 'OK ' : 'FAIL'} groupe ${id} = ${got.join(' · ')}`)
|
||||
}
|
||||
|
||||
const cadreOk = ECHELLES_CADRE_COURT === 'Trois échelles, imbriquées. Entrez par celle qui presse.'
|
||||
if (!cadreOk) fail++
|
||||
console.log(`${cadreOk ? 'OK ' : 'FAIL'} cadre court = « ${ECHELLES_CADRE_COURT} »`)
|
||||
|
||||
const total = cases.length + ORDRE_ECHELLES.length + 1
|
||||
console.log(`\n${total - fail}/${total}`)
|
||||
process.exit(fail ? 1 : 0)
|
||||
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Test du schéma Zod du formulaire assoupli (B5-M1).
|
||||
* Charge le VRAI schéma TS (utils/submitLibre.ts) via jiti (déjà une dépendance
|
||||
* transitive de Nuxt, pas de nouveau paquet) — pas de réimplémentation parallèle.
|
||||
* Usage : node scripts/test-submit-libre.mjs
|
||||
*/
|
||||
|
||||
import { createJiti } from 'jiti'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url))
|
||||
const jiti = createJiti(import.meta.url)
|
||||
|
||||
const { LibreSubmitSchema, toOrgaPayload, toReferencePayload } = await jiti.import(
|
||||
join(__dirname, '..', 'utils', 'submitLibre.ts'),
|
||||
)
|
||||
|
||||
function baseInput(overrides) {
|
||||
return { liens: [], texte: '', site_web: '', ...overrides }
|
||||
}
|
||||
|
||||
const cases = [
|
||||
{
|
||||
name: 'vide (aucun lien, aucun texte) → refus',
|
||||
input: baseInput({}),
|
||||
expectOk: false,
|
||||
},
|
||||
{
|
||||
name: '1 lien seul → ok',
|
||||
input: baseInput({ liens: ['https://exemple.fr'] }),
|
||||
expectOk: true,
|
||||
},
|
||||
{
|
||||
name: 'texte seul → ok',
|
||||
input: baseInput({ texte: "Ça m'a beaucoup aidé pour ma reconversion." }),
|
||||
expectOk: true,
|
||||
},
|
||||
{
|
||||
name: '11 liens → refus',
|
||||
input: baseInput({ liens: Array.from({ length: 11 }, (_, i) => `https://exemple${i}.fr`) }),
|
||||
expectOk: false,
|
||||
},
|
||||
{
|
||||
name: 'URL invalide (pas de schéma) → refus',
|
||||
input: baseInput({ liens: ['exemple.fr'] }),
|
||||
expectOk: false,
|
||||
},
|
||||
{
|
||||
name: 'ftp:// → refus',
|
||||
input: baseInput({ liens: ['ftp://exemple.fr/fichier.pdf'] }),
|
||||
expectOk: false,
|
||||
},
|
||||
{
|
||||
name: 'double type valide (jobs + outils) → ok',
|
||||
input: baseInput({ liens: ['https://exemple.fr'], type_suggere: 'jobs', type_secondaire: 'outils' }),
|
||||
expectOk: true,
|
||||
},
|
||||
{
|
||||
name: 'type_secondaire sans type_suggere → refus',
|
||||
input: baseInput({ liens: ['https://exemple.fr'], type_secondaire: 'outils' }),
|
||||
expectOk: false,
|
||||
},
|
||||
{
|
||||
name: 'type_secondaire = type_suggere → refus',
|
||||
input: baseInput({ liens: ['https://exemple.fr'], type_suggere: 'jobs', type_secondaire: 'jobs' }),
|
||||
expectOk: false,
|
||||
},
|
||||
{
|
||||
name: 'type inconnu → refus',
|
||||
input: baseInput({ liens: ['https://exemple.fr'], type_suggere: 'inconnu' }),
|
||||
expectOk: false,
|
||||
},
|
||||
]
|
||||
|
||||
let failures = 0
|
||||
|
||||
for (const c of cases) {
|
||||
const result = LibreSubmitSchema.safeParse(c.input)
|
||||
const pass = result.success === c.expectOk
|
||||
const detail = result.success ? '' : ` (${JSON.stringify(result.error.flatten().fieldErrors)})`
|
||||
console.log(`${pass ? 'PASS' : 'FAIL'} — ${c.name}${pass ? '' : detail}`)
|
||||
if (!pass) failures++
|
||||
}
|
||||
|
||||
// ── Mappings (toOrgaPayload / toReferencePayload) ──────────────────────────
|
||||
function checkMapping(name, ok) {
|
||||
console.log(`${ok ? 'PASS' : 'FAIL'} — ${name}`)
|
||||
if (!ok) failures++
|
||||
}
|
||||
|
||||
{
|
||||
const data = LibreSubmitSchema.parse(baseInput({ liens: ['https://exemple.fr'] }))
|
||||
const payload = toOrgaPayload(data)
|
||||
checkMapping(
|
||||
'aucun type → description_user commence par « Type : non précisé »',
|
||||
payload.description_user.startsWith('Type : non précisé'),
|
||||
)
|
||||
}
|
||||
|
||||
{
|
||||
const data = LibreSubmitSchema.parse(baseInput({ liens: ['https://exemple.fr'], type_suggere: 'jobs' }))
|
||||
const payload = toOrgaPayload(data)
|
||||
checkMapping(
|
||||
'un type → pas de marqueur ni de ligne « Type suggéré »',
|
||||
!payload.description_user.startsWith('Type : non précisé') && !payload.description_user.includes('Type suggéré'),
|
||||
)
|
||||
}
|
||||
|
||||
{
|
||||
const data = LibreSubmitSchema.parse(
|
||||
baseInput({ liens: ['https://exemple.fr'], type_suggere: 'jobs', type_secondaire: 'outils' }),
|
||||
)
|
||||
const payload = toOrgaPayload(data)
|
||||
checkMapping(
|
||||
'double type → description_user commence par « Type suggéré : Jobs ou Outils »',
|
||||
payload.description_user.startsWith('Type suggéré : Jobs ou Outils'),
|
||||
)
|
||||
checkMapping('double type → submission_type = le premier (job)', payload.submission_type === 'job')
|
||||
checkMapping(
|
||||
'double type → ne commence PAS par « Type : non précisé »',
|
||||
!payload.description_user.startsWith('Type : non précisé'),
|
||||
)
|
||||
}
|
||||
|
||||
{
|
||||
const data = LibreSubmitSchema.parse(
|
||||
baseInput({ liens: ['https://exemple.fr'], type_suggere: 'references', type_secondaire: 'outils' }),
|
||||
)
|
||||
const payload = toReferencePayload(data)
|
||||
checkMapping(
|
||||
'premier = Références + second → description commence par « Type suggéré : Références ou Outils »',
|
||||
payload.description.startsWith('Type suggéré : Références ou Outils'),
|
||||
)
|
||||
}
|
||||
|
||||
const totalMappingChecks = 6
|
||||
console.log(`\n${failures === 0 ? 'PASS' : 'FAIL'} — ${cases.length + totalMappingChecks - failures}/${cases.length + totalMappingChecks} tests passés`)
|
||||
process.exit(failures > 0 ? 1 : 0)
|
||||
@@ -1,12 +1,12 @@
|
||||
/**
|
||||
* POST /api/chatbot-reseaux
|
||||
* Chatbot Réseaux AEP — Carte 2 "Réseaux de bifurcation"
|
||||
* Keyword search sur reseaux-bifurcation.json + Mistral Small.
|
||||
* Keyword search sur reseaux-bifurcation.json + LLM via Bifrost (server/utils/bifrost.ts).
|
||||
*/
|
||||
// @ts-ignore — JSON import résolu par Rollup
|
||||
import reseauxData from '../../public/data/reseaux-bifurcation.json'
|
||||
import { checkRateLimitJson } from '~/server/utils/rateLimitJson'
|
||||
import { pickBifrostTier, type BifrostChatResponse } from '~/server/utils/bifrost'
|
||||
import { pickBifrostTier, bifrostContent, REASONING_MARGIN_TOKENS, type BifrostChatResponse } from '~/server/utils/bifrost'
|
||||
|
||||
interface Structure {
|
||||
id: string
|
||||
@@ -99,7 +99,7 @@ export default defineEventHandler(async (event) => {
|
||||
model: tier.model,
|
||||
fallbacks: tier.fallbacks,
|
||||
temperature: 0.3,
|
||||
max_tokens: 700,
|
||||
max_tokens: 700 + REASONING_MARGIN_TOKENS,
|
||||
response_format: { type: 'json_object' },
|
||||
messages: [
|
||||
{ role: 'system', content: systemPrompt },
|
||||
@@ -108,7 +108,7 @@ export default defineEventHandler(async (event) => {
|
||||
}),
|
||||
}
|
||||
)
|
||||
mistralRaw = res.choices?.[0]?.message?.content ?? '{}'
|
||||
mistralRaw = bifrostContent(res, 'chatbot-reseaux')
|
||||
} catch {
|
||||
throw createError({ statusCode: 502, message: 'Erreur IA — réessaie dans quelques instants.' })
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
/**
|
||||
* POST /api/chatbot-taff
|
||||
* Chatbot d'aiguillage — Carte 3 "Trouver du taf"
|
||||
* Lit plateformes-taff.json, appelle Mistral Small, retourne recommandations.
|
||||
* Lit plateformes-taff.json, appelle un LLM via Bifrost (server/utils/bifrost.ts), retourne recommandations.
|
||||
*/
|
||||
|
||||
// @ts-ignore — JSON import résolu par Vite/Rollup
|
||||
import taffData from '../../public/data/plateformes-taff.json'
|
||||
import { checkRateLimitJson } from '~/server/utils/rateLimitJson'
|
||||
import { pickBifrostTier, type BifrostChatResponse } from '~/server/utils/bifrost'
|
||||
import { pickBifrostTier, bifrostContent, REASONING_MARGIN_TOKENS, type BifrostChatResponse } from '~/server/utils/bifrost'
|
||||
|
||||
interface PlateformeMinimal {
|
||||
id: string
|
||||
@@ -110,7 +110,7 @@ export default defineEventHandler(async (event) => {
|
||||
model: tier.model,
|
||||
fallbacks: tier.fallbacks,
|
||||
temperature: 0.3,
|
||||
max_tokens: 700,
|
||||
max_tokens: 700 + REASONING_MARGIN_TOKENS,
|
||||
response_format: { type: 'json_object' },
|
||||
messages: [
|
||||
{ role: 'system', content: systemPrompt },
|
||||
@@ -119,7 +119,7 @@ export default defineEventHandler(async (event) => {
|
||||
}),
|
||||
}
|
||||
)
|
||||
mistralRaw = res.choices?.[0]?.message?.content ?? '{}'
|
||||
mistralRaw = bifrostContent(res, 'chatbot-taff')
|
||||
} catch {
|
||||
throw createError({ statusCode: 502, statusMessage: 'Erreur IA — réessaie dans quelques instants.' })
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
/**
|
||||
* POST /api/chatbot
|
||||
*
|
||||
* Chatbot recherche sémantique — Mistral Small
|
||||
* Chatbot recherche sémantique — LLM via Bifrost (tiers et replis : server/utils/bifrost.ts)
|
||||
* Spec : F §7 (endpoint), F §8 (rate limit), E-spec §6 (détails chatbot)
|
||||
*
|
||||
* Flow :
|
||||
* 1. Rate limit : 10 req/IP/jour (JSON fichier, SHA-256)
|
||||
* 2. Circuit breaker : budget 20€/mois
|
||||
* 3. Fetch top-N fiches (keyword match sur nom+description+fonctions)
|
||||
* 4. Appel Mistral Small avec contexte JSON compact
|
||||
* 4. Appel Bifrost (tier RAPIDE par défaut) avec contexte JSON compact
|
||||
* 5. Parse JSON → { reponse_texte, fiches_recommandees }
|
||||
* 6. Log stats_usage
|
||||
*
|
||||
@@ -19,7 +19,7 @@
|
||||
|
||||
import { checkRateLimitJson } from '~/server/utils/rateLimitJson'
|
||||
import { checkBudget, calcCoutMistralSmall } from '~/server/utils/circuitBreaker'
|
||||
import { pickBifrostTier, type BifrostChatResponse } from '~/server/utils/bifrost'
|
||||
import { pickBifrostTier, bifrostContent, REASONING_MARGIN_TOKENS, type BifrostChatResponse } from '~/server/utils/bifrost'
|
||||
|
||||
// ── Types ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -277,7 +277,7 @@ export default defineEventHandler(async (event) => {
|
||||
model: tier.model,
|
||||
fallbacks: tier.fallbacks,
|
||||
temperature: 0.3,
|
||||
max_tokens: 600,
|
||||
max_tokens: 600 + REASONING_MARGIN_TOKENS,
|
||||
response_format: { type: 'json_object' },
|
||||
messages: [
|
||||
{ role: 'system', content: systemPrompt },
|
||||
@@ -286,7 +286,7 @@ export default defineEventHandler(async (event) => {
|
||||
}),
|
||||
})
|
||||
|
||||
mistralRaw = bifrostRes.choices?.[0]?.message?.content ?? '{}'
|
||||
mistralRaw = bifrostContent(bifrostRes, 'chatbot')
|
||||
tokensIn = bifrostRes.usage?.prompt_tokens ?? 0
|
||||
tokensOut = bifrostRes.usage?.completion_tokens ?? 0
|
||||
realModel =
|
||||
|
||||
+134
-37
@@ -14,6 +14,8 @@
|
||||
|
||||
import { z } from 'zod'
|
||||
import { checkRateLimit } from '~/server/utils/rateLimit'
|
||||
import { notifyNtfy, buildSubmissionNotif } from '~/server/utils/notify'
|
||||
import { LibreSubmitSchema, toOrgaPayload, toReferencePayload, type LibreSubmitInput } from '~/utils/submitLibre'
|
||||
|
||||
const SUBMISSION_TYPES = ['ecosysteme', 'reseau', 'job', 'outil'] as const
|
||||
|
||||
@@ -103,6 +105,15 @@ export default defineEventHandler(async (event) => {
|
||||
|
||||
// 3. Lire et valider le body
|
||||
const body = await readBody(event)
|
||||
|
||||
// Formulaire assoupli (B5-M1) — liens + texte libre, type suggéré optionnel.
|
||||
if (body?.mode === 'libre') {
|
||||
return handleLibreSubmit(body)
|
||||
}
|
||||
|
||||
// (rate limit déjà vérifié ci-dessus pour les deux modes)
|
||||
|
||||
// Mode détaillé (5 formulaires typés, conservés derrière un lien discret)
|
||||
const parsed = SubmitSchema.safeParse(body)
|
||||
|
||||
if (!parsed.success) {
|
||||
@@ -188,10 +199,17 @@ export default defineEventHandler(async (event) => {
|
||||
|
||||
const submissionId = insertedRecord?.Id ?? insertedRecord?.id ?? null
|
||||
|
||||
// 6. Notification email Jules (fire-and-forget — n'impacte pas la réponse)
|
||||
notifyJules(config, data, submissionId).catch((e) =>
|
||||
console.warn('[submit] Email notification échouée:', e?.message ?? e),
|
||||
)
|
||||
// 6. Notification ntfy à Jules (fire-and-forget — n'impacte pas la réponse)
|
||||
notifyNtfy(
|
||||
process.env.NTFY_TOPIC,
|
||||
buildSubmissionNotif({
|
||||
submissionId,
|
||||
nomSuggere: data.nom,
|
||||
typeSuggere: data.submission_type,
|
||||
nbLiens: data.url ? 1 : 0,
|
||||
nocodbAdminUrl: NOCODB_ADMIN_URL,
|
||||
}),
|
||||
).catch((e) => console.warn('[submit] Notification ntfy échouée:', e?.message ?? e))
|
||||
|
||||
return {
|
||||
status: 201,
|
||||
@@ -203,40 +221,119 @@ export default defineEventHandler(async (event) => {
|
||||
}
|
||||
})
|
||||
|
||||
async function notifyJules(
|
||||
config: ReturnType<typeof useRuntimeConfig>,
|
||||
data: SubmitInput,
|
||||
submissionId: number | null,
|
||||
): Promise<void> {
|
||||
if (!config.resendApiKey) return
|
||||
// ── Formulaire assoupli (B5-M1) ─────────────────────────────────────────────
|
||||
|
||||
const nocoAdminUrl = `http://localhost:8070`
|
||||
const body = {
|
||||
from: 'AEP Carte <contact@trans-former.fr>',
|
||||
to: [config.emailJules],
|
||||
subject: `[AEP] Nouvelle fiche soumise : ${data.nom}`,
|
||||
html: `
|
||||
<p><strong>Nouvelle fiche en attente de modération.</strong></p>
|
||||
<ul>
|
||||
<li><strong>Nom :</strong> ${data.nom}</li>
|
||||
<li><strong>URL :</strong> ${data.url ?? '—'}</li>
|
||||
<li><strong>Échelle :</strong> ${data.echelle}</li>
|
||||
<li><strong>Territoire :</strong> ${data.territoire}</li>
|
||||
<li><strong>Fonctions :</strong> ${data.fonctions.join(', ')}</li>
|
||||
<li><strong>Description :</strong> ${data.description_user}</li>
|
||||
${data.submitted_by_email ? `<li><strong>Email soumetteur :</strong> ${data.submitted_by_email}</li>` : ''}
|
||||
${submissionId ? `<li><strong>ID NocoDB :</strong> ${submissionId}</li>` : ''}
|
||||
</ul>
|
||||
<p><a href="${nocoAdminUrl}">Ouvrir NocoDB pour valider</a></p>
|
||||
`,
|
||||
async function handleLibreSubmit(body: unknown) {
|
||||
const parsed = LibreSubmitSchema.safeParse(body)
|
||||
|
||||
if (!parsed.success) {
|
||||
throw createError({
|
||||
statusCode: 422,
|
||||
statusMessage: 'Validation échouée',
|
||||
data: parsed.error.flatten().fieldErrors,
|
||||
})
|
||||
}
|
||||
|
||||
await $fetch('https://api.resend.com/emails', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${config.resendApiKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
const data = parsed.data
|
||||
|
||||
// Honeypot : un bot remplit ce champ caché — on répond succès sans rien écrire.
|
||||
if (data.site_web) {
|
||||
return {
|
||||
status: 201,
|
||||
submissionId: null,
|
||||
message: 'Ta fiche est en cours de traitement.',
|
||||
trackingUrl: null,
|
||||
}
|
||||
}
|
||||
|
||||
const config = useRuntimeConfig()
|
||||
|
||||
// Chip « Références » → table ressources_references, pas la table orgas.
|
||||
if (data.type_suggere === 'references') {
|
||||
return insertReferenceLibre(config, data)
|
||||
}
|
||||
|
||||
const payload = toOrgaPayload(data)
|
||||
const insertUrl = `${config.nocodbUrl}/api/v1/db/data/noco/${config.nocodbBase}/${config.orgTableId}`
|
||||
|
||||
let insertedRecord: any
|
||||
try {
|
||||
insertedRecord = await $fetch(insertUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'xc-token': config.nocodbToken, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
} catch (e: any) {
|
||||
console.error('[submit] Erreur NocoDB insert (libre):', e?.message ?? e)
|
||||
throw createError({ statusCode: 502, statusMessage: 'Erreur serveur — réessaie dans quelques instants.' })
|
||||
}
|
||||
|
||||
const submissionId = insertedRecord?.Id ?? insertedRecord?.id ?? null
|
||||
|
||||
notifyNtfy(
|
||||
process.env.NTFY_TOPIC,
|
||||
buildSubmissionNotif({
|
||||
submissionId,
|
||||
nomSuggere: nomPourNotif(payload.nom, data),
|
||||
typeSuggere: payload.submission_type,
|
||||
nbLiens: data.liens.length,
|
||||
nocodbAdminUrl: NOCODB_ADMIN_URL,
|
||||
}),
|
||||
).catch((e) => console.warn('[submit] Notification ntfy échouée (libre):', e?.message ?? e))
|
||||
|
||||
return {
|
||||
status: 201,
|
||||
submissionId,
|
||||
message: 'Ta fiche est en cours de traitement.',
|
||||
trackingUrl: null,
|
||||
}
|
||||
}
|
||||
|
||||
/** URL de modération cliquable depuis la notification (téléphone) — jamais localhost. */
|
||||
const NOCODB_ADMIN_URL = 'https://sheets.trans-former.fr'
|
||||
|
||||
/**
|
||||
* Sans lien, `nomSuggere()` retombe sur les 60 premiers caractères du texte libre :
|
||||
* ce texte ne doit jamais partir vers ntfy (topic public par URL). On ne transmet
|
||||
* le nom que lorsqu'il est dérivé d'un hostname.
|
||||
*/
|
||||
function nomPourNotif(nom: string, data: LibreSubmitInput): string {
|
||||
return data.liens.length > 0 ? nom : '[à qualifier] texte seul (voir NocoDB)'
|
||||
}
|
||||
|
||||
async function insertReferenceLibre(config: ReturnType<typeof useRuntimeConfig>, data: LibreSubmitInput) {
|
||||
const payload = toReferencePayload(data)
|
||||
const insertUrl = `${config.nocodbUrl}/api/v1/db/data/noco/${config.nocodbBase}/${config.referencesTableId}`
|
||||
|
||||
let insertedRecord: any
|
||||
try {
|
||||
insertedRecord = await $fetch(insertUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'xc-token': config.nocodbToken, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
} catch (e: any) {
|
||||
console.error('[submit] Erreur NocoDB insert (référence libre):', e?.message ?? e)
|
||||
throw createError({ statusCode: 502, statusMessage: 'Erreur serveur — réessaie dans quelques instants.' })
|
||||
}
|
||||
|
||||
const referenceId = insertedRecord?.Id ?? insertedRecord?.id ?? null
|
||||
|
||||
notifyNtfy(
|
||||
process.env.NTFY_TOPIC,
|
||||
buildSubmissionNotif({
|
||||
submissionId: referenceId,
|
||||
nomSuggere: nomPourNotif(payload.titre, data),
|
||||
typeSuggere: 'references',
|
||||
nbLiens: data.liens.length,
|
||||
nocodbAdminUrl: NOCODB_ADMIN_URL,
|
||||
}),
|
||||
).catch((e) => console.warn('[submit] Notification ntfy échouée (référence libre):', e?.message ?? e))
|
||||
|
||||
return {
|
||||
status: 201,
|
||||
submissionId: referenceId,
|
||||
message: 'Ta référence est en attente de modération.',
|
||||
trackingUrl: null,
|
||||
}
|
||||
}
|
||||
|
||||
+39
-4
@@ -3,10 +3,24 @@
|
||||
* Endpoint OpenAI-compatible : POST {bifrostUrl}/v1/chat/completions
|
||||
* Auth : header x-bf-vk
|
||||
*
|
||||
* 2 tiers validés (Mission M3, build Bifrost) :
|
||||
* 2 tiers (Mission M3 du build Bifrost ; modèles primaires changés le 28/09, session AEP front 4) :
|
||||
* RAPIDE — défaut, pas de toggle UI mode rapide/approfondi sur le site actuellement
|
||||
* APPROFONDI — activable via body.mode === 'approfondi' (prêt pour un futur toggle front)
|
||||
*
|
||||
* ⚠ 28/09 : Groq a retiré groq/llama-3.1-8b-instant (RAPIDE) et groq/llama-3.3-70b-versatile
|
||||
* (APPROFONDI) — 404 model_not_found via Bifrost. Depuis le 23/09 environ, chaque appel
|
||||
* chatbot tombait sur le premier repli Gemini (stats_usage). Primaires passés sur
|
||||
* groq/openai/gpt-oss-20b et groq/openai/gpt-oss-120b ; replis inchangés. Le worker
|
||||
* /opt/aep-worker tourne sur gpt-oss-20b en prod depuis le 28/09 (WORKER_MODEL, json_object) :
|
||||
* Bifrost accepte ce nom de modèle à slash côté Groq.
|
||||
* ⚠ gpt-oss est un modèle à raisonnement :
|
||||
* - la réponse porte un champ message.reasoning à côté de message.content. Les routes
|
||||
* chatbot ne lisent que content (JSON), usage et extra_fields : le champ est ignoré ;
|
||||
* - les tokens de raisonnement sont décomptés de max_tokens. Sans marge, le JSON de la
|
||||
* réponse peut être tronqué ; rendu en HTTP 200, Bifrost ne bascule pas, JSON.parse
|
||||
* échoue → « Je n'ai pas pu analyser ta demande ». Déjà vu le 15/07 : gpt-oss-120b (via Cerebras), 3 appels
|
||||
* corrects sur 4, « tronque parfois à max_tokens 700 ». D'où REASONING_MARGIN_TOKENS, ajouté par
|
||||
* chaque route à son budget de contenu.
|
||||
* ⚠ openrouter-oai exclu (bug Bifrost confirmé — 404 HTML sur modèles avec slash)
|
||||
* ⚠ gemini-oai exige le préfixe "models/" (sinon 403 silencieux)
|
||||
* ⚠ cerebras/gemma-4-31b RETIRÉ du tier RAPIDE (M4, 15/07) : en JSON mode avec un contexte
|
||||
@@ -19,7 +33,7 @@
|
||||
*/
|
||||
|
||||
export const BIFROST_TIER_RAPIDE = {
|
||||
model: 'groq/llama-3.1-8b-instant',
|
||||
model: 'groq/openai/gpt-oss-20b',
|
||||
fallbacks: [
|
||||
'gemini-oai/models/gemini-2.5-flash-lite',
|
||||
'cohere/command-r-08-2024',
|
||||
@@ -27,7 +41,7 @@ export const BIFROST_TIER_RAPIDE = {
|
||||
}
|
||||
|
||||
export const BIFROST_TIER_APPROFONDI = {
|
||||
model: 'groq/llama-3.3-70b-versatile',
|
||||
model: 'groq/openai/gpt-oss-120b',
|
||||
fallbacks: [
|
||||
'gemini-oai/models/gemini-2.5-flash',
|
||||
'mistral/mistral-large-latest',
|
||||
@@ -35,13 +49,34 @@ export const BIFROST_TIER_APPROFONDI = {
|
||||
],
|
||||
}
|
||||
|
||||
/**
|
||||
* Tokens ajoutés au budget de contenu de chaque route (max_tokens = contenu + marge) pour
|
||||
* absorber le raisonnement de gpt-oss. Plafond seulement : les replis sans raisonnement
|
||||
* n'écrivent pas plus long, les prompts bornent la réponse (200-250 mots). Rester modeste :
|
||||
* la limite de tokens par minute d'une clé Groq peut compter max_tokens avec le prompt.
|
||||
*/
|
||||
export const REASONING_MARGIN_TOKENS = 800
|
||||
|
||||
/** Sélectionne le tier selon le param optionnel body.mode. */
|
||||
export function pickBifrostTier(mode?: string) {
|
||||
return mode === 'approfondi' ? BIFROST_TIER_APPROFONDI : BIFROST_TIER_RAPIDE
|
||||
}
|
||||
|
||||
export interface BifrostChatResponse {
|
||||
choices: { message: { content: string } }[]
|
||||
/** reasoning : présent avec gpt-oss, jamais lu (la réponse utile est dans content). */
|
||||
choices: { message: { content: string; reasoning?: string }; finish_reason?: string }[]
|
||||
usage?: { prompt_tokens: number; completion_tokens: number }
|
||||
extra_fields?: { provider?: string; resolved_model_used?: string }
|
||||
}
|
||||
|
||||
/**
|
||||
* Contenu JSON de la réponse. Une troncature (finish_reason 'length') ne lève aucune erreur
|
||||
* et finit en message générique côté usager : on la signale au journal pour la voir.
|
||||
*/
|
||||
export function bifrostContent(res: BifrostChatResponse, route: string): string {
|
||||
const choice = res.choices?.[0]
|
||||
if (choice?.finish_reason === 'length') {
|
||||
console.warn(`[${route}] réponse tronquée (finish_reason=length) : relever REASONING_MARGIN_TOKENS`)
|
||||
}
|
||||
return choice?.message?.content ?? '{}'
|
||||
}
|
||||
|
||||
+100
-27
@@ -19,53 +19,126 @@ export interface BudgetStatus {
|
||||
cumulEur: number
|
||||
blocked: boolean
|
||||
warning: boolean
|
||||
/** false si stats_usage n'a pas pu être lu : le budget n'est alors PAS vérifié (fail-open). */
|
||||
verified: boolean
|
||||
/** Lignes lues dans stats_usage (toutes dates). */
|
||||
lignesLues: number
|
||||
/** Lignes retenues pour le mois courant. */
|
||||
lignesMois: number
|
||||
/** Lignes sans aucun champ date reconnu (ignorées, comme dans le worker). */
|
||||
lignesSansDate: number
|
||||
}
|
||||
|
||||
/** Page NocoDB v2 : seuls les champs lus ici sont typés. */
|
||||
interface StatsPage {
|
||||
list?: Record<string, unknown>[]
|
||||
pageInfo?: { isLastPage?: boolean }
|
||||
}
|
||||
|
||||
type FetchJson = (
|
||||
url: string,
|
||||
opts: { headers: Record<string, string>; query: Record<string, string | number> },
|
||||
) => Promise<StatsPage>
|
||||
|
||||
const PAGE_SIZE = 1000
|
||||
const MAX_PAGES = 20 // 20 000 lignes : garde-fou contre une boucle, pas une limite métier
|
||||
|
||||
/**
|
||||
* Date d'une ligne de stats_usage, dans l'ordre du worker (`worker/enrich.js`,
|
||||
* getBudgetMoisCourant) : `timestamp` écrit par les routes et le worker, sinon
|
||||
* la colonne système de NocoDB (`CreatedAt`, ou `created_at` selon la version).
|
||||
*/
|
||||
export function dateLigne(row: Record<string, unknown>): Date | null {
|
||||
const brut = row.timestamp ?? row.CreatedAt ?? row.created_at
|
||||
if (brut === null || brut === undefined || brut === '') return null
|
||||
const d = new Date(brut as string)
|
||||
return Number.isNaN(d.getTime()) ? null : d
|
||||
}
|
||||
|
||||
/**
|
||||
* Calcule le cumul de dépenses IA du mois courant depuis stats_usage NocoDB.
|
||||
* Retourne blocked=true si le budget est atteint.
|
||||
*
|
||||
* AF5 (29/09) : la requête ne nomme plus AUCUNE colonne (ni `where`, ni `fields`,
|
||||
* ni `sort`). L'ancienne version filtrait sur `timestamp` côté NocoDB et recevait
|
||||
* un 422 à chaque appel : budget jamais vérifié côté chatbot, en silence
|
||||
* (fail-open). On lit la table page par page et on filtre le mois en JS,
|
||||
* comme le worker, qui lit la même table sans erreur.
|
||||
*/
|
||||
export async function checkBudget(config: {
|
||||
nocodbUrl: string
|
||||
nocodbToken: string
|
||||
statsTableId: string
|
||||
/** Injecté par les tests ; `$fetch` de Nitro sinon. */
|
||||
fetchJson?: FetchJson
|
||||
/** Injecté par les tests ; maintenant sinon. */
|
||||
now?: Date
|
||||
}): Promise<BudgetStatus> {
|
||||
const { nocodbUrl, nocodbToken, statsTableId } = config
|
||||
const fetchJson: FetchJson = config.fetchJson ?? ((url, opts) => $fetch<StatsPage>(url, opts))
|
||||
const now = config.now ?? new Date()
|
||||
const annee = now.getUTCFullYear()
|
||||
const mois = now.getUTCMonth()
|
||||
|
||||
// Premier du mois courant à minuit UTC
|
||||
const now = new Date()
|
||||
const monthStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1))
|
||||
const monthStartIso = monthStart.toISOString()
|
||||
const url = `${nocodbUrl}/api/v2/tables/${statsTableId}/records`
|
||||
let cumulEur = 0
|
||||
let lignesLues = 0
|
||||
let lignesMois = 0
|
||||
let lignesSansDate = 0
|
||||
|
||||
try {
|
||||
// Fetch toutes les entrées du mois courant (NocoDB v2)
|
||||
const url = `${nocodbUrl}/api/v2/tables/${statsTableId}/records`
|
||||
|
||||
const res = await $fetch<{ list: { cout_eur: number | null; timestamp: string }[] }>(
|
||||
url,
|
||||
{
|
||||
for (let page = 0; page < MAX_PAGES; page++) {
|
||||
const res = await fetchJson(url, {
|
||||
headers: { 'xc-token': nocodbToken },
|
||||
query: {
|
||||
where: `(timestamp,gte,${monthStartIso})`,
|
||||
limit: 1000,
|
||||
fields: 'cout_eur,timestamp',
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
const rows = res?.list ?? []
|
||||
const cumulEur = rows.reduce((sum, row) => sum + (Number(row.cout_eur) || 0), 0)
|
||||
|
||||
return {
|
||||
cumulEur,
|
||||
blocked: cumulEur >= BUDGET_MAX_EUR,
|
||||
warning: cumulEur >= BUDGET_WARN_EUR,
|
||||
query: { limit: PAGE_SIZE, offset: page * PAGE_SIZE },
|
||||
})
|
||||
const rows = res?.list ?? []
|
||||
for (const row of rows) {
|
||||
lignesLues++
|
||||
const d = dateLigne(row)
|
||||
if (!d) {
|
||||
lignesSansDate++
|
||||
continue
|
||||
}
|
||||
if (d.getUTCFullYear() === annee && d.getUTCMonth() === mois) {
|
||||
lignesMois++
|
||||
cumulEur += Number(row.cout_eur) || 0
|
||||
}
|
||||
}
|
||||
if (rows.length < PAGE_SIZE || res?.pageInfo?.isLastPage) break
|
||||
}
|
||||
} catch (e) {
|
||||
// En cas d'erreur de lecture, on ne bloque PAS pour ne pas pénaliser les utilisateurs
|
||||
console.warn('[circuitBreaker] Erreur lecture stats_usage — budget non vérifié:', (e as Error).message)
|
||||
return { cumulEur: 0, blocked: false, warning: false }
|
||||
console.warn('[circuitBreaker] Erreur lecture stats_usage — budget NON vérifié:', (e as Error).message)
|
||||
return { cumulEur: 0, blocked: false, warning: false, verified: false, lignesLues, lignesMois, lignesSansDate }
|
||||
}
|
||||
|
||||
// Des lignes, mais aucune datée : on ne sait pas ce qui relève du mois.
|
||||
// Rendre « 0 € vérifié » reproduirait le fail-open silencieux d'avant AF5.
|
||||
if (lignesLues > 0 && lignesSansDate === lignesLues) {
|
||||
console.warn(
|
||||
`[circuitBreaker] budget NON vérifié : ${lignesLues} lignes stats_usage sans timestamp, CreatedAt ni created_at`,
|
||||
)
|
||||
return { cumulEur: 0, blocked: false, warning: false, verified: false, lignesLues, lignesMois, lignesSansDate }
|
||||
}
|
||||
|
||||
const status: BudgetStatus = {
|
||||
cumulEur,
|
||||
blocked: cumulEur >= BUDGET_MAX_EUR,
|
||||
warning: cumulEur >= BUDGET_WARN_EUR,
|
||||
verified: true,
|
||||
lignesLues,
|
||||
lignesMois,
|
||||
lignesSansDate,
|
||||
}
|
||||
const mm = String(mois + 1).padStart(2, '0')
|
||||
const suffixe = status.blocked ? ' — BLOQUÉ' : status.warning ? ' — alerte' : ''
|
||||
const sansDate = lignesSansDate ? `, ${lignesSansDate} sans date ignorées` : ''
|
||||
console.info(
|
||||
`[circuitBreaker] budget lu : ${cumulEur.toFixed(4)} € / ${BUDGET_MAX_EUR} € ` +
|
||||
`(${lignesMois} lignes ${annee}-${mm} sur ${lignesLues} lues${sansDate})${suffixe}`,
|
||||
)
|
||||
return status
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* Notification ntfy.sh — remplace Resend (abandonné le 15/07, domaine non vérifié).
|
||||
* POST https://ntfy.sh/${NTFY_TOPIC}
|
||||
*
|
||||
* RÈGLE : un topic ntfy est une URL, pas un coffre — le message ne contient
|
||||
* JAMAIS l'email du contributeur ni le texte libre soumis. Seulement des
|
||||
* métadonnées de modération (id NocoDB, nom suggéré, type, nb de liens).
|
||||
*
|
||||
* Si NTFY_TOPIC est absent : log et continue (pas d'erreur bloquante).
|
||||
*/
|
||||
|
||||
export interface NtfyNotifyInput {
|
||||
title: string
|
||||
message: string
|
||||
/** Priorité ntfy 1-5 (3 = défaut) */
|
||||
priority?: number
|
||||
tags?: string[]
|
||||
/** Lien cliqué depuis la notif (ex : NocoDB) */
|
||||
clickUrl?: string
|
||||
}
|
||||
|
||||
export async function notifyNtfy(topic: string | undefined, input: NtfyNotifyInput): Promise<void> {
|
||||
if (!topic) {
|
||||
console.warn('[notify] NTFY_TOPIC absent — notification skippée:', input.title)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const headers: Record<string, string> = {
|
||||
Title: encodeHeaderValue(input.title),
|
||||
Priority: String(input.priority ?? 3),
|
||||
}
|
||||
if (input.tags?.length) headers.Tags = input.tags.join(',')
|
||||
if (input.clickUrl) headers.Click = input.clickUrl
|
||||
|
||||
const res = await fetch(`https://ntfy.sh/${topic}`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: input.message,
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
console.warn('[notify] ntfy erreur HTTP:', res.status, await res.text())
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.warn('[notify] ntfy exception:', e?.message ?? e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Construit le message de notification pour une nouvelle soumission.
|
||||
* N'inclut jamais l'email ni le texte libre du contributeur.
|
||||
*/
|
||||
export function buildSubmissionNotif(input: {
|
||||
submissionId: number | string | null
|
||||
nomSuggere: string
|
||||
typeSuggere: string
|
||||
nbLiens: number
|
||||
nocodbAdminUrl?: string
|
||||
}): NtfyNotifyInput {
|
||||
const { submissionId, nomSuggere, typeSuggere, nbLiens, nocodbAdminUrl } = input
|
||||
return {
|
||||
title: '[AEP] Nouvelle fiche soumise',
|
||||
message: [
|
||||
`Id NocoDB : ${submissionId ?? '—'}`,
|
||||
`Nom suggéré : ${nomSuggere}`,
|
||||
`Type suggéré : ${typeSuggere}`,
|
||||
`Liens : ${nbLiens}`,
|
||||
].join('\n'),
|
||||
tags: ['inbox_tray'],
|
||||
clickUrl: nocodbAdminUrl,
|
||||
}
|
||||
}
|
||||
|
||||
function encodeHeaderValue(v: string): string {
|
||||
// ntfy accepte l'UTF-8 dans les headers mais certains proxies sont capricieux
|
||||
// avec les accents en header brut — on reste simple, ntfy gère nativement.
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* Les trois échelles du deck du 23/09/2026 (conférence AEP), slides 15 à 18.
|
||||
* Texte repris mot pour mot : c'est la tête de chaque onglet (directive Jules du 25/09, point 2).
|
||||
* Source unique : la nav S / M / XL (B10 : NavEchelles, NavTiroir, FilEchelle) lit aussi ce fichier.
|
||||
* Aucun libellé d'échelle ni d'onglet ne se recopie ailleurs.
|
||||
*/
|
||||
export type EchelleId = 'S' | 'M' | 'XL'
|
||||
|
||||
/** Ce que la nav lit d'une route : compatible avec `useRoute()` sans en dépendre (testable en node). */
|
||||
export interface RouteNav {
|
||||
path: string
|
||||
query?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface OngletNav {
|
||||
libelle: string
|
||||
to: string
|
||||
actif: (route: RouteNav) => boolean
|
||||
}
|
||||
|
||||
export interface Echelle {
|
||||
id: EchelleId
|
||||
titre: string
|
||||
sousTitre?: string
|
||||
mots: string[]
|
||||
phrase: string
|
||||
/** Catégorie de /proposer présélectionnée par le lien de contribution. */
|
||||
categorieProposer: 'ecosysteme' | 'reseau' | 'jobs' | 'outils' | 'references'
|
||||
/** Onglets du groupe, dans l'ordre de la barre, du menu et du fil d'échelle (B10, directive Jules du 29/09 + arbitrage 1A du 26/09). */
|
||||
onglets: OngletNav[]
|
||||
}
|
||||
|
||||
const sousChemin = (base: string) => (r: RouteNav) => r.path === base || r.path.startsWith(`${base}/`)
|
||||
const surPublications = (r: RouteNav) => r.query?.tab === 'projets'
|
||||
|
||||
export const ECHELLES: Record<EchelleId, Echelle> = {
|
||||
S: {
|
||||
id: 'S',
|
||||
titre: 'Partir de soi',
|
||||
sousTitre: "pour s'émanciper",
|
||||
mots: [
|
||||
'quête de sens',
|
||||
'où habiter, avec qui',
|
||||
'gagner sa vie',
|
||||
'santé mentale',
|
||||
'mener ses projets',
|
||||
'naviguer avec soi',
|
||||
'les compétences psychosociales',
|
||||
],
|
||||
phrase: 'Des ressources, des méthodes, des pairs : matériel et mutualisé.',
|
||||
categorieProposer: 'outils',
|
||||
onglets: [
|
||||
{ libelle: 'Jobs', to: '/trouver-du-taf', actif: sousChemin('/trouver-du-taf') },
|
||||
{ libelle: 'Outils', to: '/outils', actif: sousChemin('/outils') },
|
||||
],
|
||||
},
|
||||
M: {
|
||||
id: 'M',
|
||||
titre: 'La communauté',
|
||||
mots: [
|
||||
'entraide',
|
||||
'mutualisation',
|
||||
'appartenance',
|
||||
'être vu, soutenu',
|
||||
'traverser les creux',
|
||||
'accomplissement',
|
||||
'le codev',
|
||||
],
|
||||
phrase: "C'est le groupe qui remet un individu debout. L'affinité fait tenir, la confrontation fait avancer.",
|
||||
categorieProposer: 'ecosysteme',
|
||||
onglets: [
|
||||
{ libelle: "Écosystème d'entraide", to: '/', actif: (r) => r.path === '/' },
|
||||
{ libelle: 'Réseaux AEP', to: '/agences', actif: sousChemin('/agences') },
|
||||
{ libelle: 'Codev', to: '/codev', actif: sousChemin('/codev') },
|
||||
],
|
||||
},
|
||||
XL: {
|
||||
id: 'XL',
|
||||
titre: 'Contribuer',
|
||||
mots: [
|
||||
'contribution',
|
||||
'affiliation, filiation',
|
||||
'identité',
|
||||
'sens',
|
||||
'de nouveaux récits',
|
||||
'un nouveau contrat social',
|
||||
'la médecine du corps social',
|
||||
],
|
||||
phrase: 'La bibliothèque, les récits, la filiation entre projets.',
|
||||
categorieProposer: 'references',
|
||||
onglets: [
|
||||
{ libelle: 'Recherche média', to: '/media', actif: (r) => sousChemin('/media')(r) && !surPublications(r) },
|
||||
{ libelle: 'Publications', to: '/media?tab=projets', actif: (r) => sousChemin('/media')(r) && surPublications(r) },
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
/** Ordre des groupes dans la barre et le menu. */
|
||||
export const ORDRE_ECHELLES: EchelleId[] = ['S', 'M', 'XL']
|
||||
|
||||
/** Slide 15, commune aux trois échelles. */
|
||||
export const ECHELLES_CADRE = "Trois échelles, imbriquées. Pas un escalier : ça circule dans les deux sens. Entrez par celle qui presse."
|
||||
|
||||
/** Version courte de la slide 15 (tête du menu) : première et dernière phrase, tirées du texte ci-dessus. */
|
||||
export const ECHELLES_CADRE_COURT = (() => {
|
||||
const phrases = ECHELLES_CADRE.match(/[^.]+\./g) ?? [ECHELLES_CADRE]
|
||||
return phrases.length > 1 ? `${phrases[0].trim()} ${phrases[phrases.length - 1].trim()}` : ECHELLES_CADRE
|
||||
})()
|
||||
|
||||
/** Groupe de la page courante et son onglet actif, ou null hors groupe (Manifeste, À propos, Proposer, fiche…). */
|
||||
export function echelleDeRoute(route: RouteNav): { echelle: EchelleId; onglet: OngletNav } | null {
|
||||
for (const id of ORDRE_ECHELLES) {
|
||||
const onglet = ECHELLES[id].onglets.find((o) => o.actif(route))
|
||||
if (onglet) return { echelle: id, onglet }
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
/** Lien de don (Liberapay), partagé par la barre, le tiroir et À propos. */
|
||||
export const SOUTENIR_URL = 'https://liberapay.com/trans-former.fr/donate'
|
||||
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* B5-M1 — Schéma + mapping du formulaire « proposer » assoupli.
|
||||
*
|
||||
* LE PRINCIPE (décision Jules) : le contributeur colle un lien (ou une liste
|
||||
* de liens) + explique en texte libre pourquoi c'est pertinent. Pas de
|
||||
* description obligatoire, pas de limite de mots, pas de template imposé.
|
||||
* Le typage devient une suggestion optionnelle (chips).
|
||||
*
|
||||
* Partagé client (formulaire, validation immédiate) et serveur (validation
|
||||
* finale + mapping vers les colonnes NocoDB existantes — aucun changement de
|
||||
* schéma, cf. B5-proposer-pipe.md écart #4).
|
||||
*/
|
||||
|
||||
import { z } from 'zod'
|
||||
|
||||
/** Chips optionnelles — mêmes 5 catégories que les onglets historiques de /proposer. */
|
||||
export const TYPES_SUGGERES = ['ecosysteme', 'reseau', 'jobs', 'outils', 'references'] as const
|
||||
export type TypeSuggere = (typeof TYPES_SUGGERES)[number]
|
||||
|
||||
export const TYPES_SUGGERES_LABELS: Record<TypeSuggere, string> = {
|
||||
ecosysteme: 'Écosystème / Entraide',
|
||||
reseau: 'Réseau AEP',
|
||||
jobs: 'Jobs',
|
||||
outils: 'Outils',
|
||||
references: 'Références',
|
||||
}
|
||||
|
||||
/**
|
||||
* Légende courte sous les chips — définitions tirées des textes existants du site :
|
||||
* ecosysteme/jobs/outils/references reprennent la tête d'onglet (`TABS`, pages/proposer.vue)
|
||||
* et/ou la phrase de l'échelle qui pointe vers ce type (utils/echelles.ts) ; reseau reprend
|
||||
* la tête d'onglet « Réseau AEP » et les champs projet/lien de FormReseau.vue.
|
||||
*/
|
||||
export const TYPES_SUGGERES_HINTS: Record<TypeSuggere, string> = {
|
||||
ecosysteme: 'entraide, mutualisation',
|
||||
reseau: 'acteurs et projets AEP',
|
||||
jobs: 'offres, plateformes d\'emploi',
|
||||
outils: 'ressources, méthodes',
|
||||
references: 'bibliothèque, ouvrages',
|
||||
}
|
||||
|
||||
/** URL http(s) uniquement — un `ftp://` ou autre schéma est invalide. */
|
||||
const httpUrl = z
|
||||
.string()
|
||||
.trim()
|
||||
.refine((v) => /^https?:\/\/.+/i.test(v), { message: 'URL invalide (doit commencer par http:// ou https://)' })
|
||||
|
||||
export const LibreSubmitSchema = z
|
||||
.object({
|
||||
liens: z.array(httpUrl).max(10, 'Maximum 10 liens').default([]),
|
||||
texte: z.string().max(8000, 'Maximum 8000 caractères').default(''),
|
||||
submitted_by_email: z
|
||||
.string()
|
||||
.email('Email invalide')
|
||||
.optional()
|
||||
.or(z.literal(''))
|
||||
.transform((v) => v || undefined),
|
||||
type_suggere: z.enum(TYPES_SUGGERES).optional().or(z.literal('')).transform((v) => (v ? v : undefined)),
|
||||
// Deuxième chip optionnelle (B5-M2b) — indécis entre deux types.
|
||||
type_secondaire: z.enum(TYPES_SUGGERES).optional().or(z.literal('')).transform((v) => (v ? v : undefined)),
|
||||
// Honeypot anti-spam : champ caché, doit rester vide pour un humain.
|
||||
site_web: z.string().optional().or(z.literal('')),
|
||||
})
|
||||
.refine((data) => data.liens.length > 0 || data.texte.trim().length > 0, {
|
||||
message: 'Ajoute au moins un lien ou quelques mots.',
|
||||
path: ['texte'],
|
||||
})
|
||||
.refine((data) => !data.type_secondaire || !!data.type_suggere, {
|
||||
message: 'Choisis d\'abord un type principal.',
|
||||
path: ['type_secondaire'],
|
||||
})
|
||||
.refine((data) => !data.type_secondaire || data.type_secondaire !== data.type_suggere, {
|
||||
message: 'Le second type doit être différent du premier.',
|
||||
path: ['type_secondaire'],
|
||||
})
|
||||
|
||||
export type LibreSubmitInput = z.infer<typeof LibreSubmitSchema>
|
||||
|
||||
/** Chip 'jobs'/'outils' → valeur `submission_type` en base (table orgas). */
|
||||
const TYPE_TO_SUBMISSION_TYPE: Record<Exclude<TypeSuggere, 'references'>, 'ecosysteme' | 'reseau' | 'job' | 'outil'> = {
|
||||
ecosysteme: 'ecosysteme',
|
||||
reseau: 'reseau',
|
||||
jobs: 'job',
|
||||
outils: 'outil',
|
||||
}
|
||||
|
||||
function hostnameOf(url: string): string | null {
|
||||
try {
|
||||
return new URL(url).hostname.replace(/^www\./, '')
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function nomSuggere(data: LibreSubmitInput): string {
|
||||
const premierLien = data.liens[0]
|
||||
const base = premierLien ? hostnameOf(premierLien) : null
|
||||
const fallback = data.texte.trim().slice(0, 60)
|
||||
return `[à qualifier] ${base || fallback || 'sans titre'}`
|
||||
}
|
||||
|
||||
/**
|
||||
* `prefixLine` est soit le marqueur worker « Type : non précisé » (aucun type choisi),
|
||||
* soit la ligne « Type suggéré : X ou Y » (double type) — jamais les deux à la fois,
|
||||
* et toujours en toute première position quand présent (contrat worker/enrich.js:562).
|
||||
*/
|
||||
function descriptionAvecLiens(texte: string, liens: string[], prefixLine?: string): string {
|
||||
const parts: string[] = []
|
||||
if (prefixLine) parts.push(prefixLine)
|
||||
if (texte.trim()) parts.push(texte.trim())
|
||||
if (liens.length) parts.push(`Liens :\n${liens.join('\n')}`)
|
||||
return parts.join('\n\n')
|
||||
}
|
||||
|
||||
function ligneTypeSuggere(data: LibreSubmitInput): string | undefined {
|
||||
if (!data.type_secondaire) return undefined
|
||||
// Le schéma garantit type_suggere défini dès que type_secondaire l'est.
|
||||
return `Type suggéré : ${TYPES_SUGGERES_LABELS[data.type_suggere!]} ou ${TYPES_SUGGERES_LABELS[data.type_secondaire]}`
|
||||
}
|
||||
|
||||
/** Mapping vers la table orgas existante (submission_type ecosysteme/reseau/job/outil). */
|
||||
export function toOrgaPayload(data: LibreSubmitInput) {
|
||||
const hasSecondaire = !!data.type_secondaire
|
||||
// Marqueur worker posé uniquement quand aucun type exploitable n'a été choisi du tout —
|
||||
// un double type ne le pose jamais (contrat worker/enrich.js:562).
|
||||
const typeNonPrecise = !hasSecondaire && (!data.type_suggere || data.type_suggere === 'references')
|
||||
const submissionType = data.type_suggere && data.type_suggere !== 'references'
|
||||
? TYPE_TO_SUBMISSION_TYPE[data.type_suggere]
|
||||
: 'ecosysteme'
|
||||
const prefixLine = typeNonPrecise ? 'Type : non précisé' : ligneTypeSuggere(data)
|
||||
|
||||
return {
|
||||
submission_type: submissionType,
|
||||
nom: nomSuggere(data),
|
||||
url: data.liens[0] || null,
|
||||
description_user: descriptionAvecLiens(data.texte, data.liens, prefixLine),
|
||||
submitted_by_email: data.submitted_by_email || null,
|
||||
moderation_status: 'pending' as const,
|
||||
ai_processed: false,
|
||||
submitted_at: new Date().toISOString(),
|
||||
scrape_status: data.liens[0] ? 'pending' : 'no_link',
|
||||
}
|
||||
}
|
||||
|
||||
/** Mapping vers la table ressources_references (chip « Références »). */
|
||||
export function toReferencePayload(data: LibreSubmitInput) {
|
||||
return {
|
||||
titre: nomSuggere(data),
|
||||
auteur: 'non précisé',
|
||||
url: data.liens[0] || null,
|
||||
description: descriptionAvecLiens(data.texte, data.liens, ligneTypeSuggere(data)),
|
||||
pertinence_rag: null,
|
||||
hashtags: null,
|
||||
submitted_by_email: data.submitted_by_email || null,
|
||||
moderation_status: 'pending' as const,
|
||||
submitted_at: new Date().toISOString(),
|
||||
}
|
||||
}
|
||||
@@ -1,234 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
// worker/daily-digest.js — Email récap quotidien nouvelles fiches AEP
|
||||
// Cron : 0 8 * * * (tous les jours à 8h)
|
||||
// Usage : node worker/daily-digest.js
|
||||
|
||||
import 'dotenv/config'
|
||||
|
||||
// ─── CONFIG DEPUIS .env ───────────────────────────────────────────────────────
|
||||
const NOCODB_URL = process.env.NOCODB_URL || 'http://localhost:8070';
|
||||
const NOCODB_TOKEN = process.env.NOCODB_TOKEN;
|
||||
const NOCODB_BASE = process.env.NOCODB_BASE;
|
||||
const NOCODB_TABLE_ORGAS = process.env.NOCODB_TABLE_ORGAS;
|
||||
const RESEND_API_KEY = process.env.RESEND_API_KEY;
|
||||
const RESEND_FROM = process.env.RESEND_FROM || 'AEP Digest <noreply@trans-former.fr>';
|
||||
const EMAIL_DEST = process.env.EMAIL_JULES || 'transformationsresilientes@gmail.com';
|
||||
const NOCODB_ADMIN_URL = process.env.NOCODB_ADMIN_URL || 'http://localhost:8070';
|
||||
|
||||
// ─── UTILITAIRES LOG ─────────────────────────────────────────────────────────
|
||||
function log(...args) {
|
||||
const ts = new Date().toISOString();
|
||||
console.log(`[${ts}]`, ...args);
|
||||
}
|
||||
|
||||
// ─── NOCODB — FETCH FICHES DERNIÈRES 24H ─────────────────────────────────────
|
||||
async function fetchNewFiches() {
|
||||
const since = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
|
||||
|
||||
// NocoDB ne supporte pas bien le filtre datetime sur CreatedAt — on récupère
|
||||
// les 200 dernières fiches triées par date décroissante et on filtre en JS
|
||||
// (même pattern que getBudgetMoisCourant dans enrich.js)
|
||||
const url = `${NOCODB_URL}/api/v1/db/data/noco/${NOCODB_BASE}/${NOCODB_TABLE_ORGAS}?limit=200&sort=-CreatedAt`;
|
||||
|
||||
const res = await fetch(url, {
|
||||
headers: { 'xc-token': NOCODB_TOKEN }
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`NocoDB GET fiches → ${res.status}: ${await res.text()}`);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
const rows = data.list || [];
|
||||
|
||||
// Filtre JS sur les 24 dernières heures
|
||||
const recent = rows.filter(row => {
|
||||
const created = new Date(row.CreatedAt || row.created_at || 0);
|
||||
return created >= new Date(since);
|
||||
});
|
||||
|
||||
return recent;
|
||||
}
|
||||
|
||||
// ─── CONSTRUCTION EMAIL HTML ─────────────────────────────────────────────────
|
||||
function buildEmailHtml(fiches) {
|
||||
const count = fiches.length;
|
||||
const date = new Date().toLocaleDateString('fr-FR', {
|
||||
weekday: 'long', day: 'numeric', month: 'long', year: 'numeric'
|
||||
});
|
||||
|
||||
const lignes = fiches.map(f => {
|
||||
const nom = f.nom || '(sans nom)';
|
||||
const url = f.url || null;
|
||||
const echelle = f.echelle || '—';
|
||||
const statut = f.moderation_status || 'pending';
|
||||
const ficheUrl = `https://aep.trans-former.fr/fiche/${f.Id}`;
|
||||
|
||||
const nomHtml = url
|
||||
? `<a href="${url}" style="color:#1a56db;text-decoration:none;">${escHtml(nom)}</a>`
|
||||
: escHtml(nom);
|
||||
|
||||
const statutColor = statut === 'approved' ? '#057a55'
|
||||
: statut === 'rejected' ? '#c81e1e'
|
||||
: statut === 'ai_processed' ? '#1a56db'
|
||||
: '#9ca3af'; // pending / autre
|
||||
|
||||
return `
|
||||
<tr style="border-bottom:1px solid #f3f4f6;">
|
||||
<td style="padding:10px 12px;font-size:14px;">${nomHtml}</td>
|
||||
<td style="padding:10px 12px;font-size:13px;color:#6b7280;">${escHtml(echelle)}</td>
|
||||
<td style="padding:10px 12px;">
|
||||
<span style="display:inline-block;padding:2px 8px;border-radius:4px;font-size:12px;
|
||||
font-weight:600;background:#f3f4f6;color:${statutColor};">
|
||||
${escHtml(statut)}
|
||||
</span>
|
||||
</td>
|
||||
<td style="padding:10px 12px;font-size:12px;">
|
||||
<a href="${ficheUrl}" style="color:#6b7280;">fiche #${f.Id}</a>
|
||||
</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="fr">
|
||||
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>
|
||||
<body style="margin:0;padding:0;background:#f9fafb;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;">
|
||||
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f9fafb;padding:32px 0;">
|
||||
<tr><td align="center">
|
||||
<table width="600" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:8px;overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,0.1);">
|
||||
|
||||
<!-- Header -->
|
||||
<tr>
|
||||
<td style="background:#1a56db;padding:24px 32px;">
|
||||
<p style="margin:0;font-size:12px;color:#bfdbfe;text-transform:uppercase;letter-spacing:1px;">AEP — Agences En Pratique</p>
|
||||
<h1 style="margin:4px 0 0;font-size:20px;color:#ffffff;font-weight:700;">
|
||||
${count} nouvelle${count > 1 ? 's' : ''} fiche${count > 1 ? 's' : ''} soumise${count > 1 ? 's' : ''}
|
||||
</h1>
|
||||
<p style="margin:4px 0 0;font-size:13px;color:#bfdbfe;">${date}</p>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<!-- Corps -->
|
||||
<tr>
|
||||
<td style="padding:24px 32px;">
|
||||
<p style="margin:0 0 16px;font-size:14px;color:#374151;">
|
||||
${count} fiche${count > 1 ? 's ont été soumises' : ' a été soumise'} dans les dernières 24 heures.
|
||||
</p>
|
||||
|
||||
<!-- Tableau fiches -->
|
||||
<table width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;border:1px solid #e5e7eb;border-radius:6px;overflow:hidden;">
|
||||
<thead>
|
||||
<tr style="background:#f9fafb;">
|
||||
<th style="padding:10px 12px;text-align:left;font-size:12px;font-weight:600;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;">Organisation</th>
|
||||
<th style="padding:10px 12px;text-align:left;font-size:12px;font-weight:600;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;">Échelle</th>
|
||||
<th style="padding:10px 12px;text-align:left;font-size:12px;font-weight:600;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;">Statut</th>
|
||||
<th style="padding:10px 12px;text-align:left;font-size:12px;font-weight:600;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;">Lien</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${lignes}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<!-- CTA modération -->
|
||||
<div style="margin-top:24px;text-align:center;">
|
||||
<a href="${NOCODB_ADMIN_URL}"
|
||||
style="display:inline-block;padding:10px 20px;background:#1a56db;color:#ffffff;
|
||||
border-radius:6px;font-size:14px;font-weight:600;text-decoration:none;">
|
||||
Ouvrir NocoDB pour modérer
|
||||
</a>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<!-- Footer -->
|
||||
<tr>
|
||||
<td style="padding:16px 32px;border-top:1px solid #f3f4f6;">
|
||||
<p style="margin:0;font-size:11px;color:#9ca3af;text-align:center;">
|
||||
Digest automatique AEP — envoyé chaque matin à 8h
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
</td></tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
// Échappement HTML minimal
|
||||
function escHtml(str) {
|
||||
return String(str ?? '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
// ─── ENVOI VIA RESEND ─────────────────────────────────────────────────────────
|
||||
async function sendDigest(fiches) {
|
||||
const count = fiches.length;
|
||||
const subject = `AEP — ${count} nouvelle${count > 1 ? 's' : ''} fiche${count > 1 ? 's' : ''} soumise${count > 1 ? 's' : ''}`;
|
||||
const html = buildEmailHtml(fiches);
|
||||
|
||||
const res = await fetch('https://api.resend.com/emails', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${RESEND_API_KEY}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
from: RESEND_FROM,
|
||||
to: [EMAIL_DEST],
|
||||
subject,
|
||||
html
|
||||
})
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.text();
|
||||
throw new Error(`Resend API ${res.status}: ${err}`);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
log(`Email digest envoyé → ${EMAIL_DEST} | id: ${data.id} | sujet: "${subject}"`);
|
||||
}
|
||||
|
||||
// ─── MAIN ─────────────────────────────────────────────────────────────────────
|
||||
async function run() {
|
||||
log('=== daily-digest démarré ===');
|
||||
|
||||
// Vérification variables obligatoires
|
||||
if (!NOCODB_TOKEN || !NOCODB_BASE || !NOCODB_TABLE_ORGAS) {
|
||||
log('ERREUR : Variables NocoDB manquantes (NOCODB_TOKEN, NOCODB_BASE, NOCODB_TABLE_ORGAS)');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!RESEND_API_KEY) {
|
||||
log('ERREUR : RESEND_API_KEY manquante');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
// Fetch fiches des 24 dernières heures
|
||||
const fiches = await fetchNewFiches();
|
||||
log(`${fiches.length} fiche(s) trouvée(s) dans les dernières 24h`);
|
||||
|
||||
if (fiches.length === 0) {
|
||||
log('Aucune nouvelle fiche — digest non envoyé.');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// Envoi email
|
||||
await sendDigest(fiches);
|
||||
log('=== daily-digest terminé avec succès ===');
|
||||
|
||||
} catch (e) {
|
||||
log('ERREUR daily-digest:', e.message);
|
||||
console.error(e.stack);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
run();
|
||||
+286
-184
@@ -1,14 +1,28 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* NAV V2 — Worker enrichissement IA
|
||||
* Lancé via systemd timer toutes les 5 minutes
|
||||
* Pipeline : fetch pending → scrape crawl4ai → Mistral Nemo → update NocoDB → log stats
|
||||
* AEP — Worker enrichissement IA (B5-M2)
|
||||
* Lancé via systemd timer toutes les 15 minutes (deploy/aep-worker/aep-worker.timer)
|
||||
* Pipeline : fetch pending → scrape léger (fetch natif) → Bifrost (LLM) → update NocoDB → ntfy
|
||||
*
|
||||
* Écarts à la version NAV V2 d'origine (PIPE-IA-DOC.md, fusionné pas réécrit) :
|
||||
* - LLM : Bifrost (passerelle OpenAI-compatible en prod) au lieu de Mistral direct.
|
||||
* - Scrape : fetch natif Node 22 (timeout 8s, 500 Ko max, texte tronqué 4000 car.)
|
||||
* au lieu de crawl4ai/Python (disque VPS tendu, décision MOE 27/09).
|
||||
* - Notification : ntfy (https://ntfy.sh/$NTFY_TOPIC) au lieu de Resend (abandonné 15/07).
|
||||
* Le message ne contient JAMAIS l'email ni le texte libre du contributeur.
|
||||
* - Le formulaire assoupli (B5-M1) écrit un `nom` placeholder ("[à qualifier] host") et
|
||||
* éventuellement "Type : non précisé" en tête de description_user. Le worker propose un
|
||||
* vrai nom et un type — voir §Sortie JSON ci-dessous et PIPE-IA-DOC.md.
|
||||
* - Seuil « email à 5 fiches pending » PAS réactivé (décision MOE : volume faible, une
|
||||
* notif par fiche traitée suffit — cf. B5-proposer-pipe.md §Points d'attention).
|
||||
*/
|
||||
|
||||
import { spawnSync, execSync } from 'child_process';
|
||||
import { existsSync, writeFileSync, unlinkSync } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import { join } from 'path';
|
||||
import { existsSync, writeFileSync, unlinkSync, readFileSync, mkdirSync } from 'fs';
|
||||
import { dirname, join } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
// ─── CONFIG DEPUIS .env ───────────────────────────────────────────────────────
|
||||
const NOCODB_URL = process.env.NOCODB_URL || 'http://localhost:8070';
|
||||
@@ -16,25 +30,44 @@ const NOCODB_TOKEN = process.env.NOCODB_TOKEN;
|
||||
const NOCODB_BASE = process.env.NOCODB_BASE;
|
||||
const NOCODB_TABLE_ORGAS = process.env.NOCODB_TABLE_ORGAS;
|
||||
const NOCODB_TABLE_STATS = process.env.NOCODB_TABLE_STATS;
|
||||
const MISTRAL_API_KEY = process.env.MISTRAL_API_KEY;
|
||||
const RESEND_API_KEY = process.env.RESEND_API_KEY;
|
||||
const RESEND_FROM = process.env.RESEND_FROM || 'contact@trans-former.fr';
|
||||
const EMAIL_JULES = process.env.EMAIL_JULES || 'jules@trans-former.fr';
|
||||
|
||||
const BIFROST_URL = process.env.BIFROST_URL || 'http://127.0.0.1:8080';
|
||||
const BIFROST_VK = process.env.BIFROST_VK;
|
||||
const WORKER_MODEL = process.env.WORKER_MODEL || 'groq/openai/gpt-oss-20b'; // llama-3.1-8b-instant retiré par Groq (28/09)
|
||||
|
||||
const NTFY_TOPIC = process.env.NTFY_TOPIC;
|
||||
|
||||
const BUDGET_MAX_EUR = parseFloat(process.env.BUDGET_MAX_EUR || '20');
|
||||
const WORKER_LIMIT = parseInt(process.env.WORKER_LIMIT || '5');
|
||||
const LOCK_FILE = '/tmp/nav-worker.lock';
|
||||
const LOCK_FILE = process.env.WORKER_LOCK_FILE || '/tmp/aep-worker.lock';
|
||||
|
||||
// ─── PRIX MISTRAL NEMO (USD → EUR) ───────────────────────────────────────────
|
||||
const NEMO_PRICE_IN = 0.02 / 1_000_000; // $0.02 / 1M tokens input
|
||||
const NEMO_PRICE_OUT = 0.04 / 1_000_000; // $0.04 / 1M tokens output
|
||||
// Prix par 1M tokens (USD) — par défaut 0 (Groq gratuit dans le tier RAPIDE Bifrost).
|
||||
// Réglable si le worker bascule un jour sur un modèle payant.
|
||||
const WORKER_PRICE_IN = parseFloat(process.env.WORKER_PRICE_IN_USD_PER_M || '0') / 1_000_000;
|
||||
const WORKER_PRICE_OUT = parseFloat(process.env.WORKER_PRICE_OUT_USD_PER_M || '0') / 1_000_000;
|
||||
const USD_TO_EUR = 0.93;
|
||||
|
||||
// Scrape léger
|
||||
const SCRAPE_TIMEOUT_MS = 8_000;
|
||||
const SCRAPE_MAX_BYTES = 500_000;
|
||||
const SCRAPE_TEXT_MAX_CHARS = 4_000;
|
||||
const SCRAPE_USER_AGENT = 'AEP/2.0 contact@trans-former.fr';
|
||||
|
||||
// ─── CLI ──────────────────────────────────────────────────────────────────────
|
||||
const DRY_RUN = process.argv.includes('--dry-run');
|
||||
// DRY_RUN_LIVE=1 : en dry-run, tente quand même de vrais appels réseau (scrape + Bifrost)
|
||||
// pour un test manuel avec accès réseau — ne touche JAMAIS NocoDB en dry-run, dans tous les cas.
|
||||
const DRY_RUN_LIVE = process.env.DRY_RUN_LIVE === '1';
|
||||
const DRY_RUN_FIXTURE = process.env.DRY_RUN_FIXTURE || join(__dirname, 'fixtures', 'dry-run-rows.json');
|
||||
|
||||
// ─── TAXONOMIE VALIDE (apostrophe typographique U+2019 comme NocoDB) ─────────
|
||||
const VALID_FONCTIONS = [
|
||||
'Juridique', 'Technique', 'Économique', 'Administratif', 'Chantier',
|
||||
'Comptabilité', 'Développement', 'Formation', 'Gestion d\u2019agence', 'Santé mentale'
|
||||
'Comptabilité', 'Développement', 'Formation', 'Gestion d’agence', 'Santé mentale'
|
||||
];
|
||||
|
||||
const VALID_SUBMISSION_TYPES = ['ecosysteme', 'reseau', 'job', 'outil'];
|
||||
|
||||
// ─── MAPPING NORMALISATION TAGS ───────────────────────────────────────────────
|
||||
const TAG_MAP = [
|
||||
[['juridique', 'droit', 'litige', 'contrat', 'déontologie', 'décennale', 'médiation', 'pi ', 'propriété intellectuelle', 'ccag', 'marchés publics droit'], 'Juridique'],
|
||||
@@ -45,16 +78,14 @@ const TAG_MAP = [
|
||||
[['comptabilité', 'fiscal', 'tva', 'bnc', 'bic', 'expert-comptable', 'bilan', 'trésorerie', 'transmission agence', 'création agence', 'micro'], 'Comptabilité'],
|
||||
[['développement', 'prospection', 'commercial', 'client', 'réseau', 'candidature', 'consultation', 'acquisition', 'marketing', 'notoriété', 'ao '], 'Développement'],
|
||||
[['formation', 'école', 'mooc', 'organisme', 'formation continue', 'cpf', 'dpc', 'cfaa'], 'Formation'],
|
||||
[['gestion d\u2019agence', 'gestion d\'agence', 'rh', 'recrutement', 'emploi', 'salaire', 'ccn', 'convention collective', 'idcc', 'temps de travail', 'management'], 'Gestion d\u2019agence'],
|
||||
[['gestion d’agence', 'gestion d\'agence', 'rh', 'recrutement', 'emploi', 'salaire', 'ccn', 'convention collective', 'idcc', 'temps de travail', 'management'], 'Gestion d’agence'],
|
||||
[['santé mentale', 'burn-out', 'épuisement', 'souffrance', 'bien-être', 'harcèlement', 'stress', 'psychologique', 'équilibre'], 'Santé mentale'],
|
||||
];
|
||||
|
||||
function normalizeTag(raw) {
|
||||
const t = raw.toLowerCase().trim();
|
||||
// D'abord chercher correspondance exacte dans les valeurs valides
|
||||
const t = String(raw).toLowerCase().trim();
|
||||
const exact = VALID_FONCTIONS.find(v => v.toLowerCase() === t);
|
||||
if (exact) return exact;
|
||||
// Sinon chercher par mots-clés
|
||||
for (const [patterns, normalized] of TAG_MAP) {
|
||||
if (patterns.some(p => t.includes(p))) return normalized;
|
||||
}
|
||||
@@ -117,8 +148,18 @@ async function nocodbPost(tableId, data) {
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/** Écrit une mise à jour de fiche — no-op loggé en dry-run (jamais de PATCH réel). */
|
||||
async function patchRow(rowId, data) {
|
||||
if (DRY_RUN) {
|
||||
log(`[dry-run] PATCH fiche ${rowId} :`, JSON.stringify(data));
|
||||
return;
|
||||
}
|
||||
return nocodbPatch(NOCODB_TABLE_ORGAS, rowId, data);
|
||||
}
|
||||
|
||||
// ─── BUDGET CIRCUIT BREAKER ──────────────────────────────────────────────────
|
||||
async function getBudgetMoisCourant() {
|
||||
if (DRY_RUN) return 0;
|
||||
const now = new Date();
|
||||
const year = now.getFullYear();
|
||||
const month = now.getMonth(); // 0-indexed
|
||||
@@ -142,7 +183,12 @@ async function getBudgetMoisCourant() {
|
||||
async function logUsage(usage, model, endpoint, orgaId) {
|
||||
const tokensIn = usage?.prompt_tokens || 0;
|
||||
const tokensOut = usage?.completion_tokens || 0;
|
||||
const coutEur = ((tokensIn * NEMO_PRICE_IN) + (tokensOut * NEMO_PRICE_OUT)) * USD_TO_EUR;
|
||||
const coutEur = ((tokensIn * WORKER_PRICE_IN) + (tokensOut * WORKER_PRICE_OUT)) * USD_TO_EUR;
|
||||
|
||||
if (DRY_RUN) {
|
||||
log(`[dry-run] Usage (non loggé) : ${tokensIn}in + ${tokensOut}out = €${coutEur.toFixed(6)} (${model})`);
|
||||
return coutEur;
|
||||
}
|
||||
|
||||
await nocodbPost(NOCODB_TABLE_STATS, {
|
||||
model,
|
||||
@@ -166,111 +212,168 @@ async function fetchPendingRows() {
|
||||
return data.list || [];
|
||||
}
|
||||
|
||||
// ─── SCRAPING CRAWL4AI (mode HTTP statique, sans Playwright) ─────────────────
|
||||
async function scrapeWithCrawl4ai(url) {
|
||||
log(`Scraping: ${url}`);
|
||||
function loadFixtureRows() {
|
||||
if (!existsSync(DRY_RUN_FIXTURE)) {
|
||||
throw new Error(`Fixture dry-run introuvable : ${DRY_RUN_FIXTURE}`);
|
||||
}
|
||||
const raw = JSON.parse(readFileSync(DRY_RUN_FIXTURE, 'utf-8'));
|
||||
return Array.isArray(raw) ? raw : [raw];
|
||||
}
|
||||
|
||||
// Script Python temporaire pour crawl4ai
|
||||
const urlSafe = url.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
|
||||
const script = `
|
||||
import asyncio, sys
|
||||
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig
|
||||
from crawl4ai.async_crawler_strategy import AsyncHTTPCrawlerStrategy
|
||||
|
||||
async def scrape():
|
||||
strategy = AsyncHTTPCrawlerStrategy()
|
||||
run_cfg = CrawlerRunConfig(
|
||||
word_count_threshold=20,
|
||||
excluded_tags=['nav', 'footer', 'script', 'style', 'head'],
|
||||
remove_overlay_elements=True
|
||||
)
|
||||
async with AsyncWebCrawler(crawler_strategy=strategy, verbose=False) as crawler:
|
||||
result = await crawler.arun(url='${urlSafe}', config=run_cfg)
|
||||
if result.success and result.markdown:
|
||||
content = result.markdown[:16000]
|
||||
sys.stdout.buffer.write(content.encode('utf-8'))
|
||||
else:
|
||||
sys.stderr.write(f"Scrape failed: success={result.success}\\n")
|
||||
sys.exit(1)
|
||||
|
||||
asyncio.run(scrape())
|
||||
`;
|
||||
|
||||
const scriptPath = join(tmpdir(), `nav-scrape-${Date.now()}.py`);
|
||||
writeFileSync(scriptPath, script, 'utf-8');
|
||||
// ─── LIENS — extraits de url + description_user (format B5-M1 "Liens :\n...") ─
|
||||
function extractLinks(row) {
|
||||
const text = `${row.url || ''}\n${row.description_user || row.description || ''}`;
|
||||
const matches = text.match(/https?:\/\/[^\s)"'<>]+/g) || [];
|
||||
const cleaned = matches.map(u => u.replace(/[.,;:!?]+$/, ''));
|
||||
return [...new Set(cleaned)];
|
||||
}
|
||||
|
||||
// ─── SCRAPE LÉGER (fetch natif, pas de crawl4ai) ─────────────────────────────
|
||||
async function fetchCapped(url) {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), SCRAPE_TIMEOUT_MS);
|
||||
try {
|
||||
const result = spawnSync('python3', [scriptPath], {
|
||||
timeout: 180_000,
|
||||
maxBuffer: 20 * 1024 * 1024,
|
||||
env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1', PYTHONIOENCODING: 'utf-8' }
|
||||
const res = await fetch(url, {
|
||||
signal: controller.signal,
|
||||
redirect: 'follow',
|
||||
headers: { 'User-Agent': SCRAPE_USER_AGENT },
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
|
||||
if (result.error) throw result.error;
|
||||
const reader = res.body?.getReader();
|
||||
if (!reader) return await res.text();
|
||||
|
||||
const stdout = result.stdout?.toString('utf-8') || '';
|
||||
const stderr = result.stderr?.toString('utf-8') || '';
|
||||
|
||||
if (result.status === 0 && stdout.length > 50) {
|
||||
log(`Scrape OK: ${stdout.length} chars`);
|
||||
return stdout.trim();
|
||||
} else {
|
||||
throw new Error(`Scrape failed (code ${result.status}): ${stderr.slice(0, 300)}`);
|
||||
const chunks = [];
|
||||
let total = 0;
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
chunks.push(value);
|
||||
total += value.length;
|
||||
if (total >= SCRAPE_MAX_BYTES) {
|
||||
await reader.cancel().catch(() => {});
|
||||
break;
|
||||
}
|
||||
}
|
||||
const buf = Buffer.concat(chunks.map(c => Buffer.from(c)));
|
||||
return buf.subarray(0, SCRAPE_MAX_BYTES).toString('utf-8');
|
||||
} finally {
|
||||
try { unlinkSync(scriptPath); } catch {}
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── APPEL MISTRAL NEMO ───────────────────────────────────────────────────────
|
||||
const SYSTEM_PROMPT = `Tu es un assistant spécialisé dans l'écosystème professionnel de l'architecture en France. Tu reçois des informations sur une organisation ou ressource liée au secteur de l'architecture, et tu dois les enrichir pour alimenter une cartographie collaborative.
|
||||
function extractMeta(html, key) {
|
||||
const re1 = new RegExp(`<meta[^>]*(?:name|property)=["']${key}["'][^>]*content=["']([^"']*)["']`, 'i');
|
||||
const re2 = new RegExp(`<meta[^>]*content=["']([^"']*)["'][^>]*(?:name|property)=["']${key}["']`, 'i');
|
||||
return (html.match(re1) || html.match(re2))?.[1]?.trim() || null;
|
||||
}
|
||||
|
||||
function extractOgTags(html) {
|
||||
const og = {};
|
||||
const re1 = /<meta[^>]*property=["']og:([a-zA-Z:_-]+)["'][^>]*content=["']([^"']*)["']/gi;
|
||||
const re2 = /<meta[^>]*content=["']([^"']*)["'][^>]*property=["']og:([a-zA-Z:_-]+)["']/gi;
|
||||
let m;
|
||||
while ((m = re1.exec(html))) og[m[1]] = m[2];
|
||||
while ((m = re2.exec(html))) if (!(m[2] in og)) og[m[2]] = m[1];
|
||||
return og;
|
||||
}
|
||||
|
||||
function decodeEntities(s) {
|
||||
return s
|
||||
.replace(/ /g, ' ')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/�?39;/g, "'");
|
||||
}
|
||||
|
||||
function extractVisibleText(html) {
|
||||
let s = html
|
||||
.replace(/<!--[\s\S]*?-->/g, ' ')
|
||||
.replace(/<script[\s\S]*?<\/script>/gi, ' ')
|
||||
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
|
||||
.replace(/<nav[\s\S]*?<\/nav>/gi, ' ')
|
||||
.replace(/<footer[\s\S]*?<\/footer>/gi, ' ')
|
||||
.replace(/<head[\s\S]*?<\/head>/gi, ' ');
|
||||
s = s.replace(/<[^>]+>/g, ' ');
|
||||
s = decodeEntities(s);
|
||||
s = s.replace(/\s+/g, ' ').trim();
|
||||
return s.slice(0, SCRAPE_TEXT_MAX_CHARS);
|
||||
}
|
||||
|
||||
function extractTitle(html) {
|
||||
return html.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1]?.trim() || null;
|
||||
}
|
||||
|
||||
async function scrapeLight(url) {
|
||||
log(`Scraping léger: ${url}`);
|
||||
const html = await fetchCapped(url);
|
||||
return {
|
||||
title: extractTitle(html),
|
||||
metaDescription: extractMeta(html, 'description'),
|
||||
og: extractOgTags(html),
|
||||
text: extractVisibleText(html),
|
||||
};
|
||||
}
|
||||
|
||||
const MOCK_SCRAPE_RESULT = {
|
||||
title: '[mock dry-run] Titre de la page',
|
||||
metaDescription: '[mock dry-run] Meta description factice, aucun réseau contacté.',
|
||||
og: { site_name: '[mock dry-run]' },
|
||||
text: '[mock dry-run] Extrait de texte factice utilisé quand DRY_RUN_LIVE n’est pas activé.',
|
||||
};
|
||||
|
||||
// ─── APPEL LLM VIA BIFROST ────────────────────────────────────────────────────
|
||||
const SYSTEM_PROMPT = `Tu es un assistant qui aide à qualifier des ressources soumises pour une cartographie collaborative de l'écosystème professionnel de l'architecture en France (AEP).
|
||||
|
||||
RÈGLES ABSOLUES :
|
||||
1. Tu ne dois JAMAIS inventer d'informations non présentes dans les sources fournies.
|
||||
2. Si une information est absente ou incertaine, retourne \`null\` pour ce champ.
|
||||
3. Tu dois retourner UNIQUEMENT un objet JSON valide, sans texte avant ou après.
|
||||
4. La description_enrichie doit être neutre, factuelle, en français, sans jugement de valeur.
|
||||
5. Les points_cles sont des phrases courtes (max 12 mots chacune), actionnables pour un architecte.
|
||||
6. Pour les tags_fonction, ne propose que des valeurs parmi la liste autorisée.
|
||||
4. "description" : neutre, factuelle, en français, max 300 caractères, sans jugement de valeur.
|
||||
5. "nom" : un nom de fiche court et identifiable, sans le préfixe "[à qualifier]".
|
||||
6. "tags" : 1 à 5 valeurs, uniquement parmi la liste autorisée.
|
||||
|
||||
TAXONOMIE AUTORISÉE :
|
||||
- Échelle (une seule valeur) : "National" | "Régional" | "Départemental" | "Local"
|
||||
- Territoire (une seule valeur) : "Métropole" | "Guadeloupe" | "Martinique" | "Guyane" | "Réunion" | "Mayotte" | null
|
||||
- Tags fonction (1 à 5 valeurs) : "Juridique" | "Technique" | "Économique" | "Administratif" | "Chantier" | "Comptabilité" | "Développement" | "Formation" | "Gestion d\u2019agence" | "Santé mentale"
|
||||
TAGS AUTORISÉS : "Juridique" | "Technique" | "Économique" | "Administratif" | "Chantier" | "Comptabilité" | "Développement" | "Formation" | "Gestion d’agence" | "Santé mentale"
|
||||
TYPE_SUGGERE AUTORISÉ (une seule valeur ou null) : "ecosysteme" | "reseau" | "job" | "outil"
|
||||
|
||||
FORMAT DE SORTIE JSON :
|
||||
{
|
||||
"description_enrichie": "string (max 300 chars, français, neutre, factuel)",
|
||||
"points_cles": ["string", "string", "string"],
|
||||
"tags_fonction": ["Valeur1", "Valeur2"],
|
||||
"echelle": "National" | "Régional" | "Départemental" | "Local" | null,
|
||||
"territoire": "Métropole" | ... | null,
|
||||
"localisation_ville": "string" | null,
|
||||
"nom": "string | null",
|
||||
"description": "string (max 300 chars, français, neutre, factuel) | null",
|
||||
"type_suggere": "ecosysteme" | "reseau" | "job" | "outil" | null,
|
||||
"ville": "string | null",
|
||||
"tags": ["string", "..."],
|
||||
"confiance": "haute" | "moyenne" | "faible"
|
||||
}
|
||||
|
||||
Le champ "confiance" reflète ta certitude globale sur l'enrichissement :
|
||||
- "haute" : URL scrapée avec contenu riche, informations claires
|
||||
- "moyenne" : URL scrapée mais contenu partiel, ou description_user seule suffisante
|
||||
- "faible" : URL non disponible et description_user vague, inférences importantes`;
|
||||
Le champ "confiance" reflète ta certitude globale :
|
||||
- "haute" : contenu scrapé riche, informations claires.
|
||||
- "moyenne" : contenu partiel, ou texte du contributeur seul mais clair.
|
||||
- "faible" : aucun contenu scrapé et texte du contributeur vague, inférences importantes.`;
|
||||
|
||||
function buildUserPrompt(row, scrapeContent) {
|
||||
return `ORGANISATION À ENRICHIR :
|
||||
function buildUserPrompt(row, scrapeData, autresLiens) {
|
||||
return `RESSOURCE À QUALIFIER :
|
||||
|
||||
Nom : ${row.nom}
|
||||
URL : ${row.url || 'non fournie'}
|
||||
Description soumise par l'utilisateur : ${row.description_user || row.description || 'non fournie'}
|
||||
Nom actuel (placeholder à remplacer) : ${row.nom}
|
||||
Lien principal : ${row.url || 'non fourni'}
|
||||
${autresLiens.length ? `Autres liens mentionnés par le contributeur : ${autresLiens.join(', ')}` : ''}
|
||||
Texte du contributeur (pourquoi c'est pertinent pour lui) : ${row.description_user || row.description || 'non fourni'}
|
||||
|
||||
CONTENU DU SITE WEB (extrait par scraping) :
|
||||
${scrapeContent || 'Site non accessible ou URL non fournie.'}
|
||||
CONTENU EXTRAIT DU SITE (scraping léger) :
|
||||
Titre : ${scrapeData?.title || 'non disponible'}
|
||||
Meta description : ${scrapeData?.metaDescription || 'non disponible'}
|
||||
Open Graph : ${scrapeData && Object.keys(scrapeData.og || {}).length ? JSON.stringify(scrapeData.og) : 'non disponible'}
|
||||
Texte visible (extrait) : ${scrapeData?.text || 'Site non accessible ou lien non fourni.'}
|
||||
|
||||
---
|
||||
|
||||
Enrichis cette fiche selon les règles du system prompt. Retourne uniquement le JSON.`;
|
||||
Qualifie cette ressource selon les règles du system prompt. Retourne uniquement le JSON.`;
|
||||
}
|
||||
|
||||
async function callMistralWithRetry(row, scrapeContent, maxRetries = 2) {
|
||||
const userPrompt = buildUserPrompt(row, scrapeContent);
|
||||
async function callBifrostWithRetry(row, scrapeData, autresLiens, maxRetries = 2) {
|
||||
const userPrompt = buildUserPrompt(row, scrapeData, autresLiens);
|
||||
|
||||
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
||||
if (attempt > 0) {
|
||||
@@ -279,14 +382,14 @@ async function callMistralWithRetry(row, scrapeContent, maxRetries = 2) {
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch('https://api.mistral.ai/v1/chat/completions', {
|
||||
const res = await fetch(`${BIFROST_URL}/v1/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${MISTRAL_API_KEY}`,
|
||||
'x-bf-vk': BIFROST_VK,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: 'open-mistral-nemo',
|
||||
model: WORKER_MODEL,
|
||||
temperature: 0.2,
|
||||
max_tokens: 800,
|
||||
response_format: { type: 'json_object' },
|
||||
@@ -300,101 +403,88 @@ async function callMistralWithRetry(row, scrapeContent, maxRetries = 2) {
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.text();
|
||||
throw new Error(`Mistral API ${res.status}: ${err}`);
|
||||
throw new Error(`Bifrost API ${res.status}: ${err}`);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
const content = data.choices?.[0]?.message?.content;
|
||||
if (!content) throw new Error('Réponse Mistral vide');
|
||||
if (!content) throw new Error('Réponse Bifrost vide');
|
||||
|
||||
const parsed = JSON.parse(content);
|
||||
// Attacher usage pour logging
|
||||
parsed._usage = data.usage;
|
||||
parsed._raw = content;
|
||||
return parsed;
|
||||
|
||||
} catch (e) {
|
||||
log(`Erreur Mistral (tentative ${attempt + 1}): ${e.message}`);
|
||||
log(`Erreur Bifrost (tentative ${attempt + 1}): ${e.message}`);
|
||||
if (attempt === maxRetries) return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ─── EMAIL JULES VIA RESEND ───────────────────────────────────────────────────
|
||||
async function sendEmailJules(subject, body) {
|
||||
if (!RESEND_API_KEY) {
|
||||
log('RESEND_API_KEY absent, email skippé');
|
||||
const MOCK_BIFROST_RESULT = {
|
||||
nom: '[mock dry-run] Nom suggéré',
|
||||
description: '[mock dry-run] Description factice générée sans appel réseau.',
|
||||
type_suggere: 'ecosysteme',
|
||||
ville: null,
|
||||
tags: ['Développement'],
|
||||
confiance: 'faible',
|
||||
_usage: { prompt_tokens: 0, completion_tokens: 0 },
|
||||
_raw: '{"mock":"dry-run"}',
|
||||
};
|
||||
|
||||
// ─── NOTIFICATION NTFY (jamais l'email ni le texte du contributeur) ──────────
|
||||
async function notifyNtfy(title, message) {
|
||||
if (DRY_RUN) {
|
||||
log(`[dry-run] ntfy (non envoyé) — ${title} :`, message.replace(/\n/g, ' | '));
|
||||
return;
|
||||
}
|
||||
if (!NTFY_TOPIC) {
|
||||
log('NTFY_TOPIC absent, notification skippée');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await fetch('https://api.resend.com/emails', {
|
||||
const res = await fetch(`https://ntfy.sh/${NTFY_TOPIC}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${RESEND_API_KEY}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
from: RESEND_FROM,
|
||||
to: [EMAIL_JULES],
|
||||
subject,
|
||||
text: body
|
||||
})
|
||||
headers: { Title: title, Priority: '3', Tags: 'inbox_tray' },
|
||||
body: message,
|
||||
});
|
||||
if (!res.ok) log('Email error:', await res.text());
|
||||
else log('Email envoyé à Jules:', subject);
|
||||
if (!res.ok) log('ntfy erreur:', await res.text());
|
||||
else log('ntfy envoyé:', title);
|
||||
} catch (e) {
|
||||
log('Email exception:', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── VÉRIFICATION SEUIL 5 FICHES PENDING MODÉRATION ─────────────────────────
|
||||
async function checkModerationQueue() {
|
||||
const data = await nocodbGet(
|
||||
`${NOCODB_TABLE_ORGAS}?where=(moderation_status,eq,ai_processed)&limit=100`
|
||||
);
|
||||
const count = data.pageInfo?.totalRows || 0;
|
||||
if (count >= 5) {
|
||||
log(`Seuil modération atteint: ${count} fiches en attente`);
|
||||
await sendEmailJules(
|
||||
`NAV — ${count} fiches à modérer`,
|
||||
`Bonjour Jules,\n\n${count} fiches ont été enrichies par l'IA et attendent ta validation dans NocoDB.\n\nLien NocoDB : http://localhost:8070\nFiltre : moderation_status = ai_processed\n\nBonne modération !`
|
||||
);
|
||||
log('ntfy exception:', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── MAIN ─────────────────────────────────────────────────────────────────────
|
||||
async function run() {
|
||||
if (!acquireLock()) {
|
||||
if (!DRY_RUN && !acquireLock()) {
|
||||
log('Worker déjà en cours, skip');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
log('=== Worker NAV enrichissement démarré ===');
|
||||
log(`=== Worker AEP enrichissement démarré${DRY_RUN ? ' (--dry-run)' : ''} ===`);
|
||||
|
||||
try {
|
||||
// Vérification clés obligatoires
|
||||
if (!NOCODB_TOKEN || !NOCODB_BASE || !NOCODB_TABLE_ORGAS || !MISTRAL_API_KEY) {
|
||||
throw new Error('Variables .env manquantes (NOCODB_TOKEN, NOCODB_BASE, NOCODB_TABLE_ORGAS, MISTRAL_API_KEY)');
|
||||
if (!DRY_RUN) {
|
||||
if (!NOCODB_TOKEN || !NOCODB_BASE || !NOCODB_TABLE_ORGAS || !BIFROST_VK) {
|
||||
throw new Error('Variables .env manquantes (NOCODB_TOKEN, NOCODB_BASE, NOCODB_TABLE_ORGAS, BIFROST_VK)');
|
||||
}
|
||||
}
|
||||
|
||||
// Check budget global
|
||||
const budgetMois = await getBudgetMoisCourant();
|
||||
log(`Budget mois courant: €${budgetMois.toFixed(4)} / €${BUDGET_MAX_EUR}`);
|
||||
|
||||
if (budgetMois >= BUDGET_MAX_EUR) {
|
||||
log('Budget épuisé pour ce mois. Worker en pause.');
|
||||
await sendEmailJules(
|
||||
'NAV — Budget IA épuisé ce mois',
|
||||
`Le budget IA de ${BUDGET_MAX_EUR}€ a été atteint. Le worker est en pause jusqu'au 1er du mois prochain.\n\nConsommation actuelle : €${budgetMois.toFixed(4)}`
|
||||
);
|
||||
await notifyNtfy('[AEP] Budget IA épuisé', `Le budget de ${BUDGET_MAX_EUR}€ a été atteint. Worker en pause jusqu'au 1er du mois prochain.`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch fiches pending
|
||||
const rows = await fetchPendingRows();
|
||||
log(`${rows.length} fiche(s) à traiter`);
|
||||
const rows = DRY_RUN ? loadFixtureRows() : await fetchPendingRows();
|
||||
log(`${rows.length} fiche(s) à traiter${DRY_RUN ? ' (fixture)' : ''}`);
|
||||
|
||||
if (rows.length === 0) {
|
||||
log('Rien à traiter.');
|
||||
@@ -407,71 +497,86 @@ async function run() {
|
||||
const rowStart = Date.now();
|
||||
log(`--- Traitement fiche ${row.Id}: ${row.nom} ---`);
|
||||
|
||||
// Re-check budget avant chaque fiche
|
||||
const budgetCheck = await getBudgetMoisCourant();
|
||||
if (budgetCheck >= BUDGET_MAX_EUR) {
|
||||
log('Budget atteint mid-pipeline, arrêt.');
|
||||
break;
|
||||
}
|
||||
|
||||
// Scraping
|
||||
let scrapeContent = null;
|
||||
const hasUrl = row.url && row.url.trim().length > 0;
|
||||
const shouldScrape = hasUrl && (row.scrape_status === 'pending' || !row.scrape_status);
|
||||
const liens = extractLinks(row);
|
||||
const primaryUrl = row.url && row.url.trim() ? row.url.trim() : null;
|
||||
const autresLiens = liens.filter(l => l !== primaryUrl);
|
||||
|
||||
// Scraping (uniquement le lien principal — un seul champ scrape_content en base)
|
||||
let scrapeData = null;
|
||||
const shouldScrape = primaryUrl && (row.scrape_status === 'pending' || !row.scrape_status);
|
||||
const useNetwork = !DRY_RUN || DRY_RUN_LIVE;
|
||||
|
||||
if (shouldScrape) {
|
||||
try {
|
||||
scrapeContent = await scrapeWithCrawl4ai(row.url);
|
||||
await nocodbPatch(NOCODB_TABLE_ORGAS, row.Id, {
|
||||
scrapeData = useNetwork ? await scrapeLight(primaryUrl) : MOCK_SCRAPE_RESULT;
|
||||
await patchRow(row.Id, {
|
||||
scrape_status: 'scraped',
|
||||
scrape_content: scrapeContent
|
||||
scrape_content: JSON.stringify(scrapeData),
|
||||
});
|
||||
} catch (e) {
|
||||
log(`Scrape échoué: ${e.message}`);
|
||||
await nocodbPatch(NOCODB_TABLE_ORGAS, row.Id, { scrape_status: 'failed' });
|
||||
// Continue avec l'IA sans contenu scrape
|
||||
await patchRow(row.Id, { scrape_status: 'failed' });
|
||||
}
|
||||
} else if (!hasUrl) {
|
||||
await nocodbPatch(NOCODB_TABLE_ORGAS, row.Id, { scrape_status: 'no_link' });
|
||||
} else if (!primaryUrl) {
|
||||
await patchRow(row.Id, { scrape_status: 'no_link' });
|
||||
}
|
||||
|
||||
// Appel Mistral Nemo
|
||||
const enriched = await callMistralWithRetry(row, scrapeContent);
|
||||
// Appel LLM (Bifrost)
|
||||
const enriched = useNetwork
|
||||
? await callBifrostWithRetry(row, scrapeData, autresLiens)
|
||||
: MOCK_BIFROST_RESULT;
|
||||
|
||||
if (!enriched) {
|
||||
log(`Échec Mistral sur fiche ${row.Id}, flag ai_error`);
|
||||
await nocodbPatch(NOCODB_TABLE_ORGAS, row.Id, {
|
||||
moderation_status: 'ai_error',
|
||||
ai_processed: true
|
||||
});
|
||||
log(`Échec Bifrost sur fiche ${row.Id}, flag ai_error`);
|
||||
await patchRow(row.Id, { moderation_status: 'ai_error', ai_processed: true });
|
||||
continue;
|
||||
}
|
||||
|
||||
// Normalisation tags
|
||||
const rawTags = enriched.tags_fonction || [];
|
||||
const rawTags = enriched.tags || enriched.tags_fonction || [];
|
||||
const normalizedTags = [...new Set(rawTags.map(normalizeTag).filter(Boolean))];
|
||||
|
||||
// Update NocoDB
|
||||
const updateData = {
|
||||
description_enrichie: enriched.description_enrichie || null,
|
||||
points_cles: enriched.points_cles ? JSON.stringify(enriched.points_cles) : null,
|
||||
description_enrichie: enriched.description || null,
|
||||
tags_fonction: normalizedTags.join(','),
|
||||
moderation_status: 'ai_processed',
|
||||
ai_processed: true,
|
||||
ai_raw_output: JSON.stringify({ output: enriched, confiance: enriched.confiance })
|
||||
ai_raw_output: JSON.stringify({ output: enriched, confiance: enriched.confiance }),
|
||||
};
|
||||
|
||||
// Conserver echelle/territoire/localisation si l'IA les a enrichis
|
||||
if (enriched.echelle && !row.echelle) updateData.echelle = enriched.echelle;
|
||||
if (enriched.territoire && !row.territoire) updateData.territoire = enriched.territoire;
|
||||
if (enriched.localisation_ville && !row.localisation_ville) {
|
||||
updateData.localisation_ville = enriched.localisation_ville;
|
||||
// Nom : ne remplacer que le placeholder posé par le formulaire assoupli (B5-M1).
|
||||
if (enriched.nom && typeof row.nom === 'string' && row.nom.startsWith('[à qualifier]')) {
|
||||
updateData.nom = enriched.nom;
|
||||
}
|
||||
if (enriched.ville && !row.localisation_ville) {
|
||||
updateData.localisation_ville = enriched.ville;
|
||||
}
|
||||
// submission_type : ne réajuster que si l'utilisateur n'avait pas choisi de chip
|
||||
// (marqueur posé par utils/submitLibre.ts::toOrgaPayload — "Type : non précisé").
|
||||
const typeNonPrecise = typeof row.description_user === 'string'
|
||||
&& row.description_user.startsWith('Type : non précisé');
|
||||
if (typeNonPrecise && VALID_SUBMISSION_TYPES.includes(enriched.type_suggere)) {
|
||||
updateData.submission_type = enriched.type_suggere;
|
||||
}
|
||||
|
||||
await nocodbPatch(NOCODB_TABLE_ORGAS, row.Id, updateData);
|
||||
await patchRow(row.Id, updateData);
|
||||
await logUsage(enriched._usage, WORKER_MODEL, 'enrichissement', row.Id);
|
||||
|
||||
// Log usage tokens
|
||||
await logUsage(enriched._usage, 'open-mistral-nemo', 'enrichissement', row.Id);
|
||||
await notifyNtfy(
|
||||
'[AEP] Fiche enrichie',
|
||||
[
|
||||
`Id NocoDB : ${row.Id}`,
|
||||
`Nom suggéré : ${updateData.nom || row.nom}`,
|
||||
`Type : ${updateData.submission_type || row.submission_type || 'nc'}`,
|
||||
`Confiance : ${enriched.confiance || 'nc'}`,
|
||||
].join('\n'),
|
||||
);
|
||||
|
||||
const elapsed = ((Date.now() - rowStart) / 1000).toFixed(1);
|
||||
log(`Fiche ${row.Id} traitée en ${elapsed}s — confiance: ${enriched.confiance || 'nc'}`);
|
||||
@@ -480,15 +585,12 @@ async function run() {
|
||||
|
||||
log(`=== Run terminé: ${processedCount}/${rows.length} fiches traitées en ${((Date.now() - startTime) / 1000).toFixed(1)}s ===`);
|
||||
|
||||
// Check seuil modération
|
||||
await checkModerationQueue();
|
||||
|
||||
} catch (e) {
|
||||
log('ERREUR WORKER:', e.message);
|
||||
console.error(e.stack);
|
||||
process.exit(1);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
releaseLock();
|
||||
if (!DRY_RUN) releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
[
|
||||
{
|
||||
"Id": 9001,
|
||||
"nom": "[à qualifier] exemple.org",
|
||||
"url": "https://exemple.org",
|
||||
"description_user": "Ça m'a beaucoup aidé à sortir de l'isolement quand j'ai monté mon agence.\n\nLiens :\nhttps://exemple.org\nhttps://exemple.org/guide-installation",
|
||||
"submitted_by_email": null,
|
||||
"submission_type": "ecosysteme",
|
||||
"moderation_status": "pending",
|
||||
"ai_processed": false,
|
||||
"scrape_status": "pending",
|
||||
"localisation_ville": null
|
||||
},
|
||||
{
|
||||
"Id": 9002,
|
||||
"nom": "[à qualifier] sans titre",
|
||||
"url": null,
|
||||
"description_user": "Type : non précisé\n\nUn super groupe d'entraide entre archis installés en rural, très actif sur les questions de reconversion.",
|
||||
"submitted_by_email": "test@exemple.fr",
|
||||
"submission_type": "ecosysteme",
|
||||
"moderation_status": "pending",
|
||||
"ai_processed": false,
|
||||
"scrape_status": "no_link",
|
||||
"localisation_ville": null
|
||||
}
|
||||
]
|
||||
Reference in New Issue
Block a user