K24–K26 sind seit dem Webshop-Livegang (main) vergeben; der Mail-Lader sucht die Vorlage über den Dateianfang, doppelte Nummern hätten die falsche Mail geschickt. Das Feld ist noch nicht in der Produktion angelegt (zeiten-setup.mjs lief noch nicht), daher jetzt ein sprechender Name. Spec und Plan behalten die alten Nummern (Hinweis oben im Dokument). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
271 lines
15 KiB
JavaScript
271 lines
15 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 { ZEITEN_COLLECTIONS, ZEITEN_DATETIMES, ZEITEN_FEATURE_ATTRIBUTES } from '../server/services/zeiten/schema.js'
|
|
|
|
// Das Skript und die Konfiguration laden erst nach useTestEnv (Endpunkt des Nachbaus), daher dynamische Imports
|
|
const aw = await startAppwriteMock({ schema: { oeffnungszeiten: schemaKeys('oeffnungszeiten') }, datetimes: ZEITEN_DATETIMES })
|
|
const st = await startFakeStripe()
|
|
useTestEnv({ appwriteUrl: aw.url, stripeUrl: st.url })
|
|
const { config } = await import('../server/config.js')
|
|
const { main } = await import('../scripts/zeiten-setup.mjs')
|
|
const { createDocument, updateDocument, getDocument } = await import('../server/services/appwriteAdmin.js')
|
|
after(() => Promise.all([aw.close(), st.close()]))
|
|
|
|
const NAMES = ['oeffnungszeiten', 'zeitenErinnerungen']
|
|
const FEATURE_KEYS = ['unlockedBy', 'aboEndeAt', 'einbau', 'behaltenSessionId', 'einschaltMailAt']
|
|
const keysOf = (name) => ZEITEN_COLLECTIONS[name].attributes.map((a) => a.key)
|
|
|
|
/**
|
|
* Appwrite-Client mit Zustand (wie in termineSetup.test.js): Attribute gibt es nur in vorhandenen Collections,
|
|
* Indizes nur auf vorhandenen Attributen. `initial` = { collectionId: { attrs: [...], indexes: [...] } }.
|
|
* portalFeatures gibt es immer (legt setup-abo-collections.mjs an), mit den Feldern, die schon da sind.
|
|
*/
|
|
function fakeClient(initial = {}) {
|
|
const start = { portalFeatures: { attrs: ['customerId', 'projectId', 'featureKey', 'state'] }, ...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 = { 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 featuresId = config.collections.portalFeatures
|
|
const expectedAttrs = [
|
|
...NAMES.flatMap((name) => keysOf(name).map((key) => `${config.collections[name]}.${key}`)),
|
|
...FEATURE_KEYS.map((key) => `${featuresId}.${key}`),
|
|
]
|
|
const expectedIndexes = NAMES.flatMap((name) => ZEITEN_COLLECTIONS[name].indexes.map((i) => `${config.collections[name]}.${i.key}`))
|
|
|
|
test('oeffnungszeiten hat die Felder aus Spec 2.1', () => {
|
|
assert.deepEqual(Object.keys(ZEITEN_COLLECTIONS), NAMES)
|
|
const keys = keysOf('oeffnungszeiten')
|
|
for (const key of ['customerId', 'projectId', 'featureId', 'version', 'daten', 'teamVersion', 'team', 'ersatzHash', 'updatedAt', 'updatedBy']) {
|
|
assert.ok(keys.includes(key), key)
|
|
}
|
|
assert.equal(keys.length, 10)
|
|
|
|
const byKey = Object.fromEntries(ZEITEN_COLLECTIONS.oeffnungszeiten.attributes.map((a) => [a.key, a]))
|
|
assert.deepEqual(byKey.daten, { key: 'daten', type: 'string', size: 40000, required: false })
|
|
assert.deepEqual(byKey.team, { key: 'team', type: 'string', size: 2000, required: false })
|
|
assert.deepEqual(byKey.ersatzHash, { key: 'ersatzHash', type: 'string', size: 64, required: false })
|
|
assert.deepEqual(byKey.updatedBy, { key: 'updatedBy', type: 'string', size: 64, required: false })
|
|
for (const key of ['customerId', 'projectId', 'featureId']) assert.deepEqual([byKey[key].type, byKey[key].size], ['string', 64], key)
|
|
for (const key of ['version', 'teamVersion']) assert.equal(byKey[key].type, 'integer', key)
|
|
assert.equal(byKey.updatedAt.type, 'datetime')
|
|
// Löschung beim Kunden-Löschen liest über customerId
|
|
assert.deepEqual(ZEITEN_COLLECTIONS.oeffnungszeiten.indexes, [{ key: 'idx_customer', type: 'key', attributes: ['customerId'] }])
|
|
})
|
|
|
|
test('daten fasst 32 KB JSON', () => {
|
|
const daten = ZEITEN_COLLECTIONS.oeffnungszeiten.attributes.find((a) => a.key === 'daten')
|
|
assert.ok(daten.size >= 40000, `daten.size ${daten.size}`)
|
|
// 32 KB Spielraum auch bei JSON-Maskierung von Umlauten und Anführungszeichen
|
|
assert.ok(daten.size >= 32 * 1024)
|
|
})
|
|
|
|
test('zeitenErinnerungen: featureId, datum, createdAt', () => {
|
|
assert.deepEqual(keysOf('zeitenErinnerungen'), ['featureId', 'datum', 'createdAt'])
|
|
const byKey = Object.fromEntries(ZEITEN_COLLECTIONS.zeitenErinnerungen.attributes.map((a) => [a.key, a]))
|
|
assert.deepEqual(byKey.featureId, { key: 'featureId', type: 'string', size: 64, required: false })
|
|
assert.deepEqual(byKey.datum, { key: 'datum', type: 'string', size: 10, required: false })
|
|
assert.deepEqual(byKey.createdAt, { key: 'createdAt', type: 'datetime', required: false })
|
|
assert.deepEqual(ZEITEN_COLLECTIONS.zeitenErinnerungen.indexes, [
|
|
{ key: 'idx_datum', type: 'key', attributes: ['datum'] },
|
|
// Task 9 loescht die Merker einer Funktion per featureId (Appwrite verlangt dafuer einen Index)
|
|
{ key: 'idx_feature', type: 'key', attributes: ['featureId'] },
|
|
])
|
|
})
|
|
|
|
test('portalFeatures bekommt unlockedBy(8), aboEndeAt, einbau(12), behaltenSessionId(128), einschaltMailAt', () => {
|
|
assert.deepEqual(ZEITEN_FEATURE_ATTRIBUTES, [
|
|
{ key: 'unlockedBy', type: 'string', size: 8, required: false },
|
|
{ key: 'aboEndeAt', type: 'datetime', required: false },
|
|
{ key: 'einbau', type: 'string', size: 12, required: false },
|
|
{ key: 'behaltenSessionId', type: 'string', size: 128, required: false },
|
|
{ key: 'einschaltMailAt', type: 'datetime', required: false },
|
|
])
|
|
})
|
|
|
|
test('Schema: jedes Attribut ist optional, hat eine gültige Form; Indizes nur auf vorhandenen Attributen', () => {
|
|
for (const name of NAMES) {
|
|
const { attributes, indexes } = ZEITEN_COLLECTIONS[name]
|
|
assert.equal(new Set(attributes.map((a) => a.key)).size, attributes.length, `${name}: doppelte Schlüssel`)
|
|
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}: Größe`)
|
|
else assert.equal('size' in attr, false, `${name}.${attr.key}: Größe nur bei Text`)
|
|
}
|
|
for (const index of indexes) {
|
|
assert.equal(index.type, 'key')
|
|
assert.ok(index.attributes.every((key) => keysOf(name).includes(key)), `${name}.${index.key}`)
|
|
}
|
|
}
|
|
for (const attr of ZEITEN_FEATURE_ATTRIBUTES) {
|
|
assert.match(attr.key, /^[A-Za-z][A-Za-z0-9]{0,35}$/, attr.key)
|
|
assert.equal(attr.required, false, attr.key)
|
|
if (attr.type === 'string') assert.ok(Number.isInteger(attr.size) && attr.size > 0, `${attr.key}: Größe`)
|
|
else assert.equal('size' in attr, false, `${attr.key}: Größe nur bei Text`)
|
|
}
|
|
})
|
|
|
|
test('ZEITEN_DATETIMES nennt je Collection genau die datetime-Attribute', () => {
|
|
assert.deepEqual(ZEITEN_DATETIMES, { oeffnungszeiten: ['updatedAt'], zeitenErinnerungen: ['createdAt'] })
|
|
})
|
|
|
|
test('schemaKeys liefert die Zeiten-Collections und die neuen portalFeatures-Felder', () => {
|
|
assert.deepEqual(schemaKeys('oeffnungszeiten'), keysOf('oeffnungszeiten'))
|
|
assert.deepEqual(schemaKeys('zeitenErinnerungen'), ['featureId', 'datum', 'createdAt'])
|
|
const features = schemaKeys('portalFeatures')
|
|
for (const key of FEATURE_KEYS) assert.ok(features.includes(key), `portalFeatures.${key}`)
|
|
// bestehende Felder und Setup-Skripte bleiben
|
|
for (const key of ['disabledReason', 'aboEndeMailAt', 'zahlungMeldung', 'unlockedByPurchase']) assert.ok(features.includes(key), key)
|
|
assert.ok(schemaKeys('termineConfig').includes('einstellung'))
|
|
assert.ok(schemaKeys('subscriptions').length > 0)
|
|
assert.throws(() => schemaKeys('gibtEsNicht'), /fehlt im Setup-Skript/)
|
|
})
|
|
|
|
test('Rundreise: Öffnungszeiten anlegen, ändern und zurücklesen; unbekanntes Feld lehnt der Nachbau ab', async () => {
|
|
const collection = config.collections.oeffnungszeiten
|
|
const daten = JSON.stringify({ land: 'RP', plaene: [], feiertage: {}, ausnahmen: [], hinweise: [], kontakt: { an: false } })
|
|
const created = await createDocument(
|
|
collection,
|
|
{ customerId: 'c1', projectId: 'p1', featureId: 'f1', version: 1, daten, teamVersion: 0, updatedAt: '2026-10-04T10:00:00.000Z', updatedBy: 'kunde' },
|
|
'f1',
|
|
)
|
|
assert.equal(created.$id, 'f1')
|
|
await updateDocument(collection, 'f1', { version: 2, updatedBy: 'team:s1', ersatzHash: 'abc' })
|
|
const doc = await getDocument(collection, 'f1')
|
|
assert.deepEqual([doc.version, doc.updatedBy, doc.ersatzHash, doc.daten], [2, 'team:s1', 'abc', daten])
|
|
await assert.rejects(() => createDocument(collection, { customerId: 'c1', fremd: 'x' }, 'f2'), /Unknown attribute/)
|
|
})
|
|
|
|
test('Konfiguration: Collection-IDs der Zeiten-Collections', () => {
|
|
assert.deepEqual(NAMES.map((name) => config.collections[name]), NAMES)
|
|
})
|
|
|
|
test('main legt auf leerer Datenbank 2 Collections, alle Attribute und Indizes an und ergänzt portalFeatures', 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.ok(client.calls.indexes.includes('oeffnungszeiten.idx_customer'))
|
|
assert.ok(client.calls.indexes.includes('zeitenErinnerungen.idx_datum'))
|
|
assert.ok(client.calls.indexes.includes('zeitenErinnerungen.idx_feature'))
|
|
assert.equal(result.missing.length, expectedAttrs.length)
|
|
assert.deepEqual(result.missingCollections, NAMES)
|
|
assert.equal(result.missingIndexes.length, expectedIndexes.length)
|
|
// portalFeatures wird nicht neu angelegt, bekommt aber genau die fünf Felder
|
|
assert.ok(!client.calls.collections.some((c) => c.id === featuresId))
|
|
assert.deepEqual(client.calls.attrs.filter((k) => k.startsWith(`${featuresId}.`)), FEATURE_KEYS.map((key) => `${featuresId}.${key}`))
|
|
const features = client.state.get(featuresId).attrs
|
|
assert.deepEqual(features.get('unlockedBy'), { key: 'unlockedBy', type: 'string', size: 8, required: false })
|
|
assert.deepEqual(features.get('einschaltMailAt'), { key: 'einschaltMailAt', type: 'datetime', 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({
|
|
zeitenErinnerungen: { attrs: ['featureId', 'datum'], indexes: [] },
|
|
portalFeatures: { attrs: ['customerId', 'unlockedBy', 'einbau'] },
|
|
})
|
|
await main({ client, log: quiet })
|
|
assert.ok(!client.calls.collections.some((c) => c.id === 'zeitenErinnerungen'))
|
|
assert.deepEqual(client.calls.attrs.filter((k) => k.startsWith('zeitenErinnerungen.')), ['zeitenErinnerungen.createdAt'])
|
|
assert.deepEqual(
|
|
client.calls.indexes.filter((k) => k.startsWith('zeitenErinnerungen.')),
|
|
['zeitenErinnerungen.idx_datum', 'zeitenErinnerungen.idx_feature'],
|
|
)
|
|
assert.deepEqual(
|
|
client.calls.attrs.filter((k) => k.startsWith(`${featuresId}.`)),
|
|
[`${featuresId}.aboEndeAt`, `${featuresId}.behaltenSessionId`, `${featuresId}.einschaltMailAt`],
|
|
)
|
|
assert.equal(client.calls.collections.length, 1)
|
|
})
|
|
|
|
test('--check meldet fehlende Collections und Felder, ohne zu schreiben', 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, 1, 'nur portalFeatures, nichts angelegt')
|
|
assert.deepEqual([...client.state.get(featuresId).attrs.keys()], ['customerId', 'projectId', 'featureKey', 'state'])
|
|
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('oeffnungszeiten') && line.includes('FEHLT')))
|
|
assert.ok(lines.some((line) => line.includes(`${featuresId}.unlockedBy FEHLT`)), lines.join('\n'))
|
|
assert.ok(lines.some((line) => line.includes('Index oeffnungszeiten.idx_customer FEHLT')))
|
|
})
|
|
|
|
test('--check meldet bei vollständigem Stand nichts und ein einzelnes fehlendes portalFeatures-Feld genau dieses', async () => {
|
|
const client = fakeClient()
|
|
await main({ client, log: quiet })
|
|
assert.deepEqual(await main({ check: true, client, log: quiet }), { missing: [], missingCollections: [], missingIndexes: [] })
|
|
client.state.get(featuresId).attrs.delete('einschaltMailAt')
|
|
const result = await main({ check: true, client, log: quiet })
|
|
assert.deepEqual(result.missing.map((a) => `${a.collection}.${a.key}`), [`${featuresId}.einschaltMailAt`])
|
|
assert.deepEqual(result.missingCollections, [])
|
|
})
|
|
|
|
test('main: fehlt portalFeatures, bricht es mit klarer Meldung ab, ohne etwas anzulegen', async () => {
|
|
const client = fakeClient()
|
|
client.state.delete(featuresId)
|
|
await assert.rejects(() => main({ client, log: quiet }), /portalFeatures.*fehlt/)
|
|
assert.deepEqual(client.calls, { collections: [], attrs: [], indexes: [] })
|
|
})
|