Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+109
@@ -0,0 +1,109 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
ADMIN_REASON_MIN_LENGTH,
|
||||
AdminActionInputError,
|
||||
assertAdminActionReason,
|
||||
assertConfirmPhrase,
|
||||
buildAdminActionAuditInput,
|
||||
confirmPhraseMatches,
|
||||
validateAdminActionReason,
|
||||
} from "./admin-action-audit.server";
|
||||
|
||||
describe("validateAdminActionReason", () => {
|
||||
it("rejects an empty or whitespace-only reason", () => {
|
||||
expect(validateAdminActionReason(undefined)).toEqual({ ok: false, code: "REASON_REQUIRED" });
|
||||
expect(validateAdminActionReason(" ")).toEqual({ ok: false, code: "REASON_REQUIRED" });
|
||||
});
|
||||
|
||||
it("rejects a reason below the minimum length", () => {
|
||||
const short = "a".repeat(ADMIN_REASON_MIN_LENGTH - 1);
|
||||
expect(validateAdminActionReason(short)).toEqual({ ok: false, code: "REASON_TOO_SHORT" });
|
||||
});
|
||||
|
||||
it("accepts and trims a meaningful reason", () => {
|
||||
expect(validateAdminActionReason(" Tenant auf Wunsch deaktiviert ")).toEqual({
|
||||
ok: true,
|
||||
value: "Tenant auf Wunsch deaktiviert",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("assertAdminActionReason", () => {
|
||||
it("throws a catalog error carrying an i18n key", () => {
|
||||
try {
|
||||
assertAdminActionReason("");
|
||||
throw new Error("expected throw");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(AdminActionInputError);
|
||||
expect((error as AdminActionInputError).code).toBe("REASON_REQUIRED");
|
||||
expect((error as AdminActionInputError).i18nKey).toBe("admin.audit.errors.reasonRequired");
|
||||
}
|
||||
});
|
||||
|
||||
it("returns the trimmed reason when valid", () => {
|
||||
expect(assertAdminActionReason(" valid reason ")).toBe("valid reason");
|
||||
});
|
||||
});
|
||||
|
||||
describe("confirmPhraseMatches", () => {
|
||||
it("matches only the exact trimmed phrase", () => {
|
||||
expect(confirmPhraseMatches("acme", "acme")).toBe(true);
|
||||
expect(confirmPhraseMatches("acme", " acme ")).toBe(true);
|
||||
expect(confirmPhraseMatches("acme", "Acme")).toBe(false);
|
||||
expect(confirmPhraseMatches("acme", "acm")).toBe(false);
|
||||
});
|
||||
|
||||
it("never matches an empty expected phrase", () => {
|
||||
expect(confirmPhraseMatches("", "")).toBe(false);
|
||||
expect(confirmPhraseMatches(" ", "")).toBe(false);
|
||||
});
|
||||
|
||||
it("assertConfirmPhrase throws on mismatch", () => {
|
||||
expect(() => assertConfirmPhrase("acme", "nope")).toThrowError(AdminActionInputError);
|
||||
expect(() => assertConfirmPhrase("acme", "acme")).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildAdminActionAuditInput", () => {
|
||||
it("always logs cross-tenant as an admin actor with the reason in metadata", () => {
|
||||
const input = buildAdminActionAuditInput({
|
||||
action: "tenant.statusChanged",
|
||||
actorUserId: "admin-1",
|
||||
actorEmail: "ops@hivegrid.de",
|
||||
targetKind: "tenant",
|
||||
targetId: "tenant-9",
|
||||
reason: "Zahlungsverzug",
|
||||
before: { active: true },
|
||||
after: { active: false },
|
||||
});
|
||||
expect(input.tenantId).toBeNull();
|
||||
expect(input.actorType).toBe("admin");
|
||||
expect(input.actorId).toBe("admin-1");
|
||||
expect(input.action).toBe("admin.tenant.statusChanged");
|
||||
expect(input.targetType).toBe("tenant");
|
||||
expect(input.targetId).toBe("tenant-9");
|
||||
expect(input.sourceModule).toBe("admin");
|
||||
expect(input.outcome).toBe("success");
|
||||
expect(input.metadata).toMatchObject({
|
||||
reason: "Zahlungsverzug",
|
||||
before: { active: true },
|
||||
after: { active: false },
|
||||
});
|
||||
});
|
||||
|
||||
it("extracts client ip + user-agent from a request when present", () => {
|
||||
const request = new Request("https://admin.hivegrid.de/tenants/9", {
|
||||
headers: { "x-forwarded-for": "203.0.113.7, 10.0.0.1", "user-agent": "ops-browser/1.0" },
|
||||
});
|
||||
const input = buildAdminActionAuditInput({
|
||||
action: "impersonation.started",
|
||||
actorUserId: "admin-1",
|
||||
targetKind: "user",
|
||||
targetId: "user-4",
|
||||
reason: "Support-Ticket #42",
|
||||
request,
|
||||
});
|
||||
expect(input.actorIp).toBe("203.0.113.7");
|
||||
expect(input.actorUserAgent).toBe("ops-browser/1.0");
|
||||
});
|
||||
});
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* AK-P19 — Platform-Admin operator-action audit gate (DoD #7).
|
||||
*
|
||||
* Sensitive operator actions on `admin.hivegrid.de` (tenant status change,
|
||||
* manual tenant creation, trial extension, tenant notes, subscription
|
||||
* override, impersonation) must be (a) backed by a mandatory free-text
|
||||
* `reason`, (b) for destructive actions confirmed by re-typing a
|
||||
* confirm-phrase, and (c) recorded into the cross-tenant audit log.
|
||||
*
|
||||
* Per the AK-P19 plan this REUSES the existing AuditEvent Querschnitt
|
||||
* (`@hivegrid/db/audit-events.server`, hash chain owned by AK-P3) rather
|
||||
* than building a parallel `AdminAuditLog` table: admin actions are
|
||||
* AuditEvent rows with `tenantId = null` + `actorType = "admin"`. This is
|
||||
* the same emit path that `modules/admin-sso/audit.server` already uses
|
||||
* for the login/MFA events — here generalized to operator operations.
|
||||
*
|
||||
* The validation + payload-shaping below are pure functions so they unit
|
||||
* test without a database; only `recordAdminAction` touches the writer.
|
||||
*/
|
||||
import { createAuditEvent, type AuditEventInput, type AuditOutcome } from "@hivegrid/db/audit-events.server";
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
|
||||
/**
|
||||
* Closed taxonomy of audited platform-operator actions. Closed union so a
|
||||
* typo at a call site is a TS error, not a silently-unaudited action. The
|
||||
* value is suffixed onto `admin.` to form the AuditEvent `action`.
|
||||
*/
|
||||
export const ADMIN_OPERATOR_ACTIONS = [
|
||||
"tenant.created",
|
||||
"tenant.statusChanged",
|
||||
"tenant.trialExtended",
|
||||
"tenant.note.created",
|
||||
"tenant.note.deleted",
|
||||
"subscription.overridden",
|
||||
"subscription.featureToggled",
|
||||
"subscription.syncRequested",
|
||||
"impersonation.started",
|
||||
"queue.paused",
|
||||
"queue.resumed",
|
||||
"queue.jobRetried",
|
||||
"support.replied",
|
||||
"support.noteAdded",
|
||||
"support.statusChanged",
|
||||
"support.assigned",
|
||||
] as const;
|
||||
|
||||
export type AdminOperatorAction = (typeof ADMIN_OPERATOR_ACTIONS)[number];
|
||||
|
||||
/** Minimum trimmed length of a reason before it is considered meaningful. */
|
||||
export const ADMIN_REASON_MIN_LENGTH = 5;
|
||||
|
||||
export type AdminActionInputErrorCode = "REASON_REQUIRED" | "REASON_TOO_SHORT" | "CONFIRM_PHRASE_MISMATCH";
|
||||
|
||||
/**
|
||||
* Input-validation failure for an operator action. Carries a stable `code`
|
||||
* and an i18n key so the route maps it onto an M002-catalog message — no
|
||||
* hard-coded UI text leaves this layer (Klartext-Diagnostik A.1).
|
||||
*/
|
||||
export class AdminActionInputError extends Error {
|
||||
override readonly name = "AdminActionInputError";
|
||||
readonly code: AdminActionInputErrorCode;
|
||||
readonly i18nKey: string;
|
||||
constructor(code: AdminActionInputErrorCode) {
|
||||
super(code);
|
||||
this.code = code;
|
||||
this.i18nKey = ADMIN_ACTION_ERROR_I18N_KEYS[code];
|
||||
}
|
||||
}
|
||||
|
||||
const ADMIN_ACTION_ERROR_I18N_KEYS: Record<AdminActionInputErrorCode, string> = {
|
||||
REASON_REQUIRED: "admin.audit.errors.reasonRequired",
|
||||
REASON_TOO_SHORT: "admin.audit.errors.reasonTooShort",
|
||||
CONFIRM_PHRASE_MISMATCH: "admin.audit.errors.confirmPhraseMismatch",
|
||||
};
|
||||
|
||||
export type ReasonValidationResult =
|
||||
| { readonly ok: true; readonly value: string }
|
||||
| { readonly ok: false; readonly code: Extract<AdminActionInputErrorCode, "REASON_REQUIRED" | "REASON_TOO_SHORT"> };
|
||||
|
||||
/**
|
||||
* Validates a mandatory operator reason. Pure — returns a discriminated
|
||||
* result instead of throwing so callers can branch without try/catch.
|
||||
*/
|
||||
export function validateAdminActionReason(reason: string | null | undefined): ReasonValidationResult {
|
||||
const trimmed = (reason ?? "").trim();
|
||||
if (trimmed.length === 0) return { ok: false, code: "REASON_REQUIRED" };
|
||||
if (trimmed.length < ADMIN_REASON_MIN_LENGTH) return { ok: false, code: "REASON_TOO_SHORT" };
|
||||
return { ok: true, value: trimmed };
|
||||
}
|
||||
|
||||
/** Throwing variant for imperative call sites; returns the trimmed reason. */
|
||||
export function assertAdminActionReason(reason: string | null | undefined): string {
|
||||
const result = validateAdminActionReason(reason);
|
||||
if (!result.ok) throw new AdminActionInputError(result.code);
|
||||
return result.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exact (trimmed) match of a destructive-action confirm-phrase, e.g. the
|
||||
* operator re-typing the tenant slug before a status change. Case- and
|
||||
* whitespace-sensitive beyond the outer trim so "Acme " != "acme".
|
||||
*/
|
||||
export function confirmPhraseMatches(expected: string, provided: string | null | undefined): boolean {
|
||||
return expected.trim().length > 0 && (provided ?? "").trim() === expected.trim();
|
||||
}
|
||||
|
||||
/** Throwing variant: enforces the confirm-phrase or raises a catalog error. */
|
||||
export function assertConfirmPhrase(expected: string, provided: string | null | undefined): void {
|
||||
if (!confirmPhraseMatches(expected, provided)) throw new AdminActionInputError("CONFIRM_PHRASE_MISMATCH");
|
||||
}
|
||||
|
||||
export type AdminActionAuditContext = {
|
||||
readonly action: AdminOperatorAction;
|
||||
readonly actorUserId: string | null;
|
||||
readonly actorEmail?: string | null;
|
||||
readonly targetKind: string;
|
||||
readonly targetId: string | null;
|
||||
readonly reason: string;
|
||||
/** Optional structured before/after diff stored in audit metadata. */
|
||||
readonly before?: Record<string, unknown> | null;
|
||||
readonly after?: Record<string, unknown> | null;
|
||||
readonly outcome?: AuditOutcome;
|
||||
readonly request?: Request;
|
||||
/** Extra non-sensitive metadata to merge (redacted by the audit layer). */
|
||||
readonly extraMeta?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
function clientMeta(request: Request | undefined): { ip: string | null; userAgent: string | null } {
|
||||
if (!request) return { ip: null, userAgent: null };
|
||||
const fwd = request.headers.get("x-forwarded-for") ?? "";
|
||||
const ip = fwd.split(",")[0]?.trim() || request.headers.get("x-real-ip") || null;
|
||||
const userAgent = request.headers.get("user-agent") || null;
|
||||
return { ip, userAgent };
|
||||
}
|
||||
|
||||
/**
|
||||
* Shapes the {@link AuditEventInput} for an operator action. Pure: no DB,
|
||||
* no clock. `tenantId` is always null (cross-tenant platform log) and the
|
||||
* actor is always `admin`. The reason + diff land in metadata.
|
||||
*/
|
||||
export function buildAdminActionAuditInput(context: AdminActionAuditContext): AuditEventInput {
|
||||
const { ip, userAgent } = clientMeta(context.request);
|
||||
return {
|
||||
tenantId: null,
|
||||
actorType: "admin",
|
||||
actorId: context.actorUserId,
|
||||
actorEmail: context.actorEmail ?? null,
|
||||
actorIp: ip,
|
||||
actorUserAgent: userAgent,
|
||||
action: `admin.${context.action}`,
|
||||
targetType: context.targetKind,
|
||||
targetId: context.targetId,
|
||||
sourceModule: "admin",
|
||||
outcome: context.outcome ?? "success",
|
||||
dataSensitivity: "confidential",
|
||||
regulatoryScope: ["soc2"],
|
||||
metadata: {
|
||||
reason: context.reason,
|
||||
before: context.before ?? null,
|
||||
after: context.after ?? null,
|
||||
...context.extraMeta,
|
||||
} as unknown as Prisma.InputJsonValue,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Records an operator action into the cross-tenant audit log. Errors
|
||||
* propagate (unlike the best-effort SSO logger): a sensitive operator
|
||||
* action that cannot be audited should surface, not silently succeed.
|
||||
*/
|
||||
export async function recordAdminAction(context: AdminActionAuditContext): Promise<void> {
|
||||
await createAuditEvent(buildAdminActionAuditInput(context));
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* AK-P19 — DB-backed integration test for the admin services.
|
||||
*
|
||||
* Gated on ADMIN_IT_DATABASE_URL (like the RLS gate tests): it runs the real
|
||||
* service code through a real Prisma client against a real Postgres with the
|
||||
* admin.prisma schema pushed, so it catches query/schema mismatches the
|
||||
* fake-client unit tests cannot. Skipped automatically when the env var is
|
||||
* unset, so normal `pnpm test` / CI stay green without a database.
|
||||
*
|
||||
* To run locally:
|
||||
* prisma db push --url <url>
|
||||
* ADMIN_IT_DATABASE_URL=<url> node scripts/vitest-cli-compat.mjs run \
|
||||
* apps/web/app/services/admin/admin-services.integration.test.ts
|
||||
*/
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { createDbClient, type DbClient } from "@hivegrid/db/client.server";
|
||||
import { getDefaultProductBlueprint, getProductBlueprint } from "@hivegrid/entitlements";
|
||||
import { createTenantNote, deleteTenantNote, getTenantNoteRows, type TenantNotesDeps } from "./tenant-notes.server";
|
||||
import {
|
||||
getTenantConnectorRows,
|
||||
setTenantFeatureConnector,
|
||||
type ConnectorServiceDeps,
|
||||
} from "./subscription-assembly.server";
|
||||
import {
|
||||
assignSupportTicket,
|
||||
postSupportInternalNote,
|
||||
postSupportReply,
|
||||
setSupportTicketStatus,
|
||||
type SupportInboxDeps,
|
||||
} from "./support-inbox.server";
|
||||
|
||||
const IT_URL = process.env.ADMIN_IT_DATABASE_URL;
|
||||
const gated = IT_URL ? describe : describe.skip;
|
||||
|
||||
const noopRecord = async () => {};
|
||||
const realBlueprintReader: ConnectorServiceDeps["readBlueprint"] = (blueprintId) =>
|
||||
(blueprintId ? getProductBlueprint(blueprintId) : undefined)?.features ?? getDefaultProductBlueprint().features;
|
||||
|
||||
gated("admin services against a real database", () => {
|
||||
let db: DbClient;
|
||||
let tenantId: string;
|
||||
// Unique slug per run so repeated local runs don't collide on the unique index.
|
||||
const slug = `akp19-it-${Date.now().toString(36)}`;
|
||||
|
||||
beforeAll(async () => {
|
||||
db = createDbClient({ connectionString: IT_URL });
|
||||
const tenant = await db.tenant.create({ data: { slug, name: "AK-P19 IT Tenant" } });
|
||||
tenantId = tenant.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (db && tenantId) {
|
||||
await db.adminTenantNote.deleteMany({ where: { tenantId } });
|
||||
await db.tenantFeatureOverride.deleteMany({ where: { tenantId } });
|
||||
await db.supportTicket.deleteMany({ where: { tenantId } }); // cascades to messages
|
||||
await db.tenant.delete({ where: { id: tenantId } });
|
||||
await db.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
it("creates, lists and deletes a tenant note", async () => {
|
||||
const deps: TenantNotesDeps = { db, recordAction: noopRecord };
|
||||
await createTenantNote(
|
||||
{ tenantId, noteText: "Zahlungsziel verlaengert", category: "billing", pinned: true, authorUserId: null },
|
||||
deps
|
||||
);
|
||||
|
||||
const rows = await getTenantNoteRows(tenantId, deps);
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toMatchObject({ category: "billing", pinned: true, noteText: "Zahlungsziel verlaengert" });
|
||||
|
||||
await deleteTenantNote({ noteId: rows[0]!.id, tenantId, actorUserId: null }, deps);
|
||||
expect(await getTenantNoteRows(tenantId, deps)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("toggles a feature connector override and clears it on inherit", async () => {
|
||||
const deps: ConnectorServiceDeps = {
|
||||
db,
|
||||
invalidateCache: () => {},
|
||||
readBlueprint: realBlueprintReader,
|
||||
recordAction: noopRecord,
|
||||
};
|
||||
|
||||
await setTenantFeatureConnector({ tenantId, featureKey: "files", state: "disabled", reason: "Pilot ohne Files", actorUserId: null }, deps);
|
||||
const disabled = await getTenantConnectorRows(tenantId, deps);
|
||||
expect(disabled.find((r) => r.featureKey === "files")?.overrideState).toBe("disabled");
|
||||
|
||||
await setTenantFeatureConnector({ tenantId, featureKey: "files", state: "inherit", reason: "Zurueck auf Plan-Default", actorUserId: null }, deps);
|
||||
const inherited = await getTenantConnectorRows(tenantId, deps);
|
||||
expect(inherited.find((r) => r.featureKey === "files")?.overrideState).toBeNull();
|
||||
});
|
||||
|
||||
it("runs the support-inbox thread: reply, internal note, status and assignment", async () => {
|
||||
const ticket = await db.supportTicket.create({
|
||||
data: { tenantId, source: "in_app_feedback_widget", subject: "Login kaputt", message: "Ich komme nicht rein" },
|
||||
});
|
||||
const deps: SupportInboxDeps = { db, recordAction: noopRecord };
|
||||
|
||||
await postSupportReply({ ticketId: ticket.id, body: "Wir schauen es uns an", authorUserId: null }, deps);
|
||||
await postSupportInternalNote({ ticketId: ticket.id, body: "Vermutlich MFA-Reset noetig", authorUserId: null }, deps);
|
||||
await setSupportTicketStatus({ ticketId: ticket.id, status: "closed", actorUserId: null }, deps);
|
||||
await assignSupportTicket({ ticketId: ticket.id, assigneeUserId: null, actorUserId: null }, deps);
|
||||
|
||||
const messages = await db.supportTicketMessage.findMany({
|
||||
where: { supportTicketId: ticket.id },
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
expect(messages).toHaveLength(2);
|
||||
expect(messages.map((m) => m.internalNote)).toEqual([false, true]);
|
||||
|
||||
const updated = await db.supportTicket.findUniqueOrThrow({ where: { id: ticket.id } });
|
||||
expect(updated.status).toBe("closed");
|
||||
});
|
||||
});
|
||||
+263
@@ -0,0 +1,263 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { AdminBillingError, listAdminBillingRows, requestManualBillingSync, setTenantBillingPlanSeats, type AdminBillingDeps } from "./billing-admin.server";
|
||||
|
||||
function createDeps(overrides: Partial<AdminBillingDeps> = {}): AdminBillingDeps {
|
||||
const tx = {
|
||||
tenantSubscription: {
|
||||
upsert: vi.fn(async () => ({ id: "sub_1" })),
|
||||
},
|
||||
tenantSubscriptionProduct: {
|
||||
updateMany: vi.fn(async () => ({ count: 0 })),
|
||||
findFirst: vi.fn(async () => null),
|
||||
update: vi.fn(async () => ({})),
|
||||
create: vi.fn(async () => ({})),
|
||||
},
|
||||
};
|
||||
const db = {
|
||||
tenant: {
|
||||
findMany: vi.fn(async () => [{ id: "tenant_1", name: "Acme", slug: "acme" }]),
|
||||
findUnique: vi.fn(async () => ({ id: "tenant_1", name: "Acme", slug: "acme" })),
|
||||
},
|
||||
subscriptionProduct: {
|
||||
findFirst: vi.fn(async () => ({ id: "product_1" })),
|
||||
},
|
||||
$transaction: vi.fn(async (callback) => callback(tx)),
|
||||
__tx: tx,
|
||||
};
|
||||
return {
|
||||
db: db as never,
|
||||
resolveBillingState: vi.fn(async () => ({
|
||||
tenantId: "tenant_1",
|
||||
status: "active",
|
||||
readOnly: false,
|
||||
planCode: "starter",
|
||||
seatQuantity: 3,
|
||||
lagoCustomerId: "lago_1",
|
||||
mollieCustomerId: "mollie_1",
|
||||
lastInvoiceExternalId: "inv_1",
|
||||
lastPaymentExternalId: "pay_1",
|
||||
trialStartsAt: null,
|
||||
trialEndsAt: null,
|
||||
pastDueSince: null,
|
||||
frozenAt: null,
|
||||
cancelledAt: null,
|
||||
currentPeriodStart: new Date("2026-07-01T00:00:00.000Z"),
|
||||
currentPeriodEnd: new Date("2026-08-01T00:00:00.000Z"),
|
||||
entitlements: [
|
||||
{
|
||||
featureKey: "crm",
|
||||
title: "CRM",
|
||||
enabled: true,
|
||||
limitType: 1,
|
||||
limit: 1,
|
||||
quotaValue: null,
|
||||
accumulate: false,
|
||||
sourceProductId: "product_1",
|
||||
sourcePlanCode: "starter",
|
||||
},
|
||||
],
|
||||
})),
|
||||
invalidateModuleCache: vi.fn(),
|
||||
clearSubscriptionCache: vi.fn(),
|
||||
recordAction: vi.fn(async () => undefined),
|
||||
lagoGateway: {
|
||||
createCustomer: vi.fn(),
|
||||
getCustomer: vi.fn(async () => ({
|
||||
provider: "lago",
|
||||
externalId: "tenant_1",
|
||||
providerCustomerId: "lago_1",
|
||||
name: "Acme",
|
||||
email: "billing@example.test",
|
||||
currency: "EUR",
|
||||
createdAt: "2026-07-01T00:00:00Z",
|
||||
})),
|
||||
createSubscription: vi.fn(),
|
||||
getSubscription: vi.fn(),
|
||||
listInvoices: vi.fn(async () => [
|
||||
{
|
||||
provider: "lago",
|
||||
providerInvoiceId: "invoice_1",
|
||||
number: "HIV-001",
|
||||
externalCustomerId: "tenant_1",
|
||||
status: "finalized",
|
||||
paymentStatus: "pending",
|
||||
invoiceType: "one_off",
|
||||
currency: "EUR",
|
||||
totalAmountCents: 11900,
|
||||
issuingDate: "2026-07-04",
|
||||
fileUrl: "https://files.example.test/invoice_1.pdf",
|
||||
},
|
||||
]),
|
||||
downloadInvoice: vi.fn(),
|
||||
},
|
||||
mollieGateway: {
|
||||
createPayment: vi.fn(),
|
||||
getPayment: vi.fn(async () => ({
|
||||
provider: "mollie",
|
||||
providerPaymentId: "pay_1",
|
||||
externalId: "pay_1",
|
||||
status: "paid",
|
||||
amountCents: 11900,
|
||||
amountRefundedCents: null,
|
||||
amountRemainingCents: 0,
|
||||
currency: "EUR",
|
||||
checkoutUrl: null,
|
||||
paidAt: "2026-07-04T00:00:00Z",
|
||||
expiresAt: null,
|
||||
metadata: {
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "inv_1",
|
||||
paymentExternalId: "pay_1",
|
||||
lagoCustomerId: null,
|
||||
lagoSubscriptionId: null,
|
||||
planCode: null,
|
||||
seatQuantity: null,
|
||||
},
|
||||
})),
|
||||
},
|
||||
applyLagoSync: vi.fn(async (input) => ({
|
||||
tenantId: input.tenantId,
|
||||
provider: "lago",
|
||||
idempotencyKey: input.eventKey,
|
||||
replayed: false,
|
||||
status: "active",
|
||||
})),
|
||||
applyMollieSync: vi.fn(async (input) => ({
|
||||
tenantId: input.tenantId,
|
||||
provider: "mollie",
|
||||
idempotencyKey: input.eventKey,
|
||||
replayed: false,
|
||||
status: "active",
|
||||
})),
|
||||
now: () => new Date("2026-07-04T00:00:00.000Z"),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("listAdminBillingRows", () => {
|
||||
it("maps tenants and billing state into loader rows", async () => {
|
||||
const deps = createDeps();
|
||||
|
||||
await expect(listAdminBillingRows(deps)).resolves.toMatchObject([
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
tenantName: "Acme",
|
||||
planCode: "starter",
|
||||
seatQuantity: 3,
|
||||
entitlementCount: 1,
|
||||
currentPeriodStart: "2026-07-01T00:00:00.000Z",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("setTenantBillingPlanSeats", () => {
|
||||
it("sets plan/seats, attaches matching catalog product, invalidates caches, and audits the reason", async () => {
|
||||
const deps = createDeps();
|
||||
|
||||
await setTenantBillingPlanSeats(
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
planCode: "starter",
|
||||
seatQuantity: "5",
|
||||
reason: "Sonderkunde",
|
||||
actorUserId: "user_1",
|
||||
actorEmail: "ops@hivegrid.de",
|
||||
},
|
||||
deps
|
||||
);
|
||||
|
||||
expect(deps.db.tenant.findUnique).toHaveBeenCalledWith({ where: { id: "tenant_1" }, select: { id: true, name: true, slug: true } });
|
||||
expect(deps.db.subscriptionProduct.findFirst).toHaveBeenCalled();
|
||||
expect(
|
||||
(
|
||||
deps.db as never as {
|
||||
__tx: { tenantSubscription: { upsert: ReturnType<typeof vi.fn> }; tenantSubscriptionProduct: { create: ReturnType<typeof vi.fn> } };
|
||||
}
|
||||
).__tx.tenantSubscription.upsert
|
||||
).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
create: expect.objectContaining({ planCode: "starter", seatQuantity: 5, status: "active" }),
|
||||
update: expect.objectContaining({ planCode: "starter", seatQuantity: 5, status: "active" }),
|
||||
})
|
||||
);
|
||||
expect(
|
||||
(deps.db as never as { __tx: { tenantSubscriptionProduct: { create: ReturnType<typeof vi.fn> } } }).__tx.tenantSubscriptionProduct.create
|
||||
).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({ subscriptionProductId: "product_1", planCode: "starter", seatQuantity: 5, quantity: 5 }),
|
||||
})
|
||||
);
|
||||
expect(deps.clearSubscriptionCache).toHaveBeenCalledWith("tenant_1");
|
||||
expect(deps.invalidateModuleCache).toHaveBeenCalledWith("tenant_1");
|
||||
expect(deps.recordAction).toHaveBeenCalledWith(expect.objectContaining({ action: "subscription.overridden", reason: "Sonderkunde" }));
|
||||
});
|
||||
|
||||
it("rejects invalid seats before writing", async () => {
|
||||
const deps = createDeps();
|
||||
|
||||
await expect(
|
||||
setTenantBillingPlanSeats({ tenantId: "tenant_1", planCode: "starter", seatQuantity: "0", reason: "Sonderkunde", actorUserId: "user_1" }, deps)
|
||||
).rejects.toMatchObject({ code: "INVALID_SEATS" });
|
||||
expect(deps.db.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("requestManualBillingSync", () => {
|
||||
it("refreshes Lago state directly and audits it", async () => {
|
||||
const deps = createDeps();
|
||||
|
||||
await requestManualBillingSync({ tenantId: "tenant_1", provider: "lago", actorUserId: "user_1" }, deps);
|
||||
|
||||
expect(deps.lagoGateway?.getCustomer).toHaveBeenCalledWith("tenant_1");
|
||||
expect(deps.lagoGateway?.listInvoices).toHaveBeenCalledWith({ tenantId: "tenant_1", perPage: 1 });
|
||||
expect(deps.applyLagoSync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
eventKey: "admin:lago:tenant_1:2026-07-04T00:00:00.000Z",
|
||||
lagoCustomerId: "lago_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
planCode: "starter",
|
||||
seatQuantity: 3,
|
||||
status: "active",
|
||||
}),
|
||||
);
|
||||
expect(deps.clearSubscriptionCache).toHaveBeenCalledWith("tenant_1");
|
||||
expect(deps.invalidateModuleCache).toHaveBeenCalledWith("tenant_1");
|
||||
expect(deps.recordAction).toHaveBeenCalledWith(expect.objectContaining({ action: "subscription.syncRequested", reason: "manual-lago-sync" }));
|
||||
});
|
||||
|
||||
it("refreshes Mollie payment state directly and audits it", async () => {
|
||||
const deps = createDeps();
|
||||
|
||||
await requestManualBillingSync({ tenantId: "tenant_1", provider: "mollie", actorUserId: "user_1" }, deps);
|
||||
|
||||
expect(deps.mollieGateway?.getPayment).toHaveBeenCalledWith("pay_1");
|
||||
expect(deps.applyMollieSync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
eventKey: "admin:mollie:tenant_1:pay_1:2026-07-04T00:00:00.000Z",
|
||||
mollieCustomerId: "mollie_1",
|
||||
paymentExternalId: "pay_1",
|
||||
invoiceExternalId: "inv_1",
|
||||
status: "paid",
|
||||
}),
|
||||
);
|
||||
expect(deps.recordAction).toHaveBeenCalledWith(expect.objectContaining({ action: "subscription.syncRequested", reason: "manual-mollie-sync" }));
|
||||
});
|
||||
|
||||
it("requires payment references before requesting Mollie sync", async () => {
|
||||
const deps = createDeps({
|
||||
resolveBillingState: vi.fn(async () => ({
|
||||
...(await createDeps().resolveBillingState("tenant_1")),
|
||||
lastInvoiceExternalId: null,
|
||||
lastPaymentExternalId: null,
|
||||
})),
|
||||
});
|
||||
|
||||
await expect(requestManualBillingSync({ tenantId: "tenant_1", provider: "mollie", actorUserId: "user_1" }, deps)).rejects.toBeInstanceOf(AdminBillingError);
|
||||
expect(deps.db.$transaction).not.toHaveBeenCalled();
|
||||
expect(deps.mollieGateway?.getPayment).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+346
@@ -0,0 +1,346 @@
|
||||
import { createLagoBillingGateway, createMolliePaymentGateway, type BillingGateway, type PaymentGateway } from "@hivegrid/billing";
|
||||
import { loadWebConfig } from "@hivegrid/config";
|
||||
import { resolveTenantBillingState } from "@hivegrid/db/billing-domain.server";
|
||||
import { applyLagoSubscriptionSync, applyMolliePaymentSync } from "@hivegrid/db/billing-sync.server";
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import type { AdminBillingInputRow } from "@hivegrid/view-models";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { invalidateTenantModuleAccessCache } from "~/utils/connector/tenantConnector.server";
|
||||
import { clearTenantSubscriptionCache } from "~/utils/services/.server/subscriptionService";
|
||||
import { assertAdminActionReason, recordAdminAction, type AdminActionAuditContext } from "./admin-action-audit.server";
|
||||
|
||||
export type BillingSyncProvider = "lago" | "mollie";
|
||||
|
||||
export class AdminBillingError extends Error {
|
||||
override readonly name = "AdminBillingError";
|
||||
readonly i18nKey: string;
|
||||
|
||||
constructor(readonly code: "TENANT_NOT_FOUND" | "MISSING_PROVIDER_REFERENCE" | "INVALID_PLAN" | "INVALID_SEATS") {
|
||||
super(code);
|
||||
this.i18nKey = `admin.billing.errors.${code}`;
|
||||
}
|
||||
}
|
||||
|
||||
type TenantSummary = {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
};
|
||||
|
||||
export type AdminBillingDeps = {
|
||||
readonly db: typeof db;
|
||||
readonly resolveBillingState: typeof resolveTenantBillingState;
|
||||
readonly invalidateModuleCache: (tenantId: string) => void;
|
||||
readonly clearSubscriptionCache: (tenantId: string) => void;
|
||||
readonly recordAction: (context: AdminActionAuditContext) => Promise<void>;
|
||||
readonly lagoGateway: BillingGateway | null;
|
||||
readonly mollieGateway: PaymentGateway | null;
|
||||
readonly applyLagoSync: typeof applyLagoSubscriptionSync;
|
||||
readonly applyMollieSync: typeof applyMolliePaymentSync;
|
||||
readonly now: () => Date;
|
||||
};
|
||||
|
||||
function createConfiguredLagoGateway(): BillingGateway | null {
|
||||
const config = loadWebConfig().config.lago;
|
||||
if (!config.apiUrl || !config.apiKey) return null;
|
||||
return createLagoBillingGateway({
|
||||
apiUrl: config.apiUrl,
|
||||
apiKey: config.apiKey,
|
||||
timeoutMs: config.timeoutMs,
|
||||
});
|
||||
}
|
||||
|
||||
function createConfiguredMollieGateway(): PaymentGateway | null {
|
||||
const config = loadWebConfig().config.mollie;
|
||||
if (!config.apiKey) return null;
|
||||
return createMolliePaymentGateway({
|
||||
apiKey: config.apiKey,
|
||||
profileId: config.profileId,
|
||||
timeoutMs: config.timeoutMs,
|
||||
});
|
||||
}
|
||||
|
||||
function defaultDeps(): AdminBillingDeps {
|
||||
return {
|
||||
db,
|
||||
resolveBillingState: resolveTenantBillingState,
|
||||
invalidateModuleCache: invalidateTenantModuleAccessCache,
|
||||
clearSubscriptionCache: clearTenantSubscriptionCache,
|
||||
recordAction: recordAdminAction,
|
||||
lagoGateway: createConfiguredLagoGateway(),
|
||||
mollieGateway: createConfiguredMollieGateway(),
|
||||
applyLagoSync: applyLagoSubscriptionSync,
|
||||
applyMollieSync: applyMolliePaymentSync,
|
||||
now: () => new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
function dateToIso(value: Date | null | undefined): string | null {
|
||||
return value ? value.toISOString() : null;
|
||||
}
|
||||
|
||||
function requireTenant(tenant: TenantSummary | null): TenantSummary {
|
||||
if (!tenant) throw new AdminBillingError("TENANT_NOT_FOUND");
|
||||
return tenant;
|
||||
}
|
||||
|
||||
function normalizePlanCode(value: string | null | undefined): string {
|
||||
const planCode = (value ?? "").trim();
|
||||
if (planCode.length === 0) throw new AdminBillingError("INVALID_PLAN");
|
||||
return planCode;
|
||||
}
|
||||
|
||||
function normalizeSeatQuantity(value: number | string | null | undefined): number {
|
||||
const seatQuantity = typeof value === "number" ? value : Number.parseInt(value ?? "", 10);
|
||||
if (!Number.isInteger(seatQuantity) || seatQuantity < 1 || seatQuantity > 10_000) {
|
||||
throw new AdminBillingError("INVALID_SEATS");
|
||||
}
|
||||
return seatQuantity;
|
||||
}
|
||||
|
||||
export async function listAdminBillingRows(deps: AdminBillingDeps = defaultDeps()): Promise<AdminBillingInputRow[]> {
|
||||
const tenants = await deps.db.tenant.findMany({
|
||||
orderBy: { name: "asc" },
|
||||
take: 100,
|
||||
select: { id: true, name: true, slug: true },
|
||||
});
|
||||
|
||||
return await Promise.all(
|
||||
tenants.map(async (tenant) => {
|
||||
const state = await deps.resolveBillingState(tenant.id);
|
||||
return {
|
||||
tenantId: tenant.id,
|
||||
tenantName: tenant.name,
|
||||
tenantSlug: tenant.slug,
|
||||
status: state.status,
|
||||
readOnly: state.readOnly,
|
||||
planCode: state.planCode,
|
||||
seatQuantity: state.seatQuantity,
|
||||
lagoCustomerId: state.lagoCustomerId,
|
||||
mollieCustomerId: state.mollieCustomerId,
|
||||
lastInvoiceExternalId: state.lastInvoiceExternalId,
|
||||
lastPaymentExternalId: state.lastPaymentExternalId,
|
||||
currentPeriodStart: dateToIso(state.currentPeriodStart),
|
||||
currentPeriodEnd: dateToIso(state.currentPeriodEnd),
|
||||
pastDueSince: dateToIso(state.pastDueSince),
|
||||
frozenAt: dateToIso(state.frozenAt),
|
||||
cancelledAt: dateToIso(state.cancelledAt),
|
||||
entitlementCount: state.entitlements.length,
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export type SetTenantBillingPlanSeatsInput = {
|
||||
readonly tenantId: string;
|
||||
readonly planCode: string;
|
||||
readonly seatQuantity: number | string;
|
||||
readonly reason: string;
|
||||
readonly actorUserId: string | null;
|
||||
readonly actorEmail?: string | null;
|
||||
readonly request?: Request;
|
||||
};
|
||||
|
||||
type SubscriptionProductMatch = { id: string } | null;
|
||||
|
||||
async function findPlanProduct(planCode: string, deps: AdminBillingDeps): Promise<SubscriptionProductMatch> {
|
||||
return await deps.db.subscriptionProduct.findFirst({
|
||||
where: {
|
||||
OR: [{ id: planCode }, { code: planCode }, { lagoPlanCode: planCode }],
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
}
|
||||
|
||||
async function attachMatchingProduct(
|
||||
input: { subscriptionId: string; product: { id: string }; planCode: string; seatQuantity: number; now: Date },
|
||||
tx: Prisma.TransactionClient
|
||||
): Promise<void> {
|
||||
await tx.tenantSubscriptionProduct.updateMany({
|
||||
where: {
|
||||
tenantSubscriptionId: input.subscriptionId,
|
||||
subscriptionProductId: { not: input.product.id },
|
||||
OR: [{ endsAt: null }, { endsAt: { gt: input.now } }],
|
||||
},
|
||||
data: {
|
||||
cancelledAt: input.now,
|
||||
endsAt: input.now,
|
||||
},
|
||||
});
|
||||
|
||||
const existing = await tx.tenantSubscriptionProduct.findFirst({
|
||||
where: {
|
||||
tenantSubscriptionId: input.subscriptionId,
|
||||
subscriptionProductId: input.product.id,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
await tx.tenantSubscriptionProduct.update({
|
||||
where: { id: existing.id },
|
||||
data: {
|
||||
planCode: input.planCode,
|
||||
seatQuantity: input.seatQuantity,
|
||||
quantity: input.seatQuantity,
|
||||
cancelledAt: null,
|
||||
endsAt: null,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await tx.tenantSubscriptionProduct.create({
|
||||
data: {
|
||||
tenantSubscriptionId: input.subscriptionId,
|
||||
subscriptionProductId: input.product.id,
|
||||
planCode: input.planCode,
|
||||
seatQuantity: input.seatQuantity,
|
||||
quantity: input.seatQuantity,
|
||||
cancelledAt: null,
|
||||
endsAt: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function setTenantBillingPlanSeats(input: SetTenantBillingPlanSeatsInput, deps: AdminBillingDeps = defaultDeps()): Promise<void> {
|
||||
const reason = assertAdminActionReason(input.reason);
|
||||
const planCode = normalizePlanCode(input.planCode);
|
||||
const seatQuantity = normalizeSeatQuantity(input.seatQuantity);
|
||||
const now = deps.now();
|
||||
const tenant = requireTenant(
|
||||
await deps.db.tenant.findUnique({
|
||||
where: { id: input.tenantId },
|
||||
select: { id: true, name: true, slug: true },
|
||||
})
|
||||
);
|
||||
const before = await deps.resolveBillingState(tenant.id);
|
||||
const product = await findPlanProduct(planCode, deps);
|
||||
|
||||
await deps.db.$transaction(async (tx) => {
|
||||
const subscription = await tx.tenantSubscription.upsert({
|
||||
where: { tenantId: tenant.id },
|
||||
create: {
|
||||
tenantId: tenant.id,
|
||||
planCode,
|
||||
seatQuantity,
|
||||
status: "active",
|
||||
},
|
||||
update: {
|
||||
planCode,
|
||||
seatQuantity,
|
||||
status: "active",
|
||||
frozenAt: null,
|
||||
cancelledAt: null,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (product) {
|
||||
await attachMatchingProduct({ subscriptionId: subscription.id, product, planCode, seatQuantity, now }, tx);
|
||||
}
|
||||
});
|
||||
|
||||
deps.clearSubscriptionCache(tenant.id);
|
||||
deps.invalidateModuleCache(tenant.id);
|
||||
|
||||
await deps.recordAction({
|
||||
action: "subscription.overridden",
|
||||
actorUserId: input.actorUserId,
|
||||
actorEmail: input.actorEmail ?? null,
|
||||
targetKind: "tenant",
|
||||
targetId: tenant.id,
|
||||
reason,
|
||||
before: { planCode: before.planCode, seatQuantity: before.seatQuantity, status: before.status },
|
||||
after: { planCode, seatQuantity, status: "active", catalogProductAttached: Boolean(product) },
|
||||
request: input.request,
|
||||
});
|
||||
}
|
||||
|
||||
export type RequestManualBillingSyncInput = {
|
||||
readonly tenantId: string;
|
||||
readonly provider: BillingSyncProvider;
|
||||
readonly actorUserId: string | null;
|
||||
readonly actorEmail?: string | null;
|
||||
readonly request?: Request;
|
||||
};
|
||||
|
||||
async function applyManualProviderSync(input: {
|
||||
provider: BillingSyncProvider;
|
||||
tenantId: string;
|
||||
state: Awaited<ReturnType<typeof resolveTenantBillingState>>;
|
||||
now: Date;
|
||||
}, deps: AdminBillingDeps): Promise<Record<string, unknown>> {
|
||||
if (input.provider === "lago") {
|
||||
if (!deps.lagoGateway) throw new AdminBillingError("MISSING_PROVIDER_REFERENCE");
|
||||
const [customer, invoices] = await Promise.all([
|
||||
deps.lagoGateway.getCustomer(input.tenantId),
|
||||
deps.lagoGateway.listInvoices({ tenantId: input.tenantId, perPage: 1 }),
|
||||
]);
|
||||
const latestInvoice = invoices[0] ?? null;
|
||||
const result = await deps.applyLagoSync({
|
||||
tenantId: input.tenantId,
|
||||
eventKey: `admin:lago:${input.tenantId}:${input.now.toISOString()}`,
|
||||
lagoCustomerId: customer?.providerCustomerId ?? input.state.lagoCustomerId,
|
||||
status: input.state.status,
|
||||
planCode: input.state.planCode,
|
||||
seatQuantity: input.state.seatQuantity,
|
||||
invoiceExternalId: latestInvoice?.providerInvoiceId ?? input.state.lastInvoiceExternalId,
|
||||
receivedAt: input.now,
|
||||
});
|
||||
return {
|
||||
provider: input.provider,
|
||||
synced: true,
|
||||
billingStatus: result.status,
|
||||
invoiceExternalId: latestInvoice?.providerInvoiceId ?? input.state.lastInvoiceExternalId,
|
||||
};
|
||||
}
|
||||
|
||||
const providerPaymentId = input.state.lastPaymentExternalId;
|
||||
const invoiceExternalId = input.state.lastInvoiceExternalId;
|
||||
if (!providerPaymentId || !invoiceExternalId) throw new AdminBillingError("MISSING_PROVIDER_REFERENCE");
|
||||
if (!deps.mollieGateway) throw new AdminBillingError("MISSING_PROVIDER_REFERENCE");
|
||||
const payment = await deps.mollieGateway.getPayment(providerPaymentId);
|
||||
if (!payment) throw new AdminBillingError("MISSING_PROVIDER_REFERENCE");
|
||||
const result = await deps.applyMollieSync({
|
||||
tenantId: input.tenantId,
|
||||
eventKey: `admin:mollie:${input.tenantId}:${payment.providerPaymentId}:${input.now.toISOString()}`,
|
||||
mollieCustomerId: input.state.mollieCustomerId,
|
||||
paymentExternalId: payment.externalId ?? providerPaymentId,
|
||||
invoiceExternalId: payment.metadata.invoiceExternalId ?? invoiceExternalId,
|
||||
status: payment.status,
|
||||
receivedAt: input.now,
|
||||
});
|
||||
return {
|
||||
provider: input.provider,
|
||||
synced: true,
|
||||
billingStatus: result.status,
|
||||
providerPaymentId: payment.providerPaymentId,
|
||||
paymentStatus: payment.status,
|
||||
};
|
||||
}
|
||||
|
||||
export async function requestManualBillingSync(input: RequestManualBillingSyncInput, deps: AdminBillingDeps = defaultDeps()): Promise<void> {
|
||||
const tenant = requireTenant(
|
||||
await deps.db.tenant.findUnique({
|
||||
where: { id: input.tenantId },
|
||||
select: { id: true, name: true, slug: true },
|
||||
})
|
||||
);
|
||||
const state = await deps.resolveBillingState(tenant.id);
|
||||
const syncResult = await applyManualProviderSync({ provider: input.provider, tenantId: tenant.id, state, now: deps.now() }, deps);
|
||||
|
||||
deps.clearSubscriptionCache(tenant.id);
|
||||
deps.invalidateModuleCache(tenant.id);
|
||||
|
||||
await deps.recordAction({
|
||||
action: "subscription.syncRequested",
|
||||
actorUserId: input.actorUserId,
|
||||
actorEmail: input.actorEmail ?? null,
|
||||
targetKind: "tenant",
|
||||
targetId: tenant.id,
|
||||
reason: `manual-${input.provider}-sync`,
|
||||
after: syncResult,
|
||||
request: input.request,
|
||||
});
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
getQueueMonitorSnapshot,
|
||||
pauseQueue,
|
||||
resumeQueue,
|
||||
retryQueueJob,
|
||||
type QueueInspector,
|
||||
type QueueMonitorDeps,
|
||||
} from "./queue-monitor.server";
|
||||
|
||||
function makeInspector(): QueueInspector {
|
||||
return {
|
||||
getCounts: vi.fn(async () => ({ active: 1, waiting: 2, delayed: 0, failed: 3, completed: 4, paused: false })),
|
||||
listFailedJobs: vi.fn(async () => []),
|
||||
pauseQueue: vi.fn(async () => {}),
|
||||
resumeQueue: vi.fn(async () => {}),
|
||||
retryJob: vi.fn(async () => {}),
|
||||
};
|
||||
}
|
||||
|
||||
function makeDeps(inspector: QueueInspector, queueNames: readonly string[]): {
|
||||
deps: QueueMonitorDeps;
|
||||
recordAction: ReturnType<typeof vi.fn>;
|
||||
} {
|
||||
const recordAction = vi.fn(async () => {});
|
||||
return { deps: { inspector, queueNames, recordAction }, recordAction };
|
||||
}
|
||||
|
||||
describe("getQueueMonitorSnapshot", () => {
|
||||
it("gathers counts per queue and resolves the worker group", async () => {
|
||||
const inspector = makeInspector();
|
||||
const { deps } = makeDeps(inspector, ["hivegrid.email", "hivegrid.imports"]);
|
||||
const rows = await getQueueMonitorSnapshot(deps);
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows[0]).toMatchObject({ queueName: "hivegrid.email", failed: 3, paused: false });
|
||||
expect(rows[0].group).toBeTypeOf("string");
|
||||
expect(inspector.getCounts).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("falls back to the general group for an unknown queue name", async () => {
|
||||
const inspector = makeInspector();
|
||||
const { deps } = makeDeps(inspector, ["totally.unknown.queue"]);
|
||||
const rows = await getQueueMonitorSnapshot(deps);
|
||||
expect(rows[0].group).toBe("general");
|
||||
});
|
||||
});
|
||||
|
||||
describe("queue controls", () => {
|
||||
it("pauseQueue calls the inspector and audits queue.paused", async () => {
|
||||
const inspector = makeInspector();
|
||||
const { deps, recordAction } = makeDeps(inspector, ["hivegrid.email"]);
|
||||
await pauseQueue({ queueName: "hivegrid.email", actorUserId: "a1" }, deps);
|
||||
expect(inspector.pauseQueue).toHaveBeenCalledWith("hivegrid.email");
|
||||
expect(recordAction.mock.calls[0][0]).toMatchObject({ action: "queue.paused", targetKind: "queue", targetId: "hivegrid.email" });
|
||||
});
|
||||
|
||||
it("resumeQueue calls the inspector and audits queue.resumed", async () => {
|
||||
const inspector = makeInspector();
|
||||
const { deps, recordAction } = makeDeps(inspector, ["hivegrid.email"]);
|
||||
await resumeQueue({ queueName: "hivegrid.email", actorUserId: "a1" }, deps);
|
||||
expect(inspector.resumeQueue).toHaveBeenCalledOnce();
|
||||
expect(recordAction.mock.calls[0][0]).toMatchObject({ action: "queue.resumed" });
|
||||
});
|
||||
|
||||
it("retryQueueJob retries the job and audits with the jobId", async () => {
|
||||
const inspector = makeInspector();
|
||||
const { deps, recordAction } = makeDeps(inspector, ["hivegrid.email"]);
|
||||
await retryQueueJob({ queueName: "hivegrid.email", jobId: "job-7", actorUserId: "a1" }, deps);
|
||||
expect(inspector.retryJob).toHaveBeenCalledWith("hivegrid.email", "job-7");
|
||||
expect(recordAction.mock.calls[0][0]).toMatchObject({ action: "queue.jobRetried", after: { queueName: "hivegrid.email", jobId: "job-7" } });
|
||||
});
|
||||
});
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
/**
|
||||
* AK-P19 — Queue-Monitor service (DoD #6).
|
||||
*
|
||||
* Reads BullMQ job counts for the worker fleet and exposes the operator
|
||||
* controls (pause / resume / retry). The aggregation + audited actions are
|
||||
* unit-testable through an injected {@link QueueInspector}; the concrete
|
||||
* BullMQ adapter ({@link createBullMqQueueInspector}) is thin glue that
|
||||
* needs a live Redis and is verified on staging (no Redis in unit tests).
|
||||
*
|
||||
* Pure presentation (counts -> health) lives in the queue-monitor VM; this
|
||||
* module only gathers raw counts and performs the side-effecting controls.
|
||||
*/
|
||||
import { getGroupForQueue, queueNames, resolveRedisConnectionOptionsFromProcessEnv } from "@hivegrid/queue";
|
||||
import { createQueue } from "@hivegrid/queue/runtime";
|
||||
import type { QueueCountsInput } from "@hivegrid/view-models";
|
||||
import { recordAdminAction, type AdminActionAuditContext, type AdminOperatorAction } from "./admin-action-audit.server";
|
||||
|
||||
export type QueueRawCounts = {
|
||||
readonly active: number;
|
||||
readonly waiting: number;
|
||||
readonly delayed: number;
|
||||
readonly failed: number;
|
||||
readonly completed: number;
|
||||
readonly paused: boolean;
|
||||
};
|
||||
|
||||
export type QueueFailedJobDetail = {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly failedReason: string | null;
|
||||
readonly attemptsMade: number;
|
||||
readonly timestamp: number | null;
|
||||
};
|
||||
|
||||
/** Live-queue port. The production impl wraps BullMQ; tests pass a fake. */
|
||||
export interface QueueInspector {
|
||||
getCounts(queueName: string): Promise<QueueRawCounts>;
|
||||
listFailedJobs(queueName: string, limit: number): Promise<readonly QueueFailedJobDetail[]>;
|
||||
pauseQueue(queueName: string): Promise<void>;
|
||||
resumeQueue(queueName: string): Promise<void>;
|
||||
retryJob(queueName: string, jobId: string): Promise<void>;
|
||||
}
|
||||
|
||||
export interface QueueMonitorDeps {
|
||||
readonly inspector: QueueInspector;
|
||||
readonly queueNames: readonly string[];
|
||||
readonly recordAction: (context: AdminActionAuditContext) => Promise<void>;
|
||||
}
|
||||
|
||||
const ALL_QUEUE_NAMES: readonly string[] = Object.values(queueNames);
|
||||
|
||||
function defaultQueueMonitorDeps(): QueueMonitorDeps {
|
||||
return { inspector: createBullMqQueueInspector(), queueNames: ALL_QUEUE_NAMES, recordAction: recordAdminAction };
|
||||
}
|
||||
|
||||
/** Gathers raw counts for every queue into the VM input shape. */
|
||||
export async function getQueueMonitorSnapshot(
|
||||
deps: QueueMonitorDeps = defaultQueueMonitorDeps()
|
||||
): Promise<QueueCountsInput[]> {
|
||||
return Promise.all(
|
||||
deps.queueNames.map(async (queueName) => {
|
||||
const counts = await deps.inspector.getCounts(queueName);
|
||||
const group = isKnownQueueName(queueName) ? getGroupForQueue(queueName) : "general";
|
||||
return { queueName, group, ...counts } satisfies QueueCountsInput;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function isKnownQueueName(value: string): value is (typeof queueNames)[keyof typeof queueNames] {
|
||||
return (ALL_QUEUE_NAMES as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
export interface QueueControlInput {
|
||||
readonly queueName: string;
|
||||
readonly actorUserId: string | null;
|
||||
readonly actorEmail?: string | null;
|
||||
readonly request?: Request;
|
||||
}
|
||||
|
||||
async function auditQueueControl(
|
||||
deps: QueueMonitorDeps,
|
||||
action: Extract<AdminOperatorAction, "queue.paused" | "queue.resumed" | "queue.jobRetried">,
|
||||
input: QueueControlInput,
|
||||
reason: string,
|
||||
extra?: Record<string, unknown>
|
||||
): Promise<void> {
|
||||
await deps.recordAction({
|
||||
action,
|
||||
actorUserId: input.actorUserId,
|
||||
actorEmail: input.actorEmail ?? null,
|
||||
targetKind: "queue",
|
||||
targetId: input.queueName,
|
||||
reason,
|
||||
after: { queueName: input.queueName, ...extra },
|
||||
request: input.request,
|
||||
});
|
||||
}
|
||||
|
||||
export async function pauseQueue(input: QueueControlInput, deps: QueueMonitorDeps = defaultQueueMonitorDeps()): Promise<void> {
|
||||
await deps.inspector.pauseQueue(input.queueName);
|
||||
await auditQueueControl(deps, "queue.paused", input, "Operator hat die Queue pausiert");
|
||||
}
|
||||
|
||||
export async function resumeQueue(input: QueueControlInput, deps: QueueMonitorDeps = defaultQueueMonitorDeps()): Promise<void> {
|
||||
await deps.inspector.resumeQueue(input.queueName);
|
||||
await auditQueueControl(deps, "queue.resumed", input, "Operator hat die Queue fortgesetzt");
|
||||
}
|
||||
|
||||
export async function retryQueueJob(
|
||||
input: QueueControlInput & { readonly jobId: string },
|
||||
deps: QueueMonitorDeps = defaultQueueMonitorDeps()
|
||||
): Promise<void> {
|
||||
await deps.inspector.retryJob(input.queueName, input.jobId);
|
||||
await auditQueueControl(deps, "queue.jobRetried", input, "Operator hat einen fehlgeschlagenen Job erneut gestartet", {
|
||||
jobId: input.jobId,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Structural view of the BullMQ Queue read/control surface we use. The
|
||||
* shared `TypedQueue` contract is intentionally narrowed to `add`/`close`
|
||||
* (enqueue-only); the runtime object is a real BullMQ Queue that also
|
||||
* carries these methods, so we widen structurally at the adapter boundary.
|
||||
*/
|
||||
interface BullJobControl {
|
||||
readonly id?: string | number;
|
||||
readonly name: string;
|
||||
readonly failedReason?: string;
|
||||
readonly attemptsMade: number;
|
||||
readonly timestamp?: number;
|
||||
retry(): Promise<void>;
|
||||
}
|
||||
interface BullQueueReadControl {
|
||||
getJobCounts(...types: string[]): Promise<Record<string, number>>;
|
||||
isPaused(): Promise<boolean>;
|
||||
pause(): Promise<void>;
|
||||
resume(): Promise<void>;
|
||||
getJobs(types: string[], start?: number, end?: number): Promise<BullJobControl[]>;
|
||||
getJob(jobId: string): Promise<BullJobControl | null | undefined>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* BullMQ-backed inspector. Constructs a short-lived Queue per call against
|
||||
* the worker Redis and closes it again — read traffic only, no consumers.
|
||||
* Requires BULLMQ_REDIS_URL/REDIS_URL; runtime-verified on staging.
|
||||
*/
|
||||
export function createBullMqQueueInspector(): QueueInspector {
|
||||
const connection = resolveRedisConnectionOptionsFromProcessEnv({ required: true });
|
||||
|
||||
async function withQueue<T>(queueName: string, fn: (queue: BullQueueReadControl) => Promise<T>): Promise<T> {
|
||||
const queue = createQueue(queueName as (typeof queueNames)[keyof typeof queueNames], {
|
||||
connection,
|
||||
}) as unknown as BullQueueReadControl;
|
||||
try {
|
||||
return await fn(queue);
|
||||
} finally {
|
||||
await queue.close();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
async getCounts(queueName) {
|
||||
return withQueue(queueName, async (queue) => {
|
||||
const [counts, paused] = await Promise.all([
|
||||
queue.getJobCounts("active", "waiting", "delayed", "failed", "completed"),
|
||||
queue.isPaused(),
|
||||
]);
|
||||
return {
|
||||
active: counts.active ?? 0,
|
||||
waiting: counts.waiting ?? 0,
|
||||
delayed: counts.delayed ?? 0,
|
||||
failed: counts.failed ?? 0,
|
||||
completed: counts.completed ?? 0,
|
||||
paused,
|
||||
};
|
||||
});
|
||||
},
|
||||
async listFailedJobs(queueName, limit) {
|
||||
return withQueue(queueName, async (queue) => {
|
||||
const jobs = await queue.getJobs(["failed"], 0, Math.max(0, limit - 1));
|
||||
return jobs.map((job) => ({
|
||||
id: String(job.id ?? ""),
|
||||
name: job.name,
|
||||
failedReason: job.failedReason ?? null,
|
||||
attemptsMade: job.attemptsMade,
|
||||
timestamp: job.timestamp ?? null,
|
||||
}));
|
||||
});
|
||||
},
|
||||
async pauseQueue(queueName) {
|
||||
await withQueue(queueName, (queue) => queue.pause());
|
||||
},
|
||||
async resumeQueue(queueName) {
|
||||
await withQueue(queueName, (queue) => queue.resume());
|
||||
},
|
||||
async retryJob(queueName, jobId) {
|
||||
await withQueue(queueName, async (queue) => {
|
||||
const job = await queue.getJob(jobId);
|
||||
if (job) await job.retry();
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { ProductBlueprintFeatureDefinition } from "@hivegrid/entitlements";
|
||||
import {
|
||||
AdminConnectorError,
|
||||
buildConnectorInputRows,
|
||||
getTenantConnectorRows,
|
||||
setTenantFeatureConnector,
|
||||
type ConnectorServiceDeps,
|
||||
} from "./subscription-assembly.server";
|
||||
import { AdminActionInputError } from "./admin-action-audit.server";
|
||||
|
||||
const FEATURES: readonly ProductBlueprintFeatureDefinition[] = [
|
||||
{ featureKey: "crm-basic", defaultEnabled: true, tenantToggleable: false },
|
||||
{ featureKey: "files", defaultEnabled: true, tenantToggleable: true },
|
||||
{ featureKey: "api", defaultEnabled: false, tenantToggleable: true },
|
||||
];
|
||||
|
||||
function makeDeps(overrides: Array<{ featureKey: string; override: string }> = []): {
|
||||
deps: ConnectorServiceDeps;
|
||||
upsert: ReturnType<typeof vi.fn>;
|
||||
deleteMany: ReturnType<typeof vi.fn>;
|
||||
invalidateCache: ReturnType<typeof vi.fn>;
|
||||
recordAction: ReturnType<typeof vi.fn>;
|
||||
} {
|
||||
const upsert = vi.fn(async () => ({}));
|
||||
const deleteMany = vi.fn(async () => ({ count: 1 }));
|
||||
const invalidateCache = vi.fn();
|
||||
const recordAction = vi.fn(async () => {});
|
||||
const deps = {
|
||||
db: {
|
||||
tenantProductConfiguration: { findUnique: vi.fn(async () => ({ blueprintId: "crm-saas" })) },
|
||||
tenantFeatureOverride: { findMany: vi.fn(async () => overrides), upsert, deleteMany },
|
||||
},
|
||||
invalidateCache,
|
||||
readBlueprint: () => FEATURES,
|
||||
recordAction,
|
||||
} as unknown as ConnectorServiceDeps;
|
||||
return { deps, upsert, deleteMany, invalidateCache, recordAction };
|
||||
}
|
||||
|
||||
describe("buildConnectorInputRows", () => {
|
||||
it("joins blueprint features with stored overrides", () => {
|
||||
const rows = buildConnectorInputRows(FEATURES, new Map([["files", "disabled"]]));
|
||||
expect(rows).toEqual([
|
||||
{ featureKey: "crm-basic", toggleable: false, baseEnabled: true, overrideState: null },
|
||||
{ featureKey: "files", toggleable: true, baseEnabled: true, overrideState: "disabled" },
|
||||
{ featureKey: "api", toggleable: true, baseEnabled: false, overrideState: null },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getTenantConnectorRows", () => {
|
||||
it("reads overrides and maps them onto the blueprint", async () => {
|
||||
const { deps } = makeDeps([{ featureKey: "api", override: "enabled" }]);
|
||||
const rows = await getTenantConnectorRows("t1", deps);
|
||||
expect(rows.find((r) => r.featureKey === "api")?.overrideState).toBe("enabled");
|
||||
});
|
||||
});
|
||||
|
||||
describe("setTenantFeatureConnector", () => {
|
||||
it("rejects a missing reason before touching the DB", async () => {
|
||||
const { deps, upsert } = makeDeps();
|
||||
await expect(
|
||||
setTenantFeatureConnector({ tenantId: "t1", featureKey: "files", state: "disabled", reason: "", actorUserId: "a1" }, deps)
|
||||
).rejects.toBeInstanceOf(AdminActionInputError);
|
||||
expect(upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an unknown feature key", async () => {
|
||||
const { deps } = makeDeps();
|
||||
await expect(
|
||||
setTenantFeatureConnector({ tenantId: "t1", featureKey: "nope", state: "enabled", reason: "valid reason", actorUserId: "a1" }, deps)
|
||||
).rejects.toMatchObject({ code: "FEATURE_NOT_FOUND" });
|
||||
});
|
||||
|
||||
it("refuses to toggle a non-toggleable core feature", async () => {
|
||||
const { deps } = makeDeps();
|
||||
await expect(
|
||||
setTenantFeatureConnector({ tenantId: "t1", featureKey: "crm-basic", state: "disabled", reason: "valid reason", actorUserId: "a1" }, deps)
|
||||
).rejects.toBeInstanceOf(AdminConnectorError);
|
||||
});
|
||||
|
||||
it("upserts the override, invalidates the cache and audits", async () => {
|
||||
const { deps, upsert, invalidateCache, recordAction } = makeDeps();
|
||||
await setTenantFeatureConnector(
|
||||
{ tenantId: "t1", featureKey: "api", state: "enabled", reason: "Pilot freischalten", actorUserId: "a1" },
|
||||
deps
|
||||
);
|
||||
expect(upsert).toHaveBeenCalledOnce();
|
||||
expect(invalidateCache).toHaveBeenCalledWith("t1");
|
||||
expect(recordAction).toHaveBeenCalledOnce();
|
||||
expect(recordAction.mock.calls[0][0]).toMatchObject({
|
||||
action: "subscription.featureToggled",
|
||||
targetId: "t1",
|
||||
reason: "Pilot freischalten",
|
||||
after: { featureKey: "api", state: "enabled" },
|
||||
});
|
||||
});
|
||||
|
||||
it("clears the override (deleteMany) when set back to inherit", async () => {
|
||||
const { deps, deleteMany, upsert } = makeDeps();
|
||||
await setTenantFeatureConnector(
|
||||
{ tenantId: "t1", featureKey: "files", state: "inherit", reason: "Zurueck auf Plan-Default", actorUserId: "a1" },
|
||||
deps
|
||||
);
|
||||
expect(deleteMany).toHaveBeenCalledOnce();
|
||||
expect(upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* AK-P19 — Abo-Baukasten mechanic (DoD #3, foundation for AK-P20).
|
||||
*
|
||||
* The platform operator assembles a tenant's subscription by toggling
|
||||
* product-blueprint feature *connectors* on/off per tenant. A toggle is a
|
||||
* `TenantFeatureOverride` upsert (enabled/disabled) or delete (inherit),
|
||||
* which is exactly what the canonical `tenantHasModule()` connector gate
|
||||
* already consults — so this REUSES the entitlement resolver instead of
|
||||
* inventing a parallel feature store. Every change invalidates the module
|
||||
* cache and is audited (reason-gated) through the operator-action gate.
|
||||
*
|
||||
* The billing-provider side of "Abo-Zusammenstellung" stays on the existing
|
||||
* subscription-product helpers / tenant-detail route; this module owns the
|
||||
* feature-connector mechanic, which is the part AK-P20 self-services in v2.
|
||||
*/
|
||||
import {
|
||||
getDefaultProductBlueprint,
|
||||
getProductBlueprint,
|
||||
type ProductBlueprintFeatureDefinition,
|
||||
} from "@hivegrid/entitlements";
|
||||
import type { AdminConnectorInputRow, ConnectorOverrideState } from "@hivegrid/view-models";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { invalidateTenantModuleAccessCache } from "~/utils/connector/tenantConnector.server";
|
||||
import { assertAdminActionReason, recordAdminAction, type AdminActionAuditContext } from "./admin-action-audit.server";
|
||||
|
||||
export type AdminConnectorErrorCode = "FEATURE_NOT_FOUND" | "FEATURE_NOT_TOGGLEABLE";
|
||||
|
||||
/** Connector-toggle failure carrying a stable code + M002 i18n key. */
|
||||
export class AdminConnectorError extends Error {
|
||||
override readonly name = "AdminConnectorError";
|
||||
readonly code: AdminConnectorErrorCode;
|
||||
readonly i18nKey: string;
|
||||
constructor(code: AdminConnectorErrorCode) {
|
||||
super(code);
|
||||
this.code = code;
|
||||
this.i18nKey =
|
||||
code === "FEATURE_NOT_FOUND"
|
||||
? "admin.connectors.errors.featureNotFound"
|
||||
: "admin.connectors.errors.featureNotToggleable";
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolves the blueprint definition for a tenant, falling back to default. */
|
||||
export type BlueprintReader = (blueprintId: string | null | undefined) => readonly ProductBlueprintFeatureDefinition[];
|
||||
|
||||
const defaultBlueprintReader: BlueprintReader = (blueprintId) =>
|
||||
(blueprintId ? getProductBlueprint(blueprintId) : undefined)?.features ?? getDefaultProductBlueprint().features;
|
||||
|
||||
/**
|
||||
* Pure join of blueprint features with a tenant's stored overrides into the
|
||||
* framework-free rows the connector VM consumes. Unit-tested without a DB.
|
||||
*/
|
||||
export function buildConnectorInputRows(
|
||||
features: readonly ProductBlueprintFeatureDefinition[],
|
||||
overrides: ReadonlyMap<string, string>
|
||||
): AdminConnectorInputRow[] {
|
||||
return features.map((feature) => ({
|
||||
featureKey: feature.featureKey,
|
||||
toggleable: feature.tenantToggleable,
|
||||
baseEnabled: feature.defaultEnabled,
|
||||
overrideState: overrides.get(feature.featureKey) ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
export interface ConnectorServiceDeps {
|
||||
readonly db: Pick<typeof db, "tenantProductConfiguration" | "tenantFeatureOverride">;
|
||||
readonly invalidateCache: (tenantId: string) => void;
|
||||
readonly readBlueprint: BlueprintReader;
|
||||
readonly recordAction: (context: AdminActionAuditContext) => Promise<void>;
|
||||
}
|
||||
|
||||
function defaultDeps(): ConnectorServiceDeps {
|
||||
return {
|
||||
db,
|
||||
invalidateCache: invalidateTenantModuleAccessCache,
|
||||
readBlueprint: defaultBlueprintReader,
|
||||
recordAction: recordAdminAction,
|
||||
};
|
||||
}
|
||||
|
||||
/** Reads the connector rows (blueprint features + overrides) for a tenant. */
|
||||
export async function getTenantConnectorRows(
|
||||
tenantId: string,
|
||||
deps: ConnectorServiceDeps = defaultDeps()
|
||||
): Promise<AdminConnectorInputRow[]> {
|
||||
const [configuration, overrides] = await Promise.all([
|
||||
deps.db.tenantProductConfiguration.findUnique({ where: { tenantId }, select: { blueprintId: true } }),
|
||||
deps.db.tenantFeatureOverride.findMany({ where: { tenantId }, select: { featureKey: true, override: true } }),
|
||||
]);
|
||||
const overrideMap = new Map(overrides.map((row) => [row.featureKey, row.override]));
|
||||
return buildConnectorInputRows(deps.readBlueprint(configuration?.blueprintId), overrideMap);
|
||||
}
|
||||
|
||||
export interface SetTenantFeatureConnectorInput {
|
||||
readonly tenantId: string;
|
||||
readonly featureKey: string;
|
||||
readonly state: ConnectorOverrideState;
|
||||
readonly reason: string;
|
||||
readonly actorUserId: string | null;
|
||||
readonly actorEmail?: string | null;
|
||||
readonly request?: Request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggles one feature connector for a tenant: validates the reason, ensures
|
||||
* the feature exists in the blueprint and is operator-toggleable, writes the
|
||||
* override (or clears it for `inherit`), invalidates the module cache, and
|
||||
* audits the change. Errors propagate so the route surfaces Klartext.
|
||||
*/
|
||||
export async function setTenantFeatureConnector(
|
||||
input: SetTenantFeatureConnectorInput,
|
||||
deps: ConnectorServiceDeps = defaultDeps()
|
||||
): Promise<void> {
|
||||
const reason = assertAdminActionReason(input.reason);
|
||||
|
||||
const configuration = await deps.db.tenantProductConfiguration.findUnique({
|
||||
where: { tenantId: input.tenantId },
|
||||
select: { blueprintId: true },
|
||||
});
|
||||
const feature = deps.readBlueprint(configuration?.blueprintId).find((item) => item.featureKey === input.featureKey);
|
||||
if (!feature) throw new AdminConnectorError("FEATURE_NOT_FOUND");
|
||||
if (!feature.tenantToggleable) throw new AdminConnectorError("FEATURE_NOT_TOGGLEABLE");
|
||||
|
||||
if (input.state === "inherit") {
|
||||
await deps.db.tenantFeatureOverride.deleteMany({
|
||||
where: { tenantId: input.tenantId, featureKey: input.featureKey },
|
||||
});
|
||||
} else {
|
||||
await deps.db.tenantFeatureOverride.upsert({
|
||||
where: { tenantId_featureKey: { tenantId: input.tenantId, featureKey: input.featureKey } },
|
||||
create: { tenantId: input.tenantId, featureKey: input.featureKey, override: input.state, reason },
|
||||
update: { override: input.state, reason },
|
||||
});
|
||||
}
|
||||
|
||||
deps.invalidateCache(input.tenantId);
|
||||
|
||||
await deps.recordAction({
|
||||
action: "subscription.featureToggled",
|
||||
actorUserId: input.actorUserId,
|
||||
actorEmail: input.actorEmail ?? null,
|
||||
targetKind: "tenant",
|
||||
targetId: input.tenantId,
|
||||
reason,
|
||||
after: { featureKey: input.featureKey, state: input.state },
|
||||
request: input.request,
|
||||
});
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
assignSupportTicket,
|
||||
postSupportInternalNote,
|
||||
postSupportReply,
|
||||
setSupportTicketStatus,
|
||||
SupportInboxError,
|
||||
type SupportInboxDeps,
|
||||
} from "./support-inbox.server";
|
||||
|
||||
function makeDeps(): {
|
||||
deps: SupportInboxDeps;
|
||||
createMessage: ReturnType<typeof vi.fn>;
|
||||
updateTicket: ReturnType<typeof vi.fn>;
|
||||
recordAction: ReturnType<typeof vi.fn>;
|
||||
} {
|
||||
const createMessage = vi.fn(async () => ({}));
|
||||
const updateTicket = vi.fn(async () => ({}));
|
||||
const recordAction = vi.fn(async () => {});
|
||||
const deps = {
|
||||
db: {
|
||||
supportTicket: { update: updateTicket },
|
||||
supportTicketMessage: { create: createMessage },
|
||||
},
|
||||
recordAction,
|
||||
} as unknown as SupportInboxDeps;
|
||||
return { deps, createMessage, updateTicket, recordAction };
|
||||
}
|
||||
|
||||
describe("postSupportReply", () => {
|
||||
it("creates a customer-visible message, marks answered and audits", async () => {
|
||||
const { deps, createMessage, updateTicket, recordAction } = makeDeps();
|
||||
await postSupportReply({ ticketId: "t1", body: " Hallo ", authorUserId: "a1" }, deps);
|
||||
expect(createMessage.mock.calls[0][0].data).toMatchObject({ supportTicketId: "t1", body: "Hallo", internalNote: false });
|
||||
expect(updateTicket.mock.calls[0][0].data).toMatchObject({ status: "answered" });
|
||||
expect(recordAction.mock.calls[0][0]).toMatchObject({ action: "support.replied", targetId: "t1" });
|
||||
});
|
||||
|
||||
it("rejects an empty body before any write", async () => {
|
||||
const { deps, createMessage } = makeDeps();
|
||||
await expect(postSupportReply({ ticketId: "t1", body: " ", authorUserId: "a1" }, deps)).rejects.toBeInstanceOf(SupportInboxError);
|
||||
expect(createMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("postSupportInternalNote", () => {
|
||||
it("creates an internal note (internalNote=true) and audits without touching status", async () => {
|
||||
const { deps, createMessage, updateTicket, recordAction } = makeDeps();
|
||||
await postSupportInternalNote({ ticketId: "t1", body: "intern", authorUserId: "a1" }, deps);
|
||||
expect(createMessage.mock.calls[0][0].data).toMatchObject({ internalNote: true });
|
||||
expect(updateTicket).not.toHaveBeenCalled();
|
||||
expect(recordAction.mock.calls[0][0]).toMatchObject({ action: "support.noteAdded" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("setSupportTicketStatus", () => {
|
||||
it("rejects an unknown status", async () => {
|
||||
const { deps, updateTicket } = makeDeps();
|
||||
await expect(setSupportTicketStatus({ ticketId: "t1", status: "frozen", actorUserId: "a1" }, deps)).rejects.toMatchObject({
|
||||
code: "INVALID_STATUS",
|
||||
});
|
||||
expect(updateTicket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("updates a valid status and audits", async () => {
|
||||
const { deps, updateTicket, recordAction } = makeDeps();
|
||||
await setSupportTicketStatus({ ticketId: "t1", status: "closed", actorUserId: "a1" }, deps);
|
||||
expect(updateTicket.mock.calls[0][0].data).toMatchObject({ status: "closed" });
|
||||
expect(recordAction.mock.calls[0][0]).toMatchObject({ action: "support.statusChanged", after: { status: "closed" } });
|
||||
});
|
||||
});
|
||||
|
||||
describe("assignSupportTicket", () => {
|
||||
it("sets the assignee and audits, allowing unassignment (null)", async () => {
|
||||
const { deps, updateTicket, recordAction } = makeDeps();
|
||||
await assignSupportTicket({ ticketId: "t1", assigneeUserId: null, actorUserId: "a1" }, deps);
|
||||
expect(updateTicket.mock.calls[0][0].data).toMatchObject({ assignedToUserId: null });
|
||||
expect(recordAction.mock.calls[0][0]).toMatchObject({ action: "support.assigned" });
|
||||
});
|
||||
});
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* AK-P19 — Admin Support-Inbox service (DoD #6).
|
||||
*
|
||||
* Operator actions on a support ticket: reply, internal note, status change
|
||||
* and assignment. Replies + notes are rows in the new SupportTicketMessage
|
||||
* conversation thread (admin.prisma) attached to the existing helpDesk
|
||||
* SupportTicket (which already carries source/status/priority/tenant and is
|
||||
* fed by the P21 feedback widget + inbound email via
|
||||
* `@hivegrid/db/support-tickets.server`). Every write is audited.
|
||||
*
|
||||
* DB access is injected so the orchestration is unit-testable without a
|
||||
* database. Sending the reply back to the customer (email/notify) is left
|
||||
* to the notification Querschnitt wiring and tracked separately.
|
||||
*/
|
||||
import { db } from "~/utils/db.server";
|
||||
import { recordAdminAction, type AdminActionAuditContext } from "./admin-action-audit.server";
|
||||
|
||||
/** Statuses an operator may set on a support ticket. */
|
||||
export const SUPPORT_TICKET_STATUSES = ["open", "pending", "answered", "closed"] as const;
|
||||
export type SupportTicketStatus = (typeof SUPPORT_TICKET_STATUSES)[number];
|
||||
|
||||
export type SupportInboxErrorCode = "EMPTY_BODY" | "INVALID_STATUS";
|
||||
|
||||
export class SupportInboxError extends Error {
|
||||
override readonly name = "SupportInboxError";
|
||||
readonly code: SupportInboxErrorCode;
|
||||
readonly i18nKey: string;
|
||||
constructor(code: SupportInboxErrorCode) {
|
||||
super(code);
|
||||
this.code = code;
|
||||
this.i18nKey = code === "EMPTY_BODY" ? "admin.support.errors.emptyBody" : "admin.support.errors.invalidStatus";
|
||||
}
|
||||
}
|
||||
|
||||
export function assertSupportBody(body: string | null | undefined): string {
|
||||
const trimmed = (body ?? "").trim();
|
||||
if (trimmed.length === 0) throw new SupportInboxError("EMPTY_BODY");
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
export function isSupportTicketStatus(value: string): value is SupportTicketStatus {
|
||||
return (SUPPORT_TICKET_STATUSES as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
export interface SupportInboxDeps {
|
||||
readonly db: Pick<typeof db, "supportTicket" | "supportTicketMessage">;
|
||||
readonly recordAction: (context: AdminActionAuditContext) => Promise<void>;
|
||||
}
|
||||
|
||||
function defaultDeps(): SupportInboxDeps {
|
||||
return { db, recordAction: recordAdminAction };
|
||||
}
|
||||
|
||||
export interface PostSupportMessageInput {
|
||||
readonly ticketId: string;
|
||||
readonly body: string;
|
||||
readonly authorUserId: string | null;
|
||||
readonly actorEmail?: string | null;
|
||||
readonly request?: Request;
|
||||
}
|
||||
|
||||
/** Posts an operator reply (customer-visible) and audits it. */
|
||||
export async function postSupportReply(input: PostSupportMessageInput, deps: SupportInboxDeps = defaultDeps()): Promise<void> {
|
||||
const body = assertSupportBody(input.body);
|
||||
await deps.db.supportTicketMessage.create({
|
||||
data: { supportTicketId: input.ticketId, authorUserId: input.authorUserId, body, internalNote: false },
|
||||
});
|
||||
await deps.db.supportTicket.update({ where: { id: input.ticketId }, data: { status: "answered" } });
|
||||
await deps.recordAction({
|
||||
action: "support.replied",
|
||||
actorUserId: input.authorUserId,
|
||||
actorEmail: input.actorEmail ?? null,
|
||||
targetKind: "supportTicket",
|
||||
targetId: input.ticketId,
|
||||
reason: "Operator-Antwort an den Tenant",
|
||||
request: input.request,
|
||||
});
|
||||
}
|
||||
|
||||
/** Posts an operator-only internal note and audits it. */
|
||||
export async function postSupportInternalNote(input: PostSupportMessageInput, deps: SupportInboxDeps = defaultDeps()): Promise<void> {
|
||||
const body = assertSupportBody(input.body);
|
||||
await deps.db.supportTicketMessage.create({
|
||||
data: { supportTicketId: input.ticketId, authorUserId: input.authorUserId, body, internalNote: true },
|
||||
});
|
||||
await deps.recordAction({
|
||||
action: "support.noteAdded",
|
||||
actorUserId: input.authorUserId,
|
||||
actorEmail: input.actorEmail ?? null,
|
||||
targetKind: "supportTicket",
|
||||
targetId: input.ticketId,
|
||||
reason: "Interne Notiz hinzugefuegt",
|
||||
request: input.request,
|
||||
});
|
||||
}
|
||||
|
||||
export interface SetSupportStatusInput {
|
||||
readonly ticketId: string;
|
||||
readonly status: string;
|
||||
readonly actorUserId: string | null;
|
||||
readonly actorEmail?: string | null;
|
||||
readonly request?: Request;
|
||||
}
|
||||
|
||||
export async function setSupportTicketStatus(input: SetSupportStatusInput, deps: SupportInboxDeps = defaultDeps()): Promise<void> {
|
||||
if (!isSupportTicketStatus(input.status)) throw new SupportInboxError("INVALID_STATUS");
|
||||
await deps.db.supportTicket.update({ where: { id: input.ticketId }, data: { status: input.status } });
|
||||
await deps.recordAction({
|
||||
action: "support.statusChanged",
|
||||
actorUserId: input.actorUserId,
|
||||
actorEmail: input.actorEmail ?? null,
|
||||
targetKind: "supportTicket",
|
||||
targetId: input.ticketId,
|
||||
reason: "Status geaendert",
|
||||
after: { status: input.status },
|
||||
request: input.request,
|
||||
});
|
||||
}
|
||||
|
||||
export interface AssignSupportTicketInput {
|
||||
readonly ticketId: string;
|
||||
readonly assigneeUserId: string | null;
|
||||
readonly actorUserId: string | null;
|
||||
readonly actorEmail?: string | null;
|
||||
readonly request?: Request;
|
||||
}
|
||||
|
||||
export async function assignSupportTicket(input: AssignSupportTicketInput, deps: SupportInboxDeps = defaultDeps()): Promise<void> {
|
||||
await deps.db.supportTicket.update({ where: { id: input.ticketId }, data: { assignedToUserId: input.assigneeUserId } });
|
||||
await deps.recordAction({
|
||||
action: "support.assigned",
|
||||
actorUserId: input.actorUserId,
|
||||
actorEmail: input.actorEmail ?? null,
|
||||
targetKind: "supportTicket",
|
||||
targetId: input.ticketId,
|
||||
reason: "Ticket zugewiesen",
|
||||
after: { assigneeUserId: input.assigneeUserId },
|
||||
request: input.request,
|
||||
});
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
createTenantNote,
|
||||
deleteTenantNote,
|
||||
getTenantNoteRows,
|
||||
normalizeNoteCategory,
|
||||
TenantNoteError,
|
||||
type TenantNotesDeps,
|
||||
} from "./tenant-notes.server";
|
||||
|
||||
function makeDeps(findManyResult: unknown[] = []): {
|
||||
deps: TenantNotesDeps;
|
||||
create: ReturnType<typeof vi.fn>;
|
||||
deleteMany: ReturnType<typeof vi.fn>;
|
||||
recordAction: ReturnType<typeof vi.fn>;
|
||||
} {
|
||||
const create = vi.fn(async () => ({ id: "note-1" }));
|
||||
const deleteMany = vi.fn(async () => ({ count: 1 }));
|
||||
const recordAction = vi.fn(async () => {});
|
||||
const deps = {
|
||||
db: { adminTenantNote: { findMany: vi.fn(async () => findManyResult), create, deleteMany } },
|
||||
recordAction,
|
||||
} as unknown as TenantNotesDeps;
|
||||
return { deps, create, deleteMany, recordAction };
|
||||
}
|
||||
|
||||
describe("normalizeNoteCategory", () => {
|
||||
it("keeps known categories and defaults unknown to general", () => {
|
||||
expect(normalizeNoteCategory("BILLING")).toBe("billing");
|
||||
expect(normalizeNoteCategory("weird")).toBe("general");
|
||||
expect(normalizeNoteCategory(null)).toBe("general");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getTenantNoteRows", () => {
|
||||
it("maps DB rows (author relation, ISO date) into VM input rows", async () => {
|
||||
const { deps } = makeDeps([
|
||||
{
|
||||
id: "n1",
|
||||
createdAt: new Date("2026-06-20T10:00:00.000Z"),
|
||||
category: "billing",
|
||||
pinned: true,
|
||||
noteText: "body",
|
||||
author: { id: "a1", email: "ops@hivegrid.de" },
|
||||
},
|
||||
]);
|
||||
const rows = await getTenantNoteRows("t1", deps);
|
||||
expect(rows[0]).toEqual({
|
||||
id: "n1",
|
||||
createdAtIso: "2026-06-20T10:00:00.000Z",
|
||||
category: "billing",
|
||||
pinned: true,
|
||||
noteText: "body",
|
||||
authorEmail: "ops@hivegrid.de",
|
||||
authorId: "a1",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("createTenantNote", () => {
|
||||
it("rejects an empty body before writing", async () => {
|
||||
const { deps, create } = makeDeps();
|
||||
await expect(createTenantNote({ tenantId: "t1", noteText: " ", authorUserId: "a1" }, deps)).rejects.toBeInstanceOf(TenantNoteError);
|
||||
expect(create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("creates the note with a normalized category and audits", async () => {
|
||||
const { deps, create, recordAction } = makeDeps();
|
||||
await createTenantNote({ tenantId: "t1", noteText: " hi ", category: "WEIRD", pinned: true, authorUserId: "a1" }, deps);
|
||||
expect(create.mock.calls[0][0].data).toMatchObject({ tenantId: "t1", noteText: "hi", category: "general", pinned: true });
|
||||
expect(recordAction.mock.calls[0][0]).toMatchObject({ action: "tenant.note.created", targetId: "t1" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteTenantNote", () => {
|
||||
it("scopes the delete to tenant+note and audits", async () => {
|
||||
const { deps, deleteMany, recordAction } = makeDeps();
|
||||
await deleteTenantNote({ noteId: "n1", tenantId: "t1", actorUserId: "a1" }, deps);
|
||||
expect(deleteMany.mock.calls[0][0].where).toEqual({ id: "n1", tenantId: "t1" });
|
||||
expect(recordAction.mock.calls[0][0]).toMatchObject({ action: "tenant.note.deleted", after: { noteId: "n1" } });
|
||||
});
|
||||
});
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* AK-P19 — Admin tenant-notes service (DoD #3).
|
||||
*
|
||||
* CRUD for the operator notes shown on the tenant-detail screen
|
||||
* (AdminTenantNote, admin.prisma). Create/delete are audited; the list
|
||||
* feeds the `buildAdminTenantNoteListVM` builder. DB access is injected so
|
||||
* the orchestration unit-tests without a database.
|
||||
*/
|
||||
import { ADMIN_TENANT_NOTE_CATEGORIES, type AdminTenantNoteInputRow } from "@hivegrid/view-models";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { recordAdminAction, type AdminActionAuditContext } from "./admin-action-audit.server";
|
||||
|
||||
export class TenantNoteError extends Error {
|
||||
override readonly name = "TenantNoteError";
|
||||
readonly code = "EMPTY_BODY" as const;
|
||||
readonly i18nKey = "admin.tenantNotes.errors.emptyBody";
|
||||
}
|
||||
|
||||
export function assertNoteBody(noteText: string | null | undefined): string {
|
||||
const trimmed = (noteText ?? "").trim();
|
||||
if (trimmed.length === 0) throw new TenantNoteError();
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/** Normalizes a raw category onto a known one, defaulting to general. */
|
||||
export function normalizeNoteCategory(category: string | null | undefined): string {
|
||||
const candidate = (category ?? "").trim().toLowerCase();
|
||||
return (ADMIN_TENANT_NOTE_CATEGORIES as readonly string[]).includes(candidate) ? candidate : "general";
|
||||
}
|
||||
|
||||
export interface TenantNotesDeps {
|
||||
readonly db: Pick<typeof db, "adminTenantNote">;
|
||||
readonly recordAction: (context: AdminActionAuditContext) => Promise<void>;
|
||||
}
|
||||
|
||||
function defaultDeps(): TenantNotesDeps {
|
||||
return { db, recordAction: recordAdminAction };
|
||||
}
|
||||
|
||||
/** Reads the notes for a tenant in the VM input shape (pinned/sort done in VM). */
|
||||
export async function getTenantNoteRows(tenantId: string, deps: TenantNotesDeps = defaultDeps()): Promise<AdminTenantNoteInputRow[]> {
|
||||
const notes = await deps.db.adminTenantNote.findMany({
|
||||
where: { tenantId },
|
||||
select: { id: true, createdAt: true, category: true, pinned: true, noteText: true, author: { select: { id: true, email: true } } },
|
||||
});
|
||||
return notes.map((note) => ({
|
||||
id: note.id,
|
||||
createdAtIso: note.createdAt.toISOString(),
|
||||
category: note.category,
|
||||
pinned: note.pinned,
|
||||
noteText: note.noteText,
|
||||
authorEmail: note.author?.email ?? null,
|
||||
authorId: note.author?.id ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
export interface CreateTenantNoteInput {
|
||||
readonly tenantId: string;
|
||||
readonly noteText: string;
|
||||
readonly category?: string | null;
|
||||
readonly pinned?: boolean;
|
||||
readonly authorUserId: string | null;
|
||||
readonly actorEmail?: string | null;
|
||||
readonly request?: Request;
|
||||
}
|
||||
|
||||
export async function createTenantNote(input: CreateTenantNoteInput, deps: TenantNotesDeps = defaultDeps()): Promise<void> {
|
||||
const noteText = assertNoteBody(input.noteText);
|
||||
const category = normalizeNoteCategory(input.category);
|
||||
const created = await deps.db.adminTenantNote.create({
|
||||
data: { tenantId: input.tenantId, authorUserId: input.authorUserId, noteText, category, pinned: input.pinned ?? false },
|
||||
});
|
||||
await deps.recordAction({
|
||||
action: "tenant.note.created",
|
||||
actorUserId: input.authorUserId,
|
||||
actorEmail: input.actorEmail ?? null,
|
||||
targetKind: "tenant",
|
||||
targetId: input.tenantId,
|
||||
reason: "Notiz angelegt",
|
||||
after: { noteId: created.id, category, pinned: input.pinned ?? false },
|
||||
request: input.request,
|
||||
});
|
||||
}
|
||||
|
||||
export interface DeleteTenantNoteInput {
|
||||
readonly noteId: string;
|
||||
readonly tenantId: string;
|
||||
readonly actorUserId: string | null;
|
||||
readonly actorEmail?: string | null;
|
||||
readonly request?: Request;
|
||||
}
|
||||
|
||||
export async function deleteTenantNote(input: DeleteTenantNoteInput, deps: TenantNotesDeps = defaultDeps()): Promise<void> {
|
||||
await deps.db.adminTenantNote.deleteMany({ where: { id: input.noteId, tenantId: input.tenantId } });
|
||||
await deps.recordAction({
|
||||
action: "tenant.note.deleted",
|
||||
actorUserId: input.actorUserId,
|
||||
actorEmail: input.actorEmail ?? null,
|
||||
targetKind: "tenant",
|
||||
targetId: input.tenantId,
|
||||
reason: "Notiz geloescht",
|
||||
after: { noteId: input.noteId },
|
||||
request: input.request,
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user