diff --git a/server/routes/admin/analyse.js b/server/routes/admin/analyse.js index b1cec8e..749527d 100644 --- a/server/routes/admin/analyse.js +++ b/server/routes/admin/analyse.js @@ -3,7 +3,9 @@ import { Router } from 'express' import { config } from '../../config.js' import { getDocument } from '../../services/appwriteAdmin.js' import { requireAppwriteTeam } from '../../middleware/appwriteStaff.js' -import { activateAnalyse, analyseEligibility, controllerView, deactivateAnalyse, ELIGIBILITY_MESSAGES, validateTextform } from '../../services/analyse.js' +import { activateAnalyse, analyseEligibility, controllerView, deactivateAnalyse, eligibilityMessage, validateTextform } from '../../services/analyse.js' +import { aboModellFuerKunde } from '../../services/aboFunktionen.js' +import { pruefeAboDeckung } from '../../services/funktionEinschalten.js' import { getFeatureDoc } from '../../services/siteFeatures.js' const router = Router() @@ -13,7 +15,9 @@ router.use(requireAppwriteTeam) function sendError(res, err) { const status = [400, 403, 404, 409, 503].includes(err.status) && !err.type ? err.status : 500 if (status === 500) console.error('[admin-analyse]', err.message) - res.status(status).json({ error: status === 500 ? 'Die Analyse konnte nicht geändert werden' : err.message }) + // Abo-Modell: code, grund, wechsel (und ab) der 409 abo_fehlt gehen flach in die Antwort, wie bei der Team-Aktivierung der Funktionen + const zusatz = status === 409 && err.code === 'abo_fehlt' && err.body && typeof err.body === 'object' ? err.body : {} + res.status(status).json({ ...zusatz, error: status === 500 ? 'Die Analyse konnte nicht geändert werden' : err.message }) } // Lesezugriff fuer das WOMS: Zustand + AVV-Angaben (nie siteKey oder Geheimnisse) @@ -27,9 +31,11 @@ router.get('/:projectId', async (req, res) => { throw err } const customerId = project.customerId || '' + // Abo-Modell (Kundenansicht neu): Hosting oder Wartung genuegt; fuer alle anderen Kunden gilt die Wartungs-Regel wie bisher + const aboModell = await aboModellFuerKunde(customerId) const [doc, eligibility, controller] = await Promise.all([ customerId ? getFeatureDoc(customerId, project.$id, 'analyse') : null, - analyseEligibility(customerId, project.$id), + analyseEligibility(customerId, project.$id, { aboModell }), controllerView(customerId), ]) res.json({ @@ -45,7 +51,7 @@ router.get('/:projectId', async (req, res) => { activatedAt: doc?.activatedAt || null, offSince: doc?.offSince || null, eligible: eligibility.ok, - reasonText: eligibility.reason ? ELIGIBILITY_MESSAGES[eligibility.reason] : null, + reasonText: eligibility.reason ? eligibilityMessage(eligibility.reason, { aboModell }) : null, }) } catch (err) { sendError(res, err) @@ -75,6 +81,10 @@ router.post('/:projectId', async (req, res) => { const customerId = project.customerId if (!customerId) return res.status(400).json({ error: 'Projekt hat keinen Kunden' }) const by = String(req.appwriteUser?.name || req.appwriteUser?.email || 'Mitarbeiter').slice(0, 100) + // Abo-Modell (Kundenansicht neu, V10): das Abo muss die Analyse decken (409 abo_fehlt mit grund, bevor etwas geschrieben wird); das + // Dokument bekommt den Abo-Marker. Ausschalten braucht kein Abo. Alle anderen Kunden: alles wie bisher. + const aboModell = on && (await aboModellFuerKunde(customerId)) + if (aboModell) await pruefeAboDeckung(customerId, 'analyse') const { doc } = on ? await activateAnalyse({ customerId, @@ -83,6 +93,7 @@ router.post('/:projectId', async (req, res) => { by, textform, audienceConfirmed, + ...(aboModell ? { aboModell: true, abrechnung: 'abo' } : {}), }) : await deactivateAnalyse({ customerId, projectId: project.$id, by }) res.json({ ok: true, state: doc?.state || 'off' }) diff --git a/server/services/analyse.js b/server/services/analyse.js index 674c72c..490c52b 100644 --- a/server/services/analyse.js +++ b/server/services/analyse.js @@ -10,6 +10,7 @@ import { triggerRebuild } from './previewRebuild.js' import { ensureFeatureDoc, getFeatureDoc, newSiteKey, stateFields, assertOwnProject } from './siteFeatures.js' import { laeuft } from './aboStatus.js' import { aboDeckt, aboLaeuftFuer, aboModellFuerKunde } from './aboFunktionen.js' +import { ABRECHNUNGEN } from './aboModell.js' import { consentAboAnalyse } from './featureRegistry.js' import { createFeatureTicket } from './ticketAdmin.js' import { berlinDateTime } from './berlinTime.js' @@ -290,11 +291,15 @@ async function sendK18(doc, project) { } /** - * Analyse einschalten. aboModell (neue Ansicht, nur durch den Kunden): ein Hosting- oder Wartungs-Abo genuegt, die erwartete Fassung - * ist die der Abo-Erklaerung (consentAboAnalyse().avvVersion). nachweis: async () => void, laeuft im selben try wie recordConsent, nach - * dem Dokument und davor; ein Fehler nimmt alles zurueck (kein "on" ohne Nachweis). Beides nur bei einer neuen Aktivierung. + * Analyse einschalten. aboModell (neue Ansicht, Kunde oder Team): ein Hosting- oder Wartungs-Abo genuegt, die Fassung ist die der + * Abo-Erklaerung (consentAboAnalyse().avvVersion; beim Kunden auch die erwartete). nachweis: async () => void, laeuft im selben try wie + * recordConsent, nach dem Dokument und davor; ein Fehler nimmt alles zurueck (kein "on" ohne Nachweis). Beides nur bei einer neuen Aktivierung. + * abrechnung (Team im Abo-Modell, Nachzug P6b): 'abo' | 'projekt' setzt den Marker des Abo-Modells (unlockedBy und einrichtungAbrechnung, + * istAboModell) am Dokument, ebenfalls nur bei einer neuen Aktivierung und im selben Schritt (die Rücknahme stellt ihn wieder her); null + * (Vorgabe) schreibt keinen Marker. */ -export async function activateAnalyse({ customerId, projectId, accentColor, consent, by = 'customer', actor, textform, audienceConfirmed, now = new Date(), aboModell = false, nachweis = null }) { +export async function activateAnalyse({ customerId, projectId, accentColor, consent, by = 'customer', actor, textform, audienceConfirmed, now = new Date(), aboModell = false, nachweis = null, abrechnung = null }) { + if (abrechnung !== null && !ABRECHNUNGEN.includes(abrechnung)) throw httpError(400, 'Unbekannte Abrechnung') const viaCustomer = by === 'customer' const avvVersion = aboModell ? consentAboAnalyse().avvVersion : config.analyse.avvVersion let accepted @@ -362,6 +367,7 @@ export async function activateAnalyse({ customerId, projectId, accentColor, cons avvConsentChannel: proof.channel, audienceConfirmed: true, audienceTextVersion: entry.audienceTextVersion, + ...(abrechnung ? { unlockedBy: abrechnung, einrichtungAbrechnung: abrechnung } : {}), activatedAt: at, offSince: '', activatedMailAt: '', // jede neue Aktivierung bekommt ihre K18 @@ -379,7 +385,11 @@ export async function activateAnalyse({ customerId, projectId, accentColor, cons .putSite(siteKey, { projectId, domains: analyseDomains(project), active: false }) .catch((e) => console.warn(`[analyse] Rücknahme für Projekt ${projectId} fehlgeschlagen:`, e.message)) if (updated) { - await updateDocument(config.collections.portalFeatures, existing.$id, { ...stateFields(existing.state || 'off'), offSince: existing.offSince || '' }) + await updateDocument(config.collections.portalFeatures, existing.$id, { + ...stateFields(existing.state || 'off'), + offSince: existing.offSince || '', + ...(abrechnung ? { unlockedBy: existing.unlockedBy ?? null, einrichtungAbrechnung: existing.einrichtungAbrechnung ?? null } : {}), + }) .catch((e) => console.warn(`[analyse] Zurücksetzen für Projekt ${projectId} fehlgeschlagen:`, e.message)) } throw err diff --git a/test/adminAnalyseAboModell.test.js b/test/adminAnalyseAboModell.test.js new file mode 100644 index 0000000..f33b07b --- /dev/null +++ b/test/adminAnalyseAboModell.test.js @@ -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.']) +})