Kundenansicht P6b: Team-Weg der Analyse im Abo-Modell (WOMS)

POST/GET /api/admin/analyse/:projectId kennt jetzt das Abo-Modell:
- Gilt aboModellFuerKunde, prüft das Einschalten das Abo über aboDeckt
  (Hosting und Wartung decken die Analyse); fehlt es, 409 mit code
  abo_fehlt, grund, wechsel (und ab) wie bei der Team-Aktivierung der
  anderen Funktionen, bevor etwas geschrieben wird. Lesefehler: 503.
- Das neu eingeschaltete Dokument trägt den Abo-Marker (unlockedBy und
  einrichtungAbrechnung 'abo', istAboModell); activateAnalyse nimmt dazu
  den Parameter abrechnung, setzt ihn im selben Schritt wie den Zustand
  und stellt ihn bei der Rücknahme wieder her.
- GET: Eignung und Text folgen dem Abo-Modell (Hosting-oder-Wartungs-Text).
- Alle anderen Kunden und das Ausschalten laufen unverändert.

Tests: test/adminAnalyseAboModell.test.js (9 Fälle).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ClaudeandClaude Sonnet 5.5 committed 2026-10-16 17:06:33 +00:00
1 parent 72c5fa9fea
commit 4473a746ee
3 files changed
+235 -9

No files matched your search

