diff --git a/scripts/termine-setup.mjs b/scripts/termine-setup.mjs new file mode 100644 index 0000000..58f9826 --- /dev/null +++ b/scripts/termine-setup.mjs @@ -0,0 +1,85 @@ +#!/usr/bin/env node +/** + * Terminplaner: legt die vier Collections termineConfig, termineBookings, termineClaims und termineOutbox mit + * Attributen und Indizes in Appwrite an (nur Server-Key, keine Client-Rechte). Das Schema steht in + * server/services/termine/schema.js. Idempotent: Vorhandenes wird uebersprungen, fehlende Attribute und Indizes + * auch in schon vorhandenen Collections nachgezogen. Vor dem Einschalten (TERMINE_ENABLED) ausfuehren. + * Usage: + * node scripts/termine-setup.mjs --check (nur melden, nichts anlegen; Exit 1 bei Fehlendem) + * node scripts/termine-setup.mjs (Fehlendes anlegen) + */ +import { pathToFileURL } from 'node:url' +import { config } from '../server/config.js' +import { TERMINE_COLLECTIONS } from '../server/services/termine/schema.js' +import { createAppwriteClient } from './analyse-setup.mjs' + +export async function main({ check = false, client, log = console.log } = {}) { + const api = client || createAppwriteClient() + const missing = [] + const missingCollections = [] + const missingIndexes = [] + const plan = [] + + // Erst alles pruefen, dann (ohne --check) anlegen, damit --check garantiert nichts veraendert + for (const [name, { attributes, indexes }] of Object.entries(TERMINE_COLLECTIONS)) { + const id = config.collections[name] + const exists = await api.collectionExists(id) + 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/server/config.js b/server/config.js index d7ca60d..86ea37c 100644 --- a/server/config.js +++ b/server/config.js @@ -23,6 +23,14 @@ function resolveDatabaseId() { return WOMS_DATABASE_ID } +/** Zahl >= 0 aus einer Umgebungsvariablen; leer, keine Zahl oder negativ ergibt den Vorgabewert. */ +function nonNegativeNumber(raw, fallback) { + const value = Number(raw) + return String(raw ?? '').trim() !== '' && Number.isFinite(value) && value >= 0 ? value : fallback +} + +const termineEnabled = (process.env.TERMINE_ENABLED || '').trim().toLowerCase() + // Abo-Produkte (Spec 2026-09-27 "Verträge, Hosting-Abo und E-Mail-Zusatzspeicher"). Preise in Cent, // Endpreise gemäß § 19 UStG. Texte, die Kunden sehen, stimmen mit den Vertragsbedingungen überein. const products = { @@ -160,6 +168,11 @@ export const config = { bankTransactions: process.env.APPWRITE_COLLECTION_BANK_TRANSACTIONS || 'bankTransactions', financeSettings: process.env.APPWRITE_COLLECTION_FINANCE_SETTINGS || 'financeSettings', financeFixedCosts: process.env.APPWRITE_COLLECTION_FINANCE_FIXED_COSTS || 'financeFixedCosts', + // Terminplaner (Einstellungen, Buchungen, Belegungszellen, Mail-Warteschlange; scripts/termine-setup.mjs) + termineConfig: process.env.APPWRITE_COLLECTION_TERMINE_CONFIG || 'termineConfig', + termineBookings: process.env.APPWRITE_COLLECTION_TERMINE_BOOKINGS || 'termineBookings', + termineClaims: process.env.APPWRITE_COLLECTION_TERMINE_CLAIMS || 'termineClaims', + termineOutbox: process.env.APPWRITE_COLLECTION_TERMINE_OUTBOX || 'termineOutbox', }, publicBaseUrl: (process.env.PORTAL_PUBLIC_URL || 'https://project.webklar.com').replace(/\/$/, ''), @@ -360,6 +373,23 @@ export const config = { avvVersion: '2026-10-02', }, + // Terminplaner (Funktionsschluessel 'termine'). Wird bei jedem Aufruf gelesen (Tests aendern die Werte zur + // Laufzeit); Schalter siehe server/services/termine/schalter.js + termine: { + // off (Vorgabe) | pilot (nur TERMINE_PILOT_EMAILS) | on (alle Kunden) + mode: ['pilot', 'on'].includes(termineEnabled) ? termineEnabled : 'off', + // Kunden-E-Mails fuer den Pilotbetrieb; '*' = alle + pilotEmails: (process.env.TERMINE_PILOT_EMAILS || '') + .split(',') + .map((s) => s.trim().toLowerCase()) + .filter(Boolean), + holdMinutes: 30, + zelleMin: 5, + mailsProStunde: 200, + // Mindestzeit zwischen Laden und Absenden des Buchungsformulars (schneller = Bot) + formMinSekunden: nonNegativeNumber(process.env.TERMINE_FORM_MIN_SECONDS, 3), + }, + invoiceNinja: { url: (process.env.INVOICE_NINJA_URL || 'https://invoice.webklar.com').replace(/\/$/, ''), apiToken: process.env.INVOICE_NINJA_API_TOKEN || '', diff --git a/server/services/termine/schalter.js b/server/services/termine/schalter.js new file mode 100644 index 0000000..753349a --- /dev/null +++ b/server/services/termine/schalter.js @@ -0,0 +1,30 @@ +import { config } from '../../config.js' + +/** + * Terminplaner-Schalter (Funktionsschluessel 'termine'): TERMINE_ENABLED = off (Vorgabe) | pilot | on. + * Liest config.termine bei jedem Aufruf. Bei off laufen keine Termine-Jobs und keine Termine-Abfragen. + */ + +/** 'off' | 'pilot' | 'on'; alles andere (leer, unbekannt) gilt als off. */ +export function termineModus() { + const mode = config.termine.mode + return mode === 'pilot' || mode === 'on' ? mode : 'off' +} + +export function termineAus() { + return termineModus() === 'off' +} + +/** + * Darf dieser Kunde den Terminplaner nutzen? pilot = nur Adressen aus TERMINE_PILOT_EMAILS ('*' = alle; eine leere + * Liste laesst niemanden durch); on = alle Kunden (TP1: pilot ohne E-Mail-Filter); off = niemand. + */ +export function termineFuerKunde(email) { + const modus = termineModus() + if (modus === 'off') return false + if (modus === 'on') return true + const erlaubt = config.termine.pilotEmails + if (erlaubt.includes('*')) return true + const adresse = String(email || '').trim().toLowerCase() + return adresse !== '' && erlaubt.includes(adresse) +} diff --git a/server/services/termine/schema.js b/server/services/termine/schema.js new file mode 100644 index 0000000..40f81a0 --- /dev/null +++ b/server/services/termine/schema.js @@ -0,0 +1,124 @@ +/** + * Terminplaner: Appwrite-Schema der vier Collections (Spezifikation 2026-10-02-terminplaner-design.md, Abschnitt 2). + * Reine Daten, absichtlich ohne Import von server/config.js: test/support/schema.js liest sie vor useTestEnv(), + * ein frueh geladenes config.js wuerde den Endpunkt des Appwrite-Nachbaus verfehlen. Die Collection-IDs stehen in + * config.collections.; scripts/termine-setup.mjs legt alles an. + * + * Attribut: { key, type: 'string' | 'integer' | 'boolean' | 'datetime', size (nur Text), required: false } + * Index: { key, type: 'key', attributes: [...] } + * Datumswerte sind UTC (toISOString()); Appwrite liefert sie als "+00:00" zurueck, daher immer mit new Date() lesen. + */ + +const str = (key, size) => ({ key, type: 'string', size, required: false }) +const int = (key) => ({ key, type: 'integer', required: false }) +const bool = (key) => ({ key, type: 'boolean', required: false }) +const dt = (key) => ({ key, type: 'datetime', required: false }) +const index = (key, ...attributes) => ({ key, type: 'key', attributes }) + +export const TERMINE_COLLECTIONS = { + // Eine Einstellung je Funktion; Dokument-ID = ID des portalFeatures-Dokuments. Das Feld heisst einstellung, + // nicht data: appwriteAdmin.formatRequestBody haelt Bodies mit data fuer fertig verpackt. + termineConfig: { + attributes: [ + str('customerId', 64), + str('projectId', 64), + str('einstellung', 200000), + int('version'), + dt('updatedAt'), + str('updatedBy', 100), + ], + indexes: [], + }, + + // Eine Buchung je Dokument (ID randomUUID) + termineBookings: { + attributes: [ + str('featureId', 64), + str('customerId', 64), + str('projectId', 64), + str('leistungId', 64), + str('leistungName', 120), + str('ressourceId', 64), + str('ressourceName', 80), + dt('startsAt'), + dt('endsAt'), + dt('blockEndsAt'), + str('status', 16), + str('quelle', 16), + str('gastName', 100), + str('gastEmail', 254), + str('gastTelefon', 40), + str('gastNachricht', 500), + str('gastZusatz', 2000), + bool('erinnerung'), + dt('erinnerungGesendetAt'), + dt('heldUntil'), + str('verifyHash', 64), + str('manageHash', 64), + dt('bestaetigtAt'), + dt('angenommenAt'), + dt('abgesagtAt'), + str('abgesagtVon', 16), + str('absageGrund', 300), + dt('widerrufenAt'), + str('nachweis', 4000), + int('preisCent'), + str('preisArt', 8), + str('buchungsart', 8), + bool('verbraucher'), + str('zahlart', 8), + str('zahlStatus', 16), + str('stripeSessionId', 128), + str('stripePaymentIntent', 64), + int('icsSequenz'), + dt('createdAt'), + dt('updatedAt'), + ], + indexes: [ + index('idx_feature_start', 'featureId', 'startsAt'), + index('idx_status_held', 'status', 'heldUntil'), + index('idx_feature_email', 'featureId', 'gastEmail'), + index('idx_verify', 'verifyHash'), + index('idx_manage', 'manageHash'), + index('idx_status_start', 'status', 'startsAt'), + ], + }, + + // Belegungszellen gegen Doppelbuchung; Dokument-ID c_ + 34 Hex von sha1(featureId|ressourceId|zelleIso) + termineClaims: { + attributes: [str('featureId', 64), str('ressourceId', 64), str('bookingId', 64), dt('zelle'), dt('bis')], + indexes: [index('idx_booking', 'bookingId'), index('idx_bis', 'bis')], + }, + + // Mail-Warteschlange (einziger Sendepfad); enthaelt personenbezogene Daten, daher kurze Aufbewahrung + termineOutbox: { + attributes: [ + str('featureId', 64), + str('bookingId', 64), + str('art', 16), + str('an', 254), + str('fromName', 120), + str('replyTo', 254), + str('subject', 300), + str('html', 100000), + str('text', 50000), + str('ics', 20000), + str('icsMethod', 8), + str('status', 16), + int('versuche'), + dt('naechsterVersuch'), + dt('gesendetAt'), + str('fehler', 300), + dt('createdAt'), + ], + indexes: [index('idx_status_next', 'status', 'naechsterVersuch')], + }, +} + +/** Datumsfelder je Collection, damit der Appwrite-Nachbau der Tests sie wie Appwrite formatieren kann. */ +export const TERMINE_DATETIMES = Object.fromEntries( + Object.entries(TERMINE_COLLECTIONS).map(([name, { attributes }]) => [ + name, + attributes.filter((attribute) => attribute.type === 'datetime').map((attribute) => attribute.key), + ]), +) diff --git a/test/support/schema.js b/test/support/schema.js index 873ee50..6a995b7 100644 --- a/test/support/schema.js +++ b/test/support/schema.js @@ -1,4 +1,5 @@ import { readFileSync } from 'node:fs' +import { TERMINE_COLLECTIONS } from '../../server/services/termine/schema.js' // Setup-Skripte, die Collections in Appwrite anlegen (Blockformat: 'id', ... \n ],) const SETUP_SCRIPTS = ['setup-abo-collections.mjs', 'setup-finanzen.mjs'] @@ -7,9 +8,10 @@ const SETUP_SCRIPTS = ['setup-abo-collections.mjs', 'setup-finanzen.mjs'] * Attribut-Schlüssel einer Collection, wie sie scripts/setup-abo-collections.mjs bzw. * scripts/setup-finanzen.mjs in Appwrite anlegen. Tests geben sie dem Appwrite-Nachbau als Schema: * Schreibt der Code ein Feld, das das Setup-Skript nicht anlegt, scheitert der Test wie Appwrite in - * Produktion. + * Produktion. Die Termine-Collections kommen aus server/services/termine/schema.js (scripts/termine-setup.mjs). */ export function schemaKeys(collection) { + if (Object.hasOwn(TERMINE_COLLECTIONS, collection)) return TERMINE_COLLECTIONS[collection].attributes.map((a) => a.key) for (const script of SETUP_SCRIPTS) { const src = readFileSync(new URL(`../../scripts/${script}`, import.meta.url), 'utf8') const start = src.indexOf(`'${collection}',`) diff --git a/test/termineSchalter.test.js b/test/termineSchalter.test.js new file mode 100644 index 0000000..21ffddd --- /dev/null +++ b/test/termineSchalter.test.js @@ -0,0 +1,146 @@ +import { test, beforeEach, afterEach } from 'node:test' +import assert from 'node:assert/strict' +import { config } from '../server/config.js' +import { termineAus, termineFuerKunde, termineModus } from '../server/services/termine/schalter.js' + +const TERMINE_ENV = [ + 'TERMINE_ENABLED', + 'TERMINE_PILOT_EMAILS', + 'TERMINE_FORM_MIN_SECONDS', + 'APPWRITE_COLLECTION_TERMINE_CONFIG', + 'APPWRITE_COLLECTION_TERMINE_BOOKINGS', + 'APPWRITE_COLLECTION_TERMINE_CLAIMS', + 'APPWRITE_COLLECTION_TERMINE_OUTBOX', +] + +let original +beforeEach(() => { + original = { ...config.termine } +}) +afterEach(() => { + Object.assign(config.termine, original) +}) + +/** Frische config.js-Instanz mit genau diesen Termine-Umgebungsvariablen (alle anderen entfernt). */ +let freshCounter = 0 +async function freshConfig(env = {}) { + const saved = Object.fromEntries(TERMINE_ENV.map((key) => [key, process.env[key]])) + for (const key of TERMINE_ENV) delete process.env[key] + Object.assign(process.env, env) + try { + freshCounter += 1 + return (await import(`../server/config.js?termine-test=${freshCounter}`)).config + } finally { + for (const key of TERMINE_ENV) { + if (saved[key] === undefined) delete process.env[key] + else process.env[key] = saved[key] + } + } +} + +test('Konfiguration: Vorgaben ohne Umgebungsvariablen', async () => { + const fresh = await freshConfig() + assert.deepEqual(fresh.termine, { + mode: 'off', + pilotEmails: [], + holdMinutes: 30, + zelleMin: 5, + mailsProStunde: 200, + formMinSekunden: 3, + }) + assert.equal(fresh.collections.termineConfig, 'termineConfig') + assert.equal(fresh.collections.termineBookings, 'termineBookings') + assert.equal(fresh.collections.termineClaims, 'termineClaims') + assert.equal(fresh.collections.termineOutbox, 'termineOutbox') +}) + +test('Konfiguration: Umgebungsvariablen werden gelesen und bereinigt', async () => { + const fresh = await freshConfig({ + TERMINE_ENABLED: ' Pilot ', + TERMINE_PILOT_EMAILS: ' Kenso.Gri@Gmail.com, ,justin@webklar.com ', + TERMINE_FORM_MIN_SECONDS: '0', + APPWRITE_COLLECTION_TERMINE_CONFIG: 'tConfig', + APPWRITE_COLLECTION_TERMINE_BOOKINGS: 'tBookings', + APPWRITE_COLLECTION_TERMINE_CLAIMS: 'tClaims', + APPWRITE_COLLECTION_TERMINE_OUTBOX: 'tOutbox', + }) + assert.equal(fresh.termine.mode, 'pilot') + assert.deepEqual(fresh.termine.pilotEmails, ['kenso.gri@gmail.com', 'justin@webklar.com']) + assert.equal(fresh.termine.formMinSekunden, 0) + assert.deepEqual( + [fresh.collections.termineConfig, fresh.collections.termineBookings, fresh.collections.termineClaims, fresh.collections.termineOutbox], + ['tConfig', 'tBookings', 'tClaims', 'tOutbox'], + ) +}) + +test('Konfiguration: leerer oder unbekannter Schalter ist off, ungueltige Sekunden fallen auf 3', async () => { + for (const value of ['', ' ', 'banane', 'true', '1', 'ON ']) { + const fresh = await freshConfig({ TERMINE_ENABLED: value }) + assert.equal(fresh.termine.mode, value.trim().toLowerCase() === 'on' ? 'on' : 'off', `TERMINE_ENABLED=${JSON.stringify(value)}`) + } + for (const value of ['', 'abc', '-1', 'NaN']) { + const fresh = await freshConfig({ TERMINE_FORM_MIN_SECONDS: value }) + assert.equal(fresh.termine.formMinSekunden, 3, `TERMINE_FORM_MIN_SECONDS=${JSON.stringify(value)}`) + } + assert.equal((await freshConfig({ TERMINE_FORM_MIN_SECONDS: '7' })).termine.formMinSekunden, 7) +}) + +test('termineModus: leer und unbekannt sind off, pilot und on bleiben', () => { + for (const value of [undefined, null, '', 'banane', 'PILOT', 'true']) { + config.termine.mode = value + assert.equal(termineModus(), 'off', `mode=${JSON.stringify(value)}`) + assert.equal(termineAus(), true) + } + config.termine.mode = 'pilot' + assert.equal(termineModus(), 'pilot') + assert.equal(termineAus(), false) + config.termine.mode = 'on' + assert.equal(termineModus(), 'on') + assert.equal(termineAus(), false) +}) + +test('termineModus: Aenderung von config.termine.mode wirkt sofort', () => { + config.termine.mode = 'off' + assert.equal(termineModus(), 'off') + config.termine.mode = 'on' + assert.equal(termineModus(), 'on') + config.termine.mode = 'off' + assert.equal(termineAus(), true) +}) + +test('termineFuerKunde: off sperrt alle, auch mit Stern in der Liste', () => { + config.termine.mode = 'off' + config.termine.pilotEmails = ['*', 'kenso.gri@gmail.com'] + assert.equal(termineFuerKunde('kenso.gri@gmail.com'), false) + assert.equal(termineFuerKunde('jemand@example.com'), false) +}) + +test('termineFuerKunde: pilot erlaubt nur Adressen der Liste, Schreibweise egal', () => { + config.termine.mode = 'pilot' + config.termine.pilotEmails = ['kenso.gri@gmail.com'] + assert.equal(termineFuerKunde('KENSO.gri@gmail.com '), true) + assert.equal(termineFuerKunde('kenso.gri@gmail.com'), true) + assert.equal(termineFuerKunde('jemand@example.com'), false) + assert.equal(termineFuerKunde('kenso.gri@gmail.com.evil.de'), false) +}) + +test('termineFuerKunde: pilot mit Stern erlaubt alle, mit leerer Liste niemanden', () => { + config.termine.mode = 'pilot' + config.termine.pilotEmails = ['*'] + assert.equal(termineFuerKunde('jemand@example.com'), true) + config.termine.pilotEmails = [] + assert.equal(termineFuerKunde('kenso.gri@gmail.com'), false) +}) + +test('termineFuerKunde: pilot ohne E-Mail-Adresse ist false', () => { + config.termine.mode = 'pilot' + config.termine.pilotEmails = ['kenso.gri@gmail.com'] + for (const email of [undefined, null, '', ' ']) assert.equal(termineFuerKunde(email), false) +}) + +test('termineFuerKunde: on gilt fuer alle ohne E-Mail-Filter', () => { + config.termine.mode = 'on' + config.termine.pilotEmails = ['kenso.gri@gmail.com'] + assert.equal(termineFuerKunde('jemand@example.com'), true) + assert.equal(termineFuerKunde(undefined), true) +}) diff --git a/test/termineSetup.test.js b/test/termineSetup.test.js new file mode 100644 index 0000000..c8b779a --- /dev/null +++ b/test/termineSetup.test.js @@ -0,0 +1,296 @@ +import { test, after } from 'node:test' +import assert from 'node:assert/strict' +import { startAppwriteMock } from './support/appwriteMock.js' +import { startFakeStripe } from './support/fakeStripe.js' +import { useTestEnv } from './support/testEnv.js' +import { schemaKeys } from './support/schema.js' +import { TERMINE_COLLECTIONS, TERMINE_DATETIMES } from '../server/services/termine/schema.js' + +// Das Skript und die Konfiguration laden erst nach useTestEnv (Endpunkt des Nachbaus), daher dynamische Imports +const aw = await startAppwriteMock({ schema: { termineConfig: schemaKeys('termineConfig') } }) +const st = await startFakeStripe() +useTestEnv({ appwriteUrl: aw.url, stripeUrl: st.url }) +const { config } = await import('../server/config.js') +const { main } = await import('../scripts/termine-setup.mjs') +const { createDocument, updateDocument, getDocument } = await import('../server/services/appwriteAdmin.js') +after(() => Promise.all([aw.close(), st.close()])) + +const NAMES = ['termineConfig', 'termineBookings', 'termineClaims', 'termineOutbox'] +const keysOf = (name) => TERMINE_COLLECTIONS[name].attributes.map((a) => a.key) + +/** + * Appwrite-Client mit Zustand: Attribute gibt es nur in vorhandenen Collections, Indizes nur auf vorhandenen + * Attributen (wie Appwrite). `initial` = { collectionId: { attrs: [...], indexes: [...] } }. + */ +function fakeClient(initial = {}) { + const state = new Map( + Object.entries(initial).map(([id, c]) => [id, { attrs: new Map((c.attrs || []).map((key) => [key, null])), indexes: new Set(c.indexes || []) }]), + ) + const calls = { collections: [], attrs: [], indexes: [] } + 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 quiet = () => {} +const expectedAttrs = NAMES.flatMap((name) => keysOf(name).map((key) => `${config.collections[name]}.${key}`)) +const expectedIndexes = NAMES.flatMap((name) => TERMINE_COLLECTIONS[name].indexes.map((i) => `${config.collections[name]}.${i.key}`)) + +test('Schema: Attribute je Collection wie in der Spezifikation', () => { + assert.deepEqual(Object.keys(TERMINE_COLLECTIONS), NAMES) + assert.deepEqual(keysOf('termineConfig'), ['customerId', 'projectId', 'einstellung', 'version', 'updatedAt', 'updatedBy']) + assert.deepEqual(keysOf('termineBookings'), [ + 'featureId', 'customerId', 'projectId', 'leistungId', 'leistungName', 'ressourceId', 'ressourceName', + 'startsAt', 'endsAt', 'blockEndsAt', 'status', 'quelle', + 'gastName', 'gastEmail', 'gastTelefon', 'gastNachricht', 'gastZusatz', + 'erinnerung', 'erinnerungGesendetAt', 'heldUntil', 'verifyHash', 'manageHash', + 'bestaetigtAt', 'angenommenAt', 'abgesagtAt', 'abgesagtVon', 'absageGrund', 'widerrufenAt', 'nachweis', + 'preisCent', 'preisArt', 'buchungsart', 'verbraucher', + 'zahlart', 'zahlStatus', 'stripeSessionId', 'stripePaymentIntent', + 'icsSequenz', 'createdAt', 'updatedAt', + ]) + assert.deepEqual(keysOf('termineClaims'), ['featureId', 'ressourceId', 'bookingId', 'zelle', 'bis']) + assert.deepEqual(keysOf('termineOutbox'), [ + 'featureId', 'bookingId', 'art', 'an', 'fromName', 'replyTo', 'subject', 'html', 'text', 'ics', 'icsMethod', + 'status', 'versuche', 'naechsterVersuch', 'gesendetAt', 'fehler', 'createdAt', + ]) +}) + +test('Schema: Typen und Groessen', () => { + const byKey = (name) => Object.fromEntries(TERMINE_COLLECTIONS[name].attributes.map((a) => [a.key, a])) + const settings = byKey('termineConfig') + assert.equal(settings.einstellung.size, 200000) + assert.equal(settings.version.type, 'integer') + assert.equal(settings.updatedAt.type, 'datetime') + assert.equal(settings.updatedBy.size, 100) + assert.equal(settings.projectId.size, 64) + + const bookings = byKey('termineBookings') + const sizes = { + featureId: 64, customerId: 64, projectId: 64, leistungName: 120, ressourceName: 80, status: 16, quelle: 16, + gastName: 100, gastEmail: 254, gastTelefon: 40, gastNachricht: 500, gastZusatz: 2000, verifyHash: 64, manageHash: 64, + abgesagtVon: 16, absageGrund: 300, nachweis: 4000, preisArt: 8, buchungsart: 8, zahlart: 8, zahlStatus: 16, + stripeSessionId: 128, stripePaymentIntent: 64, + } + for (const [key, size] of Object.entries(sizes)) { + assert.deepEqual([bookings[key].type, bookings[key].size], ['string', size], `termineBookings.${key}`) + } + for (const key of ['preisCent', 'icsSequenz']) assert.equal(bookings[key].type, 'integer', key) + for (const key of ['erinnerung', 'verbraucher']) assert.equal(bookings[key].type, 'boolean', key) + for (const key of ['startsAt', 'endsAt', 'blockEndsAt', 'heldUntil', 'erinnerungGesendetAt', 'bestaetigtAt', 'angenommenAt', 'abgesagtAt', 'widerrufenAt', 'createdAt', 'updatedAt']) { + assert.equal(bookings[key].type, 'datetime', key) + } + + const outbox = byKey('termineOutbox') + assert.deepEqual( + [outbox.an.size, outbox.fromName.size, outbox.replyTo.size, outbox.subject.size, outbox.html.size, outbox.text.size, outbox.ics.size, outbox.icsMethod.size, outbox.fehler.size], + [254, 120, 254, 300, 100000, 50000, 20000, 8, 300], + ) + assert.equal(outbox.versuche.type, 'integer') + const claims = byKey('termineClaims') + assert.deepEqual([claims.zelle.type, claims.bis.type], ['datetime', 'datetime']) +}) + +test('Schema: jedes Attribut ist optional, hat eine gueltige Form und einen gueltigen Schluessel', () => { + for (const name of NAMES) { + const { attributes } = TERMINE_COLLECTIONS[name] + assert.equal(new Set(attributes.map((a) => a.key)).size, attributes.length, `${name}: doppelte Schluessel`) + for (const attr of attributes) { + assert.match(attr.key, /^[A-Za-z][A-Za-z0-9]{0,35}$/, `${name}.${attr.key}`) + assert.equal(attr.required, false, `${name}.${attr.key}`) + assert.ok(['string', 'integer', 'boolean', 'datetime'].includes(attr.type), `${name}.${attr.key}: Typ ${attr.type}`) + if (attr.type === 'string') assert.ok(Number.isInteger(attr.size) && attr.size > 0, `${name}.${attr.key}: Groesse`) + else assert.equal('size' in attr, false, `${name}.${attr.key}: Groesse nur bei Text`) + } + } +}) + +test('Schema: Indizes wie in der Spezifikation und nur auf vorhandenen Attributen', () => { + const indexes = (name) => TERMINE_COLLECTIONS[name].indexes.map((i) => [i.key, ...i.attributes]) + assert.deepEqual(indexes('termineConfig'), []) + assert.deepEqual(indexes('termineBookings'), [ + ['idx_feature_start', 'featureId', 'startsAt'], + ['idx_status_held', 'status', 'heldUntil'], + ['idx_feature_email', 'featureId', 'gastEmail'], + ['idx_verify', 'verifyHash'], + ['idx_manage', 'manageHash'], + ['idx_status_start', 'status', 'startsAt'], + ]) + assert.deepEqual(indexes('termineClaims'), [['idx_booking', 'bookingId'], ['idx_bis', 'bis']]) + assert.deepEqual(indexes('termineOutbox'), [['idx_status_next', 'status', 'naechsterVersuch']]) + for (const name of NAMES) { + for (const index of TERMINE_COLLECTIONS[name].indexes) { + assert.equal(index.type, 'key') + assert.ok(index.attributes.every((key) => keysOf(name).includes(key)), `${name}.${index.key}`) + } + } +}) + +test('Schema: TERMINE_DATETIMES nennt je Collection genau die datetime-Attribute', () => { + assert.deepEqual(TERMINE_DATETIMES, { + termineConfig: ['updatedAt'], + termineBookings: [ + 'startsAt', 'endsAt', 'blockEndsAt', 'erinnerungGesendetAt', 'heldUntil', 'bestaetigtAt', 'angenommenAt', + 'abgesagtAt', 'widerrufenAt', 'createdAt', 'updatedAt', + ], + termineClaims: ['zelle', 'bis'], + termineOutbox: ['naechsterVersuch', 'gesendetAt', 'createdAt'], + }) +}) + +test('schemaKeys kennt die Termine-Collections: einstellung ja, data nein', () => { + const keys = schemaKeys('termineConfig') + assert.ok(keys.includes('einstellung')) + assert.ok(!keys.includes('data')) + assert.deepEqual(keys, keysOf('termineConfig')) + assert.deepEqual(schemaKeys('termineOutbox'), keysOf('termineOutbox')) + assert.ok(schemaKeys('termineOutbox').includes('icsMethod')) + assert.deepEqual(schemaKeys('termineClaims'), ['featureId', 'ressourceId', 'bookingId', 'zelle', 'bis']) + assert.ok(schemaKeys('termineBookings').includes('blockEndsAt')) + // bestehende Setup-Skripte funktionieren weiter + assert.ok(schemaKeys('subscriptions').length > 0) + assert.throws(() => schemaKeys('gibtEsNicht'), /fehlt im Setup-Skript/) +}) + +test('Rundreise: Einstellung mit einstellung/version/updatedBy anlegen, aendern und zuruecklesen', async () => { + const collection = config.collections.termineConfig + const einstellung = JSON.stringify({ schema: 1, betrieb: { name: 'Salon Müller' }, ressourcen: [] }) + const created = await createDocument( + collection, + { customerId: 'c1', projectId: 'p1', einstellung, version: 1, updatedAt: '2026-10-02T10:00:00.000Z', updatedBy: 'kunde' }, + 'feature-1', + ) + assert.equal(created.$id, 'feature-1') + + const geaendert = JSON.stringify({ schema: 1, betrieb: { name: 'Salon Müller & Söhne' }, ressourcen: [] }) + await updateDocument(collection, 'feature-1', { einstellung: geaendert, version: 2, updatedAt: '2026-10-02T11:00:00.000Z', updatedBy: 'team' }) + + const doc = await getDocument(collection, 'feature-1') + assert.equal(doc.einstellung, geaendert) + assert.equal(doc.version, 2) + assert.equal(doc.updatedBy, 'team') + assert.equal(doc.customerId, 'c1') + assert.equal(JSON.parse(doc.einstellung).betrieb.name, 'Salon Müller & Söhne') +}) + +test('Rundreise: unbekanntes Attribut lehnt der Nachbau ab wie Appwrite (Schema-Pruefung greift)', async () => { + await assert.rejects( + () => createDocument(config.collections.termineConfig, { customerId: 'c1', fremd: 'x' }, 'feature-2'), + /Unknown attribute/, + ) +}) + +test('Konfiguration: Collection-IDs der Termine-Collections', () => { + assert.deepEqual( + NAMES.map((name) => config.collections[name]), + NAMES, + ) +}) + +test('main legt auf leerer Datenbank 4 Collections, alle Attribute und Indizes an', async () => { + const client = fakeClient() + const result = await main({ client, log: quiet }) + assert.deepEqual(client.calls.collections, NAMES.map((id) => ({ id, name: id }))) + assert.deepEqual([...client.calls.attrs].sort(), [...expectedAttrs].sort()) + assert.deepEqual([...client.calls.indexes].sort(), [...expectedIndexes].sort()) + assert.equal(result.missing.length, expectedAttrs.length) + assert.deepEqual(result.missingCollections, NAMES) + assert.equal(result.missingIndexes.length, expectedIndexes.length) + // jedes Attribut mit Typ und Groesse im Anfragekoerper, Datum ohne Groesse + const bookings = client.state.get('termineBookings').attrs + assert.deepEqual(bookings.get('gastEmail'), { key: 'gastEmail', type: 'string', size: 254, required: false }) + assert.deepEqual(bookings.get('startsAt'), { key: 'startsAt', type: 'datetime', required: false }) + assert.deepEqual(bookings.get('icsSequenz'), { key: 'icsSequenz', type: 'integer', required: false }) + assert.deepEqual(bookings.get('verbraucher'), { key: 'verbraucher', type: 'boolean', 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, { collections: [], attrs: [], indexes: [] }) + assert.deepEqual(result, { missing: [], missingCollections: [], missingIndexes: [] }) +}) + +test('main: legt nur fehlende Attribute und Indizes einer vorhandenen Collection an', async () => { + const client = fakeClient({ + termineClaims: { attrs: ['featureId', 'ressourceId', 'bookingId'], indexes: ['idx_booking'] }, + }) + await main({ client, log: quiet }) + assert.ok(!client.calls.collections.some((c) => c.id === 'termineClaims')) + assert.deepEqual( + client.calls.attrs.filter((k) => k.startsWith('termineClaims.')), + ['termineClaims.zelle', 'termineClaims.bis'], + ) + assert.deepEqual( + client.calls.indexes.filter((k) => k.startsWith('termineClaims.')), + ['termineClaims.idx_bis'], + ) + assert.equal(client.calls.collections.length, 3) +}) + +test('main --check legt nichts an und meldet Fehlendes', async () => { + const client = fakeClient() + const lines = [] + const result = await main({ check: true, client, log: (line) => lines.push(line) }) + assert.deepEqual(client.calls, { collections: [], attrs: [], indexes: [] }) + assert.equal(client.state.size, 0) + assert.deepEqual(result.missingCollections, NAMES) + assert.equal(result.missing.length, expectedAttrs.length) + assert.equal(result.missingIndexes.length, expectedIndexes.length) + assert.ok(lines.some((line) => line.includes('termineBookings') && line.includes('FEHLT'))) +}) + +test('main --check meldet bei vollstaendigem Stand nichts', async () => { + const client = fakeClient() + await main({ client, log: quiet }) + const result = await main({ check: true, client, log: quiet }) + assert.deepEqual(result, { missing: [], missingCollections: [], missingIndexes: [] }) +}) + +test('main --check meldet ein einzelnes fehlendes Attribut', async () => { + const client = fakeClient() + await main({ client, log: quiet }) + client.state.get('termineOutbox').attrs.delete('icsMethod') + const result = await main({ check: true, client, log: quiet }) + assert.deepEqual(result.missing.map((a) => `${a.collection}.${a.key}`), ['termineOutbox.icsMethod']) + assert.deepEqual(result.missingCollections, []) +})