Soll-Ist-Abgleich Vertrag ↔ Anbieter sichtbar machen (#21)
findDrift (platform/drift.ts) vergleicht den Sollzustand aus dem Vertrag (aktiv/gesperrt/beendet) mit dem zuletzt beobachteten Ressourcenzustand. Unsichere Beobachtungen (Anbieter gestört, Daten veraltet, unbekannt) werden als 'ungewiss' statt als Abweichung gemeldet. Nichts wird automatisch zurückgeschrieben. GET /admin/drift, Dashboard-Karte. Deterministischer Test mit sechs Fällen. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
f5c689a6ad
commit
441341ccef
4 changed files with 106 additions and 1 deletions
|
|
@ -16,6 +16,7 @@ import { clientIp, requireAuth, requirePermission, type AuthContext } from '../.
|
|||
import { AppError, badRequest, forbidden, notFound } from '../../core/errors.js';
|
||||
import { can, canInOrg } from '../../core/policy.js';
|
||||
import type { KcModule } from '../../core/module.js';
|
||||
import { findDrift } from '@kc/platform/drift';
|
||||
|
||||
const STALE_FACTOR = 3;
|
||||
const json = <T>(v: unknown, d: T): T => (v == null ? d : typeof v === 'string' ? JSON.parse(v) : (v as T));
|
||||
|
|
@ -287,6 +288,11 @@ export const resourcesModule: KcModule = {
|
|||
return { id: j.id, status: j.status, attempts: j.attempts, maxAttempts: j.max_attempts, error: j.last_error, createdAt: j.created_at, updatedAt: j.updated_at };
|
||||
});
|
||||
|
||||
/** Soll-Ist-Abweichungen Vertrag ↔ Anbieter (#21). Nur Anzeige – Korrekturen bewusst über die normalen Aktionen. */
|
||||
app.get('/admin/drift', async (req) => {
|
||||
requirePermission(req, 'resources.read');
|
||||
return findDrift();
|
||||
});
|
||||
app.get('/admin/jobs', async (req) => {
|
||||
requirePermission(req, 'jobs.read');
|
||||
const q = z.object({ status: z.string().max(30).optional() }).parse(req.query);
|
||||
|
|
|
|||
43
apps/api/test/drift.test.ts
Normal file
43
apps/api/test/drift.test.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { run } from '../src/core/db.js';
|
||||
import { expectedState, findDrift, matches } from '@kc/platform/drift';
|
||||
|
||||
describe('Soll-Ist-Abgleich Vertrag ↔ Anbieter (#21)', () => {
|
||||
it('Sollzustand je Vertragsstatus, Vergleichsregel', () => {
|
||||
expect(expectedState('active')).toBe('active'); expect(expectedState('suspended')).toBe('suspended');
|
||||
expect(expectedState('cancelled')).toBe('inactive'); expect(expectedState('pending')).toBeNull(); expect(expectedState('failed')).toBeNull();
|
||||
expect(matches('inactive', 'expired')).toBe(true); expect(matches('inactive', 'active')).toBe(false); expect(matches('active', 'suspended')).toBe(false);
|
||||
});
|
||||
|
||||
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 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) => {
|
||||
const prod = randomUUID(), ver = randomUUID(), ord = randomUUID(), item = randomUUID(), res = randomUUID(), con = randomUUID();
|
||||
await run("INSERT INTO products (id, sku, category) VALUES (?, ?, 'hosting')", [prod, `DRIFT-${prod.slice(0, 8)}`]);
|
||||
await run("INSERT INTO product_versions (id, product_id, version, name, tax_rate_id, tax_bp, billing_interval) VALUES (?,?,1,'P',?,1900,'monthly')", [ver, prod, tax]);
|
||||
await run("INSERT INTO orders (id, number, org_id, status, placed_via) VALUES (?, ?, ?, 'completed', 'staff')", [ord, `B-D${ord.slice(0, 6)}`, org]);
|
||||
await run("INSERT INTO order_items (id, order_id, product_version_id, snapshot_json) VALUES (?,?,?,'{}')", [item, ord, ver]);
|
||||
await run('INSERT INTO resources (id, instance_id, external_ref, type, name, state, org_id, synced_at) VALUES (?,?,?,\'hosting\',?,?,?, DATE_SUB(UTC_TIMESTAMP(3), INTERVAL ? MINUTE))', [res, inst, res.slice(0, 8), `Res ${status}/${state}`, state, org, syncedMinAgo]);
|
||||
await run("INSERT INTO contracts (id, number, org_id, order_item_id, product_version_id, status, resource_id, price_snapshot_json) VALUES (?,?,?,?,?,?,?,'{}')", [con, `V-D${con.slice(0, 6)}`, org, item, ver, status, res]);
|
||||
return { con, res };
|
||||
};
|
||||
const a = await mk('active', 'suspended', ok); // Abweichung: im Panel gesperrt
|
||||
const b = await mk('cancelled', 'active', ok); // Abweichung: beendet, aber aktiv
|
||||
const c = await mk('active', 'active', ok); // passt
|
||||
const d = await mk('suspended', 'active', down); // Anbieter gestört → ungewiss
|
||||
const e = await mk('active', 'expired', ok, 120); // veraltet (Intervall 300 s × 3) → ungewiss
|
||||
const f = await mk('pending', 'unknown', ok); // kein Soll → nicht verglichen
|
||||
const drift = (await findDrift()).filter((x) => x.orgId === org);
|
||||
const by = Object.fromEntries(drift.map((x) => [x.contractId, x.kind]));
|
||||
expect(by[a.con]).toBe('mismatch'); expect(by[b.con]).toBe('mismatch');
|
||||
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
|
||||
});
|
||||
});
|
||||
|
|
@ -5,6 +5,7 @@ import { api, errMsg } from '@/lib/api';
|
|||
import { useSession } from '@/lib/session';
|
||||
import { Alert, Empty, InvoiceStatusBadge, TicketStatusBadge, eur, fmt, fmtDay } from '@/components/ui';
|
||||
|
||||
interface Drift { contractId: string; contractNumber: string; orgName: string; resourceId: string; resourceName: string; observed: string; expected: string; kind: 'mismatch' | 'uncertain'; reason: string }
|
||||
interface Sys { jobs: Record<string, number>; oldestPendingJob: string | null; alerts?: { key: string; label: string; since: string; detail: string | null }[]; worker?: { lastHeartbeatSecondsAgo: number | null }; backup?: { configured: boolean; lastRunAt?: string | null; ok?: boolean; ageHours?: number | null; stale?: boolean; error?: string | null; sizeBytes?: number | null; targets?: { name: string; ok: boolean }[]; lastRestoreTestAt?: string | null; restoreOk?: boolean | null; restoreStale?: boolean } }
|
||||
interface RecentTicket { id: string; number: string; orgName: string; subject: string; status: string; lastMessageAt: string }
|
||||
interface OpenInvoice { id: string; number: string | null; orgName: string; status: string; overdue: boolean; dueDate: string | null; totalGrossCents: number }
|
||||
|
|
@ -33,7 +34,7 @@ export default function Dashboard() {
|
|||
const { me, can } = useSession();
|
||||
const [mine, setMine] = useState<{ contracts: { status: string; cancelEffectiveAt: string | null }[]; resources: { type: string; state: string; stale: boolean }[]; orders: { status: string }[] } | null>(null);
|
||||
const [licenses, setLicenses] = useState<{ active: number; expiring: number; unassigned: number } | null>(null);
|
||||
const [customers, setCustomers] = useState<number | null>(null); const [sys, setSys] = useState<Sys | null>(null); const [err, setErr] = useState('');
|
||||
const [customers, setCustomers] = useState<number | null>(null); const [sys, setSys] = useState<Sys | null>(null); const [drift, setDrift] = useState<Drift[]>([]); const [err, setErr] = useState('');
|
||||
useEffect(() => {
|
||||
if (me?.kind === 'customer') {
|
||||
Promise.all([api<any[]>('GET', '/contracts'), api<any[]>('GET', '/resources'), api<any[]>('GET', '/orders')]).then(([contracts, resources, orders]) => setMine({ contracts, resources, orders })).catch((e) => setErr(errMsg(e)));
|
||||
|
|
@ -42,6 +43,7 @@ export default function Dashboard() {
|
|||
if (!me || me.kind !== 'staff') return;
|
||||
if (can('customers.read')) api<unknown[]>('GET', '/admin/customers').then((l) => setCustomers(l.length)).catch((e) => setErr(errMsg(e)));
|
||||
if (can('jobs.read')) api<Sys>('GET', '/admin/system').then(setSys).catch((e) => setErr(errMsg(e)));
|
||||
if (can('resources.read')) api<Drift[]>('GET', '/admin/drift').then(setDrift).catch(() => undefined);
|
||||
if (can('licenses.read')) api<{ active: number; expiring: number; unassigned: number }>('GET', '/admin/licenses/summary').then(setLicenses).catch(() => undefined);
|
||||
}, [me, can]);
|
||||
if (!me) return null;
|
||||
|
|
@ -64,6 +66,9 @@ export default function Dashboard() {
|
|||
{customers !== null && <div className="card"><div className="stat">{customers}</div><p className="muted">Kunden</p><Link href="/admin/kunden">Kunden verwalten</Link></div>}
|
||||
{licenses && <div className="card"><div className="stat">{licenses.active}</div><p className="muted">Aktive Lizenzen</p>{licenses.expiring > 0 && <p className="small"><span className="badge warn"><span aria-hidden="true">▲</span>{licenses.expiring} laufen in 30 Tagen ab</span></p>}{licenses.unassigned > 0 && <p className="small"><span className="badge warn"><span aria-hidden="true">▲</span>{licenses.unassigned} ohne Kunde</span></p>}<Link href="/lizenzen">Lizenzen verwalten</Link></div>}
|
||||
{sys && <div className="card"><div className="stat">{sys.jobs.scheduled ?? 0}</div><p className="muted">Wartende Aufträge</p></div>}
|
||||
{drift.length > 0 && <div className="card"><h3>Abweichungen Vertrag ↔ Anbieter</h3>
|
||||
<p className="small muted">Nur Anzeige – es wird nichts automatisch zurückgeschrieben.</p>
|
||||
<ul className="small" style={{ margin: 0, paddingLeft: 18 }}>{drift.map((d) => <li key={d.contractId}><span className={`badge ${d.kind === 'mismatch' ? 'warn' : 'info'}`}><span aria-hidden="true">{d.kind === 'mismatch' ? '▲' : 'ⓘ'}</span>{d.kind === 'mismatch' ? 'Abweichung' : 'ungewiss'}</span> <Link href={`/ressourcen/${d.resourceId}`}>{d.resourceName}</Link> ({d.orgName}, {d.contractNumber}): {d.reason}</li>)}</ul></div>}
|
||||
{sys?.alerts && sys.alerts.length > 0 && <div className="card" role="alert"><h3>Betriebsalarme</h3>
|
||||
<ul className="small" style={{ margin: 0, paddingLeft: 18 }}>{sys.alerts.map((a) => <li key={a.key}><strong>{a.label}</strong>{a.detail ? ` – ${a.detail}` : ''} <span className="muted">(seit {new Date(a.since).toLocaleString('de-DE', { dateStyle: 'short', timeStyle: 'short' })})</span></li>)}</ul></div>}
|
||||
{sys?.backup && <div className="card"><h3>Backup</h3><p className="small"><Link href="/einstellungen/backup">Details und Einstellungen</Link></p>
|
||||
|
|
|
|||
51
packages/platform/src/drift.ts
Normal file
51
packages/platform/src/drift.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { query } from './db.js';
|
||||
|
||||
/**
|
||||
* Soll-Ist-Abgleich (#21): vergleicht den Sollzustand aus dem Vertrag mit dem zuletzt beim Anbieter beobachteten Zustand
|
||||
* der bereitgestellten Ressource. Es wird NICHTS automatisch zurückgeschrieben – Abweichungen (z. B. von Hand im Panel
|
||||
* gesperrt) werden nur angezeigt; das Personal entscheidet über die Aktion. Unsichere Beobachtungen (Anbieter gestört,
|
||||
* Daten veraltet, Zustand unbekannt) werden als „ungewiss“ gekennzeichnet statt als Abweichung gemeldet.
|
||||
*/
|
||||
export type Expected = 'active' | 'suspended' | 'inactive';
|
||||
export interface Drift {
|
||||
contractId: string; contractNumber: string; contractStatus: string; orgId: string; orgName: string;
|
||||
resourceId: string; resourceName: string; observed: string; expected: Expected; kind: 'mismatch' | 'uncertain'; reason: string; syncedAt: Date;
|
||||
}
|
||||
const STALE_FACTOR = 3;
|
||||
|
||||
/** Erwarteter Ressourcenzustand je Vertragszustand (pending/failed: noch/kein Soll – nicht verglichen). */
|
||||
export function expectedState(contractStatus: string): Expected | null {
|
||||
if (contractStatus === 'active') return 'active';
|
||||
if (contractStatus === 'suspended') return 'suspended';
|
||||
if (contractStatus === 'cancelled' || contractStatus === 'expired') return 'inactive';
|
||||
return null;
|
||||
}
|
||||
/** Passt ein beobachteter Zustand zum Soll? inactive erlaubt gesperrt/abgelaufen. */
|
||||
export function matches(expected: Expected, observed: string): boolean {
|
||||
if (expected === 'inactive') return observed === 'suspended' || observed === 'expired';
|
||||
return expected === observed;
|
||||
}
|
||||
|
||||
export async function findDrift(now = new Date()): Promise<Drift[]> {
|
||||
const rows = await query(`
|
||||
SELECT c.id, c.number, c.status, c.org_id, o.name AS org_name, r.id AS rid, r.name AS rname, r.state, r.synced_at,
|
||||
i.health, i.sync_interval_sec
|
||||
FROM contracts c JOIN resources r ON r.id = c.resource_id JOIN connector_instances i ON i.id = r.instance_id
|
||||
JOIN organizations o ON o.id = c.org_id`);
|
||||
const out: Drift[] = [];
|
||||
for (const r of rows) {
|
||||
const expected = expectedState(r.status); if (!expected) continue;
|
||||
if (matches(expected, r.state)) continue;
|
||||
const stale = r.health !== 'ok' || now.getTime() - new Date(r.synced_at).getTime() > STALE_FACTOR * r.sync_interval_sec * 1000;
|
||||
const uncertain = stale || r.state === 'unknown';
|
||||
out.push({
|
||||
contractId: r.id, contractNumber: r.number, contractStatus: r.status, orgId: r.org_id, orgName: r.org_name, resourceId: r.rid, resourceName: r.rname,
|
||||
observed: r.state, expected, kind: uncertain ? 'uncertain' : 'mismatch', syncedAt: r.synced_at,
|
||||
reason: uncertain ? 'Anbieterzustand derzeit nicht verlässlich (gestört, veraltet oder unbekannt) – nach dem nächsten Abgleich erneut prüfen.'
|
||||
: expected === 'active' ? 'Vertrag aktiv, beim Anbieter aber nicht aktiv (z. B. dort gesperrt oder abgelaufen).'
|
||||
: expected === 'suspended' ? 'Vertrag gesperrt, beim Anbieter aber noch aktiv.'
|
||||
: 'Vertrag beendet, beim Anbieter aber noch aktiv.',
|
||||
});
|
||||
}
|
||||
return out.sort((a, b) => (a.kind === b.kind ? a.orgName.localeCompare(b.orgName) : a.kind === 'mismatch' ? -1 : 1));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue