Files
Webklar-Kundenbereich/test/unterkunftSetup.test.js
T

236 lines
13 KiB
JavaScript

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 { UNTERKUNFT_COLLECTIONS, UNTERKUNFT_DATETIMES } from '../server/services/unterkunft/schema.js'
const aw = await startAppwriteMock({ schema: { ukEinstellungen: schemaKeys('ukEinstellungen') }, datetimes: UNTERKUNFT_DATETIMES })
const st = await startFakeStripe()
useTestEnv({ appwriteUrl: aw.url, stripeUrl: st.url })
const { config } = await import('../server/config.js')
const { main } = await import('../scripts/unterkunft-setup.mjs')
const { createDocument, updateDocument, getDocument } = await import('../server/services/appwriteAdmin.js')
after(() => Promise.all([aw.close(), st.close()]))
const NAMES = ['ukUnterkuenfte', 'ukPreise', 'ukSperren', 'ukAnfragen', 'ukRechnungen', 'ukEinstellungen']
const keysOf = (name) => UNTERKUNFT_COLLECTIONS[name].attributes.map((a) => a.key)
const byKey = (name) => Object.fromEntries(UNTERKUNFT_COLLECTIONS[name].attributes.map((a) => [a.key, a]))
/** Appwrite-Client mit Zustand (wie shopSetup.test.js): Attribute nur in vorhandenen Collections, Indizes nur auf vorhandenen Attributen. */
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) => UNTERKUNFT_COLLECTIONS[name].indexes.map((i) => `${config.collections[name]}.${i.key}`))
test('Schema: Attribute je Collection wie in der Spezifikation', () => {
assert.deepEqual(Object.keys(UNTERKUNFT_COLLECTIONS), NAMES)
assert.deepEqual(keysOf('ukUnterkuenfte'), [
'featureId', 'customerId', 'projectId', 'name', 'beschreibung', 'maxPersonen', 'mindestNaechte', 'checkIn', 'checkOut',
'sort', 'aktiv', 'icalImporte', 'icalExportToken',
])
assert.deepEqual(keysOf('ukPreise'), [
'unterkunftId', 'featureId', 'staffeln', 'reinigungCent', 'personenInklusive', 'aufpreisPersonNachtCent',
'direktrabattProzent', 'steuerart', 'ustUebernachtung', 'ustReinigung', 'fristTage', 'stornobedingungen',
])
assert.deepEqual(keysOf('ukSperren'), ['unterkunftId', 'featureId', 'von', 'bis', 'quelle', 'notiz'])
assert.deepEqual(keysOf('ukAnfragen'), [
'featureId', 'customerId', 'projectId', 'unterkunftId', 'nummer', 'von', 'bis', 'personen', 'status', 'gast',
'rechnungsadresse', 'posten', 'summen', 'nachrichtVermieter', 'fristAt', 'tokenHash', 'zahlart', 'bezahltVia', 'bezahltAt',
'stripeSessionId', 'stripePaymentIntentId', 'erstattetCent', 'stornoGrund', 'stornobedingungenText', 'rechtstexteFassung',
'ipHash', 'freigegebenAt', 'gebuchtAt', 'abgelehntAt', 'abgelaufenAt', 'storniertAt', 'rechnungId', 'anonymisiertAt',
])
assert.deepEqual(keysOf('ukRechnungen'), ['featureId', 'anfrageId', 'art', 'nummer', 'datum', 'bruttoCent', 'inhalt'])
assert.deepEqual(keysOf('ukEinstellungen'), [
'featureId', 'firma', 'inhaber', 'strasse', 'plz', 'ort', 'email', 'telefon', 'steuernummer', 'ustId', 'iban', 'bic', 'bank',
'rechnungsPraefix', 'rechnungZaehler', 'akzentfarbe', 'stripeAccountId', 'stripeStatus', 'onlineZahlung', 'rechnungAuftragAt',
'anfrage', 'anfrageStatus', 'anfrageAt', 'anfrageEntschiedenAt', 'anfrageEntschiedenVon', 'anfrageBegruendung', 'icalFehlerMailAt',
])
})
test('Schema: Typen und Groessen', () => {
const sizes = {
ukUnterkuenfte: { featureId: 36, name: 120, beschreibung: 500, checkIn: 5, checkOut: 5, icalImporte: 8000, icalExportToken: 64 },
ukPreise: { unterkunftId: 36, staffeln: 2000, steuerart: 20, stornobedingungen: 5000 },
ukSperren: { von: 10, bis: 10, quelle: 60, notiz: 200 },
ukAnfragen: {
nummer: 12, status: 12, gast: 3000, rechnungsadresse: 1500, posten: 8000, summen: 1000, nachrichtVermieter: 2000,
tokenHash: 64, zahlart: 8, bezahltVia: 8, stripeSessionId: 100, stripePaymentIntentId: 100, stornoGrund: 500,
stornobedingungenText: 5000, rechtstexteFassung: 20, ipHash: 16, rechnungId: 36,
},
ukRechnungen: { art: 8, nummer: 24, datum: 10, inhalt: 20000 },
ukEinstellungen: {
firma: 150, plz: 10, ort: 100, email: 200, telefon: 50, steuernummer: 30, ustId: 20, iban: 34, bic: 11, bank: 100,
rechnungsPraefix: 8, rechnungZaehler: 100, akzentfarbe: 7, stripeAccountId: 40, stripeStatus: 4000, anfrage: 2000,
anfrageStatus: 16, anfrageEntschiedenVon: 120, anfrageBegruendung: 1000,
},
}
for (const [name, map] of Object.entries(sizes)) {
for (const [key, size] of Object.entries(map)) assert.deepEqual([byKey(name)[key].type, byKey(name)[key].size], ['string', size], `${name}.${key}`)
}
const ints = {
ukUnterkuenfte: ['maxPersonen', 'mindestNaechte', 'sort'],
ukPreise: ['reinigungCent', 'personenInklusive', 'aufpreisPersonNachtCent', 'direktrabattProzent', 'ustUebernachtung', 'ustReinigung', 'fristTage'],
ukAnfragen: ['personen', 'erstattetCent'],
ukRechnungen: ['bruttoCent'],
}
for (const [name, keys] of Object.entries(ints)) for (const key of keys) assert.equal(byKey(name)[key].type, 'integer', `${name}.${key}`)
assert.equal(byKey('ukUnterkuenfte').aktiv.type, 'boolean')
assert.equal(byKey('ukEinstellungen').onlineZahlung.type, 'boolean')
})
test('Schema: jedes Attribut ist optional, hat gueltige Form und Schluessel (kein Feld data)', () => {
for (const name of NAMES) {
const { attributes } = UNTERKUNFT_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.notEqual(attr.key, 'data', `${name}: Feld data ist verboten`)
assert.equal(attr.required, false, `${name}.${attr.key}`)
assert.ok(['string', 'integer', 'boolean', 'datetime'].includes(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 idx = (name) => UNTERKUNFT_COLLECTIONS[name].indexes.map((i) => i.attributes.join('+'))
assert.deepEqual(idx('ukUnterkuenfte'), ['featureId', 'icalExportToken'])
assert.deepEqual(idx('ukPreise'), ['unterkunftId'])
assert.deepEqual(idx('ukSperren'), ['unterkunftId', 'unterkunftId+quelle', 'bis'])
assert.deepEqual(idx('ukAnfragen'), ['featureId', 'unterkunftId', 'unterkunftId+status', 'status', 'bis'])
assert.deepEqual(idx('ukRechnungen'), ['featureId', 'anfrageId', 'featureId+nummer'])
for (const name of NAMES) {
const keys = new Set()
for (const index of UNTERKUNFT_COLLECTIONS[name].indexes) {
assert.equal(index.type, name === 'ukRechnungen' && index.key === 'uniq_feature_nummer' ? 'unique' : 'key')
assert.ok(!keys.has(index.key), `${name}: doppelter Index ${index.key}`)
keys.add(index.key)
assert.ok(index.attributes.every((key) => keysOf(name).includes(key)), `${name}.${index.key}`)
}
}
})
test('Schema: UNTERKUNFT_DATETIMES nennt je Collection genau die datetime-Attribute', () => {
assert.deepEqual(Object.keys(UNTERKUNFT_DATETIMES), NAMES)
assert.deepEqual(UNTERKUNFT_DATETIMES.ukAnfragen, [
'fristAt', 'bezahltAt', 'freigegebenAt', 'gebuchtAt', 'abgelehntAt', 'abgelaufenAt', 'storniertAt', 'anonymisiertAt',
])
assert.deepEqual(UNTERKUNFT_DATETIMES.ukUnterkuenfte, [])
assert.deepEqual(UNTERKUNFT_DATETIMES.ukEinstellungen, ['rechnungAuftragAt', 'anfrageAt', 'anfrageEntschiedenAt', 'icalFehlerMailAt'])
})
test('schemaKeys kennt die Collections; bestehende Setup-Skripte funktionieren weiter', () => {
for (const name of NAMES) assert.deepEqual(schemaKeys(name), keysOf(name))
assert.ok(schemaKeys('shopConfig').includes('einstellungen'))
assert.ok(schemaKeys('subscriptions').length > 0)
assert.throws(() => schemaKeys('gibtEsNicht'), /fehlt im Setup-Skript/)
})
test('Rundreise: Dokument mit Datum anlegen, aendern, lesen; unbekanntes Attribut wird abgelehnt', async () => {
const collection = config.collections.ukEinstellungen
const created = await createDocument(collection, { featureId: 'f1', firma: 'Haus Muster', onlineZahlung: false, anfrageAt: '2026-10-07T10:00:00.000Z' }, 'f1')
assert.equal(created.$id, 'f1')
await updateDocument(collection, 'f1', { onlineZahlung: true, anfrageStatus: 'offen' })
const doc = await getDocument(collection, 'f1')
assert.equal(doc.onlineZahlung, true)
assert.equal(doc.firma, 'Haus Muster')
await assert.rejects(() => createDocument(collection, { featureId: 'f2', fremd: 'x' }, 'f2'), /Unknown attribute/)
})
test('Konfiguration: Collection-IDs', () => {
assert.deepEqual(NAMES.map((name) => config.collections[name]), NAMES)
})
test('main legt auf leerer Datenbank 6 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)
assert.deepEqual(client.state.get('ukAnfragen').attrs.get('fristAt'), { key: 'fristAt', type: 'datetime', required: false })
assert.deepEqual(client.state.get('ukAnfragen').attrs.get('gast'), { key: 'gast', type: 'string', size: 3000, 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 --check legt nichts an und meldet alle sechs Collections als FEHLT', 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)
for (const name of NAMES) assert.ok(lines.some((line) => line.includes(name) && line.includes('FEHLT')), name)
})
test('main --check meldet bei vollstaendigem Stand nichts und ein einzelnes Fehlendes genau', async () => {
const client = fakeClient()
await main({ client, log: quiet })
assert.deepEqual(await main({ check: true, client, log: quiet }), { missing: [], missingCollections: [], missingIndexes: [] })
client.state.get('ukAnfragen').attrs.delete('anonymisiertAt')
client.state.get('ukSperren').indexes.delete('idx_unterkunft_quelle')
const result = await main({ check: true, client, log: quiet })
assert.deepEqual(result.missing.map((a) => `${a.collection}.${a.key}`), ['ukAnfragen.anonymisiertAt'])
assert.deepEqual(result.missingIndexes.map((i) => `${i.collection}.${i.key}`), ['ukSperren.idx_unterkunft_quelle'])
})