I-6: Neue Collection shopRechtstexteArchiv (ID r + 35 Hex aus sha256(shopId + hash)); das Bestaetigen legt die Fassung samt Versand-/Zahlungstext und Gewaehrleistungstext ab, G09 zeigt die Fassung zum rechtstexteHash der Bestellung (Rueckfall mit Warnung auf die aktuell bestaetigte), loescheShopDaten loescht das Archiv mit. I-7: Grenzen AGB 20000, Belehrung 12000, Formular 3000 plus Pruefung der maskierten Laenge beim Speichern; G09 ersetzt die AGB nie mehr durch einen Link, sondern scheitert (Marker bleibt offen, wird wiederholt). Test mit Texten in Hoechstlaenge gegen die Grenzen der Warteschlange. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
294 lines
15 KiB
JavaScript
294 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 { SHOP_COLLECTIONS, SHOP_DATETIMES } from '../server/services/shop/schema.js'
|
|
|
|
// Das Skript und die Konfiguration laden erst nach useTestEnv (Endpunkt des Nachbaus), daher dynamische Imports
|
|
const aw = await startAppwriteMock({ schema: { shopConfig: schemaKeys('shopConfig') }, datetimes: SHOP_DATETIMES })
|
|
const st = await startFakeStripe()
|
|
useTestEnv({ appwriteUrl: aw.url, stripeUrl: st.url })
|
|
const { config } = await import('../server/config.js')
|
|
const { main } = await import('../scripts/shop-setup.mjs')
|
|
const { createDocument, updateDocument, getDocument } = await import('../server/services/appwriteAdmin.js')
|
|
after(() => Promise.all([aw.close(), st.close()]))
|
|
|
|
const NAMES = ['shopConfig', 'shopProducts', 'shopOrders', 'shopWiderrufe', 'shopRechtstexteArchiv']
|
|
const keysOf = (name) => SHOP_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) => SHOP_COLLECTIONS[name].indexes.map((i) => `${config.collections[name]}.${i.key}`))
|
|
|
|
test('Schema: Attribute je Collection wie in der Spezifikation', () => {
|
|
assert.deepEqual(Object.keys(SHOP_COLLECTIONS), NAMES)
|
|
assert.deepEqual(keysOf('shopConfig'), [
|
|
'customerId', 'projectId', 'siteKey', 'anfrage', 'anfrageStatus', 'anfrageAt', 'anfrageEntschiedenAt',
|
|
'anfrageEntschiedenVon', 'anfrageBegruendung', 'stripeAccountId', 'stripeStatus', 'einstellungen', 'rechtstexte',
|
|
'rechtstexteBestaetigtAt', 'rechtstexteBestaetigtVon', 'rechtstexteHash', 'geoeffnet', 'geoeffnetAt', 'version',
|
|
])
|
|
assert.deepEqual(keysOf('shopProducts'), ['shopId', 'customerId', 'aktiv', 'sort', 'name', 'produkt'])
|
|
assert.deepEqual(keysOf('shopOrders'), [
|
|
'shopId', 'customerId', 'bestellnummer', 'status', 'tokenHash', 'stripeSessionId', 'paymentIntentId', 'summeCent',
|
|
'erstelltAt', 'ablaufAt', 'bezahltAt', 'kaeuferEmail', 'bestellung', 'anonymisiertAt',
|
|
])
|
|
assert.deepEqual(keysOf('shopWiderrufe'), [
|
|
'shopId', 'customerId', 'bestellnummer', 'name', 'email', 'nachricht', 'eingangAt', 'bestaetigungAt', 'bearbeitetAt', 'orderId',
|
|
])
|
|
})
|
|
|
|
test('Schema: Typen und Groessen', () => {
|
|
const byKey = (name) => Object.fromEntries(SHOP_COLLECTIONS[name].attributes.map((a) => [a.key, a]))
|
|
const shop = byKey('shopConfig')
|
|
const shopSizes = {
|
|
customerId: 36, projectId: 36, siteKey: 16, anfrage: 4000, anfrageStatus: 16, anfrageEntschiedenVon: 255,
|
|
anfrageBegruendung: 1000, stripeAccountId: 64, stripeStatus: 4000, einstellungen: 20000, rechtstexte: 100000,
|
|
rechtstexteBestaetigtVon: 255, rechtstexteHash: 64,
|
|
}
|
|
for (const [key, size] of Object.entries(shopSizes)) {
|
|
assert.deepEqual([shop[key].type, shop[key].size], ['string', size], `shopConfig.${key}`)
|
|
}
|
|
assert.equal(shop.geoeffnet.type, 'boolean')
|
|
assert.equal(shop.version.type, 'integer')
|
|
for (const key of ['anfrageAt', 'anfrageEntschiedenAt', 'rechtstexteBestaetigtAt', 'geoeffnetAt']) assert.equal(shop[key].type, 'datetime', key)
|
|
|
|
const products = byKey('shopProducts')
|
|
assert.deepEqual([products.shopId.size, products.customerId.size, products.name.size, products.produkt.size], [36, 36, 120, 30000])
|
|
assert.equal(products.aktiv.type, 'boolean')
|
|
assert.equal(products.sort.type, 'integer')
|
|
|
|
const orders = byKey('shopOrders')
|
|
const orderSizes = {
|
|
shopId: 36, customerId: 36, bestellnummer: 16, status: 16, tokenHash: 64, stripeSessionId: 128, paymentIntentId: 64,
|
|
kaeuferEmail: 320, bestellung: 60000,
|
|
}
|
|
for (const [key, size] of Object.entries(orderSizes)) {
|
|
assert.deepEqual([orders[key].type, orders[key].size], ['string', size], `shopOrders.${key}`)
|
|
}
|
|
assert.equal(orders.summeCent.type, 'integer')
|
|
for (const key of ['erstelltAt', 'ablaufAt', 'bezahltAt', 'anonymisiertAt']) assert.equal(orders[key].type, 'datetime', key)
|
|
|
|
const widerrufe = byKey('shopWiderrufe')
|
|
assert.deepEqual(
|
|
[widerrufe.shopId.size, widerrufe.customerId.size, widerrufe.bestellnummer.size, widerrufe.name.size, widerrufe.email.size, widerrufe.nachricht.size, widerrufe.orderId.size],
|
|
[36, 36, 32, 200, 320, 2000, 36],
|
|
)
|
|
for (const key of ['eingangAt', 'bestaetigungAt', 'bearbeitetAt']) assert.equal(widerrufe[key].type, 'datetime', key)
|
|
|
|
// I-6: Archiv der bestaetigten Rechtstexte
|
|
assert.deepEqual(keysOf('shopRechtstexteArchiv'), ['shopId', 'customerId', 'hash', 'texte', 'bestaetigtAt', 'bestaetigtVon'])
|
|
const archiv = byKey('shopRechtstexteArchiv')
|
|
assert.deepEqual([archiv.shopId.size, archiv.customerId.size, archiv.hash.size, archiv.texte.size, archiv.bestaetigtVon.size], [36, 36, 64, 100000, 255])
|
|
assert.equal(archiv.bestaetigtAt.type, 'datetime')
|
|
})
|
|
|
|
test('Schema: jedes Attribut ist optional, hat eine gueltige Form und einen gueltigen Schluessel (kein Feld data)', () => {
|
|
for (const name of NAMES) {
|
|
const { attributes } = SHOP_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), `${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) => SHOP_COLLECTIONS[name].indexes.map((i) => [i.key, ...i.attributes])
|
|
assert.deepEqual(indexes('shopConfig'), [
|
|
['idx_customer', 'customerId'],
|
|
['idx_sitekey', 'siteKey'],
|
|
['idx_anfrage', 'anfrageStatus'],
|
|
['idx_account', 'stripeAccountId'],
|
|
])
|
|
assert.deepEqual(indexes('shopProducts'), [['idx_shop', 'shopId', 'sort']])
|
|
assert.deepEqual(indexes('shopOrders'), [
|
|
['idx_shop_status', 'shopId', 'status'],
|
|
['idx_nummer', 'shopId', 'bestellnummer'],
|
|
['idx_session', 'stripeSessionId'],
|
|
['idx_erstellt', 'shopId', 'erstelltAt'],
|
|
])
|
|
assert.deepEqual(indexes('shopWiderrufe'), [['idx_shop', 'shopId', 'eingangAt']])
|
|
assert.deepEqual(indexes('shopRechtstexteArchiv'), [['idx_shop_hash', 'shopId', 'hash']])
|
|
for (const name of NAMES) {
|
|
for (const index of SHOP_COLLECTIONS[name].indexes) {
|
|
assert.equal(index.type, 'key')
|
|
assert.ok(index.attributes.every((key) => keysOf(name).includes(key)), `${name}.${index.key}`)
|
|
}
|
|
}
|
|
})
|
|
|
|
test('Schema: SHOP_DATETIMES nennt je Collection genau die datetime-Attribute', () => {
|
|
assert.deepEqual(SHOP_DATETIMES, {
|
|
shopConfig: ['anfrageAt', 'anfrageEntschiedenAt', 'rechtstexteBestaetigtAt', 'geoeffnetAt'],
|
|
shopProducts: [],
|
|
shopOrders: ['erstelltAt', 'ablaufAt', 'bezahltAt', 'anonymisiertAt'],
|
|
shopWiderrufe: ['eingangAt', 'bestaetigungAt', 'bearbeitetAt'],
|
|
shopRechtstexteArchiv: ['bestaetigtAt'],
|
|
})
|
|
})
|
|
|
|
test('schemaKeys kennt die Shop-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('shopConfig').includes('data'))
|
|
assert.ok(schemaKeys('termineConfig').includes('einstellung'))
|
|
assert.ok(schemaKeys('subscriptions').length > 0)
|
|
assert.throws(() => schemaKeys('gibtEsNicht'), /fehlt im Setup-Skript/)
|
|
})
|
|
|
|
test('Rundreise: Shop-Dokument mit Datum und JSON-Text anlegen, aendern und zuruecklesen', async () => {
|
|
const collection = config.collections.shopConfig
|
|
const einstellungen = JSON.stringify({ schema: 1, betrieb: { name: 'Blumen Müller' } })
|
|
const created = await createDocument(
|
|
collection,
|
|
{ customerId: 'c1', projectId: 'p1', siteKey: 'abc123', anfrageStatus: 'offen', anfrageAt: '2026-10-05T10:00:00.000Z', einstellungen, geoeffnet: false, version: 1 },
|
|
'feature-1',
|
|
)
|
|
assert.equal(created.$id, 'feature-1')
|
|
await updateDocument(collection, 'feature-1', { anfrageStatus: 'angenommen', geoeffnet: true, version: 2 })
|
|
const doc = await getDocument(collection, 'feature-1')
|
|
assert.equal(doc.anfrageStatus, 'angenommen')
|
|
assert.equal(doc.geoeffnet, true)
|
|
assert.equal(doc.version, 2)
|
|
assert.equal(doc.customerId, 'c1')
|
|
assert.equal(JSON.parse(doc.einstellungen).betrieb.name, 'Blumen Müller')
|
|
})
|
|
|
|
test('Rundreise: unbekanntes Attribut lehnt der Nachbau ab wie Appwrite (Schema-Pruefung greift)', async () => {
|
|
await assert.rejects(
|
|
() => createDocument(config.collections.shopConfig, { customerId: 'c1', fremd: 'x' }, 'feature-2'),
|
|
/Unknown attribute/,
|
|
)
|
|
})
|
|
|
|
test('Konfiguration: Collection-IDs der Shop-Collections', () => {
|
|
assert.deepEqual(NAMES.map((name) => config.collections[name]), NAMES)
|
|
})
|
|
|
|
test('main legt auf leerer Datenbank 5 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)
|
|
const orders = client.state.get('shopOrders').attrs
|
|
assert.deepEqual(orders.get('kaeuferEmail'), { key: 'kaeuferEmail', type: 'string', size: 320, required: false })
|
|
assert.deepEqual(orders.get('erstelltAt'), { key: 'erstelltAt', type: 'datetime', required: false })
|
|
assert.deepEqual(orders.get('summeCent'), { key: 'summeCent', type: 'integer', required: false })
|
|
assert.deepEqual(client.state.get('shopConfig').attrs.get('geoeffnet'), { key: 'geoeffnet', 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({
|
|
shopWiderrufe: { attrs: ['shopId', 'customerId', 'bestellnummer', 'name', 'email', 'nachricht', 'eingangAt', 'bestaetigungAt'], indexes: [] },
|
|
})
|
|
await main({ client, log: quiet })
|
|
assert.ok(!client.calls.collections.some((c) => c.id === 'shopWiderrufe'))
|
|
assert.deepEqual(client.calls.attrs.filter((k) => k.startsWith('shopWiderrufe.')), ['shopWiderrufe.bearbeitetAt', 'shopWiderrufe.orderId'])
|
|
assert.deepEqual(client.calls.indexes.filter((k) => k.startsWith('shopWiderrufe.')), ['shopWiderrufe.idx_shop'])
|
|
assert.equal(client.calls.collections.length, 4)
|
|
})
|
|
|
|
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('shopOrders') && 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 und einen fehlenden Index', async () => {
|
|
const client = fakeClient()
|
|
await main({ client, log: quiet })
|
|
client.state.get('shopOrders').attrs.delete('anonymisiertAt')
|
|
client.state.get('shopConfig').indexes.delete('idx_account')
|
|
const lines = []
|
|
const result = await main({ check: true, client, log: (line) => lines.push(line) })
|
|
assert.deepEqual(result.missing.map((a) => `${a.collection}.${a.key}`), ['shopOrders.anonymisiertAt'])
|
|
assert.deepEqual(result.missingIndexes.map((i) => `${i.collection}.${i.key}`), ['shopConfig.idx_account'])
|
|
assert.deepEqual(result.missingCollections, [])
|
|
assert.ok(lines.some((line) => line.includes('shopOrders.anonymisiertAt FEHLT')))
|
|
assert.ok(lines.some((line) => line.includes('Index shopConfig.idx_account FEHLT')))
|
|
})
|