+205
View File
@@ -0,0 +1,205 @@
import { test, after, beforeEach, afterEach, mock } from 'node:test'
import assert from 'node:assert/strict'
import { startAppwriteMock } from './support/appwriteMock.js'
import { startFakeStripe } from './support/fakeStripe.js'
import { mailSink } from './support/mailSink.js'
import { schemaKeys } from './support/schema.js'
import { useTestEnv } from './support/testEnv.js'
// Team-Weg der Analyse im Abo-Modell (Nachzug P6b): POST/GET /api/admin/analyse/:projectId. Kunde c1 (k@example.invalid) steht in der
// Pilotliste, c2 nicht. Im Abo-Modell reicht Hosting oder Wartung (aboDeckt), das Dokument traegt den Abo-Marker; sonst bleibt alles wie heute.
const ANALYSE_KEYS = ['accentColor', 'avvVersion', 'avvAcceptedAt', 'avvAcceptedBy', 'activatedAt', 'offSince', 'privacyTicketId', 'activatedMailAt', 'avvConsentDate', 'avvConsentChannel', 'removalTicketId', 'publishTicketId', 'audienceConfirmed', 'audienceTextVersion']
const CONSENT_KEYS = ['customerId', 'projectId', 'siteKey', 'event', 'avvVersion', 'via', 'acceptedAt', 'acceptedBy', 'textformDate', 'textformChannel', 'audienceConfirmed', 'audienceTextVersion']
const aw = await startAppwriteMock({
schema: {
portalFeatures: [...schemaKeys('portalFeatures'), ...ANALYSE_KEYS],
subscriptions: schemaKeys('subscriptions'),
contractEvents: schemaKeys('contractEvents'),
featureConsents: schemaKeys('featureConsents'),
analyseConsents: CONSENT_KEYS,
},
})
const st = await startFakeStripe()
useTestEnv({ appwriteUrl: aw.url, stripeUrl: st.url })
const { config } = await import('../server/config.js')
const { startTestApp, rawGet, post } = await import('./support/testApp.js')
const { hostingDoc, seedFixtures, subscriptionDoc, wartungDoc } = await import('./support/fixtures.js')
const { default: adminAnalyseRoutes } = await import('../server/routes/admin/analyse.js')
const { deleteDocument } = await import('../server/services/appwriteAdmin.js')
const { istAboModell } = await import('../server/services/aboModell.js')
const { gleicheAboFunktionenAb } = await import('../server/services/aboFunktionenAbgleich.js')
const { analyseUnterlagen } = await import('../server/services/aboUnterlagen.js')
const an = await import('../server/services/analyse.js')
const sf = await import('../server/services/siteFeatures.js')
const { setMailTransportForTests } = await import('../server/services/mailer.js')
const app = await startTestApp({ '/api/admin/analyse': adminAnalyseRoutes })
setMailTransportForTests(mailSink())
const vorher = { mode: config.kundenansichtNeu.mode, pilotEmails: [...config.kundenansichtNeu.pilotEmails], analyse: config.analyse.enabled }
after(() => {
Object.assign(config.kundenansichtNeu, { mode: vorher.mode, pilotEmails: vorher.pilotEmails })
config.analyse.enabled = vorher.analyse
setMailTransportForTests(null)
return Promise.all([app.close(), aw.close(), st.close()])
})
const putSiteAufrufe = []
an.analyseDeps.client = {
putSite: async (siteKey, body) => putSiteAufrufe.push({ siteKey, ...body }),
stopSite: async () => {},
getStats: async () => ({ pv: 5 }),
heatToken: () => 'token',
}
an.analyseDeps.rebuild = async () => {}
const recordConsentOriginal = an.analyseDeps.recordConsent
const JETZT = new Date()
const todayBerlin = () => new Intl.DateTimeFormat('sv-SE', { timeZone: 'Europe/Berlin' }).format(new Date())
const hdr = { headers: { Authorization: 'Bearer jwt-admin' } }
const tf = (extra = {}) => ({ textformDate: todayBerlin(), textformChannel: 'chat', audienceConfirmed: true, ...extra })
const einschalten = (id, extra = {}) => post(`/api/admin/analyse/${id}`, { on: true, ...tf(), ...extra }, hdr)
const lesen = (id) => rawGet(`/api/admin/analyse/${id}`, hdr)
const abo = (doc) => aw.seed('subscriptions', subscriptionDoc('sub_h', doc))
const featureDoc = (c, p) => sf.getFeatureDoc(c, p, 'analyse')
const consents = () => [...aw.docs('analyseConsents').values()]
// aw.docs() liefert eine Kopie: Dokumente werden ueber die API geloescht
const leere = async (...collections) => {
for (const col of collections) for (const id of aw.docs(col).keys()) await deleteDocument(col, id)
}
const nichtsGeschrieben = async (c, p) => {
assert.equal(await featureDoc(c, p), null, 'kein Dokument')
assert.deepEqual([putSiteAufrufe.length, consents().length, aw.docs('workorders').size], [0, 0, 0])
}
beforeEach(async () => {
putSiteAufrufe.length = 0
await leere('portalFeatures', 'featureConsents', 'analyseConsents', 'subscriptions', 'websiteProjects', 'contractEvents', 'workorders')
seedFixtures(aw) // c1 mit Hosting-Abo sub_h, c2 mit sub_h2
aw.seed('websiteProjects', { $id: 'p1', customerId: 'c1', projectName: 'Bäckerei', subdomain: 'baeckerei', liveDomain: 'baeckerei.de', isPublic: true })
aw.seed('websiteProjects', { $id: 'p2', customerId: 'c1', projectName: 'Privat', subdomain: 'privat', isPublic: false })
aw.seed('websiteProjects', { $id: 'p3', customerId: 'c2', projectName: 'Café', subdomain: 'cafe', isPublic: true })
config.kundenansichtNeu.mode = 'pilot'
config.kundenansichtNeu.pilotEmails = ['k@example.invalid']
config.analyse.enabled = true
an.analyseDeps.recordConsent = recordConsentOriginal
mock.method(console, 'error', () => {})
mock.method(console, 'warn', () => {})
mock.method(console, 'log', () => {})
})
afterEach(() => mock.restoreAll())
test('Hosting-Kunde im Abo-Modell: 200, Analyse aktiv, Abo-Marker am Dokument, Nachweis der Textform, Fassung der Abo-Unterlagen', async () => {
const r = await einschalten('p1')
assert.deepEqual([r.status, r.body], [200, { ok: true, state: 'active' }])
const d = await featureDoc('c1', 'p1')
assert.deepEqual([d.state, d.unlockedBy, d.einrichtungAbrechnung, istAboModell(d)], ['active', 'abo', 'abo', true])
assert.deepEqual([d.avvConsentDate, d.avvConsentChannel, d.audienceConfirmed, d.avvVersion], [todayBerlin(), 'chat', true, analyseUnterlagen().avvVersion])
assert.deepEqual([putSiteAufrufe.length, putSiteAufrufe[0].active], [1, true])
const [n] = consents()
assert.deepEqual([consents().length, n.via, n.textformDate, n.textformChannel, n.audienceConfirmed, n.avvVersion], [1, 'woms', todayBerlin(), 'chat', true, analyseUnterlagen().avvVersion])
// das Team beendet wieder: ohne Abo-Pruefung
await leere('subscriptions')
const aus = await post('/api/admin/analyse/p1', { on: false }, hdr)
assert.deepEqual([aus.status, aus.body], [200, { ok: true, state: 'off' }])
})
test('Wartungs-Kunde im Abo-Modell zählt auch; die Tagesprüfung und der Abo-Ende-Abgleich lassen das Dokument in Ruhe', async () => {
await leere('subscriptions')
abo(wartungDoc)
assert.equal((await einschalten('p1')).status, 200)
assert.equal(istAboModell(await featureDoc('c1', 'p1')), true)
await leere('subscriptions')
abo(hostingDoc)
const tag = await an.runAboCheck({ now: JETZT })
assert.deepEqual(tag.deactivated, [])
const abgleich = await gleicheAboFunktionenAb(JETZT)
assert.deepEqual([abgleich.abgeschaltet, abgleich.fehler], [0, 0])
assert.equal((await featureDoc('c1', 'p1')).state, 'active')
})
test('Kunde ohne Abo-Modell und nur Hosting: wie heute abgewiesen (403, Wartungs-Text), nichts geschrieben; Modus off ebenso', async () => {
const alt = 'Die Website-Analyse gibt es nur mit einem laufenden Wartungs-Abo.'
const r = await einschalten('p3') // c2 steht nicht in der Pilotliste
assert.deepEqual([r.status, r.body], [403, { error: alt }])
await nichtsGeschrieben('c2', 'p3')
config.kundenansichtNeu.mode = 'off'
const aus = await einschalten('p1')
assert.deepEqual([aus.status, aus.body], [403, { error: alt }])
await nichtsGeschrieben('c1', 'p1')
const g = await lesen('p3')
assert.deepEqual([g.status, g.body.eligible, g.body.reasonText], [200, false, alt])
})
test('Kunde ohne Abo-Modell mit Wartungs-Abo: wie heute, ohne Marker', async () => {
await leere('subscriptions')
aw.seed('subscriptions', subscriptionDoc('sub_w2', { ...wartungDoc, customerId: 'c2', email: 'k2@example.invalid' }))
const r = await einschalten('p3')
assert.deepEqual([r.status, r.body], [200, { ok: true, state: 'active' }])
const d = await featureDoc('c2', 'p3')
assert.deepEqual([d.state, d.unlockedBy ?? null, d.einrichtungAbrechnung ?? null, istAboModell(d)], ['active', null, null, false])
assert.equal(d.avvVersion, config.analyse.avvVersion)
})
test('Abo-Modell ohne deckendes Abo: 409 abo_fehlt mit Grund, nichts geschrieben', async () => {
const faelle = [
[null, 'kein_abo', undefined],
[{ ...hostingDoc, status: 'canceled' }, 'kein_abo', undefined],
[{ ...hostingDoc, cancelAtPeriodEnd: true }, 'gekuendigt', undefined],
[{ ...hostingDoc, status: 'past_due' }, 'nicht_aktiv', undefined],
[{ ...wartungDoc, status: 'trialing', trialEnd: '2099-01-01T05:00:00.000Z' }, 'beginnt_spaeter', '2099-01-01T05:00:00.000Z'],
]
for (const [doc, grund, ab] of faelle) {
await leere('subscriptions')
if (doc) abo(doc)
const r = await einschalten('p1')
assert.deepEqual([r.status, r.body.code, r.body.grund, r.body.wechsel, r.body.ab, typeof r.body.error], [409, 'abo_fehlt', grund, false, ab, 'string'], grund)
await nichtsGeschrieben('c1', 'p1')
}
})
test('Abo nicht lesbar: 503 statt Einschalten (fail-closed), nichts geschrieben; danach klappt es', async () => {
aw.failNext({ collection: 'subscriptions', method: 'GET', status: 500 })
const r = await einschalten('p1')
assert.deepEqual([r.status, r.body.code, typeof r.body.error], [503, undefined, 'string'])
await nichtsGeschrieben('c1', 'p1')
assert.equal((await einschalten('p1')).status, 200)
})
test('Reihenfolge: ungültige Angaben (400) und fehlendes Projekt (404) kommen vor abo_fehlt; nicht öffentliches Projekt ist 409 ohne Code', async () => {
await leere('subscriptions')
assert.equal((await einschalten('p1', { audienceConfirmed: undefined })).status, 400)
assert.equal((await einschalten('p1', { textformChannel: 'telefon' })).status, 400)
assert.equal((await einschalten('nix')).status, 404)
await nichtsGeschrieben('c1', 'p1')
abo(hostingDoc)
const privat = await einschalten('p2')
assert.deepEqual([privat.status, privat.body.code], [409, undefined])
await nichtsGeschrieben('c1', 'p2')
})
test('Misslingt der Nachweis, nimmt der Server alles zurück: Dokument aus, kein Marker', async () => {
an.analyseDeps.recordConsent = async () => {
throw new Error('Nachweis nicht gespeichert')
}
const r = await einschalten('p1')
assert.equal(r.status, 500)
const d = await featureDoc('c1', 'p1')
assert.deepEqual([d.state, d.unlockedBy ?? null, d.einrichtungAbrechnung ?? null], ['off', null, null])
assert.deepEqual(putSiteAufrufe.map((a) => a.active), [true, false])
an.analyseDeps.recordConsent = recordConsentOriginal
assert.equal((await einschalten('p1')).status, 200) // erneut versuchbar
assert.equal(istAboModell(await featureDoc('c1', 'p1')), true)
})
test('GET: Eignung und Text folgen dem Abo-Modell (Hosting ok, ohne Abo der Hosting-oder-Wartungs-Text), Rest unverändert', async () => {
const ok = await lesen('p1')
assert.deepEqual([ok.status, ok.body.eligible, ok.body.reasonText, ok.body.state, ok.body.enabled, ok.body.avvVersion], [200, true, null, null, true, config.analyse.avvVersion])
assert.deepEqual(Object.keys(ok.body).sort(), ['accentColor', 'activatedAt', 'avvAcceptedAt', 'avvAcceptedBy', 'avvConsentChannel', 'avvConsentDate', 'avvVersion', 'eligible', 'enabled', 'offSince', 'privacy', 'reasonText', 'state'].sort())
const privat = await lesen('p2')
assert.deepEqual([privat.body.eligible, privat.body.reasonText], [false, an.ELIGIBILITY_MESSAGES.nicht_oeffentlich])
assert.equal((await einschalten('p1')).status, 200)
assert.equal((await lesen('p1')).body.state, 'active')
await leere('subscriptions')
const ohne = await lesen('p1')
assert.deepEqual([ohne.body.eligible, ohne.body.reasonText], [false, 'Die Website-Analyse gibt es nur mit einem laufenden Hosting- oder Wartungs-Abo.'])
})