Stripe: Preise je Produkt, Testrabatt Hosting, Kundenportal „Abo verwalten“, Mindestlaufzeit ab termStartAt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ClaudeandClaude Opus 5.5 committed 2026-09-28 09:21:25 +00:00
1 parent 7799d7c4de
commit e5cc57cefd
7 files changed
+402 -35

No files matched your search

+21 -1
View File
@@ -2,7 +2,7 @@ import { test } from 'node:test'
import assert from 'node:assert/strict'
const { config } = await import('../server/config.js')
const { getProduct, productKeyForLookupKey, describeItems, priceIdsOfInvoice, creditMinutesForInvoice } =
const { getProduct, productKeyForLookupKey, describeItems, priceIdsOfInvoice, creditMinutesForInvoice, termsDocFor, productView } =
await import('../server/services/products.js')
const line = (price, amount, proration = false) => ({
@@ -101,3 +101,23 @@ test('priceIdsOfInvoice: eindeutige Preis-IDs, ohne Lücken', () => {
const inv = { lines: { data: [line('price_w', 5000), line('price_w', -100, true), { amount: 5 }] } }
assert.deepEqual(priceIdsOfInvoice(inv), ['price_w'])
})
test('Vertragsunterlagen je Version', () => {
assert.equal(termsDocFor('2026-10-05-v4').pdfFile, 'WEBklar-Abo-Vertragsunterlagen.pdf')
assert.equal(termsDocFor('2026-09-25-v3').url, '/vertragsunterlagen/v3/abo-bedingungen.html')
assert.equal(termsDocFor(null).url, '/vertragsunterlagen/v3/abo-bedingungen.html')
})
test('Produktansicht enthält Leistungen ohne 1-Postfach-Regel bei Wartung', () => {
const w = productView('wartung').features.flat().join(' ')
assert.ok(w.includes('beliebig viele Postfächer') && !w.includes('1 E-Mail-Postfach'))
assert.ok(productView('hosting').features.flat().join(' ').includes('1 E-Mail-Postfach'))
})
// F07: die Wartungs-Beschreibung darf die alte 1-Postfach-Regel nicht mehr enthalten (Version 4:
// beliebig viele Postfächer, zusammen 5 GB). Der Stripe-Produkttext selbst wird erst beim
// Livegang ueber scripts/stripe-products.mjs gesetzt.
test('Wartung-Beschreibung ohne 1-Postfach-Regel (F07)', () => {
assert.ok(!getProduct('wartung').description.includes('1 E-Mail-Postfach'))
assert.ok(getProduct('wartung').description.includes('beliebig viele Postfächer'))
})
+51 -1
View File
@@ -9,7 +9,7 @@ const aw = await startAppwriteMock({ schema: { subscriptions: schemaKeys('subscr
const st = await startFakeStripe()
after(() => Promise.all([aw.close(), st.close()]))
useTestEnv({ appwriteUrl: aw.url, stripeUrl: st.url })
const { syncSubscription } = await import('../server/services/stripeBilling.js')
const { syncSubscription, ensurePrice, ensureTestCoupon, ensurePortalConfiguration } = await import('../server/services/stripeBilling.js')
const sub = (id, items, extra = {}) => ({
id,
@@ -60,3 +60,53 @@ test('Spiegel: unbekannter Preis gilt als Wartungs-Abo, Betrag vom ersten Posten
const doc = await syncSubscription('sub_x')
assert.deepEqual([doc.productKey, doc.planKey, doc.priceAmount], ['wartung', 'webklar_wartung_monatlich_5000', 4900])
})
// Stripe-Nachbau braucht dazu: POST /v1/products, POST /v1/prices, GET /v1/coupons/:id, POST /v1/coupons,
// GET/POST /v1/billing_portal/configurations und POST /v1/billing_portal/configurations/:id (F09)
test('ensurePrice legt Hosting einmal an', async () => {
const id1 = await ensurePrice('hosting'); const id2 = await ensurePrice('hosting')
assert.equal(id1, id2)
const created = st.calls.filter((c) => c.method === 'POST' && c.path === '/v1/prices')
assert.equal(created.length, 1)
assert.equal(created[0].body['lookup_key'], 'webklar_hosting_monatlich_1500')
assert.equal(created[0].body['unit_amount'], '1500')
})
test('Testrabatt Hosting: 14,50 € Nachlass', async () => {
assert.equal(await ensureTestCoupon('hosting'), 'WEBKLAR-TEST-050-HOSTING')
assert.equal(st.calls.find((c) => c.path === '/v1/coupons' && c.method === 'POST').body['amount_off'], '1450')
})
// F09: eine bestehende eigene Konfiguration mit der alten Wartungs-Abo-Überschrift wird angepasst,
// nicht doppelt angelegt.
test('Kundenportal: alte Überschrift → configurations.update', async () => {
st.billingPortalConfigurations.set('bpc_old', {
id: 'bpc_old',
object: 'billing_portal.configuration',
active: true,
business_profile: { headline: 'Webklar – Wartungs-Abo verwalten' },
metadata: { webklar: 'wartungs-abo' },
})
const id = await ensurePortalConfiguration()
assert.equal(id, 'bpc_old')
const updateCall = st.calls.find((c) => c.method === 'POST' && c.path === '/v1/billing_portal/configurations/bpc_old')
assert.ok(updateCall)
assert.equal(updateCall.body['business_profile[headline]'], 'WEBklar – Abo verwalten')
})
test('Spiegel: termStartAt aus Metadaten (Wechsel), sonst Leistungsbeginn; storageUnits', async () => {
st.subscriptions.set(
'sub_s',
sub('sub_s', [item('w2', 'webklar_wartung_monatlich_5000', 5000), item('s2', 'webklar_mailspeicher_5gb_monatlich_100', 100, 3)], {
metadata: {
webklarCustomerId: 'c1',
email: 'k@example.invalid',
termsVersion: '2026-09-25-v3',
termStartAt: '2026-10-05T10:00:00.000Z',
},
})
)
const doc = await syncSubscription('sub_s')
assert.equal(doc.termStartAt, '2026-10-05T10:00:00.000Z')
assert.equal(doc.storageUnits, 3)
})
+114 -2
View File
@@ -9,7 +9,12 @@ export async function startFakeStripe() {
const subscriptions = new Map()
const prices = new Map()
const invoices = new Map()
const products = new Map()
const coupons = new Map()
const billingPortalConfigurations = new Map()
const calls = []
let seq = 0
const nextId = (prefix) => `${prefix}_test_${(seq += 1)}`
const flat = (params) => Object.fromEntries(params.entries())
const noSuch = (what, id) => [404, { error: { type: 'invalid_request_error', code: 'resource_missing', message: `No such ${what}: '${id}'` } }]
@@ -22,7 +27,26 @@ export async function startFakeStripe() {
req.on('end', () => resolve(new URLSearchParams(raw)))
})
const route = (method, path, query) => {
// Stripe serialisiert verschachtelte Parameter (z. B. recurring[interval]=month) als flache
// Formularschluessel. Fuer die Routen selbst wieder zu einem verschachtelten Objekt zusammenbauen.
const unflatten = (params) => {
const root = {}
for (const [rawKey, value] of params.entries()) {
const path = rawKey.match(/[^[\]]+/g) || [rawKey]
let node = root
path.forEach((key, i) => {
if (i === path.length - 1) {
node[key] = value
} else {
if (!(key in node)) node[key] = /^\d+$/.test(path[i + 1]) ? [] : {}
node = node[key]
}
})
}
return root
}
const route = (method, path, query, body) => {
let m
if (method === 'GET' && (m = path.match(/^\/v1\/subscriptions\/([^/]+)$/))) {
return subscriptions.has(m[1]) ? [200, subscriptions.get(m[1])] : noSuch('subscription', m[1])
@@ -38,9 +62,94 @@ export async function startFakeStripe() {
)
return [200, listOf(found)]
}
if (method === 'POST' && path === '/v1/prices') {
const data = unflatten(body)
const obj = {
id: nextId('price'),
object: 'price',
active: true,
product: data.product,
currency: data.currency || 'eur',
unit_amount: data.unit_amount != null ? Number(data.unit_amount) : null,
recurring: data.recurring ? { interval: data.recurring.interval } : null,
tax_behavior: data.tax_behavior || null,
lookup_key: data.lookup_key || null,
nickname: data.nickname || null,
}
prices.set(obj.id, obj)
return [200, obj]
}
if (method === 'GET' && (m = path.match(/^\/v1\/invoices\/([^/]+)$/))) {
return invoices.has(m[1]) ? [200, invoices.get(m[1])] : noSuch('invoice', m[1])
}
if (method === 'POST' && path === '/v1/products') {
const data = unflatten(body)
const obj = {
id: nextId('prod'),
object: 'product',
active: true,
name: data.name || '',
description: data.description ?? null,
statement_descriptor: data.statement_descriptor ?? null,
metadata: data.metadata || {},
}
products.set(obj.id, obj)
return [200, obj]
}
if (method === 'GET' && (m = path.match(/^\/v1\/coupons\/([^/]+)$/))) {
return coupons.has(m[1]) ? [200, coupons.get(m[1])] : noSuch('coupon', m[1])
}
if (method === 'POST' && path === '/v1/coupons') {
const data = unflatten(body)
const id = data.id || nextId('coupon')
const obj = {
id,
object: 'coupon',
valid: true,
name: data.name || null,
amount_off: data.amount_off != null ? Number(data.amount_off) : null,
currency: data.currency || null,
duration: data.duration || 'once',
metadata: data.metadata || {},
}
coupons.set(id, obj)
return [200, obj]
}
if (method === 'GET' && path === '/v1/billing_portal/configurations') {
const active = query.get('active')
const found = [...billingPortalConfigurations.values()].filter(
(c) => active === null || String(c.active !== false) === active
)
return [200, listOf(found)]
}
if (method === 'POST' && path === '/v1/billing_portal/configurations') {
const data = unflatten(body)
const obj = {
id: nextId('bpc'),
object: 'billing_portal.configuration',
active: true,
business_profile: data.business_profile || {},
default_return_url: data.default_return_url || null,
features: data.features || {},
metadata: data.metadata || {},
}
billingPortalConfigurations.set(obj.id, obj)
return [200, obj]
}
if (method === 'POST' && (m = path.match(/^\/v1\/billing_portal\/configurations\/([^/]+)$/))) {
const existing = billingPortalConfigurations.get(m[1])
if (!existing) return noSuch('configuration', m[1])
const data = unflatten(body)
const updated = {
...existing,
...data,
business_profile: { ...existing.business_profile, ...(data.business_profile || {}) },
features: { ...existing.features, ...(data.features || {}) },
metadata: { ...existing.metadata, ...(data.metadata || {}) },
}
billingPortalConfigurations.set(m[1], updated)
return [200, updated]
}
return [404, { error: { type: 'invalid_request_error', message: `No such route: ${method} ${path}` } }]
}
@@ -48,7 +157,7 @@ export async function startFakeStripe() {
const url = new URL(req.url, 'http://127.0.0.1')
const body = await readBody(req)
calls.push({ method: req.method, path: url.pathname, query: flat(url.searchParams), body: flat(body) })
const [status, payload] = route(req.method, url.pathname, url.searchParams)
const [status, payload] = route(req.method, url.pathname, url.searchParams, body)
res.writeHead(status, { 'Content-Type': 'application/json', 'Request-Id': `req_test_${calls.length}` })
res.end(JSON.stringify(payload))
})
@@ -60,6 +169,9 @@ export async function startFakeStripe() {
subscriptions,
prices,
invoices,
products,
coupons,
billingPortalConfigurations,
close: () => new Promise((resolve) => server.close(resolve)),
}
}