diff --git a/apps/api/src/modules/customers/index.ts b/apps/api/src/modules/customers/index.ts index dc4ec2e..92e0d2b 100644 --- a/apps/api/src/modules/customers/index.ts +++ b/apps/api/src/modules/customers/index.ts @@ -17,6 +17,7 @@ import { AppError } from '../../core/errors.js'; import { config } from '../../core/config.js'; import { sendTemplateMail } from '../../core/mail.js'; import type { KcModule } from '../../core/module.js'; +import { enqueueCustomerSync } from '@kc/platform/customerSync'; const deMoney = (cents: number) => (cents / 100).toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }); const INTERVAL_LABEL: Record = { once: 'einmalig', monthly: 'monatlich', yearly: 'jährlich' }; @@ -115,6 +116,16 @@ export const customersModule: KcModule = { * Sicht dieses Kunden um (echte Rechteeinschränkung, nicht nur eine andere Oberfläche). Admin/Superadmin * only; Grund ist Pflicht und wird protokolliert. Lässt sich nicht verschachteln (erfordert customers.read, * das während einer laufenden Impersonation nicht mehr greift). */ + /** Kundenangaben an allen Lizenzen dieses Kunden beim Anbieter nachziehen bzw. (Löschanspruch) leeren (#64). */ + app.post('/admin/customers/:id/provider-sync', async (req) => { + const a = requirePermission(req, 'customers.write'); + const { id } = z.object({ id: z.string().uuid() }).parse(req.params); + const { mode } = z.object({ mode: z.enum(['update', 'erase']) }).parse(req.body); + if (!(await one('SELECT 1 AS x FROM organizations WHERE id = ?', [id]))) throw notFound(); + await enqueueCustomerSync(id, mode, a.user.id, req.correlationId); + await audit({ actorType: 'user', actorId: a.user.id, orgId: id, action: `customer.provider_sync.request.${mode}`, resourceType: 'organization', resourceId: id, correlationId: req.correlationId, ip: clientIp(req) }); + return { status: 'queued' }; + }); app.post('/admin/customers/:id/impersonate', async (req) => { const a = requirePermission(req, 'customers.impersonate'); const { id } = z.object({ id: z.string().uuid() }).parse(req.params); @@ -178,6 +189,7 @@ export const customersModule: KcModule = { if (keys.length) await run(`UPDATE billing_profiles SET ${keys.map((k) => `${cols[k]} = ?`).join(', ')} WHERE org_id = ?`, [...keys.map((k) => patch[k] ?? null), id], c); }); await audit({ actorType: 'user', actorId: a.user.id, orgId: id, action: 'customer.update', resourceType: 'organization', resourceId: id, correlationId: req.correlationId, ip: clientIp(req), before, after: b }); + if (b.name !== undefined && b.name !== before.name) await enqueueCustomerSync(id, 'update', a.user.id, req.correlationId); // Kundenname an Lizenzen nachziehen (#64) return loadOrg(id); }); diff --git a/apps/api/src/modules/identity/index.ts b/apps/api/src/modules/identity/index.ts index 3a0de6a..cfa6269 100644 --- a/apps/api/src/modules/identity/index.ts +++ b/apps/api/src/modules/identity/index.ts @@ -14,6 +14,7 @@ import { can, staffPermissions } from '../../core/policy.js'; import { createInvitedUser, createToken, mailInvite, inviteLink, resetLink } from '../../core/accounts.js'; import { sendTemplateMail } from '../../core/mail.js'; import type { KcModule } from '../../core/module.js'; +import { enqueueSyncForOwner } from '@kc/platform/customerSync'; const ARGON = { memoryCost: 19456, timeCost: 2, parallelism: 1 }; const MAX_FAILS = 5; @@ -307,6 +308,7 @@ export const identityModule: KcModule = { await run('UPDATE users SET status = COALESCE(?, status), staff_role = COALESCE(?, staff_role) WHERE id = ?', [b.status ?? null, b.staffRole ?? null, id], c); }); if (b.status === 'disabled') await run('UPDATE sessions SET revoked_at = UTC_TIMESTAMP(3) WHERE user_id = ? AND revoked_at IS NULL', [id]); + if (emailChanged || (b.name !== undefined && b.name !== u.name)) await enqueueSyncForOwner(id, a.user.id, req.correlationId); // Inhaber-Angaben an Lizenzen (#64) await audit({ actorType: 'user', actorId: a.user.id, action: 'user.update', resourceType: 'user', resourceId: id, correlationId: req.correlationId, ip: clientIp(req), before: { status: u.status, staffRole: u.staff_role, ...(emailChanged ? { email: u.email } : {}), ...(b.name !== undefined ? { name: u.name } : {}) }, after: b }); return { status: 'ok' }; }); diff --git a/apps/api/test/worker.test.ts b/apps/api/test/worker.test.ts index 29eb8bc..2cb7fb6 100644 --- a/apps/api/test/worker.test.ts +++ b/apps/api/test/worker.test.ts @@ -72,3 +72,25 @@ describe('Worker: Discord-Nachrichten im Ticketkanal (#110)', () => { expect((await messages()).length).toBe(before); expect(replies.at(-1)).toMatch(/geschlossen/); }); }); + +describe('Kundenangaben beim Anbieter nachziehen (#64)', () => { + it('Namensänderung plant den Abgleich; Objekte ohne Fähigkeit werden übersprungen und gezählt, keine Daten in Logs', async () => { + const { buildApp } = await import('../src/server.js'); const { call, code, login } = await import('./helpers.js'); + const app = await buildApp(); await app.ready(); + await makeUser({ email: 'sync-admin@example.com', kind: 'staff', staffRole: 'superadmin' }); const { client } = await login(app, 'sync-admin@example.com'); + const s = (await call(app, client, 'POST', '/auth/mfa/setup')).json(); await call(app, client, 'POST', '/auth/mfa/confirm', { code: code(s.secret) }); + const org = (await call(app, client, 'POST', '/admin/customers', { type: 'business', name: 'Sync Alt', owner: { email: 'sync-owner@example.com', name: 'Owner' } })).json().id as string; + const inst = randomUUID(); await run("INSERT INTO connector_instances (id, connector_key, name, config_json, enabled) VALUES (?, 'mock', CONCAT('Mock ', ?), '{}', 1)", [inst, inst.slice(0, 8)]); + await run("INSERT INTO resources (id, instance_id, external_ref, type, name, state, org_id, synced_at) VALUES (UUID(), ?, 'm-1', 'license', 'Lizenz', 'active', ?, UTC_TIMESTAMP(3))", [inst, org]); + expect((await call(app, client, 'PATCH', `/admin/customers/${org}`, { name: 'Sync Neu' })).statusCode).toBe(200); + const job = (await one("SELECT id FROM jobs WHERE type = 'customer.provider_sync' AND JSON_VALUE(payload, '$.orgId') = ?", [org]))!; + for (let i = 0; i < 20 && (await one('SELECT status FROM jobs WHERE id = ?', [job.id]))!.status === 'scheduled'; i++) await runJob(job.id); // ältere Aufträge kommen zuerst + const j = (await one('SELECT status, last_error FROM jobs WHERE id = ?', [job.id]))!; + expect(j.status).toBe('succeeded'); expect(j.last_error).toMatch(/0 aktualisiert, 1 übersprungen/); + expect((await call(app, client, 'POST', `/admin/customers/${org}/provider-sync`, { mode: 'erase' })).statusCode).toBe(200); + expect(await one("SELECT 1 AS x FROM jobs WHERE type = 'customer.provider_sync' AND JSON_VALUE(payload, '$.mode') = 'erase' AND JSON_VALUE(payload, '$.orgId') = ?", [org])).toBeTruthy(); + const audit = await query("SELECT after_json FROM audit_events WHERE action = 'customer.provider_sync.update' AND org_id = ?", [org]); + expect(JSON.stringify(audit)).not.toMatch(/Sync Neu|sync-owner/); // keine personenbezogenen Werte im Audit + await app.close(); + }); +}); diff --git a/apps/web/src/app/(app)/admin/kunden/[id]/page.tsx b/apps/web/src/app/(app)/admin/kunden/[id]/page.tsx index f8236f5..fc8e21a 100644 --- a/apps/web/src/app/(app)/admin/kunden/[id]/page.tsx +++ b/apps/web/src/app/(app)/admin/kunden/[id]/page.tsx @@ -72,6 +72,10 @@ export default function Kunde() {
} + {w &&

Kundenangaben bei Anbietern

+

Name, Kundennummer und Inhaber werden bei Änderungen automatisch an die Lizenzen dieses Kunden übertragen (soweit der Anbieter das unterstützt). Bei einem Löschanspruch lassen sich die personenbezogenen Angaben dort leeren; Bestell- und Vertragsnummern bleiben beim Anbieter erhalten.

+
+
}

Stammdaten & Rechnungsanschrift

{o.customerType === 'business' && } diff --git a/apps/worker/src/jobs.ts b/apps/worker/src/jobs.ts index 955a5f5..be5f21d 100644 --- a/apps/worker/src/jobs.ts +++ b/apps/worker/src/jobs.ts @@ -5,7 +5,7 @@ import { notifyAdmin, postTicketMessage } from './discord.js'; import { JobFailure } from '@kc/platform/jobs'; import { sendTemplateMail } from '@kc/platform/mail'; import { alertText } from '@kc/platform/monitor'; -import { executeAction, executeChild, provisionOrder, syncInstance, type ChildPayload, type ExecutePayload } from '@kc/connectors'; +import { executeAction, executeChild, provisionOrder, syncCustomerInfo, syncInstance, type ChildPayload, type CustomerSyncPayload, type ExecutePayload } from '@kc/connectors'; // Kennung dieses Worker-Prozesses (nur zur Diagnose in locked_by, kein Sicherheitsmerkmal). const WORKER_ID = `${hostname()}:${process.pid}:${randomUUID().slice(0, 8)}`; @@ -45,6 +45,7 @@ handlers['connector.sync'] = async (p, j) => { handlers['order.provision'] = (p: { orderId: string }, j) => provisionOrder(p.orderId, j); handlers['connector.child'] = (p: ChildPayload, j) => executeChild(p, j.id, j.correlationId, () => j.attempt >= j.maxAttempts); handlers['connector.execute'] = (p: ExecutePayload, j) => executeAction(p, j.id, j.correlationId); +handlers['customer.provider_sync'] = (p: CustomerSyncPayload, j) => syncCustomerInfo(p, j.correlationId); const backoff = (attempt: number) => Math.min(3600, 30 * 2 ** attempt); // Sekunden, exponentiell /** Holt einen fälligen Auftrag (SKIP LOCKED) und führt ihn aus. Liefert false, wenn nichts zu tun war. diff --git a/docs/connector-lizenzsystem.md b/docs/connector-lizenzsystem.md index 7441789..625cd5f 100644 --- a/docs/connector-lizenzsystem.md +++ b/docs/connector-lizenzsystem.md @@ -72,6 +72,6 @@ Normalisiert (`mapLicense`): `externalRef = "4711"`, `type = license`, Name = Pr | Sperren/Verlängern nur per PUT, Laufzeit approximiert | Lebenszyklus-Endpunkte mit Idempotenz, explizites Ablaufdatum | | Eine Aktivierung je Lizenz | mehrere Aktivierungen (Aktivierungslimit), Freigabe einzeln | | Naive Ortszeit | `utc_timestamps` | -| Keine Kundendaten am Provider | `customer_info` bei Anlage; Änderung/Löschung danach offen (#64) | +| Keine Kundendaten am Provider | `customer_info` bei Anlage; Änderungen (Kundenname, Inhaber-Name/-E-Mail) werden per Auftrag `customer.provider_sync` nachgezogen, Löschanspruch leert Name/Ansprechpartner/E-Mail/Kundennummer (`PUT /licenses/{id}`, #64). Unveränderlich beim Anbieter und bewusst nicht gelöscht: Quelle, Bestell- und Vertragsnummer (keine direkten Personendaten; Aufbewahrung) | Abnahme gegen den aktuellen Licensing-Source (Schema-/Endpunktvergleich) erst nach dem Abgleich Server ↔ Forge (#114). Testabdeckung im KC: `packages/connector-licensing/test` (18 Tests, gegen nachgebildete Antworten; keine echten Schlüssel in Fixtures). diff --git a/packages/connector-licensing/src/index.ts b/packages/connector-licensing/src/index.ts index a5ee254..d194c6c 100644 --- a/packages/connector-licensing/src/index.ts +++ b/packages/connector-licensing/src/index.ts @@ -245,6 +245,15 @@ export function createLicensingConnector(deps: LicensingDeps = {}): Connector { if (productId && created.product_id !== productId) throw new ConnectorError('INVALID_RESPONSE', `Lizenz ${created.id} wurde ohne das bestellte Produkt ${productId} angelegt`); return { resource: map(created, new Map(programs.map((p) => [p.id, p.name])), zone) }; }, + async updateCustomerInfo(ctx, externalRef, info) { + if (!allows(ctx, 'licenses:write')) throw new ConnectorError('UNSUPPORTED', 'Zugang ohne Schreibrecht (licenses:write)'); + if (!(await features(ctx)).includes('customer_info')) throw new ConnectorError('UNSUPPORTED', 'Das Lizenzsystem kennt keine Kundenangaben'); + // Zielwerte setzen (wiederholbar). null leert die personenbezogenen Felder; source/order_ref/external_ref sind beim + // Anbieter unveränderlich und werden nicht gesendet. + await call(ctx, 'PUT', `/licenses/${encodeURIComponent(externalRef)}`, { + customer_name: info?.customerName ?? null, customer_contact: info?.contactName ?? null, customer_email: info?.customerEmail ?? null, customer_reference: info?.customerNumber ?? null, + }); + }, async execute(ctx, req) { if (!hasAuth(ctx)) throw new ConnectorError('UNSUPPORTED', 'weder Service-Token noch API-Benutzer konfiguriert'); const id = encodeURIComponent(req.externalRef); const f = await features(ctx); const zone = f.includes('utc_timestamps') ? 'UTC' : tz(ctx); diff --git a/packages/connector-licensing/test/modern.test.ts b/packages/connector-licensing/test/modern.test.ts index d8c3470..0b9b82e 100644 --- a/packages/connector-licensing/test/modern.test.ts +++ b/packages/connector-licensing/test/modern.test.ts @@ -29,6 +29,7 @@ const api = (opts: { licenses?: object[]; features?: string[] | null; log?: Call if (u.pathname === '/products/groups') return json(GROUPS); if (u.pathname === '/licenses/' && init.method === 'GET') return json(opts.licenses ?? [lic()]); if (/^\/licenses\/\d+$/.test(u.pathname) && init.method === 'GET') return json(lic({ id: Number(u.pathname.split('/')[2]) })); + if (/^\/licenses\/\d+$/.test(u.pathname) && init.method === 'PUT') return json(lic({ id: Number(u.pathname.split('/')[2]), ...body })); if (u.pathname === '/licenses/' && init.method === 'POST') return json(lic({ id: 99, product_id: body.product_id === 6 ? 6 : null, expires_at: body.expires_at ?? null }), 201); const m = /^\/licenses\/(\d+)\/(suspend|unsuspend|extend|revoke)$/.exec(u.pathname); if (m && init.method === 'POST') return json({ changed: true, action: m[2], license: lic({ id: Number(m[1]), is_active: !['suspend', 'revoke'].includes(m[2]!), revoked_at: m[2] === 'revoke' ? '2026-09-26T12:00:00Z' : null, suspended_at: m[2] === 'suspend' ? '2026-09-26T12:00:00Z' : null, status: m[2] === 'suspend' ? 'suspended' : 'active', expires_at: m[2] === 'extend' ? body.until : '2026-10-01T10:00:00Z' }) }); @@ -144,3 +145,20 @@ describe('Lizenz-Connector: Rechte aus Scopes, Widerruf, Idempotenz, Health (#43 expect(log.map((x) => x.path)).toEqual(['/ready']); }); }); + +describe('Lizenz-Connector: Kundenangaben nachziehen und leeren (#64)', () => { + const CI = ['customer_info', 'lifecycle', 'utc_timestamps']; + it('setzt Zielwerte per PUT; Leeren schickt null für alle personenbezogenen Felder, nie Herkunftsfelder', async () => { + const log: Call[] = []; const c = mk({ log, features: CI }); + await c.updateCustomerInfo!(ctx, '18', { customerName: 'Neue Firma GmbH', contactName: 'Erika Muster', customerEmail: 'erika@example.com', customerNumber: 'K-10001' }); + await c.updateCustomerInfo!(ctx, '18', null); + const puts = log.filter((x) => x.method === 'PUT'); + expect(puts[0]!.body).toEqual({ customer_name: 'Neue Firma GmbH', customer_contact: 'Erika Muster', customer_email: 'erika@example.com', customer_reference: 'K-10001' }); + expect(puts[1]!.body).toEqual({ customer_name: null, customer_contact: null, customer_email: null, customer_reference: null }); + for (const p of puts) for (const k of ['source', 'order_ref', 'external_ref']) expect(p.body).not.toHaveProperty(k); + }); + it('ohne Fähigkeit beim Anbieter oder ohne Schreibrecht: klare Ablehnung statt stiller Erfolg', async () => { + await expect(mk({ features: ['lifecycle'] }).updateCustomerInfo!(ctx, '18', null)).rejects.toMatchObject({ code: 'UNSUPPORTED' }); + await expect(mk({ features: CI }).updateCustomerInfo!({ ...ctx, config: { ...ctx.config, scopes: 'licenses:read' } }, '18', null)).rejects.toMatchObject({ code: 'UNSUPPORTED' }); + }); +}); diff --git a/packages/connector-sdk/src/index.ts b/packages/connector-sdk/src/index.ts index b6817cb..7bdf661 100644 --- a/packages/connector-sdk/src/index.ts +++ b/packages/connector-sdk/src/index.ts @@ -53,6 +53,10 @@ export interface ProvisionContext { source: 'kundencenter'; customerNumber: string; customerName: string; contactName: string | null; customerEmail: string | null; orderNumber: string; contractNumber: string; } +/** Kundenangaben am Anbieter-Objekt nachträglich ändern (Capability `license.customer_info`). `null` = personenbezogene + * Felder leeren (Löschanspruch). Herkunftsreferenzen (Quelle, Bestell-/Vertragsnummer) bleiben beim Anbieter unverändert. */ +export type CustomerInfoUpdate = Pick | null; + // ---- Kunden des Anbieters (Übernahme) und neue Angebote ---- /** Ein Kunde/Konto beim Anbieter, das ins Kundencenter übernommen werden kann. Enthält keine Geheimnisse. */ export interface ImportableCustomer { @@ -117,6 +121,8 @@ export interface Connector { /** Unterobjekte eines Objekts (Capability `children.read`/`children.write`). */ children?: ChildAccess; reveal?(ctx: ConnectorContext, externalRef: string): Promise<{ label: string; value: string }[]>; + /** Kundenangaben an einem Objekt aktualisieren oder leeren (Capability `license.customer_info`). Idempotent (setzt Zielwerte). */ + updateCustomerInfo?(ctx: ConnectorContext, externalRef: string, info: CustomerInfoUpdate): Promise; /** Liest die Kunden des Anbieters für die Übernahme (Capability `customers.list`). */ listCustomers?(ctx: ConnectorContext): Promise; /** Legt ein neues Angebot beim Anbieter an und liefert es als Vorlage zurück (Capability `catalog.write`). */ diff --git a/packages/connectors/src/index.ts b/packages/connectors/src/index.ts index 321a3ad..961efb5 100644 --- a/packages/connectors/src/index.ts +++ b/packages/connectors/src/index.ts @@ -230,6 +230,32 @@ export async function processContractLifecycle(now: Date, enqueueJob: (type: str } +/** + * Kundenangaben an den Lizenzen/Objekten eines Kunden beim Anbieter nachziehen (#64). mode=update setzt die aktuellen Werte + * (Organisationsname, Kundennummer, Inhaber-Name/-E-Mail – wie bei der Anlage), mode=erase leert die personenbezogenen + * Felder (Löschanspruch). Wiederholbar: es werden Zielwerte gesetzt. Objekte, deren Verbindung die Fähigkeit nicht hat, + * werden übersprungen und im Ergebnis genannt. Keine personenbezogenen Werte in Logs/Audit. + */ +export interface CustomerSyncPayload { orgId: string; mode: 'update' | 'erase'; actorUserId: string | null } +export async function syncCustomerInfo(p: CustomerSyncPayload, correlationId: string): Promise { + const org = await one('SELECT id, name, customer_number FROM organizations WHERE id = ?', [p.orgId]); + if (!org) throw new JobFailure('Kunde nicht gefunden', false, 'failed'); + const owner = await one("SELECT u.name, u.email FROM memberships m JOIN users u ON u.id = m.user_id WHERE m.org_id = ? AND m.role = 'owner' ORDER BY m.created_at LIMIT 1", [p.orgId]); + const info = p.mode === 'erase' ? null : { customerName: org.name, customerNumber: org.customer_number, contactName: owner?.name ?? null, customerEmail: owner?.email ?? null }; + const rows = await query("SELECT r.id, r.external_ref, r.instance_id FROM resources r WHERE r.org_id = ? AND r.type = 'license'", [p.orgId]); + let done = 0; const skipped: string[] = []; const failed: string[] = []; + for (const r of rows) { + const { inst, connector, ctx } = await loadInstance(r.instance_id, correlationId); + if (!inst.enabled || !connector.updateCustomerInfo || !(await connector.capabilities(ctx)).includes('license.customer_info')) { skipped.push(r.id); continue; } + try { await connector.updateCustomerInfo(ctx, r.external_ref, info); done++; } + catch (e) { if (e instanceof ConnectorError && e.code === 'UNSUPPORTED') skipped.push(r.id); else failed.push(r.id); } + } + await audit({ actorType: p.actorUserId ? 'user' : 'system', actorId: p.actorUserId ?? undefined, orgId: p.orgId, action: `customer.provider_sync.${p.mode}`, resourceType: 'organization', resourceId: p.orgId, + result: failed.length ? 'failure' : 'success', correlationId, after: { updated: done, skipped: skipped.length, failed: failed.length } }); + if (failed.length) throw new Error(`${failed.length} Objekt(e) beim Anbieter nicht aktualisiert – wird wiederholt`); + return `${done} aktualisiert${skipped.length ? `, ${skipped.length} übersprungen (Anbieter ohne Kundenangaben)` : ''}`; +} + export interface ChildPayload { resourceId: string; kind: ChildKind; op: ChildOp; id?: string; data?: Record; secretEnc?: string; actorUserId: string | null; destructive?: boolean } /** * Führt eine Änderung an einem Unterobjekt aus (Auftrag `connector.child`). Geheimnisse (z. B. Passwörter) liegen nur verschlüsselt im Auftrag und diff --git a/packages/platform/src/customerSync.ts b/packages/platform/src/customerSync.ts new file mode 100644 index 0000000..92a042d --- /dev/null +++ b/packages/platform/src/customerSync.ts @@ -0,0 +1,12 @@ +import { enqueue } from './jobs.js'; +import { query } from './db.js'; + +/** Plant den Abgleich der Kundenangaben beim Anbieter ein (#64). Der Auftrag liest die Werte erst bei der Ausführung, + * mehrere Änderungen kurz hintereinander führen daher höchstens zu überflüssigen, aber korrekten Läufen. */ +export const enqueueCustomerSync = (orgId: string, mode: 'update' | 'erase', actorUserId: string | null, correlationId?: string) => + enqueue('customer.provider_sync', { orgId, mode, actorUserId }, { idempotencyKey: `customer.provider_sync:${mode}:${orgId}:${Date.now()}`, correlationId }); + +/** Nach Änderung von Name/E-Mail eines Benutzers: alle Organisationen, deren Inhaber er ist, nachziehen. */ +export async function enqueueSyncForOwner(userId: string, actorUserId: string | null, correlationId?: string): Promise { + for (const m of await query("SELECT org_id FROM memberships WHERE user_id = ? AND role = 'owner'", [userId])) await enqueueCustomerSync(m.org_id, 'update', actorUserId, correlationId); +}