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,
|
||||
});
|
||||
}
|
||||
+1
-1
@@ -10,7 +10,7 @@ import {
|
||||
isSensitiveAdminAction,
|
||||
} from "./admin-mfa-gate.server";
|
||||
|
||||
vi.mock("@toolctrl/config", () => ({
|
||||
vi.mock("@hivegrid/config", () => ({
|
||||
loadRequiredWebConfig: vi.fn(() => ({ routing: { appUrl: "https://app.example.test" } })),
|
||||
}));
|
||||
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@
|
||||
* redirect when challenge is required.
|
||||
*/
|
||||
import { redirect } from "react-router";
|
||||
import { loadRequiredWebConfig } from "@toolctrl/config";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
|
||||
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
|
||||
import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
|
||||
|
||||
+14
-3
@@ -16,7 +16,7 @@ describe("auth rate limiting", () => {
|
||||
|
||||
it("builds stable keys from action, client ip, and normalized identifier", () => {
|
||||
const request = new Request("https://example.test/login", {
|
||||
headers: { "x-forwarded-for": "203.0.113.10, 198.51.100.5" },
|
||||
headers: { "cf-connecting-ip": "203.0.113.10" },
|
||||
});
|
||||
|
||||
expect(getAuthRateLimitKey({ request, action: "login", identifier: " Ada@Example.COM " })).toBe(
|
||||
@@ -27,9 +27,20 @@ describe("auth rate limiting", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("does not key on a spoofable X-Forwarded-For / X-Client-IP", () => {
|
||||
// Both spoofable headers must be ignored, so a forged value cannot move the
|
||||
// request into a fresh rate-limit bucket. Both requests collapse to the same
|
||||
// (untrusted -> "unknown") key.
|
||||
const forged = new Request("https://example.test/login", { headers: { "x-forwarded-for": "9.9.9.9", "x-client-ip": "8.8.8.8" } });
|
||||
const bare = new Request("https://example.test/login", {});
|
||||
expect(getAuthRateLimitKey({ request: forged, action: "login", identifier: "ada@example.com" })).toBe(
|
||||
getAuthRateLimitKey({ request: bare, action: "login", identifier: "ada@example.com" })
|
||||
);
|
||||
});
|
||||
|
||||
it("allows requests up to the limit and returns retry timing after the limit", () => {
|
||||
const request = new Request("https://example.test/login", {
|
||||
headers: { "x-client-ip": "203.0.113.10" },
|
||||
headers: { "cf-connecting-ip": "203.0.113.10" },
|
||||
});
|
||||
const options = { request, action: "login" as const, identifier: "ada@example.com", limit: 2, windowMs: 30_000 };
|
||||
|
||||
@@ -40,7 +51,7 @@ describe("auth rate limiting", () => {
|
||||
|
||||
it("starts a new window after the cached counter expires", () => {
|
||||
const request = new Request("https://example.test/mfa", {
|
||||
headers: { "x-client-ip": "203.0.113.10" },
|
||||
headers: { "cf-connecting-ip": "203.0.113.10" },
|
||||
});
|
||||
const options = { request, action: "mfa" as const, identifier: "ada@example.com", limit: 1, windowMs: 10_000 };
|
||||
|
||||
|
||||
+4
-2
@@ -1,7 +1,7 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { cache } from "~/utils/cache.server";
|
||||
import { getClientIPAddress } from "~/utils/server/IpUtils";
|
||||
import { getTrustedClientIp } from "~/utils/server/IpUtils";
|
||||
|
||||
type AuthRateLimitOptions = {
|
||||
request: Request;
|
||||
@@ -16,7 +16,9 @@ type AuthRateLimitResult =
|
||||
| { allowed: false; retryAfterSeconds: number };
|
||||
|
||||
export function getAuthRateLimitKey({ request, action, identifier }: Omit<AuthRateLimitOptions, "limit" | "windowMs">) {
|
||||
const ipAddress = getClientIPAddress(request.headers)?.toString() ?? "unknown";
|
||||
// Trusted proxy-set header only; leftmost X-Forwarded-For / X-Client-IP are
|
||||
// client-spoofable and would let an attacker reset this per-IP auth throttle.
|
||||
const ipAddress = getTrustedClientIp(request) || "unknown";
|
||||
const normalizedIdentifier = identifier?.trim().toLowerCase() ?? "";
|
||||
const digest = createHash("sha256").update(`${action}:${ipAddress}:${normalizedIdentifier}`).digest("hex");
|
||||
return `auth-rate-limit:${action}:${digest}`;
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import { getMailTranslator, getMailTranslatorFromRequest } from "~/locale/mail-t
|
||||
import { queueTransactionalEmail } from "~/modules/emails/services/TransactionalEmailQueue.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
vi.mock("@toolctrl/config", () => ({
|
||||
vi.mock("@hivegrid/config", () => ({
|
||||
loadRequiredWebConfig: vi.fn(() => ({ cryptoSecret: "test-secret", sessionSecret: "session-secret" })),
|
||||
}));
|
||||
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { resolveTransactionalBrandTokens } from "@toolctrl/brand";
|
||||
import { loadRequiredWebConfig } from "@toolctrl/config";
|
||||
import { buildBrand, renderTransactionalEmail } from "@toolctrl/mail";
|
||||
import { resolveTransactionalBrandTokens } from "@hivegrid/brand";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { buildBrand, renderTransactionalEmail } from "@hivegrid/mail";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { getAbsoluteUrl } from "~/utils/url.server";
|
||||
import { queueTransactionalEmail } from "~/modules/emails/services/TransactionalEmailQueue.server";
|
||||
|
||||
+5
-5
@@ -9,8 +9,8 @@ vi.mock("~/utils/api/.server/CryptoApi", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@toolctrl/config", () => ({
|
||||
loadRequiredWebConfig: vi.fn(() => ({ appName: "ToolCTRL" })),
|
||||
vi.mock("@hivegrid/config", () => ({
|
||||
loadRequiredWebConfig: vi.fn(() => ({ appName: "HiveGrid" })),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/users.db.server", () => ({
|
||||
@@ -35,7 +35,7 @@ const vectorSecret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
|
||||
|
||||
function generateExpectedCode(secret: string, timestamp: number): string {
|
||||
const totp = new OTPAuth.TOTP({
|
||||
issuer: "ToolCTRL",
|
||||
issuer: "HiveGrid",
|
||||
label: "test",
|
||||
algorithm: "SHA1",
|
||||
digits: 6,
|
||||
@@ -147,7 +147,7 @@ describe("services/auth/totp.server", () => {
|
||||
|
||||
test("startTotpEnrollment yields encrypted secret + parsable otpauth URI", async () => {
|
||||
const { startTotpEnrollment } = await import("./totp.server");
|
||||
const enrollment = startTotpEnrollment("person@example.com", { issuer: "ToolCTRL" });
|
||||
const enrollment = startTotpEnrollment("person@example.com", { issuer: "HiveGrid" });
|
||||
|
||||
expect(enrollment.secret).toMatch(/^[A-Z2-7]{32}$/);
|
||||
expect(enrollment.encryptedSecret).toBe(`encrypted:${enrollment.secret}`);
|
||||
@@ -191,7 +191,7 @@ describe("services/auth/totp.server", () => {
|
||||
const result = await createTotpEnrollmentForUser({
|
||||
userId: "user_1",
|
||||
userEmail: "security@example.com",
|
||||
issuer: "ToolCTRL Admin",
|
||||
issuer: "HiveGrid Admin",
|
||||
now,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as OTPAuth from "otpauth";
|
||||
import { loadRequiredWebConfig } from "@toolctrl/config";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import CryptoApi from "~/utils/api/.server/CryptoApi";
|
||||
import {
|
||||
activateUserTotpPendingSecret,
|
||||
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { automationActionCatalog, automationTriggerCatalog } from "./automation.registry";
|
||||
import {
|
||||
applyAutomationEditorOperation,
|
||||
buildAutomationDryRunPreview,
|
||||
buildAutomationEditorFlow,
|
||||
buildAutomationReversePlan,
|
||||
canConfirmAutomationDryRun,
|
||||
serializeAutomationEditorFlow,
|
||||
validateAutomationEditorFlow,
|
||||
} from "./automation.editor";
|
||||
|
||||
const catalog = [...automationTriggerCatalog, ...automationActionCatalog];
|
||||
|
||||
describe("automation editor contract", () => {
|
||||
it("validates missing triggers, missing parents, and loops with Klartext keys", () => {
|
||||
const missingTrigger = buildAutomationEditorFlow({
|
||||
flowData: {},
|
||||
steps: [{ stepKey: "task", stepKind: "action", nodeType: "task.create", parentStepIds: [] }],
|
||||
});
|
||||
expect(validateAutomationEditorFlow(missingTrigger).issues.map((issue) => issue.code)).toContain("missing_trigger");
|
||||
expect(validateAutomationEditorFlow(missingTrigger).issues.map((issue) => issue.code)).toContain("unconnected_step");
|
||||
|
||||
const loop = buildAutomationEditorFlow({
|
||||
flowData: {},
|
||||
steps: [
|
||||
{ stepKey: "trigger", stepKind: "trigger", nodeType: "lead.qualified", parentStepIds: ["task"] },
|
||||
{ stepKey: "task", stepKind: "action", nodeType: "task.create", parentStepIds: ["trigger"] },
|
||||
],
|
||||
});
|
||||
expect(validateAutomationEditorFlow(loop).issues).toContainEqual(expect.objectContaining({ code: "loop_detected", messageKey: "automation.editor.validation.loopDetected" }));
|
||||
});
|
||||
|
||||
it("applies graph operations with undo and redo history", () => {
|
||||
const initial = buildAutomationEditorFlow({ flowData: {}, steps: [] });
|
||||
const withTrigger = applyAutomationEditorOperation(initial, { type: "add-node", nodeType: "lead.qualified" }, catalog);
|
||||
const withTask = applyAutomationEditorOperation(withTrigger, { type: "add-node", nodeType: "task.create", parentStepKey: withTrigger.steps[0]?.stepKey }, catalog);
|
||||
const connected = applyAutomationEditorOperation(withTask, { type: "connect", fromStepKey: withTrigger.steps[0]!.stepKey, toStepKey: withTask.steps[1]!.stepKey }, catalog);
|
||||
|
||||
expect(validateAutomationEditorFlow(connected).canActivate).toBe(true);
|
||||
expect(serializeAutomationEditorFlow(connected).steps).toHaveLength(2);
|
||||
|
||||
const undone = applyAutomationEditorOperation(connected, { type: "undo" }, catalog);
|
||||
expect(undone.history.future).toHaveLength(1);
|
||||
|
||||
const redone = applyAutomationEditorOperation(undone, { type: "redo" }, catalog);
|
||||
expect(redone.steps).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("builds dry-run previews with confirmation threshold", () => {
|
||||
const flow = buildAutomationEditorFlow({
|
||||
flowData: {},
|
||||
steps: [
|
||||
{ stepKey: "trigger", stepKind: "trigger", nodeType: "lead.qualified", parentStepIds: [] },
|
||||
{ stepKey: "task", stepKind: "action", nodeType: "task.create", parentStepIds: ["trigger"] },
|
||||
],
|
||||
});
|
||||
const preview = buildAutomationDryRunPreview({ flow, matchedRecords: 101, examples: ["Lead A", "Lead B", "Lead C", "Lead D", "Lead E", "Lead F"] });
|
||||
|
||||
expect(preview.requiresConfirmation).toBe(true);
|
||||
expect(preview.examples).toHaveLength(5);
|
||||
expect(canConfirmAutomationDryRun({ matchedRecords: 101, confirmationPhrase: "falsch" })).toBe(false);
|
||||
expect(canConfirmAutomationDryRun({ matchedRecords: 101, confirmationPhrase: preview.confirmationPhrase })).toBe(true);
|
||||
});
|
||||
|
||||
it("builds 24h reverse plans and marks deliveries as not reversible", () => {
|
||||
const plan = buildAutomationReversePlan({
|
||||
reverseWindowExpiresAt: "2026-07-02T10:00:00.000Z",
|
||||
now: new Date("2026-07-02T09:00:00.000Z"),
|
||||
steps: [
|
||||
{ stepKey: "task", nodeType: "task.create" },
|
||||
{ stepKey: "notify", nodeType: "notification.send" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(plan.canReverse).toBe(true);
|
||||
expect(plan.items).toEqual([
|
||||
expect.objectContaining({ actionKey: "automation.editor.reverse.actions.deleteTask", reversible: true }),
|
||||
expect.objectContaining({ actionKey: "automation.editor.reverse.actions.deliveryNotReversible", reversible: false }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
+408
@@ -0,0 +1,408 @@
|
||||
import {
|
||||
evaluateLoopGuard,
|
||||
getAutomationNode,
|
||||
type AutomationGraphStep,
|
||||
type AutomationNodeDefinition,
|
||||
type AutomationNodeKind,
|
||||
} from "./automation.registry";
|
||||
|
||||
export type AutomationEditorIssueCode = "missing_trigger" | "multiple_triggers" | "unknown_node" | "unconnected_step" | "missing_parent" | "loop_detected" | "empty_flow";
|
||||
|
||||
export interface AutomationEditorStep {
|
||||
readonly stepKey: string;
|
||||
readonly kind: AutomationNodeKind;
|
||||
readonly nodeType: string;
|
||||
readonly parentStepIds: readonly string[];
|
||||
readonly config: Record<string, unknown>;
|
||||
readonly position: { readonly x: number; readonly y: number };
|
||||
readonly sortOrder: number;
|
||||
readonly summaryKey: string;
|
||||
}
|
||||
|
||||
export interface AutomationEditorSnapshot {
|
||||
readonly triggerKey: string;
|
||||
readonly steps: readonly AutomationEditorStep[];
|
||||
}
|
||||
|
||||
export interface AutomationEditorFlow extends AutomationEditorSnapshot {
|
||||
readonly history: {
|
||||
readonly past: readonly AutomationEditorSnapshot[];
|
||||
readonly future: readonly AutomationEditorSnapshot[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface AutomationEditorValidationIssue {
|
||||
readonly code: AutomationEditorIssueCode;
|
||||
readonly severity: "error" | "warning";
|
||||
readonly stepKey: string | null;
|
||||
readonly messageKey: string;
|
||||
readonly detail: string | null;
|
||||
}
|
||||
|
||||
export interface AutomationEditorValidationResult {
|
||||
readonly issues: readonly AutomationEditorValidationIssue[];
|
||||
readonly canActivate: boolean;
|
||||
readonly dependencyEdges: readonly { readonly from: string; readonly to: string }[];
|
||||
}
|
||||
|
||||
export interface AutomationEditorStepInput {
|
||||
readonly stepKey?: unknown;
|
||||
readonly kind?: unknown;
|
||||
readonly stepKind?: unknown;
|
||||
readonly nodeType?: unknown;
|
||||
readonly parentStepIds?: unknown;
|
||||
readonly config?: unknown;
|
||||
readonly position?: unknown;
|
||||
readonly sortOrder?: unknown;
|
||||
readonly summaryKey?: unknown;
|
||||
readonly summaryText?: unknown;
|
||||
}
|
||||
|
||||
export type AutomationEditorOperation =
|
||||
| { readonly type: "add-node"; readonly nodeType: string; readonly parentStepKey?: string | null }
|
||||
| { readonly type: "delete-node"; readonly stepKey: string }
|
||||
| { readonly type: "duplicate-node"; readonly stepKey: string }
|
||||
| { readonly type: "connect"; readonly fromStepKey: string; readonly toStepKey: string }
|
||||
| { readonly type: "disconnect"; readonly fromStepKey: string; readonly toStepKey: string }
|
||||
| { readonly type: "auto-layout" }
|
||||
| { readonly type: "undo" }
|
||||
| { readonly type: "redo" };
|
||||
|
||||
export interface AutomationDryRunPreview {
|
||||
readonly requiresConfirmation: boolean;
|
||||
readonly confirmationPhrase: string;
|
||||
readonly matchedRecords: number;
|
||||
readonly examples: readonly string[];
|
||||
readonly steps: readonly {
|
||||
readonly stepKey: string;
|
||||
readonly nodeType: string;
|
||||
readonly summaryKey: string;
|
||||
readonly effectKey: string;
|
||||
}[];
|
||||
readonly warnings: readonly string[];
|
||||
}
|
||||
|
||||
export interface AutomationReversePlan {
|
||||
readonly canReverse: boolean;
|
||||
readonly confirmationPhrase: string;
|
||||
readonly items: readonly {
|
||||
readonly stepKey: string;
|
||||
readonly nodeType: string;
|
||||
readonly actionKey: string;
|
||||
readonly reversible: boolean;
|
||||
}[];
|
||||
readonly warnings: readonly string[];
|
||||
}
|
||||
|
||||
const DRY_RUN_CONFIRMATION_PHRASE = "DRY RUN STARTEN";
|
||||
const DRY_RUN_CONFIRMATION_THRESHOLD = 100;
|
||||
const REVERSE_CONFIRMATION_PHRASE = "AUTOMATION RUECKGAENGIG";
|
||||
const MAX_HISTORY = 20;
|
||||
|
||||
export function buildAutomationEditorFlow(input: { readonly flowData: unknown; readonly steps: readonly AutomationEditorStepInput[] }): AutomationEditorFlow {
|
||||
const rawFlow = objectOrEmpty(input.flowData);
|
||||
const rawSteps = input.steps.length > 0 ? input.steps : Array.isArray(rawFlow.steps) ? (rawFlow.steps as AutomationEditorStepInput[]) : [];
|
||||
const steps = rawSteps
|
||||
.map((raw, index) => normalizeStep(raw, index))
|
||||
.filter((step): step is AutomationEditorStep => step !== null)
|
||||
.sort((a, b) => a.sortOrder - b.sortOrder || a.stepKey.localeCompare(b.stepKey));
|
||||
const triggerKey = typeof rawFlow.triggerKey === "string" ? rawFlow.triggerKey : steps.find((step) => step.kind === "trigger")?.nodeType ?? "";
|
||||
const history = normalizeHistory(rawFlow.history);
|
||||
return { triggerKey, steps, history };
|
||||
}
|
||||
|
||||
export function serializeAutomationEditorFlow(flow: AutomationEditorFlow): Record<string, unknown> {
|
||||
return {
|
||||
triggerKey: flow.steps.find((step) => step.kind === "trigger")?.nodeType ?? flow.triggerKey,
|
||||
steps: flow.steps.map((step) => ({
|
||||
stepKey: step.stepKey,
|
||||
kind: step.kind,
|
||||
nodeType: step.nodeType,
|
||||
parentStepIds: [...step.parentStepIds],
|
||||
config: step.config,
|
||||
position: step.position,
|
||||
sortOrder: step.sortOrder,
|
||||
summaryKey: step.summaryKey,
|
||||
})),
|
||||
history: flow.history,
|
||||
};
|
||||
}
|
||||
|
||||
export function validateAutomationEditorFlow(flow: AutomationEditorFlow): AutomationEditorValidationResult {
|
||||
const issues: AutomationEditorValidationIssue[] = [];
|
||||
if (flow.steps.length === 0) {
|
||||
issues.push(issue("empty_flow", null, "automation.editor.validation.emptyFlow"));
|
||||
}
|
||||
const triggerSteps = flow.steps.filter((step) => step.kind === "trigger");
|
||||
if (triggerSteps.length === 0) {
|
||||
issues.push(issue("missing_trigger", null, "automation.editor.validation.missingTrigger"));
|
||||
}
|
||||
if (triggerSteps.length > 1) {
|
||||
issues.push(issue("multiple_triggers", null, "automation.editor.validation.multipleTriggers", triggerSteps.map((step) => step.stepKey).join(", ")));
|
||||
}
|
||||
|
||||
const stepKeys = new Set(flow.steps.map((step) => step.stepKey));
|
||||
for (const step of flow.steps) {
|
||||
if (!getAutomationNode(step.nodeType)) {
|
||||
issues.push(issue("unknown_node", step.stepKey, "automation.editor.validation.unknownNode", step.nodeType));
|
||||
}
|
||||
for (const parentStepId of step.parentStepIds) {
|
||||
if (!stepKeys.has(parentStepId)) {
|
||||
issues.push(issue("missing_parent", step.stepKey, "automation.editor.validation.missingParent", parentStepId));
|
||||
}
|
||||
}
|
||||
if (step.kind !== "trigger" && step.parentStepIds.length === 0) {
|
||||
issues.push(issue("unconnected_step", step.stepKey, "automation.editor.validation.unconnectedStep"));
|
||||
}
|
||||
}
|
||||
|
||||
const loop = evaluateLoopGuard(toGraphSteps(flow.steps));
|
||||
if (!loop.ok) {
|
||||
issues.push(issue("loop_detected", null, "automation.editor.validation.loopDetected", loop.cycleStepKeys.join(" -> ")));
|
||||
}
|
||||
|
||||
const reachable = reachableStepKeys(flow.steps, triggerSteps[0]?.stepKey ?? null);
|
||||
for (const step of flow.steps) {
|
||||
if (triggerSteps.length > 0 && !reachable.has(step.stepKey)) {
|
||||
issues.push(issue("unconnected_step", step.stepKey, "automation.editor.validation.unreachableStep"));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
issues,
|
||||
canActivate: !issues.some((item) => item.severity === "error"),
|
||||
dependencyEdges: loop.dependencyEdges,
|
||||
};
|
||||
}
|
||||
|
||||
export function applyAutomationEditorOperation(flow: AutomationEditorFlow, operation: AutomationEditorOperation, catalog: readonly AutomationNodeDefinition[]): AutomationEditorFlow {
|
||||
if (operation.type === "undo") return undoFlow(flow);
|
||||
if (operation.type === "redo") return redoFlow(flow);
|
||||
|
||||
const before = snapshot(flow);
|
||||
let nextSteps = [...flow.steps];
|
||||
if (operation.type === "add-node") {
|
||||
const node = catalog.find((item) => item.key === operation.nodeType) ?? getAutomationNode(operation.nodeType);
|
||||
if (!node) return flow;
|
||||
const stepKey = uniqueStepKey(nextSteps, operation.nodeType);
|
||||
const parentStepIds = node.kind === "trigger" ? [] : [operation.parentStepKey || nextSteps.at(-1)?.stepKey || ""].filter(Boolean);
|
||||
nextSteps.push({
|
||||
stepKey,
|
||||
kind: node.kind,
|
||||
nodeType: node.key,
|
||||
parentStepIds,
|
||||
config: node.defaultConfig,
|
||||
position: { x: 160 * (nextSteps.length % 4), y: 120 * Math.floor(nextSteps.length / 4) },
|
||||
sortOrder: nextSteps.length,
|
||||
summaryKey: node.titleKey,
|
||||
});
|
||||
}
|
||||
if (operation.type === "delete-node") {
|
||||
nextSteps = nextSteps
|
||||
.filter((step) => step.stepKey !== operation.stepKey)
|
||||
.map((step, index) => ({ ...step, parentStepIds: step.parentStepIds.filter((parent) => parent !== operation.stepKey), sortOrder: index }));
|
||||
}
|
||||
if (operation.type === "duplicate-node") {
|
||||
const source = nextSteps.find((step) => step.stepKey === operation.stepKey);
|
||||
if (!source) return flow;
|
||||
nextSteps.push({ ...source, stepKey: uniqueStepKey(nextSteps, source.nodeType), sortOrder: nextSteps.length, position: { x: source.position.x + 48, y: source.position.y + 48 } });
|
||||
}
|
||||
if (operation.type === "connect") {
|
||||
nextSteps = nextSteps.map((step) =>
|
||||
step.stepKey === operation.toStepKey && step.stepKey !== operation.fromStepKey
|
||||
? { ...step, parentStepIds: uniqueStrings([...step.parentStepIds, operation.fromStepKey]) }
|
||||
: step
|
||||
);
|
||||
}
|
||||
if (operation.type === "disconnect") {
|
||||
nextSteps = nextSteps.map((step) => (step.stepKey === operation.toStepKey ? { ...step, parentStepIds: step.parentStepIds.filter((parent) => parent !== operation.fromStepKey) } : step));
|
||||
}
|
||||
if (operation.type === "auto-layout") {
|
||||
nextSteps = nextSteps.map((step, index) => ({ ...step, position: { x: 220 * (index % 3), y: 140 * Math.floor(index / 3) }, sortOrder: index }));
|
||||
}
|
||||
|
||||
return withHistory({ triggerKey: nextSteps.find((step) => step.kind === "trigger")?.nodeType ?? flow.triggerKey, steps: nextSteps, history: flow.history }, before);
|
||||
}
|
||||
|
||||
export function buildAutomationDryRunPreview(input: { readonly flow: AutomationEditorFlow; readonly matchedRecords?: number; readonly examples?: readonly string[] }): AutomationDryRunPreview {
|
||||
const matchedRecords = Math.max(0, input.matchedRecords ?? 0);
|
||||
const validation = validateAutomationEditorFlow(input.flow);
|
||||
return {
|
||||
requiresConfirmation: matchedRecords > DRY_RUN_CONFIRMATION_THRESHOLD,
|
||||
confirmationPhrase: DRY_RUN_CONFIRMATION_PHRASE,
|
||||
matchedRecords,
|
||||
examples: (input.examples ?? []).slice(0, 5),
|
||||
steps: input.flow.steps.map((step) => ({
|
||||
stepKey: step.stepKey,
|
||||
nodeType: step.nodeType,
|
||||
summaryKey: step.summaryKey,
|
||||
effectKey: step.kind === "trigger" ? "automation.editor.dryRun.effects.trigger" : "automation.editor.dryRun.effects.noSideEffect",
|
||||
})),
|
||||
warnings: validation.issues.map((item) => item.messageKey),
|
||||
};
|
||||
}
|
||||
|
||||
export function canConfirmAutomationDryRun(input: { readonly matchedRecords: number; readonly confirmationPhrase?: string | null }): boolean {
|
||||
return input.matchedRecords <= DRY_RUN_CONFIRMATION_THRESHOLD || input.confirmationPhrase === DRY_RUN_CONFIRMATION_PHRASE;
|
||||
}
|
||||
|
||||
export function buildAutomationReversePlan(input: {
|
||||
readonly reverseWindowExpiresAt: string | Date | null;
|
||||
readonly steps: readonly { readonly stepKey: string; readonly nodeType: string }[];
|
||||
readonly now?: Date;
|
||||
}): AutomationReversePlan {
|
||||
const expiresAt = typeof input.reverseWindowExpiresAt === "string" ? new Date(input.reverseWindowExpiresAt) : input.reverseWindowExpiresAt;
|
||||
const canReverse = !!expiresAt && expiresAt.getTime() > (input.now ?? new Date()).getTime();
|
||||
const items = input.steps.map((step) => {
|
||||
const action = reverseActionForNode(step.nodeType);
|
||||
return { stepKey: step.stepKey, nodeType: step.nodeType, actionKey: action.actionKey, reversible: action.reversible };
|
||||
});
|
||||
return {
|
||||
canReverse,
|
||||
confirmationPhrase: REVERSE_CONFIRMATION_PHRASE,
|
||||
items,
|
||||
warnings: items.filter((item) => !item.reversible).map((item) => item.actionKey),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeStep(raw: AutomationEditorStepInput, index: number): AutomationEditorStep | null {
|
||||
const object = objectOrEmpty(raw);
|
||||
const nodeType = typeof object.nodeType === "string" ? object.nodeType : "";
|
||||
const node = getAutomationNode(nodeType);
|
||||
const kind = normalizeKind(object.kind ?? object.stepKind, node?.kind ?? "action");
|
||||
const stepKey = typeof object.stepKey === "string" && object.stepKey.trim() ? object.stepKey.trim() : uniqueFallbackStepKey(nodeType, index);
|
||||
return {
|
||||
stepKey,
|
||||
kind,
|
||||
nodeType,
|
||||
parentStepIds: Array.isArray(object.parentStepIds) ? object.parentStepIds.filter((item): item is string => typeof item === "string") : [],
|
||||
config: objectOrEmpty(object.config),
|
||||
position: normalizePosition(object.position, index),
|
||||
sortOrder: typeof object.sortOrder === "number" ? object.sortOrder : index,
|
||||
summaryKey: typeof object.summaryKey === "string" ? object.summaryKey : typeof object.summaryText === "string" ? object.summaryText : node?.titleKey ?? "automation.execution.stepQueued",
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeHistory(value: unknown): AutomationEditorFlow["history"] {
|
||||
const raw = objectOrEmpty(value);
|
||||
return {
|
||||
past: Array.isArray(raw.past) ? raw.past.map(normalizeSnapshot).filter((item): item is AutomationEditorSnapshot => item !== null).slice(-MAX_HISTORY) : [],
|
||||
future: Array.isArray(raw.future) ? raw.future.map(normalizeSnapshot).filter((item): item is AutomationEditorSnapshot => item !== null).slice(-MAX_HISTORY) : [],
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeSnapshot(value: unknown): AutomationEditorSnapshot | null {
|
||||
const raw = objectOrEmpty(value);
|
||||
const steps = Array.isArray(raw.steps) ? raw.steps.map((step, index) => normalizeStep(step as AutomationEditorStepInput, index)).filter((step): step is AutomationEditorStep => step !== null) : [];
|
||||
if (steps.length === 0) return null;
|
||||
return { triggerKey: typeof raw.triggerKey === "string" ? raw.triggerKey : steps.find((step) => step.kind === "trigger")?.nodeType ?? "", steps };
|
||||
}
|
||||
|
||||
function normalizeKind(value: unknown, fallback: AutomationNodeKind): AutomationNodeKind {
|
||||
return value === "trigger" || value === "condition" || value === "action" || value === "flow_control" ? value : fallback;
|
||||
}
|
||||
|
||||
function normalizePosition(value: unknown, index: number): AutomationEditorStep["position"] {
|
||||
const raw = objectOrEmpty(value);
|
||||
return {
|
||||
x: typeof raw.x === "number" ? raw.x : 220 * (index % 3),
|
||||
y: typeof raw.y === "number" ? raw.y : 140 * Math.floor(index / 3),
|
||||
};
|
||||
}
|
||||
|
||||
function withHistory(flow: AutomationEditorFlow, before: AutomationEditorSnapshot): AutomationEditorFlow {
|
||||
return {
|
||||
...flow,
|
||||
history: {
|
||||
past: [...flow.history.past, before].slice(-MAX_HISTORY),
|
||||
future: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function undoFlow(flow: AutomationEditorFlow): AutomationEditorFlow {
|
||||
const previous = flow.history.past.at(-1);
|
||||
if (!previous) return flow;
|
||||
return {
|
||||
...previous,
|
||||
history: {
|
||||
past: flow.history.past.slice(0, -1),
|
||||
future: [snapshot(flow), ...flow.history.future].slice(0, MAX_HISTORY),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function redoFlow(flow: AutomationEditorFlow): AutomationEditorFlow {
|
||||
const next = flow.history.future[0];
|
||||
if (!next) return flow;
|
||||
return {
|
||||
...next,
|
||||
history: {
|
||||
past: [...flow.history.past, snapshot(flow)].slice(-MAX_HISTORY),
|
||||
future: flow.history.future.slice(1),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function snapshot(flow: AutomationEditorFlow): AutomationEditorSnapshot {
|
||||
return { triggerKey: flow.triggerKey, steps: flow.steps };
|
||||
}
|
||||
|
||||
function toGraphSteps(steps: readonly AutomationEditorStep[]): readonly AutomationGraphStep[] {
|
||||
return steps.map((step) => ({ stepKey: step.stepKey, nodeType: step.nodeType, parentStepIds: step.parentStepIds }));
|
||||
}
|
||||
|
||||
function reachableStepKeys(steps: readonly AutomationEditorStep[], triggerStepKey: string | null): Set<string> {
|
||||
const reachable = new Set<string>();
|
||||
if (!triggerStepKey) return reachable;
|
||||
reachable.add(triggerStepKey);
|
||||
let changed = true;
|
||||
while (changed) {
|
||||
changed = false;
|
||||
for (const step of steps) {
|
||||
if (!reachable.has(step.stepKey) && step.parentStepIds.some((parent) => reachable.has(parent))) {
|
||||
reachable.add(step.stepKey);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return reachable;
|
||||
}
|
||||
|
||||
function uniqueStepKey(steps: readonly AutomationEditorStep[], nodeType: string): string {
|
||||
const base = nodeType.replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-|-$/g, "") || "step";
|
||||
const existing = new Set(steps.map((step) => step.stepKey));
|
||||
let candidate = base;
|
||||
let counter = 2;
|
||||
while (existing.has(candidate)) {
|
||||
candidate = `${base}-${counter}`;
|
||||
counter += 1;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function uniqueFallbackStepKey(nodeType: string, index: number): string {
|
||||
const base = nodeType.replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-|-$/g, "") || "step";
|
||||
return `${base}-${index + 1}`;
|
||||
}
|
||||
|
||||
function uniqueStrings(values: readonly string[]): readonly string[] {
|
||||
return [...new Set(values.filter(Boolean))];
|
||||
}
|
||||
|
||||
function reverseActionForNode(nodeType: string): { actionKey: string; reversible: boolean } {
|
||||
if (nodeType === "task.create") return { actionKey: "automation.editor.reverse.actions.deleteTask", reversible: true };
|
||||
if (nodeType === "crm.update_kontakt") return { actionKey: "automation.editor.reverse.actions.revertCrmStatus", reversible: true };
|
||||
if (nodeType === "crm.create_note") return { actionKey: "automation.editor.reverse.actions.deleteCrmNote", reversible: true };
|
||||
if (nodeType === "task.assign") return { actionKey: "automation.editor.reverse.actions.restoreTaskAssignment", reversible: true };
|
||||
if (nodeType === "notification.send" || nodeType.startsWith("email.")) return { actionKey: "automation.editor.reverse.actions.deliveryNotReversible", reversible: false };
|
||||
return { actionKey: "automation.editor.reverse.actions.noop", reversible: false };
|
||||
}
|
||||
|
||||
function objectOrEmpty(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
|
||||
}
|
||||
|
||||
function issue(code: AutomationEditorIssueCode, stepKey: string | null, messageKey: string, detail: string | null = null): AutomationEditorValidationIssue {
|
||||
return { code, severity: "error", stepKey, messageKey, detail };
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
AUTOMATION_MODULE_KEY,
|
||||
AUTOMATION_READ_PERMISSION,
|
||||
automationActionCatalog,
|
||||
automationTemplateCatalog,
|
||||
automationTriggerCatalog,
|
||||
buildAutomationIdempotencyKey,
|
||||
buildReverseWindowExpiresAt,
|
||||
evaluateLoopGuard,
|
||||
evaluateTriggerVolume,
|
||||
listAutomationNodes,
|
||||
planAutomationRetry,
|
||||
} from "./automation.registry";
|
||||
|
||||
describe("automation registry contract", () => {
|
||||
it("uses the R-P12a module and permission keys", () => {
|
||||
expect(AUTOMATION_MODULE_KEY).toBe("automation");
|
||||
expect(AUTOMATION_READ_PERMISSION).toBe("automation.read");
|
||||
});
|
||||
|
||||
it("covers the required trigger and action groups", () => {
|
||||
expect(new Set(automationTriggerCatalog.map((node) => node.group))).toEqual(new Set(["crm", "lead", "sales", "projects", "email", "forms", "booking", "calendar", "time", "webhook"]));
|
||||
expect(new Set(automationActionCatalog.map((node) => node.group))).toEqual(new Set(["crm", "notification", "http", "task", "flow_control", "kwp"]));
|
||||
expect(automationActionCatalog.find((node) => node.key === "kwp.push_project")?.availability).toBe("extension_slot");
|
||||
expect(listAutomationNodes()).toHaveLength(automationTriggerCatalog.length + automationActionCatalog.length);
|
||||
});
|
||||
|
||||
it("ships platform templates that can become rules", () => {
|
||||
expect(automationTemplateCatalog.map((template) => template.key)).toEqual(["lead-qualified-follow-up", "project-deadline-warning", "form-submission-create-task"]);
|
||||
for (const template of automationTemplateCatalog) {
|
||||
expect(template.steps[0]?.kind).toBe("trigger");
|
||||
expect(template.steps.map((step) => step.stepKey)).toContain("trigger");
|
||||
}
|
||||
});
|
||||
|
||||
it("detects dependency cycles for loop guard warnings", () => {
|
||||
expect(
|
||||
evaluateLoopGuard([
|
||||
{ stepKey: "a", nodeType: "trigger", parentStepIds: ["c"] },
|
||||
{ stepKey: "b", nodeType: "task.create", parentStepIds: ["a"] },
|
||||
{ stepKey: "c", nodeType: "notification.send", parentStepIds: ["b"] },
|
||||
])
|
||||
).toMatchObject({ ok: false, cycleStepKeys: ["a", "b", "c", "a"] });
|
||||
|
||||
expect(
|
||||
evaluateLoopGuard([
|
||||
{ stepKey: "trigger", nodeType: "lead.qualified", parentStepIds: [] },
|
||||
{ stepKey: "task", nodeType: "task.create", parentStepIds: ["trigger"] },
|
||||
]).ok
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("builds idempotency keys and 24h reverse windows deterministically", () => {
|
||||
expect(buildAutomationIdempotencyKey({ tenantId: "t1", ruleId: "r1", triggerKey: "lead.qualified", sourceEventId: "evt1" })).toBe("t1:r1:lead.qualified:evt1");
|
||||
expect(buildReverseWindowExpiresAt(new Date("2026-07-01T10:00:00.000Z")).toISOString()).toBe("2026-07-02T10:00:00.000Z");
|
||||
});
|
||||
|
||||
it("pauses anomalous trigger volumes with Klartext diagnostics", () => {
|
||||
const result = evaluateTriggerVolume({ triggerKey: "lead.qualified", countInWindow: 2000, windowMinutes: 5, typicalDailyMin: 5, typicalDailyMax: 10, hardLimitInWindow: 2000 });
|
||||
|
||||
expect(result.action).toBe("pause");
|
||||
expect(result.summaryText).toContain("2000 automation triggers in 5 minutes");
|
||||
expect(result.summaryText).toContain("typical volume is 5-10 per day");
|
||||
});
|
||||
|
||||
it("plans bounded auto retries for resumable executions", () => {
|
||||
const retry = planAutomationRetry({ attempt: 1, baseDelayMs: 1_000, now: new Date("2026-07-01T10:00:00.000Z") });
|
||||
expect(retry).toMatchObject({ shouldRetry: true, nextAttempt: 2, summaryKey: "automation.guards.retryScheduled" });
|
||||
expect(retry.nextRetryAt?.toISOString()).toBe("2026-07-01T10:00:01.000Z");
|
||||
|
||||
expect(planAutomationRetry({ attempt: 3, maxAttempts: 3 })).toMatchObject({ shouldRetry: false, nextAttempt: 4, summaryKey: "automation.guards.retryExhausted" });
|
||||
});
|
||||
});
|
||||
+274
@@ -0,0 +1,274 @@
|
||||
export const AUTOMATION_MODULE_KEY = "automation";
|
||||
export const AUTOMATION_READ_PERMISSION = "automation.read";
|
||||
export const AUTOMATION_MANAGE_PERMISSION = "automation.manage";
|
||||
export const AUTOMATION_RUN_PERMISSION = "automation.run";
|
||||
export const AUTOMATION_ADMIN_PERMISSION = "automation.admin";
|
||||
|
||||
export type AutomationNodeGroup = "crm" | "lead" | "sales" | "projects" | "email" | "forms" | "booking" | "calendar" | "time" | "webhook" | "notification" | "http" | "task" | "flow_control" | "kwp";
|
||||
export type AutomationNodeKind = "trigger" | "condition" | "action" | "flow_control";
|
||||
export type AutomationNodeAvailability = "active" | "extension_slot";
|
||||
|
||||
export interface AutomationNodeDefinition {
|
||||
readonly key: string;
|
||||
readonly kind: AutomationNodeKind;
|
||||
readonly group: AutomationNodeGroup;
|
||||
readonly titleKey: string;
|
||||
readonly descriptionKey: string;
|
||||
readonly requiredAnyPermission: readonly string[];
|
||||
readonly availability: AutomationNodeAvailability;
|
||||
readonly defaultConfig: Record<string, string | number | boolean>;
|
||||
}
|
||||
|
||||
export interface AutomationTemplateDefinition {
|
||||
readonly key: string;
|
||||
readonly nameKey: string;
|
||||
readonly descriptionKey: string;
|
||||
readonly category: "crm" | "sales" | "projects" | "operations";
|
||||
readonly triggerKey: string;
|
||||
readonly steps: readonly {
|
||||
readonly stepKey: string;
|
||||
readonly kind: AutomationNodeKind;
|
||||
readonly nodeType: string;
|
||||
readonly parentStepIds: readonly string[];
|
||||
readonly summaryKey: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface AutomationGraphStep {
|
||||
readonly stepKey: string;
|
||||
readonly nodeType: string;
|
||||
readonly parentStepIds: readonly string[];
|
||||
}
|
||||
|
||||
export interface AutomationLoopGuardResult {
|
||||
readonly ok: boolean;
|
||||
readonly summaryKey: string;
|
||||
readonly cycleStepKeys: readonly string[];
|
||||
readonly dependencyEdges: readonly { readonly from: string; readonly to: string }[];
|
||||
}
|
||||
|
||||
export interface AutomationTriggerVolumeInput {
|
||||
readonly triggerKey: string;
|
||||
readonly countInWindow: number;
|
||||
readonly windowMinutes: number;
|
||||
readonly typicalDailyMin: number;
|
||||
readonly typicalDailyMax: number;
|
||||
readonly hardLimitInWindow: number;
|
||||
}
|
||||
|
||||
export interface AutomationTriggerVolumeResult {
|
||||
readonly action: "allow" | "pause";
|
||||
readonly summaryText: string;
|
||||
}
|
||||
|
||||
export interface AutomationRetryPlan {
|
||||
readonly shouldRetry: boolean;
|
||||
readonly nextRetryAt: Date | null;
|
||||
readonly nextAttempt: number;
|
||||
readonly summaryKey: string;
|
||||
}
|
||||
|
||||
export const automationTriggerCatalog = Object.freeze([
|
||||
trigger("crm.kontakt_created", "crm", ["crm.read_all", "crm.write"]),
|
||||
trigger("crm.kontakt_updated", "crm", ["crm.read_all", "crm.write"]),
|
||||
trigger("lead.captured", "lead", ["leads.read_all", "leads.write"]),
|
||||
trigger("lead.qualified", "lead", ["leads.read_all", "leads.write"]),
|
||||
trigger("sales.project_won", "sales", ["projects.read_all", "deals.read_aggregates"]),
|
||||
trigger("sales.stage_changed", "sales", ["projects.read_all", "projects.change_stage"]),
|
||||
trigger("projects.project_created", "projects", ["projects.read_all", "projects.write"]),
|
||||
trigger("projects.deadline_soon", "projects", ["projects.read_all", "projects.read_own_pl"]),
|
||||
trigger("email.inbound_received", "email", ["email.domain.view", "emailMarketing.view"]),
|
||||
trigger("email.campaign_bounced", "email", ["emailMarketing.view"]),
|
||||
trigger("forms.submitted", "forms", ["forms.basic", "forms.builder"]),
|
||||
trigger("booking.appointment_booked", "booking", ["bookings.read_all", "bookings.read_own"]),
|
||||
trigger("booking.appointment_cancelled", "booking", ["bookings.read_all", "bookings.read_own"]),
|
||||
trigger("calendar.event_created", "calendar", ["calendar.connect_own", "calendar.admin"]),
|
||||
trigger("time.schedule", "time", [AUTOMATION_MANAGE_PERMISSION]),
|
||||
trigger("webhook.received", "webhook", [AUTOMATION_RUN_PERMISSION, AUTOMATION_MANAGE_PERMISSION]),
|
||||
] as const satisfies readonly AutomationNodeDefinition[]);
|
||||
|
||||
export const automationActionCatalog = Object.freeze([
|
||||
action("crm.update_kontakt", "crm", ["crm.write"]),
|
||||
action("crm.create_note", "crm", ["crm.write"]),
|
||||
action("notification.send", "notification", [AUTOMATION_RUN_PERMISSION]),
|
||||
action("http.request", "http", [AUTOMATION_RUN_PERMISSION]),
|
||||
action("task.create", "task", ["tasks.write"]),
|
||||
action("task.assign", "task", ["tasks.write"]),
|
||||
flow("condition.if_else", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
|
||||
flow("delay.wait", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
|
||||
flow("loop.for_each", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
|
||||
extension("kwp.push_project", "kwp", ["integrations.manual_sync", AUTOMATION_MANAGE_PERMISSION]),
|
||||
] as const satisfies readonly AutomationNodeDefinition[]);
|
||||
|
||||
export const automationTemplateCatalog = Object.freeze([
|
||||
{
|
||||
key: "lead-qualified-follow-up",
|
||||
nameKey: "automation.templates.leadQualifiedFollowUp.name",
|
||||
descriptionKey: "automation.templates.leadQualifiedFollowUp.description",
|
||||
category: "sales",
|
||||
triggerKey: "lead.qualified",
|
||||
steps: [
|
||||
{ stepKey: "trigger", kind: "trigger", nodeType: "lead.qualified", parentStepIds: [], summaryKey: "automation.steps.triggerLeadQualified" },
|
||||
{ stepKey: "create-task", kind: "action", nodeType: "task.create", parentStepIds: ["trigger"], summaryKey: "automation.steps.createSalesTask" },
|
||||
{ stepKey: "notify-office", kind: "action", nodeType: "notification.send", parentStepIds: ["create-task"], summaryKey: "automation.steps.notifyOffice" },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "project-deadline-warning",
|
||||
nameKey: "automation.templates.projectDeadlineWarning.name",
|
||||
descriptionKey: "automation.templates.projectDeadlineWarning.description",
|
||||
category: "projects",
|
||||
triggerKey: "projects.deadline_soon",
|
||||
steps: [
|
||||
{ stepKey: "trigger", kind: "trigger", nodeType: "projects.deadline_soon", parentStepIds: [], summaryKey: "automation.steps.triggerProjectDeadline" },
|
||||
{ stepKey: "notify-project-lead", kind: "action", nodeType: "notification.send", parentStepIds: ["trigger"], summaryKey: "automation.steps.notifyProjectLead" },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "form-submission-create-task",
|
||||
nameKey: "automation.templates.formSubmissionCreateTask.name",
|
||||
descriptionKey: "automation.templates.formSubmissionCreateTask.description",
|
||||
category: "operations",
|
||||
triggerKey: "forms.submitted",
|
||||
steps: [
|
||||
{ stepKey: "trigger", kind: "trigger", nodeType: "forms.submitted", parentStepIds: [], summaryKey: "automation.steps.triggerFormSubmitted" },
|
||||
{ stepKey: "create-task", kind: "action", nodeType: "task.create", parentStepIds: ["trigger"], summaryKey: "automation.steps.createBackofficeTask" },
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly AutomationTemplateDefinition[]);
|
||||
|
||||
const nodeByKey = new Map([...automationTriggerCatalog, ...automationActionCatalog].map((node) => [node.key, node]));
|
||||
|
||||
export function listAutomationNodes(): readonly AutomationNodeDefinition[] {
|
||||
return [...automationTriggerCatalog, ...automationActionCatalog];
|
||||
}
|
||||
|
||||
export function getAutomationNode(key: string): AutomationNodeDefinition | undefined {
|
||||
return nodeByKey.get(key);
|
||||
}
|
||||
|
||||
export function assertAutomationNodeExists(key: string): AutomationNodeDefinition {
|
||||
const node = getAutomationNode(key);
|
||||
if (!node) {
|
||||
throw new Error(`Unknown automation node: ${key}`);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
export function evaluateLoopGuard(steps: readonly AutomationGraphStep[]): AutomationLoopGuardResult {
|
||||
const stepKeys = new Set(steps.map((step) => step.stepKey));
|
||||
const dependencyEdges = steps.flatMap((step) =>
|
||||
step.parentStepIds.filter((parentStepId) => stepKeys.has(parentStepId)).map((parentStepId) => ({ from: parentStepId, to: step.stepKey }))
|
||||
);
|
||||
const outgoing = new Map<string, string[]>();
|
||||
for (const edge of dependencyEdges) {
|
||||
outgoing.set(edge.from, [...(outgoing.get(edge.from) ?? []), edge.to]);
|
||||
}
|
||||
|
||||
const visiting = new Set<string>();
|
||||
const visited = new Set<string>();
|
||||
const path: string[] = [];
|
||||
|
||||
function visit(stepKey: string): string[] | null {
|
||||
if (visiting.has(stepKey)) {
|
||||
const start = path.indexOf(stepKey);
|
||||
return start >= 0 ? path.slice(start).concat(stepKey) : [stepKey];
|
||||
}
|
||||
if (visited.has(stepKey)) return null;
|
||||
visiting.add(stepKey);
|
||||
path.push(stepKey);
|
||||
for (const next of outgoing.get(stepKey) ?? []) {
|
||||
const cycle = visit(next);
|
||||
if (cycle) return cycle;
|
||||
}
|
||||
path.pop();
|
||||
visiting.delete(stepKey);
|
||||
visited.add(stepKey);
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const step of steps) {
|
||||
const cycle = visit(step.stepKey);
|
||||
if (cycle) {
|
||||
return {
|
||||
ok: false,
|
||||
summaryKey: "automation.guards.loopDetected",
|
||||
cycleStepKeys: cycle,
|
||||
dependencyEdges,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
summaryKey: "automation.guards.loopClear",
|
||||
cycleStepKeys: [],
|
||||
dependencyEdges,
|
||||
};
|
||||
}
|
||||
|
||||
export function evaluateTriggerVolume(input: AutomationTriggerVolumeInput): AutomationTriggerVolumeResult {
|
||||
if (input.countInWindow >= input.hardLimitInWindow) {
|
||||
return {
|
||||
action: "pause",
|
||||
summaryText: `${input.countInWindow} automation triggers in ${input.windowMinutes} minutes for ${input.triggerKey}; typical volume is ${input.typicalDailyMin}-${input.typicalDailyMax} per day. Rule paused for review.`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
action: "allow",
|
||||
summaryText: `${input.countInWindow} automation triggers in ${input.windowMinutes} minutes for ${input.triggerKey}; guard within limit.`,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildAutomationIdempotencyKey(input: { tenantId: string; ruleId: string; triggerKey: string; sourceEventId?: string | null; payloadHash?: string | null }): string {
|
||||
return [input.tenantId, input.ruleId, input.triggerKey, input.sourceEventId || input.payloadHash || "manual"].join(":");
|
||||
}
|
||||
|
||||
export function planAutomationRetry(input: { attempt: number; maxAttempts?: number; baseDelayMs?: number; now?: Date }): AutomationRetryPlan {
|
||||
const maxAttempts = input.maxAttempts ?? 3;
|
||||
const nextAttempt = input.attempt + 1;
|
||||
if (nextAttempt > maxAttempts) {
|
||||
return { shouldRetry: false, nextRetryAt: null, nextAttempt, summaryKey: "automation.guards.retryExhausted" };
|
||||
}
|
||||
const delayMs = (input.baseDelayMs ?? 60_000) * 2 ** Math.max(input.attempt - 1, 0);
|
||||
return {
|
||||
shouldRetry: true,
|
||||
nextRetryAt: new Date((input.now ?? new Date()).getTime() + delayMs),
|
||||
nextAttempt,
|
||||
summaryKey: "automation.guards.retryScheduled",
|
||||
};
|
||||
}
|
||||
|
||||
export function buildReverseWindowExpiresAt(now = new Date()): Date {
|
||||
return new Date(now.getTime() + 24 * 60 * 60 * 1000);
|
||||
}
|
||||
|
||||
function trigger(key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[]): AutomationNodeDefinition {
|
||||
return node("trigger", key, group, requiredAnyPermission, "active");
|
||||
}
|
||||
|
||||
function action(key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[]): AutomationNodeDefinition {
|
||||
return node("action", key, group, requiredAnyPermission, "active");
|
||||
}
|
||||
|
||||
function flow(key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[]): AutomationNodeDefinition {
|
||||
return node("flow_control", key, group, requiredAnyPermission, "active");
|
||||
}
|
||||
|
||||
function extension(key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[]): AutomationNodeDefinition {
|
||||
return node("action", key, group, requiredAnyPermission, "extension_slot");
|
||||
}
|
||||
|
||||
function node(kind: AutomationNodeKind, key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[], availability: AutomationNodeAvailability): AutomationNodeDefinition {
|
||||
const i18nKey = key.replaceAll(".", "_");
|
||||
return {
|
||||
key,
|
||||
kind,
|
||||
group,
|
||||
titleKey: `automation.nodes.${i18nKey}.title`,
|
||||
descriptionKey: `automation.nodes.${i18nKey}.description`,
|
||||
requiredAnyPermission,
|
||||
availability,
|
||||
defaultConfig: {},
|
||||
};
|
||||
}
|
||||
+863
@@ -0,0 +1,863 @@
|
||||
import { encryptTenantField } from "@hivegrid/db/crypto/tenant-envelope.server";
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import type { Params } from "react-router";
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import {
|
||||
applyAutomationEditorOperation,
|
||||
buildAutomationReversePlan,
|
||||
buildAutomationDryRunPreview,
|
||||
buildAutomationEditorFlow,
|
||||
canConfirmAutomationDryRun,
|
||||
serializeAutomationEditorFlow,
|
||||
validateAutomationEditorFlow,
|
||||
type AutomationDryRunPreview,
|
||||
type AutomationEditorFlow,
|
||||
type AutomationEditorOperation,
|
||||
type AutomationEditorValidationResult,
|
||||
type AutomationReversePlan,
|
||||
} from "./automation.editor";
|
||||
import {
|
||||
AUTOMATION_ADMIN_PERMISSION,
|
||||
AUTOMATION_MANAGE_PERMISSION,
|
||||
AUTOMATION_MODULE_KEY,
|
||||
AUTOMATION_READ_PERMISSION,
|
||||
AUTOMATION_RUN_PERMISSION,
|
||||
automationActionCatalog,
|
||||
automationTemplateCatalog,
|
||||
automationTriggerCatalog,
|
||||
buildAutomationIdempotencyKey,
|
||||
buildReverseWindowExpiresAt,
|
||||
evaluateLoopGuard,
|
||||
evaluateTriggerVolume,
|
||||
getAutomationNode,
|
||||
listAutomationNodes,
|
||||
type AutomationGraphStep,
|
||||
type AutomationNodeDefinition,
|
||||
} from "./automation.registry";
|
||||
|
||||
export interface AutomationContext {
|
||||
readonly tenantId: string;
|
||||
readonly tenantSlug: string;
|
||||
readonly userId: string;
|
||||
readonly permissions: readonly string[];
|
||||
readonly canManage: boolean;
|
||||
readonly canRun: boolean;
|
||||
readonly canAdmin: boolean;
|
||||
}
|
||||
|
||||
export interface AutomationListItemVM {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly description: string | null;
|
||||
readonly status: string;
|
||||
readonly enabled: boolean;
|
||||
readonly triggerKey: string | null;
|
||||
readonly runs30d: number;
|
||||
readonly lastExecutionAt: string | null;
|
||||
readonly executionsUrl: string;
|
||||
readonly editUrl: string;
|
||||
}
|
||||
|
||||
export interface AutomationListVM {
|
||||
readonly tenantSlug: string;
|
||||
readonly rules: readonly AutomationListItemVM[];
|
||||
readonly triggers: readonly AutomationNodeDefinition[];
|
||||
readonly actions: readonly AutomationNodeDefinition[];
|
||||
readonly templates: readonly { readonly id: string; readonly name: string; readonly category: string; readonly isPublished: boolean }[];
|
||||
readonly canManage: boolean;
|
||||
readonly canRun: boolean;
|
||||
}
|
||||
|
||||
export interface AutomationExecutionListVM {
|
||||
readonly rule: { readonly id: string; readonly name: string; readonly triggerKey: string | null };
|
||||
readonly executions: readonly {
|
||||
readonly id: string;
|
||||
readonly status: string;
|
||||
readonly dryRun: boolean;
|
||||
readonly triggerKey: string;
|
||||
readonly summaryText: string;
|
||||
readonly createdAt: string;
|
||||
readonly durationMs: number | null;
|
||||
readonly detailUrl: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface AutomationExecutionDetailVM {
|
||||
readonly rule: { readonly id: string; readonly name: string };
|
||||
readonly execution: {
|
||||
readonly id: string;
|
||||
readonly status: string;
|
||||
readonly dryRun: boolean;
|
||||
readonly triggerKey: string;
|
||||
readonly summaryText: string;
|
||||
readonly errorText: string | null;
|
||||
readonly reverseWindowExpiresAt: string | null;
|
||||
readonly canReverse: boolean;
|
||||
};
|
||||
readonly steps: readonly {
|
||||
readonly id: string;
|
||||
readonly stepKey: string;
|
||||
readonly nodeType: string;
|
||||
readonly status: string;
|
||||
readonly summaryText: string;
|
||||
readonly durationMs: number | null;
|
||||
readonly errorText: string | null;
|
||||
}[];
|
||||
readonly reversePlan: AutomationReversePlan;
|
||||
}
|
||||
|
||||
export interface AutomationEditorVM {
|
||||
readonly rule: {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly description: string | null;
|
||||
readonly status: string;
|
||||
readonly enabled: boolean;
|
||||
readonly triggerKey: string | null;
|
||||
readonly executionsUrl: string;
|
||||
};
|
||||
readonly flow: AutomationEditorFlow;
|
||||
readonly validation: AutomationEditorValidationResult;
|
||||
readonly catalog: readonly AutomationNodeDefinition[];
|
||||
readonly canManage: boolean;
|
||||
readonly canRun: boolean;
|
||||
readonly templatesUrl: string;
|
||||
}
|
||||
|
||||
export interface AutomationTemplateCatalogVM {
|
||||
readonly templates: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly description: string | null;
|
||||
readonly category: string;
|
||||
readonly isTenantTemplate: boolean;
|
||||
readonly useCount: number;
|
||||
}[];
|
||||
readonly rules: readonly { readonly id: string; readonly name: string }[];
|
||||
readonly canManage: boolean;
|
||||
}
|
||||
|
||||
export type AutomationEditorActionData =
|
||||
| { readonly ok: true; readonly messageKey: string; readonly dryRunPreview?: AutomationDryRunPreview }
|
||||
| { readonly ok: false; readonly errorKey: string; readonly detail?: string | null; readonly dryRunPreview?: AutomationDryRunPreview };
|
||||
|
||||
function hasAnyPermission(permissions: readonly string[], requiredAnyPermission: readonly string[]): boolean {
|
||||
return requiredAnyPermission.some((permission) => permissions.includes(permission));
|
||||
}
|
||||
|
||||
function assertAutomationRead(permissions: readonly string[]): void {
|
||||
if (!permissions.includes(AUTOMATION_READ_PERMISSION) && !permissions.includes(AUTOMATION_ADMIN_PERMISSION)) {
|
||||
throw new CatalogError(foundationErrors.notFound, { permission: AUTOMATION_READ_PERMISSION });
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadAutomationContext({ request, params }: { request: Request; params: Params }): Promise<AutomationContext> {
|
||||
await requireAuth({ request, params });
|
||||
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
|
||||
if (!tenantId || !userInfo.userId) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
const [hasModule, permissions] = await Promise.all([
|
||||
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: AUTOMATION_MODULE_KEY }),
|
||||
getPermissionsByUser(userInfo.userId, tenantId),
|
||||
]);
|
||||
if (!hasModule) {
|
||||
throw new CatalogError(foundationErrors.notFound, { module: AUTOMATION_MODULE_KEY });
|
||||
}
|
||||
assertAutomationRead(permissions);
|
||||
return {
|
||||
tenantId,
|
||||
tenantSlug: params.tenant ?? tenantId,
|
||||
userId: userInfo.userId,
|
||||
permissions,
|
||||
canManage: hasAnyPermission(permissions, [AUTOMATION_MANAGE_PERMISSION, AUTOMATION_ADMIN_PERMISSION]),
|
||||
canRun: hasAnyPermission(permissions, [AUTOMATION_RUN_PERMISSION, AUTOMATION_ADMIN_PERMISSION]),
|
||||
canAdmin: permissions.includes(AUTOMATION_ADMIN_PERMISSION),
|
||||
};
|
||||
}
|
||||
|
||||
export async function ensureDefaultAutomationTemplates(ctx: Pick<AutomationContext, "tenantId">): Promise<void> {
|
||||
await withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
for (const template of automationTemplateCatalog) {
|
||||
const flowData = toPrismaJson(templateToFlowData(template));
|
||||
const existing = await tx.automationTemplate.findFirst({
|
||||
where: { tenantId: null, name: template.nameKey, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (existing) {
|
||||
await tx.automationTemplate.update({
|
||||
where: { id: existing.id },
|
||||
data: { description: template.descriptionKey, category: template.category, flowData, isPublished: true, isDemoData: true },
|
||||
});
|
||||
} else {
|
||||
await tx.automationTemplate.create({
|
||||
data: { tenantId: null, name: template.nameKey, description: template.descriptionKey, category: template.category, flowData, isPublished: true, isDemoData: true },
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadAutomationListVM({ request, params }: { request: Request; params: Params }): Promise<AutomationListVM> {
|
||||
const ctx = await loadAutomationContext({ request, params });
|
||||
await ensureDefaultAutomationTemplates(ctx);
|
||||
const since30d = new Date();
|
||||
since30d.setDate(since30d.getDate() - 30);
|
||||
return withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
const [rules, templates] = await Promise.all([
|
||||
tx.automationRule.findMany({
|
||||
where: { tenantId: ctx.tenantId, archivedAt: null },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
take: 50,
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
description: true,
|
||||
status: true,
|
||||
enabled: true,
|
||||
triggerKey: true,
|
||||
executions: {
|
||||
where: { createdAt: { gte: since30d } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: { createdAt: true },
|
||||
take: 30,
|
||||
},
|
||||
},
|
||||
}),
|
||||
tx.automationTemplate.findMany({
|
||||
where: { OR: [{ tenantId: null }, { tenantId: ctx.tenantId }], isPublished: true, archivedAt: null },
|
||||
orderBy: [{ tenantId: "asc" }, { category: "asc" }, { name: "asc" }],
|
||||
select: { id: true, name: true, category: true, isPublished: true },
|
||||
}),
|
||||
]);
|
||||
return {
|
||||
tenantSlug: ctx.tenantSlug,
|
||||
rules: rules.map((rule) => ({
|
||||
id: rule.id,
|
||||
name: rule.name,
|
||||
description: rule.description,
|
||||
status: rule.status,
|
||||
enabled: rule.enabled,
|
||||
triggerKey: rule.triggerKey,
|
||||
runs30d: rule.executions.length,
|
||||
lastExecutionAt: rule.executions[0]?.createdAt.toISOString() ?? null,
|
||||
executionsUrl: appPath({ tenantSlug: ctx.tenantSlug, path: `automations/${rule.id}/executions`, mode: "host-aware" }),
|
||||
editUrl: appPath({ tenantSlug: ctx.tenantSlug, path: `automations/${rule.id}/edit`, mode: "host-aware" }),
|
||||
})),
|
||||
triggers: filterNodesForPermissions(automationTriggerCatalog, ctx.permissions),
|
||||
actions: filterNodesForPermissions(automationActionCatalog, ctx.permissions),
|
||||
templates,
|
||||
canManage: ctx.canManage,
|
||||
canRun: ctx.canRun,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadAutomationExecutionsVM({ request, params }: { request: Request; params: Params & { id?: string } }): Promise<AutomationExecutionListVM> {
|
||||
const ctx = await loadAutomationContext({ request, params });
|
||||
const ruleId = params.id;
|
||||
if (!ruleId) throw new CatalogError(foundationErrors.notFound);
|
||||
return withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
const rule = await tx.automationRule.findFirst({
|
||||
where: { id: ruleId, tenantId: ctx.tenantId, archivedAt: null },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
triggerKey: true,
|
||||
executions: {
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 50,
|
||||
select: { id: true, status: true, dryRun: true, triggerKey: true, summaryText: true, createdAt: true, durationMs: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!rule) throw new CatalogError(foundationErrors.notFound);
|
||||
return {
|
||||
rule: { id: rule.id, name: rule.name, triggerKey: rule.triggerKey },
|
||||
executions: rule.executions.map((execution) => ({
|
||||
id: execution.id,
|
||||
status: execution.status,
|
||||
dryRun: execution.dryRun,
|
||||
triggerKey: execution.triggerKey,
|
||||
summaryText: execution.summaryText,
|
||||
createdAt: execution.createdAt.toISOString(),
|
||||
durationMs: execution.durationMs,
|
||||
detailUrl: appPath({ tenantSlug: ctx.tenantSlug, path: `automations/${rule.id}/executions/${execution.id}`, mode: "host-aware" }),
|
||||
})),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadAutomationExecutionDetailVM({
|
||||
request,
|
||||
params,
|
||||
}: {
|
||||
request: Request;
|
||||
params: Params & { id?: string; executionId?: string };
|
||||
}): Promise<AutomationExecutionDetailVM> {
|
||||
const ctx = await loadAutomationContext({ request, params });
|
||||
const { id: ruleId, executionId } = params;
|
||||
if (!ruleId || !executionId) throw new CatalogError(foundationErrors.notFound);
|
||||
return withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
const execution = await tx.automationExecution.findFirst({
|
||||
where: { id: executionId, ruleId, tenantId: ctx.tenantId },
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
dryRun: true,
|
||||
triggerKey: true,
|
||||
summaryText: true,
|
||||
errorText: true,
|
||||
reverseWindowExpiresAt: true,
|
||||
rule: { select: { id: true, name: true } },
|
||||
stepExecutions: {
|
||||
orderBy: { sortOrder: "asc" },
|
||||
select: { id: true, stepKey: true, nodeType: true, status: true, summaryText: true, durationMs: true, errorText: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!execution) throw new CatalogError(foundationErrors.notFound);
|
||||
const reverseWindowExpiresAt = execution.reverseWindowExpiresAt?.toISOString() ?? null;
|
||||
const steps = execution.stepExecutions;
|
||||
return {
|
||||
rule: execution.rule,
|
||||
execution: {
|
||||
id: execution.id,
|
||||
status: execution.status,
|
||||
dryRun: execution.dryRun,
|
||||
triggerKey: execution.triggerKey,
|
||||
summaryText: execution.summaryText,
|
||||
errorText: execution.errorText,
|
||||
reverseWindowExpiresAt,
|
||||
canReverse: !!execution.reverseWindowExpiresAt && execution.reverseWindowExpiresAt.getTime() > Date.now(),
|
||||
},
|
||||
steps,
|
||||
reversePlan: buildAutomationReversePlan({ reverseWindowExpiresAt, steps }),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadAutomationEditorVM({ request, params }: { request: Request; params: Params & { id?: string } }): Promise<AutomationEditorVM> {
|
||||
const ctx = await loadAutomationContext({ request, params });
|
||||
const ruleId = params.id;
|
||||
if (!ruleId) throw new CatalogError(foundationErrors.notFound);
|
||||
return withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
const rule = await tx.automationRule.findFirst({
|
||||
where: { id: ruleId, tenantId: ctx.tenantId, archivedAt: null },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
description: true,
|
||||
status: true,
|
||||
enabled: true,
|
||||
triggerKey: true,
|
||||
flowData: true,
|
||||
steps: {
|
||||
orderBy: { sortOrder: "asc" },
|
||||
select: { stepKey: true, stepKind: true, nodeType: true, parentStepIds: true, config: true, position: true, sortOrder: true, summaryText: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!rule) throw new CatalogError(foundationErrors.notFound);
|
||||
const flow = buildAutomationEditorFlow({
|
||||
flowData: rule.flowData,
|
||||
steps: rule.steps.map((step) => ({
|
||||
stepKey: step.stepKey,
|
||||
stepKind: step.stepKind,
|
||||
nodeType: step.nodeType,
|
||||
parentStepIds: step.parentStepIds,
|
||||
config: step.config,
|
||||
position: step.position,
|
||||
sortOrder: step.sortOrder,
|
||||
summaryText: step.summaryText,
|
||||
})),
|
||||
});
|
||||
return {
|
||||
rule: {
|
||||
id: rule.id,
|
||||
name: rule.name,
|
||||
description: rule.description,
|
||||
status: rule.status,
|
||||
enabled: rule.enabled,
|
||||
triggerKey: rule.triggerKey,
|
||||
executionsUrl: appPath({ tenantSlug: ctx.tenantSlug, path: `automations/${rule.id}/executions`, mode: "host-aware" }),
|
||||
},
|
||||
flow,
|
||||
validation: validateAutomationEditorFlow(flow),
|
||||
catalog: filterNodesForPermissions(listAutomationNodes(), ctx.permissions),
|
||||
canManage: ctx.canManage,
|
||||
canRun: ctx.canRun,
|
||||
templatesUrl: appPath({ tenantSlug: ctx.tenantSlug, path: "automations/templates", mode: "host-aware" }),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadAutomationTemplateCatalogVM({ request, params }: { request: Request; params: Params }): Promise<AutomationTemplateCatalogVM> {
|
||||
const ctx = await loadAutomationContext({ request, params });
|
||||
await ensureDefaultAutomationTemplates(ctx);
|
||||
return withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
const [templates, rules] = await Promise.all([
|
||||
tx.automationTemplate.findMany({
|
||||
where: { OR: [{ tenantId: null }, { tenantId: ctx.tenantId }], isPublished: true, archivedAt: null },
|
||||
orderBy: [{ tenantId: "asc" }, { category: "asc" }, { name: "asc" }],
|
||||
select: { id: true, tenantId: true, name: true, description: true, category: true, createdFromRuleId: true },
|
||||
}),
|
||||
tx.automationRule.findMany({
|
||||
where: { tenantId: ctx.tenantId, archivedAt: null },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
take: 50,
|
||||
select: { id: true, name: true },
|
||||
}),
|
||||
]);
|
||||
const useCounts = new Map<string, number>();
|
||||
for (const template of templates) {
|
||||
if (template.createdFromRuleId) useCounts.set(template.createdFromRuleId, (useCounts.get(template.createdFromRuleId) ?? 0) + 1);
|
||||
}
|
||||
return {
|
||||
templates: templates.map((template) => ({
|
||||
id: template.id,
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
category: template.category,
|
||||
isTenantTemplate: template.tenantId === ctx.tenantId,
|
||||
useCount: template.createdFromRuleId ? useCounts.get(template.createdFromRuleId) ?? 0 : 0,
|
||||
})),
|
||||
rules,
|
||||
canManage: ctx.canManage,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function handleAutomationEditorAction({ request, params }: { request: Request; params: Params & { id?: string } }): Promise<AutomationEditorActionData> {
|
||||
const ctx = await loadAutomationContext({ request, params });
|
||||
if (!ctx.canManage) throw new CatalogError(foundationErrors.notFound, { permission: AUTOMATION_MANAGE_PERMISSION });
|
||||
const ruleId = params.id;
|
||||
if (!ruleId) throw new CatalogError(foundationErrors.notFound);
|
||||
const formData = await request.formData();
|
||||
const intent = String(formData.get("intent") ?? "");
|
||||
|
||||
if (intent === "dry-run") {
|
||||
const flow = await loadAutomationEditorFlowForAction(ctx.tenantId, ruleId);
|
||||
const matchedRecords = Number(formData.get("matchedRecords") ?? 0);
|
||||
const dryRunPreview = buildAutomationDryRunPreview({
|
||||
flow,
|
||||
matchedRecords: Number.isFinite(matchedRecords) ? matchedRecords : 0,
|
||||
examples: String(formData.get("examples") ?? "")
|
||||
.split("\n")
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean),
|
||||
});
|
||||
if (!canConfirmAutomationDryRun({ matchedRecords: dryRunPreview.matchedRecords, confirmationPhrase: formData.get("confirmationPhrase")?.toString() })) {
|
||||
return { ok: false, errorKey: "automation.editor.dryRun.confirmationRequired", dryRunPreview };
|
||||
}
|
||||
return { ok: true, messageKey: "automation.editor.dryRun.previewReady", dryRunPreview };
|
||||
}
|
||||
|
||||
if (intent === "activate") {
|
||||
const flow = await loadAutomationEditorFlowForAction(ctx.tenantId, ruleId);
|
||||
const validation = validateAutomationEditorFlow(flow);
|
||||
if (!validation.canActivate) {
|
||||
return { ok: false, errorKey: "automation.editor.actions.activateBlocked", detail: validation.issues[0]?.messageKey ?? null };
|
||||
}
|
||||
await withTenantRLS(ctx.tenantId, (tx) => tx.automationRule.update({ where: { id: ruleId }, data: { status: "active", enabled: true } }));
|
||||
return { ok: true, messageKey: "automation.editor.actions.activated" };
|
||||
}
|
||||
|
||||
if (intent === "pause") {
|
||||
await withTenantRLS(ctx.tenantId, (tx) => tx.automationRule.update({ where: { id: ruleId }, data: { status: "paused", enabled: false } }));
|
||||
return { ok: true, messageKey: "automation.editor.actions.paused" };
|
||||
}
|
||||
|
||||
if (intent === "create-template") {
|
||||
await createAutomationTemplateFromRule({
|
||||
request,
|
||||
params,
|
||||
ruleId,
|
||||
name: String(formData.get("templateName") ?? "").trim() || `automation.template.${ruleId}`,
|
||||
category: String(formData.get("category") ?? "operations"),
|
||||
publish: true,
|
||||
});
|
||||
return { ok: true, messageKey: "automation.editor.actions.templateCreated" };
|
||||
}
|
||||
|
||||
const currentFlow = await loadAutomationEditorFlowForAction(ctx.tenantId, ruleId);
|
||||
const nextFlow = intent === "save-json" ? parseFlowJson(formData.get("flowJson"), currentFlow) : applyAutomationEditorOperation(currentFlow, operationFromFormData(intent, formData), listAutomationNodes());
|
||||
const validation = validateAutomationEditorFlow(nextFlow);
|
||||
await persistAutomationEditorFlow(ctx.tenantId, ruleId, nextFlow);
|
||||
return { ok: true, messageKey: validation.canActivate ? "automation.editor.actions.saved" : "automation.editor.actions.savedWithWarnings" };
|
||||
}
|
||||
|
||||
export async function createAutomationRuleFromTemplate(input: {
|
||||
request: Request;
|
||||
params: Params;
|
||||
templateId: string;
|
||||
name?: string;
|
||||
}): Promise<{ id: string }> {
|
||||
const ctx = await loadAutomationContext({ request: input.request, params: input.params });
|
||||
if (!ctx.canManage) throw new CatalogError(foundationErrors.notFound, { permission: AUTOMATION_MANAGE_PERMISSION });
|
||||
return withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
const template = await tx.automationTemplate.findFirst({
|
||||
where: { id: input.templateId, OR: [{ tenantId: null }, { tenantId: ctx.tenantId }], isPublished: true, archivedAt: null },
|
||||
select: { name: true, description: true, flowData: true },
|
||||
});
|
||||
if (!template) throw new CatalogError(foundationErrors.notFound);
|
||||
const flowData = normalizeFlowData(template.flowData);
|
||||
const guard = evaluateLoopGuard(flowData.steps);
|
||||
if (!guard.ok) {
|
||||
throw new Error(`Automation loop guard blocked template: ${guard.cycleStepKeys.join(" -> ")}`);
|
||||
}
|
||||
const rule = await tx.automationRule.create({
|
||||
data: {
|
||||
tenantId: ctx.tenantId,
|
||||
name: input.name?.trim() || template.name,
|
||||
description: template.description,
|
||||
status: "draft",
|
||||
enabled: false,
|
||||
createdVia: "template",
|
||||
triggerKey: flowData.triggerKey,
|
||||
flowData: toPrismaJson(template.flowData),
|
||||
createdByUserId: ctx.userId,
|
||||
steps: {
|
||||
create: flowData.steps.map((step, index) => ({
|
||||
tenantId: ctx.tenantId,
|
||||
stepKey: step.stepKey,
|
||||
stepKind: nodeKindToStepKind(step.kind),
|
||||
nodeType: step.nodeType,
|
||||
config: {},
|
||||
parentStepIds: [...step.parentStepIds],
|
||||
sortOrder: index,
|
||||
summaryText: step.summaryKey,
|
||||
isDemoData: true,
|
||||
})),
|
||||
},
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return rule;
|
||||
});
|
||||
}
|
||||
|
||||
export async function createAutomationRuleFromTemplateForRoute(input: { request: Request; params: Params; templateId: string; name?: string }): Promise<{ id: string; editUrl: string }> {
|
||||
const rule = await createAutomationRuleFromTemplate(input);
|
||||
return {
|
||||
id: rule.id,
|
||||
editUrl: appPath({ tenantSlug: input.params.tenant ?? "", path: `automations/${rule.id}/edit`, mode: "host-aware" }),
|
||||
};
|
||||
}
|
||||
|
||||
export async function createAutomationTemplateFromRule(input: {
|
||||
request: Request;
|
||||
params: Params;
|
||||
ruleId: string;
|
||||
name: string;
|
||||
category: string;
|
||||
publish?: boolean;
|
||||
}): Promise<{ id: string }> {
|
||||
const ctx = await loadAutomationContext({ request: input.request, params: input.params });
|
||||
if (!ctx.canManage) throw new CatalogError(foundationErrors.notFound, { permission: AUTOMATION_MANAGE_PERMISSION });
|
||||
return withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
const rule = await tx.automationRule.findFirst({
|
||||
where: { id: input.ruleId, tenantId: ctx.tenantId, archivedAt: null },
|
||||
select: {
|
||||
id: true,
|
||||
description: true,
|
||||
triggerKey: true,
|
||||
steps: {
|
||||
orderBy: { sortOrder: "asc" },
|
||||
select: { stepKey: true, stepKind: true, nodeType: true, parentStepIds: true, summaryText: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!rule) throw new CatalogError(foundationErrors.notFound);
|
||||
const flowData = {
|
||||
createdFromRuleId: rule.id,
|
||||
triggerKey: rule.triggerKey ?? "",
|
||||
steps: rule.steps.map((step) => ({
|
||||
stepKey: step.stepKey,
|
||||
kind: step.stepKind,
|
||||
nodeType: step.nodeType,
|
||||
parentStepIds: step.parentStepIds,
|
||||
summaryKey: step.summaryText,
|
||||
})),
|
||||
};
|
||||
return tx.automationTemplate.create({
|
||||
data: {
|
||||
tenantId: ctx.tenantId,
|
||||
name: input.name.trim(),
|
||||
description: rule.description,
|
||||
category: input.category,
|
||||
flowData: toPrismaJson(flowData),
|
||||
isPublished: input.publish === true,
|
||||
createdByUserId: ctx.userId,
|
||||
createdFromRuleId: rule.id,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function startAutomationExecutionForRule(input: {
|
||||
tenantId: string;
|
||||
tenantSlug: string;
|
||||
userId: string | null;
|
||||
ruleId: string;
|
||||
triggerKey: string;
|
||||
triggerPayload: Record<string, unknown>;
|
||||
sourceEventId?: string | null;
|
||||
dryRun?: boolean;
|
||||
resumeFromStepId?: string | null;
|
||||
}): Promise<{ id: string; deduplicated: boolean; status: string }> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const rule = await tx.automationRule.findFirst({
|
||||
where: { id: input.ruleId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: {
|
||||
id: true,
|
||||
enabled: true,
|
||||
status: true,
|
||||
triggerKey: true,
|
||||
steps: { orderBy: { sortOrder: "asc" }, select: { id: true, stepKey: true, nodeType: true, stepKind: true, parentStepIds: true, sortOrder: true, summaryText: true } },
|
||||
},
|
||||
});
|
||||
if (!rule || !rule.enabled || rule.status !== "active") {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
const idempotencyKey = buildAutomationIdempotencyKey({
|
||||
tenantId: input.tenantId,
|
||||
ruleId: rule.id,
|
||||
triggerKey: input.triggerKey,
|
||||
sourceEventId: input.sourceEventId,
|
||||
payloadHash: JSON.stringify(input.triggerPayload).slice(0, 128),
|
||||
});
|
||||
const existing = await tx.automationExecution.findFirst({
|
||||
where: { tenantId: input.tenantId, idempotencyKey },
|
||||
select: { id: true, status: true },
|
||||
});
|
||||
if (existing) {
|
||||
return { id: existing.id, status: existing.status, deduplicated: true };
|
||||
}
|
||||
|
||||
const meter = await recordTriggerVolume({ tenantId: input.tenantId, triggerKey: input.triggerKey });
|
||||
if (meter.action === "pause") {
|
||||
await tx.automationRule.update({ where: { id: rule.id }, data: { status: "paused", enabled: false } });
|
||||
}
|
||||
const guard = evaluateLoopGuard(
|
||||
rule.steps.map((step) => ({ stepKey: step.stepKey, nodeType: step.nodeType, parentStepIds: step.parentStepIds }))
|
||||
);
|
||||
if (!guard.ok) {
|
||||
await tx.automationRule.update({ where: { id: rule.id }, data: { status: "paused", enabled: false } });
|
||||
}
|
||||
|
||||
const execution = await tx.automationExecution.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
ruleId: rule.id,
|
||||
triggerKey: input.triggerKey,
|
||||
triggerPayload: toPrismaJsonObject(input.triggerPayload),
|
||||
status: meter.action === "pause" || !guard.ok ? "paused" : "queued",
|
||||
dryRun: input.dryRun === true,
|
||||
idempotencyKey,
|
||||
reverseWindowExpiresAt: buildReverseWindowExpiresAt(),
|
||||
resumeFromStepId: input.resumeFromStepId ?? null,
|
||||
summaryText: !guard.ok ? "automation.execution.loopGuardPaused" : meter.summaryText,
|
||||
createdByUserId: input.userId,
|
||||
stepExecutions: {
|
||||
create: rule.steps.map((step) => ({
|
||||
tenantId: input.tenantId,
|
||||
ruleStepId: step.id,
|
||||
stepKey: step.stepKey,
|
||||
stepKind: step.stepKind,
|
||||
nodeType: step.nodeType,
|
||||
status: "queued",
|
||||
input: toPrismaJsonObject({}),
|
||||
output: toPrismaJsonObject({}),
|
||||
summaryText: step.summaryText || "automation.execution.stepQueued",
|
||||
sortOrder: step.sortOrder,
|
||||
})),
|
||||
},
|
||||
},
|
||||
select: { id: true, status: true },
|
||||
});
|
||||
return { id: execution.id, status: execution.status, deduplicated: false };
|
||||
});
|
||||
}
|
||||
|
||||
export async function createAutomationCredential(input: {
|
||||
request: Request;
|
||||
params: Params;
|
||||
name: string;
|
||||
kind: string;
|
||||
value: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
}): Promise<{ id: string }> {
|
||||
const ctx = await loadAutomationContext({ request: input.request, params: input.params });
|
||||
if (!ctx.canAdmin) throw new CatalogError(foundationErrors.notFound, { permission: AUTOMATION_ADMIN_PERMISSION });
|
||||
const encryptedValue = await encryptTenantField(ctx.tenantId, input.value);
|
||||
return withTenantRLS(ctx.tenantId, async (tx) =>
|
||||
tx.automationCredential.create({
|
||||
data: {
|
||||
tenantId: ctx.tenantId,
|
||||
name: input.name,
|
||||
kind: input.kind,
|
||||
encryptedValue,
|
||||
metadata: toPrismaJsonObject(input.metadata ?? {}),
|
||||
createdByUserId: ctx.userId,
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async function recordTriggerVolume(input: { tenantId: string; triggerKey: string }): Promise<{ action: "allow" | "pause"; summaryText: string }> {
|
||||
const now = new Date();
|
||||
const windowMinutes = 5;
|
||||
const windowStart = new Date(Math.floor(now.getTime() / (windowMinutes * 60_000)) * windowMinutes * 60_000);
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const row = await tx.automationTriggerMeter.upsert({
|
||||
where: { tenantId_triggerKey_windowStart_windowMinutes: { tenantId: input.tenantId, triggerKey: input.triggerKey, windowStart, windowMinutes } },
|
||||
update: { count: { increment: 1 } },
|
||||
create: { tenantId: input.tenantId, triggerKey: input.triggerKey, windowStart, windowMinutes, count: 1 },
|
||||
select: { count: true },
|
||||
});
|
||||
const result = evaluateTriggerVolume({
|
||||
triggerKey: input.triggerKey,
|
||||
countInWindow: row.count,
|
||||
windowMinutes,
|
||||
typicalDailyMin: 5,
|
||||
typicalDailyMax: 10,
|
||||
hardLimitInWindow: 2000,
|
||||
});
|
||||
if (result.action === "pause") {
|
||||
const pausedUntil = new Date(now.getTime() + 60 * 60_000);
|
||||
await tx.automationTriggerMeter.update({
|
||||
where: { tenantId_triggerKey_windowStart_windowMinutes: { tenantId: input.tenantId, triggerKey: input.triggerKey, windowStart, windowMinutes } },
|
||||
data: { pausedUntil, anomalyText: result.summaryText },
|
||||
});
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
function filterNodesForPermissions(nodes: readonly AutomationNodeDefinition[], permissions: readonly string[]): readonly AutomationNodeDefinition[] {
|
||||
return nodes.filter((node) => hasAnyPermission(permissions, node.requiredAnyPermission));
|
||||
}
|
||||
|
||||
async function loadAutomationEditorFlowForAction(tenantId: string, ruleId: string): Promise<AutomationEditorFlow> {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
const rule = await tx.automationRule.findFirst({
|
||||
where: { id: ruleId, tenantId, archivedAt: null },
|
||||
select: {
|
||||
flowData: true,
|
||||
steps: { orderBy: { sortOrder: "asc" }, select: { stepKey: true, stepKind: true, nodeType: true, parentStepIds: true, config: true, position: true, sortOrder: true, summaryText: true } },
|
||||
},
|
||||
});
|
||||
if (!rule) throw new CatalogError(foundationErrors.notFound);
|
||||
return buildAutomationEditorFlow({
|
||||
flowData: rule.flowData,
|
||||
steps: rule.steps.map((step) => ({
|
||||
stepKey: step.stepKey,
|
||||
stepKind: step.stepKind,
|
||||
nodeType: step.nodeType,
|
||||
parentStepIds: step.parentStepIds,
|
||||
config: step.config,
|
||||
position: step.position,
|
||||
sortOrder: step.sortOrder,
|
||||
summaryText: step.summaryText,
|
||||
})),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function persistAutomationEditorFlow(tenantId: string, ruleId: string, flow: AutomationEditorFlow): Promise<void> {
|
||||
const triggerKey = flow.steps.find((step) => step.kind === "trigger")?.nodeType ?? null;
|
||||
await withTenantRLS(tenantId, async (tx) => {
|
||||
await tx.automationRuleStep.deleteMany({ where: { tenantId, ruleId } });
|
||||
await tx.automationRule.update({
|
||||
where: { id: ruleId },
|
||||
data: {
|
||||
triggerKey,
|
||||
flowData: toPrismaJson(serializeAutomationEditorFlow(flow)),
|
||||
steps: {
|
||||
create: flow.steps.map((step, index) => ({
|
||||
tenantId,
|
||||
stepKey: step.stepKey,
|
||||
stepKind: nodeKindToStepKind(step.kind),
|
||||
nodeType: step.nodeType,
|
||||
config: toPrismaJsonObject(step.config),
|
||||
parentStepIds: [...step.parentStepIds],
|
||||
position: toPrismaJsonObject(step.position),
|
||||
sortOrder: index,
|
||||
summaryText: step.summaryKey,
|
||||
})),
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function operationFromFormData(intent: string, formData: FormData): AutomationEditorOperation {
|
||||
if (intent === "add-node") return { type: "add-node", nodeType: String(formData.get("nodeType") ?? ""), parentStepKey: formData.get("parentStepKey")?.toString() ?? null };
|
||||
if (intent === "delete-node") return { type: "delete-node", stepKey: String(formData.get("stepKey") ?? "") };
|
||||
if (intent === "duplicate-node") return { type: "duplicate-node", stepKey: String(formData.get("stepKey") ?? "") };
|
||||
if (intent === "connect") return { type: "connect", fromStepKey: String(formData.get("fromStepKey") ?? ""), toStepKey: String(formData.get("toStepKey") ?? "") };
|
||||
if (intent === "disconnect") return { type: "disconnect", fromStepKey: String(formData.get("fromStepKey") ?? ""), toStepKey: String(formData.get("toStepKey") ?? "") };
|
||||
if (intent === "undo") return { type: "undo" };
|
||||
if (intent === "redo") return { type: "redo" };
|
||||
return { type: "auto-layout" };
|
||||
}
|
||||
|
||||
function parseFlowJson(value: FormDataEntryValue | null, fallback: AutomationEditorFlow): AutomationEditorFlow {
|
||||
if (typeof value !== "string") return fallback;
|
||||
try {
|
||||
return buildAutomationEditorFlow({ flowData: JSON.parse(value), steps: [] });
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function templateToFlowData(template: (typeof automationTemplateCatalog)[number]) {
|
||||
return {
|
||||
templateKey: template.key,
|
||||
triggerKey: template.triggerKey,
|
||||
steps: template.steps,
|
||||
};
|
||||
}
|
||||
|
||||
function toPrismaJson(value: unknown): Prisma.InputJsonValue {
|
||||
return JSON.parse(JSON.stringify(value ?? {})) as Prisma.InputJsonValue;
|
||||
}
|
||||
|
||||
function toPrismaJsonObject(value: Record<string, unknown>): Prisma.InputJsonObject {
|
||||
return toPrismaJson(value) as Prisma.InputJsonObject;
|
||||
}
|
||||
|
||||
function normalizeFlowData(value: unknown): { triggerKey: string; steps: (AutomationGraphStep & { kind: string; summaryKey: string })[] } {
|
||||
const data = value && typeof value === "object" ? (value as { triggerKey?: unknown; steps?: unknown }) : {};
|
||||
const steps = Array.isArray(data.steps) ? data.steps : [];
|
||||
return {
|
||||
triggerKey: typeof data.triggerKey === "string" ? data.triggerKey : "",
|
||||
steps: steps.map((raw, index) => {
|
||||
const step = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
|
||||
const nodeType = typeof step.nodeType === "string" ? step.nodeType : "";
|
||||
const node = getAutomationNode(nodeType);
|
||||
return {
|
||||
stepKey: typeof step.stepKey === "string" ? step.stepKey : `step-${index + 1}`,
|
||||
kind: typeof step.kind === "string" ? step.kind : node?.kind ?? "action",
|
||||
nodeType,
|
||||
parentStepIds: Array.isArray(step.parentStepIds) ? step.parentStepIds.filter((item): item is string => typeof item === "string") : [],
|
||||
summaryKey: typeof step.summaryKey === "string" ? step.summaryKey : "automation.execution.stepQueued",
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function nodeKindToStepKind(kind: string): "trigger" | "condition" | "action" | "flow_control" {
|
||||
if (kind === "trigger" || kind === "condition" || kind === "flow_control") return kind;
|
||||
return "action";
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { BillingGateway, BillingGatewayInvoice } from "@hivegrid/billing";
|
||||
import {
|
||||
CustomerBillingInvoiceError,
|
||||
getCustomerBillingInvoiceDownloadTarget,
|
||||
getCustomerBillingInvoiceDownloadUrl,
|
||||
listCustomerBillingInvoices,
|
||||
} from "./customer-invoices.server";
|
||||
|
||||
function invoice(overrides: Partial<BillingGatewayInvoice> = {}): BillingGatewayInvoice {
|
||||
return {
|
||||
provider: "lago",
|
||||
providerInvoiceId: "invoice_1",
|
||||
number: "LAG-001",
|
||||
externalCustomerId: "tenant_1",
|
||||
status: "finalized",
|
||||
paymentStatus: "succeeded",
|
||||
invoiceType: "subscription",
|
||||
currency: "EUR",
|
||||
totalAmountCents: 4900,
|
||||
issuingDate: "2026-07-04",
|
||||
fileUrl: "https://files.example.test/invoice_1.pdf",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function gateway(overrides: Partial<BillingGateway> = {}): BillingGateway {
|
||||
return {
|
||||
createCustomer: vi.fn(),
|
||||
getCustomer: vi.fn(),
|
||||
createSubscription: vi.fn(),
|
||||
getSubscription: vi.fn(),
|
||||
listInvoices: vi.fn(async () => [invoice(), invoice({ providerInvoiceId: "foreign_invoice", externalCustomerId: "tenant_2" })]),
|
||||
downloadInvoice: vi.fn(async () => invoice()),
|
||||
...overrides,
|
||||
} as BillingGateway;
|
||||
}
|
||||
|
||||
describe("customer billing invoices", () => {
|
||||
it("lists only invoices that belong to the current tenant", async () => {
|
||||
const deps = { gateway: gateway() };
|
||||
|
||||
await expect(listCustomerBillingInvoices({ tenantId: "tenant_1", tenantSlug: "acme" }, deps)).resolves.toEqual([
|
||||
{
|
||||
id: "invoice_1",
|
||||
number: "LAG-001",
|
||||
issuingDate: "2026-07-04",
|
||||
amountCents: 4900,
|
||||
currency: "EUR",
|
||||
status: "finalized",
|
||||
paymentStatus: "succeeded",
|
||||
invoiceType: "subscription",
|
||||
downloadHref: "/acme/settings/subscription/invoices/invoice_1/download",
|
||||
},
|
||||
]);
|
||||
expect(deps.gateway.listInvoices).toHaveBeenCalledWith({ tenantId: "tenant_1", perPage: 50 });
|
||||
});
|
||||
|
||||
it("returns an empty customer invoice list when Lago is not configured", async () => {
|
||||
await expect(listCustomerBillingInvoices({ tenantId: "tenant_1", tenantSlug: "acme" }, { gateway: null })).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps voided invoices visible but not downloadable", async () => {
|
||||
await expect(
|
||||
listCustomerBillingInvoices(
|
||||
{ tenantId: "tenant_1", tenantSlug: "acme" },
|
||||
{ gateway: gateway({ listInvoices: vi.fn(async () => [invoice({ status: "voided" })]) }) }
|
||||
)
|
||||
).resolves.toMatchObject([{ id: "invoice_1", status: "voided", downloadHref: null }]);
|
||||
});
|
||||
|
||||
it("returns a generated download URL after tenant ownership is verified", async () => {
|
||||
const deps = { gateway: gateway() };
|
||||
|
||||
await expect(getCustomerBillingInvoiceDownloadUrl({ tenantId: "tenant_1", invoiceId: "invoice_1" }, deps)).resolves.toBe(
|
||||
"https://files.example.test/invoice_1.pdf"
|
||||
);
|
||||
expect(deps.gateway.listInvoices).toHaveBeenCalledWith({ tenantId: "tenant_1", perPage: 50 });
|
||||
expect(deps.gateway.downloadInvoice).toHaveBeenCalledWith("invoice_1");
|
||||
});
|
||||
|
||||
it("accepts Lago download responses without customer data after list ownership check", async () => {
|
||||
await expect(
|
||||
getCustomerBillingInvoiceDownloadTarget(
|
||||
{ tenantId: "tenant_1", invoiceId: "invoice_1" },
|
||||
{ gateway: gateway({ downloadInvoice: vi.fn(async () => invoice({ externalCustomerId: null })) }) }
|
||||
)
|
||||
).resolves.toEqual({
|
||||
fileUrl: "https://files.example.test/invoice_1.pdf",
|
||||
filename: "LAG-001.pdf",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects downloads for invoices from another tenant", async () => {
|
||||
await expect(
|
||||
getCustomerBillingInvoiceDownloadUrl(
|
||||
{ tenantId: "tenant_1", invoiceId: "foreign_invoice" },
|
||||
{ gateway: gateway({ downloadInvoice: vi.fn(async () => invoice({ providerInvoiceId: "foreign_invoice", externalCustomerId: "tenant_2" })) }) }
|
||||
)
|
||||
).rejects.toMatchObject({ name: "CustomerBillingInvoiceError", code: "INVOICE_NOT_FOUND" });
|
||||
});
|
||||
|
||||
it("rejects downloads when Lago has not generated a file URL", async () => {
|
||||
await expect(
|
||||
getCustomerBillingInvoiceDownloadUrl(
|
||||
{ tenantId: "tenant_1", invoiceId: "invoice_1" },
|
||||
{
|
||||
gateway: gateway({
|
||||
listInvoices: vi.fn(async () => [invoice({ fileUrl: null })]),
|
||||
downloadInvoice: vi.fn(async () => invoice({ fileUrl: null })),
|
||||
}),
|
||||
}
|
||||
)
|
||||
).rejects.toBeInstanceOf(CustomerBillingInvoiceError);
|
||||
});
|
||||
});
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
import { createLagoBillingGateway, type BillingGateway, type BillingGatewayInvoice } from "@hivegrid/billing";
|
||||
import { loadWebConfig } from "@hivegrid/config";
|
||||
import type { CustomerBillingInvoiceDto } from "~/application/dtos/billing/CustomerBillingInvoiceDto";
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
export class CustomerBillingInvoiceError extends Error {
|
||||
override readonly name = "CustomerBillingInvoiceError";
|
||||
readonly i18nKey: string;
|
||||
|
||||
constructor(readonly code: "CONFIGURATION_MISSING" | "INVOICE_NOT_FOUND" | "DOWNLOAD_UNAVAILABLE") {
|
||||
super(code);
|
||||
this.i18nKey = `settings.subscription.errors.${code}`;
|
||||
}
|
||||
}
|
||||
|
||||
type CustomerInvoiceDeps = {
|
||||
gateway?: BillingGateway | null;
|
||||
loadGateway?: () => BillingGateway | null;
|
||||
};
|
||||
|
||||
export type CustomerBillingInvoiceDownloadTarget = {
|
||||
fileUrl: string;
|
||||
filename: string;
|
||||
};
|
||||
|
||||
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 resolveGateway(deps: CustomerInvoiceDeps = {}): BillingGateway | null {
|
||||
if ("gateway" in deps) return deps.gateway ?? null;
|
||||
return (deps.loadGateway ?? createConfiguredLagoGateway)();
|
||||
}
|
||||
|
||||
function toCustomerInvoice(invoice: BillingGatewayInvoice, tenantSlug: string): CustomerBillingInvoiceDto {
|
||||
const isDownloadable = invoice.status !== "voided";
|
||||
return {
|
||||
id: invoice.providerInvoiceId,
|
||||
number: invoice.number,
|
||||
issuingDate: invoice.issuingDate,
|
||||
amountCents: invoice.totalAmountCents,
|
||||
currency: invoice.currency,
|
||||
status: invoice.status,
|
||||
paymentStatus: invoice.paymentStatus,
|
||||
invoiceType: invoice.invoiceType,
|
||||
downloadHref: isDownloadable
|
||||
? appPath({ tenantSlug, path: `settings/subscription/invoices/${encodeURIComponent(invoice.providerInvoiceId)}/download`, mode: "host-aware" })
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
function filenameForInvoice(invoice: BillingGatewayInvoice): string {
|
||||
return `${(invoice.number || invoice.providerInvoiceId).replace(/[^a-zA-Z0-9._-]+/g, "-")}.pdf`;
|
||||
}
|
||||
|
||||
function toServerReachableLagoFileUrl(fileUrl: string): string {
|
||||
const config = loadWebConfig().config.lago;
|
||||
if (!config.apiUrl) return fileUrl;
|
||||
|
||||
try {
|
||||
const original = new URL(fileUrl);
|
||||
if (!original.pathname.startsWith("/rails/active_storage/")) return fileUrl;
|
||||
const apiUrl = new URL(config.apiUrl);
|
||||
return `${apiUrl.toString().replace(/\/$/u, "")}${original.pathname}${original.search}`;
|
||||
} catch {
|
||||
return fileUrl;
|
||||
}
|
||||
}
|
||||
|
||||
export async function listCustomerBillingInvoices(input: { tenantId: string; tenantSlug: string }, deps: CustomerInvoiceDeps = {}): Promise<CustomerBillingInvoiceDto[]> {
|
||||
const gateway = resolveGateway(deps);
|
||||
if (!gateway) return [];
|
||||
const invoices = await gateway.listInvoices({ tenantId: input.tenantId, perPage: 50 });
|
||||
return invoices
|
||||
.filter((invoice) => invoice.externalCustomerId === input.tenantId)
|
||||
.map((invoice) => toCustomerInvoice(invoice, input.tenantSlug));
|
||||
}
|
||||
|
||||
export async function getCustomerBillingInvoiceDownloadUrl(
|
||||
input: { tenantId: string; invoiceId: string },
|
||||
deps: CustomerInvoiceDeps = {}
|
||||
): Promise<string> {
|
||||
return (await getCustomerBillingInvoiceDownloadTarget(input, deps)).fileUrl;
|
||||
}
|
||||
|
||||
export async function getCustomerBillingInvoiceDownloadTarget(
|
||||
input: { tenantId: string; invoiceId: string },
|
||||
deps: CustomerInvoiceDeps = {}
|
||||
): Promise<CustomerBillingInvoiceDownloadTarget> {
|
||||
const gateway = resolveGateway(deps);
|
||||
if (!gateway) throw new CustomerBillingInvoiceError("CONFIGURATION_MISSING");
|
||||
|
||||
const ownedInvoice = (await gateway.listInvoices({ tenantId: input.tenantId, perPage: 50 })).find(
|
||||
(invoice) => invoice.providerInvoiceId === input.invoiceId && invoice.externalCustomerId === input.tenantId
|
||||
);
|
||||
if (!ownedInvoice) {
|
||||
throw new CustomerBillingInvoiceError("INVOICE_NOT_FOUND");
|
||||
}
|
||||
|
||||
const downloadedInvoice = await gateway.downloadInvoice(input.invoiceId);
|
||||
const fileUrl = downloadedInvoice?.fileUrl ?? ownedInvoice.fileUrl;
|
||||
if (!fileUrl) {
|
||||
throw new CustomerBillingInvoiceError("DOWNLOAD_UNAVAILABLE");
|
||||
}
|
||||
return {
|
||||
fileUrl: toServerReachableLagoFileUrl(fileUrl),
|
||||
filename: filenameForInvoice(downloadedInvoice ?? ownedInvoice),
|
||||
};
|
||||
}
|
||||
+360
@@ -0,0 +1,360 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
createLagoBillingGateway,
|
||||
createMolliePaymentGateway,
|
||||
type BillingGateway,
|
||||
type BillingGatewaySubscription,
|
||||
type PaymentGateway,
|
||||
type PaymentGatewayPayment,
|
||||
} from "@hivegrid/billing";
|
||||
import { loadWebConfig } from "@hivegrid/config";
|
||||
import { applyLagoSubscriptionSync, applyMolliePaymentSync } from "@hivegrid/db/billing-sync.server";
|
||||
import type { CheckoutSessionStatus, SubscriptionPrice, SubscriptionProduct } from "@hivegrid/db/prisma-browser";
|
||||
import {
|
||||
createCheckoutSessionStatus,
|
||||
getCheckoutSessionStatus,
|
||||
getSubscriptionProduct,
|
||||
updateCheckoutSessionStatus,
|
||||
type SubscriptionProductPriceWithDetails,
|
||||
type SubscriptionProductWithDetails,
|
||||
} from "@hivegrid/db/subscriptions.server";
|
||||
import { SubscriptionPriceType } from "~/application/enums/subscriptions/SubscriptionPriceType";
|
||||
import { apiUrl } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { absolutePublicAppPath } from "~/utils/app/CrossHostUrls";
|
||||
import { invalidateTenantModuleAccessCache } from "~/utils/connector/tenantConnector.server";
|
||||
import { clearTenantSubscriptionCache } from "~/utils/services/.server/subscriptionService";
|
||||
|
||||
export class SelfServiceCheckoutError extends Error {
|
||||
override readonly name = "SelfServiceCheckoutError";
|
||||
readonly i18nKey: string;
|
||||
|
||||
constructor(
|
||||
readonly code:
|
||||
| "PROVIDER_CONFIGURATION_MISSING"
|
||||
| "PLAN_NOT_FOUND"
|
||||
| "PRICE_NOT_FOUND"
|
||||
| "PLAN_NOT_PURCHASABLE"
|
||||
| "CHECKOUT_NOT_PAYABLE"
|
||||
| "CHECKOUT_URL_MISSING"
|
||||
| "SESSION_NOT_FOUND"
|
||||
| "PAYMENT_NOT_FOUND"
|
||||
) {
|
||||
super(code);
|
||||
this.i18nKey = `settings.subscription.errors.${code}`;
|
||||
}
|
||||
}
|
||||
|
||||
type TenantCheckoutContext = {
|
||||
tenantId: string;
|
||||
tenantSlug: string;
|
||||
tenantName: string;
|
||||
userId: string;
|
||||
userEmail: string;
|
||||
userName: string;
|
||||
};
|
||||
|
||||
export type CreateSelfServiceCheckoutInput = TenantCheckoutContext & {
|
||||
request: Request;
|
||||
productId: string;
|
||||
billingPeriod: number;
|
||||
currency: string;
|
||||
quantity: number;
|
||||
};
|
||||
|
||||
export type CompleteSelfServiceCheckoutInput = {
|
||||
sessionId: string;
|
||||
tenantId: string;
|
||||
};
|
||||
|
||||
export type SelfServiceCheckoutResponse = {
|
||||
id: string;
|
||||
customer: {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
};
|
||||
products: {
|
||||
id: string;
|
||||
title: string;
|
||||
quantity: number;
|
||||
subscription: string | undefined;
|
||||
prices: { flatPrice?: SubscriptionPrice; quantity?: number }[];
|
||||
}[];
|
||||
status: CheckoutSessionStatus | null;
|
||||
source: "self-service";
|
||||
};
|
||||
|
||||
type SelfServiceCheckoutDeps = {
|
||||
lagoGateway?: BillingGateway | null;
|
||||
mollieGateway?: PaymentGateway | null;
|
||||
};
|
||||
|
||||
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 getLagoGateway(deps: SelfServiceCheckoutDeps = {}) {
|
||||
if ("lagoGateway" in deps) return deps.lagoGateway ?? null;
|
||||
return createConfiguredLagoGateway();
|
||||
}
|
||||
|
||||
function getMollieGateway(deps: SelfServiceCheckoutDeps = {}) {
|
||||
if ("mollieGateway" in deps) return deps.mollieGateway ?? null;
|
||||
return createConfiguredMollieGateway();
|
||||
}
|
||||
|
||||
function normalizeQuantity(value: number): number {
|
||||
if (!Number.isFinite(value)) return 1;
|
||||
return Math.min(10_000, Math.max(1, Math.trunc(value)));
|
||||
}
|
||||
|
||||
function resolvePlanCode(product: Pick<SubscriptionProduct, "id" | "code" | "lagoPlanCode">): string {
|
||||
return product.lagoPlanCode?.trim() || product.code?.trim() || product.id;
|
||||
}
|
||||
|
||||
function findCheckoutPrice(product: SubscriptionProductWithDetails, billingPeriod: number, currency: string) {
|
||||
return product.prices.find(
|
||||
(price) =>
|
||||
price.active &&
|
||||
price.type === SubscriptionPriceType.RECURRING &&
|
||||
price.billingPeriod === billingPeriod &&
|
||||
price.currency.toLowerCase() === currency.toLowerCase()
|
||||
);
|
||||
}
|
||||
|
||||
function requireRecordId(id: string | undefined, code: "PLAN_NOT_FOUND" | "PRICE_NOT_FOUND"): string {
|
||||
if (!id) throw new SelfServiceCheckoutError(code);
|
||||
return id;
|
||||
}
|
||||
|
||||
function centsForPrice(price: SubscriptionProductPriceWithDetails, quantity: number): number {
|
||||
return Math.round(Number(price.price ?? 0) * 100 * quantity);
|
||||
}
|
||||
|
||||
function buildRedirectUrl(tenantSlug: string, sessionId: string) {
|
||||
const routing = loadWebConfig().config.routing;
|
||||
return absolutePublicAppPath(routing, `/subscribe/${encodeURIComponent(tenantSlug)}/${encodeURIComponent(sessionId)}/success`);
|
||||
}
|
||||
|
||||
function buildWebhookUrl() {
|
||||
const routing = loadWebConfig().config.routing;
|
||||
return apiUrl({
|
||||
rootDomain: routing.apiHost,
|
||||
protocol: routing.protocol,
|
||||
path: "billing/mollie/webhooks",
|
||||
version: "v1",
|
||||
mode: "host-aware",
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureLagoCustomer(gateway: BillingGateway, input: TenantCheckoutContext, currency: string) {
|
||||
const existing = await gateway.getCustomer(input.tenantId);
|
||||
if (existing) return existing;
|
||||
return gateway.createCustomer({
|
||||
tenantId: input.tenantId,
|
||||
name: input.tenantName,
|
||||
email: input.userEmail,
|
||||
currency: currency.toUpperCase(),
|
||||
});
|
||||
}
|
||||
|
||||
function isPaidPayment(payment: PaymentGatewayPayment | null): payment is PaymentGatewayPayment {
|
||||
return payment?.status === "paid" || payment?.status === "authorized";
|
||||
}
|
||||
|
||||
function mollieEventKey(payment: PaymentGatewayPayment) {
|
||||
const refundPart = typeof payment.amountRefundedCents === "number" ? payment.amountRefundedCents : "none";
|
||||
return `mollie:webhook:${payment.providerPaymentId}:${payment.status}:${refundPart}`.replace(/[^A-Za-z0-9._:-]/gu, "_").slice(0, 256);
|
||||
}
|
||||
|
||||
function lagoEventKey(payment: PaymentGatewayPayment) {
|
||||
return `mollie:lago:${payment.providerPaymentId}:${payment.status}`.replace(/[^A-Za-z0-9._:-]/gu, "_").slice(0, 256);
|
||||
}
|
||||
|
||||
async function syncPaidCheckoutSession(payment: PaymentGatewayPayment, session: CheckoutSessionStatus) {
|
||||
const tenantId = payment.metadata.tenantId ?? session.fromTenantId;
|
||||
const invoiceExternalId = payment.metadata.invoiceExternalId ?? session.invoiceExternalId;
|
||||
if (!tenantId || !invoiceExternalId) return;
|
||||
|
||||
await applyMolliePaymentSync({
|
||||
tenantId,
|
||||
eventKey: mollieEventKey(payment),
|
||||
paymentExternalId: payment.externalId ?? payment.providerPaymentId,
|
||||
invoiceExternalId,
|
||||
status: payment.status,
|
||||
receivedAt: new Date(),
|
||||
});
|
||||
|
||||
const planCode = payment.metadata.planCode ?? session.planCode;
|
||||
const lagoSubscriptionId = payment.metadata.lagoSubscriptionId ?? session.lagoSubscriptionId;
|
||||
if (planCode && lagoSubscriptionId) {
|
||||
await applyLagoSubscriptionSync({
|
||||
tenantId,
|
||||
eventKey: lagoEventKey(payment),
|
||||
lagoCustomerId: payment.metadata.lagoCustomerId,
|
||||
lagoSubscriptionId,
|
||||
planCode,
|
||||
seatQuantity: payment.metadata.seatQuantity ?? session.quantity,
|
||||
invoiceExternalId,
|
||||
status: "active",
|
||||
receivedAt: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
clearTenantSubscriptionCache(tenantId);
|
||||
invalidateTenantModuleAccessCache(tenantId);
|
||||
}
|
||||
|
||||
export async function createSelfServiceCheckout(
|
||||
input: CreateSelfServiceCheckoutInput,
|
||||
deps: SelfServiceCheckoutDeps = {}
|
||||
): Promise<{ sessionId: string; checkoutUrl: string; providerPaymentId: string }> {
|
||||
const [lagoGateway, mollieGateway] = [getLagoGateway(deps), getMollieGateway(deps)];
|
||||
if (!lagoGateway || !mollieGateway) {
|
||||
throw new SelfServiceCheckoutError("PROVIDER_CONFIGURATION_MISSING");
|
||||
}
|
||||
|
||||
const product = await getSubscriptionProduct(input.productId);
|
||||
if (!product) throw new SelfServiceCheckoutError("PLAN_NOT_FOUND");
|
||||
if (!product.active || !product.public) throw new SelfServiceCheckoutError("PLAN_NOT_PURCHASABLE");
|
||||
const productId = requireRecordId(product.id, "PLAN_NOT_FOUND");
|
||||
|
||||
const price = findCheckoutPrice(product, input.billingPeriod, input.currency);
|
||||
if (!price) throw new SelfServiceCheckoutError("PRICE_NOT_FOUND");
|
||||
const priceId = requireRecordId(price.id, "PRICE_NOT_FOUND");
|
||||
|
||||
const quantity = normalizeQuantity(input.quantity);
|
||||
const amountCents = centsForPrice(price, quantity);
|
||||
if (amountCents <= 0) throw new SelfServiceCheckoutError("CHECKOUT_NOT_PAYABLE");
|
||||
|
||||
const sessionId = `hgco_${randomUUID().replaceAll("-", "")}`;
|
||||
const planCode = resolvePlanCode({ id: productId, code: product.code, lagoPlanCode: product.lagoPlanCode });
|
||||
const lagoCustomer = await ensureLagoCustomer(lagoGateway, input, price.currency);
|
||||
const lagoSubscription: BillingGatewaySubscription = await lagoGateway.createSubscription({
|
||||
tenantId: input.tenantId,
|
||||
subscriptionExternalId: sessionId,
|
||||
planCode,
|
||||
seatQuantity: quantity,
|
||||
name: `${input.tenantName} · ${product.title}`,
|
||||
});
|
||||
const redirectUrl = buildRedirectUrl(input.tenantSlug, sessionId);
|
||||
const payment = await mollieGateway.createPayment({
|
||||
tenantId: input.tenantId,
|
||||
invoiceExternalId: sessionId,
|
||||
paymentExternalId: sessionId,
|
||||
amountCents,
|
||||
currency: price.currency.toUpperCase(),
|
||||
redirectUrl,
|
||||
webhookUrl: buildWebhookUrl(),
|
||||
lagoCustomerId: lagoCustomer.providerCustomerId,
|
||||
lagoSubscriptionId: lagoSubscription.externalId,
|
||||
planCode,
|
||||
seatQuantity: quantity,
|
||||
description: `${loadWebConfig().config.appName} ${product.title}`,
|
||||
});
|
||||
if (!payment.checkoutUrl) {
|
||||
throw new SelfServiceCheckoutError("CHECKOUT_URL_MISSING");
|
||||
}
|
||||
|
||||
await createCheckoutSessionStatus({
|
||||
id: sessionId,
|
||||
email: input.userEmail,
|
||||
fromUrl: new URL(input.request.url).pathname,
|
||||
fromUserId: input.userId,
|
||||
fromTenantId: input.tenantId,
|
||||
provider: "mollie",
|
||||
providerPaymentId: payment.providerPaymentId,
|
||||
invoiceExternalId: sessionId,
|
||||
subscriptionProductId: productId,
|
||||
subscriptionPriceId: priceId,
|
||||
lagoSubscriptionId: lagoSubscription.externalId,
|
||||
planCode,
|
||||
quantity,
|
||||
amountCents,
|
||||
currency: price.currency.toUpperCase(),
|
||||
checkoutUrl: payment.checkoutUrl,
|
||||
status: payment.status,
|
||||
});
|
||||
|
||||
return { sessionId, checkoutUrl: payment.checkoutUrl, providerPaymentId: payment.providerPaymentId };
|
||||
}
|
||||
|
||||
export async function completeSelfServiceCheckout(
|
||||
input: CompleteSelfServiceCheckoutInput,
|
||||
deps: SelfServiceCheckoutDeps = {}
|
||||
): Promise<SelfServiceCheckoutResponse | null> {
|
||||
const session = await getCheckoutSessionStatus(input.sessionId);
|
||||
if (!session || session.fromTenantId !== input.tenantId) {
|
||||
throw new SelfServiceCheckoutError("SESSION_NOT_FOUND");
|
||||
}
|
||||
if (!session.providerPaymentId) {
|
||||
throw new SelfServiceCheckoutError("PAYMENT_NOT_FOUND");
|
||||
}
|
||||
|
||||
const gateway = getMollieGateway(deps);
|
||||
if (!gateway) throw new SelfServiceCheckoutError("PROVIDER_CONFIGURATION_MISSING");
|
||||
|
||||
const payment = await gateway.getPayment(session.providerPaymentId);
|
||||
if (!payment) throw new SelfServiceCheckoutError("PAYMENT_NOT_FOUND");
|
||||
|
||||
await updateCheckoutSessionStatus(session.id, {
|
||||
pending: !isPaidPayment(payment),
|
||||
status: payment.status,
|
||||
providerPaymentId: payment.providerPaymentId,
|
||||
invoiceExternalId: payment.metadata.invoiceExternalId ?? session.invoiceExternalId,
|
||||
lagoSubscriptionId: payment.metadata.lagoSubscriptionId ?? session.lagoSubscriptionId,
|
||||
});
|
||||
|
||||
if (!isPaidPayment(payment)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
await syncPaidCheckoutSession(payment, session);
|
||||
|
||||
const product = session.subscriptionProductId ? await getSubscriptionProduct(session.subscriptionProductId) : null;
|
||||
const flatPrice = product?.prices.find((price) => price.id === session.subscriptionPriceId) ?? undefined;
|
||||
const responseFlatPrice: SubscriptionPrice | undefined =
|
||||
flatPrice && flatPrice.id
|
||||
? {
|
||||
...flatPrice,
|
||||
id: flatPrice.id,
|
||||
}
|
||||
: undefined;
|
||||
return {
|
||||
id: session.id,
|
||||
customer: {
|
||||
id: session.fromTenantId ?? input.tenantId,
|
||||
email: session.email,
|
||||
name: session.email,
|
||||
},
|
||||
products: product
|
||||
? [
|
||||
{
|
||||
id: requireRecordId(product.id, "PLAN_NOT_FOUND"),
|
||||
title: product.title,
|
||||
quantity: session.quantity,
|
||||
subscription: session.lagoSubscriptionId ?? undefined,
|
||||
prices: [{ flatPrice: responseFlatPrice, quantity: session.quantity }],
|
||||
},
|
||||
]
|
||||
: [],
|
||||
status: await getCheckoutSessionStatus(session.id),
|
||||
source: "self-service",
|
||||
};
|
||||
}
|
||||
+19
-33
@@ -26,11 +26,6 @@ function rootData(tenantApiKeys = true, admin = false, routingConfig?: typeof ro
|
||||
function appData(options?: { admin?: boolean; permissions?: string[]; tenantApiKeys?: boolean }) {
|
||||
return {
|
||||
currentTenant: { id: "tenant_1", slug: "acme" },
|
||||
entities: [
|
||||
{ name: "company", titlePlural: "models.company.plural", slug: "companies", showInSidebar: true },
|
||||
{ name: "contact", titlePlural: "models.contact.plural", slug: "contacts", showInSidebar: true },
|
||||
{ name: "opportunity", titlePlural: "models.opportunity.plural", slug: "opportunities", showInSidebar: true },
|
||||
],
|
||||
myTenants: [{ id: "tenant_2", slug: "other" }],
|
||||
permissions: options?.permissions ?? [
|
||||
"app.settings.members.view",
|
||||
@@ -38,9 +33,6 @@ function appData(options?: { admin?: boolean; permissions?: string[]; tenantApiK
|
||||
"app.settings.account.view",
|
||||
"app.settings.apiKeys.view",
|
||||
"app.settings.auditTrails.view",
|
||||
"entity.company.view",
|
||||
"entity.contact.view",
|
||||
"entity.opportunity.view",
|
||||
],
|
||||
isSuperAdmin: false,
|
||||
user: { id: "user_1", admin: options?.admin ?? true },
|
||||
@@ -104,24 +96,6 @@ describe("command registry", () => {
|
||||
expect(actions.some((action) => action.id === "events")).toBe(false);
|
||||
});
|
||||
|
||||
it("filters tenant entity commands through permission-aware scope metadata", () => {
|
||||
const actions = getCommandRegistryActions({
|
||||
layout: "app",
|
||||
t,
|
||||
navigate: navigateMock(),
|
||||
appData: appData({ permissions: ["entity.company.view"] }),
|
||||
rootData: rootData(),
|
||||
});
|
||||
|
||||
expect(actions.find((action) => action.id === "entity-company")?.scope).toMatchObject({
|
||||
layout: "app",
|
||||
tenantSlug: "acme",
|
||||
permission: "entity.company.view",
|
||||
});
|
||||
expect(actions.some((action) => action.id === "entity-contact")).toBe(false);
|
||||
expect(actions.some((action) => action.id === "entity-opportunity")).toBe(false);
|
||||
});
|
||||
|
||||
it("omits CRM command while the CRM route tree is disabled", () => {
|
||||
const disabled = getCommandRegistryActions({
|
||||
layout: "app",
|
||||
@@ -197,9 +171,15 @@ describe("command registry", () => {
|
||||
expect(actions.every((action) => action.scope.layout === "admin")).toBe(true);
|
||||
});
|
||||
|
||||
it("builds admin commands with host-aware paths and app fallback switch", () => {
|
||||
it("builds admin commands with host-aware paths and tenant selector switch", () => {
|
||||
const navigate = navigateMock();
|
||||
const actions = getCommandRegistryActions({ layout: "admin", t, navigate, rootData: rootData(true, true) });
|
||||
const actions = getCommandRegistryActions({
|
||||
layout: "admin",
|
||||
t,
|
||||
navigate,
|
||||
rootData: rootData(true, true),
|
||||
appData: { ...appData({ admin: true, permissions: ["admin.accounts.view"] }), currentTenant: null, isSuperAdmin: true } as any,
|
||||
});
|
||||
|
||||
perform(actions.find((action) => action.id === "/dashboard")!);
|
||||
perform(actions.find((action) => action.id === "/settings/profile")!);
|
||||
@@ -207,7 +187,7 @@ describe("command registry", () => {
|
||||
|
||||
expect(navigate).toHaveBeenNthCalledWith(1, "/dashboard");
|
||||
expect(navigate).toHaveBeenNthCalledWith(2, "/settings/profile");
|
||||
expect(navigate).toHaveBeenNthCalledWith(3, "/");
|
||||
expect(navigate).toHaveBeenNthCalledWith(3, "/select-tenant");
|
||||
expect(actions.find((action) => action.id === "/dashboard")?.scope).toMatchObject({ layout: "admin", platform: true, adminOnly: true });
|
||||
expect(actions.find((action) => action.name === "admin.switchToApp")?.scope).toMatchObject({ layout: "admin", platform: true, adminOnly: true });
|
||||
expectNoLegacyPrefixes(navigate.mock.calls.map(([target]) => target));
|
||||
@@ -269,11 +249,17 @@ describe("command registry", () => {
|
||||
expect(actions.find((action) => action.id === "/settings/profile")?.subtitle).toBe("Settings");
|
||||
});
|
||||
|
||||
it("builds admin public-app commands with absolute app-host URLs when routing is configured", () => {
|
||||
it("builds admin tenant selector commands and public-app create URLs when routing is configured", () => {
|
||||
const navigate = navigateMock();
|
||||
const actions = getCommandRegistryActions({ layout: "admin", t, navigate, rootData: rootData(true, true, routing) });
|
||||
const actions = getCommandRegistryActions({
|
||||
layout: "admin",
|
||||
t,
|
||||
navigate,
|
||||
rootData: rootData(true, true, routing),
|
||||
appData: { ...appData({ admin: true, permissions: ["admin.accounts.view"] }), currentTenant: null, isSuperAdmin: true } as any,
|
||||
});
|
||||
|
||||
expect(actions.find((action) => action.name === "admin.switchToApp")?.id).toBe("https://app.example.test/");
|
||||
expect(actions.find((action) => action.name === "admin.switchToApp")?.id).toBe("/select-tenant");
|
||||
|
||||
vi.stubGlobal("window", undefined);
|
||||
try {
|
||||
@@ -283,7 +269,7 @@ describe("command registry", () => {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
|
||||
expect(navigate).toHaveBeenNthCalledWith(1, "https://app.example.test/");
|
||||
expect(navigate).toHaveBeenNthCalledWith(1, "/select-tenant");
|
||||
expect(navigate).toHaveBeenNthCalledWith(2, "https://app.example.test/new-account");
|
||||
});
|
||||
|
||||
|
||||
+1
-14
@@ -10,7 +10,6 @@ import { getDocCommands } from "~/utils/services/docsService";
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { absoluteAdminPath, absoluteAppRootPath, isAbsoluteHttpUrl, type PublicDomainRoutingConfig } from "~/utils/app/CrossHostUrls";
|
||||
import { filterCommandActions } from "~/services/search/commandSearch";
|
||||
import { translateLabel } from "~/utils/i18n/translateLabel";
|
||||
|
||||
// Registry marker: services/command-registry paths are app-relative for package verification.
|
||||
export type CommandRegistryLayout = "app" | "admin" | "docs";
|
||||
@@ -70,7 +69,7 @@ function getUnfilteredCommandRegistryActions(context: CommandRegistryContext): S
|
||||
return getDocsCommandActions(context);
|
||||
}
|
||||
|
||||
function getAppCommandActions({ t, i18n, navigate, submitLogout, appData, rootData }: CommandRegistryContext): ScopedCommandAction[] {
|
||||
function getAppCommandActions({ t, navigate, submitLogout, appData, rootData }: CommandRegistryContext): ScopedCommandAction[] {
|
||||
if (!appData || !rootData) {
|
||||
return [];
|
||||
}
|
||||
@@ -89,18 +88,6 @@ function getAppCommandActions({ t, i18n, navigate, submitLogout, appData, rootDa
|
||||
},
|
||||
];
|
||||
|
||||
appData.entities
|
||||
.filter((entity) => entity.showInSidebar)
|
||||
.forEach((entity) => {
|
||||
const permission = typeof entity.name === "string" && entity.name.trim() ? `entity.${entity.name}.view` : undefined;
|
||||
actions.push({
|
||||
id: "entity-" + entity.name,
|
||||
name: translateLabel(t, i18n, entity.titlePlural),
|
||||
scope: tenantScope({ permission }),
|
||||
perform: () => navigate(tenantPath(entity.slug)),
|
||||
});
|
||||
});
|
||||
|
||||
actions.push({
|
||||
id: "profile",
|
||||
shortcut: [],
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import type { Params } from "react-router";
|
||||
import type { EntitlementDecision } from "@toolctrl/entitlements";
|
||||
import type { EntitlementDecision } from "@hivegrid/entitlements";
|
||||
import type {
|
||||
SubscriptionEntitlementSubscription,
|
||||
SubscriptionEntitlementTrialState,
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
DASHBOARD_CUSTOMIZE_PERMISSION,
|
||||
DASHBOARD_MODULE_KEY,
|
||||
DASHBOARD_READ_PERMISSION,
|
||||
getDashboardWidgetCatalog,
|
||||
getDefaultDashboardRoleLayouts,
|
||||
LEGACY_DASHBOARD_PERMISSION,
|
||||
} from "./dashboard.server";
|
||||
|
||||
describe("dashboard role layout contract", () => {
|
||||
it("defines the R-P11b dashboard module and permissions", () => {
|
||||
expect(DASHBOARD_MODULE_KEY).toBe("dashboard");
|
||||
expect(DASHBOARD_READ_PERMISSION).toBe("dashboard.read");
|
||||
expect(DASHBOARD_CUSTOMIZE_PERMISSION).toBe("dashboard.customize");
|
||||
expect(LEGACY_DASHBOARD_PERMISSION).toBe("app.dashboard.view");
|
||||
});
|
||||
|
||||
it("ships exactly the fixed v1 GF, office, and Monteur layouts", () => {
|
||||
const layouts = getDefaultDashboardRoleLayouts();
|
||||
|
||||
expect(layouts.map((layout) => layout.role)).toEqual(["gf", "office", "monteur"]);
|
||||
expect(layouts.find((layout) => layout.role === "monteur")?.mobileFirst).toBe(true);
|
||||
expect(layouts.find((layout) => layout.role === "gf")?.widgets.map((widget) => widget.key)).toEqual([
|
||||
"general.welcome",
|
||||
"sales.kpis",
|
||||
"sales.forecast",
|
||||
"projects.kpis",
|
||||
"hr.requests_pending",
|
||||
"projects.open_defects",
|
||||
"activity.recent",
|
||||
]);
|
||||
expect(layouts.find((layout) => layout.role === "office")?.widgets.map((widget) => widget.key)).toEqual([
|
||||
"general.welcome",
|
||||
"projects.kpis",
|
||||
"tasks.my_open",
|
||||
"comms.calls_today",
|
||||
"hr.requests_pending",
|
||||
"activity.recent",
|
||||
]);
|
||||
expect(layouts.find((layout) => layout.role === "monteur")?.widgets.map((widget) => widget.key)).toEqual([
|
||||
"schedule.my_today",
|
||||
"projects.my_active",
|
||||
"tasks.my_open",
|
||||
]);
|
||||
});
|
||||
|
||||
it("covers Sales, Projekte, Tasks, HR, Activity, and Comms in the widget catalog", () => {
|
||||
const catalog = getDashboardWidgetCatalog();
|
||||
const domains = new Set(catalog.map((widget) => widget.domain));
|
||||
const catalogKeys = new Set(catalog.map((widget) => widget.key));
|
||||
|
||||
expect(domains).toEqual(new Set(["general", "sales", "projects", "tasks", "hr", "activity", "comms", "schedule"]));
|
||||
for (const layout of getDefaultDashboardRoleLayouts()) {
|
||||
for (const widget of layout.widgets) {
|
||||
expect(catalogKeys.has(widget.key), `${layout.role}.${widget.key}`).toBe(true);
|
||||
}
|
||||
}
|
||||
expect(catalog.find((widget) => widget.key === "sales.kpis")?.requiredAnyPermission).toContain("projects.read_all");
|
||||
expect(catalog.find((widget) => widget.key === "tasks.my_open")?.requiredAnyPermission).toContain("tasks.read_own");
|
||||
});
|
||||
});
|
||||
+686
@@ -0,0 +1,686 @@
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { featureKeys } from "@hivegrid/entitlements";
|
||||
import type { Params } from "react-router";
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
|
||||
export const DASHBOARD_MODULE_KEY = featureKeys.dashboard;
|
||||
export const DASHBOARD_READ_PERMISSION = "dashboard.read";
|
||||
export const DASHBOARD_CUSTOMIZE_PERMISSION = "dashboard.customize";
|
||||
export const LEGACY_DASHBOARD_PERMISSION = "app.dashboard.view";
|
||||
|
||||
export type DashboardRoleKey = "gf" | "office" | "monteur";
|
||||
export type DashboardWidgetDomain = "general" | "sales" | "projects" | "tasks" | "hr" | "activity" | "comms" | "schedule";
|
||||
export type DashboardWidgetKind = "hero" | "kpi" | "list" | "trend";
|
||||
|
||||
export interface DashboardWidgetDefinition {
|
||||
readonly key: string;
|
||||
readonly domain: DashboardWidgetDomain;
|
||||
readonly kind: DashboardWidgetKind;
|
||||
readonly titleKey: string;
|
||||
readonly descriptionKey: string;
|
||||
readonly requiredAnyPermission: readonly string[];
|
||||
readonly defaultPeriod: "today" | "7d" | "30d" | "quarter";
|
||||
}
|
||||
|
||||
export interface DashboardRoleLayoutDefinition {
|
||||
readonly role: DashboardRoleKey;
|
||||
readonly nameKey: string;
|
||||
readonly descriptionKey: string;
|
||||
readonly mobileFirst: boolean;
|
||||
readonly widgets: readonly {
|
||||
readonly key: string;
|
||||
readonly position: { readonly x: number; readonly y: number };
|
||||
readonly size: { readonly w: number; readonly h: number };
|
||||
readonly config?: Record<string, string | number | boolean>;
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface DashboardContext {
|
||||
readonly tenantId: string;
|
||||
readonly tenantSlug: string;
|
||||
readonly userId: string;
|
||||
readonly permissions: readonly string[];
|
||||
readonly canCustomize: boolean;
|
||||
}
|
||||
|
||||
export interface DashboardMetric {
|
||||
readonly labelKey: string;
|
||||
readonly value: string;
|
||||
}
|
||||
|
||||
export interface DashboardWidgetVM {
|
||||
readonly key: string;
|
||||
readonly titleKey: string;
|
||||
readonly descriptionKey: string;
|
||||
readonly domain: DashboardWidgetDomain;
|
||||
readonly kind: DashboardWidgetKind;
|
||||
readonly period: DashboardWidgetDefinition["defaultPeriod"];
|
||||
readonly visible: boolean;
|
||||
readonly loadingMode: "lazy";
|
||||
readonly metrics: readonly DashboardMetric[];
|
||||
readonly items: readonly { readonly id: string; readonly label?: string; readonly labelKey?: string; readonly href?: string; readonly meta?: string }[];
|
||||
readonly position: { readonly x: number; readonly y: number };
|
||||
readonly size: { readonly w: number; readonly h: number };
|
||||
}
|
||||
|
||||
export interface DashboardRoleVM {
|
||||
readonly role: DashboardRoleKey;
|
||||
readonly nameKey: string;
|
||||
readonly descriptionKey: string;
|
||||
readonly mobileFirst: boolean;
|
||||
readonly isDefault: boolean;
|
||||
readonly widgets: readonly DashboardWidgetVM[];
|
||||
}
|
||||
|
||||
export interface DashboardVM {
|
||||
readonly activeRole: DashboardRoleKey;
|
||||
readonly roles: readonly DashboardRoleVM[];
|
||||
readonly generatedAt: string;
|
||||
readonly streamUrl: string;
|
||||
readonly liveUpdatesEnabled: boolean;
|
||||
readonly canCustomize: boolean;
|
||||
}
|
||||
|
||||
type DashboardSourceSnapshot = {
|
||||
readonly generatedAt: string;
|
||||
readonly sales: {
|
||||
readonly openProjects: number;
|
||||
readonly wonProjects: number;
|
||||
readonly forecastValue: number;
|
||||
};
|
||||
readonly projects: {
|
||||
readonly activeProjects: number;
|
||||
readonly dueSoon: number;
|
||||
readonly openDefects: number;
|
||||
readonly myProjects: readonly { id: string; label?: string; labelKey?: string; href: string; meta?: string }[];
|
||||
};
|
||||
readonly tasks: {
|
||||
readonly myOpen: number;
|
||||
readonly dueToday: number;
|
||||
readonly items: readonly { id: string; label?: string; labelKey?: string; href: string; meta?: string }[];
|
||||
};
|
||||
readonly hr: {
|
||||
readonly pendingRequests: number;
|
||||
};
|
||||
readonly activity: {
|
||||
readonly items: readonly { id: string; label?: string; labelKey?: string; href?: string; meta?: string }[];
|
||||
};
|
||||
readonly comms: {
|
||||
readonly callsToday: number;
|
||||
};
|
||||
readonly schedule: {
|
||||
readonly today: readonly { id: string; label?: string; labelKey?: string; href?: string; meta?: string }[];
|
||||
};
|
||||
};
|
||||
|
||||
const widgetCatalog = Object.freeze([
|
||||
{
|
||||
key: "general.welcome",
|
||||
domain: "general",
|
||||
kind: "hero",
|
||||
titleKey: "app.dashboard.widgets.welcome.title",
|
||||
descriptionKey: "app.dashboard.widgets.welcome.description",
|
||||
requiredAnyPermission: [DASHBOARD_READ_PERMISSION, LEGACY_DASHBOARD_PERMISSION],
|
||||
defaultPeriod: "today",
|
||||
},
|
||||
{
|
||||
key: "sales.kpis",
|
||||
domain: "sales",
|
||||
kind: "kpi",
|
||||
titleKey: "app.dashboard.widgets.salesKpis.title",
|
||||
descriptionKey: "app.dashboard.widgets.salesKpis.description",
|
||||
requiredAnyPermission: ["projects.read_all", "deals.read_aggregates"],
|
||||
defaultPeriod: "30d",
|
||||
},
|
||||
{
|
||||
key: "sales.forecast",
|
||||
domain: "sales",
|
||||
kind: "trend",
|
||||
titleKey: "app.dashboard.widgets.salesForecast.title",
|
||||
descriptionKey: "app.dashboard.widgets.salesForecast.description",
|
||||
requiredAnyPermission: ["deals.read_aggregates", "deals.read_volume_all"],
|
||||
defaultPeriod: "quarter",
|
||||
},
|
||||
{
|
||||
key: "projects.kpis",
|
||||
domain: "projects",
|
||||
kind: "kpi",
|
||||
titleKey: "app.dashboard.widgets.projectKpis.title",
|
||||
descriptionKey: "app.dashboard.widgets.projectKpis.description",
|
||||
requiredAnyPermission: ["projects.read_all", "projects.read_own", "projects.read_own_member", "projects.read_own_pl"],
|
||||
defaultPeriod: "30d",
|
||||
},
|
||||
{
|
||||
key: "projects.open_defects",
|
||||
domain: "projects",
|
||||
kind: "kpi",
|
||||
titleKey: "app.dashboard.widgets.openDefects.title",
|
||||
descriptionKey: "app.dashboard.widgets.openDefects.description",
|
||||
requiredAnyPermission: ["acceptance.read", "acceptance.admin"],
|
||||
defaultPeriod: "30d",
|
||||
},
|
||||
{
|
||||
key: "projects.my_active",
|
||||
domain: "projects",
|
||||
kind: "list",
|
||||
titleKey: "app.dashboard.widgets.myProjects.title",
|
||||
descriptionKey: "app.dashboard.widgets.myProjects.description",
|
||||
requiredAnyPermission: ["projects.read_all", "projects.read_own", "projects.read_own_member", "projects.read_own_pl"],
|
||||
defaultPeriod: "today",
|
||||
},
|
||||
{
|
||||
key: "tasks.my_open",
|
||||
domain: "tasks",
|
||||
kind: "list",
|
||||
titleKey: "app.dashboard.widgets.myTasks.title",
|
||||
descriptionKey: "app.dashboard.widgets.myTasks.description",
|
||||
requiredAnyPermission: ["tasks.read_all", "tasks.read_own"],
|
||||
defaultPeriod: "today",
|
||||
},
|
||||
{
|
||||
key: "hr.requests_pending",
|
||||
domain: "hr",
|
||||
kind: "kpi",
|
||||
titleKey: "app.dashboard.widgets.hrRequests.title",
|
||||
descriptionKey: "app.dashboard.widgets.hrRequests.description",
|
||||
requiredAnyPermission: ["hr.read_all", "hr.write", "hr.admin", "hr.leave.approve"],
|
||||
defaultPeriod: "30d",
|
||||
},
|
||||
{
|
||||
key: "activity.recent",
|
||||
domain: "activity",
|
||||
kind: "list",
|
||||
titleKey: "app.dashboard.widgets.activity.title",
|
||||
descriptionKey: "app.dashboard.widgets.activity.description",
|
||||
requiredAnyPermission: [DASHBOARD_READ_PERMISSION, LEGACY_DASHBOARD_PERMISSION],
|
||||
defaultPeriod: "7d",
|
||||
},
|
||||
{
|
||||
key: "comms.calls_today",
|
||||
domain: "comms",
|
||||
kind: "kpi",
|
||||
titleKey: "app.dashboard.widgets.callsToday.title",
|
||||
descriptionKey: "app.dashboard.widgets.callsToday.description",
|
||||
requiredAnyPermission: [DASHBOARD_READ_PERMISSION, LEGACY_DASHBOARD_PERMISSION],
|
||||
defaultPeriod: "today",
|
||||
},
|
||||
{
|
||||
key: "schedule.my_today",
|
||||
domain: "schedule",
|
||||
kind: "list",
|
||||
titleKey: "app.dashboard.widgets.scheduleToday.title",
|
||||
descriptionKey: "app.dashboard.widgets.scheduleToday.description",
|
||||
requiredAnyPermission: ["calendar.connect_own", "bookings.read_own", "plantafel.read_own", "plantafel.read_all"],
|
||||
defaultPeriod: "today",
|
||||
},
|
||||
] as const satisfies readonly DashboardWidgetDefinition[]);
|
||||
|
||||
const roleLayouts = Object.freeze([
|
||||
{
|
||||
role: "gf",
|
||||
nameKey: "app.dashboard.roles.gf.name",
|
||||
descriptionKey: "app.dashboard.roles.gf.description",
|
||||
mobileFirst: false,
|
||||
widgets: [
|
||||
{ key: "general.welcome", position: { x: 0, y: 0 }, size: { w: 12, h: 1 } },
|
||||
{ key: "sales.kpis", position: { x: 0, y: 1 }, size: { w: 4, h: 2 } },
|
||||
{ key: "sales.forecast", position: { x: 4, y: 1 }, size: { w: 4, h: 2 } },
|
||||
{ key: "projects.kpis", position: { x: 8, y: 1 }, size: { w: 4, h: 2 } },
|
||||
{ key: "hr.requests_pending", position: { x: 0, y: 3 }, size: { w: 4, h: 2 } },
|
||||
{ key: "projects.open_defects", position: { x: 4, y: 3 }, size: { w: 4, h: 2 } },
|
||||
{ key: "activity.recent", position: { x: 8, y: 3 }, size: { w: 4, h: 2 } },
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "office",
|
||||
nameKey: "app.dashboard.roles.office.name",
|
||||
descriptionKey: "app.dashboard.roles.office.description",
|
||||
mobileFirst: false,
|
||||
widgets: [
|
||||
{ key: "general.welcome", position: { x: 0, y: 0 }, size: { w: 12, h: 1 } },
|
||||
{ key: "projects.kpis", position: { x: 0, y: 1 }, size: { w: 4, h: 2 } },
|
||||
{ key: "tasks.my_open", position: { x: 4, y: 1 }, size: { w: 4, h: 2 } },
|
||||
{ key: "comms.calls_today", position: { x: 8, y: 1 }, size: { w: 4, h: 2 } },
|
||||
{ key: "hr.requests_pending", position: { x: 0, y: 3 }, size: { w: 6, h: 2 } },
|
||||
{ key: "activity.recent", position: { x: 6, y: 3 }, size: { w: 6, h: 2 } },
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "monteur",
|
||||
nameKey: "app.dashboard.roles.monteur.name",
|
||||
descriptionKey: "app.dashboard.roles.monteur.description",
|
||||
mobileFirst: true,
|
||||
widgets: [
|
||||
{ key: "schedule.my_today", position: { x: 0, y: 0 }, size: { w: 12, h: 2 } },
|
||||
{ key: "projects.my_active", position: { x: 0, y: 2 }, size: { w: 12, h: 2 } },
|
||||
{ key: "tasks.my_open", position: { x: 0, y: 4 }, size: { w: 12, h: 2 } },
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly DashboardRoleLayoutDefinition[]);
|
||||
|
||||
const widgetByKey = new Map(widgetCatalog.map((widget) => [widget.key, widget]));
|
||||
|
||||
export function getDashboardWidgetCatalog(): readonly DashboardWidgetDefinition[] {
|
||||
return widgetCatalog;
|
||||
}
|
||||
|
||||
export function getDefaultDashboardRoleLayouts(): readonly DashboardRoleLayoutDefinition[] {
|
||||
return roleLayouts;
|
||||
}
|
||||
|
||||
function hasAnyPermission(permissions: readonly string[], requiredAnyPermission: readonly string[]): boolean {
|
||||
return requiredAnyPermission.some((permission) => permissions.includes(permission));
|
||||
}
|
||||
|
||||
function widgetConfig(widget: DashboardRoleLayoutDefinition["widgets"][number]): Record<string, string | number | boolean> {
|
||||
return "config" in widget && widget.config ? widget.config : {};
|
||||
}
|
||||
|
||||
function assertDashboardRead(permissions: readonly string[]): void {
|
||||
if (!hasAnyPermission(permissions, [DASHBOARD_READ_PERMISSION, LEGACY_DASHBOARD_PERMISSION])) {
|
||||
throw new CatalogError(foundationErrors.notFound, { permission: DASHBOARD_READ_PERMISSION });
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadDashboardContext({ request, params }: { request: Request; params: Params }): Promise<DashboardContext> {
|
||||
await requireAuth({ request, params });
|
||||
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
|
||||
if (!tenantId || !userInfo.userId) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
const [hasModule, permissions] = await Promise.all([
|
||||
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: DASHBOARD_MODULE_KEY }),
|
||||
getPermissionsByUser(userInfo.userId, tenantId),
|
||||
]);
|
||||
if (!hasModule) {
|
||||
throw new CatalogError(foundationErrors.notFound, { module: DASHBOARD_MODULE_KEY });
|
||||
}
|
||||
assertDashboardRead(permissions);
|
||||
return {
|
||||
tenantId,
|
||||
tenantSlug: params.tenant ?? tenantId,
|
||||
userId: userInfo.userId,
|
||||
permissions,
|
||||
canCustomize: permissions.includes(DASHBOARD_CUSTOMIZE_PERMISSION),
|
||||
};
|
||||
}
|
||||
|
||||
export async function ensureDefaultDashboards(ctx: Pick<DashboardContext, "tenantId">): Promise<void> {
|
||||
await withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
for (const layout of roleLayouts) {
|
||||
const dashboard = await tx.dashboard.upsert({
|
||||
where: { tenantId_role_name: { tenantId: ctx.tenantId, role: layout.role, name: layout.nameKey } },
|
||||
update: {
|
||||
description: layout.descriptionKey,
|
||||
isDefaultForRole: true,
|
||||
isShared: true,
|
||||
archivedAt: null,
|
||||
},
|
||||
create: {
|
||||
tenantId: ctx.tenantId,
|
||||
role: layout.role,
|
||||
name: layout.nameKey,
|
||||
description: layout.descriptionKey,
|
||||
isDefaultForRole: true,
|
||||
isShared: true,
|
||||
},
|
||||
});
|
||||
const layoutRow = await tx.dashboardLayout.findFirst({
|
||||
where: { tenantId: ctx.tenantId, dashboardId: dashboard.id, userId: null, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
const layoutData = { role: layout.role, columns: 12, mobileFirst: layout.mobileFirst };
|
||||
const widgets = layout.widgets.map((widget) => ({ key: widget.key, position: widget.position, size: widget.size, config: widgetConfig(widget) }));
|
||||
if (layoutRow) {
|
||||
await tx.dashboardLayout.update({
|
||||
where: { id: layoutRow.id },
|
||||
data: { widgets, layoutData, archivedAt: null },
|
||||
});
|
||||
} else {
|
||||
await tx.dashboardLayout.create({
|
||||
data: { tenantId: ctx.tenantId, dashboardId: dashboard.id, userId: null, widgets, layoutData },
|
||||
});
|
||||
}
|
||||
const existingInstances = await tx.widgetInstance.findMany({
|
||||
where: { tenantId: ctx.tenantId, dashboardId: dashboard.id, archivedAt: null },
|
||||
select: { id: true, widgetCatalogKey: true },
|
||||
});
|
||||
const instanceByKey = new Map(existingInstances.map((instance) => [instance.widgetCatalogKey, instance.id]));
|
||||
for (const widget of layout.widgets) {
|
||||
const existingId = instanceByKey.get(widget.key);
|
||||
const data = {
|
||||
config: widgetConfig(widget),
|
||||
position: widget.position,
|
||||
size: widget.size,
|
||||
archivedAt: null,
|
||||
};
|
||||
if (existingId) {
|
||||
await tx.widgetInstance.update({ where: { id: existingId }, data });
|
||||
} else {
|
||||
await tx.widgetInstance.create({
|
||||
data: {
|
||||
tenantId: ctx.tenantId,
|
||||
dashboardId: dashboard.id,
|
||||
widgetCatalogKey: widget.key,
|
||||
...data,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadDashboardVM({ request, params }: { request: Request; params: Params }): Promise<DashboardVM> {
|
||||
const ctx = await loadDashboardContext({ request, params });
|
||||
await ensureDefaultDashboards(ctx);
|
||||
const snapshot = await loadDashboardSourceSnapshot(ctx);
|
||||
const requestedRole = new URL(request.url).searchParams.get("role");
|
||||
const activeRole = isDashboardRole(requestedRole) ? requestedRole : defaultRoleForPermissions(ctx.permissions);
|
||||
return buildDashboardVM({ ctx, snapshot, activeRole });
|
||||
}
|
||||
|
||||
export async function loadDashboardStreamSnapshot({ request, params }: { request: Request; params: Params }): Promise<DashboardVM> {
|
||||
const ctx = await loadDashboardContext({ request, params });
|
||||
const requestedRole = new URL(request.url).searchParams.get("role");
|
||||
const activeRole = isDashboardRole(requestedRole) ? requestedRole : defaultRoleForPermissions(ctx.permissions);
|
||||
const snapshot = await loadDashboardSourceSnapshot(ctx);
|
||||
return buildDashboardVM({ ctx, snapshot, activeRole });
|
||||
}
|
||||
|
||||
function buildDashboardVM({ ctx, snapshot, activeRole }: { ctx: DashboardContext; snapshot: DashboardSourceSnapshot; activeRole: DashboardRoleKey }): DashboardVM {
|
||||
return {
|
||||
activeRole,
|
||||
generatedAt: snapshot.generatedAt,
|
||||
streamUrl: appPath({ tenantSlug: ctx.tenantSlug, path: `dashboard/stream?role=${activeRole}`, mode: "host-aware" }),
|
||||
liveUpdatesEnabled: true,
|
||||
canCustomize: ctx.canCustomize,
|
||||
roles: roleLayouts.map((layout) => ({
|
||||
role: layout.role,
|
||||
nameKey: layout.nameKey,
|
||||
descriptionKey: layout.descriptionKey,
|
||||
mobileFirst: layout.mobileFirst,
|
||||
isDefault: layout.role === activeRole,
|
||||
widgets: layout.widgets.map((widgetLayout) => {
|
||||
const widget = widgetByKey.get(widgetLayout.key);
|
||||
if (!widget) {
|
||||
throw new Error(`Unknown dashboard widget key: ${widgetLayout.key}`);
|
||||
}
|
||||
const visible = hasAnyPermission(ctx.permissions, widget.requiredAnyPermission);
|
||||
return {
|
||||
key: widget.key,
|
||||
titleKey: widget.titleKey,
|
||||
descriptionKey: widget.descriptionKey,
|
||||
domain: widget.domain,
|
||||
kind: widget.kind,
|
||||
period: widget.defaultPeriod,
|
||||
visible,
|
||||
loadingMode: "lazy",
|
||||
position: widgetLayout.position,
|
||||
size: widgetLayout.size,
|
||||
...(visible ? widgetData(widget.key, snapshot) : { metrics: [], items: [] }),
|
||||
};
|
||||
}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
async function loadDashboardSourceSnapshot(ctx: DashboardContext): Promise<DashboardSourceSnapshot> {
|
||||
const now = new Date();
|
||||
const todayStart = new Date(now);
|
||||
todayStart.setHours(0, 0, 0, 0);
|
||||
const todayEnd = new Date(todayStart);
|
||||
todayEnd.setDate(todayEnd.getDate() + 1);
|
||||
const dueSoon = new Date(now);
|
||||
dueSoon.setDate(dueSoon.getDate() + 14);
|
||||
const generatedAt = now.toISOString();
|
||||
|
||||
return withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
const canReadAllProjects = ctx.permissions.includes("projects.read_all");
|
||||
const canReadProjects = hasAnyPermission(ctx.permissions, ["projects.read_all", "projects.read_own", "projects.read_own_member", "projects.read_own_pl"]);
|
||||
const canReadTasks = hasAnyPermission(ctx.permissions, ["tasks.read_all", "tasks.read_own"]);
|
||||
const canReadHr = hasAnyPermission(ctx.permissions, ["hr.read_all", "hr.write", "hr.admin", "hr.leave.approve"]);
|
||||
const canReadSchedule = hasAnyPermission(ctx.permissions, ["calendar.connect_own", "bookings.read_own", "plantafel.read_own", "plantafel.read_all"]);
|
||||
const canReadDefects = hasAnyPermission(ctx.permissions, ["acceptance.read", "acceptance.admin"]);
|
||||
const projectOwnerWhere = canReadAllProjects
|
||||
? {}
|
||||
: { OR: [{ zustaendigePersonId: ctx.userId }, { projektleiterId: ctx.userId }, { createdByUserId: ctx.userId }] };
|
||||
const projectWhere = { tenantId: ctx.tenantId, archivedAt: null, ...projectOwnerWhere };
|
||||
|
||||
const [
|
||||
openProjects,
|
||||
wonProjects,
|
||||
forecastSnapshots,
|
||||
activeProjects,
|
||||
dueSoonProjects,
|
||||
myProjects,
|
||||
myOpenTasks,
|
||||
dueTodayTasks,
|
||||
taskItems,
|
||||
pendingHrRequests,
|
||||
openDefects,
|
||||
recentActivity,
|
||||
callsToday,
|
||||
calendarEvents,
|
||||
appointments,
|
||||
] = await Promise.all([
|
||||
canReadProjects ? tx.projekt.count({ where: projectWhere }) : Promise.resolve(0),
|
||||
canReadProjects ? tx.projekt.count({ where: { ...projectWhere, wonAt: { not: null } } }) : Promise.resolve(0),
|
||||
hasAnyPermission(ctx.permissions, ["deals.read_aggregates", "deals.read_volume_all"])
|
||||
? tx.pipelineAggregateSnapshot.findMany({
|
||||
where: { tenantId: ctx.tenantId, scopeKey: "pipeline" },
|
||||
orderBy: { calculatedAt: "desc" },
|
||||
take: 12,
|
||||
select: { weightedForecast: true },
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
canReadProjects ? tx.projekt.count({ where: projectWhere }) : Promise.resolve(0),
|
||||
canReadProjects ? tx.projekt.count({ where: { ...projectWhere, deadline: { gte: todayStart, lt: dueSoon } } }) : Promise.resolve(0),
|
||||
canReadProjects
|
||||
? tx.projekt.findMany({
|
||||
where: projectWhere,
|
||||
orderBy: { updatedAt: "desc" },
|
||||
take: 4,
|
||||
select: { id: true, projektname: true, projektNummer: true, deadline: true },
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
canReadTasks
|
||||
? tx.task.count({
|
||||
where: { tenantId: ctx.tenantId, archivedAt: null, status: { notIn: ["done", "cancelled"] }, OR: [{ assignedToUserId: ctx.userId }, { createdByUserId: ctx.userId }] },
|
||||
})
|
||||
: Promise.resolve(0),
|
||||
canReadTasks
|
||||
? tx.task.count({
|
||||
where: {
|
||||
tenantId: ctx.tenantId,
|
||||
archivedAt: null,
|
||||
status: { notIn: ["done", "cancelled"] },
|
||||
deadline: { gte: todayStart, lt: todayEnd },
|
||||
OR: [{ assignedToUserId: ctx.userId }, { createdByUserId: ctx.userId }],
|
||||
},
|
||||
})
|
||||
: Promise.resolve(0),
|
||||
canReadTasks
|
||||
? tx.task.findMany({
|
||||
where: { tenantId: ctx.tenantId, archivedAt: null, status: { notIn: ["done", "cancelled"] }, OR: [{ assignedToUserId: ctx.userId }, { createdByUserId: ctx.userId }] },
|
||||
orderBy: [{ deadline: "asc" }, { updatedAt: "desc" }],
|
||||
take: 4,
|
||||
select: { id: true, title: true, deadline: true, status: true },
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
canReadHr
|
||||
? tx.hrRequest.count({ where: { tenantId: ctx.tenantId, archivedAt: null, status: { in: ["submitted", "clarification"] } } })
|
||||
: Promise.resolve(0),
|
||||
canReadDefects
|
||||
? tx.projektChecklistItem.count({
|
||||
where: {
|
||||
tenantId: ctx.tenantId,
|
||||
status: "offen",
|
||||
checklist: {
|
||||
tenantId: ctx.tenantId,
|
||||
typ: "maengel",
|
||||
archivedAt: null,
|
||||
},
|
||||
},
|
||||
})
|
||||
: Promise.resolve(0),
|
||||
tx.activity.findMany({
|
||||
where: { tenantId: ctx.tenantId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 5,
|
||||
select: { id: true, summaryText: true, subjectType: true, subjectId: true, createdAt: true },
|
||||
}),
|
||||
tx.activity.count({
|
||||
where: { tenantId: ctx.tenantId, activityType: { in: ["call", "phone_call", "comms.call"] }, createdAt: { gte: todayStart, lt: todayEnd } },
|
||||
}),
|
||||
canReadSchedule
|
||||
? tx.calendarEvent.findMany({
|
||||
where: { tenantId: ctx.tenantId, userId: ctx.userId, archivedAt: null, startsAt: { gte: todayStart, lt: todayEnd } },
|
||||
orderBy: { startsAt: "asc" },
|
||||
take: 5,
|
||||
select: { id: true, title: true, startsAt: true, endsAt: true },
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
canReadSchedule
|
||||
? tx.appointment.findMany({
|
||||
where: { tenantId: ctx.tenantId, providerUserId: ctx.userId, status: "scheduled", startAt: { gte: todayStart, lt: todayEnd } },
|
||||
orderBy: { startAt: "asc" },
|
||||
take: 5,
|
||||
select: { id: true, startAt: true, endAt: true, notesInternal: true },
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
]);
|
||||
|
||||
const forecastValue = forecastSnapshots.reduce((sum, snapshot) => sum + numeric(snapshot.weightedForecast), 0);
|
||||
return {
|
||||
generatedAt,
|
||||
sales: { openProjects, wonProjects, forecastValue },
|
||||
projects: {
|
||||
activeProjects,
|
||||
dueSoon: dueSoonProjects,
|
||||
openDefects,
|
||||
myProjects: myProjects.map((project) => ({
|
||||
id: project.id,
|
||||
label: project.projektname,
|
||||
href: appPath({ tenantSlug: ctx.tenantSlug, path: `projects/${project.id}`, mode: "host-aware" }),
|
||||
meta: project.projektNummer || formatDate(project.deadline),
|
||||
})),
|
||||
},
|
||||
tasks: {
|
||||
myOpen: myOpenTasks,
|
||||
dueToday: dueTodayTasks,
|
||||
items: taskItems.map((task) => ({
|
||||
id: task.id,
|
||||
label: task.title,
|
||||
href: appPath({ tenantSlug: ctx.tenantSlug, path: `tasks`, mode: "host-aware" }),
|
||||
meta: task.deadline ? formatDate(task.deadline) : task.status,
|
||||
})),
|
||||
},
|
||||
hr: { pendingRequests: pendingHrRequests },
|
||||
activity: {
|
||||
items: recentActivity.map((activity) => ({
|
||||
id: activity.id,
|
||||
label: activity.summaryText,
|
||||
meta: `${activity.subjectType}:${activity.subjectId}`,
|
||||
})),
|
||||
},
|
||||
comms: { callsToday },
|
||||
schedule: {
|
||||
today: [
|
||||
...calendarEvents.map((event) => ({
|
||||
id: event.id,
|
||||
...(event.title ? { label: event.title } : { labelKey: "app.dashboard.schedule.untitled" }),
|
||||
meta: formatTimeRange(event.startsAt, event.endsAt),
|
||||
})),
|
||||
...appointments.map((appointment) => ({
|
||||
id: appointment.id,
|
||||
...(appointment.notesInternal ? { label: appointment.notesInternal } : { labelKey: "app.dashboard.schedule.appointment" }),
|
||||
meta: formatTimeRange(appointment.startAt, appointment.endAt),
|
||||
})),
|
||||
],
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function widgetData(key: string, snapshot: DashboardSourceSnapshot): Pick<DashboardWidgetVM, "metrics" | "items"> {
|
||||
switch (key) {
|
||||
case "general.welcome":
|
||||
return { metrics: [{ labelKey: "app.dashboard.metrics.lastUpdated", value: snapshot.generatedAt }], items: [] };
|
||||
case "sales.kpis":
|
||||
return {
|
||||
metrics: [
|
||||
{ labelKey: "app.dashboard.metrics.openProjects", value: String(snapshot.sales.openProjects) },
|
||||
{ labelKey: "app.dashboard.metrics.wonProjects", value: String(snapshot.sales.wonProjects) },
|
||||
],
|
||||
items: [],
|
||||
};
|
||||
case "sales.forecast":
|
||||
return { metrics: [{ labelKey: "app.dashboard.metrics.forecast", value: currency(snapshot.sales.forecastValue) }], items: [] };
|
||||
case "projects.kpis":
|
||||
return {
|
||||
metrics: [
|
||||
{ labelKey: "app.dashboard.metrics.activeProjects", value: String(snapshot.projects.activeProjects) },
|
||||
{ labelKey: "app.dashboard.metrics.dueSoon", value: String(snapshot.projects.dueSoon) },
|
||||
],
|
||||
items: [],
|
||||
};
|
||||
case "projects.open_defects":
|
||||
return { metrics: [{ labelKey: "app.dashboard.metrics.openDefects", value: String(snapshot.projects.openDefects) }], items: [] };
|
||||
case "projects.my_active":
|
||||
return { metrics: [], items: snapshot.projects.myProjects };
|
||||
case "tasks.my_open":
|
||||
return {
|
||||
metrics: [
|
||||
{ labelKey: "app.dashboard.metrics.myOpenTasks", value: String(snapshot.tasks.myOpen) },
|
||||
{ labelKey: "app.dashboard.metrics.dueToday", value: String(snapshot.tasks.dueToday) },
|
||||
],
|
||||
items: snapshot.tasks.items,
|
||||
};
|
||||
case "hr.requests_pending":
|
||||
return { metrics: [{ labelKey: "app.dashboard.metrics.pendingHrRequests", value: String(snapshot.hr.pendingRequests) }], items: [] };
|
||||
case "activity.recent":
|
||||
return { metrics: [], items: snapshot.activity.items };
|
||||
case "comms.calls_today":
|
||||
return { metrics: [{ labelKey: "app.dashboard.metrics.callsToday", value: String(snapshot.comms.callsToday) }], items: [] };
|
||||
case "schedule.my_today":
|
||||
return { metrics: [], items: snapshot.schedule.today };
|
||||
default:
|
||||
return { metrics: [], items: [] };
|
||||
}
|
||||
}
|
||||
|
||||
function isDashboardRole(value: string | null): value is DashboardRoleKey {
|
||||
return value === "gf" || value === "office" || value === "monteur";
|
||||
}
|
||||
|
||||
function defaultRoleForPermissions(permissions: readonly string[]): DashboardRoleKey {
|
||||
if (permissions.includes("projects.read_all") || permissions.includes("deals.read_aggregates")) return "gf";
|
||||
if (permissions.includes("plantafel.read_own") || permissions.includes("calendar.connect_own")) return "monteur";
|
||||
return "office";
|
||||
}
|
||||
|
||||
function numeric(value: unknown): number {
|
||||
if (typeof value === "number") return value;
|
||||
if (typeof value === "string") return Number(value) || 0;
|
||||
if (value && typeof value === "object" && "toString" in value) return Number(value.toString()) || 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
function currency(value: number): string {
|
||||
return new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR", maximumFractionDigits: 0 }).format(value);
|
||||
}
|
||||
|
||||
function formatDate(value: Date | null | undefined): string | undefined {
|
||||
return value ? value.toISOString().slice(0, 10) : undefined;
|
||||
}
|
||||
|
||||
function formatTimeRange(start: Date, end: Date): string {
|
||||
return `${start.toISOString().slice(11, 16)}-${end.toISOString().slice(11, 16)}`;
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
import { redirect } from "react-router";
|
||||
import {
|
||||
consumeMcpOAuthAuthorizationCode,
|
||||
consumeMcpOAuthRefreshToken,
|
||||
createMcpOAuthAuthorizationCode,
|
||||
findMcpOAuthClient,
|
||||
issueMcpOAuthTokenPair,
|
||||
registerMcpOAuthClient,
|
||||
revokeMcpOAuthToken,
|
||||
verifyMcpOAuthPkceS256,
|
||||
type McpOAuthClientSummary,
|
||||
} from "@hivegrid/db/mcp-oauth.server";
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { getTenantByIdOrSlug, getTenantMembershipByIds, getTenantsForUser } from "@hivegrid/db/auth-boundary.server";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
|
||||
export const MCP_OAUTH_SUPPORTED_SCOPES = [
|
||||
"mcp:read",
|
||||
"mcp:write",
|
||||
"mcp:lead:read",
|
||||
"mcp:lead:create",
|
||||
"mcp:contact:read",
|
||||
"mcp:project:read",
|
||||
"mcp:project:write",
|
||||
"mcp:pipeline:read",
|
||||
"mcp:activity:write",
|
||||
] as const;
|
||||
|
||||
const DEFAULT_SCOPE = "mcp:read";
|
||||
const SUPPORTED_SCOPE_SET = new Set<string>(MCP_OAUTH_SUPPORTED_SCOPES);
|
||||
|
||||
export type McpOAuthAuthorizeRequest = {
|
||||
responseType: "code";
|
||||
client: McpOAuthClientSummary;
|
||||
redirectUri: string;
|
||||
scopes: string[];
|
||||
state?: string;
|
||||
codeChallenge: string;
|
||||
codeChallengeMethod: "S256";
|
||||
resource: string;
|
||||
tenant: { id: string; slug: string; name: string };
|
||||
};
|
||||
|
||||
export type McpOAuthPublicUrls = {
|
||||
issuer: string;
|
||||
resource: string;
|
||||
authorizationEndpoint: string;
|
||||
tokenEndpoint: string;
|
||||
registrationEndpoint: string;
|
||||
revocationEndpoint: string;
|
||||
};
|
||||
|
||||
export class McpOAuthError extends Error {
|
||||
readonly error: string;
|
||||
readonly status: number;
|
||||
readonly description: string;
|
||||
|
||||
constructor(error: string, description: string, status = 400) {
|
||||
super(description);
|
||||
this.name = "McpOAuthError";
|
||||
this.error = error;
|
||||
this.status = status;
|
||||
this.description = description;
|
||||
}
|
||||
}
|
||||
|
||||
export function getMcpOAuthPublicUrls(): McpOAuthPublicUrls {
|
||||
const routing = loadRequiredWebConfig().routing;
|
||||
const issuer = trimTrailingSlash(process.env.MCP_AUTHORIZATION_SERVER_URL) ?? `${routing.protocol}://${routing.webAppHost}`;
|
||||
const resource = trimTrailingSlash(process.env.MCP_RESOURCE_URL) ?? deriveMcpResourceOrigin(routing.protocol, routing.webAppHost, routing.appBaseDomain);
|
||||
return {
|
||||
issuer,
|
||||
resource,
|
||||
authorizationEndpoint: `${issuer}/oauth/authorize`,
|
||||
tokenEndpoint: `${issuer}/oauth/token`,
|
||||
registrationEndpoint: `${issuer}/oauth/register`,
|
||||
revocationEndpoint: `${issuer}/oauth/revoke`,
|
||||
};
|
||||
}
|
||||
|
||||
export function oauthAuthorizationServerMetadata() {
|
||||
const urls = getMcpOAuthPublicUrls();
|
||||
return {
|
||||
issuer: urls.issuer,
|
||||
authorization_endpoint: urls.authorizationEndpoint,
|
||||
token_endpoint: urls.tokenEndpoint,
|
||||
registration_endpoint: urls.registrationEndpoint,
|
||||
revocation_endpoint: urls.revocationEndpoint,
|
||||
response_types_supported: ["code"],
|
||||
grant_types_supported: ["authorization_code", "refresh_token"],
|
||||
code_challenge_methods_supported: ["S256"],
|
||||
token_endpoint_auth_methods_supported: ["none"],
|
||||
scopes_supported: MCP_OAUTH_SUPPORTED_SCOPES,
|
||||
resource_indicators_supported: true,
|
||||
};
|
||||
}
|
||||
|
||||
export async function resolveAuthorizeRequest(url: URL, userId: string): Promise<McpOAuthAuthorizeRequest> {
|
||||
if (url.searchParams.get("response_type") !== "code") {
|
||||
throw new McpOAuthError("unsupported_response_type", "MCP OAuth supports response_type=code only.");
|
||||
}
|
||||
|
||||
const clientId = requiredParam(url, "client_id");
|
||||
const redirectUri = requiredParam(url, "redirect_uri");
|
||||
const codeChallenge = requiredParam(url, "code_challenge");
|
||||
const codeChallengeMethod = requiredParam(url, "code_challenge_method");
|
||||
if (codeChallengeMethod !== "S256") {
|
||||
throw new McpOAuthError("invalid_request", "Only PKCE S256 is supported.");
|
||||
}
|
||||
|
||||
const client = await findMcpOAuthClient(clientId);
|
||||
if (!client?.active) {
|
||||
throw new McpOAuthError("invalid_client", "OAuth client is unknown or inactive.", 401);
|
||||
}
|
||||
if (!client.redirectUris.includes(redirectUri)) {
|
||||
throw new McpOAuthError("invalid_request", "redirect_uri is not registered for this client.");
|
||||
}
|
||||
|
||||
const scopes = parseScopes(url.searchParams.get("scope"));
|
||||
assertScopesSupported(scopes);
|
||||
assertScopesAllowedByClient(scopes, client);
|
||||
|
||||
const urls = getMcpOAuthPublicUrls();
|
||||
const resource = trimTrailingSlash(url.searchParams.get("resource")) ?? urls.resource;
|
||||
if (resource !== urls.resource) {
|
||||
throw new McpOAuthError("invalid_target", "resource must match the MCP resource.");
|
||||
}
|
||||
|
||||
const tenant = await resolveAuthorizeTenant(url.searchParams.get("tenant"), userId);
|
||||
return {
|
||||
responseType: "code",
|
||||
client,
|
||||
redirectUri,
|
||||
scopes,
|
||||
state: url.searchParams.get("state") ?? undefined,
|
||||
codeChallenge,
|
||||
codeChallengeMethod: "S256",
|
||||
resource,
|
||||
tenant,
|
||||
};
|
||||
}
|
||||
|
||||
export async function approveAuthorizeRequest(request: Request, userId: string): Promise<Response> {
|
||||
const form = await request.formData();
|
||||
const url = new URL("/oauth/authorize", request.url);
|
||||
for (const key of ["response_type", "client_id", "redirect_uri", "scope", "state", "code_challenge", "code_challenge_method", "resource", "tenant"]) {
|
||||
const value = form.get(key);
|
||||
if (typeof value === "string" && value.length > 0) {
|
||||
url.searchParams.set(key, value);
|
||||
}
|
||||
}
|
||||
const resolved = await resolveAuthorizeRequest(url, userId);
|
||||
if (form.get("decision") !== "approve") {
|
||||
throw redirect(withOAuthRedirectParams(resolved.redirectUri, { error: "access_denied", state: resolved.state }));
|
||||
}
|
||||
|
||||
const { code } = await createMcpOAuthAuthorizationCode({
|
||||
clientId: resolved.client.id,
|
||||
userId,
|
||||
tenantId: resolved.tenant.id,
|
||||
tenantSlug: resolved.tenant.slug,
|
||||
redirectUri: resolved.redirectUri,
|
||||
scopes: resolved.scopes,
|
||||
resource: resolved.resource,
|
||||
codeChallenge: resolved.codeChallenge,
|
||||
codeChallengeMethod: "S256",
|
||||
secret: getMcpOAuthTokenHashSecret(),
|
||||
});
|
||||
|
||||
throw redirect(withOAuthRedirectParams(resolved.redirectUri, { code, state: resolved.state }));
|
||||
}
|
||||
|
||||
export async function registerOAuthClientFromRequest(request: Request): Promise<Response> {
|
||||
const body = await readJson(request);
|
||||
const redirectUris = normalizeRedirectUris(body.redirect_uris);
|
||||
const scopes = parseScopes(typeof body.scope === "string" ? body.scope : undefined);
|
||||
assertScopesSupported(scopes);
|
||||
const grantTypes = normalizeGrantTypes(body.grant_types);
|
||||
const client = await registerMcpOAuthClient({
|
||||
clientName: typeof body.client_name === "string" && body.client_name.trim() ? body.client_name.trim() : "MCP Client",
|
||||
redirectUris,
|
||||
scopes,
|
||||
grantTypes,
|
||||
contacts: Array.isArray(body.contacts) ? body.contacts.filter((item): item is string => typeof item === "string") : undefined,
|
||||
metadata: body as Prisma.InputJsonObject,
|
||||
});
|
||||
return json(
|
||||
{
|
||||
client_id: client.clientId,
|
||||
client_id_issued_at: Math.floor(Date.now() / 1000),
|
||||
client_name: client.clientName,
|
||||
redirect_uris: client.redirectUris,
|
||||
grant_types: grantTypes,
|
||||
response_types: ["code"],
|
||||
token_endpoint_auth_method: "none",
|
||||
scope: client.scopes.join(" "),
|
||||
},
|
||||
201,
|
||||
);
|
||||
}
|
||||
|
||||
export async function tokenEndpointFromRequest(request: Request): Promise<Response> {
|
||||
const form = await request.formData();
|
||||
const grantType = stringFormValue(form, "grant_type");
|
||||
if (grantType === "authorization_code") {
|
||||
return exchangeAuthorizationCode(form);
|
||||
}
|
||||
if (grantType === "refresh_token") {
|
||||
return exchangeRefreshToken(form);
|
||||
}
|
||||
return oauthJsonError("unsupported_grant_type", "Unsupported grant_type.", 400);
|
||||
}
|
||||
|
||||
export async function revokeEndpointFromRequest(request: Request): Promise<Response> {
|
||||
const form = await request.formData();
|
||||
const token = stringFormValue(form, "token");
|
||||
if (token) {
|
||||
await revokeMcpOAuthToken(token, getMcpOAuthTokenHashSecret());
|
||||
}
|
||||
return new Response(null, { status: 200 });
|
||||
}
|
||||
|
||||
export function oauthJsonError(error: string, description: string, status = 400): Response {
|
||||
return json({ error, error_description: description }, status);
|
||||
}
|
||||
|
||||
async function exchangeAuthorizationCode(form: FormData): Promise<Response> {
|
||||
const code = requiredFormValue(form, "code");
|
||||
const clientId = requiredFormValue(form, "client_id");
|
||||
const redirectUri = requiredFormValue(form, "redirect_uri");
|
||||
const codeVerifier = requiredFormValue(form, "code_verifier");
|
||||
const consumed = await consumeMcpOAuthAuthorizationCode(code, getMcpOAuthTokenHashSecret());
|
||||
if (!consumed || consumed.client.clientId !== clientId || consumed.redirectUri !== redirectUri) {
|
||||
return oauthJsonError("invalid_grant", "Authorization code is invalid, expired, or already used.", 400);
|
||||
}
|
||||
if (!verifyMcpOAuthPkceS256(codeVerifier, consumed.codeChallenge)) {
|
||||
return oauthJsonError("invalid_grant", "PKCE verification failed.", 400);
|
||||
}
|
||||
const pair = await issueMcpOAuthTokenPair({
|
||||
clientId: consumed.client.id,
|
||||
userId: consumed.userId,
|
||||
tenantId: consumed.tenantId,
|
||||
tenantSlug: consumed.tenantSlug,
|
||||
scopes: consumed.scopes,
|
||||
resource: consumed.resource,
|
||||
secret: getMcpOAuthTokenHashSecret(),
|
||||
});
|
||||
return tokenResponse(pair.accessToken, pair.refreshToken, pair.accessTokenExpiresIn, consumed.scopes, consumed.resource);
|
||||
}
|
||||
|
||||
async function exchangeRefreshToken(form: FormData): Promise<Response> {
|
||||
const refreshToken = requiredFormValue(form, "refresh_token");
|
||||
const clientId = requiredFormValue(form, "client_id");
|
||||
const consumed = await consumeMcpOAuthRefreshToken(refreshToken, getMcpOAuthTokenHashSecret());
|
||||
if (!consumed || consumed.client.clientId !== clientId) {
|
||||
return oauthJsonError("invalid_grant", "Refresh token is invalid, expired, or already rotated.", 400);
|
||||
}
|
||||
// A deactivated tenant is an operator kill-switch — do not let a rotating
|
||||
// refresh token keep minting fresh access tokens for it indefinitely.
|
||||
const tenant = await getTenantByIdOrSlug(consumed.tenantId);
|
||||
if (!tenant || tenant.deactivatedReason) {
|
||||
return oauthJsonError("invalid_grant", "Tenant is deactivated.", 400);
|
||||
}
|
||||
const pair = await issueMcpOAuthTokenPair({
|
||||
clientId: consumed.client.id,
|
||||
userId: consumed.userId,
|
||||
tenantId: consumed.tenantId,
|
||||
tenantSlug: consumed.tenantSlug,
|
||||
scopes: consumed.scopes,
|
||||
resource: consumed.resource,
|
||||
secret: getMcpOAuthTokenHashSecret(),
|
||||
});
|
||||
return tokenResponse(pair.accessToken, pair.refreshToken, pair.accessTokenExpiresIn, consumed.scopes, consumed.resource);
|
||||
}
|
||||
|
||||
function tokenResponse(accessToken: string, refreshToken: string, expiresIn: number, scopes: readonly string[], resource: string): Response {
|
||||
return json({
|
||||
access_token: accessToken,
|
||||
token_type: "Bearer",
|
||||
expires_in: expiresIn,
|
||||
refresh_token: refreshToken,
|
||||
scope: scopes.join(" "),
|
||||
resource,
|
||||
});
|
||||
}
|
||||
|
||||
function getMcpOAuthTokenHashSecret(): string | undefined {
|
||||
return process.env.MCP_OAUTH_TOKEN_HASH_SECRET ?? process.env.API_KEY_HASH_SECRET;
|
||||
}
|
||||
|
||||
async function resolveAuthorizeTenant(tenantParam: string | null, userId: string): Promise<{ id: string; slug: string; name: string }> {
|
||||
if (tenantParam) {
|
||||
const tenant = await getTenantByIdOrSlug(tenantParam);
|
||||
if (!tenant) {
|
||||
throw new McpOAuthError("invalid_request", "Unknown tenant.");
|
||||
}
|
||||
const membership = await getTenantMembershipByIds(tenant.id, userId);
|
||||
if (!membership) {
|
||||
throw new McpOAuthError("access_denied", "Current user is not a member of this tenant.", 403);
|
||||
}
|
||||
return { id: tenant.id, slug: tenant.slug, name: tenant.name };
|
||||
}
|
||||
|
||||
const tenants = await getTenantsForUser(userId);
|
||||
const tenant = tenants[0];
|
||||
if (!tenant) {
|
||||
throw new McpOAuthError("access_denied", "Current user has no active tenant.", 403);
|
||||
}
|
||||
return { id: tenant.id, slug: tenant.slug, name: tenant.name };
|
||||
}
|
||||
|
||||
function parseScopes(raw: string | null | undefined): string[] {
|
||||
const scopes = (raw ?? DEFAULT_SCOPE)
|
||||
.split(/\s+/)
|
||||
.map((scope) => scope.trim())
|
||||
.filter(Boolean);
|
||||
return scopes.length > 0 ? [...new Set(scopes)] : [DEFAULT_SCOPE];
|
||||
}
|
||||
|
||||
function assertScopesSupported(scopes: readonly string[]) {
|
||||
const unsupported = scopes.filter((scope) => !SUPPORTED_SCOPE_SET.has(scope));
|
||||
if (unsupported.length > 0) {
|
||||
throw new McpOAuthError("invalid_scope", `Unsupported scope: ${unsupported.join(", ")}`);
|
||||
}
|
||||
}
|
||||
|
||||
function assertScopesAllowedByClient(scopes: readonly string[], client: McpOAuthClientSummary) {
|
||||
const allowed = new Set(client.scopes);
|
||||
const denied = scopes.filter((scope) => !allowed.has(scope));
|
||||
if (denied.length > 0) {
|
||||
throw new McpOAuthError("invalid_scope", `Scope not registered for this client: ${denied.join(", ")}`);
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeRedirectUris(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) {
|
||||
throw new McpOAuthError("invalid_client_metadata", "redirect_uris must be an array.");
|
||||
}
|
||||
const redirectUris = value.filter((item): item is string => typeof item === "string").map((item) => item.trim()).filter(Boolean);
|
||||
if (redirectUris.length === 0) {
|
||||
throw new McpOAuthError("invalid_client_metadata", "At least one redirect_uri is required.");
|
||||
}
|
||||
for (const uri of redirectUris) {
|
||||
assertAllowedRedirectUri(uri);
|
||||
}
|
||||
return [...new Set(redirectUris)];
|
||||
}
|
||||
|
||||
function assertAllowedRedirectUri(uri: string) {
|
||||
try {
|
||||
const parsed = new URL(uri);
|
||||
if (parsed.protocol === "https:") {
|
||||
return;
|
||||
}
|
||||
if (parsed.protocol === "http:" && ["localhost", "127.0.0.1", "::1"].includes(parsed.hostname)) {
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
throw new McpOAuthError("invalid_redirect_uri", "redirect_uri must be an absolute URL.");
|
||||
}
|
||||
throw new McpOAuthError("invalid_redirect_uri", "redirect_uri must use https or localhost http.");
|
||||
}
|
||||
|
||||
function normalizeGrantTypes(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) {
|
||||
return ["authorization_code", "refresh_token"];
|
||||
}
|
||||
const requested = value.filter((item): item is string => typeof item === "string");
|
||||
const allowed = requested.filter((item) => item === "authorization_code" || item === "refresh_token");
|
||||
return allowed.includes("authorization_code") ? [...new Set(allowed)] : ["authorization_code", "refresh_token"];
|
||||
}
|
||||
|
||||
function requiredParam(url: URL, name: string): string {
|
||||
const value = url.searchParams.get(name)?.trim();
|
||||
if (!value) {
|
||||
throw new McpOAuthError("invalid_request", `${name} is required.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function requiredFormValue(form: FormData, name: string): string {
|
||||
const value = stringFormValue(form, name);
|
||||
if (!value) {
|
||||
throw new McpOAuthError("invalid_request", `${name} is required.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function stringFormValue(form: FormData, name: string): string | null {
|
||||
const value = form.get(name);
|
||||
return typeof value === "string" && value.trim() ? value.trim() : null;
|
||||
}
|
||||
|
||||
async function readJson(request: Request): Promise<Record<string, unknown>> {
|
||||
try {
|
||||
const body = await request.json();
|
||||
return body && typeof body === "object" && !Array.isArray(body) ? (body as Record<string, unknown>) : {};
|
||||
} catch {
|
||||
throw new McpOAuthError("invalid_client_metadata", "Request body must be JSON.");
|
||||
}
|
||||
}
|
||||
|
||||
function withOAuthRedirectParams(redirectUri: string, params: { code?: string; error?: string; state?: string }): string {
|
||||
const url = new URL(redirectUri);
|
||||
if (params.code) {
|
||||
url.searchParams.set("code", params.code);
|
||||
}
|
||||
if (params.error) {
|
||||
url.searchParams.set("error", params.error);
|
||||
}
|
||||
if (params.state) {
|
||||
url.searchParams.set("state", params.state);
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function deriveMcpResourceOrigin(protocol: "http" | "https", webAppHost: string, baseDomain: string): string {
|
||||
if (webAppHost.startsWith("staging-app.")) {
|
||||
return `${protocol}://staging-mcp.${webAppHost.slice("staging-app.".length)}`;
|
||||
}
|
||||
if (webAppHost.startsWith("app.")) {
|
||||
return `${protocol}://mcp.${webAppHost.slice("app.".length)}`;
|
||||
}
|
||||
return `${protocol}://mcp.${baseDomain}`;
|
||||
}
|
||||
|
||||
function trimTrailingSlash(value: string | null | undefined): string | undefined {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed ? trimmed.replace(/\/+$/, "") : undefined;
|
||||
}
|
||||
|
||||
function json(body: unknown, status = 200): Response {
|
||||
return Response.json(body, {
|
||||
status,
|
||||
headers: {
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
});
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const dbMocks = vi.hoisted(() => ({
|
||||
kontaktFindMany: vi.fn(),
|
||||
inboxLeadFindMany: vi.fn(),
|
||||
projektFindMany: vi.fn(),
|
||||
fileFindMany: vi.fn(),
|
||||
taskFindMany: vi.fn(),
|
||||
tenantUserFindMany: vi.fn(),
|
||||
recentSearchFindMany: vi.fn(),
|
||||
recentSearchCreate: vi.fn(),
|
||||
searchIndexEntryUpsert: vi.fn(),
|
||||
}));
|
||||
|
||||
const accessMocks = vi.hoisted(() => ({
|
||||
permissions: ["search.use"] as string[],
|
||||
hasModule: true,
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
dbRead: {
|
||||
kontakt: { findMany: dbMocks.kontaktFindMany },
|
||||
inboxLead: { findMany: dbMocks.inboxLeadFindMany },
|
||||
projekt: { findMany: dbMocks.projektFindMany },
|
||||
file: { findMany: dbMocks.fileFindMany },
|
||||
task: { findMany: dbMocks.taskFindMany },
|
||||
tenantUser: { findMany: dbMocks.tenantUserFindMany },
|
||||
recentSearch: { findMany: dbMocks.recentSearchFindMany },
|
||||
},
|
||||
db: {
|
||||
recentSearch: { create: dbMocks.recentSearchCreate },
|
||||
searchIndexEntry: { upsert: dbMocks.searchIndexEntryUpsert },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/loaders.middleware", () => ({ requireAuth: vi.fn(async () => undefined) }));
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: vi.fn(async () => "tenant_1") }));
|
||||
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(async () => ({ userId: "user_1", lng: "de" })) }));
|
||||
vi.mock("~/utils/connector/tenantConnector.server", () => ({
|
||||
tenantHasModule: vi.fn(async () => accessMocks.hasModule),
|
||||
}));
|
||||
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({
|
||||
getPermissionsByUser: vi.fn(async () => accessMocks.permissions),
|
||||
}));
|
||||
|
||||
import { runGlobalSearch } from "./globalSearch.server";
|
||||
|
||||
describe("runGlobalSearch", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.SEARCH_BACKEND = "sql";
|
||||
accessMocks.permissions = ["search.use"];
|
||||
accessMocks.hasModule = true;
|
||||
dbMocks.recentSearchFindMany.mockResolvedValue([]);
|
||||
dbMocks.recentSearchCreate.mockResolvedValue({});
|
||||
dbMocks.searchIndexEntryUpsert.mockResolvedValue({});
|
||||
dbMocks.kontaktFindMany.mockResolvedValue([]);
|
||||
dbMocks.inboxLeadFindMany.mockResolvedValue([]);
|
||||
dbMocks.projektFindMany.mockResolvedValue([]);
|
||||
dbMocks.fileFindMany.mockResolvedValue([]);
|
||||
dbMocks.taskFindMany.mockResolvedValue([]);
|
||||
dbMocks.tenantUserFindMany.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("requires entity permissions in addition to search.use", async () => {
|
||||
const result = await runGlobalSearch({
|
||||
request: new Request("https://app.example.test/acme/search?q=ada"),
|
||||
params: { tenant: "acme" },
|
||||
query: "ada",
|
||||
});
|
||||
|
||||
expect(result.results).toEqual([]);
|
||||
expect(result.hiddenEntityTypes).toContain("contact");
|
||||
expect(dbMocks.kontaktFindMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("owner-filters CRM contacts when the caller only has crm.read_own", async () => {
|
||||
accessMocks.permissions = ["search.use", "crm.read_own"];
|
||||
dbMocks.kontaktFindMany.mockResolvedValueOnce([
|
||||
{
|
||||
id: "kontakt_1",
|
||||
vorname: "Ada",
|
||||
nachname: "Lovelace",
|
||||
orgName: null,
|
||||
primaerEmail: "ada@example.test",
|
||||
updatedAt: new Date("2026-07-01T10:00:00.000Z"),
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runGlobalSearch({
|
||||
request: new Request("https://app.example.test/acme/search?q=ada"),
|
||||
params: { tenant: "acme" },
|
||||
query: "ada",
|
||||
entityTypes: ["contact"],
|
||||
});
|
||||
|
||||
expect(result.results[0]).toMatchObject({
|
||||
id: "kontakt_1",
|
||||
entityType: "contact",
|
||||
permissionSubject: "crm.read_own",
|
||||
});
|
||||
expect(dbMocks.kontaktFindMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
AND: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
OR: expect.arrayContaining([expect.objectContaining({ zustaendigerUserId: "user_1" }), expect.objectContaining({ createdByUserId: "user_1" })]),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+655
@@ -0,0 +1,655 @@
|
||||
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
|
||||
import {
|
||||
createSearchClient,
|
||||
crmContactsIndex,
|
||||
filesIndex,
|
||||
projectsIndex,
|
||||
searchWithFallback,
|
||||
tasksIndex,
|
||||
usersIndex,
|
||||
type SearchDocument,
|
||||
type SearchHit,
|
||||
} from "@hivegrid/search";
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
|
||||
import { db, dbRead } from "~/utils/db.server";
|
||||
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
|
||||
export const SEARCH_MODULE_KEY = "search";
|
||||
export const SEARCH_USE_PERMISSION = "search.use";
|
||||
|
||||
export type GlobalSearchEntityType = "contact" | "company" | "lead" | "project" | "file" | "task" | "user";
|
||||
|
||||
export type GlobalSearchResult = {
|
||||
id: string;
|
||||
entityType: GlobalSearchEntityType;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
href: string;
|
||||
permissionSubject: string;
|
||||
updatedAt: string | null;
|
||||
};
|
||||
|
||||
export type RecentSearchItem = {
|
||||
id: string;
|
||||
queryText: string;
|
||||
resultCount: number;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
export type GlobalSearchResponse = {
|
||||
query: string;
|
||||
results: GlobalSearchResult[];
|
||||
recentSearches: RecentSearchItem[];
|
||||
hiddenEntityTypes: GlobalSearchEntityType[];
|
||||
latencyHint: string;
|
||||
};
|
||||
|
||||
type SearchContext = {
|
||||
tenantId: string;
|
||||
tenantSlug: string;
|
||||
userId: string;
|
||||
permissions: string[];
|
||||
};
|
||||
|
||||
type SearchInput = {
|
||||
request: Request;
|
||||
params: Record<string, string | undefined>;
|
||||
query: string;
|
||||
limit?: number;
|
||||
entityTypes?: GlobalSearchEntityType[];
|
||||
recordRecent?: boolean;
|
||||
};
|
||||
|
||||
type EntityAccess = {
|
||||
allowed: boolean;
|
||||
permissionSubject: string;
|
||||
all?: boolean;
|
||||
own?: boolean;
|
||||
};
|
||||
|
||||
const LATENCY_HINT = "Suchindex-Aktualisierungen koennen bis zu 10 Sekunden dauern.";
|
||||
const DEFAULT_LIMIT = 20;
|
||||
const RECENT_LIMIT = 6;
|
||||
|
||||
export async function loadSearchContext({ request, params }: { request: Request; params: Record<string, string | undefined> }): Promise<SearchContext> {
|
||||
await requireAuth({ request, params });
|
||||
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
|
||||
if (!tenantId || !userInfo.userId) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
const [hasModule, permissions] = await Promise.all([
|
||||
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: SEARCH_MODULE_KEY }),
|
||||
getPermissionsByUser(userInfo.userId, tenantId),
|
||||
]);
|
||||
if (!hasModule) {
|
||||
throw new CatalogError(foundationErrors.notFound, { module: SEARCH_MODULE_KEY });
|
||||
}
|
||||
requirePermission({ tenantId, userId: userInfo.userId, permissions }, SEARCH_USE_PERMISSION);
|
||||
return {
|
||||
tenantId,
|
||||
tenantSlug: params.tenant ?? tenantId,
|
||||
userId: userInfo.userId,
|
||||
permissions,
|
||||
};
|
||||
}
|
||||
|
||||
export async function runGlobalSearch(input: SearchInput): Promise<GlobalSearchResponse> {
|
||||
const ctx = await loadSearchContext({ request: input.request, params: input.params });
|
||||
const query = input.query.trim();
|
||||
const limit = clampLimit(input.limit);
|
||||
const access = buildAccessMap(ctx.permissions);
|
||||
const requestedTypes = input.entityTypes?.length ? new Set(input.entityTypes) : null;
|
||||
const searchableTypes = (Object.keys(access) as GlobalSearchEntityType[]).filter((type) => access[type].allowed && (!requestedTypes || requestedTypes.has(type)));
|
||||
const hiddenEntityTypes = (Object.keys(access) as GlobalSearchEntityType[]).filter((type) => !access[type].allowed);
|
||||
const recentSearches = await loadRecentSearches(ctx);
|
||||
|
||||
if (!query) {
|
||||
return { query, results: [], recentSearches, hiddenEntityTypes, latencyHint: LATENCY_HINT };
|
||||
}
|
||||
|
||||
const [sqlResults, meiliResults] = await Promise.all([
|
||||
searchSqlFallback({ ctx, access, query, limit, searchableTypes }),
|
||||
searchMeili({ ctx, access, query, limit, searchableTypes }),
|
||||
]);
|
||||
const results = mergeResults([...meiliResults, ...sqlResults]).slice(0, limit);
|
||||
|
||||
if (input.recordRecent !== false) {
|
||||
await recordRecentSearch({ ctx, query, resultCount: results.length, entityTypes: searchableTypes });
|
||||
await mirrorSearchIndexEntries({ ctx, results });
|
||||
}
|
||||
|
||||
return { query, results, recentSearches, hiddenEntityTypes, latencyHint: LATENCY_HINT };
|
||||
}
|
||||
|
||||
function buildAccessMap(permissions: string[]): Record<GlobalSearchEntityType, EntityAccess> {
|
||||
const granted = new Set(permissions);
|
||||
return {
|
||||
contact: {
|
||||
allowed: granted.has("crm.read_all") || granted.has("crm.read_own"),
|
||||
all: granted.has("crm.read_all"),
|
||||
own: granted.has("crm.read_own"),
|
||||
permissionSubject: granted.has("crm.read_all") ? "crm.read_all" : "crm.read_own",
|
||||
},
|
||||
company: {
|
||||
allowed: granted.has("crm.read_all") || granted.has("crm.read_own"),
|
||||
all: granted.has("crm.read_all"),
|
||||
own: granted.has("crm.read_own"),
|
||||
permissionSubject: granted.has("crm.read_all") ? "crm.read_all" : "crm.read_own",
|
||||
},
|
||||
lead: {
|
||||
allowed: granted.has("leads.read_all") || granted.has("leads.read_own"),
|
||||
all: granted.has("leads.read_all"),
|
||||
own: granted.has("leads.read_own"),
|
||||
permissionSubject: granted.has("leads.read_all") ? "leads.read_all" : "leads.read_own",
|
||||
},
|
||||
project: {
|
||||
allowed: granted.has("projects.read_all") || granted.has("projects.read_own") || granted.has("projects.read_own_member") || granted.has("projects.read_own_pl"),
|
||||
all: granted.has("projects.read_all"),
|
||||
own: granted.has("projects.read_own") || granted.has("projects.read_own_member") || granted.has("projects.read_own_pl"),
|
||||
permissionSubject: granted.has("projects.read_all") ? "projects.read_all" : "projects.read_own",
|
||||
},
|
||||
file: {
|
||||
allowed: granted.has("files.read_all") || granted.has("files.read_own"),
|
||||
all: granted.has("files.read_all"),
|
||||
own: granted.has("files.read_own"),
|
||||
permissionSubject: granted.has("files.read_all") ? "files.read_all" : "files.read_own",
|
||||
},
|
||||
task: {
|
||||
allowed: granted.has("tasks.read_all") || granted.has("tasks.read_own"),
|
||||
all: granted.has("tasks.read_all"),
|
||||
own: granted.has("tasks.read_own"),
|
||||
permissionSubject: granted.has("tasks.read_all") ? "tasks.read_all" : "tasks.read_own",
|
||||
},
|
||||
user: {
|
||||
allowed: granted.has("app.settings.members.view"),
|
||||
all: granted.has("app.settings.members.view"),
|
||||
permissionSubject: "app.settings.members.view",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function searchSqlFallback(input: {
|
||||
ctx: SearchContext;
|
||||
access: Record<GlobalSearchEntityType, EntityAccess>;
|
||||
query: string;
|
||||
limit: number;
|
||||
searchableTypes: GlobalSearchEntityType[];
|
||||
}): Promise<GlobalSearchResult[]> {
|
||||
const jobs = input.searchableTypes.map((entityType) => {
|
||||
switch (entityType) {
|
||||
case "contact":
|
||||
return searchContacts(input, "contact");
|
||||
case "company":
|
||||
return searchContacts(input, "company");
|
||||
case "lead":
|
||||
return searchLeads(input);
|
||||
case "project":
|
||||
return searchProjects(input);
|
||||
case "file":
|
||||
return searchFiles(input);
|
||||
case "task":
|
||||
return searchTasks(input);
|
||||
case "user":
|
||||
return searchUsers(input);
|
||||
}
|
||||
});
|
||||
const chunks = await Promise.all(jobs);
|
||||
return chunks.flat().sort(compareUpdatedDesc).slice(0, input.limit);
|
||||
}
|
||||
|
||||
async function searchContacts(
|
||||
{ ctx, access, query, limit }: Pick<Parameters<typeof searchSqlFallback>[0], "ctx" | "access" | "query" | "limit">,
|
||||
entityType: "contact" | "company"
|
||||
) {
|
||||
const entityAccess = access[entityType];
|
||||
const rows = await dbRead.kontakt.findMany({
|
||||
where: {
|
||||
tenantId: ctx.tenantId,
|
||||
archivedAt: null,
|
||||
...(entityType === "company" ? { kontaktTyp: "organisation" as const } : { kontaktTyp: "privatperson" as const }),
|
||||
AND: [
|
||||
entityAccess.all ? {} : { OR: [{ zustaendigerUserId: ctx.userId }, { createdByUserId: ctx.userId }] },
|
||||
{
|
||||
OR: [
|
||||
{ vorname: { contains: query, mode: "insensitive" } },
|
||||
{ nachname: { contains: query, mode: "insensitive" } },
|
||||
{ orgName: { contains: query, mode: "insensitive" } },
|
||||
{ primaerEmail: { contains: query, mode: "insensitive" } },
|
||||
{ primaerTelefon: { contains: query, mode: "insensitive" } },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
orderBy: { updatedAt: "desc" },
|
||||
take: limit,
|
||||
select: { id: true, vorname: true, nachname: true, orgName: true, primaerEmail: true, updatedAt: true },
|
||||
});
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
entityType,
|
||||
title: entityType === "company" ? (row.orgName ?? row.primaerEmail ?? row.id) : [row.vorname, row.nachname].filter(Boolean).join(" ") || row.primaerEmail || row.id,
|
||||
subtitle: row.primaerEmail ?? "",
|
||||
href: appPath({ tenantSlug: ctx.tenantSlug, path: entityType === "company" ? `contacts/companies/${row.id}` : `contacts/${row.id}`, mode: "host-aware" }),
|
||||
permissionSubject: entityAccess.permissionSubject,
|
||||
updatedAt: serializeDate(row.updatedAt),
|
||||
}));
|
||||
}
|
||||
|
||||
async function searchLeads({ ctx, access, query, limit }: Pick<Parameters<typeof searchSqlFallback>[0], "ctx" | "access" | "query" | "limit">) {
|
||||
const entityAccess = access.lead;
|
||||
const rows = await dbRead.inboxLead.findMany({
|
||||
where: {
|
||||
tenantId: ctx.tenantId,
|
||||
archivedAt: null,
|
||||
AND: [
|
||||
entityAccess.all ? {} : { OR: [{ zustaendigerUserId: ctx.userId }, { createdByUserId: ctx.userId }] },
|
||||
{
|
||||
OR: [
|
||||
{ vorname: { contains: query, mode: "insensitive" } },
|
||||
{ nachname: { contains: query, mode: "insensitive" } },
|
||||
{ email: { contains: query, mode: "insensitive" } },
|
||||
{ telefon: { contains: query, mode: "insensitive" } },
|
||||
{ message: { contains: query, mode: "insensitive" } },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
orderBy: { updatedAt: "desc" },
|
||||
take: limit,
|
||||
select: { id: true, vorname: true, nachname: true, email: true, message: true, updatedAt: true },
|
||||
});
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
entityType: "lead" as const,
|
||||
title: [row.vorname, row.nachname].filter(Boolean).join(" ") || row.email || row.id,
|
||||
subtitle: row.email ?? row.message ?? "",
|
||||
href: appPath({ tenantSlug: ctx.tenantSlug, path: `leads/${row.id}`, mode: "host-aware" }),
|
||||
permissionSubject: entityAccess.permissionSubject,
|
||||
updatedAt: serializeDate(row.updatedAt),
|
||||
}));
|
||||
}
|
||||
|
||||
async function searchProjects({ ctx, access, query, limit }: Pick<Parameters<typeof searchSqlFallback>[0], "ctx" | "access" | "query" | "limit">) {
|
||||
const entityAccess = access.project;
|
||||
const rows = await dbRead.projekt.findMany({
|
||||
where: {
|
||||
tenantId: ctx.tenantId,
|
||||
archivedAt: null,
|
||||
AND: [
|
||||
entityAccess.all ? {} : { OR: [{ zustaendigePersonId: ctx.userId }, { projektleiterId: ctx.userId }, { createdByUserId: ctx.userId }] },
|
||||
{
|
||||
OR: [
|
||||
{ projektNummer: { contains: query, mode: "insensitive" } },
|
||||
{ projektname: { contains: query, mode: "insensitive" } },
|
||||
{ beschreibung: { contains: query, mode: "insensitive" } },
|
||||
{ projekttyp: { contains: query, mode: "insensitive" } },
|
||||
{ quelle: { contains: query, mode: "insensitive" } },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
orderBy: { updatedAt: "desc" },
|
||||
take: limit,
|
||||
select: { id: true, projektNummer: true, projektname: true, beschreibung: true, updatedAt: true },
|
||||
});
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
entityType: "project" as const,
|
||||
title: row.projektname,
|
||||
subtitle: row.projektNummer || row.beschreibung || "",
|
||||
href: appPath({ tenantSlug: ctx.tenantSlug, path: `projects/${row.id}`, mode: "host-aware" }),
|
||||
permissionSubject: entityAccess.permissionSubject,
|
||||
updatedAt: serializeDate(row.updatedAt),
|
||||
}));
|
||||
}
|
||||
|
||||
async function searchFiles({ ctx, access, query, limit }: Pick<Parameters<typeof searchSqlFallback>[0], "ctx" | "access" | "query" | "limit">) {
|
||||
const entityAccess = access.file;
|
||||
const rows = await dbRead.file.findMany({
|
||||
where: {
|
||||
tenantId: ctx.tenantId,
|
||||
archivedAt: null,
|
||||
AND: [
|
||||
entityAccess.all ? {} : { OR: [{ assignedToUserId: ctx.userId }, { createdByUserId: ctx.userId }] },
|
||||
{
|
||||
OR: [
|
||||
{ displayName: { contains: query, mode: "insensitive" } },
|
||||
{ notes: { contains: query, mode: "insensitive" } },
|
||||
{ tags: { has: query } },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
orderBy: { updatedAt: "desc" },
|
||||
take: limit,
|
||||
select: { id: true, displayName: true, mimeType: true, updatedAt: true },
|
||||
});
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
entityType: "file" as const,
|
||||
title: row.displayName,
|
||||
subtitle: row.mimeType,
|
||||
href: appPath({ tenantSlug: ctx.tenantSlug, path: `files/${row.id}`, mode: "host-aware" }),
|
||||
permissionSubject: entityAccess.permissionSubject,
|
||||
updatedAt: serializeDate(row.updatedAt),
|
||||
}));
|
||||
}
|
||||
|
||||
async function searchTasks({ ctx, access, query, limit }: Pick<Parameters<typeof searchSqlFallback>[0], "ctx" | "access" | "query" | "limit">) {
|
||||
const entityAccess = access.task;
|
||||
const rows = await dbRead.task.findMany({
|
||||
where: {
|
||||
tenantId: ctx.tenantId,
|
||||
archivedAt: null,
|
||||
AND: [
|
||||
entityAccess.all ? {} : { OR: [{ assignedToUserId: ctx.userId }, { createdByUserId: ctx.userId }, { watchers: { some: { userId: ctx.userId } } }] },
|
||||
{ OR: [{ title: { contains: query, mode: "insensitive" } }, { description: { contains: query, mode: "insensitive" } }] },
|
||||
],
|
||||
},
|
||||
orderBy: { updatedAt: "desc" },
|
||||
take: limit,
|
||||
select: { id: true, title: true, status: true, updatedAt: true },
|
||||
});
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
entityType: "task" as const,
|
||||
title: row.title,
|
||||
subtitle: row.status,
|
||||
href: appPath({ tenantSlug: ctx.tenantSlug, path: `tasks/${row.id}`, mode: "host-aware" }),
|
||||
permissionSubject: entityAccess.permissionSubject,
|
||||
updatedAt: serializeDate(row.updatedAt),
|
||||
}));
|
||||
}
|
||||
|
||||
async function searchUsers({ ctx, access, query, limit }: Pick<Parameters<typeof searchSqlFallback>[0], "ctx" | "access" | "query" | "limit">) {
|
||||
const entityAccess = access.user;
|
||||
const rows = await dbRead.tenantUser.findMany({
|
||||
where: {
|
||||
tenantId: ctx.tenantId,
|
||||
user: {
|
||||
OR: [
|
||||
{ firstName: { contains: query, mode: "insensitive" } },
|
||||
{ lastName: { contains: query, mode: "insensitive" } },
|
||||
{ email: { contains: query, mode: "insensitive" } },
|
||||
],
|
||||
},
|
||||
},
|
||||
orderBy: { user: { email: "asc" } },
|
||||
take: limit,
|
||||
select: { id: true, userId: true, user: { select: { firstName: true, lastName: true, email: true, updatedAt: true } } },
|
||||
});
|
||||
return rows.map((row) => ({
|
||||
id: row.userId,
|
||||
entityType: "user" as const,
|
||||
title: [row.user.firstName, row.user.lastName].filter(Boolean).join(" ") || row.user.email,
|
||||
subtitle: row.user.email,
|
||||
href: appPath({ tenantSlug: ctx.tenantSlug, path: "settings/members", mode: "host-aware" }),
|
||||
permissionSubject: entityAccess.permissionSubject,
|
||||
updatedAt: serializeDate(row.user.updatedAt),
|
||||
}));
|
||||
}
|
||||
|
||||
async function searchMeili(input: {
|
||||
ctx: SearchContext;
|
||||
access: Record<GlobalSearchEntityType, EntityAccess>;
|
||||
query: string;
|
||||
limit: number;
|
||||
searchableTypes: GlobalSearchEntityType[];
|
||||
}): Promise<GlobalSearchResult[]> {
|
||||
if (!process.env.MEILI_URL || process.env.SEARCH_BACKEND === "sql") return [];
|
||||
const client = createSearchClient({ url: process.env.MEILI_URL, apiKey: process.env.MEILI_API_KEY });
|
||||
const jobs: Promise<GlobalSearchResult[]>[] = [];
|
||||
for (const entityType of ["contact", "company", "lead"] as const) {
|
||||
if (input.searchableTypes.includes(entityType)) {
|
||||
jobs.push(
|
||||
searchWithFallback({
|
||||
client,
|
||||
schema: crmContactsIndex,
|
||||
tenantId: input.ctx.tenantId,
|
||||
query: input.query,
|
||||
options: { limit: input.limit, extraFilters: [`entityType = "${entityType}"`, ...ownerMeiliFilters(input.access[entityType], input.ctx.userId, ["ownerId"])] },
|
||||
fallback: async () => ({ hits: [], estimatedTotalHits: 0, processingTimeMs: 0 }),
|
||||
}).then((result) => result.hits.map((hit) => meiliCrmHit(input, entityType, hit)))
|
||||
);
|
||||
}
|
||||
}
|
||||
if (input.searchableTypes.includes("project")) {
|
||||
jobs.push(
|
||||
searchWithFallback({
|
||||
client,
|
||||
schema: projectsIndex,
|
||||
tenantId: input.ctx.tenantId,
|
||||
query: input.query,
|
||||
options: { limit: input.limit, extraFilters: ownerMeiliFilters(input.access.project, input.ctx.userId, ["ownerId", "projectLeadId"]) },
|
||||
fallback: async () => ({ hits: [], estimatedTotalHits: 0, processingTimeMs: 0 }),
|
||||
}).then((result) => result.hits.map((hit) => meiliProjectHit(input, hit)))
|
||||
);
|
||||
}
|
||||
if (input.searchableTypes.includes("file")) {
|
||||
jobs.push(
|
||||
searchWithFallback({
|
||||
client,
|
||||
schema: filesIndex,
|
||||
tenantId: input.ctx.tenantId,
|
||||
query: input.query,
|
||||
options: { limit: input.limit, extraFilters: ownerMeiliFilters(input.access.file, input.ctx.userId, ["createdByUserId", "assignedToUserId"]) },
|
||||
fallback: async () => ({ hits: [], estimatedTotalHits: 0, processingTimeMs: 0 }),
|
||||
}).then((result) => result.hits.map((hit) => meiliFileHit(input, hit)))
|
||||
);
|
||||
}
|
||||
if (input.searchableTypes.includes("task")) {
|
||||
jobs.push(
|
||||
searchWithFallback({
|
||||
client,
|
||||
schema: tasksIndex,
|
||||
tenantId: input.ctx.tenantId,
|
||||
query: input.query,
|
||||
options: { limit: input.limit, extraFilters: ownerMeiliFilters(input.access.task, input.ctx.userId, ["createdByUserId", "assignedToUserId"]) },
|
||||
fallback: async () => ({ hits: [], estimatedTotalHits: 0, processingTimeMs: 0 }),
|
||||
}).then((result) => result.hits.map((hit) => meiliTaskHit(input, hit)))
|
||||
);
|
||||
}
|
||||
if (input.searchableTypes.includes("user")) {
|
||||
jobs.push(
|
||||
searchWithFallback({
|
||||
client,
|
||||
schema: usersIndex,
|
||||
tenantId: input.ctx.tenantId,
|
||||
query: input.query,
|
||||
options: { limit: input.limit },
|
||||
fallback: async () => ({ hits: [], estimatedTotalHits: 0, processingTimeMs: 0 }),
|
||||
}).then((result) => result.hits.map((hit) => meiliUserHit(input, hit)))
|
||||
);
|
||||
}
|
||||
try {
|
||||
return (await Promise.all(jobs)).flat();
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function meiliCrmHit(
|
||||
input: Pick<Parameters<typeof searchMeili>[0], "ctx" | "access">,
|
||||
entityType: "contact" | "company" | "lead",
|
||||
hit: SearchHit<SearchDocument>
|
||||
): GlobalSearchResult {
|
||||
const doc = hit.document;
|
||||
const title =
|
||||
entityType === "company"
|
||||
? String(doc.company ?? doc.email ?? doc.id)
|
||||
: [doc.firstName, doc.lastName].filter(Boolean).join(" ") || String(doc.email ?? doc.id);
|
||||
const path = entityType === "company" ? `contacts/companies/${doc.id}` : entityType === "lead" ? `leads/${doc.id}` : `contacts/${doc.id}`;
|
||||
return {
|
||||
id: String(doc.id),
|
||||
entityType,
|
||||
title,
|
||||
subtitle: String(doc.email ?? doc.status ?? ""),
|
||||
href: appPath({ tenantSlug: input.ctx.tenantSlug, path, mode: "host-aware" }),
|
||||
permissionSubject: input.access[entityType].permissionSubject,
|
||||
updatedAt: stringOrNull(doc.updatedAt),
|
||||
};
|
||||
}
|
||||
|
||||
function meiliProjectHit(input: Pick<Parameters<typeof searchMeili>[0], "ctx" | "access">, hit: SearchHit<SearchDocument>): GlobalSearchResult {
|
||||
const doc = hit.document;
|
||||
return {
|
||||
id: String(doc.id),
|
||||
entityType: "project",
|
||||
title: String(doc.name ?? doc.projectNumber ?? doc.id),
|
||||
subtitle: String(doc.projectNumber ?? doc.type ?? ""),
|
||||
href: appPath({ tenantSlug: input.ctx.tenantSlug, path: `projects/${doc.id}`, mode: "host-aware" }),
|
||||
permissionSubject: input.access.project.permissionSubject,
|
||||
updatedAt: stringOrNull(doc.updatedAt),
|
||||
};
|
||||
}
|
||||
|
||||
function ownerMeiliFilters(access: EntityAccess, userId: string, fields: readonly string[]): string[] {
|
||||
if (access.all) return [];
|
||||
const escaped = escapeMeiliFilterValue(userId);
|
||||
return [`${fields.map((field) => `${field} = "${escaped}"`).join(" OR ")}`];
|
||||
}
|
||||
|
||||
function meiliFileHit(input: Pick<Parameters<typeof searchMeili>[0], "ctx" | "access">, hit: SearchHit<SearchDocument>): GlobalSearchResult {
|
||||
const doc = hit.document;
|
||||
return {
|
||||
id: String(doc.id),
|
||||
entityType: "file",
|
||||
title: String(doc.displayName ?? doc.id),
|
||||
subtitle: String(doc.mimeType ?? ""),
|
||||
href: appPath({ tenantSlug: input.ctx.tenantSlug, path: `files/${doc.id}`, mode: "host-aware" }),
|
||||
permissionSubject: input.access.file.permissionSubject,
|
||||
updatedAt: stringOrNull(doc.updatedAt),
|
||||
};
|
||||
}
|
||||
|
||||
function meiliTaskHit(input: Pick<Parameters<typeof searchMeili>[0], "ctx" | "access">, hit: SearchHit<SearchDocument>): GlobalSearchResult {
|
||||
const doc = hit.document;
|
||||
return {
|
||||
id: String(doc.id),
|
||||
entityType: "task",
|
||||
title: String(doc.title ?? doc.id),
|
||||
subtitle: String(doc.status ?? ""),
|
||||
href: appPath({ tenantSlug: input.ctx.tenantSlug, path: `tasks/${doc.id}`, mode: "host-aware" }),
|
||||
permissionSubject: input.access.task.permissionSubject,
|
||||
updatedAt: stringOrNull(doc.updatedAt),
|
||||
};
|
||||
}
|
||||
|
||||
function meiliUserHit(input: Pick<Parameters<typeof searchMeili>[0], "ctx" | "access">, hit: SearchHit<SearchDocument>): GlobalSearchResult {
|
||||
const doc = hit.document;
|
||||
const title = [doc.firstName, doc.lastName].filter(Boolean).join(" ") || String(doc.email ?? doc.id);
|
||||
return {
|
||||
id: String(doc.id),
|
||||
entityType: "user",
|
||||
title,
|
||||
subtitle: String(doc.email ?? ""),
|
||||
href: appPath({ tenantSlug: input.ctx.tenantSlug, path: "settings/members", mode: "host-aware" }),
|
||||
permissionSubject: input.access.user.permissionSubject,
|
||||
updatedAt: stringOrNull(doc.lastLoginAt),
|
||||
};
|
||||
}
|
||||
|
||||
async function loadRecentSearches(ctx: SearchContext): Promise<RecentSearchItem[]> {
|
||||
const rows = await dbRead.recentSearch.findMany({
|
||||
where: { tenantId: ctx.tenantId, userId: ctx.userId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: RECENT_LIMIT,
|
||||
select: { id: true, queryText: true, resultCount: true, createdAt: true },
|
||||
});
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
queryText: row.queryText,
|
||||
resultCount: row.resultCount,
|
||||
createdAt: serializeDate(row.createdAt) ?? "",
|
||||
}));
|
||||
}
|
||||
|
||||
async function recordRecentSearch(input: { ctx: SearchContext; query: string; resultCount: number; entityTypes: readonly string[] }) {
|
||||
try {
|
||||
await db.recentSearch.create({
|
||||
data: {
|
||||
tenantId: input.ctx.tenantId,
|
||||
userId: input.ctx.userId,
|
||||
queryText: input.query,
|
||||
resultCount: input.resultCount,
|
||||
appliedFilters: { entityTypes: input.entityTypes },
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
// Recent searches are helpful state, not a reason to fail the search request.
|
||||
}
|
||||
}
|
||||
|
||||
async function mirrorSearchIndexEntries(input: { ctx: SearchContext; results: GlobalSearchResult[] }) {
|
||||
await Promise.all(
|
||||
input.results.map((result) =>
|
||||
db.searchIndexEntry
|
||||
.upsert({
|
||||
where: {
|
||||
tenantId_entityType_entityId: {
|
||||
tenantId: input.ctx.tenantId,
|
||||
entityType: result.entityType,
|
||||
entityId: result.id,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
tenantId: input.ctx.tenantId,
|
||||
entityType: result.entityType,
|
||||
entityId: result.id,
|
||||
title: result.title,
|
||||
subtitle: result.subtitle,
|
||||
bodyText: `${result.title} ${result.subtitle}`,
|
||||
routePath: result.href,
|
||||
sourceIndex: result.entityType,
|
||||
permissionSubject: result.permissionSubject,
|
||||
},
|
||||
update: {
|
||||
title: result.title,
|
||||
subtitle: result.subtitle,
|
||||
bodyText: `${result.title} ${result.subtitle}`,
|
||||
routePath: result.href,
|
||||
permissionSubject: result.permissionSubject,
|
||||
lastIndexedAt: new Date(),
|
||||
isArchived: false,
|
||||
},
|
||||
})
|
||||
.catch(() => undefined)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function mergeResults(results: GlobalSearchResult[]) {
|
||||
const seen = new Set<string>();
|
||||
return results.filter((result) => {
|
||||
const key = `${result.entityType}:${result.id}`;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
function compareUpdatedDesc(left: GlobalSearchResult, right: GlobalSearchResult) {
|
||||
return Date.parse(right.updatedAt ?? "") - Date.parse(left.updatedAt ?? "");
|
||||
}
|
||||
|
||||
function clampLimit(limit: number | undefined) {
|
||||
if (!limit || Number.isNaN(limit)) return DEFAULT_LIMIT;
|
||||
return Math.min(Math.max(Math.floor(limit), 1), 50);
|
||||
}
|
||||
|
||||
function serializeDate(value: Date | string | null): string | null {
|
||||
if (value === null) return null;
|
||||
return value instanceof Date ? value.toISOString() : value;
|
||||
}
|
||||
|
||||
function stringOrNull(value: unknown): string | null {
|
||||
return typeof value === "string" ? value : null;
|
||||
}
|
||||
|
||||
function escapeMeiliFilterValue(value: string): string {
|
||||
return value.replace(/\\/gu, "\\\\").replace(/"/gu, '\\"');
|
||||
}
|
||||
+427
@@ -0,0 +1,427 @@
|
||||
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import {
|
||||
crmContactsIndex,
|
||||
filesIndex,
|
||||
projectsIndex,
|
||||
publishSearchDeleteEvent,
|
||||
publishSearchUpsertEvent,
|
||||
tasksIndex,
|
||||
usersIndex,
|
||||
type SearchIndexSchema,
|
||||
} from "@hivegrid/search";
|
||||
|
||||
type SearchProjectionTx = Prisma.TransactionClient & {
|
||||
searchIndexEntry: {
|
||||
upsert(args: {
|
||||
where: { tenantId_entityType_entityId: { tenantId: string; entityType: string; entityId: string } };
|
||||
create: Prisma.SearchIndexEntryUncheckedCreateInput;
|
||||
update: Prisma.SearchIndexEntryUncheckedUpdateInput;
|
||||
}): Promise<unknown>;
|
||||
updateMany(args: { where: { tenantId: string; entityType: string; entityId: string }; data: Prisma.SearchIndexEntryUncheckedUpdateInput }): Promise<unknown>;
|
||||
};
|
||||
};
|
||||
|
||||
type SearchEntityType = "contact" | "company" | "lead" | "project" | "file" | "task" | "user";
|
||||
|
||||
type SearchProjectionInput = {
|
||||
tx: SearchProjectionTx;
|
||||
schema: SearchIndexSchema;
|
||||
tenantId: string;
|
||||
entityType: SearchEntityType;
|
||||
entityId: string;
|
||||
title: string;
|
||||
subtitle?: string | null;
|
||||
bodyText?: string | null;
|
||||
routePath: string;
|
||||
permissionSubject: string;
|
||||
document: Record<string, unknown> & { id: string; tenantId: string };
|
||||
};
|
||||
|
||||
type KontaktSearchRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
kontaktTyp: "privatperson" | "organisation";
|
||||
kontaktStatus: string;
|
||||
vorname: string | null;
|
||||
nachname: string | null;
|
||||
orgName: string | null;
|
||||
primaerEmail: string | null;
|
||||
zustaendigerUserId: string | null;
|
||||
createdByUserId: string | null;
|
||||
createdAt: Date | string;
|
||||
updatedAt: Date | string;
|
||||
};
|
||||
|
||||
type LeadSearchRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
createdByUserId: string | null;
|
||||
zustaendigerUserId: string | null;
|
||||
quelle: string;
|
||||
sourceOrigin: string | null;
|
||||
status: string;
|
||||
vorname: string | null;
|
||||
nachname: string | null;
|
||||
email: string | null;
|
||||
telefon: string | null;
|
||||
message: string | null;
|
||||
createdAt: Date | string;
|
||||
updatedAt: Date | string;
|
||||
};
|
||||
|
||||
type ProjectSearchRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
projektNummer: string;
|
||||
projektname: string;
|
||||
beschreibung: string | null;
|
||||
projekttyp: string | null;
|
||||
quelle: string | null;
|
||||
pipelineId: string;
|
||||
stageId: string;
|
||||
zustaendigePersonId: string | null;
|
||||
projektleiterId: string | null;
|
||||
archivedAt: Date | string | null;
|
||||
createdAt: Date | string;
|
||||
updatedAt: Date | string;
|
||||
deadline: Date | string | null;
|
||||
potenziellerAuftragswert: unknown;
|
||||
auftragsvolumen: unknown;
|
||||
};
|
||||
|
||||
type FileSearchRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
displayName: string;
|
||||
notes: string | null;
|
||||
tags: string[];
|
||||
mimeType: string;
|
||||
createdByUserId: string;
|
||||
assignedToUserId: string | null;
|
||||
archivedAt: Date | string | null;
|
||||
createdAt: Date | string;
|
||||
updatedAt: Date | string;
|
||||
sizeBytes: number;
|
||||
};
|
||||
|
||||
type TaskSearchRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
createdByUserId: string;
|
||||
title: string;
|
||||
description: string | null;
|
||||
status: string;
|
||||
priority: string;
|
||||
deadline: Date | string | null;
|
||||
assignedToUserId: string | null;
|
||||
assignedToGroupId: string | null;
|
||||
linkedEntityType: string | null;
|
||||
linkedEntityId: string | null;
|
||||
archivedAt: Date | string | null;
|
||||
createdAt: Date | string;
|
||||
updatedAt: Date | string;
|
||||
};
|
||||
|
||||
type TenantUserSearchRow = {
|
||||
tenantId: string;
|
||||
type: number;
|
||||
status: number;
|
||||
user: {
|
||||
id: string;
|
||||
createdAt: Date | string;
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
active: boolean;
|
||||
admin?: { userId: string } | null;
|
||||
logs?: Array<{ createdAt: Date | string }>;
|
||||
};
|
||||
};
|
||||
|
||||
const TENANT_USER_STATUS_ACTIVE = 2;
|
||||
|
||||
export async function publishKontaktSearchUpsert(tx: Prisma.TransactionClient, row: KontaktSearchRow): Promise<void> {
|
||||
const entityType = row.kontaktTyp === "organisation" ? "company" : "contact";
|
||||
const title = entityType === "company" ? (row.orgName ?? row.primaerEmail ?? row.id) : [row.vorname, row.nachname].filter(Boolean).join(" ") || row.primaerEmail || row.id;
|
||||
await publishSearchProjectionUpsert({
|
||||
tx: tx as SearchProjectionTx,
|
||||
schema: crmContactsIndex,
|
||||
tenantId: row.tenantId,
|
||||
entityType,
|
||||
entityId: row.id,
|
||||
title,
|
||||
subtitle: row.primaerEmail,
|
||||
bodyText: [title, row.primaerEmail].filter(Boolean).join(" "),
|
||||
routePath: `/app/${row.tenantId}/${entityType === "company" ? "contacts/companies" : "contacts"}/${row.id}`,
|
||||
permissionSubject: "crm.read_own",
|
||||
document: {
|
||||
id: row.id,
|
||||
tenantId: row.tenantId,
|
||||
entityType,
|
||||
firstName: row.vorname ?? "",
|
||||
lastName: row.nachname ?? "",
|
||||
email: row.primaerEmail ?? "",
|
||||
company: row.orgName ?? "",
|
||||
jobTitle: "",
|
||||
tags: [],
|
||||
status: row.kontaktStatus,
|
||||
ownerId: row.zustaendigerUserId ?? row.createdByUserId ?? "",
|
||||
createdAt: serializeDate(row.createdAt),
|
||||
updatedAt: serializeDate(row.updatedAt),
|
||||
lastInteractionAt: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function publishLeadSearchUpsert(tx: Prisma.TransactionClient, row: LeadSearchRow): Promise<void> {
|
||||
const title = [row.vorname, row.nachname].filter(Boolean).join(" ") || row.email || row.telefon || row.id;
|
||||
await publishSearchProjectionUpsert({
|
||||
tx: tx as SearchProjectionTx,
|
||||
schema: crmContactsIndex,
|
||||
tenantId: row.tenantId,
|
||||
entityType: "lead",
|
||||
entityId: row.id,
|
||||
title,
|
||||
subtitle: row.email ?? row.telefon ?? row.sourceOrigin ?? row.quelle,
|
||||
bodyText: [title, row.email, row.telefon, row.message].filter(Boolean).join(" "),
|
||||
routePath: `/app/${row.tenantId}/leads/${row.id}`,
|
||||
permissionSubject: "leads.read_own",
|
||||
document: {
|
||||
id: row.id,
|
||||
tenantId: row.tenantId,
|
||||
entityType: "lead",
|
||||
firstName: row.vorname ?? "",
|
||||
lastName: row.nachname ?? "",
|
||||
email: row.email ?? "",
|
||||
company: row.sourceOrigin ?? "",
|
||||
jobTitle: "",
|
||||
tags: [],
|
||||
status: row.status,
|
||||
ownerId: row.zustaendigerUserId ?? row.createdByUserId ?? "",
|
||||
createdAt: serializeDate(row.createdAt),
|
||||
updatedAt: serializeDate(row.updatedAt),
|
||||
lastInteractionAt: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function publishProjectSearchUpsert(tx: Prisma.TransactionClient, row: ProjectSearchRow): Promise<void> {
|
||||
await publishSearchProjectionUpsert({
|
||||
tx: tx as SearchProjectionTx,
|
||||
schema: projectsIndex,
|
||||
tenantId: row.tenantId,
|
||||
entityType: "project",
|
||||
entityId: row.id,
|
||||
title: row.projektname || row.projektNummer || row.id,
|
||||
subtitle: row.projektNummer,
|
||||
bodyText: [row.projektname, row.projektNummer, row.beschreibung, row.projekttyp, row.quelle].filter(Boolean).join(" "),
|
||||
routePath: `/app/${row.tenantId}/projects/${row.id}`,
|
||||
permissionSubject: "projects.read_own",
|
||||
document: {
|
||||
id: row.id,
|
||||
tenantId: row.tenantId,
|
||||
projectNumber: row.projektNummer,
|
||||
name: row.projektname,
|
||||
description: row.beschreibung ?? "",
|
||||
type: row.projekttyp ?? "",
|
||||
source: row.quelle ?? "",
|
||||
pipelineId: row.pipelineId,
|
||||
stageId: row.stageId,
|
||||
ownerId: row.zustaendigePersonId ?? "",
|
||||
projectLeadId: row.projektleiterId ?? "",
|
||||
archived: row.archivedAt !== null,
|
||||
createdAt: serializeDate(row.createdAt),
|
||||
updatedAt: serializeDate(row.updatedAt),
|
||||
deadline: serializeDate(row.deadline),
|
||||
potentialValue: serializeDecimal(row.potenziellerAuftragswert),
|
||||
orderVolume: serializeDecimal(row.auftragsvolumen),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function publishFileSearchUpsert(tx: Prisma.TransactionClient, row: FileSearchRow): Promise<void> {
|
||||
await publishSearchProjectionUpsert({
|
||||
tx: tx as SearchProjectionTx,
|
||||
schema: filesIndex,
|
||||
tenantId: row.tenantId,
|
||||
entityType: "file",
|
||||
entityId: row.id,
|
||||
title: row.displayName || row.id,
|
||||
subtitle: row.mimeType,
|
||||
bodyText: [row.displayName, row.notes, ...(row.tags ?? [])].filter(Boolean).join(" "),
|
||||
routePath: `/app/${row.tenantId}/files/${row.id}`,
|
||||
permissionSubject: "files.read_own",
|
||||
document: {
|
||||
id: row.id,
|
||||
tenantId: row.tenantId,
|
||||
displayName: row.displayName,
|
||||
notes: row.notes ?? "",
|
||||
tags: row.tags ?? [],
|
||||
mimeType: row.mimeType,
|
||||
createdByUserId: row.createdByUserId,
|
||||
assignedToUserId: row.assignedToUserId ?? "",
|
||||
archived: row.archivedAt !== null,
|
||||
createdAt: serializeDate(row.createdAt),
|
||||
updatedAt: serializeDate(row.updatedAt),
|
||||
sizeBytes: row.sizeBytes,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function publishTaskSearchUpsert(tx: Prisma.TransactionClient, row: TaskSearchRow): Promise<void> {
|
||||
await publishSearchProjectionUpsert({
|
||||
tx: tx as SearchProjectionTx,
|
||||
schema: tasksIndex,
|
||||
tenantId: row.tenantId,
|
||||
entityType: "task",
|
||||
entityId: row.id,
|
||||
title: row.title || row.id,
|
||||
subtitle: row.status,
|
||||
bodyText: [row.title, row.description].filter(Boolean).join(" "),
|
||||
routePath: `/app/${row.tenantId}/tasks/${row.id}`,
|
||||
permissionSubject: "tasks.read_own",
|
||||
document: {
|
||||
id: row.id,
|
||||
tenantId: row.tenantId,
|
||||
title: row.title,
|
||||
description: row.description ?? "",
|
||||
status: row.status,
|
||||
priority: row.priority,
|
||||
createdByUserId: row.createdByUserId,
|
||||
assignedToUserId: row.assignedToUserId ?? "",
|
||||
assignedToGroupId: row.assignedToGroupId ?? "",
|
||||
linkedEntityType: row.linkedEntityType ?? "",
|
||||
linkedEntityId: row.linkedEntityId ?? "",
|
||||
archived: row.archivedAt !== null,
|
||||
createdAt: serializeDate(row.createdAt),
|
||||
updatedAt: serializeDate(row.updatedAt),
|
||||
deadline: serializeDate(row.deadline),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function publishTenantUserSearchUpsert(tx: Prisma.TransactionClient, row: TenantUserSearchRow): Promise<void> {
|
||||
const title = [row.user.firstName, row.user.lastName].filter(Boolean).join(" ") || row.user.email || row.user.id;
|
||||
await publishSearchProjectionUpsert({
|
||||
tx: tx as SearchProjectionTx,
|
||||
schema: usersIndex,
|
||||
tenantId: row.tenantId,
|
||||
entityType: "user",
|
||||
entityId: row.user.id,
|
||||
title,
|
||||
subtitle: row.user.email,
|
||||
bodyText: [title, row.user.email].filter(Boolean).join(" "),
|
||||
routePath: `/app/${row.tenantId}/settings/members`,
|
||||
permissionSubject: "app.settings.members.view",
|
||||
document: {
|
||||
id: row.user.id,
|
||||
tenantId: row.tenantId,
|
||||
firstName: row.user.firstName,
|
||||
lastName: row.user.lastName,
|
||||
email: row.user.email,
|
||||
type: row.type,
|
||||
admin: Boolean(row.user.admin),
|
||||
active: row.user.active && row.status === TENANT_USER_STATUS_ACTIVE,
|
||||
createdAt: serializeDate(row.user.createdAt),
|
||||
lastLoginAt: serializeDate(row.user.logs?.[0]?.createdAt ?? null),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function publishUserSearchDelete(tx: Prisma.TransactionClient, input: { tenantId: string; userId: string }): Promise<void> {
|
||||
await publishSearchProjectionDelete(tx, {
|
||||
schema: usersIndex,
|
||||
tenantId: input.tenantId,
|
||||
entityType: "user",
|
||||
entityId: input.userId,
|
||||
});
|
||||
}
|
||||
|
||||
export async function publishSearchProjectionDelete(
|
||||
tx: Prisma.TransactionClient,
|
||||
input: { schema: SearchIndexSchema; tenantId: string; entityType: SearchEntityType; entityId: string },
|
||||
): Promise<void> {
|
||||
await (tx as SearchProjectionTx).searchIndexEntry.updateMany({
|
||||
where: { tenantId: input.tenantId, entityType: input.entityType, entityId: input.entityId },
|
||||
data: { isArchived: true, lastIndexedAt: new Date() },
|
||||
});
|
||||
await publishSearchDeleteEvent({
|
||||
publish: (event) =>
|
||||
publishOutboxEvent(tx as unknown as OutboxPublisherTransaction, {
|
||||
tenantId: event.tenantId,
|
||||
type: event.type,
|
||||
payload: event.payload as Prisma.InputJsonValue,
|
||||
}),
|
||||
schema: input.schema,
|
||||
tenantId: input.tenantId,
|
||||
entityName: input.entityType,
|
||||
documentId: input.entityId,
|
||||
});
|
||||
}
|
||||
|
||||
async function publishSearchProjectionUpsert(input: SearchProjectionInput): Promise<void> {
|
||||
const now = new Date();
|
||||
await input.tx.searchIndexEntry.upsert({
|
||||
where: {
|
||||
tenantId_entityType_entityId: {
|
||||
tenantId: input.tenantId,
|
||||
entityType: input.entityType,
|
||||
entityId: input.entityId,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
tenantId: input.tenantId,
|
||||
entityType: input.entityType,
|
||||
entityId: input.entityId,
|
||||
title: input.title,
|
||||
subtitle: input.subtitle ?? null,
|
||||
bodyText: input.bodyText ?? input.title,
|
||||
routePath: input.routePath,
|
||||
sourceIndex: input.schema.name,
|
||||
permissionSubject: input.permissionSubject,
|
||||
lastIndexedAt: now,
|
||||
},
|
||||
update: {
|
||||
title: input.title,
|
||||
subtitle: input.subtitle ?? null,
|
||||
bodyText: input.bodyText ?? input.title,
|
||||
routePath: input.routePath,
|
||||
sourceIndex: input.schema.name,
|
||||
permissionSubject: input.permissionSubject,
|
||||
lastIndexedAt: now,
|
||||
isArchived: false,
|
||||
},
|
||||
});
|
||||
await publishSearchUpsertEvent({
|
||||
publish: (event) =>
|
||||
publishOutboxEvent(input.tx as unknown as OutboxPublisherTransaction, {
|
||||
tenantId: event.tenantId,
|
||||
type: event.type,
|
||||
payload: event.payload as Prisma.InputJsonValue,
|
||||
}),
|
||||
schema: input.schema,
|
||||
tenantId: input.tenantId,
|
||||
entityName: input.entityType,
|
||||
document: input.document,
|
||||
});
|
||||
}
|
||||
|
||||
function serializeDate(value: Date | string | null | undefined): string | null {
|
||||
if (value === null || value === undefined) return null;
|
||||
return value instanceof Date ? value.toISOString() : value;
|
||||
}
|
||||
|
||||
function serializeDecimal(value: unknown): number | null {
|
||||
if (value === null || value === undefined) return null;
|
||||
if (typeof value === "number") return Number.isFinite(value) ? value : null;
|
||||
if (typeof value === "string") {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
if (typeof value === "object" && "toString" in value && typeof value.toString === "function") {
|
||||
const parsed = Number(value.toString());
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
// Kontakt adapter for the typed model registry (R-P14C-T2 / R-P14D, AD-2).
|
||||
//
|
||||
// Maps the registry's generic read/create/update/delete contract onto the typed
|
||||
// CRM domain service (`crmService.server`), replacing the generic
|
||||
// `EntitiesSingleton.getEntity("contact")` + `RowsApi.*` path. Kontakt is the
|
||||
// first (and currently only) addressable model; the kern chain registers further
|
||||
// models (Projekt, Rechnung, …) as they are built.
|
||||
//
|
||||
// Workflows act as a tenant-level system actor: reads run with `crm.read_all`
|
||||
// within the run's tenant (mirroring the pre-typed generic builder, which was
|
||||
// tenant-scoped without per-user visibility); writes require the triggering user
|
||||
// (`createdByUserId`) and write the M001 audit + activity trail via crmAudit.
|
||||
|
||||
import {
|
||||
CatalogError,
|
||||
foundationErrors,
|
||||
} from "@hivegrid/foundation";
|
||||
import {
|
||||
createKontakt,
|
||||
getVisibleKontaktOrThrow,
|
||||
hardDeleteKontakt,
|
||||
updateKontakt,
|
||||
type CreateKontaktInput,
|
||||
type CrmVisibilityContext,
|
||||
type KontaktRow,
|
||||
type KontaktStatus,
|
||||
type KontaktTyp,
|
||||
type OrgMerkmal,
|
||||
} from "~/utils/integrations/crm/crmService.server";
|
||||
import { auditCrmEvent, logKontaktActivity } from "~/utils/integrations/crm/crmAudit.server";
|
||||
import type { FieldSchema, ModelCtx, ModelRecord, TypedModelAdapter } from "./types";
|
||||
import { TypedModelError } from "./types";
|
||||
|
||||
const KONTAKT_TYP_VALUES = ["privatperson", "organisation"] as const satisfies readonly KontaktTyp[];
|
||||
const KONTAKT_STATUS_VALUES = ["kontakt", "kunde", "bestandskunde"] as const satisfies readonly KontaktStatus[];
|
||||
const ORG_MERKMAL_VALUES = ["gmbh", "kg", "oeffentliche_einrichtung", "sonstige"] as const satisfies readonly OrgMerkmal[];
|
||||
|
||||
const kontaktFieldSchema: FieldSchema = {
|
||||
id: { type: "string", readonly: true },
|
||||
kontaktTyp: { type: "enum", required: true, enum: KONTAKT_TYP_VALUES },
|
||||
kontaktStatus: { type: "enum", enum: KONTAKT_STATUS_VALUES },
|
||||
vorname: { type: "string", nullable: true },
|
||||
nachname: { type: "string", nullable: true },
|
||||
orgName: { type: "string", nullable: true },
|
||||
orgMerkmal: { type: "enum", nullable: true, enum: ORG_MERKMAL_VALUES },
|
||||
primaerEmail: { type: "string", nullable: true, readonly: true },
|
||||
primaerTelefon: { type: "string", nullable: true, readonly: true },
|
||||
zustaendigerUserId: { type: "string", nullable: true },
|
||||
createdAt: { type: "date", readonly: true },
|
||||
updatedAt: { type: "date", readonly: true },
|
||||
archivedAt: { type: "date", nullable: true, readonly: true },
|
||||
};
|
||||
|
||||
/** Tenant required for any Kontakt operation (the model is tenant-scoped). */
|
||||
function requireTenant(ctx: ModelCtx): string {
|
||||
if (!ctx.tenantId) {
|
||||
throw new TypedModelError("workflows.errors.modelMissingTenant", "Kontakt operations require a tenant context.");
|
||||
}
|
||||
return ctx.tenantId;
|
||||
}
|
||||
|
||||
/** Triggering user required for any write (createdByUserId / audit actor). */
|
||||
function requireUser(ctx: ModelCtx): string {
|
||||
if (!ctx.userId) {
|
||||
throw new TypedModelError("workflows.errors.modelMissingUser", "Kontakt writes require a user context.");
|
||||
}
|
||||
return ctx.userId;
|
||||
}
|
||||
|
||||
/** System read context: full read within the run's tenant (no per-user filter). */
|
||||
function systemReadCtx(userId: string): CrmVisibilityContext {
|
||||
return { userId, permissions: ["crm.read_all"] };
|
||||
}
|
||||
|
||||
function isNotFound(error: unknown): boolean {
|
||||
return error instanceof CatalogError && error.code === foundationErrors.notFound.code;
|
||||
}
|
||||
|
||||
// --- payload coercion (replaces ApiHelper.getRowPropertiesFromJson) ---------
|
||||
|
||||
function optString(value: unknown): string | null | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
if (value === null) return null;
|
||||
if (typeof value === "string") return value;
|
||||
throw new TypedModelError("workflows.errors.invalidFieldValue", `Expected a string but received ${typeof value}.`);
|
||||
}
|
||||
|
||||
function optEnum<T extends string>(value: unknown, allowed: readonly T[], field: string): T | null | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
if (value === null) return null;
|
||||
if (typeof value === "string" && (allowed as readonly string[]).includes(value)) return value as T;
|
||||
throw new TypedModelError("workflows.errors.invalidFieldValue", `Invalid value for '${field}': ${String(value)}.`);
|
||||
}
|
||||
|
||||
function requireKontaktTyp(value: unknown): KontaktTyp {
|
||||
if (typeof value === "string" && (KONTAKT_TYP_VALUES as readonly string[]).includes(value)) {
|
||||
return value as KontaktTyp;
|
||||
}
|
||||
throw new TypedModelError(
|
||||
"workflows.errors.invalidFieldValue",
|
||||
`Kontakt requires 'kontaktTyp' to be one of: ${KONTAKT_TYP_VALUES.join(", ")}.`
|
||||
);
|
||||
}
|
||||
|
||||
function parseEmails(data: ModelRecord): CreateKontaktInput["emails"] {
|
||||
if (Array.isArray(data.emails)) {
|
||||
return data.emails
|
||||
.filter((e): e is { email: string; primaer?: boolean } => typeof e === "object" && e !== null && typeof (e as { email?: unknown }).email === "string")
|
||||
.map((e) => ({ email: e.email, primaer: e.primaer }));
|
||||
}
|
||||
const single = optString(data.primaerEmail) ?? optString(data.email);
|
||||
return single ? [{ email: single, primaer: true }] : undefined;
|
||||
}
|
||||
|
||||
function parseTelefone(data: ModelRecord): CreateKontaktInput["telefone"] {
|
||||
if (Array.isArray(data.telefone)) {
|
||||
return data.telefone
|
||||
.filter((t): t is { telefon: string; primaer?: boolean } => typeof t === "object" && t !== null && typeof (t as { telefon?: unknown }).telefon === "string")
|
||||
.map((t) => ({ telefon: t.telefon, primaer: t.primaer }));
|
||||
}
|
||||
const single = optString(data.primaerTelefon) ?? optString(data.telefon);
|
||||
return single ? [{ telefon: single, primaer: true }] : undefined;
|
||||
}
|
||||
|
||||
// --- serialization (replaces ApiHelper.getApiFormat) ------------------------
|
||||
|
||||
function kontaktToJson(k: KontaktRow): ModelRecord {
|
||||
return {
|
||||
id: k.id,
|
||||
kontaktTyp: k.kontaktTyp,
|
||||
kontaktStatus: k.kontaktStatus,
|
||||
vorname: k.vorname,
|
||||
nachname: k.nachname,
|
||||
orgName: k.orgName,
|
||||
orgMerkmal: k.orgMerkmal,
|
||||
primaerEmail: k.primaerEmail,
|
||||
primaerTelefon: k.primaerTelefon,
|
||||
zustaendigerUserId: k.zustaendigerUserId,
|
||||
createdAt: k.createdAt.toISOString(),
|
||||
updatedAt: k.updatedAt.toISOString(),
|
||||
archivedAt: k.archivedAt ? k.archivedAt.toISOString() : null,
|
||||
};
|
||||
}
|
||||
|
||||
export const kontaktAdapter: TypedModelAdapter = {
|
||||
key: "kontakt",
|
||||
labelKey: "crm.contacts.title",
|
||||
fieldSchema: kontaktFieldSchema,
|
||||
|
||||
async read(id, ctx) {
|
||||
const tenantId = requireTenant(ctx);
|
||||
const userId = ctx.userId ?? "system";
|
||||
try {
|
||||
const kontakt = await getVisibleKontaktOrThrow(tenantId, id, systemReadCtx(userId));
|
||||
return kontaktToJson(kontakt);
|
||||
} catch (error) {
|
||||
if (isNotFound(error)) return null;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
async create(data, ctx) {
|
||||
const tenantId = requireTenant(ctx);
|
||||
const userId = requireUser(ctx);
|
||||
const created = await createKontakt({
|
||||
tenantId,
|
||||
userId,
|
||||
kontaktTyp: requireKontaktTyp(data.kontaktTyp),
|
||||
kontaktStatus: optEnum(data.kontaktStatus, KONTAKT_STATUS_VALUES, "kontaktStatus") ?? undefined,
|
||||
vorname: optString(data.vorname),
|
||||
nachname: optString(data.nachname),
|
||||
orgName: optString(data.orgName),
|
||||
orgMerkmal: optEnum(data.orgMerkmal, ORG_MERKMAL_VALUES, "orgMerkmal"),
|
||||
zustaendigerUserId: optString(data.zustaendigerUserId),
|
||||
emails: parseEmails(data),
|
||||
telefone: parseTelefone(data),
|
||||
});
|
||||
await auditCrmEvent({ ctx: { tenantId, userId }, action: "kontakt.created", targetType: "kontakt", targetId: created.id });
|
||||
await logKontaktActivity({
|
||||
ctx: { tenantId, userId },
|
||||
kontaktId: created.id,
|
||||
kontaktTyp: created.kontaktTyp,
|
||||
activityType: "contact_created",
|
||||
summaryText: "Kontakt per Workflow angelegt",
|
||||
});
|
||||
return kontaktToJson(created);
|
||||
},
|
||||
|
||||
async update(id, data, ctx) {
|
||||
const tenantId = requireTenant(ctx);
|
||||
const userId = requireUser(ctx);
|
||||
// Ensure the contact exists/visible before mutating (parity with the old
|
||||
// get-then-update path); throws CatalogError.notFound otherwise.
|
||||
const existing = await getVisibleKontaktOrThrow(tenantId, id, systemReadCtx(userId));
|
||||
await updateKontakt({
|
||||
tenantId,
|
||||
kontaktId: id,
|
||||
kontaktStatus: optEnum(data.kontaktStatus, KONTAKT_STATUS_VALUES, "kontaktStatus") ?? undefined,
|
||||
vorname: optString(data.vorname),
|
||||
nachname: optString(data.nachname),
|
||||
orgName: optString(data.orgName),
|
||||
orgMerkmal: optEnum(data.orgMerkmal, ORG_MERKMAL_VALUES, "orgMerkmal"),
|
||||
});
|
||||
const updated = await getVisibleKontaktOrThrow(tenantId, id, systemReadCtx(userId));
|
||||
await auditCrmEvent({ ctx: { tenantId, userId }, action: "kontakt.updated", targetType: "kontakt", targetId: id });
|
||||
await logKontaktActivity({
|
||||
ctx: { tenantId, userId },
|
||||
kontaktId: id,
|
||||
kontaktTyp: existing.kontaktTyp,
|
||||
activityType: "contact_updated",
|
||||
summaryText: "Kontakt per Workflow aktualisiert",
|
||||
});
|
||||
return kontaktToJson(updated);
|
||||
},
|
||||
|
||||
async delete(id, ctx) {
|
||||
const tenantId = requireTenant(ctx);
|
||||
const userId = requireUser(ctx);
|
||||
const snapshot = await getVisibleKontaktOrThrow(tenantId, id, systemReadCtx(userId));
|
||||
await hardDeleteKontakt({ tenantId, kontaktId: id });
|
||||
await auditCrmEvent({ ctx: { tenantId, userId }, action: "kontakt.deleted", targetType: "kontakt", targetId: id });
|
||||
return kontaktToJson(snapshot);
|
||||
},
|
||||
};
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
createKontakt: vi.fn(),
|
||||
getVisibleKontaktOrThrow: vi.fn(),
|
||||
updateKontakt: vi.fn(),
|
||||
hardDeleteKontakt: vi.fn(),
|
||||
auditCrmEvent: vi.fn(),
|
||||
logKontaktActivity: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/integrations/crm/crmService.server", () => ({
|
||||
createKontakt: mocks.createKontakt,
|
||||
getVisibleKontaktOrThrow: mocks.getVisibleKontaktOrThrow,
|
||||
updateKontakt: mocks.updateKontakt,
|
||||
hardDeleteKontakt: mocks.hardDeleteKontakt,
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/integrations/crm/crmAudit.server", () => ({
|
||||
auditCrmEvent: mocks.auditCrmEvent,
|
||||
logKontaktActivity: mocks.logKontaktActivity,
|
||||
}));
|
||||
|
||||
import { getModelAdapter, getModelAdapterOrThrow, isAddressableModel, listModelKeys } from "./registry.server";
|
||||
import { TypedModelError } from "./types";
|
||||
|
||||
const kontaktRow = {
|
||||
id: "k-1",
|
||||
tenantId: "tenant-1",
|
||||
createdByUserId: "user-1",
|
||||
kontaktTyp: "privatperson" as const,
|
||||
kontaktStatus: "kontakt" as const,
|
||||
vorname: "Max",
|
||||
nachname: "Mustermann",
|
||||
orgName: null,
|
||||
orgMerkmal: null,
|
||||
primaerEmail: "max@example.com",
|
||||
primaerTelefon: null,
|
||||
adresseId: null,
|
||||
zustaendigerUserId: "user-1",
|
||||
isDemoData: false,
|
||||
createdAt: new Date("2026-06-30T10:00:00.000Z"),
|
||||
updatedAt: new Date("2026-06-30T11:00:00.000Z"),
|
||||
archivedAt: null,
|
||||
};
|
||||
|
||||
const ctx = { tenantId: "tenant-1", userId: "user-1" };
|
||||
|
||||
describe("typed model registry", () => {
|
||||
test("kontakt is addressable; unknown keys are not", () => {
|
||||
expect(listModelKeys()).toContain("kontakt");
|
||||
expect(isAddressableModel("kontakt")).toBe(true);
|
||||
expect(isAddressableModel("projekt")).toBe(false);
|
||||
expect(getModelAdapter("kontakt")?.key).toBe("kontakt");
|
||||
expect(getModelAdapter("projekt")).toBeUndefined();
|
||||
});
|
||||
|
||||
test("getModelAdapterOrThrow throws a Klartext error for an unaddressable model", () => {
|
||||
expect(() => getModelAdapterOrThrow("projekt")).toThrow(TypedModelError);
|
||||
});
|
||||
});
|
||||
|
||||
describe("kontakt adapter", () => {
|
||||
const adapter = getModelAdapterOrThrow("kontakt");
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.createKontakt.mockResolvedValue(kontaktRow);
|
||||
mocks.getVisibleKontaktOrThrow.mockResolvedValue(kontaktRow);
|
||||
mocks.updateKontakt.mockResolvedValue(undefined);
|
||||
mocks.hardDeleteKontakt.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
test("create maps the payload, audits and serializes dates to ISO", async () => {
|
||||
const result = await adapter.create({ kontaktTyp: "privatperson", vorname: "Max", primaerEmail: "max@example.com" }, ctx);
|
||||
|
||||
expect(mocks.createKontakt).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tenantId: "tenant-1",
|
||||
userId: "user-1",
|
||||
kontaktTyp: "privatperson",
|
||||
vorname: "Max",
|
||||
emails: [{ email: "max@example.com", primaer: true }],
|
||||
})
|
||||
);
|
||||
expect(mocks.auditCrmEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ action: "kontakt.created", targetType: "kontakt", targetId: "k-1" })
|
||||
);
|
||||
expect(result).toMatchObject({ id: "k-1", createdAt: "2026-06-30T10:00:00.000Z", archivedAt: null });
|
||||
});
|
||||
|
||||
test("create rejects a missing/invalid kontaktTyp with a Klartext error", async () => {
|
||||
await expect(adapter.create({ vorname: "Max" }, ctx)).rejects.toBeInstanceOf(TypedModelError);
|
||||
expect(mocks.createKontakt).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("create without a user context throws (createdByUserId required)", async () => {
|
||||
await expect(adapter.create({ kontaktTyp: "privatperson" }, { tenantId: "tenant-1", userId: null })).rejects.toBeInstanceOf(
|
||||
TypedModelError
|
||||
);
|
||||
});
|
||||
|
||||
test("read returns the serialized record", async () => {
|
||||
const result = await adapter.read("k-1", ctx);
|
||||
expect(result).toMatchObject({ id: "k-1", vorname: "Max" });
|
||||
});
|
||||
|
||||
test("read returns null when the contact is not found", async () => {
|
||||
mocks.getVisibleKontaktOrThrow.mockRejectedValueOnce(new CatalogError(foundationErrors.notFound, { kontaktId: "k-x" }));
|
||||
expect(await adapter.read("k-x", ctx)).toBeNull();
|
||||
});
|
||||
|
||||
test("update mutates only typed fields and audits", async () => {
|
||||
await adapter.update("k-1", { nachname: "Neumann", kontaktStatus: "kunde" }, ctx);
|
||||
expect(mocks.updateKontakt).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ tenantId: "tenant-1", kontaktId: "k-1", nachname: "Neumann", kontaktStatus: "kunde" })
|
||||
);
|
||||
expect(mocks.auditCrmEvent).toHaveBeenCalledWith(expect.objectContaining({ action: "kontakt.updated", targetId: "k-1" }));
|
||||
});
|
||||
|
||||
test("delete reads a snapshot, hard-deletes and audits", async () => {
|
||||
const snapshot = await adapter.delete("k-1", ctx);
|
||||
expect(mocks.hardDeleteKontakt).toHaveBeenCalledWith({ tenantId: "tenant-1", kontaktId: "k-1" });
|
||||
expect(mocks.auditCrmEvent).toHaveBeenCalledWith(expect.objectContaining({ action: "kontakt.deleted", targetId: "k-1" }));
|
||||
expect(snapshot).toMatchObject({ id: "k-1" });
|
||||
});
|
||||
});
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
// Typed model registry (R-P14C-T2 / R-P14D, AD-2) — the registry itself.
|
||||
//
|
||||
// The typed replacement for `EntitiesSingleton.getEntity({ name })`: address an
|
||||
// addressable model by its stable key and get a `TypedModelAdapter` over a real
|
||||
// typed Prisma model. Starts with `Kontakt`; the kern chain registers further
|
||||
// models (Projekt, Rechnung, …) here as they are built — same convention as the
|
||||
// global-search `indexedEntities` registry.
|
||||
//
|
||||
// This is also the seam R-P6B-β builds on: the remaining EntitiesSingleton
|
||||
// consumers migrate onto `listModelAdapters()` / `fieldSchema` here.
|
||||
|
||||
import { kontaktAdapter } from "./kontaktAdapter.server";
|
||||
import type { TypedModelAdapter } from "./types";
|
||||
import { TypedModelError } from "./types";
|
||||
|
||||
/** Registered adapters, keyed by their stable address key. Grows module by module. */
|
||||
const MODEL_ADAPTERS = {
|
||||
[kontaktAdapter.key]: kontaktAdapter,
|
||||
} satisfies Record<string, TypedModelAdapter>;
|
||||
|
||||
/** Stable address keys of all registered models (e.g. for editor dropdowns). */
|
||||
export function listModelKeys(): string[] {
|
||||
return Object.keys(MODEL_ADAPTERS);
|
||||
}
|
||||
|
||||
/** All registered adapters, in registration order. */
|
||||
export function listModelAdapters(): TypedModelAdapter[] {
|
||||
return Object.values(MODEL_ADAPTERS);
|
||||
}
|
||||
|
||||
/** Look up an adapter by key; `undefined` when the model is not addressable. */
|
||||
export function getModelAdapter(key: string): TypedModelAdapter | undefined {
|
||||
return MODEL_ADAPTERS[key];
|
||||
}
|
||||
|
||||
/** True when `key` addresses a registered model. */
|
||||
export function isAddressableModel(key: string): boolean {
|
||||
return key in MODEL_ADAPTERS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up an adapter or throw a Klartext error (M002) — never a silent fail.
|
||||
* Used by the WorkflowEngine row* blocks: an unknown/unaddressable model key
|
||||
* surfaces as a clear error instead of a swallowed lookup.
|
||||
*/
|
||||
export function getModelAdapterOrThrow(key: string): TypedModelAdapter {
|
||||
const adapter = MODEL_ADAPTERS[key];
|
||||
if (!adapter) {
|
||||
throw new TypedModelError(
|
||||
"workflows.errors.unknownModel",
|
||||
`Model '${key}' is not addressable. Addressable models: ${listModelKeys().join(", ") || "(none)"}.`
|
||||
);
|
||||
}
|
||||
return adapter;
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
// Typed model registry (R-P14C-T2 / R-P14D, AD-2) — shared building block.
|
||||
//
|
||||
// The generic entity-builder exposed `EntitiesSingleton.getEntity({ name })`
|
||||
// (generic entity metadata) + `RowsApi.*` (generic CRUD over `Row`). Its typed
|
||||
// replacement is this registry: a stable address key → a `TypedModelAdapter`
|
||||
// over a real, typed Prisma model (R-P6 `Kontakt`, later `Projekt`/… as the
|
||||
// kern chain builds them). Consumers (WorkflowEngine row* blocks today; the
|
||||
// broader EntitiesSingleton consumers in R-P6B-β) address a model by key and
|
||||
// CRUD through typed services instead of the polymorphic row engine.
|
||||
//
|
||||
// Pure types live here (no runtime/server deps) so they can be referenced from
|
||||
// DTOs/tests without pulling server-only code; the adapters + registry are
|
||||
// `.server.ts` because they call the tenant-scoped domain services.
|
||||
|
||||
/** Coarse field kind for the typed `fieldSchema` (replaces PropertyWithDetails). */
|
||||
export type FieldType = "string" | "number" | "boolean" | "date" | "enum";
|
||||
|
||||
/** One field of a model's typed schema. */
|
||||
export type FieldSchemaEntry = {
|
||||
type: FieldType;
|
||||
/** Required on create. */
|
||||
required?: boolean;
|
||||
/** Server-managed; never accepted from a create/update payload. */
|
||||
readonly?: boolean;
|
||||
/** May be null. */
|
||||
nullable?: boolean;
|
||||
/** Allowed values when `type === "enum"`. */
|
||||
enum?: readonly string[];
|
||||
};
|
||||
|
||||
/** A model's typed field schema, keyed by field name. */
|
||||
export type FieldSchema = Record<string, FieldSchemaEntry>;
|
||||
|
||||
/**
|
||||
* A model record serialized to a plain JSON object — the shape a workflow row*
|
||||
* block reads/writes (replaces `ApiHelper.getApiFormat` / `getRowPropertiesFromJson`).
|
||||
*/
|
||||
export type ModelRecord = Record<string, unknown>;
|
||||
|
||||
/**
|
||||
* Execution context for a model operation. Automation/system actors (a workflow
|
||||
* run) carry the tenant they operate in and, for writes, the triggering user.
|
||||
*/
|
||||
export type ModelCtx = {
|
||||
tenantId: string | null;
|
||||
userId: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Typed CRUD adapter for one addressable model. All ops are tenant-scoped (the
|
||||
* underlying domain service runs inside `withTenantRLS`) and write the M001 audit
|
||||
* + activity trail. `read` returns `null` when the record is absent/not visible
|
||||
* (parity with the old generic `RowsApi.get(...).catch(() => null)`); writes throw
|
||||
* a `TypedModelError` (Klartext, M002) on a missing/invalid payload or context.
|
||||
*/
|
||||
export interface TypedModelAdapter {
|
||||
/** Stable address key, e.g. "kontakt". */
|
||||
key: string;
|
||||
/** i18n key for the human label of this model. */
|
||||
labelKey: string;
|
||||
/** Typed field schema (replaces generic `Property` rows). */
|
||||
fieldSchema: FieldSchema;
|
||||
read(id: string, ctx: ModelCtx): Promise<ModelRecord | null>;
|
||||
create(data: ModelRecord, ctx: ModelCtx): Promise<ModelRecord>;
|
||||
update(id: string, data: ModelRecord, ctx: ModelCtx): Promise<ModelRecord>;
|
||||
delete(id: string, ctx: ModelCtx): Promise<ModelRecord>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Klartext domain error (M002) for the registry: an unaddressable model, or a
|
||||
* write attempted without the required tenant/user context or a required field.
|
||||
* Carries an i18n `messageKey` (mirrors `CrmServiceError` / `WorkflowTemplateImportError`)
|
||||
* so callers can map it to a catalog message instead of leaking a bare code.
|
||||
*/
|
||||
export class TypedModelError extends Error {
|
||||
override readonly name = "TypedModelError";
|
||||
readonly messageKey: string;
|
||||
constructor(messageKey: string, message: string) {
|
||||
super(message);
|
||||
this.messageKey = messageKey;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user