diff --git a/scripts/auftraege-setup.mjs b/scripts/auftraege-setup.mjs new file mode 100644 index 0000000..830be01 --- /dev/null +++ b/scripts/auftraege-setup.mjs @@ -0,0 +1,102 @@ +#!/usr/bin/env node +/** + * Aufträge und Rechnungen: legt die Collections auftraege und projektRechnungen mit Attributen und Indizes in + * Appwrite an (nur Server-Key, keine Client-Rechte) und ergänzt die vorhandenen Collections customers (Feld + * kundenart) und financeSettings (Feld steuernummer). Das Schema steht in server/services/auftraege/schema.js. + * Idempotent: Vorhandenes wird übersprungen, fehlende Attribute und Indizes auch in schon vorhandenen Collections + * nachgezogen. customers (gehört dem Ticketsystem) und financeSettings (scripts/setup-finanzen.mjs) legt dieses + * Skript nie an; fehlen sie, bricht es vor jeder Änderung ab. Vor dem Code-Deploy und vor dem Einschalten + * (AUFTRAEGE_ENABLED) ausführen: der Code schreibt die neuen Felder, ohne Schema antwortet Appwrite mit + * "Unknown attribute". + * Usage: + * docker exec -w /app webklar-kundenbereich-server node scripts/auftraege-setup.mjs + * node scripts/auftraege-setup.mjs --check (nur melden, nichts anlegen; Exit 1 bei Fehlendem) + * node scripts/auftraege-setup.mjs (Fehlendes anlegen) + */ +import { pathToFileURL } from 'node:url' +import { config } from '../server/config.js' +import { AUFTRAEGE_COLLECTIONS, AUFTRAEGE_ZUSATZ_ATTRIBUTE } from '../server/services/auftraege/schema.js' +import { createAppwriteClient } from './analyse-setup.mjs' + +// Hinweis, falls eine nicht eigene Collection fehlt +const HINWEIS = { + financeSettings: 'zuerst scripts/setup-finanzen.mjs ausfuehren', + customers: 'die Kunden-Collection gehört dem Ticketsystem (WOMS)', +} + +export async function main({ check = false, client, log = console.log } = {}) { + const api = client || createAppwriteClient() + const missing = [] + const missingCollections = [] + const missingIndexes = [] + const plan = [] + + // Eigene Collections plus die vorhandenen customers und financeSettings (nur zusätzliche Attribute, keine Indizes) + const targets = [ + ...Object.entries(AUFTRAEGE_COLLECTIONS).map(([name, { attributes, indexes }]) => ({ name, id: config.collections[name], attributes, indexes, own: true })), + ...Object.entries(AUFTRAEGE_ZUSATZ_ATTRIBUTE).map(([name, attributes]) => ({ name, id: config.collections[name], attributes, indexes: [], own: false })), + ] + + // Erst alles pruefen, dann (ohne --check) anlegen, damit --check garantiert nichts veraendert + for (const { name, id, attributes, indexes, own } of targets) { + const exists = await api.collectionExists(id) + if (!exists && !own) throw new Error(`Collection ${id} fehlt – ${HINWEIS[name]}`) + const haveAttributes = exists ? new Set((await api.listAttributes(id)).map((a) => a.key)) : new Set() + const haveIndexes = exists ? new Set((await api.listIndexes(id)).map((i) => i.key)) : new Set() + const absentAttributes = attributes.filter((a) => !haveAttributes.has(a.key)) + const absentIndexes = indexes.filter((i) => !haveIndexes.has(i.key)) + + if (!exists) { + log(`${check ? '-' : '+'} Collection ${id}${check ? ' FEHLT' : ''}`) + missingCollections.push(id) + } else { + log(`= ${id}: ${haveAttributes.size} Attribute, ${haveIndexes.size} Indizes vorhanden`) + } + if (check) { + absentAttributes.forEach((a) => log(`- ${id}.${a.key} FEHLT`)) + absentIndexes.forEach((i) => log(`- Index ${id}.${i.key} FEHLT`)) + } + absentAttributes.forEach((a) => missing.push({ ...a, collection: id })) + absentIndexes.forEach((i) => missingIndexes.push({ ...i, collection: id })) + plan.push({ id, exists, absentAttributes, absentIndexes }) + } + + const result = { missing, missingCollections, missingIndexes } + if (check) { + const open = missing.length + missingCollections.length + missingIndexes.length + log(open ? `${open} Eintrag/Eintraege fehlen.` : 'Alles vorhanden.') + return result + } + + for (const { id, exists, absentAttributes } of plan) { + if (!exists) await api.ensureCollection(id, id) + for (const attr of absentAttributes) { + await api.createAttribute(id, attr) + log(`+ Attribut ${id}.${attr.key}`) + } + } + // Indizes brauchen verfuegbare Attribute: erst warten, dann anlegen + for (const { id, absentAttributes } of plan) { + for (const attr of absentAttributes) await api.waitForAttribute(id, attr.key) + } + for (const { id, absentIndexes } of plan) { + for (const index of absentIndexes) { + await api.createIndex(id, index) + log(`+ Index ${id}.${index.key}`) + } + } + log('Fertig.') + return result +} + +const invokedDirectly = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href +if (invokedDirectly) { + const check = process.argv.includes('--check') + main({ check }) + .then(({ missing, missingCollections, missingIndexes }) => + process.exit(check && (missing.length || missingCollections.length || missingIndexes.length) ? 1 : 0)) + .catch((e) => { + console.error(e.message) + process.exit(1) + }) +} diff --git a/test/auftraegeSetup.test.js b/test/auftraegeSetup.test.js new file mode 100644 index 0000000..934714e --- /dev/null +++ b/test/auftraegeSetup.test.js @@ -0,0 +1,155 @@ +// test/auftraegeSetup.test.js +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { config } from '../server/config.js' +import { AUFTRAEGE_COLLECTIONS } from '../server/services/auftraege/schema.js' +import { main } from '../scripts/auftraege-setup.mjs' + +// Geprüft wird nur mit dem Client mit Zustand unten (Muster: test/zeitenSetup.test.js), nie gegen Appwrite. +const NAMES = ['auftraege', 'projektRechnungen'] +const ids = NAMES.map((name) => config.collections[name]) +const customersId = config.collections.customers +const settingsId = config.collections.financeSettings +const keysOf = (name) => AUFTRAEGE_COLLECTIONS[name].attributes.map((a) => a.key) +const quiet = () => {} +const leer = () => ({ collections: [], attrs: [], indexes: [] }) + +/** Client mit Zustand: Attribute gibt es nur in vorhandenen Collections, Indizes nur auf vorhandenen Attributen. */ +function fakeClient(initial = {}) { + const start = { + [customersId]: { attrs: ['name', 'email'] }, + [settingsId]: { attrs: ['minBufferCents', 'bankDetailsText'] }, + ...initial, + } + const state = new Map( + Object.entries(start).map(([id, c]) => [id, { attrs: new Map((c.attrs || []).map((key) => [key, null])), indexes: new Set(c.indexes || []) }]), + ) + const calls = leer() + const need = (id) => { + if (!state.has(id)) throw Object.assign(new Error(`Collection ${id} fehlt`), { status: 404 }) + return state.get(id) + } + return { + state, + calls, + async collectionExists(id) { + return state.has(id) + }, + async ensureCollection(id, name) { + if (state.has(id)) return false + state.set(id, { attrs: new Map(), indexes: new Set() }) + calls.collections.push({ id, name }) + return true + }, + async listAttributes(id) { + return [...need(id).attrs.keys()].map((key) => ({ key })) + }, + async createAttribute(id, attr) { + const collection = need(id) + if (collection.attrs.has(attr.key)) throw new Error(`Attribut ${id}.${attr.key} existiert schon`) + collection.attrs.set(attr.key, attr) + calls.attrs.push(`${id}.${attr.key}`) + }, + async waitForAttribute(id, key) { + assert.ok(need(id).attrs.has(key), `wartet auf nie angelegtes Attribut ${id}.${key}`) + }, + async listIndexes(id) { + return [...need(id).indexes].map((key) => ({ key })) + }, + async createIndex(id, index) { + const collection = need(id) + for (const key of index.attributes) { + if (!collection.attrs.has(key)) throw new Error(`Index ${index.key}: Attribut ${key} fehlt in ${id}`) + } + collection.indexes.add(index.key) + calls.indexes.push(`${id}.${index.key}`) + }, + } +} + +const expectedAttrs = [ + ...NAMES.flatMap((name) => keysOf(name).map((key) => `${config.collections[name]}.${key}`)), + `${customersId}.kundenart`, + `${settingsId}.steuernummer`, +] +const expectedIndexes = NAMES.flatMap((name) => AUFTRAEGE_COLLECTIONS[name].indexes.map((i) => `${config.collections[name]}.${i.key}`)) + +test('main legt auf leerer Datenbank 2 Collections mit allen Attributen und Indizes an und ergänzt customers und financeSettings', async () => { + const client = fakeClient() + const result = await main({ client, log: quiet }) + assert.deepEqual(client.calls.collections, ids.map((id) => ({ id, name: id }))) + assert.deepEqual([...client.calls.attrs].sort(), [...expectedAttrs].sort()) + assert.deepEqual([...client.calls.indexes].sort(), [...expectedIndexes].sort()) + assert.equal(expectedAttrs.length, 55) + assert.equal(expectedIndexes.length, 8) + assert.equal(result.missing.length, 55) + assert.deepEqual(result.missingCollections, ids) + assert.equal(result.missingIndexes.length, 8) + // customers und financeSettings gibt es schon: sie werden nie angelegt, bekommen nur ihr neues Feld + assert.ok(!client.calls.collections.some((c) => [customersId, settingsId].includes(c.id))) + assert.deepEqual(client.state.get(customersId).attrs.get('kundenart'), { key: 'kundenart', type: 'string', size: 20, required: false }) + assert.deepEqual(client.state.get(settingsId).attrs.get('steuernummer'), { key: 'steuernummer', type: 'string', size: 40, required: false }) +}) + +test('main: zweiter Lauf legt nichts mehr an', async () => { + const client = fakeClient() + await main({ client, log: quiet }) + client.calls.collections.length = client.calls.attrs.length = client.calls.indexes.length = 0 + const result = await main({ client, log: quiet }) + assert.deepEqual(client.calls, leer()) + assert.deepEqual(result, { missing: [], missingCollections: [], missingIndexes: [] }) +}) + +test('main legt nur Fehlendes an, auch in einer schon vorhandenen Collection', async () => { + const pr = config.collections.projektRechnungen + const client = fakeClient({ + [pr]: { attrs: ['invoiceId', 'kundenId'], indexes: ['idx_kunde'] }, + [customersId]: { attrs: ['name', 'kundenart'] }, + }) + await main({ client, log: quiet }) + assert.deepEqual(client.calls.collections, [{ id: config.collections.auftraege, name: config.collections.auftraege }]) + assert.deepEqual( + client.calls.attrs.filter((k) => k.startsWith(`${pr}.`)), + keysOf('projektRechnungen').filter((k) => !['invoiceId', 'kundenId'].includes(k)).map((k) => `${pr}.${k}`), + ) + assert.deepEqual(client.calls.indexes.filter((k) => k.startsWith(`${pr}.`)), [`${pr}.idx_projekt`, `${pr}.idx_auftrag`]) + assert.ok(!client.calls.attrs.includes(`${customersId}.kundenart`)) + assert.ok(client.calls.attrs.includes(`${settingsId}.steuernummer`)) +}) + +test('--check meldet Fehlendes und schreibt nichts', async () => { + const client = fakeClient() + const lines = [] + const result = await main({ check: true, client, log: (line) => lines.push(line) }) + assert.deepEqual(client.calls, leer()) + assert.equal(client.state.size, 2, 'nur customers und financeSettings, nichts angelegt') + assert.deepEqual([...client.state.get(settingsId).attrs.keys()], ['minBufferCents', 'bankDetailsText']) + assert.deepEqual(result.missingCollections, ids) + assert.equal(result.missing.length, 55) + assert.ok(lines.some((l) => l.includes(config.collections.auftraege) && l.includes('FEHLT')), lines.join('\n')) + assert.ok(lines.some((l) => l.includes(`${settingsId}.steuernummer FEHLT`)), lines.join('\n')) + assert.ok(lines.some((l) => l.includes(`Index ${config.collections.auftraege}.idx_nummer FEHLT`)), lines.join('\n')) +}) + +test('--check bei vollständigem Stand: nichts fehlt; ein einzelnes fehlendes Feld wird genau genannt', async () => { + const client = fakeClient() + await main({ client, log: quiet }) + assert.deepEqual(await main({ check: true, client, log: quiet }), { missing: [], missingCollections: [], missingIndexes: [] }) + client.state.get(customersId).attrs.delete('kundenart') + const result = await main({ check: true, client, log: quiet }) + assert.deepEqual(result.missing.map((a) => `${a.collection}.${a.key}`), [`${customersId}.kundenart`]) + assert.deepEqual(result.missingCollections, []) +}) + +test('fehlt customers oder financeSettings, bricht main mit klarer Meldung ab, ohne etwas anzulegen', async () => { + for (const [fehlt, hinweis] of [[settingsId, /setup-finanzen/], [customersId, /Ticketsystem/]]) { + const client = fakeClient() + client.state.delete(fehlt) + await assert.rejects( + () => main({ client, log: quiet }), + (err) => err.message.includes(fehlt) && err.message.includes('fehlt') && hinweis.test(err.message), + fehlt, + ) + assert.deepEqual(client.calls, leer()) + } +})