diff --git a/apps/api/src/core/policy.ts b/apps/api/src/core/policy.ts index dd35dce..5f3e6a7 100644 --- a/apps/api/src/core/policy.ts +++ b/apps/api/src/core/policy.ts @@ -1,5 +1,6 @@ /** Zentrale Policy-Schicht: RBAC (Staff-Rollen, Org-Rollen) + objektbezogene Prüfung. */ -export type StaffRole = 'support' | 'accounting' | 'admin' | 'superadmin'; +/** management: nur Management-Auswertung (analytics.read, aus dem Modul analytics), sonst nichts (#133). */ +export type StaffRole = 'support' | 'accounting' | 'admin' | 'superadmin' | 'management'; export type OrgRole = 'owner' | 'admin' | 'member'; const STAFF: Record = { @@ -7,6 +8,7 @@ const STAFF: Record = { accounting: ['customers.read'], admin: ['customers.read', 'customers.write', 'users.read', 'users.write', 'audit.read', 'jobs.read'], superadmin: ['customers.read', 'customers.write', 'users.read', 'users.write', 'users.write_privileged', 'audit.read', 'jobs.read', 'settings.write'], + management: [], }; const ORG: Record = { owner: ['org.read', 'org.members.read', 'org.members.invite'], diff --git a/apps/api/src/modules/analytics/index.ts b/apps/api/src/modules/analytics/index.ts new file mode 100644 index 0000000..7815859 --- /dev/null +++ b/apps/api/src/modules/analytics/index.ts @@ -0,0 +1,67 @@ +import type { FastifyInstance } from 'fastify'; +import { z } from 'zod'; +import { one, query } from '../../core/db.js'; +import { requirePermission } from '../../core/auth.js'; +import { badRequest } from '../../core/errors.js'; +import type { KcModule } from '../../core/module.js'; + +/** + * Management-Auswertung (#133), rein lesend. Alle Kennzahlen kommen aus vorhandenen Kunden-, Vertrags-, Rechnungs- und + * Produktdaten (keine externe Analyse, keine Testdaten-Vermischung: die Produktivdatenbank enthält nur echte Vorgänge). + * Definitionen (auch in der Antwort unter `definitions` und in docs/management-auswertung.md): + * - Zeitraum: Rechnungsdatum (issue_date) von `from` bis einschließlich `to`; Entwürfe zählen nie. + * - Beträge in Cent, Währung EUR, netto/Steuer/brutto getrennt. Stornos sind eigene Rechnungen mit negativen + * Beträgen und werden getrennt ausgewiesen; „netto nach Storno“ = ausgestellt + Stornos. + * - „als bezahlt markiert“ ist der Rechnungsstatus, KEIN gebuchter Zahlungseingang; nichts hier ist Gewinn oder Umsatz + * im bilanziellen Sinn. + */ +const DAY = /^\d{4}-\d{2}-\d{2}$/; +const n = (v: unknown) => Number(v ?? 0); +const money = (r: any) => ({ count: n(r?.c), netCents: n(r?.net), taxCents: n(r?.tax), grossCents: n(r?.gross) }); + +export const analyticsModule: KcModule = { + name: 'analytics', + permissions: { staff: { management: ['analytics.read'] } }, + register(app: FastifyInstance) { + app.get('/analytics/summary', async (req) => { + requirePermission(req, 'analytics.read'); + const q = z.object({ from: z.string().regex(DAY), to: z.string().regex(DAY) }).parse(req.query); + const from = new Date(`${q.from}T00:00:00Z`); const to = new Date(`${q.to}T00:00:00Z`); + if (Number.isNaN(from.getTime()) || Number.isNaN(to.getTime()) || to < from) throw badRequest('Zeitraum ungültig', 'BAD_RANGE'); + if (to.getTime() - from.getTime() > 3 * 366 * 86400000) throw badRequest('Höchstens drei Jahre auf einmal', 'RANGE_TOO_LONG'); + const P = [q.from, q.to]; + const IN = "v.status <> 'draft' AND v.issue_date BETWEEN ? AND ?"; + const sum = (extra: string, params: unknown[] = []) => one(`SELECT COUNT(*) AS c, SUM(v.total_net_cents) AS net, SUM(v.total_tax_cents) AS tax, SUM(v.total_gross_cents) AS gross FROM invoices v WHERE ${IN} ${extra}`, [...P, ...params]); + const issued = money(await sum('AND v.cancels_invoice_id IS NULL')); + const credits = money(await sum('AND v.cancels_invoice_id IS NOT NULL')); + const paid = money(await sum("AND v.cancels_invoice_id IS NULL AND v.status = 'paid'")); + const open = money(await sum("AND v.cancels_invoice_id IS NULL AND v.status = 'open'")); + const overdue = money(await sum("AND v.cancels_invoice_id IS NULL AND v.status = 'open' AND v.due_date < CURDATE()")); + const byTax = (await query(`SELECT ii.tax_bp, SUM(ii.net_cents) AS net, SUM(ii.tax_cents) AS tax, SUM(ii.gross_cents) AS gross FROM invoice_items ii JOIN invoices v ON v.id = ii.invoice_id WHERE ${IN} GROUP BY ii.tax_bp ORDER BY ii.tax_bp DESC`, P)) + .map((r) => ({ taxBp: n(r.tax_bp), netCents: n(r.net), taxCents: n(r.tax), grossCents: n(r.gross) })); + const byCategory = (await query(`SELECT COALESCE(p.category, 'ohne_vertrag') AS cat, SUM(ii.net_cents) AS net, SUM(ii.gross_cents) AS gross + FROM invoice_items ii JOIN invoices v ON v.id = ii.invoice_id LEFT JOIN contracts c ON c.id = ii.contract_id + LEFT JOIN product_versions pv ON pv.id = c.product_version_id LEFT JOIN products p ON p.id = pv.product_id + WHERE ${IN} GROUP BY cat ORDER BY net DESC`, P)).map((r) => ({ category: r.cat, netCents: n(r.net), grossCents: n(r.gross) })); + const byMonth = (await query(`SELECT DATE_FORMAT(v.issue_date, '%Y-%m') AS m, SUM(IF(v.cancels_invoice_id IS NULL, v.total_net_cents, 0)) AS issued, SUM(IF(v.cancels_invoice_id IS NOT NULL, v.total_net_cents, 0)) AS credits + FROM invoices v WHERE ${IN} GROUP BY m ORDER BY m`, P)).map((r) => ({ month: r.m, issuedNetCents: n(r.issued), creditNetCents: n(r.credits), netAfterCreditsCents: n(r.issued) + n(r.credits) })); + const cust = await one(`SELECT SUM(status = 'active') AS active, SUM(status = 'suspended') AS suspended, SUM(DATE(created_at) BETWEEN ? AND ?) AS created FROM organizations`, P); + const con = await one(`SELECT SUM(status = 'active') AS active, SUM(DATE(created_at) BETWEEN ? AND ?) AS created, SUM(DATE(cancelled_at) BETWEEN ? AND ?) AS ended FROM contracts`, [...P, ...P]); + return { + period: { from: q.from, to: q.to, basis: 'Rechnungsdatum, beide Tage einschließlich' }, currency: 'EUR', dataAsOf: new Date().toISOString(), + customers: { activeNow: n(cust?.active), suspendedNow: n(cust?.suspended), createdInPeriod: n(cust?.created) }, + contracts: { activeNow: n(con?.active), createdInPeriod: n(con?.created), endedInPeriod: n(con?.ended) }, + invoices: { issued, credits, netAfterCreditsCents: issued.netCents + credits.netCents, grossAfterCreditsCents: issued.grossCents + credits.grossCents, markedPaid: paid, open, overdueNow: overdue }, + byTaxRate: byTax, byCategory, byMonth, + definitions: [ + 'Zeitraum nach Rechnungsdatum; Entwürfe zählen nicht.', + 'Stornos sind eigene Rechnungen mit negativen Beträgen und werden getrennt ausgewiesen.', + '„Als bezahlt markiert“ ist ein Rechnungsstatus, kein gebuchter Zahlungseingang.', + 'Rechnungsbeträge sind weder Gewinn noch Umsatz im bilanziellen Sinn.', + '„ohne_vertrag“: Positionen ohne Vertragsbezug (z. B. Domains oder manuelle Positionen).', + 'Kunden/Verträge „aktiv“ ist der Stand zum Abrufzeitpunkt, nicht zum Zeitraumende.', + ], + }; + }); + }, +}; diff --git a/apps/api/src/modules/identity/index.ts b/apps/api/src/modules/identity/index.ts index 5248992..996e0ea 100644 --- a/apps/api/src/modules/identity/index.ts +++ b/apps/api/src/modules/identity/index.ts @@ -237,8 +237,9 @@ export const identityModule: KcModule = { }); app.post('/admin/users', async (req) => { const a = requirePermission(req, 'users.write'); - const b = z.object({ email, name: z.string().min(1).max(150), staffRole: z.enum(['support', 'accounting', 'admin', 'superadmin']) }).parse(req.body); - if ((b.staffRole === 'admin' || b.staffRole === 'superadmin') && !can(a.principal, 'users.write_privileged')) throw forbidden('Nur Superadministratoren dürfen Administratoren anlegen', 'PRIVILEGED_ONLY'); + const b = z.object({ email, name: z.string().min(1).max(150), staffRole: z.enum(['support', 'accounting', 'admin', 'superadmin', 'management']) }).parse(req.body); + // admin/superadmin und die Management-Rolle (organisationsübergreifende Finanzkennzahlen) vergibt nur ein Superadmin + if (['admin', 'superadmin', 'management'].includes(b.staffRole) && !can(a.principal, 'users.write_privileged')) throw forbidden('Nur Superadministratoren dürfen diese Rolle vergeben', 'PRIVILEGED_ONLY'); if (await one('SELECT 1 AS x FROM users WHERE email = ?', [b.email])) throw conflict('E-Mail bereits vergeben', 'EMAIL_EXISTS'); const inv = await tx(async (c) => { const cap = await assertStaffCapacity(c); // Sperre hält bis zum Commit: der letzte freie Platz wird genau einmal vergeben @@ -279,11 +280,11 @@ export const identityModule: KcModule = { app.patch('/admin/users/:id', async (req) => { const a = requirePermission(req, 'users.write'); const { id } = z.object({ id: z.string().uuid() }).parse(req.params); - const b = z.object({ status: z.enum(['active', 'disabled']).optional(), staffRole: z.enum(['support', 'accounting', 'admin', 'superadmin']).optional(), email: email.optional(), name: z.string().trim().min(1).max(150).optional() }).parse(req.body); + const b = z.object({ status: z.enum(['active', 'disabled']).optional(), staffRole: z.enum(['support', 'accounting', 'admin', 'superadmin', 'management']).optional(), email: email.optional(), name: z.string().trim().min(1).max(150).optional() }).parse(req.body); const u = await one('SELECT * FROM users WHERE id = ?', [id]); if (!u) throw notFound(); if (id === a.user.id) throw forbidden('Eigenes Konto kann hier nicht geändert werden', 'SELF_CHANGE'); - const privileged = (r: unknown) => r === 'admin' || r === 'superadmin'; + const privileged = (r: unknown) => r === 'admin' || r === 'superadmin' || r === 'management'; if ((privileged(u.staff_role) || privileged(b.staffRole)) && !can(a.principal, 'users.write_privileged')) throw forbidden('Nur Superadministratoren', 'PRIVILEGED_ONLY'); if (b.staffRole && u.kind !== 'staff') throw badRequest('Nur für Mitarbeiter'); if (b.status === 'active' && u.status === 'invited') throw badRequest('Eingeladene Benutzer aktivieren sich selbst'); diff --git a/apps/api/src/modules/index.ts b/apps/api/src/modules/index.ts index d91a556..7def335 100644 --- a/apps/api/src/modules/index.ts +++ b/apps/api/src/modules/index.ts @@ -16,6 +16,7 @@ import { discordModule } from './discord/index.js'; import { licenseModule } from './license/index.js'; import { licensingModule } from './licensing/index.js'; import { statusModule } from './status/index.js'; +import { analyticsModule } from './analytics/index.js'; /** Aktive Module. Neue Module (Produkte, Verträge, Connectoren, Tickets, Rechnungen) werden hier eingetragen. */ -export const modules: KcModule[] = [systemModule, identityModule, customersModule, auditModule, connectorsModule, resourcesModule, catalogModule, domainsModule, ordersModule, ticketsModule, invoicesModule, backupModule, mailModule, discordModule, licenseModule, licensingModule, statusModule]; +export const modules: KcModule[] = [systemModule, identityModule, customersModule, auditModule, connectorsModule, resourcesModule, catalogModule, domainsModule, ordersModule, ticketsModule, invoicesModule, backupModule, mailModule, discordModule, licenseModule, licensingModule, statusModule, analyticsModule]; diff --git a/apps/api/test/analytics.test.ts b/apps/api/test/analytics.test.ts new file mode 100644 index 0000000..6531c17 --- /dev/null +++ b/apps/api/test/analytics.test.ts @@ -0,0 +1,75 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +import type { FastifyInstance } from 'fastify'; +import { randomUUID } from 'node:crypto'; +import { buildApp } from '../src/server.js'; +import { one, run } from '../src/core/db.js'; +import { call, code, login, makeUser } from './helpers.js'; + +let app: FastifyInstance; +async function staff(email: string, role: string) { + await makeUser({ email, kind: 'staff', staffRole: role }); const { client } = await login(app, email); + const s = (await call(app, client, 'POST', '/auth/mfa/setup')).json(); await call(app, client, 'POST', '/auth/mfa/confirm', { code: code(s.secret) }); return client; +} +const inv = async (o: { issue: string | null; status: string; due?: string; lines: [number, number, string | null][]; cancels?: string }) => { + const id = randomUUID(); let net = 0, tax = 0; + for (const [n] of o.lines) net += n; for (const [n, bp] of o.lines) tax += Math.round((n * bp) / 10000); + await run('INSERT INTO invoices (id, number, org_id, status, issue_date, due_date, total_net_cents, total_tax_cents, total_gross_cents, cancels_invoice_id) VALUES (?,?,?,?,?,?,?,?,?,?)', + [id, o.status === 'draft' ? null : `RE-A${id.slice(0, 6)}`, ORG, o.status, o.issue, o.due ?? o.issue, net, tax, net + tax, o.cancels ?? null]); + let k = 0; for (const [n, bp, contract] of o.lines) { const t = Math.round((n * bp) / 10000); + await run('INSERT INTO invoice_items (id, invoice_id, contract_id, description, quantity, unit_price_net_cents, tax_bp, net_cents, tax_cents, gross_cents, sort_order) VALUES (?,?,?,?,1,?,?,?,?,?,?)', [randomUUID(), id, contract, 'x', n, bp, n, t, n + t, k++]); } + return id; +}; +let ORG = ''; let MGMT: any; const STAFF: Record = {}; + +beforeAll(async () => { + app = await buildApp(); await app.ready(); + ORG = randomUUID(); await run("INSERT INTO organizations (id, customer_number, name, customer_type) VALUES (?, 'K-AN1', 'Auswertung AG', 'business')", [ORG]); + const tax = (await one('SELECT id FROM tax_rates WHERE rate_bp = 1900 LIMIT 1'))!.id; // vorhandene Stammdaten nutzen, nichts hinzufügen + const prod = randomUUID(), ver = randomUUID(), ord = randomUUID(), item = randomUUID(), con = randomUUID(); + await run("INSERT INTO products (id, sku, category) VALUES (?, 'AN-HOST', 'hosting')", [prod]); + await run("INSERT INTO product_versions (id, product_id, version, name, tax_rate_id, tax_bp, billing_interval) VALUES (?,?,1,'Host',?,1900,'monthly')", [ver, prod, tax]); + await run("INSERT INTO orders (id, number, org_id, status, placed_via) VALUES (?, 'B-AN1', ?, 'completed', 'staff')", [ord, ORG]); + await run("INSERT INTO order_items (id, order_id, product_version_id, snapshot_json) VALUES (?,?,?,'{}')", [item, ord, ver]); + await run("INSERT INTO contracts (id, number, org_id, order_item_id, product_version_id, status, price_snapshot_json) VALUES (?, 'V-AN1', ?, ?, ?, 'active', '{}')", [con, ORG, item, ver]); + await inv({ issue: '2026-01-31', status: 'paid', lines: [[1000, 1900, con]] }); // Grenze: nur im Januar + await inv({ issue: '2026-02-01', status: 'open', due: '2026-02-15', lines: [[500, 700, null]] }); // offen + überfällig, 7 %, ohne Vertrag + const c = await inv({ issue: '2026-02-10', status: 'cancelled', lines: [[2000, 1900, con]] }); // storniert ... + await inv({ issue: '2026-02-12', status: 'open', lines: [[-2000, 1900, con]], cancels: c }); // ... durch Stornorechnung + await inv({ issue: null, status: 'draft', lines: [[99999, 1900, con]] }); // Entwurf zählt nie +}); + +describe('Management-Auswertung (#133)', () => { + it('Kennzahlen an festen Daten: Storno getrennt, Steuersätze, Kategorien, Zeitraumgrenze, Entwürfe ausgeschlossen', async () => { + const m = MGMT = await staff('an-mgmt@example.com', 'superadmin'); // Rolle wird unten auf management gesetzt + await run("UPDATE users SET staff_role = 'management' WHERE email = 'an-mgmt@example.com'"); + const feb = (await call(app, m, 'GET', '/analytics/summary?from=2026-02-01&to=2026-02-28')).json(); + expect(feb.invoices.issued).toEqual({ count: 2, netCents: 2500, taxCents: 415, grossCents: 2915 }); + expect(feb.invoices.credits).toEqual({ count: 1, netCents: -2000, taxCents: -380, grossCents: -2380 }); + expect(feb.invoices.netAfterCreditsCents).toBe(500); expect(feb.invoices.grossAfterCreditsCents).toBe(535); + expect(feb.invoices.markedPaid.grossCents).toBe(0); expect(feb.invoices.open.grossCents).toBe(535); expect(feb.invoices.overdueNow.grossCents).toBe(535); + expect(feb.byTaxRate).toEqual([{ taxBp: 1900, netCents: 0, taxCents: 0, grossCents: 0 }, { taxBp: 700, netCents: 500, taxCents: 35, grossCents: 535 }]); + expect(Object.fromEntries(feb.byCategory.map((c: any) => [c.category, c.netCents]))).toEqual({ hosting: 0, ohne_vertrag: 500 }); + expect(feb.byMonth).toEqual([{ month: '2026-02', issuedNetCents: 2500, creditNetCents: -2000, netAfterCreditsCents: 500 }]); + const jan = (await call(app, m, 'GET', '/analytics/summary?from=2026-01-31&to=2026-01-31')).json(); + expect(jan.invoices.issued.netCents).toBe(1000); expect(jan.invoices.markedPaid.grossCents).toBe(1190); expect(jan.invoices.credits.count).toBe(0); + expect(feb.currency).toBe('EUR'); expect(feb.definitions.join(' ')).toMatch(/kein gebuchter Zahlungseingang/); + expect((await call(app, m, 'GET', '/analytics/summary?from=2026-03-01&to=2026-02-01')).statusCode).toBe(400); + }); + it('Rechte: nur Management; Management hat sonst nichts; keine Schreibwege; Rolle vergibt nur Superadmin', async () => { + const m = MGMT; + for (const role of ['support', 'accounting', 'admin', 'superadmin']) { + const c = STAFF[role] = await staff(`an-${role}@example.com`, role); + expect((await call(app, c, 'GET', '/analytics/summary?from=2026-01-01&to=2026-12-31')).statusCode).toBe(403); + } + await makeUser({ email: 'an-kunde@example.com' }); const k = (await login(app, 'an-kunde@example.com')).client; + expect((await call(app, k, 'GET', '/analytics/summary?from=2026-01-01&to=2026-12-31')).statusCode).toBe(403); + for (const url of ['/admin/customers', '/admin/users', '/admin/system', '/admin/drift', `/orgs/${ORG}`]) expect([403, 404]).toContain((await call(app, m, 'GET', url)).statusCode); + const list = await call(app, m, 'GET', '/invoices'); // Liste ist auch für Kunden – für Management ohne Mitgliedschaft leer + expect(list.statusCode === 403 || (Array.isArray(list.json()) ? list.json() : list.json().items ?? []).length === 0).toBe(true); + expect((await call(app, m, 'POST', '/invoices', { orgId: ORG })).statusCode).toBe(403); + expect((await call(app, m, 'POST', '/analytics/summary', {})).statusCode).toBe(404); + const admin = STAFF.admin; const sa = STAFF.superadmin; + expect((await call(app, admin, 'POST', '/admin/users', { email: 'neu-mgmt@example.com', name: 'M', staffRole: 'management' })).statusCode).toBe(403); + expect((await call(app, sa, 'POST', '/admin/users', { email: 'neu-mgmt@example.com', name: 'M', staffRole: 'management' })).statusCode).toBe(200); + }); +}); diff --git a/apps/api/test/drift.test.ts b/apps/api/test/drift.test.ts index cb9cd62..43ff4c6 100644 --- a/apps/api/test/drift.test.ts +++ b/apps/api/test/drift.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import { randomUUID } from 'node:crypto'; -import { run } from '../src/core/db.js'; +import { one, run } from '../src/core/db.js'; import { expectedState, findDrift, matches } from '@kc/platform/drift'; describe('Soll-Ist-Abgleich Vertrag ↔ Anbieter (#21)', () => { @@ -12,7 +12,7 @@ describe('Soll-Ist-Abgleich Vertrag ↔ Anbieter (#21)', () => { it('erkennt Abweichungen, kennzeichnet unsichere Beobachtungen und schreibt nichts zurück', async () => { const org = randomUUID(); await run("INSERT INTO organizations (id, customer_number, name, customer_type) VALUES (?, 'K-DRIFT', 'Drift GmbH', 'business')", [org]); - const tax = randomUUID(); await run("INSERT INTO tax_rates (id, name, rate_bp) VALUES (?, 'Test', 1900)", [tax]); + const tax = (await one('SELECT id FROM tax_rates WHERE rate_bp = 1900 LIMIT 1'))!.id; // vorhandene Stammdaten nutzen, nichts hinzufügen const ok = randomUUID(); const down = randomUUID(); await run("INSERT INTO connector_instances (id, connector_key, name, config_json, health) VALUES (?, 'mock', 'Drift ok', '{}', 'ok'), (?, 'mock', 'Drift gestört', '{}', 'down')", [ok, down]); const mk = async (status: string, state: string, inst: string, syncedMinAgo = 0) => { @@ -37,7 +37,6 @@ describe('Soll-Ist-Abgleich Vertrag ↔ Anbieter (#21)', () => { expect(by[d.con]).toBe('uncertain'); expect(by[e.con]).toBe('uncertain'); expect(by[c.con]).toBeUndefined(); expect(by[f.con]).toBeUndefined(); expect(drift[0]!.kind).toBe('mismatch'); // sichere Abweichungen zuerst - const { one } = await import('../src/core/db.js'); expect((await one('SELECT state FROM resources WHERE id = ?', [a.res]))!.state).toBe('suspended'); // nichts zurückgeschrieben }); }); diff --git a/apps/web/src/app/(app)/admin/benutzer/page.tsx b/apps/web/src/app/(app)/admin/benutzer/page.tsx index 5c058dd..9ea6366 100644 --- a/apps/web/src/app/(app)/admin/benutzer/page.tsx +++ b/apps/web/src/app/(app)/admin/benutzer/page.tsx @@ -29,7 +29,7 @@ export default function Benutzer() { {msg && {msg.t}} {open &&

Neuer Mitarbeiter

-
+

Mitarbeiter müssen bei der ersten Anmeldung 2FA einrichten.

} {resetFor &&

2FA von {resetFor.name} zurücksetzen? Alle Sitzungen des Benutzers werden beendet. Bitte nur nach Prüfung der Identität ausführen. Die Aktion wird protokolliert.

} diff --git a/apps/web/src/app/(app)/auswertung/page.tsx b/apps/web/src/app/(app)/auswertung/page.tsx new file mode 100644 index 0000000..a0ca1dc --- /dev/null +++ b/apps/web/src/app/(app)/auswertung/page.tsx @@ -0,0 +1,48 @@ +'use client'; +import { useCallback, useEffect, useState } from 'react'; +import { api, errMsg } from '@/lib/api'; +import { Alert, Field, eur } from '@/components/ui'; + +interface Money { count: number; netCents: number; taxCents: number; grossCents: number } +interface Sum { + period: { from: string; to: string; basis: string }; currency: string; dataAsOf: string; + customers: { activeNow: number; suspendedNow: number; createdInPeriod: number }; contracts: { activeNow: number; createdInPeriod: number; endedInPeriod: number }; + invoices: { issued: Money; credits: Money; netAfterCreditsCents: number; grossAfterCreditsCents: number; markedPaid: Money; open: Money; overdueNow: Money }; + byTaxRate: { taxBp: number; netCents: number; taxCents: number; grossCents: number }[]; byCategory: { category: string; netCents: number; grossCents: number }[]; + byMonth: { month: string; issuedNetCents: number; creditNetCents: number; netAfterCreditsCents: number }[]; definitions: string[]; +} +const CAT: Record = { hosting: 'Hosting', license: 'Lizenzen', addon: 'Zusatzleistungen', service: 'Dienstleistungen', ohne_vertrag: 'ohne Vertragsbezug' }; +const iso = (d: Date) => d.toISOString().slice(0, 10); +const Tile = ({ label, value, sub }: { label: string; value: string; sub?: string }) =>

{label}

{value}

{sub &&

{sub}

}
; + +/** Management-Auswertung (#133): nur lesend, Rolle „Management“. */ +export default function Auswertung() { + const now = new Date(); const [from, setFrom] = useState(iso(new Date(Date.UTC(now.getUTCFullYear(), 0, 1)))); const [to, setTo] = useState(iso(now)); + const [s, setS] = useState(null); const [err, setErr] = useState(''); + const load = useCallback(() => { setErr(''); api('GET', `/analytics/summary?from=${from}&to=${to}`).then(setS).catch((e) => setErr(errMsg(e))); }, [from, to]); + useEffect(() => { load(); }, [load]); + return (<> +

Auswertung

+
setFrom(e.target.value)} /> setTo(e.target.value)} />
+ {err && {err}} + {!s ?

Wird geladen …

: (<> +

Datenstand {new Date(s.dataAsOf).toLocaleString('de-DE')} · Beträge in {s.currency} · {s.period.basis}

+
+ + + + + + + +
+

Nach Produktkategorie

+ {s.byCategory.map((c) => )}
KategorieNettoBrutto
{CAT[c.category] ?? c.category}{eur(c.netCents)}{eur(c.grossCents)}
+

Nach Steuersatz

+ {s.byTaxRate.map((t) => )}
USt.NettoSteuerBrutto
{t.taxBp / 100} %{eur(t.netCents)}{eur(t.taxCents)}{eur(t.grossCents)}
+

Nach Monat (netto)

+ {s.byMonth.map((m) => )}
MonatAusgestelltStornosNach Storno
{m.month}{eur(m.issuedNetCents)}{eur(m.creditNetCents)}{eur(m.netAfterCreditsCents)}
+

So wird gerechnet

    {s.definitions.map((d) =>
  • {d}
  • )}
+ )} + ); +} diff --git a/apps/web/src/app/(app)/layout.tsx b/apps/web/src/app/(app)/layout.tsx index a5b1a39..a0c2065 100644 --- a/apps/web/src/app/(app)/layout.tsx +++ b/apps/web/src/app/(app)/layout.tsx @@ -42,6 +42,7 @@ export default function AppLayout({ children }: { children: ReactNode }) { {!enrollNeeded && (me.kind === 'customer' || can('invoices.read')) && group('Abrechnung', ['/rechnungen'], link('/rechnungen', 'Rechnungen'))} {!enrollNeeded && (me.kind === 'customer' || can('tickets.read')) && group('Support', ['/tickets', '/admin/posteingang'], <>{link('/tickets', 'Tickets')}{can('tickets.read') && {link('/admin/posteingang', 'Posteingang')}})} {!enrollNeeded && me.organizations.length > 0 && link('/organisation', 'Organisation')} + {!enrollNeeded && can('analytics.read') && link('/auswertung', 'Auswertung')} {!enrollNeeded && link('/domains', 'Domain prüfen')} {!enrollNeeded && me.kind === 'staff' && verwaltung.length > 0 && group('Verwaltung', verwaltung.map(([h]) => h), verwaltung.map(([h, l]) => {link(h, l)}))}
diff --git a/apps/web/src/components/ui.tsx b/apps/web/src/components/ui.tsx index 1d22e48..691a8bb 100644 --- a/apps/web/src/components/ui.tsx +++ b/apps/web/src/components/ui.tsx @@ -23,7 +23,7 @@ export const fmt = (d: string | Date) => new Date(d).toLocaleString('de-DE', { d export const fmtDate = (d: string | Date) => new Date(d).toLocaleDateString('de-DE', { dateStyle: 'medium' }); /** Reine Datumsspalte (SQL DATE, kommt als UTC-Mitternacht) – ohne Zeitzonenverschiebung. */ export const fmtDay = (d: string | Date) => new Date(d).toLocaleDateString('de-DE', { dateStyle: 'medium', timeZone: 'UTC' }); -export const ROLE_LABEL: Record = { support: 'Support', accounting: 'Buchhaltung', admin: 'Administrator', superadmin: 'Superadministrator', owner: 'Inhaber', member: 'Mitglied' }; +export const ROLE_LABEL: Record = { support: 'Support', accounting: 'Buchhaltung', admin: 'Administrator', superadmin: 'Superadministrator', management: 'Management (nur Auswertung)', owner: 'Inhaber', member: 'Mitglied' }; export const STATE: Record = { active: { cls: 'ok', icon: '●', label: 'Aktiv' }, suspended: { cls: 'lock', icon: '⊘', label: 'Gesperrt' }, expired: { cls: 'warn', icon: '▲', label: 'Abgelaufen' }, diff --git a/docs/management-auswertung.md b/docs/management-auswertung.md new file mode 100644 index 0000000..3af2217 --- /dev/null +++ b/docs/management-auswertung.md @@ -0,0 +1,39 @@ +# Management-Auswertung („CEO-Zugang“) – Konzept und MVP + +Stand: 07.10.2026 · Plane #133 (aus Björns Feedback in #117). Ersetzt weder die Lizenzmatrix (#113) noch Preise/Bundles (#117). + +## Ziel +Ein rein lesender Überblick über Kunden, Verträge und Rechnungen für die Geschäftsführung – aus den vorhandenen Daten, ohne externes Analysesystem, ohne Schreibrechte und ohne Zugriff auf Einzelvorgänge. + +## Rechte +- Neue Personalrolle **Management** (`staff_role = 'management'`) mit genau einem Recht: `analytics.read`. Sie hat **keine** weiteren Rechte (keine Kunden-, Rechnungs-, Verwaltungs- oder Schreibrechte) – per Test nachgewiesen. +- Die Rolle wird **niemandem automatisch** zugewiesen; vergeben darf sie nur ein Superadmin (wie admin/superadmin). Bestehende Rollen bekommen `analytics.read` nicht. +- Auswertungen sind organisationsübergreifend und deshalb nur für Personal mit dieser Rolle. Ein Kundenzugang zu eigenen Kennzahlen ist nicht Teil des MVP (wäre mandantenbezogen über `canInOrg` zu bauen). + +## Seite `/auswertung` (MVP, umgesetzt) +Zeitraumfilter (Rechnungsdatum von–bis, beide Tage einschließlich), Datenstand und Währung sichtbar. Kacheln und Tabellen: + +| Kennzahl | Definition | Quelle | +|---|---|---| +| Aktive Kunden (jetzt), gesperrt, neu im Zeitraum | `organizations.status`; neu = `created_at` im Zeitraum | organizations | +| Aktive Verträge (jetzt), neu, beendet im Zeitraum | `contracts.status`; neu = `created_at`, beendet = `cancelled_at` im Zeitraum | contracts | +| Ausgestellt netto/Steuer/brutto | Rechnungen mit Rechnungsdatum im Zeitraum, ohne Entwürfe, ohne Stornorechnungen (auch später stornierte Originale zählen hier) | invoices | +| Stornos | Stornorechnungen (`cancels_invoice_id` gesetzt) im Zeitraum, negative Beträge | invoices | +| Netto/brutto nach Storno | ausgestellt + Stornos | – | +| Als bezahlt markiert | Originalrechnungen im Status `paid` – **Rechnungsstatus, kein gebuchter Zahlungseingang** | invoices | +| Offen / davon überfällig | Status `open`; überfällig = Fälligkeit vor heute | invoices | +| Nach Steuersatz | Summen der Positionen je Steuersatz (inkl. Stornos) | invoice_items | +| Nach Produktkategorie | Position → Vertrag → Produkt (`hosting`, `license`, `addon`, `service`); ohne Vertragsbezug (z. B. Domains, manuell) eigene Zeile | invoice_items, contracts, products | +| Nach Monat | netto ausgestellt, Stornos, nach Storno je Rechnungsmonat | invoices | + +Alle Beträge in Cent/EUR, netto/Steuer/brutto getrennt beschriftet. **Kein** Umsatz, Gewinn, Forecast oder Bilanzwert. + +## Abnahme (umgesetzt) +`apps/api/test/analytics.test.ts`: feste Testdaten mit Storno, 19 %/7 %, Zeitraumgrenze (31.01./01.02.), Entwurf (zählt nicht), überfälliger Rechnung; Rechte: support/accounting/admin/superadmin/Kunde → 403, Management → 200, Management ohne sonstige Rechte und ohne Schreibweg, Rolle vergibt nur Superadmin. + +## Fachlich offen (bewusst nicht erfunden) +- Zahlungseingänge/Liquidität: erst mit Zahlungserfassung (#56) bzw. Zahlungsanbieter. +- Wiederkehrender Umsatz (MRR/ARR), Kundenwert, Abwanderung: Definitionen müssen festgelegt werden (z. B. Umgang mit Jahresverträgen, Rabatten, Stornos). +- Einkauf/Marge (Domains haben EK, Hosting/Lizenzen nicht): erst mit vollständigen Einkaufspreisen. +- Kennzahlen je Kunde/Produkt im Detail, Export, Diagramme. +- Simulations-/Testdaten für ein „Analysetestsystem“: nur in einer isolierten Umgebung (z. B. `ops/dev/run.sh` mit eigener Datenbank), nie in der Produktivdatenbank. diff --git a/migrations/045_management_role.sql b/migrations/045_management_role.sql new file mode 100644 index 0000000..6a251b6 --- /dev/null +++ b/migrations/045_management_role.sql @@ -0,0 +1,3 @@ +-- Management-Auswertung (#133): eigene, rein lesende Personalrolle. Wird niemandem automatisch zugewiesen; +-- vergeben darf sie nur ein Superadmin. +ALTER TABLE users MODIFY staff_role ENUM('support','accounting','admin','superadmin','management') NULL;