From 7df0b72019ce1eb259cc20972a92882c47f5606f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 28 Sep 2026 10:02:03 +0000 Subject: [PATCH] =?UTF-8?q?Stripe:=20Testrabatt-Namen,=20Produktbild,=20Ho?= =?UTF-8?q?sting-Leistungen,=20Tests=20f=C3=BCr=20Bestandskunden?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- scripts/stripe-products.mjs | 47 ++++++++--- server/config.js | 27 ++++-- server/services/products.js | 4 +- server/services/stripeBilling.js | 59 +++++++++---- test/products.test.js | 54 ++++++++++-- test/stripeBilling.test.js | 138 +++++++++++++++++++++++++++++-- test/support/fakeStripe.js | 20 +++++ 7 files changed, 297 insertions(+), 52 deletions(-) diff --git a/scripts/stripe-products.mjs b/scripts/stripe-products.mjs index ed162ac..afe88ea 100644 --- a/scripts/stripe-products.mjs +++ b/scripts/stripe-products.mjs @@ -6,8 +6,11 @@ * Idempotent: vorhandene Preise werden ueber lookup_key gefunden, nicht neu angelegt. * * Usage (im Container): - * node scripts/stripe-products.mjs --pruefen (nur anzeigen, was fehlt oder abweicht) - * node scripts/stripe-products.mjs (anlegen/anpassen) + * node scripts/stripe-products.mjs --pruefen (nur anzeigen, was fehlt oder abweicht, keine Schreibzugriffe) + * node scripts/stripe-products.mjs --anlegen (anlegen/anpassen) + * + * Fix round 1, Minor 7: genau einer der beiden Schalter ist Pflicht - kein stiller Livegang bei + * fehlendem oder falsch geschriebenem Schalter. */ import 'dotenv/config' import { config } from '../server/config.js' @@ -15,6 +18,14 @@ import { ensurePortalConfiguration, ensurePrice, getStripe, PORTAL_HEADLINE } fr import { PRODUCT_KEYS } from '../server/services/products.js' const KEYS = [...PRODUCT_KEYS, 'mailStorage'] // ['wartung', 'hosting', 'mailStorage'] +const USAGE = 'Usage: node scripts/stripe-products.mjs --pruefen | --anlegen' + +export function parseArgs(argv) { + const args = argv.slice(2) + if (args.length === 1 && args[0] === '--pruefen') return 'pruefen' + if (args.length === 1 && args[0] === '--anlegen') return 'anlegen' + return null +} function catalogEntry(key) { return key === 'mailStorage' ? config.mailStorage : config.products[key] @@ -33,6 +44,12 @@ async function checkPrice(key) { if (price.unit_amount !== catalog.amountCents) mismatches.push(`Betrag ${price.unit_amount} statt ${catalog.amountCents}`) if (price.recurring?.interval !== 'month') mismatches.push(`recurring.interval "${price.recurring?.interval}" statt "month"`) if (price.tax_behavior !== 'inclusive') mismatches.push(`tax_behavior "${price.tax_behavior}" statt "inclusive"`) + // Important 2: Produkt ohne Bild faellt in --pruefen auf (Checkout zeigt sonst kein Bild) + const productId = typeof price.product === 'string' ? price.product : price.product?.id + if (productId) { + const product = await getStripe().products.retrieve(productId) + if (!product.images?.length) mismatches.push('kein Produktbild') + } return { ok: mismatches.length === 0, note: mismatches.length ? mismatches.join('; ') : `OK (${price.id})` } } @@ -68,7 +85,9 @@ async function pruefen() { console.log(`${portal.ok ? '✅' : '❌'} Kundenportal-Konfiguration: ${portal.note}`) if (!allOk) { console.log('') - console.log('Zum Anlegen/Anpassen: node scripts/stripe-products.mjs') + console.log('Zum Anlegen/Anpassen: node scripts/stripe-products.mjs --anlegen') + // Minor 7: --pruefen bleibt rein lesend, meldet Luecken aber ueber den Exit-Code (fuer Cron/CI) + process.exitCode = 1 } } @@ -86,18 +105,26 @@ async function anlegen() { } async function main() { + const mode = parseArgs(process.argv) + if (!mode) { + console.error(`❌ ${USAGE}`) + process.exit(1) + } if (!config.stripe.secretKey) { console.error('❌ STRIPE_SECRET_KEY fehlt') process.exit(1) } - const checkOnly = process.argv.includes('--pruefen') - console.log(checkOnly ? 'Modus: --pruefen (nur lesen, keine Änderungen)' : 'Modus: anlegen/anpassen') + console.log(mode === 'pruefen' ? 'Modus: --pruefen (nur lesen, keine Änderungen)' : 'Modus: --anlegen (anlegen/anpassen)') console.log('') - if (checkOnly) await pruefen() + if (mode === 'pruefen') await pruefen() else await anlegen() } -main().catch((err) => { - console.error('❌', err.message) - process.exit(1) -}) +// Nur beim direkten Aufruf laufen lassen, nicht wenn das Modul importiert wird (z. B. fuer +// parseArgs in einem Test) - main() wuerde sonst ueber process.exit den Prozess mitreissen. +if (import.meta.url === `file://${process.argv[1]}`) { + main().catch((err) => { + console.error('❌', err.message) + process.exit(1) + }) +} diff --git a/server/config.js b/server/config.js index e176497..84dea59 100644 --- a/server/config.js +++ b/server/config.js @@ -31,22 +31,24 @@ const products = { name: 'WEBklar Wartungs-Abo', lookupKey: process.env.STRIPE_ABO_PRICE_LOOKUP_KEY || 'webklar_wartung_monatlich_5000', amountCents: 5000, - // Version 4 (Rechtsrunde 28.09.2026): beliebig viele Postfächer statt 1 E-Mail-Postfach (F07) + // Version 4 (Rechtsrunde 28.09.2026): beliebig viele E-Mail-Postfächer statt 1 E-Mail-Postfach (F07; + // Fix round 1, item 11: ausgeschrieben "E-Mail-Postfächer" statt bloß "Postfächer") description: - 'Betrieb und Pflege Ihrer Website bzw. Web-Anwendung auf unserem Server in Deutschland (Sicherheitsupdates, SSL, tägliche Datensicherung, Überwachung der Erreichbarkeit), 1 Domain inklusive Verwaltung, beliebig viele Postfächer (zusammen 5 GB) und 1 Stunde Arbeitszeit pro Monat (12 Monate nutzbar). Mindestlaufzeit 12 Monate, danach monatlich kündbar. Gemäß § 19 UStG ohne Umsatzsteuer.', + 'Betrieb und Pflege Ihrer Website bzw. Web-Anwendung auf unserem Server in Deutschland (Sicherheitsupdates, SSL, tägliche Datensicherung, Überwachung der Erreichbarkeit), 1 Domain inklusive Verwaltung, beliebig viele E-Mail-Postfächer (zusammen 5 GB) und 1 Stunde Arbeitszeit pro Monat (12 Monate nutzbar). Mindestlaufzeit 12 Monate, danach monatlich kündbar. Gemäß § 19 UStG ohne Umsatzsteuer.', statementDescriptor: 'WEBKLAR WARTUNG', priceNickname: 'Wartungs-Abo monatlich', minTermMonths: 12, minutesPerMonth: 60, + // Testrabatt: id passend zur amount_off-Regel (amountCents - 50), siehe global-constraints.md + testCouponId: 'WEBKLAR-TEST-050', // Leistungen fuers Kundenportal (Vergleich, Bestellseite): [Titel, Detail], Spec 3.1 / Fassung 4 features: [ ['Betrieb & Pflege Ihrer Website bzw. Web-Anwendung', 'Server in Deutschland, Updates, Sicherheit, tägliche Datensicherung, Überwachung'], - ['1 Domain inklusive', 'Registrierung auf Ihren Namen, DNS- und Zertifikatsverwaltung'], + ['1 Domain inklusive', '.de, .com, .eu, .net oder .org, Registrierung und DNS-Verwaltung'], ['beliebig viele Postfächer', 'zusammen 5 GB Speicher'], ['1 Stunde Arbeitszeit pro Monat', 'nicht genutzte Zeit bleibt 12 Monate verfügbar'], ], }, - // Noch nicht bestellbar: Die Beschreibung geht erst mit den Vertragsbedingungen Version 4 an Stripe hosting: { key: 'hosting', name: 'WEBklar Hosting-Abo', @@ -58,11 +60,15 @@ const products = { priceNickname: 'Hosting-Abo monatlich', minTermMonths: 12, minutesPerMonth: 0, + testCouponId: 'WEBKLAR-TEST-050-HOSTING', + // Fix round 1, Important 3: row 1 war wörtlich von Wartung kopiert und suggerierte Website-Pflege + // (die es im Hosting-Abo nicht gibt); row 4 nennt jetzt die Abrechnung in 15-Minuten-Schritten. features: [ - ['Bereitstellung Ihrer statischen Website', 'Server in Deutschland, Updates, Sicherheit, tägliche Datensicherung, Überwachung'], - ['1 Domain inklusive', 'Registrierung auf Ihren Namen, DNS- und Zertifikatsverwaltung'], + ['Bereitstellung Ihrer statischen Website', 'Server in Deutschland, SSL, Updates von Betriebssystem und Server-Software, tägliche Datensicherung, Überwachung'], + ['1 Domain inklusive', '.de, .com, .eu, .net oder .org, Registrierung und DNS-Verwaltung'], ['1 E-Mail-Postfach', 'mit Ihrer eigenen Domain, 5 GB Speicher'], - ['Änderungen nur nach Freigabe', '100 € pro Stunde'], + ['Keine Pflege der Website', 'Pflege und Updates der Website nur im Wartungs-Abo'], + ['Änderungen nur nach Freigabe', '100 € pro Stunde in 15-Minuten-Schritten (gemäß § 19 UStG ohne Umsatzsteuer)'], ], }, } @@ -126,8 +132,9 @@ export const config = { priceLookupKey: products.wartung.lookupKey, priceAmountCents: products.wartung.amountCents, productName: products.wartung.name, - productDescription: products.wartung.description, statementDescriptor: products.wartung.statementDescriptor, + // Generisches Logo, allen drei Stripe-Produkten mitgegeben (ensurePrice); ein Katalogeintrag + // kann das mit einem eigenen "image"-Feld ueberschreiben productImage: 'https://project.webklar.com/img/wartungs-abo-produkt.png', // Kleinunternehmer: Pflichthinweis auf jeder Stripe-Rechnung invoiceFooter: @@ -154,7 +161,9 @@ export const config = { .split(',') .map((s) => s.trim().toLowerCase()) .filter(Boolean), - testCouponId: 'WEBKLAR-TEST-050', + // Fix round 1, Minor 8: einzige Quelle ist der Katalog (products.wartung.testCouponId); Hosting + // hat sein eigenes unter products.hosting.testCouponId + testCouponId: products.wartung.testCouponId, }, // Individuelle Abo-Angebote (z. B. erste 2 Monate je 25 €): je Angebot ein einmal einloesbarer Stripe-Coupon diff --git a/server/services/products.js b/server/services/products.js index 735d101..2cd33fa 100644 --- a/server/services/products.js +++ b/server/services/products.js @@ -43,7 +43,9 @@ export function productView(key) { amountCents: product.amountCents, minTermMonths: product.minTermMonths, minutesPerMonth: product.minutesPerMonth, - features: product.features, + // Kopie, kein Verweis auf den Katalog: aufrufender Code darf das zurueckgegebene Array + // veraendern, ohne den geteilten Katalogeintrag fuer alle anderen zu verfaelschen (B10) + features: product.features.map((row) => [...row]), } } diff --git a/server/services/stripeBilling.js b/server/services/stripeBilling.js index 15e6754..00c6303 100644 --- a/server/services/stripeBilling.js +++ b/server/services/stripeBilling.js @@ -81,6 +81,9 @@ export async function ensurePrice(key) { name: catalog.name, ...(catalog.description ? { description: catalog.description } : {}), ...(catalog.statementDescriptor ? { statement_descriptor: catalog.statementDescriptor } : {}), + // Produktbild: eigenes Katalogbild, sonst das generische Logo (Fix round 1, Important 2 - war + // beim Verallgemeinern von ensureAboPrice zu ensurePrice verloren gegangen) + images: [catalog.image || config.stripe.productImage], metadata: { webklar: PRODUCT_METADATA[key] }, }) const price = await stripe.prices.create({ @@ -100,6 +103,11 @@ export async function ensurePrice(key) { export const PORTAL_HEADLINE = 'WEBklar – Abo verwalten' let cachedPortalConfigId = null +/** Nur fuer Tests: Cache zuruecksetzen, damit beide Zweige (Update noetig / schon richtig) einzeln pruefbar sind. */ +export function resetPortalConfigCacheForTests() { + cachedPortalConfigId = null +} + /** Kundenportal-Konfiguration (Zahlungsmittel, Rechnungen, Kuendigung zum Periodenende). */ export async function ensurePortalConfiguration() { if (cachedPortalConfigId) return cachedPortalConfigId @@ -107,16 +115,25 @@ export async function ensurePortalConfiguration() { const { data } = await stripe.billingPortal.configurations.list({ active: true, limit: 20 }) const own = data.find((c) => c.metadata?.webklar === 'wartungs-abo') if (own) { - cachedPortalConfigId = own.id - // Aeltere Konfiguration (frueher nur Wartung) traegt noch die alte Ueberschrift -> anpassen + // Aeltere Konfiguration (frueher nur Wartung) traegt noch die alte Ueberschrift -> anpassen. + // Fix round 1, Minor 6: Cache erst nach Erfolg setzen, damit ein Fehlschlag beim naechsten + // Aufruf (z. B. Klick auf "Abo verwalten") erneut versucht wird statt fuer immer stehen zu + // bleiben; ein Fehlschlag bricht den Aufruf selbst nicht ab (die Portal-Sitzung soll trotzdem + // zustande kommen), nur eine Warnung im Log. if (own.business_profile?.headline !== PORTAL_HEADLINE) { - await stripe.billingPortal.configurations.update(own.id, { - business_profile: { - headline: PORTAL_HEADLINE, - terms_of_service_url: `${config.publicBaseUrl}/abo-bedingungen.html`, - }, - }) + try { + await stripe.billingPortal.configurations.update(own.id, { + business_profile: { + headline: PORTAL_HEADLINE, + terms_of_service_url: `${config.publicBaseUrl}/abo-bedingungen.html`, + }, + }) + } catch (err) { + console.warn(`[stripe] Kundenportal-Konfiguration ${own.id}: Überschrift konnte nicht aktualisiert werden - ${err.message}`) + return own.id + } } + cachedPortalConfigId = own.id return own.id } const created = await stripe.billingPortal.configurations.create({ @@ -299,7 +316,13 @@ export function minTermMonthsFor(termsVersion) { */ export function termStartOf(sub) { const termStartAt = sub.metadata?.termStartAt - if (termStartAt) return new Date(termStartAt) + if (termStartAt) { + const date = new Date(termStartAt) + if (!Number.isNaN(date.getTime())) return date + // Von Hand verstellte/beschaedigte Metadaten duerfen syncSubscription (toISOString) und + // cancelSubscriptionAt nicht mit einer Exception abschiessen - Warnung, Fallback wie ohne Wechsel + console.warn(`[stripe] Abo ${sub.id || '?'}: ungültiges termStartAt in den Metadaten ("${termStartAt}") - falle auf Leistungsbeginn zurück`) + } return new Date(((sub.trial_end || sub.start_date) || 0) * 1000) } @@ -405,12 +428,17 @@ async function getOrCreateStripeCustomer(customer) { return created.id } -// Testrabatt-IDs je Produkt: amount_off = amountCents - 50 -> es werden nur 0,50 € abgebucht -const TEST_COUPON_IDS = { wartung: config.abo.testCouponId, hosting: 'WEBKLAR-TEST-050-HOSTING' } +const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1) -/** Rabatt fuer Testkonten holen oder (einmalig) anlegen. productKey: 'wartung' | 'hosting'. */ +/** + * Rabatt fuer Testkonten holen oder (einmalig) anlegen. productKey: 'wartung' | 'hosting'; die ID + * kommt aus dem Katalog (products..testCouponId), wie amountCents und der lookup_key. + * Fix round 1, Important 1: Stripe begrenzt den Coupon-Namen auf 40 Zeichen - der volle Produktname + * ("Testzugang WEBklar (0,50 €) – WEBklar Hosting-Abo" = 49) hätte in echtem Stripe 400 zurückgegeben. + */ export async function ensureTestCoupon(productKey) { - const id = TEST_COUPON_IDS[productKey] + const catalog = getProduct(productKey) // 'mailStorage' oder unbekannt -> 400 (kein Testrabatt dafuer) + const id = catalog.testCouponId if (!id) { const err = new Error(`Kein Testrabatt fuer ${productKey}`) err.status = 400 @@ -419,14 +447,13 @@ export async function ensureTestCoupon(productKey) { const stripe = getStripe() const existing = await stripe.coupons.retrieve(id).catch(() => null) if (existing) return existing.id - const catalog = getProduct(productKey) const created = await stripe.coupons.create({ id, - name: `Testzugang WEBklar (0,50 €) – ${catalog.name}`, + name: `Testzugang ${capitalize(productKey)} (0,50 €)`, amount_off: catalog.amountCents - 50, currency: 'eur', duration: 'forever', - metadata: { webklar: `${productKey}-test` }, + metadata: { webklar: `${PRODUCT_METADATA[productKey]}-test` }, }) return created.id } diff --git a/test/products.test.js b/test/products.test.js index e511720..17b7c25 100644 --- a/test/products.test.js +++ b/test/products.test.js @@ -102,10 +102,17 @@ test('priceIdsOfInvoice: eindeutige Preis-IDs, ohne Lücken', () => { assert.deepEqual(priceIdsOfInvoice(inv), ['price_w']) }) +// Fix round 1 / B9: feste Form statt Einzelfelder 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') + assert.deepEqual(termsDocFor('2026-10-05-v4'), { url: '/abo-bedingungen.html', pdfFile: 'WEBklar-Abo-Vertragsunterlagen.pdf' }) + assert.deepEqual(termsDocFor('2026-09-25-v3'), { + url: '/vertragsunterlagen/v3/abo-bedingungen.html', + pdfFile: 'WEBklar-Wartungs-Abo-Vertragsunterlagen.pdf', + }) + assert.deepEqual(termsDocFor(null), { + url: '/vertragsunterlagen/v3/abo-bedingungen.html', + pdfFile: 'WEBklar-Wartungs-Abo-Vertragsunterlagen.pdf', + }) }) test('Produktansicht enthält Leistungen ohne 1-Postfach-Regel bei Wartung', () => { @@ -114,10 +121,43 @@ test('Produktansicht enthält Leistungen ohne 1-Postfach-Regel bei Wartung', () assert.ok(productView('hosting').features.flat().join(' ').includes('1 E-Mail-Postfach')) }) +// Fix round 1, Important 3: Hosting darf keine Website-Pflege suggerieren (row 1 war von Wartung +// kopiert) und muss "in 15-Minuten-Schritten" nennen. +test('Produktansicht Hosting: Betriebssystem/Server-Software statt Website-Pflege', () => { + const h = productView('hosting').features.flat().join(' ') + assert.ok(h.includes('Betriebssystem und Server-Software')) + assert.ok(!h.includes('Updates, Sicherheit')) + assert.ok(h.includes('15-Minuten-Schritten')) +}) + +// Fix round 1, B9: volle Form statt Einzelfelder, Kopie statt Referenz auf den Katalog (B10) +test('productView: vollständige Form, Kopie der features', () => { + const v = productView('hosting') + assert.deepEqual(Object.keys(v).sort(), ['amountCents', 'features', 'key', 'minTermMonths', 'minutesPerMonth', 'name'].sort()) + assert.equal(v.key, 'hosting') + assert.equal(v.name, 'WEBklar Hosting-Abo') + assert.equal(v.amountCents, 1500) + assert.equal(v.minTermMonths, 12) + assert.equal(v.minutesPerMonth, 0) + assert.ok(Array.isArray(v.features) && v.features.length > 0) + v.features.push(['x', 'y']) + assert.notEqual(productView('hosting').features.length, v.features.length) +}) + // 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. +// beliebig viele E-Mail-Postfächer, zusammen 5 GB). Der Stripe-Produkttext selbst wird erst beim +// Livegang ueber scripts/stripe-products.mjs gesetzt. B9: auch das § 19-Satzende pruefen. 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')) + const d = getProduct('wartung').description + assert.ok(!d.includes('1 E-Mail-Postfach')) + assert.ok(d.includes('beliebig viele E-Mail-Postfächer')) + assert.ok(d.endsWith('Gemäß § 19 UStG ohne Umsatzsteuer.')) +}) + +// Fix round 1, item 11: Domain-Zeile nennt die Endungen wie spec 3.1 / v4 § 3 Abs. 3 +test('Produktansicht: Domain-Zeile nennt die Endungen', () => { + for (const key of ['wartung', 'hosting']) { + const flat = productView(key).features.flat().join(' ') + assert.ok(flat.includes('.de') && flat.includes('.com') && flat.includes('.eu') && flat.includes('.net') && flat.includes('.org')) + } }) diff --git a/test/stripeBilling.test.js b/test/stripeBilling.test.js index a04b229..8ef5012 100644 --- a/test/stripeBilling.test.js +++ b/test/stripeBilling.test.js @@ -9,7 +9,17 @@ 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, ensurePrice, ensureTestCoupon, ensurePortalConfiguration } = await import('../server/services/stripeBilling.js') +const { config } = await import('../server/config.js') +const { + syncSubscription, + ensurePrice, + ensureTestCoupon, + ensurePortalConfiguration, + termStartOf, + getStripe, + PORTAL_HEADLINE, + resetPortalConfigCacheForTests, +} = await import('../server/services/stripeBilling.js') const sub = (id, items, extra = {}) => ({ id, @@ -53,6 +63,30 @@ test('Spiegel: Wartungs-Abo wie bisher', async () => { st.subscriptions.set('sub_w', sub('sub_w', [item('w', 'webklar_wartung_monatlich_5000', 5000)])) const doc = await syncSubscription('sub_w') assert.deepEqual([doc.productKey, doc.planKey, doc.priceAmount], ['wartung', 'webklar_wartung_monatlich_5000', 5000]) + // Fix round 1, Important 4: Bestandskunde ohne Wechsel-Metadaten -> termStartAt vom Leistungsbeginn (start_date) + assert.equal(doc.termStartAt, new Date(1790000000 * 1000).toISOString()) +}) + +// Fix round 1, Important 4: mit Probezeit (trial_end) und ohne Wechsel-Metadaten gewinnt trial_end +test('Spiegel: termStartAt ohne Wechsel-Metadaten faellt auf trial_end zurueck (Probezeit)', async () => { + st.subscriptions.set('sub_trial', sub('sub_trial', [item('wt', 'webklar_wartung_monatlich_5000', 5000)], { trial_end: 1791234567 })) + const doc = await syncSubscription('sub_trial') + assert.equal(doc.termStartAt, new Date(1791234567 * 1000).toISOString()) +}) + +// Fix round 1, Minor 5: eine von Hand verstellte/ungueltige Metadaten-Angabe darf nicht crashen +// (toISOString auf Invalid Date wuerde werfen) - Warnung statt Absturz, Fallback wie ohne Metadaten +test('termStartOf: ungültiges Datum in den Metadaten -> Warnung, Fallback auf trial_end/start_date', () => { + const original = console.warn + const warnings = [] + console.warn = (...args) => warnings.push(args.join(' ')) + try { + const result = termStartOf({ id: 'sub_bad', metadata: { termStartAt: 'nicht-valide' }, trial_end: 1791234567, start_date: 1790000000 }) + assert.equal(result.toISOString(), new Date(1791234567 * 1000).toISOString()) + assert.ok(warnings.some((w) => w.includes('termStartAt'))) + } finally { + console.warn = original + } }) test('Spiegel: unbekannter Preis gilt als Wartungs-Abo, Betrag vom ersten Posten', async () => { @@ -63,23 +97,91 @@ test('Spiegel: unbekannter Preis gilt als Wartungs-Abo, Betrag vom ersten Posten // 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 () => { +// Fix round 1, B9: before-Snapshot statt ueber die ganze Datei zaehlen; Preis-/Produktfelder und Bild geprueft +test('ensurePrice legt Hosting einmal an: Preis- und Produktfelder, Bild', async () => { + const before = st.calls.length 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') + const calls = st.calls.slice(before) + const createdPrices = calls.filter((c) => c.method === 'POST' && c.path === '/v1/prices') + assert.equal(createdPrices.length, 1) + assert.equal(createdPrices[0].body['lookup_key'], 'webklar_hosting_monatlich_1500') + assert.equal(createdPrices[0].body['unit_amount'], '1500') + assert.equal(createdPrices[0].body['tax_behavior'], 'inclusive') + assert.equal(createdPrices[0].body['recurring[interval]'], 'month') + const createdProducts = calls.filter((c) => c.method === 'POST' && c.path === '/v1/products') + assert.equal(createdProducts.length, 1) + assert.equal(createdProducts[0].body['metadata[webklar]'], 'hosting-abo') + // Important 2: Produktbild wiederhergestellt (7799d7c:71 hatte es, ging beim Verallgemeinern verloren) + assert.equal(createdProducts[0].body['images[0]'], config.stripe.productImage) }) -test('Testrabatt Hosting: 14,50 € Nachlass', async () => { +// Important 4: ein bereits vorhandener aktiver Preis wird gefunden, nichts wird bei Stripe angelegt +test('ensurePrice: vorhandener aktiver Preis wird gefunden, nichts wird angelegt', async () => { + st.prices.set('price_seeded_wartung', { + id: 'price_seeded_wartung', + object: 'price', + active: true, + lookup_key: 'webklar_wartung_monatlich_5000', + unit_amount: 5000, + recurring: { interval: 'month' }, + tax_behavior: 'inclusive', + }) + const before = st.calls.length + const id = await ensurePrice('wartung') + assert.equal(id, 'price_seeded_wartung') + const writes = st.calls.slice(before).filter((c) => c.method === 'POST' && (c.path === '/v1/products' || c.path === '/v1/prices')) + assert.deepEqual(writes, []) +}) + +// Important 1 (Stripe-Nachbau-Haertung): Stripe begrenzt Coupon-Namen auf 40 Zeichen, IDs und aktive +// lookup_keys sind eindeutig - der Nachbau soll das wie die echte API mit 400 quittieren. +test('Stripe-Nachbau: Grenzen bei Preisen und Coupons (400)', async () => { + const stripe = getStripe() + st.prices.set('price_dup_lookup', { + id: 'price_dup_lookup', object: 'price', active: true, lookup_key: 'lookup_fuer_diesen_test', unit_amount: 100, + }) + await assert.rejects( + stripe.prices.create({ product: 'prod_x', currency: 'eur', unit_amount: 100, lookup_key: 'lookup_fuer_diesen_test' }), + (err) => err.statusCode === 400 + ) + st.coupons.set('coupon_dup', { id: 'coupon_dup', object: 'coupon', name: 'x' }) + await assert.rejects( + stripe.coupons.create({ id: 'coupon_dup', name: 'y', amount_off: 100, currency: 'eur', duration: 'once' }), + (err) => err.statusCode === 400 + ) + await assert.rejects( + stripe.coupons.create({ name: 'x'.repeat(41), amount_off: 100, currency: 'eur', duration: 'once' }), + (err) => err.statusCode === 400 + ) +}) + +// Important 1: Namen ≤ 40 Zeichen (Stripe-Limit; die alten Namen mit dem vollen Produktnamen waren 49/50) +test('Testrabatt Hosting: 14,50 € Nachlass, Name ≤ 40 Zeichen', async () => { + const before = st.calls.length 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') + const call = st.calls.slice(before).find((c) => c.path === '/v1/coupons' && c.method === 'POST') + assert.equal(call.body['amount_off'], '1450') + assert.equal(call.body['name'], 'Testzugang Hosting (0,50 €)') + assert.ok(call.body['name'].length <= 40) +}) + +test('Testrabatt Wartung: 49,50 € Nachlass, Name ≤ 40 Zeichen', async () => { + const before = st.calls.length + assert.equal(await ensureTestCoupon('wartung'), 'WEBKLAR-TEST-050') + const call = st.calls.slice(before).find((c) => c.path === '/v1/coupons' && c.method === 'POST') + assert.equal(call.body['amount_off'], '4950') + assert.equal(call.body['name'], 'Testzugang Wartung (0,50 €)') + assert.ok(call.body['name'].length <= 40) }) // F09: eine bestehende eigene Konfiguration mit der alten Wartungs-Abo-Überschrift wird angepasst, -// nicht doppelt angelegt. +// nicht doppelt angelegt. Fix round 1, Minor 6: eigener Cache-Reset + eigene Map, damit dieser Test +// unabhaengig vom No-op-Test (gleiche Funktion, anderer Zweig) lauffaehig bleibt - ensurePortalConfiguration +// cached die Konfigurations-ID sonst ueber den ganzen Prozess hinweg. test('Kundenportal: alte Überschrift → configurations.update', async () => { + resetPortalConfigCacheForTests() + st.billingPortalConfigurations.clear() st.billingPortalConfigurations.set('bpc_old', { id: 'bpc_old', object: 'billing_portal.configuration', @@ -94,6 +196,24 @@ test('Kundenportal: alte Überschrift → configurations.update', async () => { assert.equal(updateCall.body['business_profile[headline]'], 'WEBklar – Abo verwalten') }) +// Minor 6: Ueberschrift schon richtig -> kein ueberfluessiger update-Aufruf +test('Kundenportal: Überschrift schon richtig → kein Update-Aufruf', async () => { + resetPortalConfigCacheForTests() + st.billingPortalConfigurations.clear() + st.billingPortalConfigurations.set('bpc_ok', { + id: 'bpc_ok', + object: 'billing_portal.configuration', + active: true, + business_profile: { headline: PORTAL_HEADLINE }, + metadata: { webklar: 'wartungs-abo' }, + }) + const before = st.calls.length + const id = await ensurePortalConfiguration() + assert.equal(id, 'bpc_ok') + const updateCalls = st.calls.slice(before).filter((c) => c.method === 'POST' && c.path.startsWith('/v1/billing_portal/configurations/')) + assert.deepEqual(updateCalls, []) +}) + test('Spiegel: termStartAt aus Metadaten (Wechsel), sonst Leistungsbeginn; storageUnits', async () => { st.subscriptions.set( 'sub_s', diff --git a/test/support/fakeStripe.js b/test/support/fakeStripe.js index e916908..d305e39 100644 --- a/test/support/fakeStripe.js +++ b/test/support/fakeStripe.js @@ -66,6 +66,14 @@ export async function startFakeStripe() { } if (method === 'POST' && path === '/v1/prices') { const data = unflatten(body) + // Wie echtes Stripe: ein lookup_key darf nur an einem aktiven Preis gleichzeitig haengen + // (Fix round 1, Important 1 - haertet den Nachbau, ensurePrice fragt vorher ohnehin per GET) + if (data.lookup_key) { + const clash = [...prices.values()].find((p) => p.lookup_key === data.lookup_key && p.active !== false) + if (clash) { + return [400, { error: { type: 'invalid_request_error', param: 'lookup_key', message: `An active price already exists for lookup_key: '${data.lookup_key}'.` } }] + } + } const obj = { id: nextId('price'), object: 'price', @@ -84,6 +92,10 @@ export async function startFakeStripe() { if (method === 'GET' && (m = path.match(/^\/v1\/invoices\/([^/]+)$/))) { return invoices.has(m[1]) ? [200, invoices.get(m[1])] : noSuch('invoice', m[1]) } + // scripts/stripe-products.mjs --pruefen liest das Produkt zurueck (Beschreibung, Bild) + if (method === 'GET' && (m = path.match(/^\/v1\/products\/([^/]+)$/))) { + return products.has(m[1]) ? [200, products.get(m[1])] : noSuch('product', m[1]) + } if (method === 'POST' && path === '/v1/products') { const data = unflatten(body) const obj = { @@ -93,6 +105,7 @@ export async function startFakeStripe() { name: data.name || '', description: data.description ?? null, statement_descriptor: data.statement_descriptor ?? null, + images: data.images || [], metadata: data.metadata || {}, } products.set(obj.id, obj) @@ -104,6 +117,13 @@ export async function startFakeStripe() { if (method === 'POST' && path === '/v1/coupons') { const data = unflatten(body) const id = data.id || nextId('coupon') + // Wie echtes Stripe: Name auf 40 Zeichen begrenzt, IDs eindeutig (Fix round 1, Important 1) + if (data.name && data.name.length > 40) { + return [400, { error: { type: 'invalid_request_error', param: 'name', message: 'Name must be no more than 40 characters.' } }] + } + if (coupons.has(id)) { + return [400, { error: { type: 'invalid_request_error', message: `Coupon with ID '${id}' already exists.` } }] + } const obj = { id, object: 'coupon',