The invoice/settlement flow produced statements whose every monetary field was null, behind a review/settle/void ceremony. Model charges are billed by the provider directly, so the platform only needs to report measured usage. - apps/api/src/domain/usage.ts replaces billing.ts: per-month usage lines, totals, model-measurement coverage and a formula-safe CSV export. No invoice digest, settlement records or billing entities. - Routes: GET /v1/usage/lines and /v1/usage/export (owner/admin), GET /v1/plans; platform-operator actions move to POST /v1/admin/members and /v1/admin/executions/:id/reconcile. The operator allow-list is now WF_OPERATOR_SUBJECTS. - Contracts: UsageLine replaces BillingUsageLine/BillingInvoice; the billing_event and billing_period entity kinds are removed. - Web usage page shows limits, occupancy, monthly totals and lines. - npm script tenant:invite is renamed tenant:create (it provisions a tenant). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
118 lines
5.0 KiB
TypeScript
118 lines
5.0 KiB
TypeScript
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
import { randomUUID } from 'node:crypto';
|
|
import { mkdtemp, writeFile, rm } from 'node:fs/promises';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
import pg from 'pg';
|
|
import type { Actor } from '@wishforge/contracts';
|
|
import { PgStore } from '../../apps/api/src/db/store.js';
|
|
import { ControlPlane } from '../../apps/api/src/domain/control-plane.js';
|
|
import { Usage } from '../../apps/api/src/domain/usage.js';
|
|
import { Entitlements, PILOT_PLAN } from '../../apps/api/src/domain/entitlements.js';
|
|
import { runTenantAdmin } from '../../scripts/tenant-admin.js';
|
|
|
|
const enabled = process.env.WF_INTEGRATION === '1';
|
|
if (enabled) {
|
|
try {
|
|
process.loadEnvFile('.env.local');
|
|
} catch {}
|
|
}
|
|
describe.skipIf(!enabled)('PostgreSQL fixed plans and usage reporting', () => {
|
|
const tenantId = `usage-${randomUUID()}`;
|
|
const owner: Actor = { tenantId, userId: 'usage-fixture-owner', kind: 'human', role: 'owner' };
|
|
const operator: Actor = { ...owner, userId: 'usage-fixture-operator', role: 'admin' };
|
|
let admin: pg.Client, store: PgStore, directory: string, env: NodeJS.ProcessEnv;
|
|
beforeAll(async () => {
|
|
for (const name of ['DATABASE_URL', 'DATABASE_ADMIN_URL'])
|
|
if (!['127.0.0.1', 'localhost'].includes(new URL(process.env[name]!).hostname))
|
|
throw new Error('Usage fixture is restricted to the local PostgreSQL service');
|
|
directory = await mkdtemp(join(tmpdir(), 'wishforge-usage-'));
|
|
const plan = structuredClone(PILOT_PLAN);
|
|
plan.id = 'fixture';
|
|
plan.version = 'fixture-v1';
|
|
plan.limits.maxMembers = 2;
|
|
plan.limits.maxProjects = 1;
|
|
plan.limits.maxConcurrentRuns = 1;
|
|
const file = join(directory, 'plans.json');
|
|
await writeFile(file, JSON.stringify({ schemaVersion: 1, plans: [plan] }));
|
|
env = { ...process.env, WF_PLAN_CATALOG_FILE: file, WF_OPERATOR_SUBJECTS: operator.userId };
|
|
admin = new pg.Client({ connectionString: env.DATABASE_ADMIN_URL });
|
|
await admin.connect();
|
|
const result = await runTenantAdmin(
|
|
'provision',
|
|
[tenantId, 'Usage integration fixture', 'local', owner.userId, 'fixture', operator.userId],
|
|
env,
|
|
);
|
|
expect(result).toMatchObject({ planId: 'fixture', paymentProcessed: false });
|
|
store = new PgStore(env.DATABASE_URL!);
|
|
await store.assertSafeRole();
|
|
});
|
|
afterAll(async () => {
|
|
await store?.close();
|
|
if (admin) {
|
|
for (const table of [
|
|
'memberships',
|
|
'entities',
|
|
'run_events',
|
|
'idempotency',
|
|
'outbox',
|
|
'usage_ledger',
|
|
'audit_events',
|
|
'tenants',
|
|
])
|
|
await admin.query(`DELETE FROM ${table} WHERE ${table === 'tenants' ? 'id' : 'tenant_id'}=$1`, [tenantId]);
|
|
await admin.end();
|
|
}
|
|
if (directory) await rm(directory, { recursive: true, force: true });
|
|
});
|
|
it('persists fixed operator plans and prevents runtime credentials changing tenant limits', async () => {
|
|
expect(await new Entitlements(store, env).view(owner)).toMatchObject({
|
|
planId: 'fixture',
|
|
planVersion: 'fixture-v1',
|
|
legacy: false,
|
|
limits: { maxProjects: 1 },
|
|
});
|
|
const client = await store.pool.connect();
|
|
try {
|
|
await client.query('BEGIN');
|
|
await client.query("SELECT set_config('app.tenant_id',$1,true)", [tenantId]);
|
|
await expect(
|
|
client.query('UPDATE tenants SET token_limit=999999999 WHERE id=$1', [tenantId]),
|
|
).rejects.toMatchObject({ code: '42501' });
|
|
} finally {
|
|
await client.query('ROLLBACK');
|
|
client.release();
|
|
}
|
|
await expect(runTenantAdmin('plan', [tenantId, 'caller-invented-plan', operator.userId], env)).rejects.toThrow(
|
|
'existing configured planId',
|
|
);
|
|
});
|
|
it('serializes project/member allowances in real tenant transactions', async () => {
|
|
const control = new ControlPlane(store, { NODE_ENV: 'test' });
|
|
const created = await Promise.allSettled(['one', 'two'].map(name => control.createProject(owner, { name })));
|
|
expect(created.filter(value => value.status === 'fulfilled')).toHaveLength(1);
|
|
await runTenantAdmin('member', [tenantId, operator.userId, 'admin', operator.userId], env);
|
|
await expect(
|
|
runTenantAdmin('member', [tenantId, 'excess-fixture-member', 'viewer', operator.userId], env),
|
|
).rejects.toThrow('allowance');
|
|
expect((await new Entitlements(store, env).view(owner)).counts).toMatchObject({ members: 2, projects: 1 });
|
|
});
|
|
it('stores scoped usage provenance and reports it per tenant and month', async () => {
|
|
await store.transaction(tenantId, tx =>
|
|
tx.meter({
|
|
id: 'provider-proxy:local-fixture',
|
|
tokens: 12,
|
|
computeSeconds: 0,
|
|
storageBytes: 0,
|
|
at: '2020-01-15T00:00:00Z',
|
|
}),
|
|
);
|
|
const report = await new Usage(store).report(owner, '2020-01');
|
|
expect(report.modelCoverage).toBe('reported');
|
|
expect(report.totals.modelTokens).toBe(12);
|
|
expect(report.lines).toEqual([
|
|
expect.objectContaining({ source: 'provider_proxy', modelMeasurement: 'provider_reported' }),
|
|
]);
|
|
});
|
|
});
|