Files
Webklar-Kundenbereich/scripts/setup-abo-collections.mjs
T
ClaudeandClaude Opus 5.5 4ab154bfa2 Wartungs-Abo v2: Rechtsrunde umgesetzt
- Bestellseite: Pflichtangaben direkt ueber dem Button, Zahlungsarten,
  Wahl des Leistungsbeginns (sofort / nach Widerrufsfrist via 15 Tage
  Stripe-Probezeit), keine Vorauswahl
- Zustimmungsnachweis: Zeitpunkt, Version, Wahl, IP, Browser in Stripe-
  Metadaten und Appwrite (neue Attribute, Setup-Skript ergaenzt)
- Checkout: Karte + SEPA (Fallback nur Karte), korrigierter Hinweistext
- Vertragsbestaetigung mit PDF der Vertragsunterlagen statt HTML
- Kuendigen/Widerrufen: Formular direkt (keine Zwischenseite), Wunsch-
  termin, Druck/PDF der Bestaetigung, Vorbefuellung bei Login
- Widerrufsbutton im Abo waehrend der Frist, 'beginnt am'-Status
- Pilotbetrieb per ABO_PILOT_EMAILS
- Vertragsbedingungen v2, Datenschutzerklaerung, Kalkulator ohne MwSt
  und mit 100/80 EUR

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 14:10:21 +00:00

145 lines
5.2 KiB
JavaScript

#!/usr/bin/env node
/**
* Wartungs-Abo: legt die Collections subscriptions + hourCredits in woms-database an
* und ergaenzt worksheets um das Flag countsToPlan ("zaehlt aufs Abo-Stundenkonto").
* Idempotent: existierende Collection/Attribute/Indexe werden uebersprungen.
* Usage (im Container): docker exec -w /app webklar-kundenbereich-server node scripts/setup-abo-collections.mjs
*/
const endpoint = (process.env.APPWRITE_ENDPOINT || 'https://ticket.webklar.com/v1').replace(/\/$/, '')
const projectId = process.env.APPWRITE_PROJECT_ID || '6a1058610003c5a13a05'
const apiKey = process.env.APPWRITE_API_KEY
const databaseId = process.env.APPWRITE_DATABASE_ID || 'woms-database'
if (!apiKey) {
console.error('APPWRITE_API_KEY erforderlich')
process.exit(1)
}
async function aw(path, { method = 'GET', body } = {}) {
const response = await fetch(`${endpoint}${path}`, {
method,
headers: {
'Content-Type': 'application/json',
'X-Appwrite-Project': projectId,
'X-Appwrite-Key': apiKey,
},
body: body ? JSON.stringify(body) : undefined,
})
const data = await response.json().catch(() => ({}))
if (!response.ok) {
const err = new Error(data.message || `Appwrite ${response.status}`)
err.status = response.status
throw err
}
return data
}
async function ensure(label, fn) {
try {
await fn()
console.log(`+ ${label}`)
} catch (e) {
if (e.status === 409 || /already exists/i.test(e.message)) {
console.log(`= ${label} (existiert)`)
} else {
throw new Error(`${label}: ${e.message}`)
}
}
}
async function waitForAttributes(collectionId, keys, maxSec = 60) {
for (let i = 0; i < maxSec; i += 1) {
const { attributes } = await aw(`/databases/${databaseId}/collections/${collectionId}/attributes`)
const pending = keys.filter((k) => attributes.find((a) => a.key === k)?.status !== 'available')
if (!pending.length) return
await new Promise((r) => setTimeout(r, 1000))
}
throw new Error(`Attribute in ${collectionId} wurden nicht verfuegbar`)
}
const col = (id) => `/databases/${databaseId}/collections/${id}`
async function ensureCollection(id, name, attributes, indexes) {
// Keine Dokument-Permissions: Zugriff ausschliesslich ueber den Server-API-Key
await ensure(`Collection ${id}`, () =>
aw(`/databases/${databaseId}/collections`, {
method: 'POST',
body: { collectionId: id, name, permissions: [], documentSecurity: false },
})
)
for (const a of attributes) {
const { type, key, ...rest } = a
await ensure(`${id}.${key}`, () =>
aw(`${col(id)}/attributes/${type}`, { method: 'POST', body: { key, required: false, ...rest } })
)
}
await waitForAttributes(id, attributes.map((a) => a.key))
for (const idx of indexes) {
await ensure(`${id} index ${idx.key}`, () =>
aw(`${col(id)}/indexes`, { method: 'POST', body: idx })
)
}
}
await ensureCollection(
'subscriptions',
'Abos (Stripe)',
[
{ type: 'string', key: 'customerId', size: 64 },
{ type: 'string', key: 'email', size: 255 },
{ type: 'string', key: 'stripeCustomerId', size: 64 },
{ type: 'string', key: 'stripeSubscriptionId', size: 64 },
{ type: 'string', key: 'status', size: 32 },
{ type: 'string', key: 'planKey', size: 64 },
{ type: 'integer', key: 'priceAmount' },
{ type: 'datetime', key: 'startedAt' },
{ type: 'datetime', key: 'currentPeriodEnd' },
{ type: 'boolean', key: 'cancelAtPeriodEnd' },
{ type: 'datetime', key: 'canceledAt' },
{ type: 'datetime', key: 'endedAt' },
{ type: 'string', key: 'termsVersion', size: 32 },
{ type: 'datetime', key: 'termsAcceptedAt' },
{ type: 'datetime', key: 'earlyStartConsentAt' },
{ type: 'datetime', key: 'cancelRequestedAt' },
{ type: 'datetime', key: 'withdrawalRequestedAt' },
{ type: 'datetime', key: 'confirmationSentAt' },
// v2 (25.09.2026): Wahl des Leistungsbeginns + Nachweis der Zustimmung
{ type: 'string', key: 'startChoice', size: 16 },
{ type: 'datetime', key: 'trialEnd' },
{ type: 'string', key: 'consentIp', size: 64 },
{ type: 'string', key: 'consentUserAgent', size: 300 },
{ type: 'string', key: 'consentTextVersion', size: 32 },
],
[
{ key: 'idx_customer', type: 'key', attributes: ['customerId'] },
{ key: 'idx_stripe_customer', type: 'key', attributes: ['stripeCustomerId'] },
]
)
await ensureCollection(
'hourCredits',
'Abo-Stundengutschriften',
[
{ type: 'string', key: 'customerId', size: 64 },
{ type: 'string', key: 'stripeSubscriptionId', size: 64 },
{ type: 'string', key: 'stripeInvoiceId', size: 64 },
{ type: 'integer', key: 'minutes' },
{ type: 'datetime', key: 'grantedAt' },
{ type: 'datetime', key: 'expiresAt' },
{ type: 'string', key: 'source', size: 32 },
{ type: 'string', key: 'note', size: 500 },
],
[{ key: 'idx_customer', type: 'key', attributes: ['customerId'] }]
)
// Worksheet-Flag: nur markierte Arbeitszeit wird vom Abo-Guthaben abgezogen
await ensure('worksheets.countsToPlan', () =>
aw(`${col('worksheets')}/attributes/boolean`, {
method: 'POST',
body: { key: 'countsToPlan', required: false, default: false },
})
)
await waitForAttributes('worksheets', ['countsToPlan'])
console.log('Fertig.')