kundencenter/apps/api/test/analytics.test.ts
Claude (KI) bcf188df34 Management-Auswertung: Rolle nur mit analytics.read, lesender MVP (#133)
- Konzept docs/management-auswertung.md: Rechte, Kennzahlen mit
  Definitionen und Quellen, fachlich offene Punkte (nichts erfunden).
- Neue Personalrolle management (Migration 045) mit genau analytics.read;
  niemandem automatisch zugewiesen, vergeben nur durch Superadmin.
- GET /analytics/summary (nur lesend): Kunden/Verträge, Rechnungen
  ausgestellt/Storno/nach Storno, als bezahlt markiert, offen/überfällig,
  nach Steuersatz, Kategorie und Monat; Datenstand, EUR, Definitionen.
- Seite /auswertung mit Zeitraumfilter.
Tests an festen Daten (Storno, 19/7 %, Zeitraumgrenze, Entwurf) und
Rechte-/Schreibweg-Tests. Drift-Test nutzt vorhandene Steuersätze.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 16:01:31 +02:00

75 lines
7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<string, any> = {};
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);
});
});