diff --git a/package.json b/package.json index cef9487..968daf8 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "dev": "nuxt dev", "generate": "nuxt generate", "preview": "nuxt preview", - "test": "node scripts/test-echelles-nav.mjs && node scripts/test-figures.mjs && node scripts/test-vue-fiches.mjs && node scripts/test-submit-libre.mjs && node scripts/test-circuit-breaker.mjs && node scripts/test-bandeau.mjs && node scripts/test-outils-data.mjs && node scripts/test-citations.mjs && node scripts/test-seo.mjs && node scripts/test-y.mjs && node scripts/test-connaissances.mjs && node scripts/test-media-data.mjs && node scripts/test-taxonomie.mjs && node scripts/test-geocodage.mjs && node --test \"worker/test/*.test.js\"", + "test": "node scripts/test-echelles-nav.mjs && node scripts/test-figures.mjs && node scripts/test-vue-fiches.mjs && node scripts/test-submit-libre.mjs && node scripts/test-circuit-breaker.mjs && node scripts/test-bandeau.mjs && node scripts/test-outils-data.mjs && node scripts/test-citations.mjs && node scripts/test-seo.mjs && node scripts/test-y.mjs && node scripts/test-connaissances.mjs && node scripts/test-media-data.mjs && node scripts/test-taxonomie.mjs && node scripts/test-geocodage.mjs && node scripts/test-migrer-taxonomie.mjs && node --test \"worker/test/*.test.js\"", "postinstall": "nuxt prepare" }, "dependencies": { diff --git a/scripts/migrer-taxonomie-nocodb.mjs b/scripts/migrer-taxonomie-nocodb.mjs new file mode 100644 index 0000000..3231631 --- /dev/null +++ b/scripts/migrer-taxonomie-nocodb.mjs @@ -0,0 +1,155 @@ +#!/usr/bin/env node +/** + * B4b-2 (préparé par B4b-1, lancé par la session de secteur au checkpoint, après une + * sauvegarde NocoDB de moins de 24 h) : porte le type d'organisation et les postures des + * 91 fiches d'entraide (`org:` de `data/taxonomie/organisations.json`) dans la table + * `organisations` de NocoDB, colonnes `type_organisation` (choix unique) et `postures` + * (choix multiple). + * + * Trois façons de le lancer : + * node scripts/migrer-taxonomie-nocodb.mjs + * Lecture seule, sans réseau : écrit le plan (91 lignes : Id, nom, type_organisation, + * postures) dans taxonomie-nocodb-plan.json (dossier temporaire, ou --plan ). + * NOCODB_URL=… NOCODB_TOKEN=… node scripts/migrer-taxonomie-nocodb.mjs + * À blanc contre la base : en plus du plan, vérifie les deux colonnes, chaque Id et + * chaque nom, et dit ce qui serait écrit. N'écrit rien. + * NOCODB_URL=… NOCODB_TOKEN=… node scripts/migrer-taxonomie-nocodb.mjs --ecrire + * Écrit, ligne à ligne, relit chaque ligne après écriture, rend un bilan. + * + * Garde-fous : rien n'est écrit si une des deux colonnes manque ; un Id absent ou un nom + * qui a changé = ligne sautée et listée ; une ligne relue différente de ce qui a été écrit + * = listée « différente » (code de sortie 1). L'adresse et le jeton viennent des variables + * d'environnement (NOCODB_URL, NOCODB_TOKEN ; table : NOCODB_TABLE_ORGAS, sinon celle de + * nuxt.config.ts) et ne sont jamais journalisés. + */ + +import { readFileSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { fileURLToPath } from 'node:url' +import { dirname, join, resolve } from 'node:path' + +export const TABLE_PAR_DEFAUT = 'm08t7g5v4wch6wb' +export const COLONNES = ['type_organisation', 'postures'] + +/** Le plan : une ligne par `org:`, dans l'ordre des Id. */ +export function plan(mapping) { + return Object.entries(mapping.entrees) + .filter(([cle]) => /^org:\d+$/.test(cle)) + .map(([cle, e]) => ({ Id: Number(cle.slice(4)), nom: e.nom ?? '', type_organisation: e.type_organisation, postures: [...(e.postures ?? [])] })) + .sort((a, b) => a.Id - b.Id) +} + +const normNom = (s) => String(s ?? '').normalize('NFC').replace(/\s+/g, ' ').trim() +/** Un choix multiple NocoDB se lit « a,b » (ou en tableau selon la version). */ +const lirePostures = (v) => (Array.isArray(v) ? v : String(v ?? '').split(',')).map((p) => String(p).trim()).filter(Boolean).sort() + +/** + * Vérifie (et, si `ecrire`, écrit) le plan contre une API NocoDB v2. + * `journal` reçoit des lignes de texte : jamais l'adresse ni le jeton. + */ +export async function migrer({ lignes, url, token, table = TABLE_PAR_DEFAUT, ecrire = false, journal = () => {}, pause = 100 }) { + const base = String(url).replace(/\/+$/, '') + const entetes = { 'xc-token': token, 'Content-Type': 'application/json' } + const appel = async (chemin, init = {}) => { + const r = await fetch(`${base}${chemin}`, { ...init, headers: entetes }) + const texte = await r.text() + let corps = null + try { corps = texte ? JSON.parse(texte) : null } catch { corps = null } + return { statut: r.status, corps } + } + const attendre = (ms) => new Promise((r) => setTimeout(r, ms)) + const bilan = { colonnes_manquantes: [], ecrites: [], a_ecrire: [], deja_a_jour: [], sautees: [], differentes: [] } + + // 1. Les deux colonnes existent + const meta = await appel(`/api/v2/meta/tables/${table}`) + if (meta.statut !== 200 || !Array.isArray(meta.corps?.columns)) throw new Error(`lecture des colonnes impossible (HTTP ${meta.statut})`) + const titres = new Set(meta.corps.columns.flatMap((c) => [c.title, c.column_name]).filter(Boolean)) + bilan.colonnes_manquantes = COLONNES.filter((c) => !titres.has(c)) + if (bilan.colonnes_manquantes.length) { + journal(`Colonnes absentes : ${bilan.colonnes_manquantes.join(', ')}. Rien n'est écrit.`) + return bilan + } + + for (const l of lignes) { + // 2. L'Id existe, le nom correspond + const lu = await appel(`/api/v2/tables/${table}/records/${l.Id}`) + if (lu.statut === 404 || !lu.corps || lu.corps.Id == null) { + bilan.sautees.push({ Id: l.Id, nom: l.nom, raison: 'Id absent de la base' }) + journal(`sautée ${l.Id} ${l.nom} : Id absent`) + continue + } + if (lu.statut !== 200) throw new Error(`lecture de ${l.Id} impossible (HTTP ${lu.statut})`) + if (normNom(lu.corps.nom) !== normNom(l.nom)) { + bilan.sautees.push({ Id: l.Id, nom: l.nom, raison: `nom changé dans la base : « ${lu.corps.nom} »` }) + journal(`sautée ${l.Id} ${l.nom} : nom changé (« ${lu.corps.nom} »)`) + continue + } + const voulu = { type: l.type_organisation, postures: [...l.postures].sort() } + if (lu.corps.type_organisation === voulu.type && JSON.stringify(lirePostures(lu.corps.postures)) === JSON.stringify(voulu.postures)) { + bilan.deja_a_jour.push(l.Id) + continue + } + if (!ecrire) { + bilan.a_ecrire.push(l.Id) + continue + } + // 3. Écrire la ligne, puis la relire + const w = await appel(`/api/v2/tables/${table}/records`, { method: 'PATCH', body: JSON.stringify([{ Id: l.Id, type_organisation: l.type_organisation, postures: l.postures.join(',') }]) }) + if (w.statut !== 200) { + bilan.differentes.push({ Id: l.Id, nom: l.nom, raison: `écriture refusée (HTTP ${w.statut})` }) + journal(`échec ${l.Id} ${l.nom} : HTTP ${w.statut}`) + continue + } + const relu = await appel(`/api/v2/tables/${table}/records/${l.Id}`) + const ok = relu.corps?.type_organisation === voulu.type && JSON.stringify(lirePostures(relu.corps?.postures)) === JSON.stringify(voulu.postures) + if (ok) { + bilan.ecrites.push(l.Id) + journal(`écrite ${l.Id} ${l.nom} : ${l.type_organisation} · ${l.postures.join(', ') || '(aucune posture)'}`) + } else { + bilan.differentes.push({ Id: l.Id, nom: l.nom, raison: `relue : ${relu.corps?.type_organisation} · ${lirePostures(relu.corps?.postures).join(',')}` }) + journal(`DIFFÉRENTE ${l.Id} ${l.nom} après relecture`) + } + if (pause) await attendre(pause) + } + return bilan +} + +async function principal() { + const racine = join(dirname(fileURLToPath(import.meta.url)), '..') + const args = process.argv.slice(2) + const ecrire = args.includes('--ecrire') + const iPlan = args.indexOf('--plan') + const cheminPlan = iPlan >= 0 && args[iPlan + 1] ? resolve(args[iPlan + 1]) : join(tmpdir(), 'taxonomie-nocodb-plan.json') + + const mapping = JSON.parse(readFileSync(join(racine, 'data', 'taxonomie', 'organisations.json'), 'utf8')) + const lignes = plan(mapping) + writeFileSync(cheminPlan, JSON.stringify(lignes, null, 2) + '\n', 'utf8') + console.log(`Plan : ${lignes.length} lignes org: → ${cheminPlan}`) + + const url = process.env.NOCODB_URL + const token = process.env.NOCODB_TOKEN + if (!url || !token) { + if (ecrire) { + console.error('--ecrire demande NOCODB_URL et NOCODB_TOKEN dans l’environnement. Rien n’est écrit.') + process.exit(1) + } + console.log('Sans NOCODB_URL / NOCODB_TOKEN : plan seulement, aucune lecture de la base.') + return + } + console.log(ecrire ? 'Mode ÉCRITURE : ligne à ligne, relecture après chaque écriture.' : 'À blanc : lecture de la base, rien n’est écrit (ajouter --ecrire pour écrire).') + const bilan = await migrer({ lignes, url, token, table: process.env.NOCODB_TABLE_ORGAS || TABLE_PAR_DEFAUT, ecrire, journal: (l) => console.log(l) }) + console.log('\nBilan') + if (bilan.colonnes_manquantes.length) console.log(` colonnes manquantes : ${bilan.colonnes_manquantes.join(', ')} (rien n'est écrit)`) + console.log(` ${ecrire ? 'écrites' : 'à écrire'} : ${ecrire ? bilan.ecrites.length : bilan.a_ecrire.length}`) + console.log(` déjà à jour : ${bilan.deja_a_jour.length}`) + console.log(` sautées : ${bilan.sautees.length}${bilan.sautees.map((s) => `\n ${s.Id} ${s.nom} : ${s.raison}`).join('')}`) + console.log(` différentes après relecture : ${bilan.differentes.length}${bilan.differentes.map((s) => `\n ${s.Id} ${s.nom} : ${s.raison}`).join('')}`) + if (bilan.colonnes_manquantes.length || bilan.differentes.length) process.exit(1) +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + principal().catch((e) => { + console.error(`Arrêt : ${e.message}`) + process.exit(1) + }) +} diff --git a/scripts/test-migrer-taxonomie.mjs b/scripts/test-migrer-taxonomie.mjs new file mode 100644 index 0000000..09d9d0d --- /dev/null +++ b/scripts/test-migrer-taxonomie.mjs @@ -0,0 +1,124 @@ +#!/usr/bin/env node +/** + * Test de scripts/migrer-taxonomie-nocodb.mjs (B4b-2, préparé en B4b-1) contre une fausse + * API NocoDB v2 locale : trois lignes, dont un Id absent et un nom changé ; à blanc rien + * n'est écrit ; --ecrire écrit la seule ligne sûre et la relit ; une colonne manquante + * bloque tout ; le jeton n'apparaît jamais dans le journal. Plan réel : 91 lignes org:. + * Aucune base réelle n'est touchée. + * Usage : node scripts/test-migrer-taxonomie.mjs + */ + +import { createServer } from 'node:http' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { dirname, join } from 'node:path' +import { plan, migrer } from './migrer-taxonomie-nocodb.mjs' + +const racine = join(dirname(fileURLToPath(import.meta.url)), '..') +let n = 0 +let fail = 0 +function ok(cond, libelle, detail = '') { + n++ + if (!cond) fail++ + console.log(`${cond ? 'OK ' : 'FAIL'} ${libelle}${!cond && detail ? ` → ${detail}` : ''}`) +} + +// ── Le plan réel ── +const mapping = JSON.parse(readFileSync(join(racine, 'data', 'taxonomie', 'organisations.json'), 'utf8')) +const p = plan(mapping) +ok(p.length === 91, `plan : 91 lignes org: (${p.length})`) +ok(p.every((l) => Number.isInteger(l.Id) && l.nom && l.type_organisation && Array.isArray(l.postures)), 'plan : Id, nom, type_organisation, postures sur chaque ligne') +ok(p.every((l, i) => i === 0 || p[i - 1].Id < l.Id), 'plan : trié par Id') +ok(!p.some((l) => 'source' in l), 'plan : rien d’autre que les quatre champs') + +// ── Fausse API NocoDB ── +const JETON = 'jeton-de-test-secret' +const TABLE = 'tfaux' +function fausseBase({ colonnes = ['Id', 'nom', 'type_org', 'type_organisation', 'postures'] } = {}) { + const lignes = new Map([ + [1, { Id: 1, nom: 'Collectif A', type_organisation: null, postures: null }], + [3, { Id: 3, nom: 'Nouveau nom C', type_organisation: null, postures: null }], + ]) + const ecritures = [] + const serveur = createServer((req, res) => { + const envoyer = (statut, corps) => { res.writeHead(statut, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(corps)) } + if (req.headers['xc-token'] !== JETON) return envoyer(401, { msg: 'jeton' }) + const u = new URL(req.url, 'http://x') + if (req.method === 'GET' && u.pathname === `/api/v2/meta/tables/${TABLE}`) return envoyer(200, { columns: colonnes.map((title) => ({ title, column_name: title })) }) + const m = u.pathname.match(new RegExp(`^/api/v2/tables/${TABLE}/records(?:/(\\d+))?$`)) + if (!m) return envoyer(404, {}) + if (req.method === 'GET' && m[1]) { + const l = lignes.get(Number(m[1])) + return l ? envoyer(200, l) : envoyer(404, { msg: 'Record not found' }) + } + if (req.method === 'PATCH' && !m[1]) { + let corps = '' + req.on('data', (c) => (corps += c)) + req.on('end', () => { + for (const w of JSON.parse(corps)) { + ecritures.push(w) + const l = lignes.get(w.Id) + if (l) Object.assign(l, w) + } + envoyer(200, JSON.parse(corps).map((w) => ({ Id: w.Id }))) + }) + return + } + envoyer(405, {}) + }) + return new Promise((r) => serveur.listen(0, '127.0.0.1', () => r({ serveur, lignes, ecritures, url: `http://127.0.0.1:${serveur.address().port}` }))) +} + +const trois = [ + { Id: 1, nom: 'Collectif A', type_organisation: 'association', postures: ['participatif', 'cooperative'] }, + { Id: 2, nom: 'Agence B', type_organisation: 'agence', postures: [] }, + { Id: 3, nom: 'Ancien nom C', type_organisation: 'syndicat', postures: [] }, +] + +// À blanc +{ + const f = await fausseBase() + const journal = [] + const b = await migrer({ lignes: trois, url: f.url, token: JETON, table: TABLE, ecrire: false, journal: (l) => journal.push(l), pause: 0 }) + ok(f.ecritures.length === 0, 'à blanc : aucune écriture') + ok(JSON.stringify(b.a_ecrire) === '[1]', `à blanc : la ligne 1 serait écrite (${JSON.stringify(b.a_ecrire)})`) + ok(b.sautees.length === 2 && b.sautees.some((s) => s.Id === 2 && /absent/.test(s.raison)) && b.sautees.some((s) => s.Id === 3 && /nom changé/.test(s.raison)), 'à blanc : Id absent et nom changé sautés et listés') + f.serveur.close() +} + +// Écriture +{ + const f = await fausseBase() + const journal = [] + const b = await migrer({ lignes: trois, url: f.url + '/', token: JETON, table: TABLE, ecrire: true, journal: (l) => journal.push(l), pause: 0 }) + ok(f.ecritures.length === 1 && f.ecritures[0].Id === 1, 'écriture : une seule ligne écrite, la ligne sûre', JSON.stringify(f.ecritures)) + ok(f.ecritures[0]?.postures === 'participatif,cooperative' && f.ecritures[0]?.type_organisation === 'association', 'écriture : choix multiple en « a,b », type tel quel') + ok(JSON.stringify(b.ecrites) === '[1]' && b.differentes.length === 0, 'écriture : relue identique, bilan 1 écrite, 0 différente') + ok(b.sautees.length === 2, 'écriture : Id absent et nom changé sautés (2)') + ok(f.lignes.get(3).type_organisation === null, 'écriture : la ligne au nom changé n’est pas touchée') + ok(journal.every((l) => !l.includes(JETON) && !l.includes('127.0.0.1')), 'journal : ni jeton ni adresse') + const b2 = await migrer({ lignes: trois, url: f.url, token: JETON, table: TABLE, ecrire: true, pause: 0 }) + ok(b2.ecrites.length === 0 && JSON.stringify(b2.deja_a_jour) === '[1]' && f.ecritures.length === 1, 'relancée : rien de réécrit, ligne 1 déjà à jour') + f.serveur.close() +} + +// Une colonne manquante bloque tout +{ + const f = await fausseBase({ colonnes: ['Id', 'nom', 'type_org', 'type_organisation'] }) + const b = await migrer({ lignes: trois, url: f.url, token: JETON, table: TABLE, ecrire: true, pause: 0 }) + ok(JSON.stringify(b.colonnes_manquantes) === '["postures"]' && f.ecritures.length === 0, 'colonne postures absente : rien n’est écrit') + f.serveur.close() +} + +// Relecture différente (la base ignore une colonne) → listée +{ + const f = await fausseBase() + const origine = f.lignes.get(1) + Object.defineProperty(origine, 'postures', { get: () => null, set: () => {}, enumerable: true }) + const b = await migrer({ lignes: trois, url: f.url, token: JETON, table: TABLE, ecrire: true, pause: 0 }) + ok(b.differentes.length === 1 && b.differentes[0].Id === 1 && b.ecrites.length === 0, 'relue différente de l’écriture → listée « différente »') + f.serveur.close() +} + +console.log(`\n${n - fail}/${n}`) +if (fail) process.exit(1)