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
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "@toolctrl/view-models",
|
||||
"name": "@hivegrid/view-models",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { billingReadOnlyReasonKey, buildAdminBillingVM, normalizeAdminBillingStatus, type AdminBillingInputRow } from "./billing-admin.vm.js";
|
||||
|
||||
function row(overrides: Partial<AdminBillingInputRow> = {}): AdminBillingInputRow {
|
||||
return {
|
||||
tenantId: "tenant_1",
|
||||
tenantName: "Acme",
|
||||
tenantSlug: "acme",
|
||||
status: "active",
|
||||
readOnly: false,
|
||||
planCode: "starter",
|
||||
seatQuantity: 3,
|
||||
lagoCustomerId: "lago_1",
|
||||
mollieCustomerId: "mollie_1",
|
||||
lastInvoiceExternalId: "invoice_1",
|
||||
lastPaymentExternalId: "payment_1",
|
||||
currentPeriodStart: "2026-07-01T00:00:00.000Z",
|
||||
currentPeriodEnd: "2026-08-01T00:00:00.000Z",
|
||||
pastDueSince: null,
|
||||
frozenAt: null,
|
||||
cancelledAt: null,
|
||||
entitlementCount: 4,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("normalizeAdminBillingStatus", () => {
|
||||
it("falls back to trial for unknown provider values", () => {
|
||||
expect(normalizeAdminBillingStatus("paused")).toBe("trial");
|
||||
expect(normalizeAdminBillingStatus(null)).toBe("trial");
|
||||
});
|
||||
});
|
||||
|
||||
describe("billingReadOnlyReasonKey", () => {
|
||||
it("surfaces the specific read-only reason", () => {
|
||||
expect(billingReadOnlyReasonKey({ status: "past_due", readOnly: true, pastDueSince: null, frozenAt: null, cancelledAt: null })).toBe(
|
||||
"admin.billing.readOnlyReasons.pastDue"
|
||||
);
|
||||
expect(billingReadOnlyReasonKey({ status: "frozen", readOnly: true, pastDueSince: null, frozenAt: "2026-07-01", cancelledAt: null })).toBe(
|
||||
"admin.billing.readOnlyReasons.frozen"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildAdminBillingVM", () => {
|
||||
it("returns empty for no tenants", () => {
|
||||
expect(buildAdminBillingVM({ rows: [] })).toEqual({ status: "empty" });
|
||||
});
|
||||
|
||||
it("builds operator rows with provider flags and labels", () => {
|
||||
const vm = buildAdminBillingVM({
|
||||
rows: [row(), row({ tenantId: "tenant_2", status: "past_due", readOnly: true, mollieCustomerId: null, lastPaymentExternalId: null })],
|
||||
});
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.totalCount).toBe(2);
|
||||
expect(vm.data?.readOnlyCount).toBe(1);
|
||||
expect(vm.data?.rows[0]?.statusLabelKey).toBe("admin.billing.status.active");
|
||||
expect(vm.data?.rows[0]?.hasLagoReference).toBe(true);
|
||||
expect(vm.data?.rows[1]?.hasMollieReference).toBe(false);
|
||||
expect(vm.data?.rows[1]?.recoveryHintKey).toBe("admin.billing.recoveryHints.pastDue");
|
||||
});
|
||||
});
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
export type AdminBillingStatus = "trial" | "active" | "past_due" | "cancelled" | "frozen";
|
||||
|
||||
export type AdminBillingInputRow = {
|
||||
readonly tenantId: string;
|
||||
readonly tenantName: string;
|
||||
readonly tenantSlug: string;
|
||||
readonly status: string | null;
|
||||
readonly readOnly: boolean;
|
||||
readonly planCode: string | null;
|
||||
readonly seatQuantity: number | null;
|
||||
readonly lagoCustomerId: string | null;
|
||||
readonly mollieCustomerId: string | null;
|
||||
readonly lastInvoiceExternalId: string | null;
|
||||
readonly lastPaymentExternalId: string | null;
|
||||
readonly currentPeriodStart: string | null;
|
||||
readonly currentPeriodEnd: string | null;
|
||||
readonly pastDueSince: string | null;
|
||||
readonly frozenAt: string | null;
|
||||
readonly cancelledAt: string | null;
|
||||
readonly entitlementCount: number;
|
||||
};
|
||||
|
||||
export type AdminBillingRow = AdminBillingInputRow & {
|
||||
readonly status: AdminBillingStatus;
|
||||
readonly statusLabelKey: string;
|
||||
readonly readOnlyReasonKey: string;
|
||||
readonly recoveryHintKey: string;
|
||||
readonly providerSummaryKey: string;
|
||||
readonly hasLagoReference: boolean;
|
||||
readonly hasMollieReference: boolean;
|
||||
};
|
||||
|
||||
export type AdminBillingData = {
|
||||
readonly rows: readonly AdminBillingRow[];
|
||||
readonly totalCount: number;
|
||||
readonly readOnlyCount: number;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
};
|
||||
|
||||
export type AdminBillingVM = VMState<AdminBillingData>;
|
||||
|
||||
const BILLING_STATUSES: ReadonlySet<string> = new Set(["trial", "active", "past_due", "cancelled", "frozen"]);
|
||||
|
||||
export function normalizeAdminBillingStatus(status: string | null | undefined): AdminBillingStatus {
|
||||
return BILLING_STATUSES.has(status ?? "") ? (status as AdminBillingStatus) : "trial";
|
||||
}
|
||||
|
||||
export function billingReadOnlyReasonKey(
|
||||
row: Pick<AdminBillingInputRow, "readOnly" | "pastDueSince" | "frozenAt" | "cancelledAt"> & { status: AdminBillingStatus }
|
||||
): string {
|
||||
if (!row.readOnly) return "admin.billing.readOnlyReasons.none";
|
||||
if (row.cancelledAt || row.status === "cancelled") return "admin.billing.readOnlyReasons.cancelled";
|
||||
if (row.frozenAt || row.status === "frozen") return "admin.billing.readOnlyReasons.frozen";
|
||||
if (row.pastDueSince || row.status === "past_due") return "admin.billing.readOnlyReasons.pastDue";
|
||||
return "admin.billing.readOnlyReasons.generic";
|
||||
}
|
||||
|
||||
export function billingRecoveryHintKey(status: AdminBillingStatus): string {
|
||||
if (status === "past_due") return "admin.billing.recoveryHints.pastDue";
|
||||
if (status === "frozen") return "admin.billing.recoveryHints.frozen";
|
||||
if (status === "cancelled") return "admin.billing.recoveryHints.cancelled";
|
||||
return "admin.billing.recoveryHints.none";
|
||||
}
|
||||
|
||||
export function buildAdminBillingVM(input: { readonly rows: readonly AdminBillingInputRow[] }): AdminBillingVM {
|
||||
if (input.rows.length === 0) {
|
||||
return { status: "empty" };
|
||||
}
|
||||
|
||||
const rows = input.rows.map((row): AdminBillingRow => {
|
||||
const status = normalizeAdminBillingStatus(row.status);
|
||||
return {
|
||||
...row,
|
||||
status,
|
||||
seatQuantity: row.seatQuantity && row.seatQuantity > 0 ? row.seatQuantity : 1,
|
||||
statusLabelKey: `admin.billing.status.${status}`,
|
||||
readOnlyReasonKey: billingReadOnlyReasonKey({ ...row, status }),
|
||||
recoveryHintKey: billingRecoveryHintKey(status),
|
||||
providerSummaryKey: row.lagoCustomerId || row.mollieCustomerId ? "admin.billing.providerSummary.connected" : "admin.billing.providerSummary.missing",
|
||||
hasLagoReference: Boolean(row.lagoCustomerId),
|
||||
hasMollieReference: Boolean(row.mollieCustomerId || row.lastPaymentExternalId),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows,
|
||||
totalCount: rows.length,
|
||||
readOnlyCount: rows.filter((row) => row.readOnly).length,
|
||||
emptyHeadlineKey: "admin.billing.empty.headline",
|
||||
emptyBodyKey: "admin.billing.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildQueueMonitorVM, deriveQueueHealthSignal, type QueueCountsInput } from "./queue-monitor.vm.js";
|
||||
|
||||
function queue(overrides: Partial<QueueCountsInput>): QueueCountsInput {
|
||||
return {
|
||||
queueName: "hivegrid.email",
|
||||
group: "mail",
|
||||
active: 0,
|
||||
waiting: 0,
|
||||
delayed: 0,
|
||||
failed: 0,
|
||||
completed: 0,
|
||||
paused: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("deriveQueueHealthSignal", () => {
|
||||
it("paused wins over failed", () => {
|
||||
expect(deriveQueueHealthSignal({ failed: 5, paused: true })).toBe("paused");
|
||||
});
|
||||
it("warns on failed jobs", () => {
|
||||
expect(deriveQueueHealthSignal({ failed: 1, paused: false })).toBe("warn");
|
||||
});
|
||||
it("ok when clean", () => {
|
||||
expect(deriveQueueHealthSignal({ failed: 0, paused: false })).toBe("ok");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildQueueMonitorVM", () => {
|
||||
it("returns empty for no queues", () => {
|
||||
expect(buildQueueMonitorVM({ queues: [] })).toEqual({ status: "empty" });
|
||||
});
|
||||
|
||||
it("aggregates totals and surfaces the worst overall signal (warn > paused)", () => {
|
||||
const vm = buildQueueMonitorVM({
|
||||
queues: [
|
||||
queue({ queueName: "hivegrid.email", failed: 0, paused: true }),
|
||||
queue({ queueName: "hivegrid.imports", group: "import", failed: 3 }),
|
||||
queue({ queueName: "hivegrid.exports", group: "import", failed: 0 }),
|
||||
],
|
||||
});
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.failedTotal).toBe(3);
|
||||
expect(vm.data?.pausedCount).toBe(1);
|
||||
expect(vm.data?.overallSignal).toBe("warn");
|
||||
expect(vm.data?.overallLabelKey).toBe("admin.queues.health.warn");
|
||||
const email = vm.data?.rows.find((r) => r.queueName === "hivegrid.email");
|
||||
expect(email?.healthSignal).toBe("paused");
|
||||
expect(email?.groupLabelKey).toBe("admin.queues.group.mail");
|
||||
});
|
||||
|
||||
it("overall is paused when worst case is a paused (no failures) queue", () => {
|
||||
const vm = buildQueueMonitorVM({
|
||||
queues: [queue({ paused: true }), queue({ queueName: "hivegrid.notifications", group: "general" })],
|
||||
});
|
||||
expect(vm.data?.overallSignal).toBe("paused");
|
||||
});
|
||||
});
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* AK-P19 — Queue-Monitor view-model (DoD #6). Pure function: the admin
|
||||
* health/workers loader reads BullMQ job counts and builds this once; the
|
||||
* UI only renders. No React, no Prisma, no BullMQ here (DoD A.3) — the live
|
||||
* Redis read lives in the server inspector.
|
||||
*
|
||||
* Health per queue is a Klartext signal, not a raw number dump:
|
||||
* - `paused` when the queue is paused (operator stopped consumption),
|
||||
* - `warn` when there are failed jobs needing attention,
|
||||
* - `ok` otherwise.
|
||||
* The overall signal is the worst queue signal across the fleet.
|
||||
*/
|
||||
|
||||
export type QueueHealthSignal = "ok" | "warn" | "paused";
|
||||
|
||||
export type QueueCountsInput = {
|
||||
readonly queueName: string;
|
||||
readonly group: string;
|
||||
readonly active: number;
|
||||
readonly waiting: number;
|
||||
readonly delayed: number;
|
||||
readonly failed: number;
|
||||
readonly completed: number;
|
||||
readonly paused: boolean;
|
||||
};
|
||||
|
||||
export type QueueMonitorRow = QueueCountsInput & {
|
||||
readonly groupLabelKey: string;
|
||||
readonly healthSignal: QueueHealthSignal;
|
||||
readonly healthLabelKey: string;
|
||||
};
|
||||
|
||||
export interface QueueMonitorData {
|
||||
readonly rows: readonly QueueMonitorRow[];
|
||||
readonly overallSignal: QueueHealthSignal;
|
||||
readonly overallLabelKey: string;
|
||||
readonly failedTotal: number;
|
||||
readonly pausedCount: number;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type QueueMonitorVM = VMState<QueueMonitorData>;
|
||||
|
||||
/** Per-queue Klartext health signal from counts + paused flag. */
|
||||
export function deriveQueueHealthSignal(input: Pick<QueueCountsInput, "failed" | "paused">): QueueHealthSignal {
|
||||
if (input.paused) return "paused";
|
||||
if (input.failed > 0) return "warn";
|
||||
return "ok";
|
||||
}
|
||||
|
||||
// Worst-first ranking so the overall signal surfaces the most urgent state.
|
||||
const SIGNAL_SEVERITY: Record<QueueHealthSignal, number> = { ok: 0, paused: 1, warn: 2 };
|
||||
|
||||
export function buildQueueMonitorVM(input: { readonly queues: readonly QueueCountsInput[] }): QueueMonitorVM {
|
||||
if (input.queues.length === 0) {
|
||||
return { status: "empty" };
|
||||
}
|
||||
const rows: QueueMonitorRow[] = input.queues.map((queue) => {
|
||||
const healthSignal = deriveQueueHealthSignal(queue);
|
||||
return {
|
||||
...queue,
|
||||
groupLabelKey: `admin.queues.group.${queue.group}`,
|
||||
healthSignal,
|
||||
healthLabelKey: `admin.queues.health.${healthSignal}`,
|
||||
};
|
||||
});
|
||||
|
||||
const overallSignal = rows.reduce<QueueHealthSignal>(
|
||||
(worst, row) => (SIGNAL_SEVERITY[row.healthSignal] > SIGNAL_SEVERITY[worst] ? row.healthSignal : worst),
|
||||
"ok"
|
||||
);
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows,
|
||||
overallSignal,
|
||||
overallLabelKey: `admin.queues.health.${overallSignal}`,
|
||||
failedTotal: rows.reduce((sum, row) => sum + row.failed, 0),
|
||||
pausedCount: rows.filter((row) => row.paused).length,
|
||||
emptyHeadlineKey: "admin.queues.empty.headline",
|
||||
emptyBodyKey: "admin.queues.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildAdminConnectorListVM,
|
||||
normalizeConnectorOverrideState,
|
||||
resolveEffectiveConnectorState,
|
||||
type AdminConnectorInputRow,
|
||||
} from "./subscription-connectors.vm.js";
|
||||
|
||||
function row(overrides: Partial<AdminConnectorInputRow>): AdminConnectorInputRow {
|
||||
return { featureKey: "files", toggleable: true, baseEnabled: true, overrideState: null, ...overrides };
|
||||
}
|
||||
|
||||
describe("normalizeConnectorOverrideState", () => {
|
||||
it("keeps enabled/disabled, maps everything else to inherit", () => {
|
||||
expect(normalizeConnectorOverrideState("enabled")).toBe("enabled");
|
||||
expect(normalizeConnectorOverrideState("disabled")).toBe("disabled");
|
||||
expect(normalizeConnectorOverrideState("inherit")).toBe("inherit");
|
||||
expect(normalizeConnectorOverrideState(null)).toBe("inherit");
|
||||
expect(normalizeConnectorOverrideState("garbage")).toBe("inherit");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveEffectiveConnectorState", () => {
|
||||
it("override wins over the base default", () => {
|
||||
expect(resolveEffectiveConnectorState(false, "enabled")).toBe(true);
|
||||
expect(resolveEffectiveConnectorState(true, "disabled")).toBe(false);
|
||||
});
|
||||
it("inherit falls back to the base default", () => {
|
||||
expect(resolveEffectiveConnectorState(true, "inherit")).toBe(true);
|
||||
expect(resolveEffectiveConnectorState(false, "inherit")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildAdminConnectorListVM", () => {
|
||||
it("returns empty for no rows", () => {
|
||||
expect(buildAdminConnectorListVM({ rows: [] })).toEqual({ status: "empty" });
|
||||
});
|
||||
|
||||
it("derives effective state + override divergence and counts", () => {
|
||||
const vm = buildAdminConnectorListVM({
|
||||
rows: [
|
||||
row({ featureKey: "files", baseEnabled: true, overrideState: "disabled" }), // overridden off
|
||||
row({ featureKey: "api", baseEnabled: false, overrideState: "enabled" }), // overridden on
|
||||
row({ featureKey: "tasks", baseEnabled: true, overrideState: null }), // inherits on
|
||||
row({ featureKey: "crm-basic", baseEnabled: true, overrideState: "enabled", toggleable: false }), // explicit but matches base
|
||||
],
|
||||
});
|
||||
expect(vm.status).toBe("ready");
|
||||
const byKey = Object.fromEntries((vm.data?.rows ?? []).map((r) => [r.featureKey, r]));
|
||||
expect(byKey.files.effectiveEnabled).toBe(false);
|
||||
expect(byKey.files.overridden).toBe(true);
|
||||
expect(byKey.files.labelKey).toBe("admin.connectors.feature.files");
|
||||
expect(byKey.api.effectiveEnabled).toBe(true);
|
||||
expect(byKey.api.overridden).toBe(true);
|
||||
expect(byKey.tasks.overridden).toBe(false);
|
||||
// explicit override that equals the base default is not "overridden"
|
||||
expect(byKey["crm-basic"].overridden).toBe(false);
|
||||
expect(byKey["crm-basic"].toggleable).toBe(false);
|
||||
expect(vm.data?.enabledCount).toBe(3); // api, tasks, crm-basic
|
||||
expect(vm.data?.overriddenCount).toBe(2); // files, api
|
||||
});
|
||||
});
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* AK-P19 — Abo-Baukasten connector view-model (DoD #3). Pure function: the
|
||||
* admin tenant-detail loader builds it once, the UI only renders. No
|
||||
* React, no Prisma, no app imports (DoD A.3).
|
||||
*
|
||||
* A "connector" is one product-blueprint feature an operator can switch on
|
||||
* or off per tenant (the Abo-Baukasten mechanic, foundation for AK-P20).
|
||||
* The effective state is the per-tenant override when set, otherwise the
|
||||
* blueprint default. Non-toggleable features are shown read-only so the
|
||||
* operator sees the full entitlement surface but cannot break a core gate.
|
||||
*/
|
||||
|
||||
export type ConnectorOverrideState = "enabled" | "disabled" | "inherit";
|
||||
|
||||
export type AdminConnectorRow = {
|
||||
readonly featureKey: string;
|
||||
/** i18n key for the connector label, e.g. `admin.connectors.feature.files`. */
|
||||
readonly labelKey: string;
|
||||
/** Whether the operator may override this feature per tenant. */
|
||||
readonly toggleable: boolean;
|
||||
/** Blueprint default (what the tenant gets with no override). */
|
||||
readonly baseEnabled: boolean;
|
||||
/** The stored per-tenant override (`inherit` = no override). */
|
||||
readonly overrideState: ConnectorOverrideState;
|
||||
/** Resolved on/off the tenant actually experiences. */
|
||||
readonly effectiveEnabled: boolean;
|
||||
/** True when an explicit override diverges from the blueprint default. */
|
||||
readonly overridden: boolean;
|
||||
};
|
||||
|
||||
export interface AdminConnectorListData {
|
||||
readonly rows: readonly AdminConnectorRow[];
|
||||
readonly enabledCount: number;
|
||||
readonly overriddenCount: number;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type AdminConnectorListVM = VMState<AdminConnectorListData>;
|
||||
|
||||
/** Framework-free input row: blueprint feature + the tenant's stored override. */
|
||||
export interface AdminConnectorInputRow {
|
||||
readonly featureKey: string;
|
||||
readonly toggleable: boolean;
|
||||
readonly baseEnabled: boolean;
|
||||
readonly overrideState: string | null;
|
||||
}
|
||||
|
||||
export interface BuildAdminConnectorListVMInput {
|
||||
readonly rows: readonly AdminConnectorInputRow[];
|
||||
}
|
||||
|
||||
/** Normalizes a raw override string onto a known {@link ConnectorOverrideState}. */
|
||||
export function normalizeConnectorOverrideState(value: string | null | undefined): ConnectorOverrideState {
|
||||
return value === "enabled" || value === "disabled" ? value : "inherit";
|
||||
}
|
||||
|
||||
/** Resolves the on/off a tenant experiences from base default + override. */
|
||||
export function resolveEffectiveConnectorState(baseEnabled: boolean, override: ConnectorOverrideState): boolean {
|
||||
if (override === "enabled") return true;
|
||||
if (override === "disabled") return false;
|
||||
return baseEnabled;
|
||||
}
|
||||
|
||||
export function buildAdminConnectorListVM(input: BuildAdminConnectorListVMInput): AdminConnectorListVM {
|
||||
if (input.rows.length === 0) {
|
||||
return { status: "empty" };
|
||||
}
|
||||
const rows: AdminConnectorRow[] = input.rows.map((row) => {
|
||||
const overrideState = normalizeConnectorOverrideState(row.overrideState);
|
||||
const effectiveEnabled = resolveEffectiveConnectorState(row.baseEnabled, overrideState);
|
||||
return {
|
||||
featureKey: row.featureKey,
|
||||
labelKey: `admin.connectors.feature.${row.featureKey}`,
|
||||
toggleable: row.toggleable,
|
||||
baseEnabled: row.baseEnabled,
|
||||
overrideState,
|
||||
effectiveEnabled,
|
||||
overridden: overrideState !== "inherit" && effectiveEnabled !== row.baseEnabled,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows,
|
||||
enabledCount: rows.filter((row) => row.effectiveEnabled).length,
|
||||
overriddenCount: rows.filter((row) => row.overridden).length,
|
||||
emptyHeadlineKey: "admin.connectors.empty.headline",
|
||||
emptyBodyKey: "admin.connectors.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildSupportConversationVM, type SupportConversationInputMessage } from "./support-conversation.vm.js";
|
||||
|
||||
function msg(overrides: Partial<SupportConversationInputMessage>): SupportConversationInputMessage {
|
||||
return {
|
||||
id: "m1",
|
||||
createdAtIso: "2026-06-20T10:00:00.000Z",
|
||||
internalNote: false,
|
||||
authorEmail: null,
|
||||
authorId: null,
|
||||
body: "hello",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("authorLabelFor fallback chain (support-conversation.ts:64-65)", () => {
|
||||
it("uses the trimmed author id when no email is present", () => {
|
||||
const vm = buildSupportConversationVM({
|
||||
ticketId: "t1",
|
||||
subject: "s",
|
||||
status: "open",
|
||||
priority: "normal",
|
||||
messages: [msg({ id: "reply", authorEmail: null, authorId: " op_7 " })],
|
||||
});
|
||||
expect(vm.status).toBe("ready");
|
||||
const message = vm.data?.messages[0];
|
||||
// Having an id makes it a reply (not an inbound customer message).
|
||||
expect(message?.kind).toBe("reply");
|
||||
expect(message?.authorLabel).toBe("op_7");
|
||||
});
|
||||
|
||||
it("uses the unknown-author key for an internal note that has no email or id", () => {
|
||||
const vm = buildSupportConversationVM({
|
||||
ticketId: "t1",
|
||||
subject: "s",
|
||||
status: "open",
|
||||
priority: "normal",
|
||||
messages: [msg({ id: "note", internalNote: true, authorEmail: null, authorId: null })],
|
||||
});
|
||||
const message = vm.data?.messages[0];
|
||||
// internalNote stays an internalNote even without an author -> non-inbound branch.
|
||||
expect(message?.kind).toBe("internalNote");
|
||||
expect(message?.authorLabel).toBe("admin.support.author.unknown");
|
||||
expect(vm.data?.internalNoteCount).toBe(1);
|
||||
});
|
||||
});
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildSupportConversationVM, type SupportConversationInputMessage } from "./support-conversation.vm.js";
|
||||
|
||||
function msg(overrides: Partial<SupportConversationInputMessage>): SupportConversationInputMessage {
|
||||
return {
|
||||
id: "m1",
|
||||
createdAtIso: "2026-06-20T10:00:00.000Z",
|
||||
internalNote: false,
|
||||
authorEmail: null,
|
||||
authorId: null,
|
||||
body: "hello",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildSupportConversationVM", () => {
|
||||
it("orders messages oldest-first and classifies kind", () => {
|
||||
const vm = buildSupportConversationVM({
|
||||
ticketId: "t1",
|
||||
subject: "Login broken",
|
||||
status: "open",
|
||||
priority: "high",
|
||||
messages: [
|
||||
msg({ id: "reply", createdAtIso: "2026-06-21T10:00:00.000Z", authorEmail: "ops@hivegrid.de" }),
|
||||
msg({ id: "inbound", createdAtIso: "2026-06-20T09:00:00.000Z", authorEmail: null, authorId: null }),
|
||||
msg({ id: "note", createdAtIso: "2026-06-21T11:00:00.000Z", internalNote: true, authorEmail: "ops@hivegrid.de" }),
|
||||
],
|
||||
});
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.messages.map((m) => m.id)).toEqual(["inbound", "reply", "note"]);
|
||||
const byId = Object.fromEntries((vm.data?.messages ?? []).map((m) => [m.id, m]));
|
||||
expect(byId.inbound.kind).toBe("inbound");
|
||||
expect(byId.inbound.authorLabel).toBe("admin.support.author.customer");
|
||||
expect(byId.reply.kind).toBe("reply");
|
||||
expect(byId.note.kind).toBe("internalNote");
|
||||
expect(byId.note.kindLabelKey).toBe("admin.support.kind.internalNote");
|
||||
expect(vm.data?.replyCount).toBe(1);
|
||||
expect(vm.data?.internalNoteCount).toBe(1);
|
||||
expect(vm.data?.statusLabelKey).toBe("admin.support.status.open");
|
||||
expect(vm.data?.priorityLabelKey).toBe("admin.support.priority.high");
|
||||
});
|
||||
|
||||
it("handles an empty thread as a ready VM with no messages", () => {
|
||||
const vm = buildSupportConversationVM({ ticketId: "t1", subject: "s", status: "open", priority: "normal", messages: [] });
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.messages).toEqual([]);
|
||||
});
|
||||
});
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* AK-P19 — Admin Support-Inbox conversation view-model (DoD #6). Pure
|
||||
* function: the support-detail loader builds it once, the UI only renders.
|
||||
* No React, no Prisma (DoD A.3).
|
||||
*
|
||||
* The thread is ordered oldest-first (reading order). Internal notes are
|
||||
* flagged so the UI can visually separate operator-only notes from replies
|
||||
* that the customer can see. A null author marks an inbound customer
|
||||
* message.
|
||||
*/
|
||||
|
||||
export type SupportMessageKind = "reply" | "internalNote" | "inbound";
|
||||
|
||||
export type SupportConversationMessage = {
|
||||
readonly id: string;
|
||||
readonly createdAtIso: string;
|
||||
readonly kind: SupportMessageKind;
|
||||
/** i18n key for the kind badge, e.g. `admin.support.kind.internalNote`. */
|
||||
readonly kindLabelKey: string;
|
||||
/** Author label (email > id > inbound-customer fallback key). */
|
||||
readonly authorLabel: string;
|
||||
readonly body: string;
|
||||
};
|
||||
|
||||
export interface SupportConversationData {
|
||||
readonly ticketId: string;
|
||||
readonly subject: string;
|
||||
readonly statusLabelKey: string;
|
||||
readonly priorityLabelKey: string;
|
||||
readonly messages: readonly SupportConversationMessage[];
|
||||
readonly replyCount: number;
|
||||
readonly internalNoteCount: number;
|
||||
}
|
||||
|
||||
export type SupportConversationVM = VMState<SupportConversationData>;
|
||||
|
||||
export interface SupportConversationInputMessage {
|
||||
readonly id: string;
|
||||
readonly createdAtIso: string;
|
||||
readonly internalNote: boolean;
|
||||
readonly authorEmail: string | null;
|
||||
readonly authorId: string | null;
|
||||
readonly body: string;
|
||||
}
|
||||
|
||||
export interface BuildSupportConversationVMInput {
|
||||
readonly ticketId: string;
|
||||
readonly subject: string;
|
||||
readonly status: string;
|
||||
readonly priority: string;
|
||||
readonly messages: readonly SupportConversationInputMessage[];
|
||||
}
|
||||
|
||||
function messageKind(message: SupportConversationInputMessage): SupportMessageKind {
|
||||
if (message.internalNote) return "internalNote";
|
||||
const hasAuthor = Boolean((message.authorEmail ?? message.authorId ?? "").trim());
|
||||
return hasAuthor ? "reply" : "inbound";
|
||||
}
|
||||
|
||||
function authorLabelFor(message: SupportConversationInputMessage, kind: SupportMessageKind): string {
|
||||
if (message.authorEmail && message.authorEmail.trim().length > 0) return message.authorEmail.trim();
|
||||
if (message.authorId && message.authorId.trim().length > 0) return message.authorId.trim();
|
||||
return kind === "inbound" ? "admin.support.author.customer" : "admin.support.author.unknown";
|
||||
}
|
||||
|
||||
export function buildSupportConversationVM(input: BuildSupportConversationVMInput): SupportConversationVM {
|
||||
const messages: SupportConversationMessage[] = [...input.messages]
|
||||
.sort((a, b) => a.createdAtIso.localeCompare(b.createdAtIso))
|
||||
.map((message) => {
|
||||
const kind = messageKind(message);
|
||||
return {
|
||||
id: message.id,
|
||||
createdAtIso: message.createdAtIso,
|
||||
kind,
|
||||
kindLabelKey: `admin.support.kind.${kind}`,
|
||||
authorLabel: authorLabelFor(message, kind),
|
||||
body: message.body,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
ticketId: input.ticketId,
|
||||
subject: input.subject,
|
||||
statusLabelKey: `admin.support.status.${input.status}`,
|
||||
priorityLabelKey: `admin.support.priority.${input.priority}`,
|
||||
messages,
|
||||
replyCount: messages.filter((message) => message.kind === "reply").length,
|
||||
internalNoteCount: messages.filter((message) => message.kind === "internalNote").length,
|
||||
},
|
||||
};
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildAdminTenantNoteListVM, type AdminTenantNoteInputRow } from "./tenant-note-list.vm.js";
|
||||
|
||||
function row(overrides: Partial<AdminTenantNoteInputRow>): AdminTenantNoteInputRow {
|
||||
return {
|
||||
id: "n1",
|
||||
createdAtIso: "2026-06-20T10:00:00.000Z",
|
||||
category: "general",
|
||||
pinned: false,
|
||||
noteText: "note body",
|
||||
authorEmail: null,
|
||||
authorId: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("authorLabelFor id fallback (tenant-note-list.ts:67)", () => {
|
||||
it("uses the trimmed author id when no email is present", () => {
|
||||
const vm = buildAdminTenantNoteListVM({ rows: [row({ authorEmail: null, authorId: " op_3 " })] });
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.rows[0]?.authorLabel).toBe("op_3");
|
||||
});
|
||||
});
|
||||
|
||||
describe("compareNotes pinned ordering, both directions (tenant-note-list.ts:73)", () => {
|
||||
it("hoists a pinned note above an unpinned one even when the pinned note is listed last", () => {
|
||||
// Input order is unpinned-before-pinned, forcing the `a.pinned ? -1 : 1` -> 1 branch.
|
||||
const vm = buildAdminTenantNoteListVM({
|
||||
rows: [
|
||||
row({ id: "unpinned", pinned: false, createdAtIso: "2026-06-22T10:00:00.000Z" }),
|
||||
row({ id: "pinned", pinned: true, createdAtIso: "2026-06-10T10:00:00.000Z" }),
|
||||
],
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows.map((r) => r.id)).toEqual(["pinned", "unpinned"]);
|
||||
expect(vm.data.pinnedCount).toBe(1);
|
||||
});
|
||||
|
||||
it("keeps a pinned note on top when it already leads the input (opposite arg order)", () => {
|
||||
// Input order is pinned-before-unpinned, forcing the comparator's other
|
||||
// argument order so the `a.pinned ? -1 : 1` ternary's remaining arm runs.
|
||||
const vm = buildAdminTenantNoteListVM({
|
||||
rows: [
|
||||
row({ id: "pinned", pinned: true, createdAtIso: "2026-06-10T10:00:00.000Z" }),
|
||||
row({ id: "unpinned", pinned: false, createdAtIso: "2026-06-22T10:00:00.000Z" }),
|
||||
],
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows.map((r) => r.id)).toEqual(["pinned", "unpinned"]);
|
||||
});
|
||||
|
||||
it("orders two pinned notes newest-first among themselves", () => {
|
||||
const vm = buildAdminTenantNoteListVM({
|
||||
rows: [
|
||||
row({ id: "older-pinned", pinned: true, createdAtIso: "2026-06-10T10:00:00.000Z" }),
|
||||
row({ id: "newer-pinned", pinned: true, createdAtIso: "2026-06-20T10:00:00.000Z" }),
|
||||
],
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows.map((r) => r.id)).toEqual(["newer-pinned", "older-pinned"]);
|
||||
expect(vm.data.pinnedCount).toBe(2);
|
||||
});
|
||||
});
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildAdminTenantNoteListVM,
|
||||
deriveAdminTenantNoteCategory,
|
||||
type AdminTenantNoteInputRow,
|
||||
} from "./tenant-note-list.vm.js";
|
||||
|
||||
function row(overrides: Partial<AdminTenantNoteInputRow>): AdminTenantNoteInputRow {
|
||||
return {
|
||||
id: "n1",
|
||||
createdAtIso: "2026-06-20T10:00:00.000Z",
|
||||
category: "general",
|
||||
pinned: false,
|
||||
noteText: "note body",
|
||||
authorEmail: null,
|
||||
authorId: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("deriveAdminTenantNoteCategory", () => {
|
||||
it("keeps a known category and normalizes casing", () => {
|
||||
expect(deriveAdminTenantNoteCategory("BILLING")).toBe("billing");
|
||||
});
|
||||
it("falls back to general for unknown or empty", () => {
|
||||
expect(deriveAdminTenantNoteCategory("nonsense")).toBe("general");
|
||||
expect(deriveAdminTenantNoteCategory(null)).toBe("general");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildAdminTenantNoteListVM", () => {
|
||||
it("returns an empty state for no rows", () => {
|
||||
expect(buildAdminTenantNoteListVM({ rows: [] })).toEqual({ status: "empty" });
|
||||
});
|
||||
|
||||
it("orders pinned-first then newest-first", () => {
|
||||
const vm = buildAdminTenantNoteListVM({
|
||||
rows: [
|
||||
row({ id: "old-unpinned", createdAtIso: "2026-06-18T10:00:00.000Z", pinned: false }),
|
||||
row({ id: "new-unpinned", createdAtIso: "2026-06-22T10:00:00.000Z", pinned: false }),
|
||||
row({ id: "old-pinned", createdAtIso: "2026-06-10T10:00:00.000Z", pinned: true }),
|
||||
],
|
||||
});
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.rows.map((r) => r.id)).toEqual(["old-pinned", "new-unpinned", "old-unpinned"]);
|
||||
expect(vm.data?.pinnedCount).toBe(1);
|
||||
});
|
||||
|
||||
it("emits category + author i18n keys and keeps markdown verbatim", () => {
|
||||
const vm = buildAdminTenantNoteListVM({
|
||||
rows: [row({ category: "billing", noteText: "# heading", authorEmail: "ops@hivegrid.de" })],
|
||||
});
|
||||
const note = vm.data?.rows[0];
|
||||
expect(note?.categoryLabelKey).toBe("admin.tenantNotes.category.billing");
|
||||
expect(note?.authorLabel).toBe("ops@hivegrid.de");
|
||||
expect(note?.bodyMarkdown).toBe("# heading");
|
||||
});
|
||||
|
||||
it("falls back to the anonymous author key when no email or id", () => {
|
||||
const vm = buildAdminTenantNoteListVM({ rows: [row({ authorEmail: null, authorId: null })] });
|
||||
expect(vm.data?.rows[0]?.authorLabel).toBe("admin.tenantNotes.author.unknown");
|
||||
});
|
||||
});
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* AK-P19 — Admin tenant-notes view-model (DoD #3). Pure function: the
|
||||
* admin tenant-detail loader builds it once, the UI only renders. No
|
||||
* React, no Prisma, no app imports (DoD A.3). Category + author labels
|
||||
* are emitted as i18n keys so the route resolves them with `t()`.
|
||||
*
|
||||
* Ordering is pinned-first, then newest-first — the operator's pinned
|
||||
* notes always surface at the top of the tenant detail.
|
||||
*/
|
||||
|
||||
/** Categories an operator can file a note under. Unknown values fall back. */
|
||||
export const ADMIN_TENANT_NOTE_CATEGORIES = ["general", "billing", "support", "technical", "contract"] as const;
|
||||
|
||||
export type AdminTenantNoteCategory = (typeof ADMIN_TENANT_NOTE_CATEGORIES)[number];
|
||||
|
||||
export type AdminTenantNoteRow = {
|
||||
readonly id: string;
|
||||
readonly createdAtIso: string;
|
||||
readonly category: AdminTenantNoteCategory;
|
||||
/** i18n key for the category chip, e.g. `admin.tenantNotes.category.billing`. */
|
||||
readonly categoryLabelKey: string;
|
||||
readonly pinned: boolean;
|
||||
/** Best human label for the author (email > id > anonymous fallback key). */
|
||||
readonly authorLabel: string;
|
||||
/** Raw markdown body — rendered by the UI, never trusted as HTML here. */
|
||||
readonly bodyMarkdown: string;
|
||||
};
|
||||
|
||||
export interface AdminTenantNoteListData {
|
||||
readonly rows: readonly AdminTenantNoteRow[];
|
||||
readonly pinnedCount: number;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type AdminTenantNoteListVM = VMState<AdminTenantNoteListData>;
|
||||
|
||||
/** Raw note row the loader reads from the DB (framework-free). */
|
||||
export interface AdminTenantNoteInputRow {
|
||||
readonly id: string;
|
||||
readonly createdAtIso: string;
|
||||
readonly category: string | null;
|
||||
readonly pinned: boolean;
|
||||
readonly noteText: string;
|
||||
readonly authorEmail: string | null;
|
||||
readonly authorId: string | null;
|
||||
}
|
||||
|
||||
export interface BuildAdminTenantNoteListVMInput {
|
||||
readonly rows: readonly AdminTenantNoteInputRow[];
|
||||
}
|
||||
|
||||
const KNOWN_CATEGORIES: ReadonlySet<AdminTenantNoteCategory> = new Set(ADMIN_TENANT_NOTE_CATEGORIES);
|
||||
|
||||
/** Normalizes a raw category onto a known {@link AdminTenantNoteCategory}. */
|
||||
export function deriveAdminTenantNoteCategory(category: string | null | undefined): AdminTenantNoteCategory {
|
||||
const candidate = (category ?? "").trim().toLowerCase();
|
||||
return KNOWN_CATEGORIES.has(candidate as AdminTenantNoteCategory)
|
||||
? (candidate as AdminTenantNoteCategory)
|
||||
: "general";
|
||||
}
|
||||
|
||||
function authorLabelFor(row: AdminTenantNoteInputRow): string {
|
||||
if (row.authorEmail && row.authorEmail.trim().length > 0) return row.authorEmail.trim();
|
||||
if (row.authorId && row.authorId.trim().length > 0) return row.authorId.trim();
|
||||
return "admin.tenantNotes.author.unknown";
|
||||
}
|
||||
|
||||
/** Pinned-first, then newest-first. Stable for equal keys. */
|
||||
function compareNotes(a: AdminTenantNoteRow, b: AdminTenantNoteRow): number {
|
||||
if (a.pinned !== b.pinned) return a.pinned ? -1 : 1;
|
||||
return b.createdAtIso.localeCompare(a.createdAtIso);
|
||||
}
|
||||
|
||||
export function buildAdminTenantNoteListVM(input: BuildAdminTenantNoteListVMInput): AdminTenantNoteListVM {
|
||||
if (input.rows.length === 0) {
|
||||
return { status: "empty" };
|
||||
}
|
||||
const rows: AdminTenantNoteRow[] = input.rows
|
||||
.map((row) => {
|
||||
const category = deriveAdminTenantNoteCategory(row.category);
|
||||
return {
|
||||
id: row.id,
|
||||
createdAtIso: row.createdAtIso,
|
||||
category,
|
||||
categoryLabelKey: `admin.tenantNotes.category.${category}`,
|
||||
pinned: row.pinned,
|
||||
authorLabel: authorLabelFor(row),
|
||||
bodyMarkdown: row.noteText,
|
||||
};
|
||||
})
|
||||
.sort(compareNotes);
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows,
|
||||
pinnedCount: rows.filter((row) => row.pinned).length,
|
||||
emptyHeadlineKey: "admin.tenantNotes.empty.headline",
|
||||
emptyBodyKey: "admin.tenantNotes.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildIntegrationCatalogVM, integrationCategoryKey, type CatalogAppRow } from "./integration-catalog.vm.js";
|
||||
import { buildConnectionDetailVM, connectionStatusKey, type ConnectionRow } from "./connection-detail.vm.js";
|
||||
import { buildSyncHistoryVM, type SyncRunRow } from "./sync-history.vm.js";
|
||||
import { buildSyncRunDetailVM, syncItemOperationKey, syncItemStatusKey, syncLogSeverityKey, type SyncItemRow, type SyncLogRow } from "./sync-run-detail.vm.js";
|
||||
|
||||
// R-P5 — apps-engine VMs are pure. Lock in the ready/empty contract and the
|
||||
// "no credentials in any VM" guarantee.
|
||||
|
||||
describe("buildIntegrationCatalogVM", () => {
|
||||
const row: CatalogAppRow = {
|
||||
key: "sample-data-sync",
|
||||
titleKey: "integrations.app.sampleDataSync.title",
|
||||
category: "erp",
|
||||
categoryKey: integrationCategoryKey("erp"),
|
||||
connectionType: "rest_api",
|
||||
connectionCount: 2,
|
||||
detailHref: "/acme/integrations/sample-data-sync",
|
||||
};
|
||||
|
||||
it("exposes connection count + category key, never credentials", () => {
|
||||
const vm = buildIntegrationCatalogVM({ rows: [row], canConnect: true });
|
||||
const data = vm.data?.rows[0] as unknown as Record<string, unknown>;
|
||||
expect(data).not.toHaveProperty("credentials");
|
||||
expect(data.connectionCount).toBe(2);
|
||||
expect(data.categoryKey).toBe("integrations.category.erp");
|
||||
});
|
||||
|
||||
it("empty stays ready with empty-state keys", () => {
|
||||
const vm = buildIntegrationCatalogVM({ rows: [], canConnect: false });
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.emptyHeadlineKey).toBe("integrations.catalog.empty.headline");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildConnectionDetailVM", () => {
|
||||
const row: ConnectionRow = {
|
||||
id: "dc1",
|
||||
label: "Sales mailbox",
|
||||
status: "active",
|
||||
statusKey: connectionStatusKey("active"),
|
||||
healthMessageKey: "integrations.health.active",
|
||||
lastHealthCheckIso: new Date("2026-06-01").toISOString(),
|
||||
tokenExpiresIso: null,
|
||||
syncsHref: "/acme/integrations/sample-data-sync/dc1/syncs",
|
||||
};
|
||||
|
||||
it("carries status + health metadata but never credential values", () => {
|
||||
const vm = buildConnectionDetailVM({ appKey: "sample-data-sync", appTitleKey: "x", rows: [row], canConnect: true, canDisconnect: true, canManualSync: true, connectHref: "/c" });
|
||||
const data = vm.data?.rows[0] as unknown as Record<string, unknown>;
|
||||
expect(data).not.toHaveProperty("credentials");
|
||||
expect(data).not.toHaveProperty("credentialsCiphertext");
|
||||
expect(data.statusKey).toBe("integrations.status.active");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildSyncHistoryVM", () => {
|
||||
const row: SyncRunRow = {
|
||||
id: "r1",
|
||||
kind: "manual",
|
||||
kindKey: "integrations.syncKind.manual",
|
||||
status: "completed",
|
||||
statusKey: "integrations.syncStatus.completed",
|
||||
itemsTotal: 3,
|
||||
itemsSucceeded: 3,
|
||||
itemsFailed: 0,
|
||||
summaryKey: "integrations.sync.summary.ok",
|
||||
startedIso: null,
|
||||
completedIso: null,
|
||||
};
|
||||
|
||||
it("exposes run counters + status key", () => {
|
||||
const vm = buildSyncHistoryVM({ connectionId: "dc1", rows: [row], canManualSync: true });
|
||||
expect(vm.data?.rows[0].itemsSucceeded).toBe(3);
|
||||
expect(vm.data?.rows[0].statusKey).toBe("integrations.syncStatus.completed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildSyncRunDetailVM", () => {
|
||||
const item: SyncItemRow = {
|
||||
id: "i1",
|
||||
entityType: "Kontakt",
|
||||
entityId: "k1",
|
||||
externalId: "ext-9",
|
||||
operation: "created",
|
||||
operationKey: syncItemOperationKey("created"),
|
||||
status: "failed",
|
||||
statusKey: syncItemStatusKey("failed"),
|
||||
errorText: "integrations.sync.item.error.conflict",
|
||||
};
|
||||
const log: SyncLogRow = {
|
||||
id: "l1",
|
||||
severity: "error",
|
||||
severityKey: syncLogSeverityKey("error"),
|
||||
messageKey: "integrations.sync.log.adapterError",
|
||||
createdIso: new Date("2026-06-01T10:00:00Z").toISOString(),
|
||||
};
|
||||
|
||||
it("carries run header + item/log rows, never credentials", () => {
|
||||
const vm = buildSyncRunDetailVM({
|
||||
runId: "r1",
|
||||
connectionId: "dc1",
|
||||
kind: "manual",
|
||||
kindKey: "integrations.syncKind.manual",
|
||||
status: "partial",
|
||||
statusKey: "integrations.syncStatus.partial",
|
||||
itemsTotal: 3,
|
||||
itemsSucceeded: 2,
|
||||
itemsFailed: 1,
|
||||
summaryKey: "integrations.sync.summary.ok",
|
||||
startedIso: null,
|
||||
completedIso: null,
|
||||
items: [item],
|
||||
logs: [log],
|
||||
});
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.items[0]).not.toHaveProperty("credentials");
|
||||
expect(vm.data?.items[0].operationKey).toBe("integrations.syncItemOperation.created");
|
||||
expect(vm.data?.logs[0].severityKey).toBe("integrations.syncLogSeverity.error");
|
||||
expect(vm.data?.emptyItemsHeadlineKey).toBe("integrations.runDetail.emptyItems.headline");
|
||||
});
|
||||
});
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* App connection-management view-model (R-P5). One app, its tenant connections.
|
||||
* Pure (DoD A.3). CRITICAL: credentials are NEVER part of this VM — only status,
|
||||
* label and health metadata.
|
||||
*/
|
||||
export type ConnectionStatus = "pending" | "active" | "degraded" | "broken" | "revoked";
|
||||
|
||||
export interface ConnectionRow {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly status: ConnectionStatus;
|
||||
/** i18n key for the status label (e.g. `integrations.status.active`). */
|
||||
readonly statusKey: string;
|
||||
/** i18n key for the current health message (Klartext) or null. */
|
||||
readonly healthMessageKey: string | null;
|
||||
readonly lastHealthCheckIso: string | null;
|
||||
readonly tokenExpiresIso: string | null;
|
||||
/** Internal route to this connection's sync history. */
|
||||
readonly syncsHref: string;
|
||||
}
|
||||
|
||||
export interface ConnectionDetailData {
|
||||
readonly appKey: string;
|
||||
readonly appTitleKey: string;
|
||||
readonly rows: readonly ConnectionRow[];
|
||||
readonly canConnect: boolean;
|
||||
readonly canDisconnect: boolean;
|
||||
readonly canManualSync: boolean;
|
||||
readonly connectHref: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type ConnectionDetailVM = VMState<ConnectionDetailData>;
|
||||
|
||||
export function connectionStatusKey(status: ConnectionStatus): string {
|
||||
return `integrations.status.${status}`;
|
||||
}
|
||||
|
||||
export interface BuildConnectionDetailVMInput {
|
||||
readonly appKey: string;
|
||||
readonly appTitleKey: string;
|
||||
readonly rows: readonly ConnectionRow[];
|
||||
readonly canConnect: boolean;
|
||||
readonly canDisconnect: boolean;
|
||||
readonly canManualSync: boolean;
|
||||
readonly connectHref: string;
|
||||
}
|
||||
|
||||
export function buildConnectionDetailVM(input: BuildConnectionDetailVMInput): ConnectionDetailVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
appKey: input.appKey,
|
||||
appTitleKey: input.appTitleKey,
|
||||
rows: input.rows,
|
||||
canConnect: input.canConnect,
|
||||
canDisconnect: input.canDisconnect,
|
||||
canManualSync: input.canManualSync,
|
||||
connectHref: input.connectHref,
|
||||
emptyHeadlineKey: "integrations.connections.empty.headline",
|
||||
emptyBodyKey: "integrations.connections.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* Integrations catalog view-model (R-P5). Pure function (DoD A.3): the loader
|
||||
* builds it once server-side; the UI only renders. The catalog itself is code-
|
||||
* defined (@hivegrid/integrations INTEGRATION_CATALOG); the loader passes the
|
||||
* per-app live connection count. NO credentials anywhere.
|
||||
*/
|
||||
export type IntegrationCategory = "erp" | "communication" | "calendar" | "signature" | "payment" | "ki";
|
||||
|
||||
export interface CatalogAppRow {
|
||||
readonly key: string;
|
||||
/** i18n key for the app display name. */
|
||||
readonly titleKey: string;
|
||||
readonly category: IntegrationCategory;
|
||||
/** i18n key for the category label (e.g. `integrations.category.erp`). */
|
||||
readonly categoryKey: string;
|
||||
readonly connectionType: "oauth2" | "api_key" | "rest_api" | "windows_client";
|
||||
/** Loader-computed number of the tenant's connections for this app. */
|
||||
readonly connectionCount: number;
|
||||
/** Internal route to this app's connection management. */
|
||||
readonly detailHref: string;
|
||||
}
|
||||
|
||||
export interface IntegrationCatalogData {
|
||||
readonly rows: readonly CatalogAppRow[];
|
||||
readonly canConnect: boolean;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type IntegrationCatalogVM = VMState<IntegrationCatalogData>;
|
||||
|
||||
export function integrationCategoryKey(category: IntegrationCategory): string {
|
||||
return `integrations.category.${category}`;
|
||||
}
|
||||
|
||||
/** Normalized prop-model for the catalog UI implementations (M015/M017). */
|
||||
export interface IntegrationCatalogModel {
|
||||
readonly titleKey: string;
|
||||
readonly rows: readonly CatalogAppRow[];
|
||||
readonly rowCount: number;
|
||||
/** Number of apps with at least one tenant connection (status light). */
|
||||
readonly connectedCount: number;
|
||||
readonly canConnect: boolean;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export function toIntegrationCatalogModel(data: IntegrationCatalogData): IntegrationCatalogModel {
|
||||
return {
|
||||
titleKey: "integrations.catalog.title",
|
||||
rows: data.rows,
|
||||
rowCount: data.rows.length,
|
||||
connectedCount: data.rows.filter((row) => row.connectionCount > 0).length,
|
||||
canConnect: data.canConnect,
|
||||
emptyHeadlineKey: data.emptyHeadlineKey,
|
||||
emptyBodyKey: data.emptyBodyKey,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildIntegrationCatalogVM(input: { rows: readonly CatalogAppRow[]; canConnect: boolean }): IntegrationCatalogVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows: input.rows,
|
||||
canConnect: input.canConnect,
|
||||
emptyHeadlineKey: "integrations.catalog.empty.headline",
|
||||
emptyBodyKey: "integrations.catalog.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* Sync-history view-model (R-P5). A connection's AppSyncRun list. Pure (DoD A.3).
|
||||
* `summaryKey`/`statusKey` are i18n keys; counts are loader data.
|
||||
*/
|
||||
export type SyncStatus = "pending" | "running" | "completed" | "partial" | "failed" | "cancelled";
|
||||
export type SyncKind = "manual" | "scheduled" | "webhook";
|
||||
|
||||
export interface SyncRunRow {
|
||||
readonly id: string;
|
||||
readonly kind: SyncKind;
|
||||
readonly kindKey: string;
|
||||
readonly status: SyncStatus;
|
||||
readonly statusKey: string;
|
||||
readonly itemsTotal: number;
|
||||
readonly itemsSucceeded: number;
|
||||
readonly itemsFailed: number;
|
||||
/** i18n key for the Klartext run summary, or null. */
|
||||
readonly summaryKey: string | null;
|
||||
readonly startedIso: string | null;
|
||||
readonly completedIso: string | null;
|
||||
}
|
||||
|
||||
export interface SyncHistoryData {
|
||||
readonly connectionId: string;
|
||||
readonly rows: readonly SyncRunRow[];
|
||||
readonly canManualSync: boolean;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type SyncHistoryVM = VMState<SyncHistoryData>;
|
||||
|
||||
export function syncStatusKey(status: SyncStatus): string {
|
||||
return `integrations.syncStatus.${status}`;
|
||||
}
|
||||
|
||||
export function syncKindKey(kind: SyncKind): string {
|
||||
return `integrations.syncKind.${kind}`;
|
||||
}
|
||||
|
||||
export function buildSyncHistoryVM(input: { connectionId: string; rows: readonly SyncRunRow[]; canManualSync: boolean }): SyncHistoryVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
connectionId: input.connectionId,
|
||||
rows: input.rows,
|
||||
canManualSync: input.canManualSync,
|
||||
emptyHeadlineKey: "integrations.syncs.empty.headline",
|
||||
emptyBodyKey: "integrations.syncs.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import type { VMState } from "../index.js";
|
||||
import type { SyncKind, SyncStatus } from "./sync-history.vm.js";
|
||||
|
||||
/**
|
||||
* Sync-run detail view-model (R-P5). One AppSyncRun with its AppSyncItem rows and
|
||||
* AppSyncRunLog lines. Pure (DoD A.3); message/summary fields are i18n keys.
|
||||
* NO credentials anywhere.
|
||||
*/
|
||||
export type SyncItemOperation = "created" | "updated" | "deleted" | "skipped";
|
||||
export type SyncItemStatus = "pending" | "synced" | "failed" | "skipped";
|
||||
export type SyncLogSeverity = "info" | "success" | "warning" | "error";
|
||||
|
||||
export interface SyncItemRow {
|
||||
readonly id: string;
|
||||
readonly entityType: string;
|
||||
readonly entityId: string | null;
|
||||
readonly externalId: string;
|
||||
readonly operation: SyncItemOperation;
|
||||
readonly operationKey: string;
|
||||
readonly status: SyncItemStatus;
|
||||
readonly statusKey: string;
|
||||
/** Klartext error (adapter-provided i18n key or text), or null. */
|
||||
readonly errorText: string | null;
|
||||
}
|
||||
|
||||
export interface SyncLogRow {
|
||||
readonly id: string;
|
||||
readonly severity: SyncLogSeverity;
|
||||
readonly severityKey: string;
|
||||
/** i18n key (or Klartext) of the log line. */
|
||||
readonly messageKey: string;
|
||||
readonly createdIso: string;
|
||||
}
|
||||
|
||||
export interface SyncRunDetailData {
|
||||
readonly runId: string;
|
||||
readonly connectionId: string;
|
||||
readonly kind: SyncKind;
|
||||
readonly kindKey: string;
|
||||
readonly status: SyncStatus;
|
||||
readonly statusKey: string;
|
||||
readonly itemsTotal: number;
|
||||
readonly itemsSucceeded: number;
|
||||
readonly itemsFailed: number;
|
||||
/** i18n key for the Klartext run summary, or null. */
|
||||
readonly summaryKey: string | null;
|
||||
readonly startedIso: string | null;
|
||||
readonly completedIso: string | null;
|
||||
readonly items: readonly SyncItemRow[];
|
||||
readonly logs: readonly SyncLogRow[];
|
||||
readonly emptyItemsHeadlineKey: string;
|
||||
readonly emptyItemsBodyKey: string;
|
||||
}
|
||||
|
||||
export type SyncRunDetailVM = VMState<SyncRunDetailData>;
|
||||
|
||||
export function syncItemOperationKey(operation: SyncItemOperation): string {
|
||||
return `integrations.syncItemOperation.${operation}`;
|
||||
}
|
||||
|
||||
export function syncItemStatusKey(status: SyncItemStatus): string {
|
||||
return `integrations.syncItemStatus.${status}`;
|
||||
}
|
||||
|
||||
export function syncLogSeverityKey(severity: SyncLogSeverity): string {
|
||||
return `integrations.syncLogSeverity.${severity}`;
|
||||
}
|
||||
|
||||
export interface BuildSyncRunDetailVMInput {
|
||||
readonly runId: string;
|
||||
readonly connectionId: string;
|
||||
readonly kind: SyncKind;
|
||||
readonly kindKey: string;
|
||||
readonly status: SyncStatus;
|
||||
readonly statusKey: string;
|
||||
readonly itemsTotal: number;
|
||||
readonly itemsSucceeded: number;
|
||||
readonly itemsFailed: number;
|
||||
readonly summaryKey: string | null;
|
||||
readonly startedIso: string | null;
|
||||
readonly completedIso: string | null;
|
||||
readonly items: readonly SyncItemRow[];
|
||||
readonly logs: readonly SyncLogRow[];
|
||||
}
|
||||
|
||||
export function buildSyncRunDetailVM(input: BuildSyncRunDetailVMInput): SyncRunDetailVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
...input,
|
||||
emptyItemsHeadlineKey: "integrations.runDetail.emptyItems.headline",
|
||||
emptyItemsBodyKey: "integrations.runDetail.emptyItems.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildAuditExportVM, toAuditExportResultVM } from "./audit-export.vm.js";
|
||||
|
||||
describe("buildAuditExportVM", () => {
|
||||
it("exposes defaults and i18n-keyed options", () => {
|
||||
const vm = buildAuditExportVM({ defaultFrom: "2026-06-06", defaultTo: "2026-07-06", maxRows: 50000 });
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.defaultFrom).toBe("2026-06-06");
|
||||
expect(vm.data?.maxRows).toBe(50000);
|
||||
expect(vm.data?.formatOptions.map((option) => option.value)).toEqual(["csv", "ndjson"]);
|
||||
expect(vm.data?.actorTypeOptions.every((option) => option.labelKey.startsWith("auditExport."))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toAuditExportResultVM", () => {
|
||||
it("normalizes a success payload including expiry days", () => {
|
||||
expect(
|
||||
toAuditExportResultVM({ ok: true, url: "https://storage/x", rowCount: 12, integrityOk: true, expiresInSeconds: 172800 })
|
||||
).toEqual({ ok: true, url: "https://storage/x", rowCount: 12, integrityOk: true, expiresDays: 2 });
|
||||
});
|
||||
|
||||
it("passes error keys through and rejects malformed payloads", () => {
|
||||
expect(toAuditExportResultVM({ ok: false, errorKey: "auditExport.storage.errorPurpose" })).toEqual({
|
||||
ok: false,
|
||||
errorKey: "auditExport.storage.errorPurpose",
|
||||
});
|
||||
expect(toAuditExportResultVM(undefined)).toBeNull();
|
||||
expect(toAuditExportResultVM({ ok: true })).toBeNull();
|
||||
});
|
||||
});
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* Audit-Export view-model (AK-P3 DoD 3). Pure form/result contract for the
|
||||
* admin export screen: filter defaults, select options as i18n keys, and the
|
||||
* normalized storage-export result. Streaming/PDF fallbacks stay loader-side.
|
||||
*/
|
||||
|
||||
export interface AuditExportOption {
|
||||
readonly value: string;
|
||||
readonly labelKey: string;
|
||||
}
|
||||
|
||||
export interface AuditExportData {
|
||||
readonly defaultFrom: string;
|
||||
readonly defaultTo: string;
|
||||
readonly maxRows: number;
|
||||
readonly actorTypeOptions: readonly AuditExportOption[];
|
||||
readonly outcomeOptions: readonly AuditExportOption[];
|
||||
readonly regulatoryScopeOptions: readonly AuditExportOption[];
|
||||
readonly formatOptions: readonly AuditExportOption[];
|
||||
}
|
||||
|
||||
export type AuditExportVM = VMState<AuditExportData>;
|
||||
|
||||
/** Normalized action result the screen renders (success panel or error banner). */
|
||||
export type AuditExportResultVM =
|
||||
| { readonly ok: true; readonly url: string; readonly rowCount: number; readonly integrityOk: boolean; readonly expiresDays: number }
|
||||
| { readonly ok: false; readonly errorKey: string };
|
||||
|
||||
export interface BuildAuditExportVMInput {
|
||||
readonly defaultFrom: string;
|
||||
readonly defaultTo: string;
|
||||
readonly maxRows: number;
|
||||
}
|
||||
|
||||
export function buildAuditExportVM(input: BuildAuditExportVMInput): AuditExportVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
defaultFrom: input.defaultFrom,
|
||||
defaultTo: input.defaultTo,
|
||||
maxRows: input.maxRows,
|
||||
actorTypeOptions: [
|
||||
{ value: "user", labelKey: "auditExport.actorTypes.user" },
|
||||
{ value: "admin", labelKey: "auditExport.actorTypes.admin" },
|
||||
{ value: "api_key", labelKey: "auditExport.actorTypes.apiKey" },
|
||||
{ value: "system", labelKey: "auditExport.actorTypes.system" },
|
||||
{ value: "plugin", labelKey: "auditExport.actorTypes.plugin" },
|
||||
],
|
||||
outcomeOptions: [
|
||||
{ value: "success", labelKey: "auditExport.outcomes.success" },
|
||||
{ value: "failure", labelKey: "auditExport.outcomes.failure" },
|
||||
{ value: "blocked", labelKey: "auditExport.outcomes.blocked" },
|
||||
],
|
||||
regulatoryScopeOptions: [
|
||||
{ value: "soc2", labelKey: "auditExport.scopes.soc2" },
|
||||
{ value: "gdpr", labelKey: "auditExport.scopes.gdpr" },
|
||||
{ value: "hipaa", labelKey: "auditExport.scopes.hipaa" },
|
||||
{ value: "pci", labelKey: "auditExport.scopes.pci" },
|
||||
],
|
||||
formatOptions: [
|
||||
{ value: "csv", labelKey: "auditExport.storage.formatCsv" },
|
||||
{ value: "ndjson", labelKey: "auditExport.storage.formatNdjson" },
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function toAuditExportResultVM(raw: unknown): AuditExportResultVM | null {
|
||||
if (!raw || typeof raw !== "object") return null;
|
||||
const record = raw as Record<string, unknown>;
|
||||
if (record.ok === true && typeof record.url === "string") {
|
||||
return {
|
||||
ok: true,
|
||||
url: record.url,
|
||||
rowCount: typeof record.rowCount === "number" ? record.rowCount : 0,
|
||||
integrityOk: record.integrityOk === true,
|
||||
expiresDays: typeof record.expiresInSeconds === "number" ? Math.round(record.expiresInSeconds / 86400) : 0,
|
||||
};
|
||||
}
|
||||
if (record.ok === false && typeof record.errorKey === "string") {
|
||||
return { ok: false, errorKey: record.errorKey };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildAuditListVM,
|
||||
deriveAuditActorKind,
|
||||
type AuditListFilterState,
|
||||
type AuditListInputRow,
|
||||
type AuditListPagination,
|
||||
} from "../index.js";
|
||||
|
||||
const filter: AuditListFilterState = {
|
||||
from: null,
|
||||
to: null,
|
||||
actorType: null,
|
||||
action: null,
|
||||
outcome: null,
|
||||
targetType: null,
|
||||
};
|
||||
|
||||
const pagination: AuditListPagination = { page: 1, pageSize: 25, total: 1, totalPages: 1 };
|
||||
|
||||
function row(overrides: Partial<AuditListInputRow> = {}): AuditListInputRow {
|
||||
return {
|
||||
id: "a1",
|
||||
createdAtIso: "2026-06-24T08:00:00.000Z",
|
||||
actorType: "user",
|
||||
actorEmail: "akeshan@example.com",
|
||||
actorId: "u1",
|
||||
action: "kontakt.created",
|
||||
targetType: "Kontakt",
|
||||
targetId: "k1",
|
||||
outcome: "success",
|
||||
hasMetadata: true,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("deriveAuditActorKind alias collapse (audit-list.ts:101)", () => {
|
||||
it.each(["ki", "ai", "agent"])("maps the %s alias onto ki_agent", (alias) => {
|
||||
expect(deriveAuditActorKind(alias)).toBe("ki_agent");
|
||||
});
|
||||
});
|
||||
|
||||
describe("actorKindKeySuffix camelCase mapping (audit-list.ts:107)", () => {
|
||||
it("emits kiAgent for the ki_agent actor kind", () => {
|
||||
const vm = buildAuditListVM({ rows: [row({ actorType: "ki_agent" })], filter, pagination, canExport: false });
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows[0]?.actorKind).toBe("ki_agent");
|
||||
expect(vm.data.rows[0]?.actorKindLabelKey).toBe("audit.actorKind.kiAgent");
|
||||
});
|
||||
|
||||
it("emits apiKey for the api_key actor kind", () => {
|
||||
const vm = buildAuditListVM({ rows: [row({ actorType: "api_key" })], filter, pagination, canExport: false });
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows[0]?.actorKindLabelKey).toBe("audit.actorKind.apiKey");
|
||||
});
|
||||
});
|
||||
|
||||
describe("actorLabelFor id fallback (audit-list.ts:133)", () => {
|
||||
it("uses the actor id when no email is present and surfaces it in summaryParams", () => {
|
||||
const vm = buildAuditListVM({
|
||||
rows: [row({ actorEmail: null, actorId: " u9 " })],
|
||||
filter,
|
||||
pagination,
|
||||
canExport: false,
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows[0]?.actorLabel).toBe("u9");
|
||||
expect(vm.data.rows[0]?.summaryParams.actor).toBe("u9");
|
||||
});
|
||||
});
|
||||
|
||||
describe("summaryParams target assembly (audit-list.ts:151)", () => {
|
||||
it("drops the #id suffix when only the target type is known", () => {
|
||||
const vm = buildAuditListVM({
|
||||
rows: [row({ targetType: "Kontakt", targetId: null })],
|
||||
filter,
|
||||
pagination,
|
||||
canExport: false,
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows[0]?.summaryParams.target).toBe("Kontakt");
|
||||
});
|
||||
|
||||
it("yields an empty target when there is no target type", () => {
|
||||
const vm = buildAuditListVM({
|
||||
rows: [row({ targetType: null, targetId: null })],
|
||||
filter,
|
||||
pagination,
|
||||
canExport: false,
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows[0]?.summaryParams.target).toBe("");
|
||||
});
|
||||
});
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildAuditListVM,
|
||||
deriveAuditActorKind,
|
||||
deriveAuditSummaryKey,
|
||||
buildAuditFieldDiffs,
|
||||
toAuditListModel,
|
||||
type AuditListFilterState,
|
||||
type AuditListInputRow,
|
||||
type AuditListPagination,
|
||||
} from "../index.js";
|
||||
|
||||
// Matches the codebase i18n key convention (camelCase segments allowed, see `auditExport.*`).
|
||||
const I18N_KEY = /^[a-zA-Z][a-zA-Z0-9]*(?:[.-][a-zA-Z0-9]+)*$/;
|
||||
|
||||
const filter: AuditListFilterState = {
|
||||
from: null,
|
||||
to: null,
|
||||
actorType: null,
|
||||
action: null,
|
||||
outcome: null,
|
||||
targetType: null,
|
||||
};
|
||||
|
||||
const pagination: AuditListPagination = { page: 1, pageSize: 25, total: 0, totalPages: 1 };
|
||||
|
||||
function row(overrides: Partial<AuditListInputRow> = {}): AuditListInputRow {
|
||||
return {
|
||||
id: "a1",
|
||||
createdAtIso: "2026-06-24T08:00:00.000Z",
|
||||
actorType: "user",
|
||||
actorEmail: "akeshan@example.com",
|
||||
actorId: "u1",
|
||||
action: "kontakt.created",
|
||||
targetType: "Kontakt",
|
||||
targetId: "k1",
|
||||
outcome: "success",
|
||||
hasMetadata: true,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("deriveAuditActorKind", () => {
|
||||
it("normalizes known and aliased actor types", () => {
|
||||
expect(deriveAuditActorKind("user")).toBe("user");
|
||||
expect(deriveAuditActorKind("API-KEY")).toBe("api_key");
|
||||
expect(deriveAuditActorKind("apikey")).toBe("api_key");
|
||||
expect(deriveAuditActorKind("ki_agent")).toBe("ki_agent");
|
||||
expect(deriveAuditActorKind(null)).toBe("system");
|
||||
expect(deriveAuditActorKind("something-weird")).toBe("system");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveAuditSummaryKey", () => {
|
||||
it("maps known verbs and falls back to generic", () => {
|
||||
expect(deriveAuditSummaryKey("kontakt.created")).toBe("audit.summary.created");
|
||||
expect(deriveAuditSummaryKey("audit.exported")).toBe("audit.summary.exported");
|
||||
expect(deriveAuditSummaryKey("user.signed_in")).toBe("audit.summary.login");
|
||||
expect(deriveAuditSummaryKey("weird.thing.happened")).toBe("audit.summary.generic");
|
||||
});
|
||||
|
||||
it("always returns a valid i18n key", () => {
|
||||
expect(deriveAuditSummaryKey("anything")).toMatch(I18N_KEY);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildAuditListVM", () => {
|
||||
it("returns a ready empty-state with i18n keys when there are no rows", () => {
|
||||
const vm = buildAuditListVM({ rows: [], filter, pagination, canExport: true });
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows).toHaveLength(0);
|
||||
expect(vm.data.emptyHeadlineKey).toMatch(I18N_KEY);
|
||||
expect(vm.data.emptyBodyKey).toMatch(I18N_KEY);
|
||||
expect(vm.data.canExport).toBe(true);
|
||||
});
|
||||
|
||||
it("maps actor-kind marker, summary key and detail flag per row", () => {
|
||||
const vm = buildAuditListVM({
|
||||
rows: [row(), row({ id: "a2", actorType: "system", actorEmail: null, actorId: null, action: "x.y", hasMetadata: false })],
|
||||
filter,
|
||||
pagination: { ...pagination, total: 2 },
|
||||
canExport: false,
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
const [first, second] = vm.data.rows;
|
||||
expect(first?.actorKind).toBe("user");
|
||||
expect(first?.actorKindLabelKey).toBe("audit.actorKind.user");
|
||||
expect(first?.actorLabel).toBe("akeshan@example.com");
|
||||
expect(first?.summaryKey).toBe("audit.summary.created");
|
||||
expect(first?.summaryParams.target).toBe("Kontakt#k1");
|
||||
expect(first?.hasDetail).toBe(true);
|
||||
// system actor without email/id falls back to the marker i18n key
|
||||
expect(second?.actorKind).toBe("system");
|
||||
expect(second?.actorLabel).toMatch(I18N_KEY);
|
||||
expect(second?.hasDetail).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildAuditFieldDiffs / persisted summary (AK-P3 DoD 2)", () => {
|
||||
it("prefers the persisted summaryText and keeps the derived key as fallback", () => {
|
||||
const vm = buildAuditListVM({
|
||||
rows: [row({ summaryText: " Kontakt angelegt " }), row({ id: "a2", summaryText: null })],
|
||||
filter,
|
||||
pagination,
|
||||
canExport: true,
|
||||
});
|
||||
expect(vm.data?.rows[0]?.summaryText).toBe("Kontakt angelegt");
|
||||
expect(vm.data?.rows[1]?.summaryText).toBeNull();
|
||||
expect(vm.data?.rows[1]?.summaryKey).toMatch(I18N_KEY);
|
||||
});
|
||||
|
||||
it("builds a sorted field-by-field diff with masking for redacted values", () => {
|
||||
const diffs = buildAuditFieldDiffs(
|
||||
{ name: "Alt GmbH", apiKey: "[REDACTED]", status: "kontakt" },
|
||||
{ name: "Neu GmbH", apiKey: "[REDACTED]", plz: "10115" }
|
||||
);
|
||||
expect(diffs.map((entry) => entry.field)).toEqual(["apiKey", "name", "plz", "status"]);
|
||||
const masked = diffs.find((entry) => entry.field === "apiKey");
|
||||
expect(masked).toEqual({ field: "apiKey", before: null, after: null, masked: true });
|
||||
expect(diffs.find((entry) => entry.field === "name")).toEqual({
|
||||
field: "name",
|
||||
before: "Alt GmbH",
|
||||
after: "Neu GmbH",
|
||||
masked: false,
|
||||
});
|
||||
expect(diffs.find((entry) => entry.field === "plz")).toEqual({ field: "plz", before: null, after: "10115", masked: false });
|
||||
});
|
||||
|
||||
it("collapses scalar diffs to a single value row and returns [] for legacy rows", () => {
|
||||
expect(buildAuditFieldDiffs("alt", "neu")).toEqual([{ field: "value", before: "alt", after: "neu", masked: false }]);
|
||||
expect(buildAuditFieldDiffs(null, undefined)).toEqual([]);
|
||||
});
|
||||
|
||||
it("wires diff/metadata into rows and the hot-swap model", () => {
|
||||
const vm = buildAuditListVM({
|
||||
rows: [
|
||||
row({
|
||||
beforeDiff: { status: "kontakt" },
|
||||
afterDiff: { status: "kunde" },
|
||||
metadata: { reason: "upgrade" },
|
||||
summaryText: "Status geändert",
|
||||
hasMetadata: true,
|
||||
}),
|
||||
row({ id: "legacy", hasMetadata: false }),
|
||||
],
|
||||
filter,
|
||||
pagination,
|
||||
canExport: false,
|
||||
});
|
||||
const first = vm.data?.rows[0];
|
||||
expect(first?.diff).toEqual([{ field: "status", before: "kontakt", after: "kunde", masked: false }]);
|
||||
expect(first?.metadataJson).toContain("upgrade");
|
||||
expect(first?.hasDetail).toBe(true);
|
||||
expect(vm.data?.rows[1]?.diff).toEqual([]);
|
||||
expect(vm.data?.rows[1]?.hasDetail).toBe(false);
|
||||
|
||||
if (vm.status !== "ready") throw new Error("expected ready VM");
|
||||
const model = toAuditListModel(vm.data);
|
||||
expect(model.rows[0]).toMatchObject({ summaryText: "Status geändert", diffCount: 1, hasDetail: true });
|
||||
expect(model.rowCount).toBe(2);
|
||||
expect(model.titleKey).toMatch(I18N_KEY);
|
||||
});
|
||||
});
|
||||
+303
@@ -0,0 +1,303 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* Audit-Viewer list view-model (AK-P3). Pure function: the loader builds it once
|
||||
* server-side, the UI only renders. No React, no Prisma, no app imports (DoD A.3).
|
||||
* All texts are i18n keys; the German summary line is emitted as a key + params
|
||||
* so the route resolves it with `t()` (keeps the builder pure + locale-agnostic).
|
||||
*
|
||||
* Since 2026-07 the AuditEvent table carries the LOCKED-ENTITY-MODEL columns
|
||||
* `beforeDiff`/`afterDiff` (write-time sanitized JSONB) and `summaryText`.
|
||||
* The builder prefers the persisted summary and renders a field-by-field diff
|
||||
* for the detail drawer; rows written before the columns existed fall back to
|
||||
* the derived summary + raw metadata detail.
|
||||
*/
|
||||
|
||||
/** Normalized actor marker shown next to each entry (DoD: Actor-Kind-Marker). */
|
||||
export type AuditActorKind = "user" | "admin" | "system" | "api_key" | "plugin" | "automation" | "ki_agent";
|
||||
|
||||
/**
|
||||
* One field of the before/after comparison in the detail drawer. Masked
|
||||
* entries (write-time redaction hit the value) expose no values at all —
|
||||
* the drawer renders a "value changed" placeholder instead (DoD 2).
|
||||
*/
|
||||
export type AuditFieldDiff = {
|
||||
readonly field: string;
|
||||
readonly before: string | null;
|
||||
readonly after: string | null;
|
||||
readonly masked: boolean;
|
||||
};
|
||||
|
||||
export type AuditListRow = {
|
||||
readonly id: string;
|
||||
readonly createdAtIso: string;
|
||||
readonly actorKind: AuditActorKind;
|
||||
/** i18n key for the actor-kind marker label, e.g. `audit.actorKind.user`. */
|
||||
readonly actorKindLabelKey: string;
|
||||
/** Best human label for the actor (email > id > marker fallback key). */
|
||||
readonly actorLabel: string;
|
||||
readonly action: string;
|
||||
/** Persisted German summary line — preferred over the derived template. */
|
||||
readonly summaryText: string | null;
|
||||
/** i18n key of the German summary template, resolved with {@link summaryParams}. */
|
||||
readonly summaryKey: string;
|
||||
readonly summaryParams: Readonly<Record<string, string>>;
|
||||
readonly targetType: string | null;
|
||||
readonly targetId: string | null;
|
||||
readonly outcome: string;
|
||||
/** Field-by-field before/after comparison (empty for legacy rows). */
|
||||
readonly diff: readonly AuditFieldDiff[];
|
||||
/** Pretty-printed sanitized metadata for the drawer fallback section. */
|
||||
readonly metadataJson: string | null;
|
||||
/** True when the row carries inspectable detail (diff or metadata). */
|
||||
readonly hasDetail: boolean;
|
||||
};
|
||||
|
||||
export type AuditListFilterState = {
|
||||
readonly from: string | null;
|
||||
readonly to: string | null;
|
||||
readonly actorType: string | null;
|
||||
readonly action: string | null;
|
||||
readonly outcome: string | null;
|
||||
readonly targetType: string | null;
|
||||
};
|
||||
|
||||
export type AuditListPagination = {
|
||||
readonly page: number;
|
||||
readonly pageSize: number;
|
||||
readonly total: number;
|
||||
readonly totalPages: number;
|
||||
};
|
||||
|
||||
export interface AuditListData {
|
||||
readonly rows: readonly AuditListRow[];
|
||||
readonly filter: AuditListFilterState;
|
||||
readonly pagination: AuditListPagination;
|
||||
readonly canExport: boolean;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type AuditListVM = VMState<AuditListData>;
|
||||
|
||||
/** Raw audit row the loader passes in (already read from the DB, framework-free). */
|
||||
export interface AuditListInputRow {
|
||||
readonly id: string;
|
||||
readonly createdAtIso: string;
|
||||
readonly actorType: string | null;
|
||||
readonly actorEmail: string | null;
|
||||
readonly actorId: string | null;
|
||||
readonly action: string;
|
||||
readonly targetType: string | null;
|
||||
readonly targetId: string | null;
|
||||
readonly outcome: string;
|
||||
readonly hasMetadata: boolean;
|
||||
/** Write-time sanitized metadata (already redacted) for the drawer fallback. */
|
||||
readonly metadata?: unknown;
|
||||
/** Persisted structured diffs — null/absent for legacy rows. */
|
||||
readonly beforeDiff?: unknown;
|
||||
readonly afterDiff?: unknown;
|
||||
/** Persisted German summary — null/absent for legacy rows. */
|
||||
readonly summaryText?: string | null;
|
||||
}
|
||||
|
||||
export interface BuildAuditListVMInput {
|
||||
readonly rows: readonly AuditListInputRow[];
|
||||
readonly filter: AuditListFilterState;
|
||||
readonly pagination: AuditListPagination;
|
||||
readonly canExport: boolean;
|
||||
}
|
||||
|
||||
const KNOWN_ACTOR_KINDS: ReadonlySet<AuditActorKind> = new Set([
|
||||
"user",
|
||||
"admin",
|
||||
"system",
|
||||
"api_key",
|
||||
"plugin",
|
||||
"automation",
|
||||
"ki_agent",
|
||||
]);
|
||||
|
||||
/** Maps the raw `actorType` onto a normalized {@link AuditActorKind}. */
|
||||
export function deriveAuditActorKind(actorType: string | null | undefined): AuditActorKind {
|
||||
const candidate = (actorType ?? "").trim().toLowerCase().replace(/-/g, "_");
|
||||
if (KNOWN_ACTOR_KINDS.has(candidate as AuditActorKind)) return candidate as AuditActorKind;
|
||||
if (candidate === "apikey") return "api_key";
|
||||
if (candidate === "ki" || candidate === "ai" || candidate === "agent") return "ki_agent";
|
||||
return "system";
|
||||
}
|
||||
|
||||
/** camelCase i18n suffix for an actor kind (snake_case has no place in i18n keys). */
|
||||
function actorKindKeySuffix(kind: AuditActorKind): string {
|
||||
return kind === "api_key" ? "apiKey" : kind === "ki_agent" ? "kiAgent" : kind;
|
||||
}
|
||||
|
||||
const SUMMARY_ACTION_VERBS: ReadonlyArray<readonly [RegExp, string]> = [
|
||||
[/(^|[._])created?$/i, "created"],
|
||||
[/(^|[._])updated?$/i, "updated"],
|
||||
[/(^|[._])deleted?$/i, "deleted"],
|
||||
[/(^|[._])exported?$/i, "exported"],
|
||||
[/(^|[._])(login|signed_?in)$/i, "login"],
|
||||
[/(^|[._])(logout|signed_?out)$/i, "logout"],
|
||||
];
|
||||
|
||||
/**
|
||||
* Picks the German summary i18n key for an action. Known verbs get a specific
|
||||
* template (e.g. `audit.summary.created`), everything else falls back to the
|
||||
* generic line so unmapped actions still render a readable sentence.
|
||||
*/
|
||||
export function deriveAuditSummaryKey(action: string): string {
|
||||
for (const [pattern, verb] of SUMMARY_ACTION_VERBS) {
|
||||
if (pattern.test(action)) return `audit.summary.${verb}`;
|
||||
}
|
||||
return "audit.summary.generic";
|
||||
}
|
||||
|
||||
function actorLabelFor(row: AuditListInputRow, kind: AuditActorKind): string {
|
||||
if (row.actorEmail && row.actorEmail.trim().length > 0) return row.actorEmail.trim();
|
||||
if (row.actorId && row.actorId.trim().length > 0) return row.actorId.trim();
|
||||
return `audit.actorKind.${actorKindKeySuffix(kind)}`;
|
||||
}
|
||||
|
||||
const MASKED_SENTINEL = "[REDACTED]";
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function toDiffDisplayValue(value: unknown): string | null {
|
||||
if (value === undefined || value === null) return null;
|
||||
if (typeof value === "string") return value;
|
||||
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the field-by-field before/after comparison for the detail drawer.
|
||||
* Objects compare per key (union, sorted); scalar/array payloads collapse to a
|
||||
* single `value` row. Entries where the write-time sanitizer redacted either
|
||||
* side are marked `masked` and carry no values (DoD 2 masking rule).
|
||||
*/
|
||||
export function buildAuditFieldDiffs(beforeDiff: unknown, afterDiff: unknown): AuditFieldDiff[] {
|
||||
if ((beforeDiff === null || beforeDiff === undefined) && (afterDiff === null || afterDiff === undefined)) {
|
||||
return [];
|
||||
}
|
||||
if (!isPlainObject(beforeDiff) && !isPlainObject(afterDiff)) {
|
||||
const before = toDiffDisplayValue(beforeDiff);
|
||||
const after = toDiffDisplayValue(afterDiff);
|
||||
const masked = before === MASKED_SENTINEL || after === MASKED_SENTINEL;
|
||||
return [{ field: "value", before: masked ? null : before, after: masked ? null : after, masked }];
|
||||
}
|
||||
const beforeRecord = isPlainObject(beforeDiff) ? beforeDiff : {};
|
||||
const afterRecord = isPlainObject(afterDiff) ? afterDiff : {};
|
||||
const fields = Array.from(new Set([...Object.keys(beforeRecord), ...Object.keys(afterRecord)])).sort();
|
||||
return fields.map((field) => {
|
||||
const before = toDiffDisplayValue(beforeRecord[field]);
|
||||
const after = toDiffDisplayValue(afterRecord[field]);
|
||||
const masked = before === MASKED_SENTINEL || after === MASKED_SENTINEL;
|
||||
return { field, before: masked ? null : before, after: masked ? null : after, masked };
|
||||
});
|
||||
}
|
||||
|
||||
function toMetadataJson(metadata: unknown): string | null {
|
||||
if (metadata === null || metadata === undefined) return null;
|
||||
try {
|
||||
return JSON.stringify(metadata, null, 2);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function buildAuditListVM(input: BuildAuditListVMInput): AuditListVM {
|
||||
const rows: AuditListRow[] = input.rows.map((row) => {
|
||||
const actorKind = deriveAuditActorKind(row.actorType);
|
||||
const diff = buildAuditFieldDiffs(row.beforeDiff, row.afterDiff);
|
||||
const metadataJson = toMetadataJson(row.metadata);
|
||||
const summaryText = row.summaryText && row.summaryText.trim().length > 0 ? row.summaryText.trim() : null;
|
||||
return {
|
||||
id: row.id,
|
||||
createdAtIso: row.createdAtIso,
|
||||
actorKind,
|
||||
actorKindLabelKey: `audit.actorKind.${actorKindKeySuffix(actorKind)}`,
|
||||
actorLabel: actorLabelFor(row, actorKind),
|
||||
action: row.action,
|
||||
summaryText,
|
||||
summaryKey: deriveAuditSummaryKey(row.action),
|
||||
summaryParams: {
|
||||
actor: actorLabelFor(row, actorKind),
|
||||
action: row.action,
|
||||
target: row.targetType ? `${row.targetType}${row.targetId ? `#${row.targetId}` : ""}` : "",
|
||||
},
|
||||
targetType: row.targetType,
|
||||
targetId: row.targetId,
|
||||
outcome: row.outcome,
|
||||
diff,
|
||||
metadataJson,
|
||||
hasDetail: diff.length > 0 || metadataJson !== null || row.hasMetadata,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows,
|
||||
filter: input.filter,
|
||||
pagination: input.pagination,
|
||||
canExport: input.canExport,
|
||||
emptyHeadlineKey: "audit.viewer.empty.headline",
|
||||
emptyBodyKey: "audit.viewer.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// --- Hot-swap component model (M015/M017) ---
|
||||
|
||||
/** Normalized row model shared by the Subframe and mock renderers. */
|
||||
export interface AuditListModelRow {
|
||||
readonly id: string;
|
||||
readonly createdAtIso: string;
|
||||
readonly actorKindLabelKey: string;
|
||||
readonly actorLabel: string;
|
||||
readonly action: string;
|
||||
readonly outcome: string;
|
||||
/** Persisted summary text, or null when the renderer should show the key. */
|
||||
readonly summaryText: string | null;
|
||||
readonly summaryKey: string;
|
||||
readonly diffCount: number;
|
||||
readonly hasDetail: boolean;
|
||||
}
|
||||
|
||||
export interface AuditListModel {
|
||||
readonly titleKey: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
readonly canExport: boolean;
|
||||
readonly page: number;
|
||||
readonly totalPages: number;
|
||||
readonly rows: readonly AuditListModelRow[];
|
||||
readonly rowCount: number;
|
||||
}
|
||||
|
||||
export function toAuditListModel(data: AuditListData): AuditListModel {
|
||||
return {
|
||||
titleKey: "audit.viewer.title",
|
||||
emptyHeadlineKey: data.emptyHeadlineKey,
|
||||
emptyBodyKey: data.emptyBodyKey,
|
||||
canExport: data.canExport,
|
||||
page: data.pagination.page,
|
||||
totalPages: data.pagination.totalPages,
|
||||
rows: data.rows.map((row) => ({
|
||||
id: row.id,
|
||||
createdAtIso: row.createdAtIso,
|
||||
actorKindLabelKey: row.actorKindLabelKey,
|
||||
actorLabel: row.actorLabel,
|
||||
action: row.action,
|
||||
outcome: row.outcome,
|
||||
summaryText: row.summaryText,
|
||||
summaryKey: row.summaryKey,
|
||||
diffCount: row.diff.length,
|
||||
hasDetail: row.hasDetail,
|
||||
})),
|
||||
rowCount: data.rows.length,
|
||||
};
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildSelectTenantVM, toTenantCard } from "./select-tenant.vm.js";
|
||||
|
||||
describe("toTenantCard initials edge cases (select-tenant.ts:79)", () => {
|
||||
it("falls back to '?' when the name is blank/whitespace only", () => {
|
||||
expect(toTenantCard({ id: "t1", name: " ", slug: "blank" }).avatarInitials).toBe("?");
|
||||
});
|
||||
|
||||
it("takes the first two letters of a single-word name", () => {
|
||||
expect(toTenantCard({ id: "t1", name: "Acme", slug: "acme" }).avatarInitials).toBe("AC");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildSelectTenantVM current-tenant sort branches (select-tenant.ts:111)", () => {
|
||||
it("pulls the current tenant to the front when it sits last in the input", () => {
|
||||
const vm = buildSelectTenantVM({
|
||||
tenants: [
|
||||
{ id: "t1", name: "Alpha", slug: "alpha" },
|
||||
{ id: "t2", name: "Beta", slug: "beta" },
|
||||
{ id: "t3", name: "Gamma", slug: "gamma" },
|
||||
],
|
||||
currentTenantId: "t3",
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.tenants[0].id).toBe("t3");
|
||||
expect(vm.data.tenants.slice(1).map((c) => c.name)).toEqual(["Alpha", "Beta"]);
|
||||
});
|
||||
|
||||
it("keeps the current tenant first when it already leads the input", () => {
|
||||
const vm = buildSelectTenantVM({
|
||||
tenants: [
|
||||
{ id: "t1", name: "Alpha", slug: "alpha" },
|
||||
{ id: "t2", name: "Beta", slug: "beta" },
|
||||
],
|
||||
currentTenantId: "t1",
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.tenants.map((c) => c.id)).toEqual(["t1", "t2"]);
|
||||
});
|
||||
});
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { toSelectTenantModel, type SelectTenantData } from "./select-tenant.vm.js";
|
||||
|
||||
function data(overrides: Partial<SelectTenantData> = {}): SelectTenantData {
|
||||
return {
|
||||
tenants: [
|
||||
{
|
||||
id: "t-current",
|
||||
name: "Acme GmbH",
|
||||
slug: "acme",
|
||||
avatarInitials: "AG",
|
||||
avatarColor: "blue",
|
||||
role: "owner",
|
||||
roleLabelKey: "account.selectTenant.role.owner",
|
||||
roleTone: "red-subtle",
|
||||
isCurrent: true,
|
||||
},
|
||||
{
|
||||
id: "t-other",
|
||||
name: "Globex AG",
|
||||
slug: "globex",
|
||||
avatarInitials: "GA",
|
||||
avatarColor: "green",
|
||||
isCurrent: false,
|
||||
},
|
||||
],
|
||||
totalCount: 2,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("toSelectTenantModel (M015 hot-swap mapper)", () => {
|
||||
it("maps the domain data to the normalized model with i18n keys", () => {
|
||||
const model = toSelectTenantModel(data());
|
||||
expect(model.titleKey).toBe("account.selectTenant.title");
|
||||
expect(model.emptyHeadlineKey).toBe("account.selectTenant.empty");
|
||||
expect(model.rowCount).toBe(2);
|
||||
expect(model.totalCount).toBe(2);
|
||||
expect(model.rows.map((row) => row.id)).toEqual(["t-current", "t-other"]);
|
||||
});
|
||||
|
||||
it("carries the role label as an i18n key + tone, or null when the role is absent", () => {
|
||||
const model = toSelectTenantModel(data());
|
||||
expect(model.rows[0]?.roleLabelKey).toBe("account.selectTenant.role.owner");
|
||||
expect(model.rows[0]?.roleTone).toBe("red-subtle");
|
||||
expect(model.rows[1]?.roleLabelKey).toBeNull();
|
||||
expect(model.rows[1]?.roleTone).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps tenant name/slug/initials as data", () => {
|
||||
const model = toSelectTenantModel(data());
|
||||
expect(model.rows[0]?.name).toBe("Acme GmbH");
|
||||
expect(model.rows[0]?.slug).toBe("acme");
|
||||
expect(model.rows[0]?.avatarInitials).toBe("AG");
|
||||
expect(model.rows[0]?.isCurrent).toBe(true);
|
||||
});
|
||||
|
||||
it("maps an empty tenant list to a zero-row model", () => {
|
||||
const model = toSelectTenantModel(data({ tenants: [], totalCount: 0 }));
|
||||
expect(model.rowCount).toBe(0);
|
||||
expect(model.rows).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
+50
@@ -116,3 +116,53 @@ export function buildSelectTenantVM(input: BuildSelectTenantInput): VMState<Sele
|
||||
data: { tenants: sorted, totalCount: sorted.length },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalized prop-model the UI implementation renders (M015 Subframe-adapter
|
||||
* contract). The ui-app `selectTenant` adapter maps {@link SelectTenantData} ->
|
||||
* this model once, then the ui-subframe / ui-mock renderers stay dumb (hot-swap
|
||||
* drill, M017). Role label travels as an i18n key + tone literal (data), so the
|
||||
* renderer resolves no copy itself (DoD i18n).
|
||||
*/
|
||||
export interface SelectTenantModelRow {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly slug: string;
|
||||
readonly avatarImage: string | null;
|
||||
readonly avatarInitials: string;
|
||||
readonly avatarColor: AvatarColor;
|
||||
readonly roleLabelKey: string | null;
|
||||
readonly roleTone: RoleTone | null;
|
||||
readonly isCurrent: boolean;
|
||||
readonly subtitle: string | null;
|
||||
}
|
||||
|
||||
export interface SelectTenantModel {
|
||||
readonly titleKey: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly totalCount: number;
|
||||
readonly rows: readonly SelectTenantModelRow[];
|
||||
readonly rowCount: number;
|
||||
}
|
||||
|
||||
/** Map the domain data to the normalized hot-swap model (used by the ui-app adapter). */
|
||||
export function toSelectTenantModel(data: SelectTenantData): SelectTenantModel {
|
||||
return {
|
||||
titleKey: "account.selectTenant.title",
|
||||
emptyHeadlineKey: "account.selectTenant.empty",
|
||||
totalCount: data.totalCount,
|
||||
rows: data.tenants.map((tenant) => ({
|
||||
id: tenant.id,
|
||||
name: tenant.name,
|
||||
slug: tenant.slug,
|
||||
avatarImage: tenant.avatarImage ?? null,
|
||||
avatarInitials: tenant.avatarInitials,
|
||||
avatarColor: tenant.avatarColor,
|
||||
roleLabelKey: tenant.roleLabelKey ?? null,
|
||||
roleTone: tenant.roleTone ?? null,
|
||||
isCurrent: tenant.isCurrent,
|
||||
subtitle: tenant.subtitle ?? null,
|
||||
})),
|
||||
rowCount: data.tenants.length,
|
||||
};
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildSessionListVM } from "./session-list.vm.js";
|
||||
|
||||
const NOW = Date.UTC(2026, 5, 18, 12, 0, 0);
|
||||
|
||||
describe("toMs string-vs-Date handling (session-list.ts:61)", () => {
|
||||
it("accepts an ISO string for lastSeenAt and normalizes it to ISO", () => {
|
||||
const iso = new Date(NOW - 5 * 60 * 1000).toISOString();
|
||||
const vm = buildSessionListVM({
|
||||
sessions: [{ id: "s1", lastSeenAt: iso }],
|
||||
currentSessionId: "s1",
|
||||
nowMs: NOW,
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.devices[0].lastSeenIso).toBe(iso);
|
||||
expect(vm.data.devices[0].lastSeenBucket).toBe("minutes");
|
||||
expect(vm.data.devices[0].lastSeenCount).toBe(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildSessionListVM ordering branches (session-list.ts:104)", () => {
|
||||
it("keeps insertion order when no session is the current one (equal branch)", () => {
|
||||
const vm = buildSessionListVM({
|
||||
sessions: [
|
||||
{ id: "s1", lastSeenAt: new Date(NOW) },
|
||||
{ id: "s2", lastSeenAt: new Date(NOW) },
|
||||
],
|
||||
currentSessionId: null,
|
||||
nowMs: NOW,
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.devices.map((d) => d.id)).toEqual(["s1", "s2"]);
|
||||
expect(vm.data.otherActiveCount).toBe(2);
|
||||
});
|
||||
|
||||
it("keeps the current device first when it already leads the input", () => {
|
||||
const vm = buildSessionListVM({
|
||||
sessions: [
|
||||
{ id: "s1", lastSeenAt: new Date(NOW) },
|
||||
{ id: "s2", lastSeenAt: new Date(NOW) },
|
||||
],
|
||||
currentSessionId: "s1",
|
||||
nowMs: NOW,
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.devices[0].id).toBe("s1");
|
||||
});
|
||||
});
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { toSessionListModel, type SessionListData } from "./session-list.vm.js";
|
||||
|
||||
const I18N_KEY = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/;
|
||||
|
||||
function data(overrides: Partial<SessionListData> = {}): SessionListData {
|
||||
return {
|
||||
devices: [
|
||||
{
|
||||
id: "s-current",
|
||||
isCurrent: true,
|
||||
trusted: true,
|
||||
deviceLabel: "Chrome",
|
||||
approxLocation: "Berlin, DE",
|
||||
lastSeenIso: "2026-07-06T09:00:00.000Z",
|
||||
lastSeenBucket: "justNow",
|
||||
canRevoke: false,
|
||||
},
|
||||
{
|
||||
id: "s-other",
|
||||
isCurrent: false,
|
||||
trusted: false,
|
||||
deviceLabelFallbackKey: "settings.security.sessions.unknownDevice",
|
||||
lastSeenIso: "2026-07-06T07:00:00.000Z",
|
||||
lastSeenBucket: "hours",
|
||||
lastSeenCount: 2,
|
||||
canRevoke: true,
|
||||
},
|
||||
],
|
||||
currentDeviceId: "s-current",
|
||||
otherActiveCount: 1,
|
||||
canRevokeOthers: true,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("toSessionListModel (M015 hot-swap mapper)", () => {
|
||||
it("maps the domain data to the normalized model with i18n keys", () => {
|
||||
const model = toSessionListModel(data());
|
||||
expect(model.titleKey).toMatch(I18N_KEY);
|
||||
expect(model.emptyHeadlineKey).toMatch(I18N_KEY);
|
||||
expect(model.rowCount).toBe(2);
|
||||
expect(model.currentDeviceId).toBe("s-current");
|
||||
expect(model.otherActiveCount).toBe(1);
|
||||
expect(model.canRevokeOthers).toBe(true);
|
||||
});
|
||||
|
||||
it("carries the raw device label as data and the fallback key when missing", () => {
|
||||
const model = toSessionListModel(data());
|
||||
expect(model.rows[0]?.deviceLabel).toBe("Chrome");
|
||||
expect(model.rows[0]?.deviceLabelFallbackKey).toBeNull();
|
||||
expect(model.rows[1]?.deviceLabel).toBeNull();
|
||||
expect(model.rows[1]?.deviceLabelFallbackKey).toBe("settings.security.sessions.unknownDevice");
|
||||
});
|
||||
|
||||
it("passes the bucketed last-seen through without pre-formatting", () => {
|
||||
const model = toSessionListModel(data());
|
||||
expect(model.rows[0]?.lastSeenBucket).toBe("justNow");
|
||||
expect(model.rows[0]?.lastSeenCount).toBeNull();
|
||||
expect(model.rows[1]?.lastSeenBucket).toBe("hours");
|
||||
expect(model.rows[1]?.lastSeenCount).toBe(2);
|
||||
});
|
||||
|
||||
it("maps an empty device list to a zero-row model", () => {
|
||||
const model = toSessionListModel(data({ devices: [], otherActiveCount: 0, canRevokeOthers: false }));
|
||||
expect(model.rowCount).toBe(0);
|
||||
expect(model.rows).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
+55
@@ -113,3 +113,58 @@ export function buildSessionListVM(input: BuildSessionListVMInput): SessionListV
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalized prop-model the UI implementation renders (M015 Subframe-adapter
|
||||
* contract). The ui-app `sessionList` adapter maps {@link SessionListData} -> this
|
||||
* model once, then the ui-subframe / ui-mock renderers stay dumb (hot-swap drill,
|
||||
* M017). Bucketed last-seen + the i18n device-fallback key travel as data, so the
|
||||
* renderer resolves no copy itself (DoD i18n).
|
||||
*/
|
||||
export interface SessionListModelRow {
|
||||
readonly id: string;
|
||||
/** Raw device label as DATA, or null when only the i18n fallback applies. */
|
||||
readonly deviceLabel: string | null;
|
||||
readonly deviceLabelFallbackKey: string | null;
|
||||
readonly approxLocation: string | null;
|
||||
readonly lastSeenIso: string;
|
||||
readonly lastSeenBucket: LastSeenBucket;
|
||||
readonly lastSeenCount: number | null;
|
||||
readonly isCurrent: boolean;
|
||||
readonly trusted: boolean;
|
||||
readonly canRevoke: boolean;
|
||||
}
|
||||
|
||||
export interface SessionListModel {
|
||||
readonly titleKey: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly currentDeviceId: string | null;
|
||||
readonly otherActiveCount: number;
|
||||
readonly canRevokeOthers: boolean;
|
||||
readonly rows: readonly SessionListModelRow[];
|
||||
readonly rowCount: number;
|
||||
}
|
||||
|
||||
/** Map the domain data to the normalized hot-swap model (used by the ui-app adapter). */
|
||||
export function toSessionListModel(data: SessionListData): SessionListModel {
|
||||
return {
|
||||
titleKey: "settings.security.sessions.heading",
|
||||
emptyHeadlineKey: "settings.security.sessions.empty",
|
||||
currentDeviceId: data.currentDeviceId,
|
||||
otherActiveCount: data.otherActiveCount,
|
||||
canRevokeOthers: data.canRevokeOthers,
|
||||
rows: data.devices.map((device) => ({
|
||||
id: device.id,
|
||||
deviceLabel: device.deviceLabel ?? null,
|
||||
deviceLabelFallbackKey: device.deviceLabelFallbackKey ?? null,
|
||||
approxLocation: device.approxLocation ?? null,
|
||||
lastSeenIso: device.lastSeenIso,
|
||||
lastSeenBucket: device.lastSeenBucket,
|
||||
lastSeenCount: device.lastSeenCount ?? null,
|
||||
isCurrent: device.isCurrent,
|
||||
trusted: device.trusted,
|
||||
canRevoke: device.canRevoke,
|
||||
})),
|
||||
rowCount: data.devices.length,
|
||||
};
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* AK-P16b · bookings list view-model (M06 Block C). Pure (DoD A.3): the loader
|
||||
* resolves appointments already permission-filtered (read_own → own provider rows
|
||||
* only) and this shapes the table. Customer name/email come from the booking's
|
||||
* intake answers (no cross-entity join needed). Status is rendered via an i18n key.
|
||||
*/
|
||||
|
||||
export type AppointmentStatus = "scheduled" | "held" | "cancelled" | "no_show" | "rescheduled";
|
||||
|
||||
export interface BookingListRow {
|
||||
readonly id: string;
|
||||
readonly startAtIso: string;
|
||||
readonly endAtIso: string;
|
||||
readonly status: AppointmentStatus;
|
||||
/** i18n key for the status pill (e.g. `bookings.status.scheduled`). */
|
||||
readonly statusKey: string;
|
||||
readonly customerName: string;
|
||||
readonly customerEmail: string;
|
||||
readonly pageTitle: string;
|
||||
readonly providerUserId: string;
|
||||
readonly detailHref: string;
|
||||
}
|
||||
|
||||
export interface BookingListData {
|
||||
readonly rows: readonly BookingListRow[];
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type BookingListVM = VMState<BookingListData>;
|
||||
|
||||
/** i18n key for an appointment status pill. */
|
||||
export function bookingStatusKey(status: AppointmentStatus): string {
|
||||
return `bookings.status.${status}`;
|
||||
}
|
||||
|
||||
export interface BuildBookingListInput {
|
||||
readonly rows: readonly BookingListRow[];
|
||||
}
|
||||
|
||||
export function buildBookingListVM(input: BuildBookingListInput): BookingListVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows: input.rows,
|
||||
emptyHeadlineKey: "bookings.list.empty.headline",
|
||||
emptyBodyKey: "bookings.list.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildBookingListVM, bookingStatusKey, type BookingListRow } from "./booking-list.vm.js";
|
||||
|
||||
const row = (over: Partial<BookingListRow> = {}): BookingListRow => ({
|
||||
id: "a1",
|
||||
startAtIso: "2026-07-01T09:00:00.000Z",
|
||||
endAtIso: "2026-07-01T09:30:00.000Z",
|
||||
status: "scheduled",
|
||||
statusKey: bookingStatusKey("scheduled"),
|
||||
customerName: "Max Muster",
|
||||
customerEmail: "max@example.com",
|
||||
pageTitle: "Wartungstermin",
|
||||
providerUserId: "u1",
|
||||
detailHref: "/t/bookings/a1",
|
||||
...over,
|
||||
});
|
||||
|
||||
describe("buildBookingListVM (M06 Block C)", () => {
|
||||
it("is always ready and carries the rows + empty keys", () => {
|
||||
const vm = buildBookingListVM({ rows: [row()] });
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready" || !vm.data) {
|
||||
throw new Error("expected ready");
|
||||
}
|
||||
expect(vm.data.rows).toHaveLength(1);
|
||||
expect(vm.data.emptyHeadlineKey).toBe("bookings.list.empty.headline");
|
||||
expect(vm.data.emptyBodyKey).toBe("bookings.list.empty.body");
|
||||
});
|
||||
|
||||
it("ready with an empty rows array (the UI renders the empty state)", () => {
|
||||
const vm = buildBookingListVM({ rows: [] });
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready" || !vm.data) {
|
||||
throw new Error("expected ready");
|
||||
}
|
||||
expect(vm.data.rows).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("maps every status to a stable i18n key", () => {
|
||||
expect(bookingStatusKey("scheduled")).toBe("bookings.status.scheduled");
|
||||
expect(bookingStatusKey("held")).toBe("bookings.status.held");
|
||||
expect(bookingStatusKey("cancelled")).toBe("bookings.status.cancelled");
|
||||
expect(bookingStatusKey("no_show")).toBe("bookings.status.no_show");
|
||||
expect(bookingStatusKey("rescheduled")).toBe("bookings.status.rescheduled");
|
||||
});
|
||||
});
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* AK-P16a · calendar view view-model (M25 Block B). Pure (DoD A.3). Renders the
|
||||
* caller's OWN events from all sources with a source marker (DoD 5): HiveGrid
|
||||
* internal (booking/projekt/plantafel) and external-synced (Google). Bespoke grid
|
||||
* UI waits on David D-P16 — this VM feeds both the functional shell now and the
|
||||
* grid later. External event titles are the OWNER's own here (their own calendar);
|
||||
* cross-user leak-protection lives at the availability boundary, not this view.
|
||||
*/
|
||||
|
||||
export type CalendarEventSourceMarker = "hivegrid_internal" | "external_synced";
|
||||
|
||||
export interface CalendarViewEventRow {
|
||||
readonly id: string;
|
||||
readonly source: CalendarEventSourceMarker;
|
||||
/** i18n key for the source marker label/colour (e.g. `calendar.source.external_synced`). */
|
||||
readonly sourceKey: string;
|
||||
readonly title: string;
|
||||
/** ISO timestamps. */
|
||||
readonly startsAt: string;
|
||||
readonly endsAt: string;
|
||||
readonly isAllDay: boolean;
|
||||
/** Set for HiveGrid-internal events linked to a booking/projekt/plantafel. */
|
||||
readonly linkType: string | null;
|
||||
}
|
||||
|
||||
export interface CalendarViewData {
|
||||
readonly events: readonly CalendarViewEventRow[];
|
||||
/** Inclusive ISO date window the loader resolved the events for. */
|
||||
readonly rangeStart: string;
|
||||
readonly rangeEnd: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type CalendarViewVM = VMState<CalendarViewData>;
|
||||
|
||||
export function calendarSourceKey(source: CalendarEventSourceMarker): string {
|
||||
return `calendar.source.${source}`;
|
||||
}
|
||||
|
||||
export interface BuildCalendarViewInput {
|
||||
readonly events: readonly CalendarViewEventRow[];
|
||||
readonly rangeStart: string;
|
||||
readonly rangeEnd: string;
|
||||
}
|
||||
|
||||
export function buildCalendarViewVM(input: BuildCalendarViewInput): CalendarViewVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
events: input.events,
|
||||
rangeStart: input.rangeStart,
|
||||
rangeEnd: input.rangeEnd,
|
||||
emptyHeadlineKey: "calendar.view.empty.headline",
|
||||
emptyBodyKey: "calendar.view.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildCalendarConnectionListVM, calendarConnectionStatusKey, calendarSyncDirectionKey, type CalendarConnectionRow } from "./connection-list.vm.js";
|
||||
import { buildCalendarConnectionDetailVM, calendarConflictResolutionKey, type ConflictLogRow } from "./connection-detail.vm.js";
|
||||
import { buildCalendarViewVM, calendarSourceKey, type CalendarViewEventRow } from "./calendar-view.vm.js";
|
||||
|
||||
const connectionRow: CalendarConnectionRow = {
|
||||
id: "conn-1",
|
||||
provider: "google",
|
||||
externalAccountEmail: "noah@example.com",
|
||||
status: "active",
|
||||
statusKey: calendarConnectionStatusKey("active"),
|
||||
syncDirection: "bidirectional",
|
||||
syncDirectionKey: calendarSyncDirectionKey("bidirectional"),
|
||||
lastSyncAt: "2026-07-01T10:00:00.000Z",
|
||||
lastErrorText: null,
|
||||
detailHref: "/t/settings/integrations/calendar/conn-1",
|
||||
};
|
||||
|
||||
describe("buildCalendarConnectionListVM", () => {
|
||||
it("is always ready and carries empty-state + config keys", () => {
|
||||
const vm = buildCalendarConnectionListVM({ rows: [], canConnect: true, isConfigured: false, connectHref: "/connect" });
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows).toEqual([]);
|
||||
expect(vm.data.isConfigured).toBe(false);
|
||||
expect(vm.data.emptyHeadlineKey).toBe("calendar.connections.empty.headline");
|
||||
expect(vm.data.notConfiguredKey).toBe("calendar.connections.notConfigured");
|
||||
});
|
||||
|
||||
it("passes connection rows through and never exposes a token field", () => {
|
||||
const vm = buildCalendarConnectionListVM({ rows: [connectionRow], canConnect: true, isConfigured: true, connectHref: "/connect" });
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows).toHaveLength(1);
|
||||
expect(JSON.stringify(vm.data)).not.toMatch(/token|ciphertext|refresh/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe("calendar i18n key helpers", () => {
|
||||
it("namespaces status, direction, source and resolution keys", () => {
|
||||
expect(calendarConnectionStatusKey("error")).toBe("calendar.connection.status.error");
|
||||
expect(calendarSyncDirectionKey("external_to_hivegrid_only")).toBe("calendar.connection.direction.external_to_hivegrid_only");
|
||||
expect(calendarSourceKey("external_synced")).toBe("calendar.source.external_synced");
|
||||
expect(calendarConflictResolutionKey("hivegrid_won")).toBe("calendar.conflict.hivegridWon");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCalendarConnectionDetailVM", () => {
|
||||
const conflict: ConflictLogRow = {
|
||||
id: "cf-1",
|
||||
resolution: "external_won",
|
||||
resolutionKey: calendarConflictResolutionKey("external_won"),
|
||||
descriptionText: "Termin extern geaendert, externe Version uebernommen.",
|
||||
occurredAt: "2026-07-01T09:30:00.000Z",
|
||||
};
|
||||
it("carries the conflict log (DoD 4) and an empty key", () => {
|
||||
const vm = buildCalendarConnectionDetailVM({
|
||||
id: "conn-1",
|
||||
externalAccountEmail: "noah@example.com",
|
||||
status: "active",
|
||||
statusKey: calendarConnectionStatusKey("active"),
|
||||
syncDirection: "bidirectional",
|
||||
lastSyncAt: null,
|
||||
lastErrorText: null,
|
||||
selectedCalendars: [{ externalCalendarId: "primary", name: "Primary", isPrimary: true }],
|
||||
conflicts: [conflict],
|
||||
canManage: true,
|
||||
disconnectHref: "/disconnect",
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.conflicts[0].resolutionKey).toBe("calendar.conflict.externalWon");
|
||||
expect(vm.data.conflictsEmptyKey).toBe("calendar.conflict.empty");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCalendarViewVM", () => {
|
||||
it("renders events with source markers (DoD 5)", () => {
|
||||
const events: CalendarViewEventRow[] = [
|
||||
{ id: "e1", source: "hivegrid_internal", sourceKey: calendarSourceKey("hivegrid_internal"), title: "Montage", startsAt: "2026-07-02T08:00:00.000Z", endsAt: "2026-07-02T10:00:00.000Z", isAllDay: false, linkType: "booking" },
|
||||
{ id: "e2", source: "external_synced", sourceKey: calendarSourceKey("external_synced"), title: "Privat", startsAt: "2026-07-02T12:00:00.000Z", endsAt: "2026-07-02T13:00:00.000Z", isAllDay: false, linkType: null },
|
||||
];
|
||||
const vm = buildCalendarViewVM({ events, rangeStart: "2026-07-01", rangeEnd: "2026-07-31" });
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.events.map((e) => e.sourceKey)).toEqual(["calendar.source.hivegrid_internal", "calendar.source.external_synced"]);
|
||||
});
|
||||
});
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
import type { VMState } from "../index.js";
|
||||
import type { CalendarConnectionStatus, CalendarSyncDirection } from "./connection-list.vm.js";
|
||||
|
||||
/**
|
||||
* AK-P16a · calendar connection detail view-model (M25 Block B/F). Pure (DoD A.3).
|
||||
* Shows ONE connection the caller owns (or any, with calendar.admin): the selected
|
||||
* calendars, sync status, and the last 50 conflicts in Klartext + how each was
|
||||
* resolved (DoD 4). NO tokens here.
|
||||
*/
|
||||
|
||||
export type CalendarConflictResolution = "external_won" | "hivegrid_won" | "external_deleted" | "hivegrid_deleted";
|
||||
|
||||
export interface SelectedCalendarRow {
|
||||
readonly externalCalendarId: string;
|
||||
readonly name: string;
|
||||
readonly isPrimary: boolean;
|
||||
}
|
||||
|
||||
export interface ConflictLogRow {
|
||||
readonly id: string;
|
||||
readonly resolution: CalendarConflictResolution;
|
||||
/** i18n key for the resolution label (e.g. `calendar.conflict.externalWon`). */
|
||||
readonly resolutionKey: string;
|
||||
/** Klartext description shown in the log (already rendered, M002/M003). */
|
||||
readonly descriptionText: string;
|
||||
/** ISO timestamp of the conflict. */
|
||||
readonly occurredAt: string;
|
||||
}
|
||||
|
||||
export interface CalendarConnectionDetailData {
|
||||
readonly id: string;
|
||||
readonly provider: "google";
|
||||
readonly externalAccountEmail: string;
|
||||
readonly status: CalendarConnectionStatus;
|
||||
readonly statusKey: string;
|
||||
readonly syncDirection: CalendarSyncDirection;
|
||||
readonly lastSyncAt: string | null;
|
||||
readonly lastErrorText: string | null;
|
||||
readonly selectedCalendars: readonly SelectedCalendarRow[];
|
||||
/** Up to the last 50 conflicts, newest first (DoD 4). */
|
||||
readonly conflicts: readonly ConflictLogRow[];
|
||||
readonly canManage: boolean;
|
||||
readonly disconnectHref: string;
|
||||
readonly conflictsEmptyKey: string;
|
||||
}
|
||||
|
||||
export type CalendarConnectionDetailVM = VMState<CalendarConnectionDetailData>;
|
||||
|
||||
export function calendarConflictResolutionKey(resolution: CalendarConflictResolution): string {
|
||||
// Maps the snake_case enum to the camelCase i18n suffix used by the resolver.
|
||||
const map: Record<CalendarConflictResolution, string> = {
|
||||
external_won: "externalWon",
|
||||
hivegrid_won: "hivegridWon",
|
||||
external_deleted: "externalDeleted",
|
||||
hivegrid_deleted: "hivegridDeleted",
|
||||
};
|
||||
return `calendar.conflict.${map[resolution]}`;
|
||||
}
|
||||
|
||||
export interface BuildCalendarConnectionDetailInput {
|
||||
readonly id: string;
|
||||
readonly externalAccountEmail: string;
|
||||
readonly status: CalendarConnectionStatus;
|
||||
readonly statusKey: string;
|
||||
readonly syncDirection: CalendarSyncDirection;
|
||||
readonly lastSyncAt: string | null;
|
||||
readonly lastErrorText: string | null;
|
||||
readonly selectedCalendars: readonly SelectedCalendarRow[];
|
||||
readonly conflicts: readonly ConflictLogRow[];
|
||||
readonly canManage: boolean;
|
||||
readonly disconnectHref: string;
|
||||
}
|
||||
|
||||
export function buildCalendarConnectionDetailVM(input: BuildCalendarConnectionDetailInput): CalendarConnectionDetailVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
id: input.id,
|
||||
provider: "google",
|
||||
externalAccountEmail: input.externalAccountEmail,
|
||||
status: input.status,
|
||||
statusKey: input.statusKey,
|
||||
syncDirection: input.syncDirection,
|
||||
lastSyncAt: input.lastSyncAt,
|
||||
lastErrorText: input.lastErrorText,
|
||||
selectedCalendars: input.selectedCalendars,
|
||||
conflicts: input.conflicts,
|
||||
canManage: input.canManage,
|
||||
disconnectHref: input.disconnectHref,
|
||||
conflictsEmptyKey: "calendar.conflict.empty",
|
||||
},
|
||||
};
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* AK-P16a · calendar connection list view-model (M25 Block B). Pure (DoD A.3):
|
||||
* the loader resolves the CURRENT user's own connections (leak-protection — never
|
||||
* another user's) and this builds the settings list. NO tokens/credentials ever
|
||||
* appear here. `isConfigured` reflects the EXT-10 OAuth env presence so the UI can
|
||||
* show a Klartext "not configured" hint instead of a dead connect button.
|
||||
*/
|
||||
|
||||
export type CalendarConnectionStatus = "active" | "paused" | "error" | "revoked";
|
||||
export type CalendarSyncDirection = "bidirectional" | "hivegrid_to_external_only" | "external_to_hivegrid_only";
|
||||
|
||||
export interface CalendarConnectionRow {
|
||||
readonly id: string;
|
||||
readonly provider: "google";
|
||||
readonly externalAccountEmail: string;
|
||||
readonly status: CalendarConnectionStatus;
|
||||
/** i18n key for the status pill (e.g. `calendar.connection.status.active`). */
|
||||
readonly statusKey: string;
|
||||
readonly syncDirection: CalendarSyncDirection;
|
||||
readonly syncDirectionKey: string;
|
||||
/** ISO timestamp of the last successful sync, or null. */
|
||||
readonly lastSyncAt: string | null;
|
||||
/** Klartext error detail when status = error (M002), else null. */
|
||||
readonly lastErrorText: string | null;
|
||||
readonly detailHref: string;
|
||||
}
|
||||
|
||||
export interface CalendarConnectionListData {
|
||||
readonly rows: readonly CalendarConnectionRow[];
|
||||
/** True when the user may connect a calendar (calendar.connect_own). */
|
||||
readonly canConnect: boolean;
|
||||
/** False when the Google OAuth env (EXT-10) is missing — disable connect + hint. */
|
||||
readonly isConfigured: boolean;
|
||||
readonly connectHref: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
readonly notConfiguredKey: string;
|
||||
}
|
||||
|
||||
export type CalendarConnectionListVM = VMState<CalendarConnectionListData>;
|
||||
|
||||
export function calendarConnectionStatusKey(status: CalendarConnectionStatus): string {
|
||||
return `calendar.connection.status.${status}`;
|
||||
}
|
||||
|
||||
export function calendarSyncDirectionKey(direction: CalendarSyncDirection): string {
|
||||
return `calendar.connection.direction.${direction}`;
|
||||
}
|
||||
|
||||
export interface BuildCalendarConnectionListInput {
|
||||
readonly rows: readonly CalendarConnectionRow[];
|
||||
readonly canConnect: boolean;
|
||||
readonly isConfigured: boolean;
|
||||
readonly connectHref: string;
|
||||
}
|
||||
|
||||
export function buildCalendarConnectionListVM(input: BuildCalendarConnectionListInput): CalendarConnectionListVM {
|
||||
// Always "ready" (mirrors the apps-engine catalog VM): the UI renders the
|
||||
// empty-state from `emptyHeadlineKey`/`emptyBodyKey` when `rows` is empty, while
|
||||
// keeping the connect affordance + config hint available.
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows: input.rows,
|
||||
canConnect: input.canConnect,
|
||||
isConfigured: input.isConfigured,
|
||||
connectHref: input.connectHref,
|
||||
emptyHeadlineKey: "calendar.connections.empty.headline",
|
||||
emptyBodyKey: "calendar.connections.empty.body",
|
||||
notConfiguredKey: "calendar.connections.notConfigured",
|
||||
},
|
||||
};
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
import { empty, ready, type VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* Activity-stream view-model (R-P6, P6 CRM core — Variante A). Pure function:
|
||||
* the loader builds it once server-side from the Activity rows + resolved actor
|
||||
* labels. `summaryText` is ALREADY the German Klartext line persisted on the
|
||||
* activity (DoD 14) — it is passed through verbatim, never re-translated. Static
|
||||
* markers are i18n KEYS. No React/Prisma/server imports (DoD A.3).
|
||||
*
|
||||
* The actor/type unions mirror `@hivegrid/activity/types` (kept local so the
|
||||
* view-models package stays dependency-free, matching the task VMs' pattern).
|
||||
*/
|
||||
|
||||
/** Mirrors `ActivityActorKind` from `@hivegrid/activity/types`. */
|
||||
export type ActivityActorKind = "user" | "system" | "automation" | "ki_agent";
|
||||
|
||||
/** Mirrors `ActivityType` from `@hivegrid/activity/types`. */
|
||||
export type ActivityType =
|
||||
| "call_inbound"
|
||||
| "call_outbound"
|
||||
| "email_sent"
|
||||
| "email_received"
|
||||
| "whatsapp_sent"
|
||||
| "whatsapp_received"
|
||||
| "chat_message"
|
||||
| "note_added"
|
||||
| "tag_added"
|
||||
| "tag_removed"
|
||||
| "assignee_changed"
|
||||
| "deal_stage_changed"
|
||||
| "project_stage_changed"
|
||||
| "project_member_added"
|
||||
| "project_appointment_created"
|
||||
| "project_invoice_created"
|
||||
| "project_invoice_status_changed"
|
||||
| "project_checklist_created"
|
||||
| "project_schedule_changed"
|
||||
| "project_acceptance_submitted"
|
||||
| "file_uploaded"
|
||||
| "form_submitted"
|
||||
| "task_created"
|
||||
| "task_completed"
|
||||
| "contact_created"
|
||||
| "contact_updated"
|
||||
| "contact_archived"
|
||||
| "appointment_scheduled"
|
||||
| "appointment_held"
|
||||
| "lead_promoted"
|
||||
| "deal_won"
|
||||
| "deal_lost"
|
||||
| "automation_triggered"
|
||||
| "ki_action"
|
||||
| "audit_event";
|
||||
|
||||
export interface ActivityEntryData {
|
||||
readonly id: string;
|
||||
readonly activityType: ActivityType;
|
||||
/** i18n key for the activity-type label (e.g. `crm.activity.note_added`). */
|
||||
readonly activityLabelKey: string;
|
||||
readonly actorKind: ActivityActorKind;
|
||||
/** Resolved actor display name (data) or null for non-user / system actors. */
|
||||
readonly actorLabel: string | null;
|
||||
/** Pre-rendered Klartext line from the DB — passed through, NOT translated. */
|
||||
readonly summaryText: string;
|
||||
readonly createdAtIso: string;
|
||||
/** Marker key chosen by activity type, falling back to the actor kind. */
|
||||
readonly iconKey: string;
|
||||
}
|
||||
|
||||
export interface ActivityStreamData {
|
||||
readonly entries: readonly ActivityEntryData[];
|
||||
readonly hasMore: boolean;
|
||||
}
|
||||
|
||||
export type ActivityStreamVM = VMState<ActivityStreamData>;
|
||||
|
||||
/** i18n key for an activity type (e.g. `crm.activity.tag_added`). */
|
||||
export function activityLabelKey(activityType: ActivityType): string {
|
||||
return `crm.activity.${activityType}`;
|
||||
}
|
||||
|
||||
/** Pick a stable icon marker: a type-specific marker wins, else the actor kind. */
|
||||
export function activityIconKey(actorKind: ActivityActorKind, activityType: ActivityType): string {
|
||||
switch (activityType) {
|
||||
case "email_sent":
|
||||
case "email_received":
|
||||
return "mail";
|
||||
case "call_inbound":
|
||||
case "call_outbound":
|
||||
return "phone";
|
||||
case "whatsapp_sent":
|
||||
case "whatsapp_received":
|
||||
case "chat_message":
|
||||
return "chat";
|
||||
case "note_added":
|
||||
return "note";
|
||||
case "tag_added":
|
||||
case "tag_removed":
|
||||
return "tag";
|
||||
case "file_uploaded":
|
||||
return "file";
|
||||
case "assignee_changed":
|
||||
return "assignee";
|
||||
case "contact_created":
|
||||
case "contact_updated":
|
||||
case "contact_archived":
|
||||
return "contact";
|
||||
case "task_created":
|
||||
case "task_completed":
|
||||
return "task";
|
||||
default:
|
||||
break;
|
||||
}
|
||||
switch (actorKind) {
|
||||
case "automation":
|
||||
return "automation";
|
||||
case "ki_agent":
|
||||
return "ki";
|
||||
case "system":
|
||||
return "system";
|
||||
default:
|
||||
return "user";
|
||||
}
|
||||
}
|
||||
|
||||
/** Minimal activity source row (mirrors the persisted Activity columns used). */
|
||||
export interface ActivityStreamSourceRow {
|
||||
readonly id: string;
|
||||
readonly createdAt: Date;
|
||||
readonly actorUserId: string | null;
|
||||
readonly actorKind: ActivityActorKind;
|
||||
readonly activityType: ActivityType;
|
||||
readonly summaryText: string;
|
||||
}
|
||||
|
||||
export interface BuildActivityStreamVMInput {
|
||||
readonly rows: readonly ActivityStreamSourceRow[];
|
||||
/** userId -> display label (crmService.resolveUserLabels). */
|
||||
readonly userLabels: ReadonlyMap<string, string>;
|
||||
readonly hasMore: boolean;
|
||||
}
|
||||
|
||||
export function buildActivityStreamVM(input: BuildActivityStreamVMInput): ActivityStreamVM {
|
||||
if (input.rows.length === 0) {
|
||||
return empty<ActivityStreamData>();
|
||||
}
|
||||
const entries: ActivityEntryData[] = input.rows.map((row) => ({
|
||||
id: row.id,
|
||||
activityType: row.activityType,
|
||||
activityLabelKey: activityLabelKey(row.activityType),
|
||||
actorKind: row.actorKind,
|
||||
actorLabel: row.actorUserId ? (input.userLabels.get(row.actorUserId) ?? null) : null,
|
||||
summaryText: row.summaryText,
|
||||
createdAtIso: row.createdAt.toISOString(),
|
||||
iconKey: activityIconKey(row.actorKind, row.activityType),
|
||||
}));
|
||||
return ready<ActivityStreamData>({ entries, hasMore: input.hasMore });
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildActivityStreamVM,
|
||||
buildCustomFieldAdminVM,
|
||||
buildDuplicateVM,
|
||||
buildKontaktCsv,
|
||||
buildKontaktDetailVM,
|
||||
buildKontaktListVM,
|
||||
buildTagAdminVM,
|
||||
type BuildActivityStreamVMInput,
|
||||
type BuildCustomFieldAdminVMInput,
|
||||
type BuildDuplicateVMInput,
|
||||
type BuildKontaktDetailVMInput,
|
||||
type BuildKontaktListVMInput,
|
||||
type BuildTagAdminVMInput,
|
||||
type KontaktListAppliedFilter,
|
||||
} from "../index.js";
|
||||
|
||||
const filter: KontaktListAppliedFilter = {
|
||||
kontaktTyp: null,
|
||||
kontaktStatus: null,
|
||||
zustaendigerUserId: null,
|
||||
search: null,
|
||||
tagIds: null,
|
||||
tagMatch: "or",
|
||||
includeArchived: false,
|
||||
};
|
||||
|
||||
// --- kontakt-list -----------------------------------------------------------
|
||||
describe("buildKontaktListVM", () => {
|
||||
const baseInput: BuildKontaktListVMInput = {
|
||||
rows: [
|
||||
{
|
||||
id: "k1",
|
||||
kontaktTyp: "privatperson",
|
||||
kontaktStatus: "kunde",
|
||||
vorname: "Anna",
|
||||
nachname: "Muster",
|
||||
orgName: null,
|
||||
orgMerkmal: null,
|
||||
primaerEmail: "anna@example.com",
|
||||
primaerTelefon: null,
|
||||
zustaendigerUserId: "u1",
|
||||
createdAt: new Date("2026-06-20T08:00:00.000Z"),
|
||||
archivedAt: null,
|
||||
},
|
||||
{
|
||||
id: "k2",
|
||||
kontaktTyp: "organisation",
|
||||
kontaktStatus: "bestandskunde",
|
||||
vorname: null,
|
||||
nachname: null,
|
||||
orgName: "Acme GmbH",
|
||||
orgMerkmal: "gmbh",
|
||||
primaerEmail: null,
|
||||
primaerTelefon: "+49 30 123",
|
||||
zustaendigerUserId: null,
|
||||
createdAt: new Date("2026-06-21T08:00:00.000Z"),
|
||||
archivedAt: new Date("2026-06-22T08:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
userLabels: new Map([["u1", "Raffael"]]),
|
||||
tagsByKontakt: new Map([["k1", [{ id: "t1", name: "VIP", farbe: "#f00" }]]]),
|
||||
pagination: { page: 2, pageCount: 3, total: 120 },
|
||||
sort: { field: "name", dir: "asc" },
|
||||
filter,
|
||||
perms: { canWrite: true, canDelete: false, canReadAll: true },
|
||||
tenantSlug: "acme",
|
||||
};
|
||||
|
||||
it("returns an empty state when there are no contacts", () => {
|
||||
const vm = buildKontaktListVM({ ...baseInput, rows: [] });
|
||||
expect(vm.status).toBe("empty");
|
||||
});
|
||||
|
||||
it("maps rows with display names, i18n keys, tag chips and internal hrefs", () => {
|
||||
const vm = buildKontaktListVM(baseInput);
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
const [r1, r2] = vm.data.rows;
|
||||
expect(r1?.displayName).toBe("Anna Muster");
|
||||
expect(r1?.typLabelKey).toBe("crm.kontaktTyp.privatperson");
|
||||
expect(r1?.statusLabelKey).toBe("crm.kontaktStatus.kunde");
|
||||
expect(r1?.zustaendigerLabel).toBe("Raffael");
|
||||
expect(r1?.tagChips[0]?.name).toBe("VIP");
|
||||
expect(r1?.orgMerkmalLabelKey).toBeNull();
|
||||
expect(r1?.detailHref).toBe("/acme/contacts/k1");
|
||||
expect(r1?.isArchived).toBe(false);
|
||||
expect(r1?.createdAtIso).toBe("2026-06-20T08:00:00.000Z");
|
||||
// organisation row
|
||||
expect(r2?.displayName).toBe("Acme GmbH");
|
||||
expect(r2?.orgMerkmalLabelKey).toBe("crm.orgMerkmal.gmbh");
|
||||
expect(r2?.zustaendigerLabel).toBeNull();
|
||||
expect(r2?.isArchived).toBe(true);
|
||||
});
|
||||
|
||||
it("derives pagination hasPrev/hasNext and echoes filter/sort/perms", () => {
|
||||
const vm = buildKontaktListVM(baseInput);
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.pagination).toMatchObject({ page: 2, pageCount: 3, total: 120, hasPrev: true, hasNext: true });
|
||||
expect(vm.data.sort).toEqual({ field: "name", dir: "asc" });
|
||||
expect(vm.data.appliedFilter.tagMatch).toBe("or");
|
||||
expect(vm.data.canReadAll).toBe(true);
|
||||
});
|
||||
|
||||
it("fills the optional org-only fields only when supplied", () => {
|
||||
const vm = buildKontaktListVM({
|
||||
...baseInput,
|
||||
orgKontaktAnzahl: new Map([["k2", 4]]),
|
||||
orgLastActivityIso: new Map([["k2", "2026-06-23T08:00:00.000Z"]]),
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows[0]?.kontaktAnzahl).toBeUndefined();
|
||||
expect(vm.data.rows[1]?.kontaktAnzahl).toBe(4);
|
||||
expect(vm.data.rows[1]?.letzteActivityIso).toBe("2026-06-23T08:00:00.000Z");
|
||||
});
|
||||
});
|
||||
|
||||
// --- kontakt-detail ---------------------------------------------------------
|
||||
describe("buildKontaktDetailVM", () => {
|
||||
const base: BuildKontaktDetailVMInput = {
|
||||
detail: {
|
||||
kontakt: {
|
||||
id: "k1",
|
||||
kontaktTyp: "privatperson",
|
||||
kontaktStatus: "kontakt",
|
||||
vorname: "Anna",
|
||||
nachname: "Muster",
|
||||
orgName: null,
|
||||
orgMerkmal: null,
|
||||
primaerEmail: "anna@example.com",
|
||||
zustaendigerUserId: "u1",
|
||||
archivedAt: null,
|
||||
createdAt: new Date("2026-06-20T08:00:00.000Z"),
|
||||
updatedAt: new Date("2026-06-21T08:00:00.000Z"),
|
||||
},
|
||||
emails: [{ id: "e1", email: "anna@example.com", primaer: true }],
|
||||
telefone: [{ id: "p1", telefon: "+49 30 1", primaer: true }],
|
||||
relationen: [
|
||||
{ id: "rel1", vonKontaktId: "k1", zuKontaktId: "k9", rolle: "hauptkontakt", kontext: "Buchhaltung" },
|
||||
{ id: "rel2", vonKontaktId: "k7", zuKontaktId: "k1", rolle: "mitarbeiter", kontext: null },
|
||||
],
|
||||
adresse: { strasse: "Hauptstr", hausnummer: "1", plz: "10115", ort: "Berlin", land: "DE" },
|
||||
},
|
||||
customFields: [{ definition: { id: "d1", key: "umsatz", label: "Umsatz", datentyp: "waehrung", optionen: null }, wert: 1000 }],
|
||||
tags: [{ id: "t1", name: "VIP", farbe: "#f00" }],
|
||||
userLabels: new Map([["u1", "Raffael"]]),
|
||||
perms: { canWrite: true, canDelete: false },
|
||||
tenantSlug: "acme",
|
||||
};
|
||||
|
||||
it("maps channels, relations (von/zu), custom fields and i18n keys", () => {
|
||||
const vm = buildKontaktDetailVM(base);
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.displayName).toBe("Anna Muster");
|
||||
expect(vm.data.typLabelKey).toBe("crm.kontaktTyp.privatperson");
|
||||
expect(vm.data.emails[0]?.primaer).toBe(true);
|
||||
const von = vm.data.relationen.find((r) => r.id === "rel1");
|
||||
const zu = vm.data.relationen.find((r) => r.id === "rel2");
|
||||
expect(von?.richtung).toBe("von");
|
||||
expect(von?.otherKontaktId).toBe("k9");
|
||||
expect(von?.rolleLabelKey).toBe("crm.kontaktArt.hauptkontakt");
|
||||
expect(zu?.richtung).toBe("zu");
|
||||
expect(zu?.otherKontaktId).toBe("k7");
|
||||
expect(vm.data.customFields[0]).toMatchObject({ definitionId: "d1", key: "umsatz", datentyp: "waehrung", wert: 1000 });
|
||||
expect(vm.data.zustaendigerLabel).toBe("Raffael");
|
||||
expect(vm.data.listHref).toBe("/acme/contacts");
|
||||
});
|
||||
|
||||
it("derives quickActions from perms (archive when active, +delete when deletable)", () => {
|
||||
const vm = buildKontaktDetailVM(base);
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.quickActions).toEqual(["addNote", "addTag", "reassign", "archive"]);
|
||||
|
||||
const archived = buildKontaktDetailVM({
|
||||
...base,
|
||||
detail: { ...base.detail, kontakt: { ...base.detail.kontakt, archivedAt: new Date() } },
|
||||
perms: { canWrite: true, canDelete: true },
|
||||
});
|
||||
if (archived.status !== "ready") throw new Error("expected ready");
|
||||
expect(archived.data.quickActions).toContain("reactivate");
|
||||
expect(archived.data.quickActions).toContain("delete");
|
||||
|
||||
const readOnly = buildKontaktDetailVM({ ...base, perms: { canWrite: false, canDelete: false } });
|
||||
if (readOnly.status !== "ready") throw new Error("expected ready");
|
||||
expect(readOnly.data.quickActions).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// --- activity-stream --------------------------------------------------------
|
||||
describe("buildActivityStreamVM", () => {
|
||||
const input: BuildActivityStreamVMInput = {
|
||||
rows: [
|
||||
{ id: "a1", createdAt: new Date("2026-06-20T08:00:00.000Z"), actorUserId: "u1", actorKind: "user", activityType: "note_added", summaryText: "Notiz: Rückruf vereinbart" },
|
||||
{ id: "a2", createdAt: new Date("2026-06-20T09:00:00.000Z"), actorUserId: null, actorKind: "system", activityType: "contact_created", summaryText: "Kontakt angelegt" },
|
||||
],
|
||||
userLabels: new Map([["u1", "Raffael"]]),
|
||||
hasMore: true,
|
||||
};
|
||||
|
||||
it("returns an empty state when there are no entries", () => {
|
||||
expect(buildActivityStreamVM({ ...input, rows: [] }).status).toBe("empty");
|
||||
});
|
||||
|
||||
it("passes summaryText through and derives label/icon/actor", () => {
|
||||
const vm = buildActivityStreamVM(input);
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.hasMore).toBe(true);
|
||||
const e1 = vm.data.entries[0];
|
||||
expect(e1?.summaryText).toBe("Notiz: Rückruf vereinbart");
|
||||
expect(e1?.activityLabelKey).toBe("crm.activity.note_added");
|
||||
expect(e1?.iconKey).toBe("note");
|
||||
expect(e1?.actorLabel).toBe("Raffael");
|
||||
const e2 = vm.data.entries[1];
|
||||
expect(e2?.actorLabel).toBeNull();
|
||||
expect(e2?.iconKey).toBe("contact");
|
||||
});
|
||||
});
|
||||
|
||||
// --- custom-field-admin -----------------------------------------------------
|
||||
describe("buildCustomFieldAdminVM", () => {
|
||||
const input: BuildCustomFieldAdminVMInput = {
|
||||
rows: [{ id: "d1", entityType: "kontakt", key: "umsatz", label: "Umsatz", datentyp: "waehrung", optionen: null, archiviert: false, isDemoData: false }],
|
||||
entityType: "kontakt",
|
||||
canWrite: true,
|
||||
};
|
||||
|
||||
it("stays ready (with the CTA context) even when empty", () => {
|
||||
const vm = buildCustomFieldAdminVM({ ...input, rows: [] });
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows).toHaveLength(0);
|
||||
expect(vm.data.entityType).toBe("kontakt");
|
||||
expect(vm.data.canWrite).toBe(true);
|
||||
});
|
||||
|
||||
it("maps datentyp label keys", () => {
|
||||
const vm = buildCustomFieldAdminVM(input);
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows[0]?.datentypLabelKey).toBe("crm.datentyp.waehrung");
|
||||
});
|
||||
});
|
||||
|
||||
// --- tag-admin --------------------------------------------------------------
|
||||
describe("buildTagAdminVM", () => {
|
||||
const input: BuildTagAdminVMInput = {
|
||||
tags: [
|
||||
{ id: "t1", name: "VIP", farbe: "#f00" },
|
||||
{ id: "t2", name: "Lead", farbe: "#0f0" },
|
||||
],
|
||||
usageCounts: new Map([["t1", 5]]),
|
||||
canWrite: true,
|
||||
};
|
||||
|
||||
it("defaults usageCount to 0 when no count is supplied", () => {
|
||||
const vm = buildTagAdminVM(input);
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows[0]?.usageCount).toBe(5);
|
||||
expect(vm.data.rows[1]?.usageCount).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
// --- duplicate --------------------------------------------------------------
|
||||
describe("buildDuplicateVM", () => {
|
||||
const input: BuildDuplicateVMInput = {
|
||||
pairs: [
|
||||
{
|
||||
matchType: "hard",
|
||||
matchReason: "email",
|
||||
a: { id: "k1", kontaktTyp: "privatperson", kontaktStatus: "kontakt", vorname: "Anna", nachname: "Muster", orgName: null, primaerEmail: "a@x.de", primaerTelefon: null, zustaendigerUserId: "u1", createdAt: new Date("2026-06-20T08:00:00.000Z") },
|
||||
b: { id: "k2", kontaktTyp: "privatperson", kontaktStatus: "kunde", vorname: "Anna", nachname: "Muster", orgName: null, primaerEmail: "a@x.de", primaerTelefon: null, zustaendigerUserId: null, createdAt: new Date("2026-06-21T08:00:00.000Z") },
|
||||
},
|
||||
],
|
||||
userLabels: new Map([["u1", "Raffael"]]),
|
||||
canMerge: true,
|
||||
tenantSlug: "acme",
|
||||
};
|
||||
|
||||
it("returns an empty state when there are no duplicate pairs", () => {
|
||||
expect(buildDuplicateVM({ ...input, pairs: [] }).status).toBe("empty");
|
||||
});
|
||||
|
||||
it("builds side-by-side cards with reason keys and internal hrefs", () => {
|
||||
const vm = buildDuplicateVM(input);
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
const pair = vm.data.pairs[0];
|
||||
expect(pair?.matchType).toBe("hard");
|
||||
expect(pair?.matchReasonKey).toBe("crm.duplicate.reason.email");
|
||||
expect(pair?.a.detailHref).toBe("/acme/contacts/k1");
|
||||
expect(pair?.a.zustaendigerLabel).toBe("Raffael");
|
||||
expect(pair?.b.zustaendigerLabel).toBeNull();
|
||||
expect(vm.data.canMerge).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// --- kontakt-csv ------------------------------------------------------------
|
||||
describe("buildKontaktCsv", () => {
|
||||
it("writes a German header and escapes RFC 4180 special characters", () => {
|
||||
const csv = buildKontaktCsv([
|
||||
{ displayName: 'Muster, Anna "die Erste"', kontaktTyp: "privatperson", kontaktStatus: "kunde", primaerEmail: "a@x.de", primaerTelefon: null, zustaendigerLabel: "Raffael", createdAtIso: "2026-06-20T08:00:00.000Z" },
|
||||
]);
|
||||
const lines = csv.split("\r\n");
|
||||
expect(lines[0]).toBe("Name,Typ,Status,E-Mail,Telefon,Zuständig,Erstellt am");
|
||||
// comma + quote in the name -> field quoted, inner quotes doubled
|
||||
expect(lines[1]).toContain('"Muster, Anna ""die Erste"""');
|
||||
// null telefon becomes an empty field
|
||||
expect(lines[1]).toBe('"Muster, Anna ""die Erste""",privatperson,kunde,a@x.de,,Raffael,2026-06-20T08:00:00.000Z');
|
||||
});
|
||||
|
||||
it("emits a header-only string for an empty row set", () => {
|
||||
expect(buildKontaktCsv([])).toBe("Name,Typ,Status,E-Mail,Telefon,Zuständig,Erstellt am");
|
||||
});
|
||||
});
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
import { ready, type VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* Custom-field admin view-model (R-P6, P6 CRM core — Variante A). Pure function:
|
||||
* the loader builds it from `customFieldService.listCustomFieldDefinitions`.
|
||||
* Lists the field definitions for one entity type so an admin can manage them.
|
||||
* Static texts are i18n KEYS. No React/Prisma/server imports (DoD A.3).
|
||||
*
|
||||
* Stays `ready` even with zero rows so the entity-type tabs and the "create
|
||||
* field" CTA (held in `data`) remain available for the admin.
|
||||
*/
|
||||
|
||||
/** Mirrors `CustomFieldEntityType` from customFieldService. */
|
||||
export type CustomFieldEntityType = "projekt" | "kontakt" | "lead" | "rechnung";
|
||||
|
||||
/** Mirrors `CustomFieldDatentyp` from customFieldService (12 types). */
|
||||
export type CustomFieldDatentyp =
|
||||
| "text"
|
||||
| "textarea"
|
||||
| "zahl"
|
||||
| "waehrung"
|
||||
| "datum"
|
||||
| "datum_range"
|
||||
| "select"
|
||||
| "multiselect"
|
||||
| "boolean"
|
||||
| "email"
|
||||
| "telefon"
|
||||
| "datei";
|
||||
|
||||
export interface CustomFieldAdminRowData {
|
||||
readonly id: string;
|
||||
readonly entityType: CustomFieldEntityType;
|
||||
readonly key: string;
|
||||
readonly label: string;
|
||||
readonly datentyp: CustomFieldDatentyp;
|
||||
/** i18n key for the data type label (e.g. `crm.datentyp.select`). */
|
||||
readonly datentypLabelKey: string;
|
||||
/** Opaque JSON options (select/multiselect choices etc.); UI renders them. */
|
||||
readonly optionen: unknown;
|
||||
readonly archiviert: boolean;
|
||||
readonly isDemoData: boolean;
|
||||
}
|
||||
|
||||
export interface CustomFieldAdminData {
|
||||
readonly rows: readonly CustomFieldAdminRowData[];
|
||||
/** The entity type currently being managed. */
|
||||
readonly entityType: CustomFieldEntityType;
|
||||
readonly canWrite: boolean;
|
||||
}
|
||||
|
||||
export type CustomFieldAdminVM = VMState<CustomFieldAdminData>;
|
||||
|
||||
/** i18n key for a custom-field data type (e.g. `crm.datentyp.waehrung`). */
|
||||
export function datentypLabelKey(datentyp: CustomFieldDatentyp): string {
|
||||
return `crm.datentyp.${datentyp}`;
|
||||
}
|
||||
|
||||
/** Minimal definition source row (mirrors customFieldService.CustomFieldDefinitionRow). */
|
||||
export interface CustomFieldAdminSourceRow {
|
||||
readonly id: string;
|
||||
readonly entityType: CustomFieldEntityType;
|
||||
readonly key: string;
|
||||
readonly label: string;
|
||||
readonly datentyp: CustomFieldDatentyp;
|
||||
readonly optionen: unknown;
|
||||
readonly archiviert: boolean;
|
||||
readonly isDemoData: boolean;
|
||||
}
|
||||
|
||||
export interface BuildCustomFieldAdminVMInput {
|
||||
readonly rows: readonly CustomFieldAdminSourceRow[];
|
||||
readonly entityType: CustomFieldEntityType;
|
||||
readonly canWrite: boolean;
|
||||
}
|
||||
|
||||
export function buildCustomFieldAdminVM(input: BuildCustomFieldAdminVMInput): CustomFieldAdminVM {
|
||||
const rows: CustomFieldAdminRowData[] = input.rows.map((row) => ({
|
||||
id: row.id,
|
||||
entityType: row.entityType,
|
||||
key: row.key,
|
||||
label: row.label,
|
||||
datentyp: row.datentyp,
|
||||
datentypLabelKey: datentypLabelKey(row.datentyp),
|
||||
optionen: row.optionen,
|
||||
archiviert: row.archiviert,
|
||||
isDemoData: row.isDemoData,
|
||||
}));
|
||||
return ready<CustomFieldAdminData>({ rows, entityType: input.entityType, canWrite: input.canWrite });
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
import { empty, ready, type VMState } from "../index.js";
|
||||
import {
|
||||
buildKontaktDisplayName,
|
||||
kontaktStatusLabelKey,
|
||||
kontaktTypLabelKey,
|
||||
type KontaktStatus,
|
||||
type KontaktTyp,
|
||||
} from "./kontakt-list.vm.js";
|
||||
|
||||
/**
|
||||
* Duplicate-contacts view-model (R-P6, P6 CRM core — Variante A) backing the
|
||||
* `/admin/duplicates` side-by-side merge screen. Pure function: the loader
|
||||
* builds it from `crmService.findDuplicateKontakte` results, grouped into
|
||||
* candidate pairs. `hard` = exact channel match, `soft` = name-only match.
|
||||
* Static texts are i18n KEYS. No React/Prisma/server imports (DoD A.3).
|
||||
*/
|
||||
|
||||
export type DuplicateMatchType = "hard" | "soft";
|
||||
|
||||
/** A contact card shown on one side of a merge pair (resolved display data). */
|
||||
export interface DuplicateKontaktCard {
|
||||
readonly id: string;
|
||||
readonly displayName: string;
|
||||
readonly kontaktTyp: KontaktTyp;
|
||||
readonly typLabelKey: string;
|
||||
readonly kontaktStatus: KontaktStatus;
|
||||
readonly statusLabelKey: string;
|
||||
readonly primaerEmail: string | null;
|
||||
readonly primaerTelefon: string | null;
|
||||
readonly zustaendigerLabel: string | null;
|
||||
readonly detailHref: string;
|
||||
readonly createdAtIso: string;
|
||||
}
|
||||
|
||||
export interface DuplicatePairData {
|
||||
readonly matchType: DuplicateMatchType;
|
||||
/** i18n key explaining why the pair matched (e.g. `crm.duplicate.reason.email`). */
|
||||
readonly matchReasonKey: string;
|
||||
readonly a: DuplicateKontaktCard;
|
||||
readonly b: DuplicateKontaktCard;
|
||||
}
|
||||
|
||||
export interface DuplicateData {
|
||||
readonly pairs: readonly DuplicatePairData[];
|
||||
readonly canMerge: boolean;
|
||||
}
|
||||
|
||||
export type DuplicateVM = VMState<DuplicateData>;
|
||||
|
||||
/** i18n key for a duplicate match reason (e.g. `crm.duplicate.reason.name`). */
|
||||
export function duplicateReasonKey(reason: string): string {
|
||||
return `crm.duplicate.reason.${reason}`;
|
||||
}
|
||||
|
||||
// --- Builder input ----------------------------------------------------------
|
||||
export interface DuplicateCardSource {
|
||||
readonly id: string;
|
||||
readonly kontaktTyp: KontaktTyp;
|
||||
readonly kontaktStatus: KontaktStatus;
|
||||
readonly vorname: string | null;
|
||||
readonly nachname: string | null;
|
||||
readonly orgName: string | null;
|
||||
readonly primaerEmail: string | null;
|
||||
readonly primaerTelefon: string | null;
|
||||
readonly zustaendigerUserId: string | null;
|
||||
readonly createdAt: Date;
|
||||
}
|
||||
|
||||
export interface DuplicatePairSource {
|
||||
readonly matchType: DuplicateMatchType;
|
||||
/** Reason token (e.g. "email" | "telefon" | "name" | "orgName"). */
|
||||
readonly matchReason: string;
|
||||
readonly a: DuplicateCardSource;
|
||||
readonly b: DuplicateCardSource;
|
||||
}
|
||||
|
||||
export interface BuildDuplicateVMInput {
|
||||
readonly pairs: readonly DuplicatePairSource[];
|
||||
/** userId -> display label (crmService.resolveUserLabels). */
|
||||
readonly userLabels: ReadonlyMap<string, string>;
|
||||
readonly canMerge: boolean;
|
||||
readonly tenantSlug: string;
|
||||
}
|
||||
|
||||
function toCard(source: DuplicateCardSource, userLabels: ReadonlyMap<string, string>, tenantSlug: string): DuplicateKontaktCard {
|
||||
return {
|
||||
id: source.id,
|
||||
displayName: buildKontaktDisplayName(source),
|
||||
kontaktTyp: source.kontaktTyp,
|
||||
typLabelKey: kontaktTypLabelKey(source.kontaktTyp),
|
||||
kontaktStatus: source.kontaktStatus,
|
||||
statusLabelKey: kontaktStatusLabelKey(source.kontaktStatus),
|
||||
primaerEmail: source.primaerEmail,
|
||||
primaerTelefon: source.primaerTelefon,
|
||||
zustaendigerLabel: source.zustaendigerUserId ? (userLabels.get(source.zustaendigerUserId) ?? null) : null,
|
||||
detailHref: `/${tenantSlug}/contacts/${source.id}`,
|
||||
createdAtIso: source.createdAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildDuplicateVM(input: BuildDuplicateVMInput): DuplicateVM {
|
||||
if (input.pairs.length === 0) {
|
||||
return empty<DuplicateData>();
|
||||
}
|
||||
const pairs: DuplicatePairData[] = input.pairs.map((pair) => ({
|
||||
matchType: pair.matchType,
|
||||
matchReasonKey: duplicateReasonKey(pair.matchReason),
|
||||
a: toCard(pair.a, input.userLabels, input.tenantSlug),
|
||||
b: toCard(pair.b, input.userLabels, input.tenantSlug),
|
||||
}));
|
||||
return ready<DuplicateData>({ pairs, canMerge: input.canMerge });
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Contact CSV export builder (R-P6, P6 CRM core — Variante A). Pure function:
|
||||
* the route resolves the rows (incl. display labels) and this turns them into an
|
||||
* RFC 4180 string. No React/Prisma/server imports (DoD A.3).
|
||||
*
|
||||
* Decisions:
|
||||
* - Delimiter `,`, line ending CRLF, fields quoted only when they contain a
|
||||
* comma, double-quote or newline; embedded quotes are doubled (RFC 4180 §2).
|
||||
* - Header row uses fixed GERMAN column names: the export is consumed by end
|
||||
* users (not a machine contract), so human-readable German headers win over
|
||||
* the raw column keys.
|
||||
*/
|
||||
|
||||
export interface KontaktCsvRow {
|
||||
readonly displayName: string;
|
||||
readonly kontaktTyp: string;
|
||||
readonly kontaktStatus: string;
|
||||
readonly primaerEmail: string | null;
|
||||
readonly primaerTelefon: string | null;
|
||||
readonly zustaendigerLabel: string | null;
|
||||
readonly createdAtIso: string;
|
||||
}
|
||||
|
||||
const CSV_HEADER: readonly string[] = ["Name", "Typ", "Status", "E-Mail", "Telefon", "Zuständig", "Erstellt am"];
|
||||
|
||||
/** Escape a single field per RFC 4180 (quote when needed, double inner quotes). */
|
||||
function csvField(value: string | null): string {
|
||||
const raw = value ?? "";
|
||||
if (/[",\r\n]/.test(raw)) {
|
||||
return `"${raw.replace(/"/g, '""')}"`;
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function csvLine(fields: readonly (string | null)[]): string {
|
||||
return fields.map(csvField).join(",");
|
||||
}
|
||||
|
||||
/** Build an RFC 4180 CSV (CRLF-separated) with a German header row. */
|
||||
export function buildKontaktCsv(rows: readonly KontaktCsvRow[]): string {
|
||||
const lines: string[] = [csvLine(CSV_HEADER)];
|
||||
for (const row of rows) {
|
||||
lines.push(
|
||||
csvLine([
|
||||
row.displayName,
|
||||
row.kontaktTyp,
|
||||
row.kontaktStatus,
|
||||
row.primaerEmail,
|
||||
row.primaerTelefon,
|
||||
row.zustaendigerLabel,
|
||||
row.createdAtIso,
|
||||
]),
|
||||
);
|
||||
}
|
||||
return lines.join("\r\n");
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
import { ready, type VMState } from "../index.js";
|
||||
import {
|
||||
kontaktArtLabelKey,
|
||||
kontaktStatusLabelKey,
|
||||
kontaktTypLabelKey,
|
||||
orgMerkmalLabelKey,
|
||||
buildKontaktDisplayName,
|
||||
type KontaktArt,
|
||||
type KontaktStatus,
|
||||
type KontaktTagChip,
|
||||
type KontaktTyp,
|
||||
type OrgMerkmal,
|
||||
} from "./kontakt-list.vm.js";
|
||||
|
||||
/**
|
||||
* Contact detail view-model (R-P6, P6 CRM core — Variante A). Pure function: the
|
||||
* loader builds it once server-side from `crmService.getKontaktDetail` plus the
|
||||
* custom-field values, tags and resolved user labels. All static texts are i18n
|
||||
* KEYS; resolved names are data. No React/Prisma/server imports (DoD A.3).
|
||||
*/
|
||||
|
||||
export interface KontaktDetailEmail {
|
||||
readonly id: string;
|
||||
readonly email: string;
|
||||
readonly primaer: boolean;
|
||||
}
|
||||
|
||||
export interface KontaktDetailTelefon {
|
||||
readonly id: string;
|
||||
readonly telefon: string;
|
||||
readonly primaer: boolean;
|
||||
}
|
||||
|
||||
export interface KontaktDetailAdresse {
|
||||
readonly strasse: string | null;
|
||||
readonly hausnummer: string | null;
|
||||
readonly plz: string | null;
|
||||
readonly ort: string | null;
|
||||
readonly land: string;
|
||||
}
|
||||
|
||||
/** A relation seen from the perspective of the contact being viewed. */
|
||||
export interface KontaktDetailRelation {
|
||||
readonly id: string;
|
||||
/** "von" = this contact is the source, "zu" = this contact is the target. */
|
||||
readonly richtung: "von" | "zu";
|
||||
readonly otherKontaktId: string;
|
||||
readonly rolle: KontaktArt;
|
||||
readonly rolleLabelKey: string;
|
||||
readonly kontext: string | null;
|
||||
}
|
||||
|
||||
/** A custom-field value with its definition (display-ready). `wert`/`optionen`
|
||||
* stay opaque (JSON) — the UI renders per `datentyp`. */
|
||||
export interface KontaktDetailCustomField {
|
||||
readonly definitionId: string;
|
||||
readonly key: string;
|
||||
readonly label: string;
|
||||
readonly datentyp: string;
|
||||
readonly wert: unknown;
|
||||
readonly optionen: unknown;
|
||||
}
|
||||
|
||||
export interface KontaktDetailData {
|
||||
readonly id: string;
|
||||
readonly kontaktTyp: KontaktTyp;
|
||||
readonly typLabelKey: string;
|
||||
readonly kontaktStatus: KontaktStatus;
|
||||
readonly statusLabelKey: string;
|
||||
readonly displayName: string;
|
||||
readonly vorname: string | null;
|
||||
readonly nachname: string | null;
|
||||
readonly orgName: string | null;
|
||||
readonly orgMerkmal: OrgMerkmal | null;
|
||||
readonly orgMerkmalLabelKey: string | null;
|
||||
readonly emails: readonly KontaktDetailEmail[];
|
||||
readonly telefone: readonly KontaktDetailTelefon[];
|
||||
readonly adresse: KontaktDetailAdresse | null;
|
||||
readonly relationen: readonly KontaktDetailRelation[];
|
||||
readonly tags: readonly KontaktTagChip[];
|
||||
readonly customFields: readonly KontaktDetailCustomField[];
|
||||
readonly zustaendigerLabel: string | null;
|
||||
readonly zustaendigerUserId: string | null;
|
||||
readonly isArchived: boolean;
|
||||
readonly createdAtIso: string;
|
||||
readonly updatedAtIso: string;
|
||||
/** Back link to the contact list (breadcrumb / cancel target). */
|
||||
readonly listHref: string;
|
||||
readonly canWrite: boolean;
|
||||
readonly canDelete: boolean;
|
||||
/** Action keys for the detail toolbar (gated by perms). */
|
||||
readonly quickActions: readonly string[];
|
||||
}
|
||||
|
||||
export type KontaktDetailVM = VMState<KontaktDetailData>;
|
||||
|
||||
// --- Builder input (mirrors crmService row shapes) --------------------------
|
||||
export interface KontaktDetailSourceKontakt {
|
||||
readonly id: string;
|
||||
readonly kontaktTyp: KontaktTyp;
|
||||
readonly kontaktStatus: KontaktStatus;
|
||||
readonly vorname: string | null;
|
||||
readonly nachname: string | null;
|
||||
readonly orgName: string | null;
|
||||
readonly orgMerkmal: OrgMerkmal | null;
|
||||
readonly primaerEmail: string | null;
|
||||
readonly zustaendigerUserId: string | null;
|
||||
readonly archivedAt: Date | null;
|
||||
readonly createdAt: Date;
|
||||
readonly updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface KontaktDetailSourceRelation {
|
||||
readonly id: string;
|
||||
readonly vonKontaktId: string;
|
||||
readonly zuKontaktId: string;
|
||||
readonly rolle: KontaktArt;
|
||||
readonly kontext: string | null;
|
||||
}
|
||||
|
||||
export interface KontaktDetailSource {
|
||||
readonly kontakt: KontaktDetailSourceKontakt;
|
||||
readonly emails: readonly KontaktDetailEmail[];
|
||||
readonly telefone: readonly KontaktDetailTelefon[];
|
||||
readonly relationen: readonly KontaktDetailSourceRelation[];
|
||||
readonly adresse: KontaktDetailAdresse | null;
|
||||
}
|
||||
|
||||
/** Custom-field value + definition (mirrors crmService.CustomFieldValueWithDefinition). */
|
||||
export interface KontaktDetailCustomFieldSource {
|
||||
readonly definition: {
|
||||
readonly id: string;
|
||||
readonly key: string;
|
||||
readonly label: string;
|
||||
readonly datentyp: string;
|
||||
readonly optionen: unknown;
|
||||
};
|
||||
readonly wert: unknown;
|
||||
}
|
||||
|
||||
export interface BuildKontaktDetailVMInput {
|
||||
readonly detail: KontaktDetailSource;
|
||||
readonly customFields: readonly KontaktDetailCustomFieldSource[];
|
||||
readonly tags: readonly KontaktTagChip[];
|
||||
readonly userLabels: ReadonlyMap<string, string>;
|
||||
readonly perms: { readonly canWrite: boolean; readonly canDelete: boolean };
|
||||
readonly tenantSlug: string;
|
||||
}
|
||||
|
||||
export function buildKontaktDetailVM(input: BuildKontaktDetailVMInput): KontaktDetailVM {
|
||||
const { kontakt } = input.detail;
|
||||
const isOrg = kontakt.kontaktTyp === "organisation";
|
||||
|
||||
const relationen: KontaktDetailRelation[] = input.detail.relationen.map((rel) => {
|
||||
const isVon = rel.vonKontaktId === kontakt.id;
|
||||
return {
|
||||
id: rel.id,
|
||||
richtung: isVon ? "von" : "zu",
|
||||
otherKontaktId: isVon ? rel.zuKontaktId : rel.vonKontaktId,
|
||||
rolle: rel.rolle,
|
||||
rolleLabelKey: kontaktArtLabelKey(rel.rolle),
|
||||
kontext: rel.kontext,
|
||||
};
|
||||
});
|
||||
|
||||
const customFields: KontaktDetailCustomField[] = input.customFields.map((cf) => ({
|
||||
definitionId: cf.definition.id,
|
||||
key: cf.definition.key,
|
||||
label: cf.definition.label,
|
||||
datentyp: cf.definition.datentyp,
|
||||
wert: cf.wert,
|
||||
optionen: cf.definition.optionen,
|
||||
}));
|
||||
|
||||
const isArchived = kontakt.archivedAt !== null;
|
||||
const quickActions: string[] = [];
|
||||
if (input.perms.canWrite) {
|
||||
quickActions.push("addNote", "addTag", "reassign", isArchived ? "reactivate" : "archive");
|
||||
}
|
||||
if (input.perms.canDelete) {
|
||||
quickActions.push("delete");
|
||||
}
|
||||
|
||||
return ready<KontaktDetailData>({
|
||||
id: kontakt.id,
|
||||
kontaktTyp: kontakt.kontaktTyp,
|
||||
typLabelKey: kontaktTypLabelKey(kontakt.kontaktTyp),
|
||||
kontaktStatus: kontakt.kontaktStatus,
|
||||
statusLabelKey: kontaktStatusLabelKey(kontakt.kontaktStatus),
|
||||
displayName: buildKontaktDisplayName(kontakt),
|
||||
vorname: kontakt.vorname,
|
||||
nachname: kontakt.nachname,
|
||||
orgName: kontakt.orgName,
|
||||
orgMerkmal: kontakt.orgMerkmal,
|
||||
orgMerkmalLabelKey: isOrg && kontakt.orgMerkmal ? orgMerkmalLabelKey(kontakt.orgMerkmal) : null,
|
||||
emails: input.detail.emails,
|
||||
telefone: input.detail.telefone,
|
||||
adresse: input.detail.adresse,
|
||||
relationen,
|
||||
tags: input.tags,
|
||||
customFields,
|
||||
zustaendigerLabel: kontakt.zustaendigerUserId ? (input.userLabels.get(kontakt.zustaendigerUserId) ?? null) : null,
|
||||
zustaendigerUserId: kontakt.zustaendigerUserId,
|
||||
isArchived,
|
||||
createdAtIso: kontakt.createdAt.toISOString(),
|
||||
updatedAtIso: kontakt.updatedAt.toISOString(),
|
||||
listHref: `/${input.tenantSlug}/contacts`,
|
||||
canWrite: input.perms.canWrite,
|
||||
canDelete: input.perms.canDelete,
|
||||
quickActions,
|
||||
});
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
import { empty, ready, type VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* Contact list view-model (R-P6, P6 CRM core — Variante A). Pure function: the
|
||||
* loader builds it once server-side from the crmService rows, the UI only
|
||||
* renders. No React, no Prisma, no app/server imports (DoD A.3). All static
|
||||
* texts are i18n KEYS; resolved values (zustaendigerLabel, tag chips) are data
|
||||
* passed in by the loader.
|
||||
*
|
||||
* This file is the "hub" of the CRM view-models: the shared domain enums and
|
||||
* their i18n-key helpers live here and are imported by the sibling VMs
|
||||
* (detail / duplicate) so the barrel re-export stays collision-free.
|
||||
*
|
||||
* The organisation list is served by the SAME VM with a `kontaktTyp`
|
||||
* organisation filter; the org-only fields (`kontaktAnzahl`,
|
||||
* `letzteActivityIso`) are optional and only filled when the loader supplies
|
||||
* the corresponding maps.
|
||||
*/
|
||||
|
||||
// --- Shared domain enums (mirror the crm.prisma / crmService enums 1:1) -----
|
||||
export type KontaktTyp = "privatperson" | "organisation";
|
||||
export type KontaktStatus = "kontakt" | "kunde" | "bestandskunde";
|
||||
export type OrgMerkmal = "gmbh" | "kg" | "oeffentliche_einrichtung" | "sonstige";
|
||||
export type KontaktArt = "hauptkontakt" | "sekundaerkontakt" | "mitarbeiter" | "sonstige";
|
||||
export type KontaktSortField = "name" | "createdAt" | "kontaktStatus";
|
||||
export type KontaktSortDir = "asc" | "desc";
|
||||
|
||||
/** Tag chip rendered next to a contact (resolved data, no i18n). */
|
||||
export interface KontaktTagChip {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly farbe: string;
|
||||
}
|
||||
|
||||
// --- Shared i18n-key helpers (reused by detail/duplicate VMs) ---------------
|
||||
export function kontaktTypLabelKey(typ: KontaktTyp): string {
|
||||
return `crm.kontaktTyp.${typ}`;
|
||||
}
|
||||
|
||||
export function kontaktStatusLabelKey(status: KontaktStatus): string {
|
||||
return `crm.kontaktStatus.${status}`;
|
||||
}
|
||||
|
||||
export function orgMerkmalLabelKey(merkmal: OrgMerkmal): string {
|
||||
return `crm.orgMerkmal.${merkmal}`;
|
||||
}
|
||||
|
||||
export function kontaktArtLabelKey(rolle: KontaktArt): string {
|
||||
return `crm.kontaktArt.${rolle}`;
|
||||
}
|
||||
|
||||
// --- Row data ---------------------------------------------------------------
|
||||
export interface KontaktListRowData {
|
||||
readonly id: string;
|
||||
/** Built by the loader: name (privatperson) or org name (organisation). */
|
||||
readonly displayName: string;
|
||||
readonly kontaktTyp: KontaktTyp;
|
||||
readonly typLabelKey: string;
|
||||
readonly kontaktStatus: KontaktStatus;
|
||||
readonly statusLabelKey: string;
|
||||
readonly primaerEmail: string | null;
|
||||
readonly primaerTelefon: string | null;
|
||||
/** Resolved display label of the responsible user (data) or null. */
|
||||
readonly zustaendigerLabel: string | null;
|
||||
/** Organisation merkmal (null for privatperson). */
|
||||
readonly orgMerkmal: OrgMerkmal | null;
|
||||
/** i18n key for {@link orgMerkmal} (null unless organisation + merkmal set). */
|
||||
readonly orgMerkmalLabelKey: string | null;
|
||||
readonly tagChips: readonly KontaktTagChip[];
|
||||
readonly isArchived: boolean;
|
||||
/** Internal detail route (e.g. `/acme/contacts/<id>`). */
|
||||
readonly detailHref: string;
|
||||
readonly createdAtIso: string;
|
||||
/** Org-list only: number of attached contacts (filled when supplied). */
|
||||
readonly kontaktAnzahl?: number;
|
||||
/** Org-list only: ISO timestamp of the last activity (filled when supplied). */
|
||||
readonly letzteActivityIso?: string;
|
||||
}
|
||||
|
||||
/** Echo of the applied browser filter (mirrors crmService.ListKontakteFilter). */
|
||||
export interface KontaktListAppliedFilter {
|
||||
readonly kontaktTyp: KontaktTyp | null;
|
||||
readonly kontaktStatus: KontaktStatus | null;
|
||||
readonly zustaendigerUserId: string | null;
|
||||
readonly search: string | null;
|
||||
readonly tagIds: readonly string[] | null;
|
||||
readonly tagMatch: "and" | "or";
|
||||
readonly includeArchived: boolean;
|
||||
}
|
||||
|
||||
export interface KontaktListPagination {
|
||||
readonly page: number;
|
||||
readonly pageCount: number;
|
||||
readonly total: number;
|
||||
readonly hasPrev: boolean;
|
||||
readonly hasNext: boolean;
|
||||
}
|
||||
|
||||
export interface KontaktListSort {
|
||||
readonly field: KontaktSortField;
|
||||
readonly dir: KontaktSortDir;
|
||||
}
|
||||
|
||||
export interface KontaktListData {
|
||||
readonly rows: readonly KontaktListRowData[];
|
||||
readonly pagination: KontaktListPagination;
|
||||
readonly sort: KontaktListSort;
|
||||
readonly appliedFilter: KontaktListAppliedFilter;
|
||||
readonly canWrite: boolean;
|
||||
readonly canDelete: boolean;
|
||||
readonly canReadAll: boolean;
|
||||
}
|
||||
|
||||
export type KontaktListVM = VMState<KontaktListData>;
|
||||
|
||||
// --- Builder input ----------------------------------------------------------
|
||||
/** Minimal contact source row (mirrors the crmService `KontaktRow` fields the
|
||||
* list needs). Timestamps arrive as `Date` and are converted deterministically. */
|
||||
export interface KontaktListSourceRow {
|
||||
readonly id: string;
|
||||
readonly kontaktTyp: KontaktTyp;
|
||||
readonly kontaktStatus: KontaktStatus;
|
||||
readonly vorname: string | null;
|
||||
readonly nachname: string | null;
|
||||
readonly orgName: string | null;
|
||||
readonly orgMerkmal: OrgMerkmal | null;
|
||||
readonly primaerEmail: string | null;
|
||||
readonly primaerTelefon: string | null;
|
||||
readonly zustaendigerUserId: string | null;
|
||||
readonly createdAt: Date;
|
||||
readonly archivedAt: Date | null;
|
||||
}
|
||||
|
||||
export interface BuildKontaktListVMInput {
|
||||
readonly rows: readonly KontaktListSourceRow[];
|
||||
/** userId -> display label (crmService.resolveUserLabels). */
|
||||
readonly userLabels: ReadonlyMap<string, string>;
|
||||
/** kontaktId -> tag chips (crmService tag assignments). */
|
||||
readonly tagsByKontakt: ReadonlyMap<string, readonly KontaktTagChip[]>;
|
||||
readonly pagination: { readonly page: number; readonly pageCount: number; readonly total: number };
|
||||
readonly sort: KontaktListSort;
|
||||
readonly filter: KontaktListAppliedFilter;
|
||||
readonly perms: { readonly canWrite: boolean; readonly canDelete: boolean; readonly canReadAll: boolean };
|
||||
/** Tenant slug used to build internal detail hrefs. */
|
||||
readonly tenantSlug: string;
|
||||
/** Optional override for the detail href (e.g. an organisation route). */
|
||||
readonly detailHrefFor?: (row: KontaktListSourceRow) => string;
|
||||
/** Org-list only: kontaktId -> number of attached contacts. */
|
||||
readonly orgKontaktAnzahl?: ReadonlyMap<string, number>;
|
||||
/** Org-list only: kontaktId -> ISO timestamp of the last activity. */
|
||||
readonly orgLastActivityIso?: ReadonlyMap<string, string>;
|
||||
}
|
||||
|
||||
/** Build the contact display name from raw fields (pure). */
|
||||
export function buildKontaktDisplayName(row: {
|
||||
readonly kontaktTyp: KontaktTyp;
|
||||
readonly vorname: string | null;
|
||||
readonly nachname: string | null;
|
||||
readonly orgName: string | null;
|
||||
readonly primaerEmail: string | null;
|
||||
}): string {
|
||||
if (row.kontaktTyp === "organisation") {
|
||||
return (row.orgName ?? "").trim() || (row.primaerEmail ?? "");
|
||||
}
|
||||
const name = `${row.vorname ?? ""} ${row.nachname ?? ""}`.trim();
|
||||
return name || (row.primaerEmail ?? "");
|
||||
}
|
||||
|
||||
export function buildKontaktListVM(input: BuildKontaktListVMInput): KontaktListVM {
|
||||
// Empty contact set -> dedicated empty state (DoD 23). The route renders the
|
||||
// "no contacts yet" prompt; the filter bar/CTA live in the route shell.
|
||||
if (input.rows.length === 0) {
|
||||
return empty<KontaktListData>();
|
||||
}
|
||||
|
||||
const rows: KontaktListRowData[] = input.rows.map((row) => {
|
||||
const isOrg = row.kontaktTyp === "organisation";
|
||||
const detailHref = input.detailHrefFor ? input.detailHrefFor(row) : `/${input.tenantSlug}/contacts/${row.id}`;
|
||||
const kontaktAnzahl = input.orgKontaktAnzahl?.get(row.id);
|
||||
const letzteActivityIso = input.orgLastActivityIso?.get(row.id);
|
||||
return {
|
||||
id: row.id,
|
||||
displayName: buildKontaktDisplayName(row),
|
||||
kontaktTyp: row.kontaktTyp,
|
||||
typLabelKey: kontaktTypLabelKey(row.kontaktTyp),
|
||||
kontaktStatus: row.kontaktStatus,
|
||||
statusLabelKey: kontaktStatusLabelKey(row.kontaktStatus),
|
||||
primaerEmail: row.primaerEmail,
|
||||
primaerTelefon: row.primaerTelefon,
|
||||
zustaendigerLabel: row.zustaendigerUserId ? (input.userLabels.get(row.zustaendigerUserId) ?? null) : null,
|
||||
orgMerkmal: row.orgMerkmal,
|
||||
orgMerkmalLabelKey: isOrg && row.orgMerkmal ? orgMerkmalLabelKey(row.orgMerkmal) : null,
|
||||
tagChips: input.tagsByKontakt.get(row.id) ?? [],
|
||||
isArchived: row.archivedAt !== null,
|
||||
detailHref,
|
||||
createdAtIso: row.createdAt.toISOString(),
|
||||
...(kontaktAnzahl !== undefined ? { kontaktAnzahl } : {}),
|
||||
...(letzteActivityIso !== undefined ? { letzteActivityIso } : {}),
|
||||
};
|
||||
});
|
||||
|
||||
const { page, pageCount, total } = input.pagination;
|
||||
return ready<KontaktListData>({
|
||||
rows,
|
||||
pagination: { page, pageCount, total, hasPrev: page > 1, hasNext: page < pageCount },
|
||||
sort: input.sort,
|
||||
appliedFilter: input.filter,
|
||||
canWrite: input.perms.canWrite,
|
||||
canDelete: input.perms.canDelete,
|
||||
canReadAll: input.perms.canReadAll,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { ready, type VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* Tag admin view-model (R-P6, P6 CRM core — Variante A). Pure function: the
|
||||
* loader builds it from `tagService.listTags` plus a per-tag usage count. Lets
|
||||
* an admin manage tenant tags. No React/Prisma/server imports (DoD A.3).
|
||||
*
|
||||
* Stays `ready` even with zero rows so the "create tag" CTA (held in `data`)
|
||||
* remains available.
|
||||
*/
|
||||
|
||||
export interface TagAdminRowData {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly farbe: string;
|
||||
/** Number of entities the tag is assigned to (0 when unused). */
|
||||
readonly usageCount: number;
|
||||
}
|
||||
|
||||
export interface TagAdminData {
|
||||
readonly rows: readonly TagAdminRowData[];
|
||||
readonly canWrite: boolean;
|
||||
}
|
||||
|
||||
export type TagAdminVM = VMState<TagAdminData>;
|
||||
|
||||
/** Minimal tag source row (mirrors tagService.TagRow). */
|
||||
export interface TagAdminSourceRow {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly farbe: string;
|
||||
}
|
||||
|
||||
export interface BuildTagAdminVMInput {
|
||||
readonly tags: readonly TagAdminSourceRow[];
|
||||
/** tagId -> assignment count. */
|
||||
readonly usageCounts: ReadonlyMap<string, number>;
|
||||
readonly canWrite: boolean;
|
||||
}
|
||||
|
||||
export function buildTagAdminVM(input: BuildTagAdminVMInput): TagAdminVM {
|
||||
const rows: TagAdminRowData[] = input.tags.map((tag) => ({
|
||||
id: tag.id,
|
||||
name: tag.name,
|
||||
farbe: tag.farbe,
|
||||
usageCount: input.usageCounts.get(tag.id) ?? 0,
|
||||
}));
|
||||
return ready<TagAdminData>({ rows, canWrite: input.canWrite });
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
import type { VMState } from "../index.js";
|
||||
import type { EmailMailboxProvider } from "./mailbox-list.vm.js";
|
||||
|
||||
/**
|
||||
* VA-P23 · compose view-model (M09 Block G). Pure: reply/forward prefill is
|
||||
* computed here from the (already sanitized) original; the route passes the
|
||||
* SAFE quoted html in. Sending itself is the action's job.
|
||||
*/
|
||||
|
||||
export interface ComposeMailboxOption {
|
||||
readonly id: string;
|
||||
readonly emailAddress: string;
|
||||
readonly provider: EmailMailboxProvider;
|
||||
readonly isDefaultForUser: boolean;
|
||||
}
|
||||
|
||||
export interface ComposeTemplateOption {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly subject: string;
|
||||
readonly htmlBody: string;
|
||||
}
|
||||
|
||||
export interface ComposePrefill {
|
||||
readonly to: string;
|
||||
readonly subject: string;
|
||||
/** SANITIZED quoted body html ("" for a blank compose). */
|
||||
readonly quotedHtml: string;
|
||||
readonly replyToMessageId: string | null;
|
||||
}
|
||||
|
||||
export interface EmailComposeData {
|
||||
readonly mailboxes: readonly ComposeMailboxOption[];
|
||||
readonly defaultMailboxId: string | null;
|
||||
readonly templates: readonly ComposeTemplateOption[];
|
||||
readonly prefill: ComposePrefill;
|
||||
readonly backHref: string;
|
||||
readonly noMailboxKey: string;
|
||||
}
|
||||
|
||||
export type EmailComposeVM = VMState<EmailComposeData>;
|
||||
|
||||
export interface BuildComposePrefillInput {
|
||||
readonly mode: "blank" | "reply" | "forward";
|
||||
readonly original: {
|
||||
readonly id: string;
|
||||
readonly direction: "inbound" | "outbound";
|
||||
readonly fromAddress: string;
|
||||
readonly fromName: string | null;
|
||||
readonly toSummary: string;
|
||||
readonly subject: string | null;
|
||||
readonly sentAtIso: string;
|
||||
/** SANITIZED body html of the original (never raw provider html). */
|
||||
readonly safeBodyHtml: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
function prefixedSubject(prefix: "Re:" | "Fwd:", subject: string | null): string {
|
||||
const base = (subject ?? "").trim();
|
||||
if (!base) return prefix;
|
||||
return base.toLowerCase().startsWith(prefix.toLowerCase()) ? base : `${prefix} ${base}`;
|
||||
}
|
||||
|
||||
function quoted(original: NonNullable<BuildComposePrefillInput["original"]>): string {
|
||||
const who = original.fromName ? `${original.fromName} <${original.fromAddress}>` : original.fromAddress;
|
||||
return `<br><br><blockquote style="border-left:2px solid #ccc;margin:0;padding-left:8px"><p>${who} — ${original.sentAtIso}:</p>${original.safeBodyHtml}</blockquote>`;
|
||||
}
|
||||
|
||||
export function buildComposePrefill(input: BuildComposePrefillInput): ComposePrefill {
|
||||
if (!input.original || input.mode === "blank") {
|
||||
return { to: "", subject: "", quotedHtml: "", replyToMessageId: null };
|
||||
}
|
||||
if (input.mode === "reply") {
|
||||
return {
|
||||
// Reply to an inbound mail → answer the sender; to our own outbound
|
||||
// mirror → keep the original recipients.
|
||||
to: input.original.direction === "inbound" ? input.original.fromAddress : input.original.toSummary,
|
||||
subject: prefixedSubject("Re:", input.original.subject),
|
||||
quotedHtml: quoted(input.original),
|
||||
replyToMessageId: input.original.id,
|
||||
};
|
||||
}
|
||||
return {
|
||||
to: "",
|
||||
subject: prefixedSubject("Fwd:", input.original.subject),
|
||||
quotedHtml: quoted(input.original),
|
||||
// A forward starts a new thread — no reply threading headers.
|
||||
replyToMessageId: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildEmailComposeVM(data: Omit<EmailComposeData, "noMailboxKey">): EmailComposeVM {
|
||||
return { status: "ready", data: { ...data, noMailboxKey: "emailInbox.compose.noMailbox" } };
|
||||
}
|
||||
|
||||
/** Parse a comma/semicolon separated recipient input into address objects. */
|
||||
export function parseRecipients(value: string): Array<{ address: string }> {
|
||||
return value
|
||||
.split(/[,;]/)
|
||||
.map((part) => part.trim().toLowerCase())
|
||||
.filter((part) => part.includes("@"))
|
||||
.map((address) => ({ address }));
|
||||
}
|
||||
+223
@@ -0,0 +1,223 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
aggregateInitialSync,
|
||||
buildEmailMailboxListVM,
|
||||
emailInitialSyncStatusKey,
|
||||
emailMailboxProviderKey,
|
||||
emailMailboxStatusKey,
|
||||
type EmailMailboxRow,
|
||||
} from "./mailbox-list.vm.js";
|
||||
import { buildEmailInboxListVM, decodeInboxCursor, encodeInboxCursor, parseInboxFilters, type EmailInboxRow } from "./inbox-list.vm.js";
|
||||
import { buildComposePrefill, parseRecipients } from "./compose.vm.js";
|
||||
|
||||
// VA-P23 — pure VM builder tests (DoD 18). No React/Prisma imports.
|
||||
|
||||
function rowFixture(overrides: Partial<EmailMailboxRow> = {}): EmailMailboxRow {
|
||||
return {
|
||||
id: "mb1",
|
||||
provider: "gmail",
|
||||
providerKey: emailMailboxProviderKey("gmail"),
|
||||
emailAddress: "max@handwerk.de",
|
||||
displayName: "Max",
|
||||
isDefaultForUser: true,
|
||||
isOwn: true,
|
||||
status: "active",
|
||||
statusKey: emailMailboxStatusKey("active"),
|
||||
lastSyncAt: "2026-07-01T10:00:00.000Z",
|
||||
lastErrorText: null,
|
||||
initialSync: { status: "completed", statusKey: emailInitialSyncStatusKey("completed"), progressPercent: 100, fetchedCount: 12 },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildEmailMailboxListVM", () => {
|
||||
it("is always ready and carries the Klartext keys for the empty state", () => {
|
||||
const vm = buildEmailMailboxListVM({ rows: [], canConnect: true, configuredProviders: { gmail: true, microsoft: false } });
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.rows).toEqual([]);
|
||||
expect(vm.data?.emptyHeadlineKey).toBe("emailInbox.settings.empty.headline");
|
||||
expect(vm.data?.emptyBodyKey).toBe("emailInbox.settings.empty.body");
|
||||
expect(vm.data?.notConfiguredKey).toBe("emailInbox.settings.notConfigured");
|
||||
expect(vm.data?.configuredProviders).toEqual({ gmail: true, microsoft: false });
|
||||
});
|
||||
|
||||
it("passes rows through untouched (loader owns the mapping)", () => {
|
||||
const row = rowFixture();
|
||||
const vm = buildEmailMailboxListVM({ rows: [row], canConnect: false, configuredProviders: { gmail: true, microsoft: true } });
|
||||
expect(vm.data?.rows[0]).toBe(row);
|
||||
expect(vm.data?.canConnect).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("aggregateInitialSync", () => {
|
||||
it("defaults to pending when no cursor rows exist yet", () => {
|
||||
expect(aggregateInitialSync([])).toEqual({
|
||||
status: "pending",
|
||||
statusKey: "emailInbox.settings.initialSync.pending",
|
||||
progressPercent: null,
|
||||
fetchedCount: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("lets the worst folder status win (failed > running > pending > completed)", () => {
|
||||
const status = aggregateInitialSync([
|
||||
{ mailboxId: "mb1", initialSyncStatus: "completed", initialSyncProgress: null },
|
||||
{ mailboxId: "mb1", initialSyncStatus: "running", initialSyncProgress: null },
|
||||
]);
|
||||
expect(status.status).toBe("running");
|
||||
const failed = aggregateInitialSync([
|
||||
{ mailboxId: "mb1", initialSyncStatus: "running", initialSyncProgress: null },
|
||||
{ mailboxId: "mb1", initialSyncStatus: "failed", initialSyncProgress: null },
|
||||
]);
|
||||
expect(failed.status).toBe("failed");
|
||||
});
|
||||
|
||||
it("averages folder percents only when every folder reports one", () => {
|
||||
const both = aggregateInitialSync([
|
||||
{ mailboxId: "mb1", initialSyncStatus: "running", initialSyncProgress: { percent: 40, fetchedCount: 40 } },
|
||||
{ mailboxId: "mb1", initialSyncStatus: "running", initialSyncProgress: { percent: 60, fetchedCount: 20 } },
|
||||
]);
|
||||
expect(both.progressPercent).toBe(50);
|
||||
expect(both.fetchedCount).toBe(60);
|
||||
|
||||
const partial = aggregateInitialSync([
|
||||
{ mailboxId: "mb1", initialSyncStatus: "running", initialSyncProgress: { percent: 40 } },
|
||||
{ mailboxId: "mb1", initialSyncStatus: "running", initialSyncProgress: null },
|
||||
]);
|
||||
expect(partial.progressPercent).toBeNull();
|
||||
});
|
||||
|
||||
it("reports 100% when everything completed", () => {
|
||||
const done = aggregateInitialSync([{ mailboxId: "mb1", initialSyncStatus: "completed", initialSyncProgress: null }]);
|
||||
expect(done.progressPercent).toBe(100);
|
||||
});
|
||||
|
||||
it("clamps out-of-range percents", () => {
|
||||
const clamped = aggregateInitialSync([{ mailboxId: "mb1", initialSyncStatus: "running", initialSyncProgress: { percent: 250 } }]);
|
||||
expect(clamped.progressPercent).toBe(100);
|
||||
});
|
||||
});
|
||||
|
||||
describe("inbox cursor", () => {
|
||||
it("round-trips a keyset cursor", () => {
|
||||
const cursor = encodeInboxCursor("2026-07-01T10:00:00.000Z", "msg-1");
|
||||
expect(decodeInboxCursor(cursor)).toEqual({ sentAtIso: "2026-07-01T10:00:00.000Z", id: "msg-1" });
|
||||
});
|
||||
|
||||
it("rejects malformed cursors defensively", () => {
|
||||
expect(decodeInboxCursor(null)).toBeNull();
|
||||
expect(decodeInboxCursor("garbage")).toBeNull();
|
||||
expect(decodeInboxCursor(encodeURIComponent("not-a-date~id"))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseInboxFilters", () => {
|
||||
it("parses valid params and falls back on garbage", () => {
|
||||
const params = new URLSearchParams("mailbox=mb1&direction=inbound&linked=unlinked&read=nonsense&q=+wartung+&archived=1");
|
||||
expect(parseInboxFilters(params)).toEqual({
|
||||
mailboxId: "mb1",
|
||||
direction: "inbound",
|
||||
linked: "unlinked",
|
||||
read: "all",
|
||||
q: "wartung",
|
||||
showArchived: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("defaults everything when params are absent", () => {
|
||||
expect(parseInboxFilters(new URLSearchParams())).toEqual({
|
||||
mailboxId: null,
|
||||
direction: "all",
|
||||
linked: "all",
|
||||
read: "all",
|
||||
q: "",
|
||||
showArchived: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildEmailInboxListVM", () => {
|
||||
it("is ready and carries the Klartext empty/no-mailbox keys", () => {
|
||||
const row: EmailInboxRow = {
|
||||
id: "m1",
|
||||
detailHref: "/acme/emails/m1",
|
||||
fromName: "Max",
|
||||
fromAddress: "max@kunde.de",
|
||||
subject: "Anfrage",
|
||||
snippet: "Hallo",
|
||||
sentAt: "2026-07-01T10:00:00.000Z",
|
||||
direction: "inbound",
|
||||
isRead: false,
|
||||
hasAttachments: true,
|
||||
isNewsletter: false,
|
||||
mailbox: { id: "mb1", emailAddress: "info@handwerk.de", provider: "gmail" },
|
||||
links: [{ type: "kontakt", id: "k1", href: "/acme/contacts/k1" }],
|
||||
};
|
||||
const vm = buildEmailInboxListVM({
|
||||
rows: [row],
|
||||
filters: parseInboxFilters(new URLSearchParams()),
|
||||
mailboxOptions: [{ id: "mb1", emailAddress: "info@handwerk.de" }],
|
||||
nextCursor: "abc",
|
||||
canWrite: true,
|
||||
composeHref: "/acme/emails/new",
|
||||
settingsHref: "/acme/settings/integrations/email",
|
||||
hasAnyMailbox: true,
|
||||
});
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.rows[0]).toBe(row);
|
||||
expect(vm.data?.emptyHeadlineKey).toBe("emailInbox.list.empty.headline");
|
||||
expect(vm.data?.noMailboxHeadlineKey).toBe("emailInbox.list.noMailbox.headline");
|
||||
expect(vm.data?.nextCursor).toBe("abc");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildComposePrefill", () => {
|
||||
const original = {
|
||||
id: "m1",
|
||||
direction: "inbound" as const,
|
||||
fromAddress: "max@kunde.de",
|
||||
fromName: "Max",
|
||||
toSummary: "info@handwerk.de",
|
||||
subject: "Anfrage Wartung",
|
||||
sentAtIso: "2026-07-01T10:00:00.000Z",
|
||||
safeBodyHtml: "<p>Hallo</p>",
|
||||
};
|
||||
|
||||
it("reply to inbound answers the sender with Re: and quotes the original", () => {
|
||||
const prefill = buildComposePrefill({ mode: "reply", original });
|
||||
expect(prefill.to).toBe("max@kunde.de");
|
||||
expect(prefill.subject).toBe("Re: Anfrage Wartung");
|
||||
expect(prefill.quotedHtml).toContain("<blockquote");
|
||||
expect(prefill.quotedHtml).toContain("<p>Hallo</p>");
|
||||
expect(prefill.replyToMessageId).toBe("m1");
|
||||
});
|
||||
|
||||
it("does not stack Re: prefixes", () => {
|
||||
const prefill = buildComposePrefill({ mode: "reply", original: { ...original, subject: "Re: Anfrage Wartung" } });
|
||||
expect(prefill.subject).toBe("Re: Anfrage Wartung");
|
||||
});
|
||||
|
||||
it("reply to an own outbound mirror keeps the original recipients", () => {
|
||||
const prefill = buildComposePrefill({ mode: "reply", original: { ...original, direction: "outbound" } });
|
||||
expect(prefill.to).toBe("info@handwerk.de");
|
||||
});
|
||||
|
||||
it("forward starts a new thread with Fwd: and empty recipients", () => {
|
||||
const prefill = buildComposePrefill({ mode: "forward", original });
|
||||
expect(prefill.to).toBe("");
|
||||
expect(prefill.subject).toBe("Fwd: Anfrage Wartung");
|
||||
expect(prefill.replyToMessageId).toBeNull();
|
||||
});
|
||||
|
||||
it("blank compose is empty", () => {
|
||||
expect(buildComposePrefill({ mode: "blank", original: null })).toEqual({ to: "", subject: "", quotedHtml: "", replyToMessageId: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseRecipients", () => {
|
||||
it("splits on commas/semicolons and drops garbage", () => {
|
||||
expect(parseRecipients(" Max@Kunde.de ; second@firma.de,, kein-at ")).toEqual([{ address: "max@kunde.de" }, { address: "second@firma.de" }]);
|
||||
expect(parseRecipients("")).toEqual([]);
|
||||
});
|
||||
});
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
import type { VMState } from "../index.js";
|
||||
import type { EmailMailboxProvider } from "./mailbox-list.vm.js";
|
||||
|
||||
/**
|
||||
* VA-P23 · inbox list view-model (M09 Block F). Pure (DoD A.3): the loader
|
||||
* resolves the visible messages (read_own → only the user's own mailboxes;
|
||||
* read_all → every tenant mailbox), applies filters/search/cursor server-side
|
||||
* and this shapes the rows. NO bodies here — the list carries the snippet only.
|
||||
*/
|
||||
|
||||
export type EmailDirectionFilter = "all" | "inbound" | "outbound";
|
||||
export type EmailLinkedFilter = "all" | "linked" | "unlinked";
|
||||
export type EmailReadFilter = "all" | "read" | "unread";
|
||||
|
||||
export interface EmailInboxFilters {
|
||||
readonly mailboxId: string | null;
|
||||
readonly direction: EmailDirectionFilter;
|
||||
readonly linked: EmailLinkedFilter;
|
||||
readonly read: EmailReadFilter;
|
||||
readonly q: string;
|
||||
readonly showArchived: boolean;
|
||||
}
|
||||
|
||||
export interface EmailLinkBadge {
|
||||
readonly type: "kontakt" | "lead" | "projekt";
|
||||
readonly id: string;
|
||||
readonly href: string;
|
||||
}
|
||||
|
||||
export interface EmailInboxRow {
|
||||
readonly id: string;
|
||||
readonly detailHref: string;
|
||||
readonly fromName: string | null;
|
||||
readonly fromAddress: string;
|
||||
readonly subject: string | null;
|
||||
readonly snippet: string | null;
|
||||
/** ISO timestamp (list shows relative <7d, absolute otherwise — UI concern). */
|
||||
readonly sentAt: string;
|
||||
readonly direction: "inbound" | "outbound";
|
||||
readonly isRead: boolean;
|
||||
readonly hasAttachments: boolean;
|
||||
readonly isNewsletter: boolean;
|
||||
readonly mailbox: { readonly id: string; readonly emailAddress: string; readonly provider: EmailMailboxProvider };
|
||||
readonly links: readonly EmailLinkBadge[];
|
||||
}
|
||||
|
||||
export interface EmailInboxListData {
|
||||
readonly rows: readonly EmailInboxRow[];
|
||||
readonly filters: EmailInboxFilters;
|
||||
readonly mailboxOptions: ReadonlyArray<{ readonly id: string; readonly emailAddress: string }>;
|
||||
/** Opaque cursor for the next page, or null on the last page. */
|
||||
readonly nextCursor: string | null;
|
||||
readonly canWrite: boolean;
|
||||
readonly composeHref: string;
|
||||
readonly settingsHref: string;
|
||||
readonly hasAnyMailbox: boolean;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
readonly noMailboxHeadlineKey: string;
|
||||
readonly noMailboxBodyKey: string;
|
||||
}
|
||||
|
||||
export type EmailInboxListVM = VMState<EmailInboxListData>;
|
||||
|
||||
export interface BuildEmailInboxListInput {
|
||||
readonly rows: readonly EmailInboxRow[];
|
||||
readonly filters: EmailInboxFilters;
|
||||
readonly mailboxOptions: ReadonlyArray<{ readonly id: string; readonly emailAddress: string }>;
|
||||
readonly nextCursor: string | null;
|
||||
readonly canWrite: boolean;
|
||||
readonly composeHref: string;
|
||||
readonly settingsHref: string;
|
||||
readonly hasAnyMailbox: boolean;
|
||||
}
|
||||
|
||||
export function buildEmailInboxListVM(input: BuildEmailInboxListInput): EmailInboxListVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
...input,
|
||||
emptyHeadlineKey: "emailInbox.list.empty.headline",
|
||||
emptyBodyKey: "emailInbox.list.empty.body",
|
||||
noMailboxHeadlineKey: "emailInbox.list.noMailbox.headline",
|
||||
noMailboxBodyKey: "emailInbox.list.noMailbox.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode/decode the keyset cursor `(sentAt, id)` — sorted newest first, the
|
||||
* cursor is the last row of the page. Runtime-agnostic (no Buffer — VMs are
|
||||
* pure and browser-safe); the shape is validated defensively on decode.
|
||||
*/
|
||||
export function encodeInboxCursor(sentAtIso: string, id: string): string {
|
||||
return encodeURIComponent(`${sentAtIso}~${id}`);
|
||||
}
|
||||
|
||||
export function decodeInboxCursor(cursor: string | null | undefined): { sentAtIso: string; id: string } | null {
|
||||
if (!cursor) return null;
|
||||
try {
|
||||
const raw = decodeURIComponent(cursor);
|
||||
const separator = raw.lastIndexOf("~");
|
||||
if (separator <= 0 || separator === raw.length - 1) {
|
||||
return null;
|
||||
}
|
||||
const sentAtIso = raw.slice(0, separator);
|
||||
const id = raw.slice(separator + 1);
|
||||
if (Number.isNaN(Date.parse(sentAtIso))) {
|
||||
return null;
|
||||
}
|
||||
return { sentAtIso, id };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Parse the filter query params (defensive — bad values fall back to defaults). */
|
||||
export function parseInboxFilters(searchParams: URLSearchParams): EmailInboxFilters {
|
||||
const direction = searchParams.get("direction");
|
||||
const linked = searchParams.get("linked");
|
||||
const read = searchParams.get("read");
|
||||
return {
|
||||
mailboxId: searchParams.get("mailbox") || null,
|
||||
direction: direction === "inbound" || direction === "outbound" ? direction : "all",
|
||||
linked: linked === "linked" || linked === "unlinked" ? linked : "all",
|
||||
read: read === "read" || read === "unread" ? read : "all",
|
||||
q: (searchParams.get("q") ?? "").trim(),
|
||||
showArchived: searchParams.get("archived") === "1",
|
||||
};
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* VA-P23 · mailbox connect-settings view-model (M09 Block B/D). Pure (DoD A.3):
|
||||
* the loader resolves the CURRENT user's own mailboxes (read_all admins see all)
|
||||
* and this builds the settings list. NO tokens/credentials/clientState ever
|
||||
* appear here. `configuredProviders` reflects the OAuth env presence so the UI
|
||||
* shows a Klartext "not configured" hint instead of a dead connect button.
|
||||
* `initialSync` aggregates the per-folder cursor rows into one progress line.
|
||||
*/
|
||||
|
||||
export type EmailMailboxProvider = "gmail" | "microsoft";
|
||||
export type EmailMailboxStatus = "connecting" | "active" | "paused" | "error" | "revoked";
|
||||
export type EmailInitialSyncStatus = "pending" | "running" | "completed" | "failed";
|
||||
|
||||
export interface EmailMailboxInitialSync {
|
||||
readonly status: EmailInitialSyncStatus;
|
||||
/** i18n key, e.g. `emailInbox.settings.initialSync.running`. */
|
||||
readonly statusKey: string;
|
||||
/** 0–100 when derivable from the cursor progress rows, else null. */
|
||||
readonly progressPercent: number | null;
|
||||
/** Fetched message count when known (Klartext progress line). */
|
||||
readonly fetchedCount: number | null;
|
||||
}
|
||||
|
||||
export interface EmailMailboxRow {
|
||||
readonly id: string;
|
||||
readonly provider: EmailMailboxProvider;
|
||||
/** i18n key for the provider label (brand names route through i18n, M003). */
|
||||
readonly providerKey: string;
|
||||
readonly emailAddress: string;
|
||||
readonly displayName: string | null;
|
||||
readonly isDefaultForUser: boolean;
|
||||
/** True when the row belongs to the current user (owner actions enabled). */
|
||||
readonly isOwn: boolean;
|
||||
readonly status: EmailMailboxStatus;
|
||||
/** i18n key for the status pill (e.g. `emailInbox.mailbox.status.active`). */
|
||||
readonly statusKey: string;
|
||||
/** ISO timestamp of the last successful sync, or null. */
|
||||
readonly lastSyncAt: string | null;
|
||||
/** Klartext error i18n key/text when status = error (M002), else null. */
|
||||
readonly lastErrorText: string | null;
|
||||
readonly initialSync: EmailMailboxInitialSync;
|
||||
}
|
||||
|
||||
export interface EmailMailboxListData {
|
||||
readonly rows: readonly EmailMailboxRow[];
|
||||
/** True when the user may connect a mailbox (email.write bundles it). */
|
||||
readonly canConnect: boolean;
|
||||
readonly configuredProviders: { readonly gmail: boolean; readonly microsoft: boolean };
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
readonly notConfiguredKey: string;
|
||||
}
|
||||
|
||||
export type EmailMailboxListVM = VMState<EmailMailboxListData>;
|
||||
|
||||
export function emailMailboxStatusKey(status: EmailMailboxStatus): string {
|
||||
return `emailInbox.mailbox.status.${status}`;
|
||||
}
|
||||
|
||||
export function emailMailboxProviderKey(provider: EmailMailboxProvider): string {
|
||||
return `emailInbox.provider.${provider}`;
|
||||
}
|
||||
|
||||
export function emailInitialSyncStatusKey(status: EmailInitialSyncStatus): string {
|
||||
return `emailInbox.settings.initialSync.${status}`;
|
||||
}
|
||||
|
||||
/** One per-folder cursor row as the loader reads it (progress is JSONB). */
|
||||
export interface EmailSyncCursorInput {
|
||||
readonly mailboxId: string;
|
||||
readonly initialSyncStatus: EmailInitialSyncStatus;
|
||||
readonly initialSyncProgress: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggregate the per-folder cursor rows of ONE mailbox into a single progress
|
||||
* line: worst status wins (failed > running > pending > completed); percent is
|
||||
* the mean of folder percents when every folder reports one.
|
||||
*/
|
||||
export function aggregateInitialSync(cursors: readonly EmailSyncCursorInput[]): EmailMailboxInitialSync {
|
||||
if (cursors.length === 0) {
|
||||
return { status: "pending", statusKey: emailInitialSyncStatusKey("pending"), progressPercent: null, fetchedCount: null };
|
||||
}
|
||||
const order: Record<EmailInitialSyncStatus, number> = { failed: 3, running: 2, pending: 1, completed: 0 };
|
||||
let status: EmailInitialSyncStatus = "completed";
|
||||
let fetchedCount = 0;
|
||||
let sawFetched = false;
|
||||
const percents: number[] = [];
|
||||
for (const cursor of cursors) {
|
||||
if (order[cursor.initialSyncStatus] > order[status]) {
|
||||
status = cursor.initialSyncStatus;
|
||||
}
|
||||
const progress = cursor.initialSyncProgress as { percent?: unknown; fetchedCount?: unknown } | null;
|
||||
if (progress && typeof progress.percent === "number") {
|
||||
percents.push(Math.max(0, Math.min(100, progress.percent)));
|
||||
}
|
||||
if (progress && typeof progress.fetchedCount === "number") {
|
||||
fetchedCount += progress.fetchedCount;
|
||||
sawFetched = true;
|
||||
}
|
||||
}
|
||||
const progressPercent =
|
||||
status === "completed" ? 100 : percents.length === cursors.length && percents.length > 0 ? Math.round(percents.reduce((a, b) => a + b, 0) / percents.length) : null;
|
||||
return {
|
||||
status,
|
||||
statusKey: emailInitialSyncStatusKey(status),
|
||||
progressPercent,
|
||||
fetchedCount: sawFetched ? fetchedCount : null,
|
||||
};
|
||||
}
|
||||
|
||||
export interface BuildEmailMailboxListInput {
|
||||
readonly rows: readonly EmailMailboxRow[];
|
||||
readonly canConnect: boolean;
|
||||
readonly configuredProviders: { readonly gmail: boolean; readonly microsoft: boolean };
|
||||
}
|
||||
|
||||
export function buildEmailMailboxListVM(input: BuildEmailMailboxListInput): EmailMailboxListVM {
|
||||
// Always "ready" (mirrors the calendar connection VM): the UI renders the
|
||||
// empty-state from the keys when `rows` is empty, keeping the connect
|
||||
// affordance + config hint available.
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows: input.rows,
|
||||
canConnect: input.canConnect,
|
||||
configuredProviders: input.configuredProviders,
|
||||
emptyHeadlineKey: "emailInbox.settings.empty.headline",
|
||||
emptyBodyKey: "emailInbox.settings.empty.body",
|
||||
notConfiguredKey: "emailInbox.settings.notConfigured",
|
||||
},
|
||||
};
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
import type { VMState } from "../index.js";
|
||||
import type { EmailMailboxProvider } from "./mailbox-list.vm.js";
|
||||
import type { EmailLinkBadge } from "./inbox-list.vm.js";
|
||||
|
||||
/**
|
||||
* VA-P23 · message/thread detail view-model (M09 Block F detail). Pure: the
|
||||
* loader sanitizes the bodies SERVER-SIDE (emailHtmlSanitizer) and passes the
|
||||
* safe HTML in — this VM never sees raw provider HTML. Thread = every mirror
|
||||
* with the same providerThreadId, chronological; all but the focused message
|
||||
* collapse by default.
|
||||
*/
|
||||
|
||||
export interface EmailThreadMessageVM {
|
||||
readonly id: string;
|
||||
readonly direction: "inbound" | "outbound";
|
||||
readonly fromName: string | null;
|
||||
readonly fromAddress: string;
|
||||
readonly toSummary: string;
|
||||
readonly ccSummary: string | null;
|
||||
readonly subject: string | null;
|
||||
/** SANITIZED html (or escaped plain-text render) — safe to inject. */
|
||||
readonly safeBodyHtml: string;
|
||||
readonly blockedImageCount: number;
|
||||
readonly sentAt: string;
|
||||
readonly isRead: boolean;
|
||||
readonly isFocused: boolean;
|
||||
readonly collapsedByDefault: boolean;
|
||||
}
|
||||
|
||||
export interface EmailAttachmentVM {
|
||||
readonly attachmentId: string;
|
||||
readonly filename: string;
|
||||
readonly sizeBytes: number;
|
||||
/** Set once imported into v1-Files (download runs via the Files auth-proxy). */
|
||||
readonly importedFileId: string | null;
|
||||
readonly downloadHref: string | null;
|
||||
}
|
||||
|
||||
export interface EmailMatchStateVM {
|
||||
readonly links: readonly EmailLinkBadge[];
|
||||
readonly confidence: "high" | "medium" | "low" | "manual" | "none";
|
||||
/** i18n key: auto-detected vs manually assigned hint (M09 Block F). */
|
||||
readonly sourceKey: string;
|
||||
readonly isManual: boolean;
|
||||
}
|
||||
|
||||
export interface EmailMessageDetailData {
|
||||
readonly focusedId: string;
|
||||
readonly subject: string | null;
|
||||
readonly mailbox: { readonly emailAddress: string; readonly provider: EmailMailboxProvider };
|
||||
readonly thread: readonly EmailThreadMessageVM[];
|
||||
readonly attachments: readonly EmailAttachmentVM[];
|
||||
readonly match: EmailMatchStateVM;
|
||||
readonly canWrite: boolean;
|
||||
readonly replyHref: string;
|
||||
readonly forwardHref: string;
|
||||
readonly backHref: string;
|
||||
readonly allowExternalImages: boolean;
|
||||
}
|
||||
|
||||
export type EmailMessageDetailVM = VMState<EmailMessageDetailData>;
|
||||
|
||||
export function emailMatchSourceKey(confidence: EmailMatchStateVM["confidence"]): string {
|
||||
return confidence === "manual" ? "emailInbox.detail.match.manual" : confidence === "none" ? "emailInbox.detail.match.none" : "emailInbox.detail.match.auto";
|
||||
}
|
||||
|
||||
export function buildEmailMessageDetailVM(data: EmailMessageDetailData): EmailMessageDetailVM {
|
||||
return { status: "ready", data };
|
||||
}
|
||||
|
||||
/** Address list → compact display summary ("Max <max@x.de>, anna@y.de"). */
|
||||
export function summarizeAddresses(list: unknown): string {
|
||||
if (!Array.isArray(list)) return "";
|
||||
return list
|
||||
.map((entry) => {
|
||||
if (!entry || typeof entry !== "object") return "";
|
||||
const address = String((entry as { address?: unknown }).address ?? "");
|
||||
const name = (entry as { name?: unknown }).name;
|
||||
return typeof name === "string" && name.trim() ? `${name} <${address}>` : address;
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join(", ");
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* AK-P14b · campaign detail + reporting view-model (DoD 6). Pure — no
|
||||
* React/Prisma. Turns raw aggregate counts + per-recipient rows + click rows
|
||||
* into KPI percentages, a sorted click-map, the per-recipient table and the A/B
|
||||
* comparison. Percentages are integer-rounded; rates use delivered as the
|
||||
* denominator (0 when nothing delivered).
|
||||
*/
|
||||
|
||||
export type CampaignVariantLabel = "a" | "b";
|
||||
|
||||
export interface CampaignStatsInput {
|
||||
total: number;
|
||||
delivered: number;
|
||||
opened: number;
|
||||
clicked: number;
|
||||
bounced: number;
|
||||
unsubscribed: number;
|
||||
}
|
||||
|
||||
export interface CampaignClickInput {
|
||||
link: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface CampaignRecipientInput {
|
||||
email: string;
|
||||
name: string;
|
||||
variantLabel: CampaignVariantLabel | null;
|
||||
deliveredAt: Date | null;
|
||||
openedAt: Date | null;
|
||||
clickedAt: Date | null;
|
||||
bouncedAt: Date | null;
|
||||
}
|
||||
|
||||
export interface CampaignVariantStatsInput {
|
||||
label: CampaignVariantLabel;
|
||||
subject: string;
|
||||
delivered: number;
|
||||
opened: number;
|
||||
clicked: number;
|
||||
}
|
||||
|
||||
export interface BuildCampaignDetailVMInput {
|
||||
campaign: { id: string; name: string; subject: string; status: string; sentAt: Date | null };
|
||||
stats: CampaignStatsInput;
|
||||
clickMap: readonly CampaignClickInput[];
|
||||
recipients: readonly CampaignRecipientInput[];
|
||||
variants?: readonly CampaignVariantStatsInput[];
|
||||
}
|
||||
|
||||
export interface KpiVM {
|
||||
readonly delivered: number;
|
||||
readonly openRate: number;
|
||||
readonly clickRate: number;
|
||||
readonly bounceRate: number;
|
||||
readonly unsubscribeRate: number;
|
||||
}
|
||||
|
||||
export interface ClickMapRowVM {
|
||||
readonly link: string;
|
||||
readonly count: number;
|
||||
}
|
||||
|
||||
export type RecipientStatus = "bounced" | "clicked" | "opened" | "delivered" | "pending";
|
||||
|
||||
export interface RecipientRowVM {
|
||||
readonly email: string;
|
||||
readonly name: string;
|
||||
readonly variantLabel: CampaignVariantLabel | null;
|
||||
readonly status: RecipientStatus;
|
||||
readonly statusLabelKey: string;
|
||||
}
|
||||
|
||||
export interface VariantComparisonRowVM {
|
||||
readonly label: CampaignVariantLabel;
|
||||
readonly subject: string;
|
||||
readonly delivered: number;
|
||||
readonly openRate: number;
|
||||
readonly clickRate: number;
|
||||
}
|
||||
|
||||
export interface CampaignDetailData {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly subject: string;
|
||||
readonly status: string;
|
||||
readonly statusLabelKey: string;
|
||||
readonly sentAtIso: string | null;
|
||||
readonly kpi: KpiVM;
|
||||
readonly clickMap: readonly ClickMapRowVM[];
|
||||
readonly recipients: readonly RecipientRowVM[];
|
||||
readonly variants: readonly VariantComparisonRowVM[];
|
||||
readonly hasAbTest: boolean;
|
||||
}
|
||||
|
||||
export type CampaignDetailVM = VMState<CampaignDetailData>;
|
||||
|
||||
export function rate(numerator: number, denominator: number): number {
|
||||
return denominator > 0 ? Math.round((numerator / denominator) * 100) : 0;
|
||||
}
|
||||
|
||||
function recipientStatus(r: CampaignRecipientInput): RecipientStatus {
|
||||
if (r.bouncedAt) return "bounced";
|
||||
if (r.clickedAt) return "clicked";
|
||||
if (r.openedAt) return "opened";
|
||||
if (r.deliveredAt) return "delivered";
|
||||
return "pending";
|
||||
}
|
||||
|
||||
export function buildCampaignDetailVM(input: BuildCampaignDetailVMInput): CampaignDetailVM {
|
||||
const { stats } = input;
|
||||
const variants = input.variants ?? [];
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
id: input.campaign.id,
|
||||
name: input.campaign.name,
|
||||
subject: input.campaign.subject,
|
||||
status: input.campaign.status,
|
||||
statusLabelKey: `emailMarketing.campaign.status.${input.campaign.status}`,
|
||||
sentAtIso: input.campaign.sentAt ? input.campaign.sentAt.toISOString() : null,
|
||||
kpi: {
|
||||
delivered: stats.delivered,
|
||||
openRate: rate(stats.opened, stats.delivered),
|
||||
clickRate: rate(stats.clicked, stats.delivered),
|
||||
bounceRate: rate(stats.bounced, stats.total),
|
||||
unsubscribeRate: rate(stats.unsubscribed, stats.delivered),
|
||||
},
|
||||
clickMap: [...input.clickMap].sort((a, b) => b.count - a.count).map((c) => ({ link: c.link, count: c.count })),
|
||||
recipients: input.recipients.map((r) => {
|
||||
const status = recipientStatus(r);
|
||||
return { email: r.email, name: r.name, variantLabel: r.variantLabel, status, statusLabelKey: `emailMarketing.recipient.status.${status}` };
|
||||
}),
|
||||
variants: variants.map((v) => ({ label: v.label, subject: v.subject, delivered: v.delivered, openRate: rate(v.opened, v.delivered), clickRate: rate(v.clicked, v.delivered) })),
|
||||
hasAbTest: variants.length > 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
import type { VMState } from "../index.js";
|
||||
import { rate } from "./campaign-detail.vm.js";
|
||||
|
||||
/**
|
||||
* AK-P14b · campaign list view-model (DoD 6). Pure — no React/Prisma. One row
|
||||
* per campaign with status pill, recipient count, send date and open/click rate.
|
||||
*/
|
||||
|
||||
export interface CampaignListItemInput {
|
||||
id: string;
|
||||
name: string;
|
||||
status: string;
|
||||
recipientCount: number;
|
||||
delivered: number;
|
||||
opened: number;
|
||||
clicked: number;
|
||||
sentAt: Date | null;
|
||||
}
|
||||
|
||||
export interface CampaignListRowVM {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly status: string;
|
||||
readonly statusLabelKey: string;
|
||||
readonly recipientCount: number;
|
||||
readonly openRate: number;
|
||||
readonly clickRate: number;
|
||||
readonly sentAtIso: string | null;
|
||||
}
|
||||
|
||||
export interface CampaignListData {
|
||||
readonly rows: readonly CampaignListRowVM[];
|
||||
}
|
||||
|
||||
export type CampaignListVM = VMState<CampaignListData>;
|
||||
|
||||
export function buildCampaignListVM(input: { items: readonly CampaignListItemInput[] }): CampaignListVM {
|
||||
if (input.items.length === 0) return { status: "empty" };
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows: input.items.map((c) => ({
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
status: c.status,
|
||||
statusLabelKey: `emailMarketing.campaign.status.${c.status}`,
|
||||
recipientCount: c.recipientCount,
|
||||
openRate: rate(c.opened, c.delivered),
|
||||
clickRate: rate(c.clicked, c.delivered),
|
||||
sentAtIso: c.sentAt ? c.sentAt.toISOString() : null,
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildPresendChecklistVM, evaluatePresendChecklist } from "./presend-checklist.vm.js";
|
||||
import { buildCampaignDetailVM, rate } from "./campaign-detail.vm.js";
|
||||
import { buildCampaignListVM } from "./campaign-list.vm.js";
|
||||
import { buildSegmentVM } from "./segment.vm.js";
|
||||
|
||||
describe("presend-checklist.vm", () => {
|
||||
const ok = { domainVerified: true, footerConfigured: true, subject: "Hi", recipientCount: 10, dailyCapUsed: 0, dailyCapLimit: 1000 };
|
||||
|
||||
it("passes when all green", () => {
|
||||
expect(evaluatePresendChecklist(ok).blocked).toBe(false);
|
||||
});
|
||||
it("blocks on unverified domain + over cap + empty subject + 0 recipients", () => {
|
||||
expect(evaluatePresendChecklist({ ...ok, domainVerified: false }).blocked).toBe(true);
|
||||
expect(evaluatePresendChecklist({ ...ok, dailyCapUsed: 995, recipientCount: 10, dailyCapLimit: 1000 }).blocked).toBe(true);
|
||||
expect(evaluatePresendChecklist({ ...ok, dailyCapUsed: 9e9, dailyCapLimit: null }).blocked).toBe(false);
|
||||
expect(evaluatePresendChecklist({ ...ok, subject: " " }).blocked).toBe(true);
|
||||
expect(evaluatePresendChecklist({ ...ok, recipientCount: 0 }).blocked).toBe(true);
|
||||
});
|
||||
it("VM adds label keys + tone + fix key", () => {
|
||||
const vm = buildPresendChecklistVM({ ...ok, domainVerified: false });
|
||||
expect(vm.status).toBe("ready");
|
||||
const domain = vm.data?.items.find((i) => i.key === "domain");
|
||||
expect(domain).toMatchObject({ ok: false, tone: "danger", labelKey: "emailMarketing.presend.check.domain", fixKey: "emailMarketing.presend.fix.domain" });
|
||||
expect(vm.data?.blocked).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("campaign-detail.vm", () => {
|
||||
it("rate() rounds and guards zero denominator", () => {
|
||||
expect(rate(1, 4)).toBe(25);
|
||||
expect(rate(1, 3)).toBe(33);
|
||||
expect(rate(5, 0)).toBe(0);
|
||||
});
|
||||
it("computes KPIs, sorts click-map, classifies recipients, builds A/B", () => {
|
||||
const vm = buildCampaignDetailVM({
|
||||
campaign: { id: "c1", name: "N", subject: "S", status: "completed", sentAt: new Date("2026-06-01T00:00:00Z") },
|
||||
stats: { total: 100, delivered: 80, opened: 40, clicked: 20, bounced: 20, unsubscribed: 8 },
|
||||
clickMap: [
|
||||
{ link: "https://a", count: 3 },
|
||||
{ link: "https://b", count: 9 },
|
||||
],
|
||||
recipients: [
|
||||
{ email: "a@x.de", name: "A", variantLabel: "a", deliveredAt: new Date(), openedAt: new Date(), clickedAt: new Date(), bouncedAt: null },
|
||||
{ email: "b@x.de", name: "B", variantLabel: "b", deliveredAt: new Date(), openedAt: null, clickedAt: null, bouncedAt: null },
|
||||
{ email: "c@x.de", name: "C", variantLabel: null, deliveredAt: null, openedAt: null, clickedAt: null, bouncedAt: new Date() },
|
||||
],
|
||||
variants: [
|
||||
{ label: "a", subject: "A", delivered: 40, opened: 24, clicked: 12 },
|
||||
{ label: "b", subject: "B", delivered: 40, opened: 16, clicked: 8 },
|
||||
],
|
||||
});
|
||||
expect(vm.data?.kpi).toEqual({ delivered: 80, openRate: 50, clickRate: 25, bounceRate: 20, unsubscribeRate: 10 });
|
||||
expect(vm.data?.clickMap.map((c) => c.link)).toEqual(["https://b", "https://a"]);
|
||||
expect(vm.data?.recipients.map((r) => r.status)).toEqual(["clicked", "delivered", "bounced"]);
|
||||
expect(vm.data?.hasAbTest).toBe(true);
|
||||
expect(vm.data?.variants[0]).toMatchObject({ label: "a", openRate: 60, clickRate: 30 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("campaign-list.vm", () => {
|
||||
it("is empty with no items and builds rows otherwise", () => {
|
||||
expect(buildCampaignListVM({ items: [] }).status).toBe("empty");
|
||||
const vm = buildCampaignListVM({ items: [{ id: "c1", name: "N", status: "draft", recipientCount: 5, delivered: 4, opened: 2, clicked: 1, sentAt: null }] });
|
||||
expect(vm.data?.rows[0]).toMatchObject({ id: "c1", statusLabelKey: "emailMarketing.campaign.status.draft", openRate: 50, clickRate: 25, sentAtIso: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe("segment.vm", () => {
|
||||
it("sums exclusion and exposes labelled rows", () => {
|
||||
const vm = buildSegmentVM({
|
||||
matched: 100,
|
||||
eligible: 70,
|
||||
exclusion: { archived: 5, noEmail: 10, unsubscribed: 6, suppressed: 4, noOptIn: 5 },
|
||||
sample: [{ kontaktId: "k1", name: "Ada", email: "ada@x.de" }],
|
||||
scanCapped: false,
|
||||
isStaticSnapshot: false,
|
||||
});
|
||||
expect(vm.data?.excludedTotal).toBe(30);
|
||||
expect(vm.data?.exclusion.map((r) => r.reason)).toEqual(["archived", "noEmail", "unsubscribed", "suppressed", "noOptIn"]);
|
||||
expect(vm.data?.exclusion[0]).toMatchObject({ labelKey: "emailMarketing.segment.exclusion.archived", count: 5 });
|
||||
expect(vm.data?.sample).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* AK-P14b · pre-send checklist (DoD 5). Pure — no React/Prisma. Computes the
|
||||
* DSGVO/deliverability gate that BLOCKS a campaign send when red: verified
|
||||
* sending domain, unsubscribe link, Impressum, subject, > 0 recipients, daily
|
||||
* cap. The server send-engine calls `evaluatePresendChecklist` as a hard gate;
|
||||
* the route renders `buildPresendChecklistVM` with i18n labels + fix-links.
|
||||
*/
|
||||
|
||||
export type PresendCheckKey = "domain" | "unsubscribe" | "impressum" | "subject" | "recipients" | "dailyCap";
|
||||
|
||||
export interface PresendChecklistInput {
|
||||
/** TenantSendingDomain.verificationStatus === "verified". */
|
||||
domainVerified: boolean;
|
||||
/** A non-empty footer is configured (carries unsubscribe link + Impressum). */
|
||||
footerConfigured: boolean;
|
||||
subject: string;
|
||||
recipientCount: number;
|
||||
/** Sends already counted against today's cap for this tenant. */
|
||||
dailyCapUsed: number;
|
||||
/** Daily send cap; null = no cap configured. */
|
||||
dailyCapLimit: number | null;
|
||||
}
|
||||
|
||||
export interface PresendCheckItem {
|
||||
key: PresendCheckKey;
|
||||
ok: boolean;
|
||||
/** i18n key for the fix action (only present when not ok). */
|
||||
fixKey?: string;
|
||||
}
|
||||
|
||||
export interface PresendChecklistResult {
|
||||
items: PresendCheckItem[];
|
||||
/** True when at least one check failed — the send action must be blocked. */
|
||||
blocked: boolean;
|
||||
}
|
||||
|
||||
const FIX_KEYS: Record<PresendCheckKey, string> = {
|
||||
domain: "emailMarketing.presend.fix.domain",
|
||||
unsubscribe: "emailMarketing.presend.fix.unsubscribe",
|
||||
impressum: "emailMarketing.presend.fix.impressum",
|
||||
subject: "emailMarketing.presend.fix.subject",
|
||||
recipients: "emailMarketing.presend.fix.recipients",
|
||||
dailyCap: "emailMarketing.presend.fix.dailyCap",
|
||||
};
|
||||
|
||||
export function evaluatePresendChecklist(input: PresendChecklistInput): PresendChecklistResult {
|
||||
const withinCap = input.dailyCapLimit === null || input.dailyCapUsed + input.recipientCount <= input.dailyCapLimit;
|
||||
const checks: Array<[PresendCheckKey, boolean]> = [
|
||||
["domain", input.domainVerified],
|
||||
["unsubscribe", input.footerConfigured],
|
||||
["impressum", input.footerConfigured],
|
||||
["subject", input.subject.trim().length > 0],
|
||||
["recipients", input.recipientCount > 0],
|
||||
["dailyCap", withinCap],
|
||||
];
|
||||
const items: PresendCheckItem[] = checks.map(([key, ok]) => (ok ? { key, ok } : { key, ok, fixKey: FIX_KEYS[key] }));
|
||||
return { items, blocked: items.some((i) => !i.ok) };
|
||||
}
|
||||
|
||||
// --- View-model (presentation: i18n labels + tone) -------------------------
|
||||
|
||||
export interface PresendCheckItemVM {
|
||||
readonly key: PresendCheckKey;
|
||||
readonly ok: boolean;
|
||||
/** i18n label key, e.g. `emailMarketing.presend.check.domain`. */
|
||||
readonly labelKey: string;
|
||||
readonly tone: "success" | "danger";
|
||||
readonly fixKey: string | null;
|
||||
}
|
||||
|
||||
export interface PresendChecklistData {
|
||||
readonly items: readonly PresendCheckItemVM[];
|
||||
readonly blocked: boolean;
|
||||
}
|
||||
|
||||
export type PresendChecklistVM = VMState<PresendChecklistData>;
|
||||
|
||||
export function buildPresendChecklistVM(input: PresendChecklistInput): PresendChecklistVM {
|
||||
const result = evaluatePresendChecklist(input);
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
blocked: result.blocked,
|
||||
items: result.items.map((i) => ({
|
||||
key: i.key,
|
||||
ok: i.ok,
|
||||
labelKey: `emailMarketing.presend.check.${i.key}`,
|
||||
tone: i.ok ? "success" : "danger",
|
||||
fixKey: i.fixKey ?? null,
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* AK-P14b · segment resolution view-model (DoD 2). Pure — no React/Prisma. Turns
|
||||
* a SegmentService resolution (matched / eligible / non-overlapping exclusion
|
||||
* breakdown / sample) into the segment screen: live recipient count, the
|
||||
* auto-exclusion rows (each with an i18n label) and the sample preview.
|
||||
*/
|
||||
|
||||
export type SegmentExclusionReason = "archived" | "noEmail" | "unsubscribed" | "suppressed" | "noOptIn";
|
||||
|
||||
export interface SegmentExclusionInput {
|
||||
archived: number;
|
||||
noEmail: number;
|
||||
unsubscribed: number;
|
||||
suppressed: number;
|
||||
noOptIn: number;
|
||||
}
|
||||
|
||||
export interface SegmentSampleInput {
|
||||
kontaktId: string;
|
||||
name: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface BuildSegmentVMInput {
|
||||
matched: number;
|
||||
eligible: number;
|
||||
exclusion: SegmentExclusionInput;
|
||||
sample: readonly SegmentSampleInput[];
|
||||
scanCapped: boolean;
|
||||
isStaticSnapshot: boolean;
|
||||
}
|
||||
|
||||
export interface SegmentExclusionRowVM {
|
||||
readonly reason: SegmentExclusionReason;
|
||||
readonly labelKey: string;
|
||||
readonly count: number;
|
||||
}
|
||||
|
||||
export interface SegmentData {
|
||||
readonly matched: number;
|
||||
readonly eligible: number;
|
||||
readonly excludedTotal: number;
|
||||
readonly exclusion: readonly SegmentExclusionRowVM[];
|
||||
readonly sample: readonly SegmentSampleInput[];
|
||||
readonly scanCapped: boolean;
|
||||
readonly isStaticSnapshot: boolean;
|
||||
}
|
||||
|
||||
export type SegmentVM = VMState<SegmentData>;
|
||||
|
||||
const REASON_ORDER: SegmentExclusionReason[] = ["archived", "noEmail", "unsubscribed", "suppressed", "noOptIn"];
|
||||
|
||||
export function buildSegmentVM(input: BuildSegmentVMInput): SegmentVM {
|
||||
const exclusion = REASON_ORDER.map((reason) => ({
|
||||
reason,
|
||||
labelKey: `emailMarketing.segment.exclusion.${reason}`,
|
||||
count: input.exclusion[reason],
|
||||
}));
|
||||
const excludedTotal = exclusion.reduce((sum, row) => sum + row.count, 0);
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
matched: input.matched,
|
||||
eligible: input.eligible,
|
||||
excludedTotal,
|
||||
exclusion,
|
||||
sample: input.sample.map((s) => ({ kontaktId: s.kontaktId, name: s.name, email: s.email })),
|
||||
scanCapped: input.scanCapped,
|
||||
isStaticSnapshot: input.isStaticSnapshot,
|
||||
},
|
||||
};
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildSendingDomainVM } from "./sending-domain.vm.js";
|
||||
|
||||
const baseDomain = {
|
||||
id: "d1",
|
||||
domain: "acme.test",
|
||||
status: "verifying" as const,
|
||||
dkimSelector: "mailjet._domainkey.acme.test",
|
||||
dkimRecord: "v=DKIM1; k=rsa; p=MIIB...",
|
||||
spfRecord: "v=spf1 include:spf.mailjet.com ~all",
|
||||
dmarcRecord: "v=DMARC1; p=none",
|
||||
errorMessageKey: null,
|
||||
};
|
||||
|
||||
describe("buildSendingDomainVM", () => {
|
||||
it("returns empty state when no domain is configured", () => {
|
||||
const vm = buildSendingDomainVM({ domain: null, bccAddress: null, bccEnabled: false, canManage: true });
|
||||
expect(vm.status).toBe("empty");
|
||||
});
|
||||
|
||||
it("builds three DNS record cards with copy values and the status ampel", () => {
|
||||
const vm = buildSendingDomainVM({ domain: baseDomain, bccAddress: "crm@acme.test", bccEnabled: true, canManage: true });
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.records.map((r) => r.kind)).toEqual(["dkim", "spf", "dmarc"]);
|
||||
expect(vm.data?.records[2]).toMatchObject({ kind: "dmarc", host: "_dmarc.acme.test", value: "v=DMARC1; p=none" });
|
||||
expect(vm.data?.statusLabelKey).toBe("email.domain.status.verifying");
|
||||
expect(vm.data?.statusTone).toBe("warning");
|
||||
expect(vm.data?.canSend).toBe(false);
|
||||
expect(vm.data?.bccAddress).toBe("crm@acme.test");
|
||||
expect(vm.data?.bccEnabled).toBe(true);
|
||||
});
|
||||
|
||||
it("unlocks sending and uses the success tone when verified", () => {
|
||||
const vm = buildSendingDomainVM({ domain: { ...baseDomain, status: "verified" }, bccAddress: null, bccEnabled: false, canManage: false });
|
||||
expect(vm.data?.canSend).toBe(true);
|
||||
expect(vm.data?.statusTone).toBe("success");
|
||||
expect(vm.data?.showFailure).toBe(false);
|
||||
expect(vm.data?.errorMessageKey).toBeNull();
|
||||
});
|
||||
|
||||
it("surfaces the 7-day Klartext failure when failed", () => {
|
||||
const vm = buildSendingDomainVM({ domain: { ...baseDomain, status: "failed", errorMessageKey: "email.domain.error.notVerifiedAfter7Days" }, bccAddress: null, bccEnabled: false, canManage: true });
|
||||
expect(vm.data?.showFailure).toBe(true);
|
||||
expect(vm.data?.statusTone).toBe("danger");
|
||||
expect(vm.data?.errorMessageKey).toBe("email.domain.error.notVerifiedAfter7Days");
|
||||
});
|
||||
|
||||
it("falls back to the default failure key when failed without a detail", () => {
|
||||
const vm = buildSendingDomainVM({ domain: { ...baseDomain, status: "failed", errorMessageKey: null }, bccAddress: null, bccEnabled: false, canManage: true });
|
||||
expect(vm.data?.errorMessageKey).toBe("email.domain.error.notVerifiedAfter7Days");
|
||||
});
|
||||
});
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* AK-P14a · Sending-domain view-model. Pure functions — no React, no Prisma, no
|
||||
* app imports. Maps a TenantSendingDomain (+ its BCC-logging inbound address)
|
||||
* into the settings screen: DNS record cards with copy values, the verification
|
||||
* status ampel (pending/verifying/verified/failed) with a tone token, the 7-day
|
||||
* Klartext failure surface, and the BCC-logging toggle.
|
||||
*/
|
||||
|
||||
export type SendingDomainStatusVM = "pending" | "verifying" | "verified" | "failed";
|
||||
|
||||
export type DnsRecordKind = "dkim" | "spf" | "dmarc";
|
||||
|
||||
export interface DnsRecordCard {
|
||||
readonly kind: DnsRecordKind;
|
||||
/** i18n label key, e.g. `email.domain.record.dkim`. */
|
||||
readonly labelKey: string;
|
||||
/** Host/name the tenant publishes the record at (may be null until provisioned). */
|
||||
readonly host: string | null;
|
||||
/** The record value to copy (null until Mailjet returns it). */
|
||||
readonly value: string | null;
|
||||
}
|
||||
|
||||
export interface SendingDomainData {
|
||||
readonly hasDomain: boolean;
|
||||
readonly id: string | null;
|
||||
readonly domain: string | null;
|
||||
readonly status: SendingDomainStatusVM;
|
||||
/** i18n key for the status pill, e.g. `email.domain.status.verified`. */
|
||||
readonly statusLabelKey: string;
|
||||
readonly statusTone: "success" | "warning" | "danger" | "neutral";
|
||||
readonly records: readonly DnsRecordCard[];
|
||||
/** True once the domain has failed (incomplete > 7 days) → show Klartext error. */
|
||||
readonly showFailure: boolean;
|
||||
/** i18n key carrying the Klartext failure detail, or null. */
|
||||
readonly errorMessageKey: string | null;
|
||||
/** Whether sending is unlocked (verified) — gates the marketing send (AK-P14b). */
|
||||
readonly canSend: boolean;
|
||||
readonly bccAddress: string | null;
|
||||
readonly bccEnabled: boolean;
|
||||
readonly canManage: boolean;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type SendingDomainVM = VMState<SendingDomainData>;
|
||||
|
||||
const STATUS_TONE: Record<SendingDomainStatusVM, SendingDomainData["statusTone"]> = {
|
||||
pending: "neutral",
|
||||
verifying: "warning",
|
||||
verified: "success",
|
||||
failed: "danger",
|
||||
};
|
||||
|
||||
export interface BuildSendingDomainVMInput {
|
||||
readonly domain: {
|
||||
readonly id: string;
|
||||
readonly domain: string;
|
||||
readonly status: SendingDomainStatusVM;
|
||||
readonly dkimSelector: string | null;
|
||||
readonly dkimRecord: string | null;
|
||||
readonly spfRecord: string | null;
|
||||
readonly dmarcRecord: string | null;
|
||||
readonly errorMessageKey: string | null;
|
||||
} | null;
|
||||
readonly bccAddress: string | null;
|
||||
readonly bccEnabled: boolean;
|
||||
readonly canManage: boolean;
|
||||
}
|
||||
|
||||
export function buildSendingDomainVM(input: BuildSendingDomainVMInput): SendingDomainVM {
|
||||
if (!input.domain) {
|
||||
return {
|
||||
status: "empty",
|
||||
};
|
||||
}
|
||||
const d = input.domain;
|
||||
const records: DnsRecordCard[] = [
|
||||
{ kind: "dkim", labelKey: "email.domain.record.dkim", host: d.dkimSelector, value: d.dkimRecord },
|
||||
{ kind: "spf", labelKey: "email.domain.record.spf", host: d.domain, value: d.spfRecord },
|
||||
{ kind: "dmarc", labelKey: "email.domain.record.dmarc", host: `_dmarc.${d.domain}`, value: d.dmarcRecord },
|
||||
];
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
hasDomain: true,
|
||||
id: d.id,
|
||||
domain: d.domain,
|
||||
status: d.status,
|
||||
statusLabelKey: `email.domain.status.${d.status}`,
|
||||
statusTone: STATUS_TONE[d.status],
|
||||
records,
|
||||
showFailure: d.status === "failed",
|
||||
errorMessageKey: d.status === "failed" ? d.errorMessageKey ?? "email.domain.error.notVerifiedAfter7Days" : null,
|
||||
canSend: d.status === "verified",
|
||||
bccAddress: input.bccAddress,
|
||||
bccEnabled: input.bccEnabled,
|
||||
canManage: input.canManage,
|
||||
emptyHeadlineKey: "email.domain.empty.headline",
|
||||
emptyBodyKey: "email.domain.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildFileBrowserVM, type FileBrowserFilterState, type FileBrowserRow } from "../index.js";
|
||||
|
||||
const filter: FileBrowserFilterState = {
|
||||
entityType: null,
|
||||
mimeGroup: null,
|
||||
tags: [],
|
||||
assignedToUserId: null,
|
||||
includeArchived: false,
|
||||
};
|
||||
|
||||
const row: FileBrowserRow = {
|
||||
id: "f1",
|
||||
displayName: "foto.jpg",
|
||||
mimeType: "image/jpeg",
|
||||
sizeBytes: 2048,
|
||||
createdAtIso: "2026-06-19T08:00:00.000Z",
|
||||
tags: [],
|
||||
source: "manual_upload",
|
||||
previewStatus: "ready",
|
||||
scanStatus: "clean",
|
||||
thumbnailUrl: "/acme/media/f1/thumb",
|
||||
detailHref: "/acme/files/f1",
|
||||
linkedEntityLabelKey: null,
|
||||
};
|
||||
|
||||
describe("buildFileBrowserVM nextCursor default on the non-empty path (file-browser.ts:116)", () => {
|
||||
it("coerces a missing cursor to null when rows are present (last page)", () => {
|
||||
const vm = buildFileBrowserVM({ rows: [row], filter, canWrite: true, canDelete: false });
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows).toHaveLength(1);
|
||||
expect(vm.data.nextCursor).toBeNull();
|
||||
});
|
||||
|
||||
it("coerces an explicit null cursor to null on the non-empty path", () => {
|
||||
const vm = buildFileBrowserVM({ rows: [row], filter, canWrite: true, canDelete: false, nextCursor: null });
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.nextCursor).toBeNull();
|
||||
});
|
||||
});
|
||||
+25
@@ -39,10 +39,30 @@ export interface FileBrowserFilterState {
|
||||
readonly includeArchived: boolean;
|
||||
}
|
||||
|
||||
/** A selectable assignee (Verantwortlicher) filter option. */
|
||||
export interface FileAssigneeOption {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The option lists that populate the browser filter dropdowns. Built once by the
|
||||
* loader (tenant-scoped) and passed in; the VM stays pure. `entityTypes` are raw
|
||||
* enum keys — the UI maps them to i18n labels.
|
||||
*/
|
||||
export interface FileBrowserFilterOptions {
|
||||
readonly entityTypes: readonly string[];
|
||||
readonly tags: readonly string[];
|
||||
readonly assignees: readonly FileAssigneeOption[];
|
||||
}
|
||||
|
||||
const EMPTY_FILTER_OPTIONS: FileBrowserFilterOptions = { entityTypes: [], tags: [], assignees: [] };
|
||||
|
||||
export interface FileBrowserData {
|
||||
readonly viewMode: FileViewMode;
|
||||
readonly rows: readonly FileBrowserRow[];
|
||||
readonly filter: FileBrowserFilterState;
|
||||
readonly filterOptions: FileBrowserFilterOptions;
|
||||
readonly canWrite: boolean;
|
||||
readonly canDelete: boolean;
|
||||
/** Cursor of the next page (null = last page). */
|
||||
@@ -80,6 +100,8 @@ export interface BuildFileBrowserVMInput {
|
||||
readonly viewMode?: FileViewMode;
|
||||
readonly rows: readonly FileBrowserRow[];
|
||||
readonly filter: FileBrowserFilterState;
|
||||
/** Option lists for the filter dropdowns. Defaults to empty when omitted. */
|
||||
readonly filterOptions?: FileBrowserFilterOptions;
|
||||
readonly canWrite: boolean;
|
||||
readonly canDelete: boolean;
|
||||
readonly nextCursor?: string | null;
|
||||
@@ -87,6 +109,7 @@ export interface BuildFileBrowserVMInput {
|
||||
|
||||
export function buildFileBrowserVM(input: BuildFileBrowserVMInput): FileBrowserVM {
|
||||
const viewMode: FileViewMode = input.viewMode ?? "table";
|
||||
const filterOptions = input.filterOptions ?? EMPTY_FILTER_OPTIONS;
|
||||
if (input.rows.length === 0) {
|
||||
// Empty stays a `ready` state with a plain-text empty state (DoD 23) so the
|
||||
// filter/toggle bar and upload CTA remain visible.
|
||||
@@ -96,6 +119,7 @@ export function buildFileBrowserVM(input: BuildFileBrowserVMInput): FileBrowserV
|
||||
viewMode,
|
||||
rows: [],
|
||||
filter: input.filter,
|
||||
filterOptions,
|
||||
canWrite: input.canWrite,
|
||||
canDelete: input.canDelete,
|
||||
nextCursor: null,
|
||||
@@ -111,6 +135,7 @@ export function buildFileBrowserVM(input: BuildFileBrowserVMInput): FileBrowserV
|
||||
viewMode,
|
||||
rows: input.rows,
|
||||
filter: input.filter,
|
||||
filterOptions,
|
||||
canWrite: input.canWrite,
|
||||
canDelete: input.canDelete,
|
||||
nextCursor: input.nextCursor ?? null,
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildFileDetailVM, type BuildFileDetailVMInput } from "../index.js";
|
||||
|
||||
const base: BuildFileDetailVMInput = {
|
||||
id: "f1",
|
||||
displayName: "vertrag.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 9999,
|
||||
createdAtIso: "2026-06-19T08:00:00.000Z",
|
||||
tags: [],
|
||||
notes: null,
|
||||
source: "manual_upload",
|
||||
previewStatus: "ready",
|
||||
scanStatus: "clean",
|
||||
previewUrl: "/acme/media/f1/preview",
|
||||
downloadUrl: "/acme/media/f1/original",
|
||||
assignedToUserId: null,
|
||||
linkedEntities: [],
|
||||
canWrite: true,
|
||||
canDelete: false,
|
||||
canAdmin: false,
|
||||
};
|
||||
|
||||
describe("previewFallbackKey pending/generating branch (file-detail.ts:69)", () => {
|
||||
it.each(["pending", "generating"] as const)("emits the pending hint while preview status is %s", (previewStatus) => {
|
||||
const vm = buildFileDetailVM({ ...base, previewStatus, previewUrl: null });
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.previewFallbackKey).toBe("files.detail.preview.pending");
|
||||
// A still-generating preview is never regenerable (only a failed one is).
|
||||
expect(vm.data.canRegeneratePreview).toBe(false);
|
||||
});
|
||||
|
||||
it("emits no fallback key once the preview is ready", () => {
|
||||
const vm = buildFileDetailVM({ ...base, previewStatus: "ready" });
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.previewFallbackKey).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("scanNoticeKey pending branch (file-detail.ts:75)", () => {
|
||||
it("notes a still-pending virus scan and keeps the preview URL (not infected)", () => {
|
||||
const vm = buildFileDetailVM({ ...base, scanStatus: "pending" });
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.scanNoticeKey).toBe("files.detail.scan.pending");
|
||||
expect(vm.data.previewUrl).toBe("/acme/media/f1/preview");
|
||||
});
|
||||
|
||||
it("emits no scan notice for a clean file", () => {
|
||||
const vm = buildFileDetailVM({ ...base, scanStatus: "clean" });
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.scanNoticeKey).toBeNull();
|
||||
});
|
||||
});
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* HR announcement view-models (AK-P17b). Pure functions. Feed (pinned first,
|
||||
* optional unread-only filter) and detail (markdown body, grouped reactions,
|
||||
* single-level comments, acknowledgement state, optional read-receipt table for
|
||||
* managers). No React, no Prisma, no app imports. Author/commenter display names
|
||||
* are resolved by the loader.
|
||||
*/
|
||||
|
||||
export interface HrAnnouncementFeedRow {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly snippet: string;
|
||||
readonly pinned: boolean;
|
||||
readonly isRead: boolean;
|
||||
readonly requiresAcknowledgement: boolean;
|
||||
readonly isAcknowledged: boolean;
|
||||
readonly reactionCount: number;
|
||||
readonly commentCount: number;
|
||||
readonly publishedIso: string;
|
||||
readonly detailHref: string;
|
||||
}
|
||||
|
||||
export interface HrAnnouncementFeedData {
|
||||
readonly rows: readonly HrAnnouncementFeedRow[];
|
||||
readonly unreadOnly: boolean;
|
||||
readonly canManage: boolean;
|
||||
readonly manageHref: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type HrAnnouncementFeedVM = VMState<HrAnnouncementFeedData>;
|
||||
|
||||
export interface HrReactionGroup {
|
||||
readonly reaction: string;
|
||||
readonly count: number;
|
||||
readonly mine: boolean;
|
||||
}
|
||||
|
||||
export interface HrAnnouncementComment {
|
||||
readonly id: string;
|
||||
readonly authorLabel: string;
|
||||
readonly body: string;
|
||||
readonly createdIso: string;
|
||||
readonly canArchive: boolean;
|
||||
}
|
||||
|
||||
export interface HrReadReceiptRow {
|
||||
readonly userLabel: string;
|
||||
readonly readIso: string;
|
||||
readonly acknowledged: boolean;
|
||||
}
|
||||
|
||||
export interface HrAnnouncementDetailData {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly bodyMarkdown: string;
|
||||
readonly authorLabel: string;
|
||||
readonly publishedIso: string;
|
||||
readonly requiresAcknowledgement: boolean;
|
||||
readonly isAcknowledged: boolean;
|
||||
readonly reactions: readonly HrReactionGroup[];
|
||||
readonly comments: readonly HrAnnouncementComment[];
|
||||
readonly canManage: boolean;
|
||||
/** Present only for managers (otherwise empty). */
|
||||
readonly readReceipts: readonly HrReadReceiptRow[];
|
||||
readonly commentEmptyKey: string;
|
||||
}
|
||||
|
||||
export type HrAnnouncementDetailVM = VMState<HrAnnouncementDetailData>;
|
||||
|
||||
export function buildAnnouncementFeedVM(input: { rows: readonly HrAnnouncementFeedRow[]; unreadOnly: boolean; canManage: boolean; manageHref: string }): HrAnnouncementFeedVM {
|
||||
const rows = input.unreadOnly ? input.rows.filter((row) => !row.isRead) : input.rows;
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows,
|
||||
unreadOnly: input.unreadOnly,
|
||||
canManage: input.canManage,
|
||||
manageHref: input.manageHref,
|
||||
emptyHeadlineKey: "hr.announcements.empty.headline",
|
||||
emptyBodyKey: "hr.announcements.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function buildAnnouncementDetailVM(input: Omit<HrAnnouncementDetailData, "commentEmptyKey">): HrAnnouncementDetailVM {
|
||||
return { status: "ready", data: { ...input, commentEmptyKey: "hr.announcements.comments.empty" } };
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildHrDirectoryVM, type HrDirectoryRow } from "./hr-directory.vm.js";
|
||||
import { buildHrLocationListVM, type HrLocationRow } from "./hr-location.vm.js";
|
||||
import { buildHrDocumentListVM, hrDocumentKindKey, type HrDocumentRow } from "./hr-document.vm.js";
|
||||
|
||||
// AK-P17a — directory/location/document VMs are pure; these tests cover the
|
||||
// ready/empty contract and the non-sensitive shape of the directory.
|
||||
|
||||
describe("buildHrDirectoryVM", () => {
|
||||
const row: HrDirectoryRow = {
|
||||
userId: "u1",
|
||||
name: "Alex Doe",
|
||||
email: "alex@acme.test",
|
||||
position: "Engineer",
|
||||
team: "Platform",
|
||||
locationName: "HQ",
|
||||
detailHref: "/acme/hr/directory/u1",
|
||||
};
|
||||
|
||||
it("carries only non-sensitive display fields (no emergency contact)", () => {
|
||||
const vm = buildHrDirectoryVM({ rows: [row], canManage: false });
|
||||
const data = vm.data!.rows[0]! as unknown as Record<string, unknown>;
|
||||
expect(data).not.toHaveProperty("emergencyContact");
|
||||
expect(data).not.toHaveProperty("emergencyContactCiphertext");
|
||||
expect(data.name).toBe("Alex Doe");
|
||||
});
|
||||
|
||||
it("keeps an empty directory in a ready state", () => {
|
||||
const vm = buildHrDirectoryVM({ rows: [], canManage: true });
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.emptyHeadlineKey).toBe("hr.directory.empty.headline");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildHrLocationListVM", () => {
|
||||
const row: HrLocationRow = {
|
||||
id: "l1",
|
||||
name: "HQ",
|
||||
addressLine1: "Main St 1",
|
||||
postalCode: "1010",
|
||||
city: "Vienna",
|
||||
country: "AT",
|
||||
phone: null,
|
||||
latitude: null,
|
||||
longitude: null,
|
||||
description: null,
|
||||
isDefault: true,
|
||||
employeeCount: 4,
|
||||
detailHref: "/acme/hr/locations/l1",
|
||||
};
|
||||
|
||||
it("exposes the employee count and default flag", () => {
|
||||
const vm = buildHrLocationListVM({ rows: [row], canManage: true, createHref: "/x" });
|
||||
expect(vm.data?.rows[0].employeeCount).toBe(4);
|
||||
expect(vm.data?.rows[0].isDefault).toBe(true);
|
||||
expect(vm.data?.canManage).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildHrDocumentListVM", () => {
|
||||
const row: HrDocumentRow = {
|
||||
id: "d1",
|
||||
title: "Contract",
|
||||
documentKind: "contract",
|
||||
kindKey: hrDocumentKindKey("contract"),
|
||||
createdAtIso: new Date("2026-01-01").toISOString(),
|
||||
validUntilIso: null,
|
||||
isExpired: false,
|
||||
readOnly: true,
|
||||
fileHref: "/acme/files/f1",
|
||||
};
|
||||
|
||||
it("maps a kind to its i18n key and flags read-only office uploads", () => {
|
||||
expect(hrDocumentKindKey("contract")).toBe("hr.document.kind.contract");
|
||||
const vm = buildHrDocumentListVM({ rows: [row], canUpload: true, uploadHref: "/x" });
|
||||
expect(vm.data?.rows[0].readOnly).toBe(true);
|
||||
expect(vm.data?.rows[0].kindKey).toBe("hr.document.kind.contract");
|
||||
});
|
||||
});
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* HR employee directory view-model (AK-P17a). Pure function: the loader builds it
|
||||
* once server-side, the UI only renders. No React, no Prisma, no app imports
|
||||
* (DoD A.3). All static texts are i18n keys; resolved names (employee label,
|
||||
* location label) are data passed in by the loader.
|
||||
*
|
||||
* The directory carries ONLY non-sensitive display fields — emergency contacts
|
||||
* and other sensitive data are never part of this list (reveal-on-demand only).
|
||||
*/
|
||||
export interface HrDirectoryRow {
|
||||
readonly userId: string;
|
||||
/** Resolved display name (data), built by the loader. */
|
||||
readonly name: string;
|
||||
readonly email: string;
|
||||
readonly position: string | null;
|
||||
readonly team: string | null;
|
||||
/** Resolved location display name (data) or null. */
|
||||
readonly locationName: string | null;
|
||||
/** Internal detail route (e.g. `/acme/hr/directory/<userId>`). */
|
||||
readonly detailHref: string;
|
||||
}
|
||||
|
||||
export interface HrDirectoryData {
|
||||
readonly rows: readonly HrDirectoryRow[];
|
||||
readonly canManage: boolean;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type HrDirectoryVM = VMState<HrDirectoryData>;
|
||||
|
||||
export interface BuildHrDirectoryVMInput {
|
||||
readonly rows: readonly HrDirectoryRow[];
|
||||
readonly canManage: boolean;
|
||||
}
|
||||
|
||||
export function buildHrDirectoryVM(input: BuildHrDirectoryVMInput): HrDirectoryVM {
|
||||
// Empty stays a `ready` state with a plain-text empty state (DoD 23).
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows: input.rows,
|
||||
canManage: input.canManage,
|
||||
emptyHeadlineKey: "hr.directory.empty.headline",
|
||||
emptyBodyKey: "hr.directory.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* HR "my documents" view-model (AK-P17a). Pure function (DoD A.3). Office-uploaded
|
||||
* documents are flagged read-only so the UI hides edit/delete for them; the
|
||||
* employee can still open/download.
|
||||
*/
|
||||
export type HrDocumentKind = "contract" | "certificate" | "identification" | "qualification" | "other";
|
||||
|
||||
export interface HrDocumentRow {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly documentKind: HrDocumentKind;
|
||||
/** i18n key for the kind label (e.g. `hr.document.kind.contract`). */
|
||||
readonly kindKey: string;
|
||||
readonly createdAtIso: string;
|
||||
readonly validUntilIso: string | null;
|
||||
/** Loader-computed: validUntil is set and in the past. */
|
||||
readonly isExpired: boolean;
|
||||
/** Office-uploaded → read-only for the employee (no edit/delete). */
|
||||
readonly readOnly: boolean;
|
||||
/** Internal auth-proxy route to view/download the underlying file. */
|
||||
readonly fileHref: string;
|
||||
}
|
||||
|
||||
export interface HrDocumentListData {
|
||||
readonly rows: readonly HrDocumentRow[];
|
||||
readonly canUpload: boolean;
|
||||
readonly uploadHref: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type HrDocumentListVM = VMState<HrDocumentListData>;
|
||||
|
||||
export interface BuildHrDocumentListVMInput {
|
||||
readonly rows: readonly HrDocumentRow[];
|
||||
readonly canUpload: boolean;
|
||||
readonly uploadHref: string;
|
||||
}
|
||||
|
||||
export function hrDocumentKindKey(kind: HrDocumentKind): string {
|
||||
return `hr.document.kind.${kind}`;
|
||||
}
|
||||
|
||||
export function buildHrDocumentListVM(input: BuildHrDocumentListVMInput): HrDocumentListVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows: input.rows,
|
||||
canUpload: input.canUpload,
|
||||
uploadHref: input.uploadHref,
|
||||
emptyHeadlineKey: "hr.documents.empty.headline",
|
||||
emptyBodyKey: "hr.documents.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildHrLeaveOwnVM, buildHrLeaveApproverVM, type BuildHrLeaveOwnInput, type HrLeaveApproverInputRow } from "./hr-leave.vm.js";
|
||||
import { buildHrSickOwnVM, buildHrSickOfficeVM, type HrSickLeaveInputRow } from "./hr-sickleave.vm.js";
|
||||
|
||||
// AK-P17b — leave/sick VMs are pure. These tests cover the status-derived action
|
||||
// flags, the kind/status → i18n-key mapping and the approver conflict hint.
|
||||
|
||||
describe("buildHrLeaveOwnVM", () => {
|
||||
const baseRow: BuildHrLeaveOwnInput["rows"][number] = {
|
||||
id: "r1",
|
||||
kind: "vacation",
|
||||
status: "submitted",
|
||||
startDateIso: "2026-07-01",
|
||||
endDateIso: "2026-07-05",
|
||||
note: null,
|
||||
clarificationNote: null,
|
||||
decisionNote: null,
|
||||
detailHref: "/acme/hr/leave/r1",
|
||||
};
|
||||
|
||||
it("maps kind/status to i18n keys and allows withdraw while open", () => {
|
||||
const vm = buildHrLeaveOwnVM({ rows: [baseRow], canCreate: true, newHref: "/x" });
|
||||
const row = vm.data!.rows[0]!;
|
||||
expect(row.kindLabelKey).toBe("hr.leave.kind.vacation");
|
||||
expect(row.statusLabelKey).toBe("hr.leave.status.submitted");
|
||||
expect(row.canWithdraw).toBe(true);
|
||||
expect(row.canReply).toBe(false);
|
||||
});
|
||||
|
||||
it("requires a reply only in clarification, never after a decision", () => {
|
||||
const vm = buildHrLeaveOwnVM({
|
||||
rows: [
|
||||
{ ...baseRow, id: "r2", status: "clarification" },
|
||||
{ ...baseRow, id: "r3", status: "approved" },
|
||||
],
|
||||
canCreate: true,
|
||||
newHref: "/x",
|
||||
});
|
||||
expect(vm.data!.rows[0]!.canReply).toBe(true);
|
||||
expect(vm.data!.rows[0]!.canWithdraw).toBe(true);
|
||||
expect(vm.data!.rows[1]!.canReply).toBe(false);
|
||||
expect(vm.data!.rows[1]!.canWithdraw).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps an empty list in a ready state", () => {
|
||||
const vm = buildHrLeaveOwnVM({ rows: [], canCreate: false, newHref: "/x" });
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.emptyHeadlineKey).toBe("hr.leave.own.empty.headline");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildHrLeaveApproverVM", () => {
|
||||
const row: HrLeaveApproverInputRow = {
|
||||
id: "r1",
|
||||
employeeLabel: "Alex Doe",
|
||||
kind: "vacation",
|
||||
status: "submitted",
|
||||
startDateIso: "2026-07-01",
|
||||
endDateIso: "2026-07-05",
|
||||
note: null,
|
||||
conflictCount: 0,
|
||||
detailHref: "/acme/hr/leave/r1",
|
||||
};
|
||||
|
||||
it("flags an overlapping approved absence as a conflict", () => {
|
||||
const vm = buildHrLeaveApproverVM({ rows: [{ ...row, conflictCount: 2 }] });
|
||||
expect(vm.data!.rows[0]!.hasConflict).toBe(true);
|
||||
expect(vm.data!.rows[0]!.conflictCount).toBe(2);
|
||||
expect(vm.data!.conflictHintKey).toBe("hr.leave.approver.conflictHint");
|
||||
});
|
||||
|
||||
it("reports no conflict when nothing overlaps", () => {
|
||||
const vm = buildHrLeaveApproverVM({ rows: [row] });
|
||||
expect(vm.data!.rows[0]!.hasConflict).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sick-leave VMs", () => {
|
||||
const row: HrSickLeaveInputRow = {
|
||||
id: "s1",
|
||||
status: "reported",
|
||||
startDateIso: "2026-07-01",
|
||||
expectedReturnDateIso: "2026-07-04",
|
||||
returnDateIso: null,
|
||||
note: null,
|
||||
hasCertificate: true,
|
||||
revealHref: "/acme/hr/sick/s1/certificate",
|
||||
};
|
||||
|
||||
it("never exposes the certificate id, only a hasCertificate flag", () => {
|
||||
const vm = buildHrSickOwnVM({ rows: [row], canReport: true });
|
||||
const data = vm.data!.rows[0]! as unknown as Record<string, unknown>;
|
||||
expect(data).not.toHaveProperty("certificateFileId");
|
||||
expect(data).not.toHaveProperty("certificateRefCiphertext");
|
||||
expect(data.hasCertificate).toBe(true);
|
||||
expect(data.statusLabelKey).toBe("hr.sick.status.reported");
|
||||
});
|
||||
|
||||
it("derives close/cancel flags from status", () => {
|
||||
const own = buildHrSickOwnVM({ rows: [row, { ...row, id: "s2", status: "cancelled" }], canReport: true });
|
||||
expect(own.data!.rows[0]!.canClose).toBe(true);
|
||||
expect(own.data!.rows[0]!.canCancel).toBe(true);
|
||||
expect(own.data!.rows[1]!.canClose).toBe(false);
|
||||
expect(own.data!.rows[1]!.canCancel).toBe(false);
|
||||
});
|
||||
|
||||
it("adds the employee label in the office view", () => {
|
||||
const vm = buildHrSickOfficeVM({ rows: [{ ...row, employeeLabel: "Alex Doe" }] });
|
||||
expect(vm.data!.rows[0]!.employeeLabel).toBe("Alex Doe");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* HR leave/vacation view-models (AK-P17b). Pure functions: the loader builds
|
||||
* them once server-side from already-resolved rows (dates as ISO strings,
|
||||
* employee display names resolved by the loader). No React, no Prisma, no app
|
||||
* imports (DoD A.3). All static texts are i18n keys.
|
||||
*/
|
||||
|
||||
export type HrLeaveStatus = "submitted" | "clarification" | "approved" | "rejected" | "withdrawn";
|
||||
export type HrVacationRequestKind = "vacation" | "special_leave" | "unpaid_leave" | "overtime_compensation";
|
||||
|
||||
export interface HrLeaveOwnRow {
|
||||
readonly id: string;
|
||||
readonly kind: HrVacationRequestKind;
|
||||
/** i18n key for the kind label, e.g. `hr.leave.kind.vacation`. */
|
||||
readonly kindLabelKey: string;
|
||||
readonly status: HrLeaveStatus;
|
||||
/** i18n key for the status label, e.g. `hr.leave.status.approved`. */
|
||||
readonly statusLabelKey: string;
|
||||
readonly startDateIso: string;
|
||||
readonly endDateIso: string;
|
||||
readonly note: string | null;
|
||||
readonly clarificationNote: string | null;
|
||||
readonly decisionNote: string | null;
|
||||
readonly detailHref: string;
|
||||
/** Requester may withdraw while still open. */
|
||||
readonly canWithdraw: boolean;
|
||||
/** Requester must reply when the approver asked a question. */
|
||||
readonly canReply: boolean;
|
||||
}
|
||||
|
||||
export interface HrLeaveOwnData {
|
||||
readonly rows: readonly HrLeaveOwnRow[];
|
||||
readonly canCreate: boolean;
|
||||
readonly newHref: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type HrLeaveOwnVM = VMState<HrLeaveOwnData>;
|
||||
|
||||
export interface HrLeaveApproverRow {
|
||||
readonly id: string;
|
||||
readonly employeeLabel: string;
|
||||
readonly kindLabelKey: string;
|
||||
readonly statusLabelKey: string;
|
||||
readonly startDateIso: string;
|
||||
readonly endDateIso: string;
|
||||
readonly note: string | null;
|
||||
/** Number of OTHER approved absences overlapping this window. */
|
||||
readonly conflictCount: number;
|
||||
/** True when there is at least one overlapping approved absence. */
|
||||
readonly hasConflict: boolean;
|
||||
readonly detailHref: string;
|
||||
}
|
||||
|
||||
export interface HrLeaveApproverData {
|
||||
readonly rows: readonly HrLeaveApproverRow[];
|
||||
readonly conflictHintKey: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type HrLeaveApproverVM = VMState<HrLeaveApproverData>;
|
||||
|
||||
const OPEN_STATUSES: ReadonlySet<HrLeaveStatus> = new Set<HrLeaveStatus>(["submitted", "clarification"]);
|
||||
|
||||
export interface BuildHrLeaveOwnInput {
|
||||
readonly rows: ReadonlyArray<Omit<HrLeaveOwnRow, "kindLabelKey" | "statusLabelKey" | "canWithdraw" | "canReply">>;
|
||||
readonly canCreate: boolean;
|
||||
readonly newHref: string;
|
||||
}
|
||||
|
||||
export function buildHrLeaveOwnVM(input: BuildHrLeaveOwnInput): HrLeaveOwnVM {
|
||||
const rows: HrLeaveOwnRow[] = input.rows.map((row) => ({
|
||||
...row,
|
||||
kindLabelKey: `hr.leave.kind.${row.kind}`,
|
||||
statusLabelKey: `hr.leave.status.${row.status}`,
|
||||
canWithdraw: OPEN_STATUSES.has(row.status),
|
||||
canReply: row.status === "clarification",
|
||||
}));
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows,
|
||||
canCreate: input.canCreate,
|
||||
newHref: input.newHref,
|
||||
emptyHeadlineKey: "hr.leave.own.empty.headline",
|
||||
emptyBodyKey: "hr.leave.own.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Raw approver input row: carries `kind`/`status` for label mapping; the
|
||||
* derived `kindLabelKey`/`statusLabelKey`/`hasConflict` are added by the builder. */
|
||||
export interface HrLeaveApproverInputRow extends Omit<HrLeaveApproverRow, "kindLabelKey" | "statusLabelKey" | "hasConflict"> {
|
||||
readonly kind: HrVacationRequestKind;
|
||||
readonly status: HrLeaveStatus;
|
||||
}
|
||||
|
||||
export interface BuildHrLeaveApproverInput {
|
||||
readonly rows: readonly HrLeaveApproverInputRow[];
|
||||
}
|
||||
|
||||
export function buildHrLeaveApproverVM(input: BuildHrLeaveApproverInput): HrLeaveApproverVM {
|
||||
const rows: HrLeaveApproverRow[] = input.rows.map(({ kind, status, ...row }) => ({
|
||||
...row,
|
||||
kindLabelKey: `hr.leave.kind.${kind}`,
|
||||
statusLabelKey: `hr.leave.status.${status}`,
|
||||
hasConflict: row.conflictCount > 0,
|
||||
}));
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows,
|
||||
conflictHintKey: "hr.leave.approver.conflictHint",
|
||||
emptyHeadlineKey: "hr.leave.approver.empty.headline",
|
||||
emptyBodyKey: "hr.leave.approver.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* HR locations view-model (AK-P17a). Pure function (DoD A.3): the loader builds
|
||||
* it once server-side; the UI only renders. Static texts are i18n keys; the
|
||||
* employee count is loader-computed data.
|
||||
*/
|
||||
export interface HrLocationRow {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly addressLine1: string | null;
|
||||
readonly postalCode: string | null;
|
||||
readonly city: string | null;
|
||||
readonly country: string | null;
|
||||
readonly phone: string | null;
|
||||
readonly latitude: number | null;
|
||||
readonly longitude: number | null;
|
||||
readonly description: string | null;
|
||||
readonly isDefault: boolean;
|
||||
/** Loader-computed number of employees at this location. */
|
||||
readonly employeeCount: number;
|
||||
/** Internal detail route (e.g. `/acme/hr/locations/<id>`). */
|
||||
readonly detailHref: string;
|
||||
}
|
||||
|
||||
export interface HrLocationListData {
|
||||
readonly rows: readonly HrLocationRow[];
|
||||
readonly canManage: boolean;
|
||||
readonly createHref: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type HrLocationListVM = VMState<HrLocationListData>;
|
||||
|
||||
export interface BuildHrLocationListVMInput {
|
||||
readonly rows: readonly HrLocationRow[];
|
||||
readonly canManage: boolean;
|
||||
readonly createHref: string;
|
||||
}
|
||||
|
||||
export function buildHrLocationListVM(input: BuildHrLocationListVMInput): HrLocationListVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows: input.rows,
|
||||
canManage: input.canManage,
|
||||
createHref: input.createHref,
|
||||
emptyHeadlineKey: "hr.locations.empty.headline",
|
||||
emptyBodyKey: "hr.locations.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildVaultDetailVM,
|
||||
buildVaultListVM,
|
||||
buildAdminVaultListVM,
|
||||
PASSWORD_SAFE_COPY_AUTO_CLEAR_MS,
|
||||
type EntryRow,
|
||||
} from "./hr-password-safe.vm.js";
|
||||
|
||||
// AK-P17a — the password-safe VMs carry the security-critical "never list a
|
||||
// secret value" contract. These pure-function tests lock that contract in.
|
||||
|
||||
const entry = (overrides: Partial<EntryRow> = {}): EntryRow => ({
|
||||
id: "e1",
|
||||
title: "Router admin",
|
||||
tags: ["network"],
|
||||
url: "https://router.local",
|
||||
hasUsername: true,
|
||||
hasPassword: true,
|
||||
hasNotes: false,
|
||||
revealHref: "/acme/hr/password-safe/v1/reveal",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("buildVaultDetailVM", () => {
|
||||
it("never exposes a secret value field on an entry row", () => {
|
||||
const vm = buildVaultDetailVM({ vaultId: "v1", vaultName: "Ops", accessLevel: "read", rows: [entry()], exportHref: "/x" });
|
||||
expect(vm.status).toBe("ready");
|
||||
const row = vm.data!.rows[0]! as unknown as Record<string, unknown>;
|
||||
// Only presence flags are allowed — never the plaintext.
|
||||
expect(row).not.toHaveProperty("username");
|
||||
expect(row).not.toHaveProperty("password");
|
||||
expect(row).not.toHaveProperty("notes");
|
||||
expect(row.hasUsername).toBe(true);
|
||||
expect(row.hasPassword).toBe(true);
|
||||
});
|
||||
|
||||
it("derives canWrite/canManageAccess from the access level", () => {
|
||||
expect(buildVaultDetailVM({ vaultId: "v1", vaultName: "Ops", accessLevel: "read", rows: [], exportHref: "/x" }).data?.canWrite).toBe(false);
|
||||
expect(buildVaultDetailVM({ vaultId: "v1", vaultName: "Ops", accessLevel: "write", rows: [], exportHref: "/x" }).data?.canWrite).toBe(true);
|
||||
expect(buildVaultDetailVM({ vaultId: "v1", vaultName: "Ops", accessLevel: "read", rows: [], exportHref: "/x" }).data?.canManageAccess).toBe(false);
|
||||
expect(buildVaultDetailVM({ vaultId: "v1", vaultName: "Ops", accessLevel: "admin", rows: [], exportHref: "/x" }).data?.canManageAccess).toBe(true);
|
||||
});
|
||||
|
||||
it("enforces the 30s clipboard auto-clear window", () => {
|
||||
const vm = buildVaultDetailVM({ vaultId: "v1", vaultName: "Ops", accessLevel: "read", rows: [], exportHref: "/x" });
|
||||
expect(vm.data?.copyAutoClearMs).toBe(30_000);
|
||||
expect(PASSWORD_SAFE_COPY_AUTO_CLEAR_MS).toBe(30_000);
|
||||
});
|
||||
|
||||
it("keeps an empty vault in a ready state with a plain-text empty state", () => {
|
||||
const vm = buildVaultDetailVM({ vaultId: "v1", vaultName: "Ops", accessLevel: "read", rows: [], exportHref: "/x" });
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.rows).toHaveLength(0);
|
||||
expect(vm.data?.emptyHeadlineKey).toBe("hr.passwordSafe.entries.empty.headline");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildVaultListVM / buildAdminVaultListVM", () => {
|
||||
it("the admin vault row carries only metadata + counts, never entry contents", () => {
|
||||
const vm = buildAdminVaultListVM({ rows: [{ id: "v1", name: "Ops", entryCount: 3, accessCount: 2, archived: false, detailHref: "/x" }] });
|
||||
const row = vm.data!.rows[0]! as unknown as Record<string, unknown>;
|
||||
expect(row).not.toHaveProperty("entries");
|
||||
expect(row.entryCount).toBe(3);
|
||||
expect(row.accessCount).toBe(2);
|
||||
});
|
||||
|
||||
it("an empty vault list stays ready with the empty-state keys", () => {
|
||||
const vm = buildVaultListVM({ rows: [], canCreate: true, createHref: "/x" });
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.emptyHeadlineKey).toBe("hr.passwordSafe.empty.headline");
|
||||
});
|
||||
});
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* HR password-safe view-models (AK-P17a). Pure functions (DoD A.3).
|
||||
*
|
||||
* CRITICAL: no secret value ever enters a VM. The entry rows carry only titles,
|
||||
* tags, url and BOOLEAN "hasX" flags — never the username/password/notes. The
|
||||
* actual value is fetched on demand by a separate, audited reveal action and is
|
||||
* never persisted in any rendered model.
|
||||
*/
|
||||
export type PasswordSafePermissionLevel = "read" | "write" | "admin";
|
||||
|
||||
export interface VaultRow {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly description: string | null;
|
||||
/** The caller's own access level on this vault. */
|
||||
readonly accessLevel: PasswordSafePermissionLevel;
|
||||
/** Internal route to the vault's entries. */
|
||||
readonly detailHref: string;
|
||||
}
|
||||
|
||||
export interface VaultListData {
|
||||
readonly rows: readonly VaultRow[];
|
||||
readonly canCreate: boolean;
|
||||
readonly createHref: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type VaultListVM = VMState<VaultListData>;
|
||||
|
||||
export function buildVaultListVM(input: { rows: readonly VaultRow[]; canCreate: boolean; createHref: string }): VaultListVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows: input.rows,
|
||||
canCreate: input.canCreate,
|
||||
createHref: input.createHref,
|
||||
emptyHeadlineKey: "hr.passwordSafe.empty.headline",
|
||||
emptyBodyKey: "hr.passwordSafe.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A single entry WITHOUT secret values — only presence flags. */
|
||||
export interface EntryRow {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly tags: readonly string[];
|
||||
readonly url: string | null;
|
||||
readonly hasUsername: boolean;
|
||||
readonly hasPassword: boolean;
|
||||
readonly hasNotes: boolean;
|
||||
/** Endpoint the UI calls to reveal a single field on demand (audited). */
|
||||
readonly revealHref: string;
|
||||
}
|
||||
|
||||
export interface VaultDetailData {
|
||||
readonly vaultId: string;
|
||||
readonly vaultName: string;
|
||||
readonly accessLevel: PasswordSafePermissionLevel;
|
||||
readonly canWrite: boolean;
|
||||
readonly canManageAccess: boolean;
|
||||
readonly rows: readonly EntryRow[];
|
||||
/** 30s clipboard auto-clear window (ms) the UI enforces after a copy (DoD #3). */
|
||||
readonly copyAutoClearMs: number;
|
||||
readonly exportHref: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type VaultDetailVM = VMState<VaultDetailData>;
|
||||
|
||||
export const PASSWORD_SAFE_COPY_AUTO_CLEAR_MS = 30_000;
|
||||
|
||||
export interface BuildVaultDetailVMInput {
|
||||
readonly vaultId: string;
|
||||
readonly vaultName: string;
|
||||
readonly accessLevel: PasswordSafePermissionLevel;
|
||||
readonly rows: readonly EntryRow[];
|
||||
readonly exportHref: string;
|
||||
}
|
||||
|
||||
export function buildVaultDetailVM(input: BuildVaultDetailVMInput): VaultDetailVM {
|
||||
const canWrite = input.accessLevel === "write" || input.accessLevel === "admin";
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
vaultId: input.vaultId,
|
||||
vaultName: input.vaultName,
|
||||
accessLevel: input.accessLevel,
|
||||
canWrite,
|
||||
canManageAccess: input.accessLevel === "admin",
|
||||
rows: input.rows,
|
||||
copyAutoClearMs: PASSWORD_SAFE_COPY_AUTO_CLEAR_MS,
|
||||
exportHref: input.exportHref,
|
||||
emptyHeadlineKey: "hr.passwordSafe.entries.empty.headline",
|
||||
emptyBodyKey: "hr.passwordSafe.entries.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Tenant-wide admin vault list (/admin/hr/password-safe) — metadata only, never
|
||||
* content access. */
|
||||
export interface AdminVaultRow {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly entryCount: number;
|
||||
readonly accessCount: number;
|
||||
readonly archived: boolean;
|
||||
readonly detailHref: string;
|
||||
}
|
||||
|
||||
export interface AdminVaultListData {
|
||||
readonly rows: readonly AdminVaultRow[];
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type AdminVaultListVM = VMState<AdminVaultListData>;
|
||||
|
||||
export function buildAdminVaultListVM(input: { rows: readonly AdminVaultRow[] }): AdminVaultListVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows: input.rows,
|
||||
emptyHeadlineKey: "hr.admin.passwordSafe.empty.headline",
|
||||
emptyBodyKey: "hr.admin.passwordSafe.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
import type { VMState } from "../index.js";
|
||||
import type { PayslipMatchConfidence } from "./payslip-match.js";
|
||||
|
||||
/**
|
||||
* HR payslip view-models (AK-P17b). Pure functions. Own list (PDF open marks
|
||||
* read), admin list, and the bulk-upload match preview (hard/soft/none with a
|
||||
* color-confidence key). No React, no Prisma, no app imports.
|
||||
*/
|
||||
|
||||
export interface HrPayslipRow {
|
||||
readonly id: string;
|
||||
readonly periodLabel: string;
|
||||
readonly periodYear: number;
|
||||
readonly periodMonth: number;
|
||||
readonly isRead: boolean;
|
||||
readonly openHref: string;
|
||||
}
|
||||
|
||||
export interface HrPayslipOwnData {
|
||||
readonly rows: readonly HrPayslipRow[];
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type HrPayslipOwnVM = VMState<HrPayslipOwnData>;
|
||||
|
||||
export interface HrPayslipAdminRow extends HrPayslipRow {
|
||||
readonly employeeLabel: string;
|
||||
readonly uploadedByLabel: string;
|
||||
}
|
||||
|
||||
export interface HrPayslipAdminData {
|
||||
readonly rows: readonly HrPayslipAdminRow[];
|
||||
readonly uploadHref: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type HrPayslipAdminVM = VMState<HrPayslipAdminData>;
|
||||
|
||||
export interface HrPayslipMatchRow {
|
||||
readonly fileId: string;
|
||||
readonly fileName: string;
|
||||
readonly confidence: PayslipMatchConfidence;
|
||||
/** i18n key for the confidence badge, e.g. `hr.payslips.match.confidence.hard`. */
|
||||
readonly confidenceKey: string;
|
||||
/** Color token for the confidence badge (UI maps to its palette). */
|
||||
readonly confidenceTone: "success" | "warning" | "neutral";
|
||||
readonly employeeUserId: string | null;
|
||||
readonly employeeLabel: string | null;
|
||||
readonly candidateUserIds: readonly string[];
|
||||
}
|
||||
|
||||
export interface HrPayslipMatchPreviewData {
|
||||
readonly rows: readonly HrPayslipMatchRow[];
|
||||
readonly hardCount: number;
|
||||
readonly softCount: number;
|
||||
readonly noneCount: number;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type HrPayslipMatchPreviewVM = VMState<HrPayslipMatchPreviewData>;
|
||||
|
||||
function monthLabel(year: number, month: number): string {
|
||||
// Plain numeric period (e.g. "2026-07"); locale month names are the UI's job.
|
||||
return `${year}-${String(month).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function buildHrPayslipOwnVM(input: { rows: ReadonlyArray<Omit<HrPayslipRow, "periodLabel">> }): HrPayslipOwnVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows: input.rows.map((row) => ({ ...row, periodLabel: monthLabel(row.periodYear, row.periodMonth) })),
|
||||
emptyHeadlineKey: "hr.payslips.own.empty.headline",
|
||||
emptyBodyKey: "hr.payslips.own.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function buildHrPayslipAdminVM(input: { rows: ReadonlyArray<Omit<HrPayslipAdminRow, "periodLabel">>; uploadHref: string }): HrPayslipAdminVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows: input.rows.map((row) => ({ ...row, periodLabel: monthLabel(row.periodYear, row.periodMonth) })),
|
||||
uploadHref: input.uploadHref,
|
||||
emptyHeadlineKey: "hr.payslips.admin.empty.headline",
|
||||
emptyBodyKey: "hr.payslips.admin.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const CONFIDENCE_TONE: Record<PayslipMatchConfidence, "success" | "warning" | "neutral"> = { hard: "success", soft: "warning", none: "neutral" };
|
||||
|
||||
export interface HrPayslipMatchInputRow {
|
||||
readonly fileId: string;
|
||||
readonly fileName: string;
|
||||
readonly confidence: PayslipMatchConfidence;
|
||||
readonly employeeUserId: string | null;
|
||||
readonly employeeLabel: string | null;
|
||||
readonly candidateUserIds: readonly string[];
|
||||
}
|
||||
|
||||
export function buildHrPayslipMatchPreviewVM(input: { rows: readonly HrPayslipMatchInputRow[] }): HrPayslipMatchPreviewVM {
|
||||
const rows: HrPayslipMatchRow[] = input.rows.map((row) => ({
|
||||
...row,
|
||||
confidenceKey: `hr.payslips.match.confidence.${row.confidence}`,
|
||||
confidenceTone: CONFIDENCE_TONE[row.confidence],
|
||||
}));
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows,
|
||||
hardCount: rows.filter((r) => r.confidence === "hard").length,
|
||||
softCount: rows.filter((r) => r.confidence === "soft").length,
|
||||
noneCount: rows.filter((r) => r.confidence === "none").length,
|
||||
emptyHeadlineKey: "hr.payslips.match.empty.headline",
|
||||
emptyBodyKey: "hr.payslips.match.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* HR request view-models (AK-P17b). Pure functions. Own list, approver list and
|
||||
* the template picker. Mirrors the leave VM shape (status-derived action flags,
|
||||
* kind/status → i18n keys). No React, no Prisma, no app imports.
|
||||
*/
|
||||
|
||||
export type HrRequestKind = "expense" | "hardware" | "training" | "reference";
|
||||
export type HrRequestStatus = "submitted" | "clarification" | "approved" | "rejected" | "withdrawn";
|
||||
|
||||
const OPEN: ReadonlySet<HrRequestStatus> = new Set<HrRequestStatus>(["submitted", "clarification"]);
|
||||
|
||||
export interface HrRequestRow {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly kind: HrRequestKind;
|
||||
readonly kindLabelKey: string;
|
||||
readonly status: HrRequestStatus;
|
||||
readonly statusLabelKey: string;
|
||||
readonly createdIso: string;
|
||||
readonly detailHref: string;
|
||||
readonly canWithdraw: boolean;
|
||||
}
|
||||
|
||||
export interface HrRequestOwnData {
|
||||
readonly rows: readonly HrRequestRow[];
|
||||
readonly newHref: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type HrRequestOwnVM = VMState<HrRequestOwnData>;
|
||||
|
||||
export interface HrRequestApproverRow {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly employeeLabel: string;
|
||||
readonly kindLabelKey: string;
|
||||
readonly statusLabelKey: string;
|
||||
readonly createdIso: string;
|
||||
readonly detailHref: string;
|
||||
}
|
||||
|
||||
export interface HrRequestApproverData {
|
||||
readonly rows: readonly HrRequestApproverRow[];
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type HrRequestApproverVM = VMState<HrRequestApproverData>;
|
||||
|
||||
export interface HrRequestTemplateRow {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly kind: HrRequestKind;
|
||||
readonly kindLabelKey: string;
|
||||
readonly description: string | null;
|
||||
readonly isActive: boolean;
|
||||
readonly editHref: string;
|
||||
}
|
||||
|
||||
export interface HrRequestTemplateListData {
|
||||
readonly rows: readonly HrRequestTemplateRow[];
|
||||
readonly createHref: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type HrRequestTemplateListVM = VMState<HrRequestTemplateListData>;
|
||||
|
||||
interface OwnInputRow {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly kind: HrRequestKind;
|
||||
readonly status: HrRequestStatus;
|
||||
readonly createdIso: string;
|
||||
readonly detailHref: string;
|
||||
}
|
||||
|
||||
export function buildHrRequestOwnVM(input: { rows: readonly OwnInputRow[]; newHref: string }): HrRequestOwnVM {
|
||||
const rows: HrRequestRow[] = input.rows.map((row) => ({
|
||||
...row,
|
||||
kindLabelKey: `hr.requests.kind.${row.kind}`,
|
||||
statusLabelKey: `hr.requests.status.${row.status}`,
|
||||
canWithdraw: OPEN.has(row.status),
|
||||
}));
|
||||
return { status: "ready", data: { rows, newHref: input.newHref, emptyHeadlineKey: "hr.requests.own.empty.headline", emptyBodyKey: "hr.requests.own.empty.body" } };
|
||||
}
|
||||
|
||||
interface ApproverInputRow {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly employeeLabel: string;
|
||||
readonly kind: HrRequestKind;
|
||||
readonly status: HrRequestStatus;
|
||||
readonly createdIso: string;
|
||||
readonly detailHref: string;
|
||||
}
|
||||
|
||||
export function buildHrRequestApproverVM(input: { rows: readonly ApproverInputRow[] }): HrRequestApproverVM {
|
||||
const rows: HrRequestApproverRow[] = input.rows.map(({ kind, status, ...row }) => ({
|
||||
...row,
|
||||
kindLabelKey: `hr.requests.kind.${kind}`,
|
||||
statusLabelKey: `hr.requests.status.${status}`,
|
||||
}));
|
||||
return { status: "ready", data: { rows, emptyHeadlineKey: "hr.requests.approver.empty.headline", emptyBodyKey: "hr.requests.approver.empty.body" } };
|
||||
}
|
||||
|
||||
interface TemplateInputRow {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly kind: HrRequestKind;
|
||||
readonly description: string | null;
|
||||
readonly isActive: boolean;
|
||||
readonly editHref: string;
|
||||
}
|
||||
|
||||
export function buildHrRequestTemplateListVM(input: { rows: readonly TemplateInputRow[]; createHref: string }): HrRequestTemplateListVM {
|
||||
const rows: HrRequestTemplateRow[] = input.rows.map((row) => ({ ...row, kindLabelKey: `hr.requests.kind.${row.kind}` }));
|
||||
return { status: "ready", data: { rows, createHref: input.createHref, emptyHeadlineKey: "hr.requests.templates.empty.headline", emptyBodyKey: "hr.requests.templates.empty.body" } };
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* HR sick-leave view-models (AK-P17b). Pure functions. The AU certificate is
|
||||
* sensitive: the VM NEVER carries the certificate File id or ciphertext — only a
|
||||
* `hasCertificate` flag and a `revealHref` (a permission-checked + audited POST
|
||||
* action decrypts it on demand). No React, no Prisma, no app imports.
|
||||
*/
|
||||
|
||||
export type HrSickLeaveStatus = "reported" | "closed" | "cancelled";
|
||||
|
||||
export interface HrSickLeaveRow {
|
||||
readonly id: string;
|
||||
readonly status: HrSickLeaveStatus;
|
||||
readonly statusLabelKey: string;
|
||||
readonly startDateIso: string;
|
||||
readonly expectedReturnDateIso: string | null;
|
||||
readonly returnDateIso: string | null;
|
||||
readonly note: string | null;
|
||||
/** True when an (encrypted) certificate is attached; never the id itself. */
|
||||
readonly hasCertificate: boolean;
|
||||
/** POST action that decrypts + opens the certificate (gated + audited). */
|
||||
readonly revealHref: string;
|
||||
readonly canClose: boolean;
|
||||
readonly canCancel: boolean;
|
||||
}
|
||||
|
||||
export interface HrSickLeaveOwnData {
|
||||
readonly rows: readonly HrSickLeaveRow[];
|
||||
readonly canReport: boolean;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type HrSickLeaveOwnVM = VMState<HrSickLeaveOwnData>;
|
||||
|
||||
export interface HrSickLeaveOfficeRow extends HrSickLeaveRow {
|
||||
readonly employeeLabel: string;
|
||||
}
|
||||
|
||||
export interface HrSickLeaveOfficeData {
|
||||
readonly rows: readonly HrSickLeaveOfficeRow[];
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type HrSickLeaveOfficeVM = VMState<HrSickLeaveOfficeData>;
|
||||
|
||||
export interface HrSickLeaveInputRow {
|
||||
readonly id: string;
|
||||
readonly status: HrSickLeaveStatus;
|
||||
readonly startDateIso: string;
|
||||
readonly expectedReturnDateIso: string | null;
|
||||
readonly returnDateIso: string | null;
|
||||
readonly note: string | null;
|
||||
readonly hasCertificate: boolean;
|
||||
readonly revealHref: string;
|
||||
}
|
||||
|
||||
function toRow(row: HrSickLeaveInputRow): HrSickLeaveRow {
|
||||
return {
|
||||
id: row.id,
|
||||
status: row.status,
|
||||
statusLabelKey: `hr.sick.status.${row.status}`,
|
||||
startDateIso: row.startDateIso,
|
||||
expectedReturnDateIso: row.expectedReturnDateIso,
|
||||
returnDateIso: row.returnDateIso,
|
||||
note: row.note,
|
||||
hasCertificate: row.hasCertificate,
|
||||
revealHref: row.revealHref,
|
||||
canClose: row.status === "reported",
|
||||
canCancel: row.status !== "cancelled",
|
||||
};
|
||||
}
|
||||
|
||||
export function buildHrSickOwnVM(input: { rows: readonly HrSickLeaveInputRow[]; canReport: boolean }): HrSickLeaveOwnVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows: input.rows.map(toRow),
|
||||
canReport: input.canReport,
|
||||
emptyHeadlineKey: "hr.sick.own.empty.headline",
|
||||
emptyBodyKey: "hr.sick.own.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function buildHrSickOfficeVM(input: { rows: ReadonlyArray<HrSickLeaveInputRow & { employeeLabel: string }> }): HrSickLeaveOfficeVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows: input.rows.map((row) => ({ ...toRow(row), employeeLabel: row.employeeLabel })),
|
||||
emptyHeadlineKey: "hr.sick.office.empty.headline",
|
||||
emptyBodyKey: "hr.sick.office.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* HR survey view-models (AK-P17b). Pure functions. List, participation (items)
|
||||
* and the gated results view (per-item distribution + average; chart rendering
|
||||
* is the UI's job). No React, no Prisma, no app imports.
|
||||
*/
|
||||
|
||||
export type HrSurveyItemType = "text" | "rating_5" | "nps" | "choice" | "boolean" | "date";
|
||||
export type HrSurveyStatus = "draft" | "open" | "closed";
|
||||
|
||||
export interface HrSurveyListRow {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly status: HrSurveyStatus;
|
||||
readonly statusLabelKey: string;
|
||||
readonly isAnonymous: boolean;
|
||||
readonly hasSubmitted: boolean;
|
||||
readonly canViewResults: boolean;
|
||||
readonly participateHref: string;
|
||||
readonly resultsHref: string;
|
||||
}
|
||||
|
||||
export interface HrSurveyListData {
|
||||
readonly rows: readonly HrSurveyListRow[];
|
||||
readonly canManage: boolean;
|
||||
readonly createHref: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type HrSurveyListVM = VMState<HrSurveyListData>;
|
||||
|
||||
export interface HrSurveyItem {
|
||||
readonly id: string;
|
||||
readonly itemType: HrSurveyItemType;
|
||||
readonly typeLabelKey: string;
|
||||
readonly prompt: string;
|
||||
readonly required: boolean;
|
||||
readonly options: readonly string[];
|
||||
}
|
||||
|
||||
export interface HrSurveyParticipationData {
|
||||
readonly surveyId: string;
|
||||
readonly title: string;
|
||||
readonly description: string | null;
|
||||
readonly isAnonymous: boolean;
|
||||
readonly anonymousHintKey: string;
|
||||
readonly items: readonly HrSurveyItem[];
|
||||
readonly alreadySubmitted: boolean;
|
||||
readonly submittedHintKey: string;
|
||||
}
|
||||
|
||||
export type HrSurveyParticipationVM = VMState<HrSurveyParticipationData>;
|
||||
|
||||
export interface HrSurveyItemResult {
|
||||
readonly itemId: string;
|
||||
readonly prompt: string;
|
||||
readonly itemType: HrSurveyItemType;
|
||||
readonly responseCount: number;
|
||||
readonly distribution: Readonly<Record<string, number>>;
|
||||
readonly average: number | null;
|
||||
readonly textResponses: readonly string[];
|
||||
}
|
||||
|
||||
export interface HrSurveyResultsData {
|
||||
readonly surveyId: string;
|
||||
readonly title: string;
|
||||
readonly submissionCount: number;
|
||||
readonly isAnonymous: boolean;
|
||||
readonly items: readonly HrSurveyItemResult[];
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type HrSurveyResultsVM = VMState<HrSurveyResultsData>;
|
||||
|
||||
interface SurveyListInputRow {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly status: HrSurveyStatus;
|
||||
readonly isAnonymous: boolean;
|
||||
readonly hasSubmitted: boolean;
|
||||
readonly canViewResults: boolean;
|
||||
readonly participateHref: string;
|
||||
readonly resultsHref: string;
|
||||
}
|
||||
|
||||
export function buildHrSurveyListVM(input: { rows: readonly SurveyListInputRow[]; canManage: boolean; createHref: string }): HrSurveyListVM {
|
||||
const rows: HrSurveyListRow[] = input.rows.map((row) => ({ ...row, statusLabelKey: `hr.surveys.status.${row.status}` }));
|
||||
return { status: "ready", data: { rows, canManage: input.canManage, createHref: input.createHref, emptyHeadlineKey: "hr.surveys.empty.headline", emptyBodyKey: "hr.surveys.empty.body" } };
|
||||
}
|
||||
|
||||
export function buildHrSurveyParticipationVM(input: {
|
||||
surveyId: string;
|
||||
title: string;
|
||||
description: string | null;
|
||||
isAnonymous: boolean;
|
||||
items: ReadonlyArray<Omit<HrSurveyItem, "typeLabelKey">>;
|
||||
alreadySubmitted: boolean;
|
||||
}): HrSurveyParticipationVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
surveyId: input.surveyId,
|
||||
title: input.title,
|
||||
description: input.description,
|
||||
isAnonymous: input.isAnonymous,
|
||||
anonymousHintKey: "hr.surveys.participation.anonymousHint",
|
||||
items: input.items.map((item) => ({ ...item, typeLabelKey: `hr.surveys.itemType.${item.itemType}` })),
|
||||
alreadySubmitted: input.alreadySubmitted,
|
||||
submittedHintKey: "hr.surveys.participation.submittedHint",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function buildHrSurveyResultsVM(input: { surveyId: string; title: string; submissionCount: number; isAnonymous: boolean; items: readonly HrSurveyItemResult[] }): HrSurveyResultsVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: { ...input, emptyHeadlineKey: "hr.surveys.results.empty.headline", emptyBodyKey: "hr.surveys.results.empty.body" },
|
||||
};
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
import type { VMState } from "../index.js";
|
||||
import type { HrReminderCadenceKind } from "./reminder-cadence.js";
|
||||
|
||||
/**
|
||||
* HR upload-reminder admin view-model (AK-P17b). Pure function. Lists reminder
|
||||
* definitions with cadence/audience/status labels and dispatch counts. No React,
|
||||
* no Prisma, no app imports. `HrReminderCadenceKind` is reused from
|
||||
* reminder-cadence.js to keep a single source of truth for the cadence union.
|
||||
*/
|
||||
|
||||
export type HrReminderStatus = "active" | "paused" | "completed";
|
||||
|
||||
export interface HrReminderRow {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly cadenceKind: HrReminderCadenceKind;
|
||||
readonly cadenceLabelKey: string;
|
||||
readonly intervalMonths: number | null;
|
||||
readonly documentKindKey: string;
|
||||
readonly audienceLabelKey: string;
|
||||
readonly mandatory: boolean;
|
||||
readonly escalateToManager: boolean;
|
||||
readonly status: HrReminderStatus;
|
||||
readonly statusLabelKey: string;
|
||||
readonly dueIso: string | null;
|
||||
readonly pendingCount: number;
|
||||
readonly detailHref: string;
|
||||
}
|
||||
|
||||
export interface HrReminderListData {
|
||||
readonly rows: readonly HrReminderRow[];
|
||||
readonly createHref: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type HrReminderListVM = VMState<HrReminderListData>;
|
||||
|
||||
export interface HrReminderInputRow {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly cadenceKind: HrReminderCadenceKind;
|
||||
readonly intervalMonths: number | null;
|
||||
readonly documentKind: string;
|
||||
readonly audienceKind: string;
|
||||
readonly mandatory: boolean;
|
||||
readonly escalateToManager: boolean;
|
||||
readonly status: HrReminderStatus;
|
||||
readonly dueIso: string | null;
|
||||
readonly pendingCount: number;
|
||||
readonly detailHref: string;
|
||||
}
|
||||
|
||||
export function buildHrReminderListVM(input: { rows: readonly HrReminderInputRow[]; createHref: string }): HrReminderListVM {
|
||||
const rows: HrReminderRow[] = input.rows.map((row) => ({
|
||||
id: row.id,
|
||||
title: row.title,
|
||||
cadenceKind: row.cadenceKind,
|
||||
cadenceLabelKey: `hr.reminders.cadence.${row.cadenceKind}`,
|
||||
intervalMonths: row.intervalMonths,
|
||||
documentKindKey: `hr.document.kind.${row.documentKind}`,
|
||||
audienceLabelKey: `hr.audience.${row.audienceKind}`,
|
||||
mandatory: row.mandatory,
|
||||
escalateToManager: row.escalateToManager,
|
||||
status: row.status,
|
||||
statusLabelKey: `hr.reminders.status.${row.status}`,
|
||||
dueIso: row.dueIso,
|
||||
pendingCount: row.pendingCount,
|
||||
detailHref: row.detailHref,
|
||||
}));
|
||||
return {
|
||||
status: "ready",
|
||||
data: { rows, createHref: input.createHref, emptyHeadlineKey: "hr.reminders.empty.headline", emptyBodyKey: "hr.reminders.empty.body" },
|
||||
};
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { matchPayslipFile, type PayslipMatchEmployee } from "./payslip-match.js";
|
||||
|
||||
// AK-P17b — payslip auto-match is pure. Covers hard (personal number), soft
|
||||
// (name), ambiguous and no-match classifications.
|
||||
|
||||
const employees: PayslipMatchEmployee[] = [
|
||||
{ userId: "u1", personalNumber: "0042", name: "Alex Doe" },
|
||||
{ userId: "u2", personalNumber: "0043", name: "Sam Roe" },
|
||||
{ userId: "u3", personalNumber: null, name: "Alex Smith" },
|
||||
];
|
||||
|
||||
describe("matchPayslipFile", () => {
|
||||
it("hard-matches on a unique personal number token", () => {
|
||||
const r = matchPayslipFile("lohn_2026_07_0042.pdf", employees);
|
||||
expect(r.confidence).toBe("hard");
|
||||
expect(r.employeeUserId).toBe("u1");
|
||||
});
|
||||
|
||||
it("normalises a prefixed personal number (PN-0043 ⇒ 0043)", () => {
|
||||
const r = matchPayslipFile("payslip-PN-0043-juli.pdf", [{ userId: "u2", personalNumber: "PN-0043", name: "Sam Roe" }]);
|
||||
expect(r.confidence).toBe("hard");
|
||||
expect(r.employeeUserId).toBe("u2");
|
||||
});
|
||||
|
||||
it("soft-matches on full name when no personal number hits", () => {
|
||||
const r = matchPayslipFile("Sam_Roe_07_2026.pdf", employees);
|
||||
expect(r.confidence).toBe("soft");
|
||||
expect(r.employeeUserId).toBe("u2");
|
||||
});
|
||||
|
||||
it("downgrades to ambiguous soft when a partial name matches several", () => {
|
||||
const r = matchPayslipFile("Alex_2026.pdf", [
|
||||
{ userId: "u1", personalNumber: "0042", name: "Alex" },
|
||||
{ userId: "u3", personalNumber: null, name: "Alex" },
|
||||
]);
|
||||
expect(r.confidence).toBe("soft");
|
||||
expect(r.employeeUserId).toBeNull();
|
||||
expect(r.candidateUserIds).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("returns none when nothing matches", () => {
|
||||
const r = matchPayslipFile("random_document.pdf", employees);
|
||||
expect(r.confidence).toBe("none");
|
||||
expect(r.employeeUserId).toBeNull();
|
||||
expect(r.candidateUserIds).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Payslip bulk-upload auto-match (AK-P17b). Pure function — no DB, no IO — so it
|
||||
* is unit-testable in isolation. Given an uploaded file name and the tenant's
|
||||
* employees, it classifies the match confidence:
|
||||
* - `hard`: the file name contains the employee's personal number as a token.
|
||||
* - `soft`: the file name contains the employee's (last) name but no personal
|
||||
* number hit, OR more than one employee matches by name.
|
||||
* - `none`: nothing matched.
|
||||
* The admin confirms/overrides before any payslip is created. This module maps a
|
||||
* file name to a single best classification plus the ambiguous candidate set.
|
||||
*/
|
||||
|
||||
export type PayslipMatchConfidence = "hard" | "soft" | "none";
|
||||
|
||||
export interface PayslipMatchEmployee {
|
||||
readonly userId: string;
|
||||
readonly personalNumber: string | null;
|
||||
/** Display name (e.g. "Alex Doe"); matched token-wise, case-insensitive. */
|
||||
readonly name: string;
|
||||
}
|
||||
|
||||
export interface PayslipMatchResult {
|
||||
readonly fileName: string;
|
||||
readonly confidence: PayslipMatchConfidence;
|
||||
/** The single matched employee when unambiguous; null for none/ambiguous. */
|
||||
readonly employeeUserId: string | null;
|
||||
/** All plausible candidates (length > 1 ⇒ ambiguous ⇒ soft). */
|
||||
readonly candidateUserIds: readonly string[];
|
||||
}
|
||||
|
||||
/** Lowercased alphanumeric tokens of length ≥ 2 (drops the file extension). */
|
||||
function tokenize(value: string): string[] {
|
||||
const withoutExt = value.replace(/\.[a-z0-9]{1,5}$/i, "");
|
||||
return withoutExt
|
||||
.toLowerCase()
|
||||
.split(/[^a-z0-9]+/i)
|
||||
.filter((token) => token.length >= 2);
|
||||
}
|
||||
|
||||
/** Normalised digits of a personal number (so "PN-0042" matches "0042"). */
|
||||
function digitsOf(value: string): string {
|
||||
return value.replace(/\D+/g, "");
|
||||
}
|
||||
|
||||
export function matchPayslipFile(fileName: string, employees: readonly PayslipMatchEmployee[]): PayslipMatchResult {
|
||||
const tokens = tokenize(fileName);
|
||||
const tokenSet = new Set(tokens);
|
||||
const haystackDigits = digitsOf(fileName);
|
||||
|
||||
// 1. Hard match on personal number (unique digit token in the file name).
|
||||
const hardHits = employees.filter((employee) => {
|
||||
const pn = employee.personalNumber ? digitsOf(employee.personalNumber) : "";
|
||||
return pn.length >= 2 && haystackDigits.includes(pn);
|
||||
});
|
||||
if (hardHits.length === 1) {
|
||||
return { fileName, confidence: "hard", employeeUserId: hardHits[0]!.userId, candidateUserIds: [hardHits[0]!.userId] };
|
||||
}
|
||||
if (hardHits.length > 1) {
|
||||
// Multiple personal-number hits ⇒ ambiguous, downgrade to soft.
|
||||
return { fileName, confidence: "soft", employeeUserId: null, candidateUserIds: hardHits.map((e) => e.userId) };
|
||||
}
|
||||
|
||||
// 2. Soft match on name tokens (every name token present in the file name).
|
||||
const nameHits = employees.filter((employee) => {
|
||||
const nameTokens = tokenize(employee.name);
|
||||
return nameTokens.length > 0 && nameTokens.every((token) => tokenSet.has(token));
|
||||
});
|
||||
if (nameHits.length === 1) {
|
||||
return { fileName, confidence: "soft", employeeUserId: nameHits[0]!.userId, candidateUserIds: [nameHits[0]!.userId] };
|
||||
}
|
||||
if (nameHits.length > 1) {
|
||||
return { fileName, confidence: "soft", employeeUserId: null, candidateUserIds: nameHits.map((e) => e.userId) };
|
||||
}
|
||||
|
||||
return { fileName, confidence: "none", employeeUserId: null, candidateUserIds: [] };
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { computeNextDue } from "./reminder-cadence.js";
|
||||
|
||||
// AK-P17b — cadence math is pure. Covers every cadence kind.
|
||||
|
||||
describe("computeNextDue", () => {
|
||||
const from = new Date("2026-01-15T00:00:00.000Z");
|
||||
|
||||
it("returns null for a one-off reminder", () => {
|
||||
expect(computeNextDue({ cadenceKind: "once", from })).toBeNull();
|
||||
});
|
||||
|
||||
it("advances a yearly reminder by 12 months", () => {
|
||||
const next = computeNextDue({ cadenceKind: "yearly", from })!;
|
||||
expect(next.getFullYear()).toBe(2027);
|
||||
expect(next.getMonth()).toBe(0);
|
||||
});
|
||||
|
||||
it("advances every_n_months by the interval (default 1)", () => {
|
||||
expect(computeNextDue({ cadenceKind: "every_n_months", intervalMonths: 3, from })!.getMonth()).toBe(3);
|
||||
expect(computeNextDue({ cadenceKind: "every_n_months", intervalMonths: null, from })!.getMonth()).toBe(1);
|
||||
});
|
||||
|
||||
it("uses the document expiry for on_expiry, null when absent", () => {
|
||||
const expiry = new Date("2026-06-30T00:00:00.000Z");
|
||||
expect(computeNextDue({ cadenceKind: "on_expiry", from, validUntil: expiry })).toEqual(expiry);
|
||||
expect(computeNextDue({ cadenceKind: "on_expiry", from, validUntil: null })).toBeNull();
|
||||
});
|
||||
});
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Upload-reminder cadence math (AK-P17b). Pure function — no DB, no IO — so it
|
||||
* is unit-testable. Given a cadence and the current due date, it computes the
|
||||
* NEXT due date (or null when the cadence does not repeat).
|
||||
*/
|
||||
|
||||
export type HrReminderCadenceKind = "once" | "yearly" | "every_n_months" | "on_expiry";
|
||||
|
||||
export interface ComputeNextDueInput {
|
||||
readonly cadenceKind: HrReminderCadenceKind;
|
||||
/** Months between dispatches for `every_n_months` (defaults to 1 if absent). */
|
||||
readonly intervalMonths?: number | null;
|
||||
/** The current due date the next one is derived from. */
|
||||
readonly from: Date;
|
||||
/** Document expiry for `on_expiry`; the next due equals this date. */
|
||||
readonly validUntil?: Date | null;
|
||||
}
|
||||
|
||||
/** Add `months` calendar months to `date` (clamps to month length). */
|
||||
function addMonths(date: Date, months: number): Date {
|
||||
const result = new Date(date.getTime());
|
||||
const targetMonth = result.getMonth() + months;
|
||||
result.setMonth(targetMonth);
|
||||
return result;
|
||||
}
|
||||
|
||||
export function computeNextDue(input: ComputeNextDueInput): Date | null {
|
||||
switch (input.cadenceKind) {
|
||||
case "once":
|
||||
return null;
|
||||
case "yearly":
|
||||
return addMonths(input.from, 12);
|
||||
case "every_n_months": {
|
||||
const interval = input.intervalMonths && input.intervalMonths > 0 ? Math.floor(input.intervalMonths) : 1;
|
||||
return addMonths(input.from, interval);
|
||||
}
|
||||
case "on_expiry":
|
||||
return input.validUntil ?? null;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { assertI18nLabel } from "./index.js";
|
||||
|
||||
// Targets the descriptionKey validation branch of assertI18nLabel (index.ts:96-98),
|
||||
// which the existing index.test.ts never exercises (it only passes a labelKey).
|
||||
describe("assertI18nLabel descriptionKey validation", () => {
|
||||
test("accepts a label whose optional descriptionKey is a valid i18n key", () => {
|
||||
const label = { labelKey: "shell.nav.home", descriptionKey: "shell.nav.home.desc" };
|
||||
expect(assertI18nLabel(label)).toBe(label);
|
||||
});
|
||||
|
||||
test("rejects a non-i18n descriptionKey even when the labelKey is valid", () => {
|
||||
expect(() => assertI18nLabel({ labelKey: "shell.nav.home", descriptionKey: "Plain Text" })).toThrow(
|
||||
/descriptions must use i18n keys/i,
|
||||
);
|
||||
});
|
||||
|
||||
test("error message names the offending descriptionKey", () => {
|
||||
expect(() => assertI18nLabel({ labelKey: "a.b", descriptionKey: "BAD_KEY" })).toThrow(/BAD_KEY/);
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, test } from "vitest";
|
||||
|
||||
import { assertI18nLabel, empty, ready, type ActionCallbacks, type SidebarRegistryItem, type VMState } from "./index.js";
|
||||
|
||||
describe("@toolctrl/view-models", () => {
|
||||
describe("@hivegrid/view-models", () => {
|
||||
test("exports serializable VM state helpers", () => {
|
||||
expect(ready({ id: "1" })).toEqual({ status: "ready", data: { id: "1" } } satisfies VMState<{ id: string }>);
|
||||
expect(empty()).toEqual({ status: "empty" });
|
||||
|
||||
@@ -108,3 +108,60 @@ export * from "./files/file-detail.vm.js";
|
||||
export * from "./files/file-upload.vm.js";
|
||||
export * from "./tasks/task-list.vm.js";
|
||||
export * from "./tasks/task-detail.vm.js";
|
||||
export * from "./leads/lead-list.vm.js";
|
||||
export * from "./crm/kontakt-list.vm.js";
|
||||
export * from "./crm/kontakt-detail.vm.js";
|
||||
export * from "./crm/activity-stream.vm.js";
|
||||
export * from "./crm/custom-field-admin.vm.js";
|
||||
export * from "./crm/tag-admin.vm.js";
|
||||
export * from "./crm/duplicate.vm.js";
|
||||
export * from "./crm/kontakt-csv.js";
|
||||
export * from "./hr/hr-directory.vm.js";
|
||||
export * from "./hr/hr-location.vm.js";
|
||||
export * from "./hr/hr-document.vm.js";
|
||||
export * from "./hr/hr-password-safe.vm.js";
|
||||
export * from "./hr/hr-leave.vm.js";
|
||||
export * from "./hr/hr-sickleave.vm.js";
|
||||
export * from "./hr/payslip-match.js";
|
||||
export * from "./hr/reminder-cadence.js";
|
||||
export * from "./hr/hr-announcement.vm.js";
|
||||
export * from "./hr/hr-payslip.vm.js";
|
||||
export * from "./hr/hr-upload-reminder.vm.js";
|
||||
export * from "./hr/hr-request.vm.js";
|
||||
export * from "./hr/hr-survey.vm.js";
|
||||
export * from "./audit/audit-list.vm.js";
|
||||
export * from "./audit/audit-export.vm.js";
|
||||
export * from "./notifications/notification-center.vm.js";
|
||||
export * from "./notifications/notification-settings.vm.js";
|
||||
export * from "./admin/tenant-note-list.vm.js";
|
||||
export * from "./admin/subscription-connectors.vm.js";
|
||||
export * from "./admin/billing-admin.vm.js";
|
||||
export * from "./admin/queue-monitor.vm.js";
|
||||
export * from "./admin/support-conversation.vm.js";
|
||||
export * from "./apps-engine/integration-catalog.vm.js";
|
||||
export * from "./apps-engine/connection-detail.vm.js";
|
||||
export * from "./apps-engine/sync-history.vm.js";
|
||||
export * from "./apps-engine/sync-run-detail.vm.js";
|
||||
export * from "./email/sending-domain.vm.js";
|
||||
export * from "./email/presend-checklist.vm.js";
|
||||
export * from "./email/campaign-detail.vm.js";
|
||||
export * from "./email/campaign-list.vm.js";
|
||||
export * from "./email/segment.vm.js";
|
||||
// AK-P16a · calendar sync view-models.
|
||||
export * from "./calendar/connection-list.vm.js";
|
||||
export * from "./calendar/connection-detail.vm.js";
|
||||
export * from "./calendar/calendar-view.vm.js";
|
||||
// AK-P16b · booking view-models.
|
||||
export * from "./booking/booking-list.vm.js";
|
||||
// AK-P16d · project signature view-models.
|
||||
export * from "./signature/project-signature.vm.js";
|
||||
// VA-P23 · email-inbox (Postfach-Sync) view-models.
|
||||
export * from "./email-inbox/mailbox-list.vm.js";
|
||||
export * from "./email-inbox/inbox-list.vm.js";
|
||||
export * from "./email-inbox/message-detail.vm.js";
|
||||
export * from "./email-inbox/compose.vm.js";
|
||||
// R-P2b · members/roles/groups admin view-models (D-P2 Admin RBAC).
|
||||
export * from "./users/members-list.vm.js";
|
||||
export * from "./users/roles-list.vm.js";
|
||||
export * from "./users/role-editor.vm.js";
|
||||
export * from "./users/groups-detail.vm.js";
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildLeadDisplayName, buildLeadListVM, leadFreigabeLabelKey, leadQuelleLabelKey, leadStatusLabelKey } from "./lead-list.vm.js";
|
||||
|
||||
describe("lead list view-model", () => {
|
||||
it("derives i18n keys and display names", () => {
|
||||
expect(leadQuelleLabelKey("form")).toBe("leads.quelle.form");
|
||||
expect(leadStatusLabelKey("qualified")).toBe("leads.status.qualified");
|
||||
expect(leadFreigabeLabelKey("ja")).toBe("leads.freigabe.ja");
|
||||
expect(buildLeadDisplayName({ vorname: "Anna", nachname: "Muster", email: null, telefon: null, quelle: "manual" })).toBe("Anna Muster");
|
||||
expect(buildLeadDisplayName({ vorname: null, nachname: null, email: "a@example.test", telefon: null, quelle: "form" })).toBe("a@example.test");
|
||||
});
|
||||
|
||||
it("maps rows, markers, permissions and cursor state", () => {
|
||||
const vm = buildLeadListVM({
|
||||
tenantSlug: "acme",
|
||||
createHref: "/acme/leads/new",
|
||||
statisticsHref: "/acme/leads/statistics",
|
||||
userLabels: new Map([["u1", "Raffael"]]),
|
||||
duplicateLeadIds: new Set(["l1"]),
|
||||
total: 2,
|
||||
nextCursor: "l2",
|
||||
perms: { canWrite: true, canDelete: false, canReadAll: true },
|
||||
rows: [
|
||||
{
|
||||
id: "l1",
|
||||
quelle: "form",
|
||||
status: "new",
|
||||
weiterverarbeitungFreigabe: "unklar",
|
||||
vorname: "Anna",
|
||||
nachname: "Muster",
|
||||
email: "anna@example.test",
|
||||
telefon: null,
|
||||
message: "Bitte melden.",
|
||||
zustaendigerUserId: "u1",
|
||||
spamScore: 55,
|
||||
spamReason: "fast_submit",
|
||||
isQuarantined: true,
|
||||
konvertiertProjektId: null,
|
||||
verknuepfterKontaktId: null,
|
||||
createdAt: new Date("2026-07-01T08:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows[0]).toMatchObject({
|
||||
displayName: "Anna Muster",
|
||||
quelleLabelKey: "leads.quelle.form",
|
||||
statusLabelKey: "leads.status.new",
|
||||
zustaendigerLabel: "Raffael",
|
||||
markers: ["duplicate", "spam"],
|
||||
detailHref: "/acme/leads/l1",
|
||||
createdAtIso: "2026-07-01T08:00:00.000Z",
|
||||
});
|
||||
expect(vm.data.nextCursor).toBe("l2");
|
||||
expect(vm.data.canReadAll).toBe(true);
|
||||
});
|
||||
});
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
export type LeadQuelle = "form" | "email" | "aircall" | "manual" | "custom";
|
||||
export type LeadStatus = "new" | "qualified" | "converted" | "lost" | "spam";
|
||||
export type LeadWeiterverarbeitungFreigabe = "ja" | "nein" | "unklar";
|
||||
|
||||
export interface LeadListRowSource {
|
||||
readonly id: string;
|
||||
readonly quelle: LeadQuelle;
|
||||
readonly status: LeadStatus;
|
||||
readonly weiterverarbeitungFreigabe: LeadWeiterverarbeitungFreigabe;
|
||||
readonly vorname: string | null;
|
||||
readonly nachname: string | null;
|
||||
readonly email: string | null;
|
||||
readonly telefon: string | null;
|
||||
readonly message: string | null;
|
||||
readonly zustaendigerUserId: string | null;
|
||||
readonly spamScore: number;
|
||||
readonly spamReason: string | null;
|
||||
readonly isQuarantined: boolean;
|
||||
readonly konvertiertProjektId: string | null;
|
||||
readonly verknuepfterKontaktId: string | null;
|
||||
readonly createdAt: Date;
|
||||
}
|
||||
|
||||
export interface LeadListRow {
|
||||
readonly id: string;
|
||||
readonly displayName: string;
|
||||
readonly preview: string | null;
|
||||
readonly quelle: LeadQuelle;
|
||||
readonly quelleLabelKey: string;
|
||||
readonly status: LeadStatus;
|
||||
readonly statusLabelKey: string;
|
||||
readonly weiterverarbeitungFreigabe: LeadWeiterverarbeitungFreigabe;
|
||||
readonly freigabeLabelKey: string;
|
||||
readonly email: string | null;
|
||||
readonly telefon: string | null;
|
||||
readonly zustaendigerLabel: string | null;
|
||||
readonly spamScore: number;
|
||||
readonly markers: readonly ("duplicate" | "spam" | "converted")[];
|
||||
readonly detailHref: string;
|
||||
readonly createdAtIso: string;
|
||||
}
|
||||
|
||||
export interface LeadListData {
|
||||
readonly rows: readonly LeadListRow[];
|
||||
readonly total: number;
|
||||
readonly nextCursor: string | null;
|
||||
readonly canWrite: boolean;
|
||||
readonly canDelete: boolean;
|
||||
readonly canReadAll: boolean;
|
||||
readonly createHref: string;
|
||||
readonly statisticsHref: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type LeadListVM = VMState<LeadListData>;
|
||||
|
||||
export interface BuildLeadListVMInput {
|
||||
readonly rows: readonly LeadListRowSource[];
|
||||
readonly userLabels: ReadonlyMap<string, string>;
|
||||
readonly duplicateLeadIds?: ReadonlySet<string>;
|
||||
readonly total: number;
|
||||
readonly nextCursor: string | null;
|
||||
readonly perms: { readonly canWrite: boolean; readonly canDelete: boolean; readonly canReadAll: boolean };
|
||||
readonly tenantSlug: string;
|
||||
readonly createHref: string;
|
||||
readonly statisticsHref: string;
|
||||
}
|
||||
|
||||
export function leadQuelleLabelKey(quelle: LeadQuelle): string {
|
||||
return `leads.quelle.${quelle}`;
|
||||
}
|
||||
|
||||
export function leadStatusLabelKey(status: LeadStatus): string {
|
||||
return `leads.status.${status}`;
|
||||
}
|
||||
|
||||
export function leadFreigabeLabelKey(value: LeadWeiterverarbeitungFreigabe): string {
|
||||
return `leads.freigabe.${value}`;
|
||||
}
|
||||
|
||||
export function buildLeadDisplayName(row: Pick<LeadListRowSource, "vorname" | "nachname" | "email" | "telefon" | "quelle">): string {
|
||||
const name = `${row.vorname ?? ""} ${row.nachname ?? ""}`.trim();
|
||||
return name || row.email || row.telefon || row.quelle;
|
||||
}
|
||||
|
||||
export function buildLeadListVM(input: BuildLeadListVMInput): LeadListVM {
|
||||
const rows = input.rows.map((row) => {
|
||||
const markers: ("duplicate" | "spam" | "converted")[] = [];
|
||||
if (input.duplicateLeadIds?.has(row.id)) markers.push("duplicate");
|
||||
if (row.isQuarantined || row.status === "spam" || row.spamScore >= 50) markers.push("spam");
|
||||
if (row.konvertiertProjektId || row.status === "converted") markers.push("converted");
|
||||
return {
|
||||
id: row.id,
|
||||
displayName: buildLeadDisplayName(row),
|
||||
preview: row.message ? row.message.slice(0, 80) : null,
|
||||
quelle: row.quelle,
|
||||
quelleLabelKey: leadQuelleLabelKey(row.quelle),
|
||||
status: row.status,
|
||||
statusLabelKey: leadStatusLabelKey(row.status),
|
||||
weiterverarbeitungFreigabe: row.weiterverarbeitungFreigabe,
|
||||
freigabeLabelKey: leadFreigabeLabelKey(row.weiterverarbeitungFreigabe),
|
||||
email: row.email,
|
||||
telefon: row.telefon,
|
||||
zustaendigerLabel: row.zustaendigerUserId ? (input.userLabels.get(row.zustaendigerUserId) ?? null) : null,
|
||||
spamScore: row.spamScore,
|
||||
markers,
|
||||
detailHref: `/${input.tenantSlug}/leads/${row.id}`,
|
||||
createdAtIso: row.createdAt.toISOString(),
|
||||
} satisfies LeadListRow;
|
||||
});
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows,
|
||||
total: input.total,
|
||||
nextCursor: input.nextCursor,
|
||||
canWrite: input.perms.canWrite,
|
||||
canDelete: input.perms.canDelete,
|
||||
canReadAll: input.perms.canReadAll,
|
||||
createHref: input.createHref,
|
||||
statisticsHref: input.statisticsHref,
|
||||
emptyHeadlineKey: "leads.list.empty.headline",
|
||||
emptyBodyKey: "leads.list.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildNotificationCenterVM,
|
||||
deriveNotificationDeeplink,
|
||||
mergeNotificationCenterItems,
|
||||
toNotificationCenterItemVM,
|
||||
toNotificationCenterModel,
|
||||
NOTIFICATION_CENTER_MAX_ITEMS,
|
||||
type NotificationCenterItemInput,
|
||||
} from "./notification-center.vm.js";
|
||||
|
||||
function makeInput(overrides: Partial<NotificationCenterItemInput> = {}): NotificationCenterItemInput {
|
||||
return {
|
||||
id: "delivery_1",
|
||||
messageKey: "notifications.messages.demo",
|
||||
category: "billing",
|
||||
channel: "IN_APP",
|
||||
status: "SENT",
|
||||
attemptsMade: 1,
|
||||
createdAtIso: "2026-07-01T10:00:00.000Z",
|
||||
updatedAtIso: "2026-07-01T11:00:00.000Z",
|
||||
sentAtIso: "2026-07-01T10:30:00.000Z",
|
||||
readAtIso: null,
|
||||
lastError: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("toNotificationCenterItemVM", () => {
|
||||
it("derives keys, read state and sort timestamp", () => {
|
||||
const item = toNotificationCenterItemVM(makeInput());
|
||||
expect(item.categoryKey).toBe("notifications.center.categories.billing");
|
||||
expect(item.channelKey).toBe("notifications.center.channels.in_app");
|
||||
expect(item.statusKey).toBe("notifications.center.statuses.sent");
|
||||
expect(item.isRead).toBe(false);
|
||||
expect(item.sortTimestamp).toBe(Date.parse("2026-07-01T11:00:00.000Z"));
|
||||
expect(item.bounceKey).toBeNull();
|
||||
expect(item.deeplinkHref).toBeNull();
|
||||
});
|
||||
|
||||
it("marks READ items and classifies bounce errors into M002 keys", () => {
|
||||
const read = toNotificationCenterItemVM(makeInput({ status: "read", readAtIso: "2026-07-01T12:00:00.000Z" }));
|
||||
expect(read.isRead).toBe(true);
|
||||
|
||||
const bounced = toNotificationCenterItemVM(
|
||||
makeInput({ status: "FAILED", lastError: "550 5.1.1 unknown recipient mailbox" })
|
||||
);
|
||||
expect(bounced.bounceKey).toBe("notifications.center.bounce.invalidRecipient");
|
||||
expect(bounced.lastErrorRedacted).toContain("550");
|
||||
});
|
||||
|
||||
it("redacts secret-looking fragments in the display error", () => {
|
||||
const item = toNotificationCenterItemVM(
|
||||
makeInput({ status: "FAILED", lastError: "provider throttled api_key=sk_live_abcdef123456 too many requests" })
|
||||
);
|
||||
expect(item.lastErrorRedacted).not.toContain("sk_live_abcdef123456");
|
||||
expect(item.bounceKey).toBe("notifications.center.bounce.rateLimited");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveNotificationDeeplink", () => {
|
||||
it("accepts app-relative paths only", () => {
|
||||
expect(deriveNotificationDeeplink({ deeplink: "/app/acme/tasks/task_1" })).toBe("/app/acme/tasks/task_1");
|
||||
expect(deriveNotificationDeeplink({ deeplink: "/app/acme/projects?tab=open" })).toBe("/app/acme/projects?tab=open");
|
||||
});
|
||||
|
||||
it("rejects unsafe or malformed candidates", () => {
|
||||
expect(deriveNotificationDeeplink(null)).toBeNull();
|
||||
expect(deriveNotificationDeeplink({})).toBeNull();
|
||||
expect(deriveNotificationDeeplink({ deeplink: "https://evil.example" })).toBeNull();
|
||||
expect(deriveNotificationDeeplink({ deeplink: "//evil.example" })).toBeNull();
|
||||
expect(deriveNotificationDeeplink({ deeplink: "javascript:alert(1)" })).toBeNull();
|
||||
expect(deriveNotificationDeeplink({ deeplink: "/app\\evil" })).toBeNull();
|
||||
expect(deriveNotificationDeeplink({ deeplink: "/app/with space" })).toBeNull();
|
||||
expect(deriveNotificationDeeplink({ deeplink: "/" })).toBeNull();
|
||||
expect(deriveNotificationDeeplink({ deeplink: 42 })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("mergeNotificationCenterItems", () => {
|
||||
it("dedupes by id, keeps newest-first order and caps the list", () => {
|
||||
const older = toNotificationCenterItemVM(makeInput({ id: "a", updatedAtIso: "2026-07-01T09:00:00.000Z" }));
|
||||
const newer = toNotificationCenterItemVM(makeInput({ id: "b", updatedAtIso: "2026-07-01T12:00:00.000Z" }));
|
||||
const updatedA = toNotificationCenterItemVM(
|
||||
makeInput({ id: "a", status: "READ", updatedAtIso: "2026-07-01T13:00:00.000Z" })
|
||||
);
|
||||
|
||||
const merged = mergeNotificationCenterItems([older, newer], [updatedA]);
|
||||
expect(merged.map((item) => item.id)).toEqual(["a", "b"]);
|
||||
expect(merged[0]?.isRead).toBe(true);
|
||||
|
||||
const many = Array.from({ length: NOTIFICATION_CENTER_MAX_ITEMS + 10 }, (_, index) =>
|
||||
toNotificationCenterItemVM(makeInput({ id: `bulk_${index}` }))
|
||||
);
|
||||
expect(mergeNotificationCenterItems([], many)).toHaveLength(NOTIFICATION_CENTER_MAX_ITEMS);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildNotificationCenterVM", () => {
|
||||
it("builds a ready VM with counts and deeplinks", () => {
|
||||
const vm = buildNotificationCenterVM({
|
||||
items: [
|
||||
makeInput({ id: "a", payloadMetadata: { deeplink: "/app/acme/tasks/task_1" } }),
|
||||
makeInput({ id: "b", status: "READ" }),
|
||||
],
|
||||
streamAvailable: true,
|
||||
});
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.totalCount).toBe(2);
|
||||
expect(vm.data?.unreadCount).toBe(1);
|
||||
expect(vm.data?.items.find((item) => item.id === "a")?.deeplinkHref).toBe("/app/acme/tasks/task_1");
|
||||
expect(vm.data?.streamAvailable).toBe(true);
|
||||
});
|
||||
|
||||
it("maps into the hot-swap component model with i18n keys only", () => {
|
||||
const vm = buildNotificationCenterVM({ items: [makeInput()], streamAvailable: false });
|
||||
if (vm.status !== "ready") throw new Error("expected ready VM");
|
||||
const model = toNotificationCenterModel(vm.data);
|
||||
expect(model.titleKey).toBe("notifications.center.title");
|
||||
expect(model.items[0]).toMatchObject({
|
||||
id: "delivery_1",
|
||||
statusKey: "notifications.center.statuses.sent",
|
||||
categoryKey: "notifications.center.categories.billing",
|
||||
isRead: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* Notification-Center view-model (AK-P3 DoD 4). Pure functions: the loader
|
||||
* builds the VM once server-side; the SSE hook re-uses the same item mapper
|
||||
* client-side so live updates and the initial payload share one shape.
|
||||
* No React, no Prisma, no app imports (DoD A.3). All labels are i18n keys.
|
||||
*/
|
||||
|
||||
/** Raw delivery record as the loader/stream provides it (framework-free). */
|
||||
export interface NotificationCenterItemInput {
|
||||
readonly id: string;
|
||||
readonly messageKey: string;
|
||||
readonly category: string;
|
||||
readonly channel: string;
|
||||
readonly status: string;
|
||||
readonly attemptsMade: number;
|
||||
readonly createdAtIso?: string | null;
|
||||
readonly updatedAtIso?: string | null;
|
||||
readonly sentAtIso?: string | null;
|
||||
readonly readAtIso?: string | null;
|
||||
/** Already provider-redacted error text (loader runs the DB redactor). */
|
||||
readonly lastError?: string | null;
|
||||
/** `NotificationDelivery.payloadMetadata` — source of the deeplink (loader path). */
|
||||
readonly payloadMetadata?: unknown;
|
||||
/** Pre-validated deeplink scalar (SSE stream path) — re-validated here anyway. */
|
||||
readonly deeplink?: string | null;
|
||||
}
|
||||
|
||||
export interface NotificationCenterItemVM {
|
||||
readonly id: string;
|
||||
readonly messageKey: string;
|
||||
readonly category: string;
|
||||
readonly categoryKey: string;
|
||||
readonly channel: string;
|
||||
readonly channelKey: string;
|
||||
readonly status: string;
|
||||
readonly statusKey: string;
|
||||
readonly isRead: boolean;
|
||||
readonly attemptsMade: number;
|
||||
readonly createdAtIso: string | null;
|
||||
readonly updatedAtIso: string | null;
|
||||
readonly sentAtIso: string | null;
|
||||
readonly readAtIso: string | null;
|
||||
/** Newest known activity timestamp — drives sorting/merging. */
|
||||
readonly sortTimestamp: number;
|
||||
/** M002 plain-text bounce key, or null when the delivery has no error. */
|
||||
readonly bounceKey: string | null;
|
||||
/** Display-safe (re-redacted + truncated) raw error detail. */
|
||||
readonly lastErrorRedacted: string | null;
|
||||
/** Validated app-relative deeplink from payloadMetadata, or null. */
|
||||
readonly deeplinkHref: string | null;
|
||||
}
|
||||
|
||||
export interface NotificationCenterData {
|
||||
readonly items: readonly NotificationCenterItemVM[];
|
||||
readonly totalCount: number;
|
||||
readonly unreadCount: number;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
readonly unreadEmptyKey: string;
|
||||
readonly streamAvailable: boolean;
|
||||
}
|
||||
|
||||
export type NotificationCenterVM = VMState<NotificationCenterData>;
|
||||
|
||||
// Map a raw provider bounce/failure reason onto a stable, human-readable i18n
|
||||
// key (M002 plain-text diagnostics). Order matters: most specific first.
|
||||
const BOUNCE_REASON_MATCHERS: ReadonlyArray<{ key: string; pattern: RegExp }> = [
|
||||
{ key: "notifications.center.bounce.invalidRecipient", pattern: /(invalid|unknown|no such|not found|does not exist|nonexistent|undeliverable).{0,20}(recipient|address|mailbox|user)|550|5\.1\.1/i },
|
||||
{ key: "notifications.center.bounce.mailboxFull", pattern: /(mailbox|quota).{0,20}(full|exceeded)|over\s?quota|552|5\.2\.2/i },
|
||||
{ key: "notifications.center.bounce.rejectedSpam", pattern: /spam|blocklist|blacklist|reputation|reject|blocked|policy/i },
|
||||
{ key: "notifications.center.bounce.rateLimited", pattern: /rate\s?limit|throttl|too many requests|429|4\.7\.0/i },
|
||||
{ key: "notifications.center.bounce.serviceUnavailable", pattern: /timeout|timed out|connection|network|unavailable|temporarily|try again|503|421/i },
|
||||
];
|
||||
|
||||
export function deriveBounceMessageKey(lastError: string): string {
|
||||
for (const matcher of BOUNCE_REASON_MATCHERS) {
|
||||
if (matcher.pattern.test(lastError)) {
|
||||
return matcher.key;
|
||||
}
|
||||
}
|
||||
return "notifications.center.bounce.generic";
|
||||
}
|
||||
|
||||
/** Second-pass display redaction + truncation for raw provider errors. */
|
||||
export function redactNotificationErrorForDisplay(lastError: string): string {
|
||||
const withoutTokenPairs = lastError.replace(/\b((?:api[_-]?key|secret|token|password|provider[_-]?id))\s*[:=]\s*[^\s,;]+/gi, "$1=[redacted]");
|
||||
const withoutLikelyBearer = withoutTokenPairs.replace(/\b(?:sk|pk|provider|secret|token)_[A-Za-z0-9_-]{6,}\b/g, "[redacted]");
|
||||
return withoutLikelyBearer.length > 160 ? `${withoutLikelyBearer.slice(0, 157)}...` : withoutLikelyBearer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deeplink contract (AK-P3 DoD 4): `payloadMetadata.deeplink` must be an
|
||||
* app-relative path ("/…"). Everything else — absolute URLs, protocol-relative
|
||||
* ("//…"), schemes, backslashes, whitespace — is rejected so a compromised
|
||||
* payload can never navigate off-app.
|
||||
*/
|
||||
export function deriveNotificationDeeplink(payloadMetadata: unknown): string | null {
|
||||
if (typeof payloadMetadata !== "object" || payloadMetadata === null || Array.isArray(payloadMetadata)) {
|
||||
return null;
|
||||
}
|
||||
return validateAppRelativePath((payloadMetadata as Record<string, unknown>).deeplink);
|
||||
}
|
||||
|
||||
/** Shared deeplink validation (mirrors the db/realtime stream contract). */
|
||||
export function validateAppRelativePath(candidate: unknown): string | null {
|
||||
if (typeof candidate !== "string") return null;
|
||||
const trimmed = candidate.trim();
|
||||
if (trimmed.length < 2 || !trimmed.startsWith("/")) return null;
|
||||
if (trimmed.startsWith("//") || trimmed.includes("\\") || /\s/.test(trimmed)) return null;
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const READ_STATUS = "READ";
|
||||
|
||||
function normalizeIso(value: string | null | undefined): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
||||
}
|
||||
|
||||
function toSortTimestamp(input: NotificationCenterItemInput): number {
|
||||
const raw = input.updatedAtIso ?? input.sentAtIso ?? input.createdAtIso;
|
||||
if (!raw) return 0;
|
||||
const parsed = Date.parse(raw);
|
||||
return Number.isNaN(parsed) ? 0 : parsed;
|
||||
}
|
||||
|
||||
export function toNotificationCenterItemVM(input: NotificationCenterItemInput): NotificationCenterItemVM {
|
||||
const status = input.status.trim().toUpperCase();
|
||||
const lastError = typeof input.lastError === "string" && input.lastError.trim().length > 0 ? input.lastError : null;
|
||||
return {
|
||||
id: input.id,
|
||||
messageKey: input.messageKey,
|
||||
category: input.category,
|
||||
categoryKey: `notifications.center.categories.${input.category.toLowerCase()}`,
|
||||
channel: input.channel,
|
||||
channelKey: `notifications.center.channels.${input.channel.toLowerCase()}`,
|
||||
status,
|
||||
statusKey: `notifications.center.statuses.${status.toLowerCase()}`,
|
||||
isRead: status === READ_STATUS,
|
||||
attemptsMade: Number.isFinite(input.attemptsMade) ? input.attemptsMade : 0,
|
||||
createdAtIso: normalizeIso(input.createdAtIso),
|
||||
updatedAtIso: normalizeIso(input.updatedAtIso),
|
||||
sentAtIso: normalizeIso(input.sentAtIso),
|
||||
readAtIso: normalizeIso(input.readAtIso),
|
||||
sortTimestamp: toSortTimestamp(input),
|
||||
bounceKey: lastError ? deriveBounceMessageKey(lastError) : null,
|
||||
lastErrorRedacted: lastError ? redactNotificationErrorForDisplay(lastError) : null,
|
||||
deeplinkHref: deriveNotificationDeeplink(input.payloadMetadata) ?? validateAppRelativePath(input.deeplink),
|
||||
};
|
||||
}
|
||||
|
||||
export const NOTIFICATION_CENTER_MAX_ITEMS = 50;
|
||||
|
||||
/**
|
||||
* Pure merge used by both the loader (initial + revalidated data) and the SSE
|
||||
* hook (live updates): newest-first, de-duplicated by id, capped.
|
||||
*/
|
||||
export function mergeNotificationCenterItems(
|
||||
current: readonly NotificationCenterItemVM[],
|
||||
incoming: readonly NotificationCenterItemVM[]
|
||||
): NotificationCenterItemVM[] {
|
||||
if (incoming.length === 0) return [...current];
|
||||
const byId = new Map(current.map((item) => [item.id, item]));
|
||||
for (const item of incoming) {
|
||||
const existing = byId.get(item.id);
|
||||
// Null-preserving merge: stream updates may omit deeplink/error context
|
||||
// (payloadMetadata is not part of every event) — keep what we know.
|
||||
byId.set(
|
||||
item.id,
|
||||
existing
|
||||
? {
|
||||
...existing,
|
||||
...item,
|
||||
deeplinkHref: item.deeplinkHref ?? existing.deeplinkHref,
|
||||
bounceKey: item.bounceKey ?? existing.bounceKey,
|
||||
lastErrorRedacted: item.lastErrorRedacted ?? existing.lastErrorRedacted,
|
||||
}
|
||||
: item
|
||||
);
|
||||
}
|
||||
return Array.from(byId.values())
|
||||
.sort((left, right) => right.sortTimestamp - left.sortTimestamp)
|
||||
.slice(0, NOTIFICATION_CENTER_MAX_ITEMS);
|
||||
}
|
||||
|
||||
export interface BuildNotificationCenterVMInput {
|
||||
readonly items: readonly NotificationCenterItemInput[];
|
||||
readonly streamAvailable: boolean;
|
||||
}
|
||||
|
||||
export function buildNotificationCenterVM(input: BuildNotificationCenterVMInput): NotificationCenterVM {
|
||||
const items = mergeNotificationCenterItems(
|
||||
[],
|
||||
input.items.map((item) => toNotificationCenterItemVM(item))
|
||||
);
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
items,
|
||||
totalCount: items.length,
|
||||
unreadCount: items.filter((item) => !item.isRead).length,
|
||||
emptyHeadlineKey: "notifications.center.empty",
|
||||
emptyBodyKey: "notifications.center.emptyHelper",
|
||||
unreadEmptyKey: "notifications.center.unreadEmpty",
|
||||
streamAvailable: input.streamAvailable,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// --- Hot-swap component model (M015/M017) ---
|
||||
|
||||
export interface NotificationCenterModelItem {
|
||||
readonly id: string;
|
||||
readonly messageKey: string;
|
||||
readonly statusKey: string;
|
||||
readonly categoryKey: string;
|
||||
readonly isRead: boolean;
|
||||
readonly bounceKey: string | null;
|
||||
readonly deeplinkHref: string | null;
|
||||
}
|
||||
|
||||
export interface NotificationCenterModel {
|
||||
readonly titleKey: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
readonly totalCount: number;
|
||||
readonly unreadCount: number;
|
||||
readonly items: readonly NotificationCenterModelItem[];
|
||||
}
|
||||
|
||||
export function toNotificationCenterModel(data: NotificationCenterData): NotificationCenterModel {
|
||||
return {
|
||||
titleKey: "notifications.center.title",
|
||||
emptyHeadlineKey: data.emptyHeadlineKey,
|
||||
emptyBodyKey: data.emptyBodyKey,
|
||||
totalCount: data.totalCount,
|
||||
unreadCount: data.unreadCount,
|
||||
items: data.items.map((item) => ({
|
||||
id: item.id,
|
||||
messageKey: item.messageKey,
|
||||
statusKey: item.statusKey,
|
||||
categoryKey: item.categoryKey,
|
||||
isRead: item.isRead,
|
||||
bounceKey: item.bounceKey,
|
||||
deeplinkHref: item.deeplinkHref,
|
||||
})),
|
||||
};
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildNotificationSettingsVM,
|
||||
resolveNotificationPreferenceStates,
|
||||
NOTIFICATION_CATEGORY_REGISTRY,
|
||||
} from "./notification-settings.vm.js";
|
||||
|
||||
describe("resolveNotificationPreferenceStates", () => {
|
||||
it("defaults every category/channel to enabled", () => {
|
||||
const states = resolveNotificationPreferenceStates([]);
|
||||
expect(states.default).toEqual({ IN_APP: true, EMAIL: true });
|
||||
expect(states.billing).toEqual({ IN_APP: true, EMAIL: true });
|
||||
expect(states.team).toEqual({ IN_APP: true, EMAIL: true });
|
||||
});
|
||||
|
||||
it("inherits the default category when a category has no explicit row", () => {
|
||||
const states = resolveNotificationPreferenceStates([
|
||||
{ category: "default", channel: "EMAIL", enabled: false },
|
||||
{ category: "billing", channel: "EMAIL", enabled: true },
|
||||
]);
|
||||
// billing has an explicit row → keeps it; team inherits default=off.
|
||||
expect(states.billing.EMAIL).toBe(true);
|
||||
expect(states.team.EMAIL).toBe(false);
|
||||
expect(states.team.IN_APP).toBe(true);
|
||||
});
|
||||
|
||||
it("normalizes channel/category casing and ignores unknown entries", () => {
|
||||
const states = resolveNotificationPreferenceStates([
|
||||
{ category: "Billing", channel: "in-app", enabled: false },
|
||||
{ category: "nonsense", channel: "EMAIL", enabled: false },
|
||||
{ category: "team", channel: "CARRIER_PIGEON", enabled: false },
|
||||
]);
|
||||
expect(states.billing.IN_APP).toBe(false);
|
||||
expect(states.team.EMAIL).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildNotificationSettingsVM", () => {
|
||||
it("groups categories per module with i18n keys", () => {
|
||||
const vm = buildNotificationSettingsVM([]);
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.groups.map((group) => group.module)).toEqual(
|
||||
NOTIFICATION_CATEGORY_REGISTRY.map((group) => group.module)
|
||||
);
|
||||
const billing = vm.data?.groups.find((group) => group.module === "billing");
|
||||
expect(billing?.moduleLabelKey).toBe("settings.notifications.modules.billing");
|
||||
expect(billing?.categories[0]).toMatchObject({
|
||||
category: "billing",
|
||||
labelKey: "settings.notifications.categories.billing",
|
||||
channels: { IN_APP: true, EMAIL: true },
|
||||
});
|
||||
expect(vm.data?.allEmailsDisabled).toBe(false);
|
||||
});
|
||||
|
||||
it("reports the master switch on when EMAIL is off for every category", () => {
|
||||
const vm = buildNotificationSettingsVM([
|
||||
{ category: "default", channel: "EMAIL", enabled: false },
|
||||
{ category: "billing", channel: "EMAIL", enabled: false },
|
||||
{ category: "team", channel: "EMAIL", enabled: false },
|
||||
]);
|
||||
expect(vm.data?.allEmailsDisabled).toBe(true);
|
||||
});
|
||||
});
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* Notification-Settings view-model (AK-P3 DoD 5). Owns the event-type-per-
|
||||
* module registry and the default-category inheritance merge (mirrors the
|
||||
* worker-side isNotificationEnabled() fallback) as pure functions so the
|
||||
* route loader and the interim screen share one contract.
|
||||
*/
|
||||
|
||||
export const NOTIFICATION_CATEGORY_REGISTRY = [
|
||||
{ module: "general", categories: ["default"] },
|
||||
{ module: "billing", categories: ["billing"] },
|
||||
{ module: "team", categories: ["team"] },
|
||||
] as const;
|
||||
|
||||
export const NOTIFICATION_SETTING_CATEGORIES: readonly string[] = NOTIFICATION_CATEGORY_REGISTRY.flatMap(
|
||||
(group) => group.categories
|
||||
);
|
||||
export const NOTIFICATION_SETTING_CHANNELS = ["IN_APP", "EMAIL"] as const;
|
||||
export type NotificationSettingChannel = (typeof NOTIFICATION_SETTING_CHANNELS)[number];
|
||||
|
||||
export interface NotificationPreferenceInput {
|
||||
readonly channel: string;
|
||||
readonly category: string;
|
||||
readonly enabled: boolean;
|
||||
}
|
||||
|
||||
export type NotificationChannelStates = Readonly<Record<NotificationSettingChannel, boolean>>;
|
||||
|
||||
export interface NotificationSettingsCategoryVM {
|
||||
readonly category: string;
|
||||
readonly labelKey: string;
|
||||
readonly channels: NotificationChannelStates;
|
||||
}
|
||||
|
||||
export interface NotificationSettingsGroupVM {
|
||||
readonly module: string;
|
||||
readonly moduleLabelKey: string;
|
||||
readonly categories: readonly NotificationSettingsCategoryVM[];
|
||||
}
|
||||
|
||||
export interface NotificationSettingsData {
|
||||
readonly groups: readonly NotificationSettingsGroupVM[];
|
||||
/** True when EMAIL is off for every registered category (master switch state). */
|
||||
readonly allEmailsDisabled: boolean;
|
||||
}
|
||||
|
||||
export type NotificationSettingsVM = VMState<NotificationSettingsData>;
|
||||
|
||||
export function isAllowedNotificationCategory(value: string): boolean {
|
||||
return NOTIFICATION_SETTING_CATEGORIES.includes(value);
|
||||
}
|
||||
|
||||
export function isAllowedNotificationChannel(value: string): value is NotificationSettingChannel {
|
||||
return (NOTIFICATION_SETTING_CHANNELS as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
type MutableStates = Record<string, Record<NotificationSettingChannel, boolean>>;
|
||||
|
||||
/**
|
||||
* Merges explicit preference rows over the enabled-by-default matrix.
|
||||
* Categories without an explicit row inherit the "default" category —
|
||||
* exactly mirroring the worker-side isNotificationEnabled() fallback.
|
||||
*/
|
||||
export function resolveNotificationPreferenceStates(records: readonly NotificationPreferenceInput[]): MutableStates {
|
||||
const states: MutableStates = {};
|
||||
for (const category of NOTIFICATION_SETTING_CATEGORIES) {
|
||||
states[category] = { IN_APP: true, EMAIL: true };
|
||||
}
|
||||
const explicit = new Set<string>();
|
||||
for (const record of records) {
|
||||
const category = record.category.trim().toLowerCase();
|
||||
const channel = record.channel.trim().replace(/-/g, "_").toUpperCase();
|
||||
if (isAllowedNotificationCategory(category) && isAllowedNotificationChannel(channel)) {
|
||||
states[category][channel] = record.enabled;
|
||||
explicit.add(`${category}:${channel}`);
|
||||
}
|
||||
}
|
||||
for (const category of NOTIFICATION_SETTING_CATEGORIES) {
|
||||
if (category === "default") continue;
|
||||
for (const channel of NOTIFICATION_SETTING_CHANNELS) {
|
||||
if (!explicit.has(`${category}:${channel}`)) {
|
||||
states[category][channel] = states.default[channel];
|
||||
}
|
||||
}
|
||||
}
|
||||
return states;
|
||||
}
|
||||
|
||||
export function buildNotificationSettingsVM(records: readonly NotificationPreferenceInput[]): NotificationSettingsVM {
|
||||
const states = resolveNotificationPreferenceStates(records);
|
||||
const groups: NotificationSettingsGroupVM[] = NOTIFICATION_CATEGORY_REGISTRY.map((group) => ({
|
||||
module: group.module,
|
||||
moduleLabelKey: `settings.notifications.modules.${group.module}`,
|
||||
categories: group.categories.map((category) => ({
|
||||
category,
|
||||
labelKey: `settings.notifications.categories.${category}`,
|
||||
channels: { IN_APP: states[category].IN_APP, EMAIL: states[category].EMAIL },
|
||||
})),
|
||||
}));
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
groups,
|
||||
allEmailsDisabled: NOTIFICATION_SETTING_CATEGORIES.every((category) => !states[category].EMAIL),
|
||||
},
|
||||
};
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildProjectSignaturePanelVM, signatureDocumentStatusKey, signatureProviderKey, signatureSignerStatusKey } from "../index.js";
|
||||
|
||||
const I18N_KEY = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/;
|
||||
|
||||
describe("buildProjectSignaturePanelVM", () => {
|
||||
it("keeps AK-P16d project signatures as a ready panel with i18n keys", () => {
|
||||
const vm = buildProjectSignaturePanelVM({
|
||||
canRead: true,
|
||||
canSend: true,
|
||||
canRevoke: false,
|
||||
canAdmin: false,
|
||||
rows: [
|
||||
{
|
||||
id: "doc-1",
|
||||
title: "Angebot 2026",
|
||||
provider: "ses_selfhosted",
|
||||
providerKey: signatureProviderKey("ses_selfhosted"),
|
||||
status: "sent",
|
||||
statusKey: signatureDocumentStatusKey("sent"),
|
||||
sourcePdfFileId: "file-1",
|
||||
signedPdfFileId: null,
|
||||
completionCertFileId: null,
|
||||
sentAtIso: "2026-07-01T10:00:00.000Z",
|
||||
completedAtIso: null,
|
||||
expiresAtIso: null,
|
||||
signers: [
|
||||
{
|
||||
id: "signer-1",
|
||||
signerName: "Erika Mustermann",
|
||||
signerEmail: "erika@example.test",
|
||||
signerRole: "kunde",
|
||||
status: "viewed",
|
||||
statusKey: signatureSignerStatusKey("viewed"),
|
||||
signedAtIso: null,
|
||||
lastReminderAtIso: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows).toHaveLength(1);
|
||||
expect(vm.data.rows[0]?.statusKey).toMatch(I18N_KEY);
|
||||
expect(vm.data.rows[0]?.signers[0]?.statusKey).toMatch(I18N_KEY);
|
||||
expect(vm.data.createActionIntent).toBe("createSignatureDraft");
|
||||
expect(vm.data.designBlockedByKey).toMatch(I18N_KEY);
|
||||
});
|
||||
});
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
export type SignatureProvider = "ses_selfhosted" | "pandadoc_byok";
|
||||
export type SignatureDocumentStatus = "draft" | "sent" | "viewed" | "signed" | "declined" | "revoked" | "expired";
|
||||
export type SignatureSignerStatus = "draft" | "sent" | "viewed" | "otp_verified" | "signed" | "declined" | "revoked" | "expired";
|
||||
export type SignatureSignerRole = "kunde" | "bauherr" | "auftraggeber" | "rechnungsempfaenger" | "intern";
|
||||
|
||||
export interface ProjectSignatureSignerRow {
|
||||
readonly id: string;
|
||||
readonly signerName: string;
|
||||
readonly signerEmail: string;
|
||||
readonly signerRole: SignatureSignerRole;
|
||||
readonly status: SignatureSignerStatus;
|
||||
readonly statusKey: string;
|
||||
readonly signedAtIso: string | null;
|
||||
readonly lastReminderAtIso: string | null;
|
||||
}
|
||||
|
||||
export interface ProjectSignatureDocumentRow {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly provider: SignatureProvider;
|
||||
readonly providerKey: string;
|
||||
readonly status: SignatureDocumentStatus;
|
||||
readonly statusKey: string;
|
||||
readonly sourcePdfFileId: string;
|
||||
readonly signedPdfFileId: string | null;
|
||||
readonly completionCertFileId: string | null;
|
||||
readonly sentAtIso: string | null;
|
||||
readonly completedAtIso: string | null;
|
||||
readonly expiresAtIso: string | null;
|
||||
readonly signers: readonly ProjectSignatureSignerRow[];
|
||||
}
|
||||
|
||||
export interface ProjectSignaturePanelData {
|
||||
readonly rows: readonly ProjectSignatureDocumentRow[];
|
||||
readonly canRead: boolean;
|
||||
readonly canSend: boolean;
|
||||
readonly canRevoke: boolean;
|
||||
readonly canAdmin: boolean;
|
||||
readonly createActionIntent: string;
|
||||
readonly sendActionIntent: string;
|
||||
readonly remindActionIntent: string;
|
||||
readonly revokeActionIntent: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
readonly designBlockedByKey: string;
|
||||
}
|
||||
|
||||
export type ProjectSignaturePanelVM = VMState<ProjectSignaturePanelData>;
|
||||
|
||||
export interface BuildProjectSignaturePanelVMInput {
|
||||
readonly rows: readonly ProjectSignatureDocumentRow[];
|
||||
readonly canRead: boolean;
|
||||
readonly canSend: boolean;
|
||||
readonly canRevoke: boolean;
|
||||
readonly canAdmin: boolean;
|
||||
}
|
||||
|
||||
export function buildProjectSignaturePanelVM(input: BuildProjectSignaturePanelVMInput): ProjectSignaturePanelVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows: input.rows,
|
||||
canRead: input.canRead,
|
||||
canSend: input.canSend,
|
||||
canRevoke: input.canRevoke,
|
||||
canAdmin: input.canAdmin,
|
||||
createActionIntent: "createSignatureDraft",
|
||||
sendActionIntent: "sendSignatureDocument",
|
||||
remindActionIntent: "remindSignatureSigner",
|
||||
revokeActionIntent: "revokeSignatureDocument",
|
||||
emptyHeadlineKey: "signature.project.empty.headline",
|
||||
emptyBodyKey: "signature.project.empty.body",
|
||||
designBlockedByKey: "signature.project.designblockedby",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function signatureDocumentStatusKey(status: SignatureDocumentStatus): string {
|
||||
return `signature.status.document.${status}`;
|
||||
}
|
||||
|
||||
export function signatureSignerStatusKey(status: SignatureSignerStatus): string {
|
||||
return `signature.status.signer.${status}`;
|
||||
}
|
||||
|
||||
export function signatureProviderKey(provider: SignatureProvider): string {
|
||||
return `signature.provider.${provider}`;
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildTaskDetailVM,
|
||||
buildTaskListVM,
|
||||
taskPriorityKey,
|
||||
taskSourceKey,
|
||||
taskStatusKey,
|
||||
toTaskListModel,
|
||||
type BuildTaskDetailVMInput,
|
||||
type TaskListFilterState,
|
||||
type TaskListRow,
|
||||
} from "../index.js";
|
||||
|
||||
const filter: TaskListFilterState = {
|
||||
preset: "all",
|
||||
status: null,
|
||||
priority: null,
|
||||
assignedToUserId: null,
|
||||
includeArchived: false,
|
||||
};
|
||||
|
||||
describe("buildTaskDetailVM linkedEntity null branch (task-detail.ts:104)", () => {
|
||||
const base: BuildTaskDetailVMInput = {
|
||||
task: {
|
||||
id: "t1",
|
||||
title: "Standalone task",
|
||||
description: null,
|
||||
status: "open",
|
||||
priority: "normal",
|
||||
deadlineIso: null,
|
||||
isOverdue: false,
|
||||
assignee: null,
|
||||
linkedEntity: null,
|
||||
source: "manual",
|
||||
sourceHref: null,
|
||||
watchers: [],
|
||||
createdAtIso: "2026-06-20T08:00:00.000Z",
|
||||
completedAtIso: null,
|
||||
},
|
||||
canWrite: true,
|
||||
canDelete: true,
|
||||
listHref: "/acme/tasks",
|
||||
};
|
||||
|
||||
it("leaves linkedEntity null when the task is not linked to an entity", () => {
|
||||
const vm = buildTaskDetailVM(base);
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.linkedEntity).toBeNull();
|
||||
});
|
||||
|
||||
it("defaults the picker option lists to empty arrays for a writer when none are supplied", () => {
|
||||
// canWrite is true but assignableUsers/assignableGroups are omitted -> `?? []`.
|
||||
const vm = buildTaskDetailVM(base);
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.assignableUsers).toEqual([]);
|
||||
expect(vm.data.assignableGroups).toEqual([]);
|
||||
expect(vm.data.canWrite).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toTaskListModel assignee fallback (task-list.ts:155)", () => {
|
||||
it("maps a row without an assignee to a null assigneeLabel", () => {
|
||||
const row: TaskListRow = {
|
||||
id: "t1",
|
||||
title: "Unassigned task",
|
||||
status: "open",
|
||||
statusKey: taskStatusKey("open"),
|
||||
priority: "low",
|
||||
priorityKey: taskPriorityKey("low"),
|
||||
deadlineIso: null,
|
||||
isOverdue: false,
|
||||
assignee: null,
|
||||
linkedEntity: null,
|
||||
source: "manual",
|
||||
sourceKey: taskSourceKey("manual"),
|
||||
sourceHref: null,
|
||||
detailHref: "/acme/tasks/t1",
|
||||
};
|
||||
const vm = buildTaskListVM({ rows: [row], filter, canWrite: false, canDelete: false, createHref: "/acme/tasks/new" });
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
const model = toTaskListModel(vm.data);
|
||||
expect(model.rows[0]?.assigneeLabel).toBeNull();
|
||||
expect(model.rowCount).toBe(1);
|
||||
});
|
||||
});
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildGroupsDetailVM, filterGroupMemberRows, type GroupsDetailInputUser } from "../index.js";
|
||||
|
||||
function user(id: string, firstName: string | null, email: string): GroupsDetailInputUser {
|
||||
return { userId: id, firstName, lastName: null, email };
|
||||
}
|
||||
|
||||
const GROUP = { id: "g1", name: "Montage Nord", description: "Bautrupp" };
|
||||
|
||||
describe("buildGroupsDetailVM", () => {
|
||||
it("splits members and candidates without overlap", () => {
|
||||
const vm = buildGroupsDetailVM({
|
||||
group: GROUP,
|
||||
memberUsers: [user("u1", "Ada", "ada@example.com")],
|
||||
tenantUsers: [user("u1", "Ada", "ada@example.com"), user("u2", "Grace", "grace@example.com"), user("u3", null, "linus@example.com")],
|
||||
canManage: true,
|
||||
});
|
||||
expect(vm.status).toBe("ready");
|
||||
const data = vm.data!;
|
||||
expect(data.memberRows.map((r) => r.userId)).toEqual(["u1"]);
|
||||
expect(data.candidateRows.map((r) => r.userId)).toEqual(["u2", "u3"]);
|
||||
expect(data.memberCount).toBe(1);
|
||||
expect(data.emptyCandidatesKey).toBe("settings.members.groups.bulk.emptyCandidates");
|
||||
});
|
||||
|
||||
it("derives display name and initials with email fallback", () => {
|
||||
const vm = buildGroupsDetailVM({ group: GROUP, memberUsers: [user("u3", null, "linus@example.com")], tenantUsers: [], canManage: false });
|
||||
const row = vm.data!.memberRows[0];
|
||||
expect(row.name).toBe("linus@example.com");
|
||||
expect(row.initials).toBe("L");
|
||||
expect(vm.data!.canManage).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterGroupMemberRows", () => {
|
||||
const rows = buildGroupsDetailVM({
|
||||
group: GROUP,
|
||||
memberUsers: [user("u1", "Ada", "ada@example.com"), user("u2", "Grace", "grace@example.com")],
|
||||
tenantUsers: [],
|
||||
canManage: true,
|
||||
}).data!.memberRows;
|
||||
|
||||
it("matches name or email, empty query returns all", () => {
|
||||
expect(filterGroupMemberRows(rows, "grace").map((r) => r.userId)).toEqual(["u2"]);
|
||||
expect(filterGroupMemberRows(rows, "example.com").length).toBe(2);
|
||||
expect(filterGroupMemberRows(rows, "").length).toBe(2);
|
||||
});
|
||||
});
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* Group members bulk view-model (R-P2b, interim UI per AD-28 — David parked
|
||||
* groups for RBAC V2, so this screen is a `~/ui` preview with an open
|
||||
* design-nachzug). Pure function, no React/Prisma/app imports.
|
||||
*
|
||||
* Backs the bulk add/remove dialog on top of the idempotent
|
||||
* `addUsersToGroup`/`removeUsersFromGroup` backend ops.
|
||||
*/
|
||||
|
||||
export type GroupMemberRow = {
|
||||
readonly userId: string;
|
||||
readonly name: string;
|
||||
readonly email: string;
|
||||
readonly initials: string;
|
||||
};
|
||||
|
||||
export interface GroupsDetailData {
|
||||
readonly groupId: string;
|
||||
readonly name: string;
|
||||
readonly description: string;
|
||||
/** Users currently in the group (bulk-remove candidates). */
|
||||
readonly memberRows: readonly GroupMemberRow[];
|
||||
/** Tenant members not yet in the group (bulk-add candidates). */
|
||||
readonly candidateRows: readonly GroupMemberRow[];
|
||||
readonly memberCount: number;
|
||||
readonly canManage: boolean;
|
||||
readonly emptyMembersKey: string;
|
||||
readonly emptyCandidatesKey: string;
|
||||
}
|
||||
|
||||
export type GroupsDetailVM = VMState<GroupsDetailData>;
|
||||
|
||||
export interface GroupsDetailInputUser {
|
||||
readonly userId: string;
|
||||
readonly firstName: string | null;
|
||||
readonly lastName: string | null;
|
||||
readonly email: string;
|
||||
}
|
||||
|
||||
export interface BuildGroupsDetailVMInput {
|
||||
readonly group: { readonly id: string; readonly name: string; readonly description: string };
|
||||
readonly memberUsers: readonly GroupsDetailInputUser[];
|
||||
/** All (active) tenant users — candidates are derived as "not yet member". */
|
||||
readonly tenantUsers: readonly GroupsDetailInputUser[];
|
||||
readonly canManage: boolean;
|
||||
}
|
||||
|
||||
function toRow(user: GroupsDetailInputUser): GroupMemberRow {
|
||||
const name =
|
||||
[user.firstName, user.lastName]
|
||||
.map((part) => (part ?? "").trim())
|
||||
.filter(Boolean)
|
||||
.join(" ") || user.email;
|
||||
const initials =
|
||||
`${(user.firstName ?? "").trim().charAt(0)}${(user.lastName ?? "").trim().charAt(0)}`.toUpperCase() || user.email.charAt(0).toUpperCase();
|
||||
return { userId: user.userId, name, email: user.email, initials };
|
||||
}
|
||||
|
||||
export function buildGroupsDetailVM(input: BuildGroupsDetailVMInput): GroupsDetailVM {
|
||||
const memberIds = new Set(input.memberUsers.map((user) => user.userId));
|
||||
const memberRows = input.memberUsers.map(toRow);
|
||||
const candidateRows = input.tenantUsers.filter((user) => !memberIds.has(user.userId)).map(toRow);
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
groupId: input.group.id,
|
||||
name: input.group.name,
|
||||
description: input.group.description,
|
||||
memberRows,
|
||||
candidateRows,
|
||||
memberCount: memberRows.length,
|
||||
canManage: input.canManage,
|
||||
emptyMembersKey: "settings.members.groups.bulk.emptyMembers",
|
||||
emptyCandidatesKey: "settings.members.groups.bulk.emptyCandidates",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Search across name/email — shared by both pick lists in the bulk dialog. */
|
||||
export function filterGroupMemberRows(rows: readonly GroupMemberRow[], query: string): GroupMemberRow[] {
|
||||
const normalized = query.trim().toUpperCase();
|
||||
if (!normalized) return [...rows];
|
||||
return rows.filter((row) => `${row.name} ${row.email}`.toUpperCase().includes(normalized));
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildMembersListVM,
|
||||
deriveMemberInitials,
|
||||
deriveMemberName,
|
||||
filterMembersRows,
|
||||
toMembersListModel,
|
||||
EMPTY_MEMBERS_FILTER,
|
||||
type MembersListInputRow,
|
||||
} from "../index.js";
|
||||
|
||||
function inputRow(overrides: Partial<MembersListInputRow> = {}): MembersListInputRow {
|
||||
return {
|
||||
tenantUserId: "tu1",
|
||||
userId: "u1",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
email: "ada@example.com",
|
||||
phone: "+49 123",
|
||||
status: "active",
|
||||
mfaEnabled: true,
|
||||
roles: [{ id: "r1", name: "Monteur", description: "" }],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildVM(rows: MembersListInputRow[], currentUserId = "me") {
|
||||
return buildMembersListVM({
|
||||
rows,
|
||||
pendingInvitations: [],
|
||||
assignableRoles: [{ id: "r1", name: "Monteur", description: "" }],
|
||||
currentUserId,
|
||||
canInvite: true,
|
||||
canEditRoles: true,
|
||||
canManageMembers: true,
|
||||
});
|
||||
}
|
||||
|
||||
describe("deriveMemberName / deriveMemberInitials", () => {
|
||||
it("joins names and falls back to email", () => {
|
||||
expect(deriveMemberName("Ada", "Lovelace", "ada@example.com")).toBe("Ada Lovelace");
|
||||
expect(deriveMemberName(null, null, "ada@example.com")).toBe("ada@example.com");
|
||||
expect(deriveMemberInitials("Ada", "Lovelace", "ada@example.com")).toBe("AL");
|
||||
expect(deriveMemberInitials(null, null, "ada@example.com")).toBe("A");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildMembersListVM", () => {
|
||||
it("maps rows with status label keys and capabilities", () => {
|
||||
const vm = buildVM([inputRow(), inputRow({ tenantUserId: "tu2", userId: "u2", status: "inactive", mfaEnabled: false })]);
|
||||
expect(vm.status).toBe("ready");
|
||||
const [active, inactive] = vm.data!.rows;
|
||||
expect(active.statusLabelKey).toBe("settings.members.status.active");
|
||||
expect(active.canDeactivate).toBe(true);
|
||||
expect(active.canReactivate).toBe(false);
|
||||
expect(inactive.statusLabelKey).toBe("settings.members.status.deactivated");
|
||||
expect(inactive.canDeactivate).toBe(false);
|
||||
expect(inactive.canReactivate).toBe(true);
|
||||
});
|
||||
|
||||
it("never offers self-deactivation (server guards last-admin anyway)", () => {
|
||||
const vm = buildVM([inputRow({ userId: "me" })], "me");
|
||||
const row = vm.data!.rows[0];
|
||||
expect(row.isSelf).toBe(true);
|
||||
expect(row.canDeactivate).toBe(false);
|
||||
});
|
||||
|
||||
it("drops manage capabilities without permission", () => {
|
||||
const vm = buildMembersListVM({
|
||||
rows: [inputRow()],
|
||||
pendingInvitations: [],
|
||||
assignableRoles: [],
|
||||
currentUserId: "me",
|
||||
canInvite: false,
|
||||
canEditRoles: false,
|
||||
canManageMembers: false,
|
||||
});
|
||||
expect(vm.data!.rows[0].canDeactivate).toBe(false);
|
||||
expect(vm.data!.canInvite).toBe(false);
|
||||
});
|
||||
|
||||
it("normalizes empty phone to null and keeps invited status", () => {
|
||||
const vm = buildVM([inputRow({ phone: " ", status: "invited" })]);
|
||||
const row = vm.data!.rows[0];
|
||||
expect(row.phone).toBeNull();
|
||||
expect(row.statusLabelKey).toBe("settings.members.status.invited");
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterMembersRows", () => {
|
||||
const rows = buildVM([
|
||||
inputRow(),
|
||||
inputRow({ tenantUserId: "tu2", userId: "u2", firstName: "Grace", lastName: "Hopper", email: "grace@example.com", phone: null, mfaEnabled: false, roles: [] }),
|
||||
inputRow({ tenantUserId: "tu3", userId: "u3", firstName: "Linus", lastName: null, email: "linus@example.com", status: "inactive" }),
|
||||
]).data!.rows;
|
||||
|
||||
it("searches across name, email and phone", () => {
|
||||
expect(filterMembersRows(rows, { ...EMPTY_MEMBERS_FILTER, query: "grace" }).map((r) => r.userId)).toEqual(["u2"]);
|
||||
expect(filterMembersRows(rows, { ...EMPTY_MEMBERS_FILTER, query: "+49" }).length).toBe(2);
|
||||
});
|
||||
|
||||
it("filters by role, status and 2FA", () => {
|
||||
expect(filterMembersRows(rows, { ...EMPTY_MEMBERS_FILTER, roleId: "r1" }).length).toBe(2);
|
||||
expect(filterMembersRows(rows, { ...EMPTY_MEMBERS_FILTER, status: "inactive" }).map((r) => r.userId)).toEqual(["u3"]);
|
||||
expect(filterMembersRows(rows, { ...EMPTY_MEMBERS_FILTER, mfa: false }).map((r) => r.userId)).toEqual(["u2"]);
|
||||
});
|
||||
|
||||
it("returns everything for the empty filter", () => {
|
||||
expect(filterMembersRows(rows, EMPTY_MEMBERS_FILTER).length).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toMembersListModel", () => {
|
||||
it("normalizes rows for the hot-swap renderers", () => {
|
||||
const model = toMembersListModel(buildVM([inputRow()]).data!);
|
||||
expect(model.titleKey).toBe("settings.members.title");
|
||||
expect(model.rowCount).toBe(1);
|
||||
expect(model.rows[0]).toMatchObject({ name: "Ada Lovelace", roleNames: ["Monteur"], canDeactivate: true });
|
||||
});
|
||||
});
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* Members admin list view-model (R-P2b, David's D-P2 `WF-P2 Admin RBAC` S01).
|
||||
* Pure function: the loader builds it once server-side, the UI only renders.
|
||||
* No React, no Prisma, no app imports (DoD A.3).
|
||||
*
|
||||
* Role display names need the app-side `roleDisplayName(t)` resolver, so rows
|
||||
* carry raw role refs ({ id, name, description }) and the screen resolves the
|
||||
* labels — the builder stays locale- and app-agnostic.
|
||||
*/
|
||||
|
||||
/** Normalized membership status (route maps the numeric TenantUserStatus enum). */
|
||||
export type MemberStatus = "active" | "inactive" | "invited";
|
||||
|
||||
export type MemberRoleRef = {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly description: string;
|
||||
};
|
||||
|
||||
export type MembersListRow = {
|
||||
readonly tenantUserId: string;
|
||||
readonly userId: string;
|
||||
/** Display name (first/last name, falls back to email). */
|
||||
readonly name: string;
|
||||
readonly email: string;
|
||||
readonly phone: string | null;
|
||||
/** Avatar initials derived from name/email. */
|
||||
readonly initials: string;
|
||||
readonly status: MemberStatus;
|
||||
/** i18n key for the status badge label. */
|
||||
readonly statusLabelKey: string;
|
||||
readonly mfaEnabled: boolean;
|
||||
/** Roles assigned in this tenant (screen resolves display labels). */
|
||||
readonly roles: readonly MemberRoleRef[];
|
||||
readonly isSelf: boolean;
|
||||
/** Row menu capability: deactivate (M03) — active members that are not you. */
|
||||
readonly canDeactivate: boolean;
|
||||
/** Row menu capability: reactivate — inactive members. */
|
||||
readonly canReactivate: boolean;
|
||||
};
|
||||
|
||||
export type MembersListFilterState = {
|
||||
readonly query: string;
|
||||
/** Role id filter, null = all. */
|
||||
readonly roleId: string | null;
|
||||
readonly status: MemberStatus | null;
|
||||
/** 2FA filter: true = enabled only, false = disabled only, null = all. */
|
||||
readonly mfa: boolean | null;
|
||||
};
|
||||
|
||||
export const EMPTY_MEMBERS_FILTER: MembersListFilterState = {
|
||||
query: "",
|
||||
roleId: null,
|
||||
status: null,
|
||||
mfa: null,
|
||||
};
|
||||
|
||||
export type PendingInvitationRow = {
|
||||
readonly id: string;
|
||||
readonly email: string;
|
||||
readonly name: string;
|
||||
readonly createdAtIso: string | null;
|
||||
};
|
||||
|
||||
export interface MembersListData {
|
||||
readonly rows: readonly MembersListRow[];
|
||||
readonly pendingInvitations: readonly PendingInvitationRow[];
|
||||
/** Roles available for the inline role dropdown (D01) and the role filter. */
|
||||
readonly assignableRoles: readonly MemberRoleRef[];
|
||||
readonly canInvite: boolean;
|
||||
readonly canEditRoles: boolean;
|
||||
readonly canManageMembers: boolean;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
readonly noMatchesKey: string;
|
||||
}
|
||||
|
||||
export type MembersListVM = VMState<MembersListData>;
|
||||
|
||||
/** Raw member row the loader passes in (already read from the DB, framework-free). */
|
||||
export interface MembersListInputRow {
|
||||
readonly tenantUserId: string;
|
||||
readonly userId: string;
|
||||
readonly firstName: string | null;
|
||||
readonly lastName: string | null;
|
||||
readonly email: string;
|
||||
readonly phone: string | null;
|
||||
readonly status: MemberStatus;
|
||||
readonly mfaEnabled: boolean;
|
||||
readonly roles: readonly MemberRoleRef[];
|
||||
}
|
||||
|
||||
export interface BuildMembersListVMInput {
|
||||
readonly rows: readonly MembersListInputRow[];
|
||||
readonly pendingInvitations: readonly PendingInvitationRow[];
|
||||
readonly assignableRoles: readonly MemberRoleRef[];
|
||||
readonly currentUserId: string;
|
||||
readonly canInvite: boolean;
|
||||
readonly canEditRoles: boolean;
|
||||
readonly canManageMembers: boolean;
|
||||
}
|
||||
|
||||
const STATUS_LABEL_KEYS: Readonly<Record<MemberStatus, string>> = {
|
||||
active: "settings.members.status.active",
|
||||
inactive: "settings.members.status.deactivated",
|
||||
invited: "settings.members.status.invited",
|
||||
};
|
||||
|
||||
export function deriveMemberName(firstName: string | null, lastName: string | null, email: string): string {
|
||||
const name = [firstName, lastName]
|
||||
.map((part) => (part ?? "").trim())
|
||||
.filter(Boolean)
|
||||
.join(" ");
|
||||
return name || email;
|
||||
}
|
||||
|
||||
export function deriveMemberInitials(firstName: string | null, lastName: string | null, email: string): string {
|
||||
const initials = `${(firstName ?? "").trim().charAt(0)}${(lastName ?? "").trim().charAt(0)}`.toUpperCase();
|
||||
return initials || email.charAt(0).toUpperCase();
|
||||
}
|
||||
|
||||
export function buildMembersListVM(input: BuildMembersListVMInput): MembersListVM {
|
||||
const rows: MembersListRow[] = input.rows.map((row) => {
|
||||
const isSelf = row.userId === input.currentUserId;
|
||||
return {
|
||||
tenantUserId: row.tenantUserId,
|
||||
userId: row.userId,
|
||||
name: deriveMemberName(row.firstName, row.lastName, row.email),
|
||||
email: row.email,
|
||||
phone: row.phone && row.phone.trim().length > 0 ? row.phone.trim() : null,
|
||||
initials: deriveMemberInitials(row.firstName, row.lastName, row.email),
|
||||
status: row.status,
|
||||
statusLabelKey: STATUS_LABEL_KEYS[row.status],
|
||||
mfaEnabled: row.mfaEnabled,
|
||||
roles: row.roles,
|
||||
isSelf,
|
||||
// Server enforces the last-admin guard again (V01) — these flags only shape the menu.
|
||||
canDeactivate: input.canManageMembers && row.status === "active" && !isSelf,
|
||||
canReactivate: input.canManageMembers && row.status === "inactive",
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows,
|
||||
pendingInvitations: input.pendingInvitations,
|
||||
assignableRoles: input.assignableRoles,
|
||||
canInvite: input.canInvite,
|
||||
canEditRoles: input.canEditRoles,
|
||||
canManageMembers: input.canManageMembers,
|
||||
emptyHeadlineKey: "settings.members.empty.headline",
|
||||
emptyBodyKey: "settings.members.empty.body",
|
||||
noMatchesKey: "settings.members.empty.noMatches",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Client-side filter for S01 (search across name/email/phone + role/status/2FA
|
||||
* selects). Pure so it is unit-testable and shared between renderers.
|
||||
*/
|
||||
export function filterMembersRows(rows: readonly MembersListRow[], filter: MembersListFilterState): MembersListRow[] {
|
||||
const query = filter.query.trim().toUpperCase();
|
||||
return rows.filter((row) => {
|
||||
if (query) {
|
||||
const haystack = [row.name, row.email, row.phone ?? ""].join(" ").toUpperCase();
|
||||
if (!haystack.includes(query)) return false;
|
||||
}
|
||||
if (filter.roleId && !row.roles.some((role) => role.id === filter.roleId)) return false;
|
||||
if (filter.status && row.status !== filter.status) return false;
|
||||
if (filter.mfa !== null && row.mfaEnabled !== filter.mfa) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
// --- Hot-swap component model (M015/M017) ---
|
||||
|
||||
/** Normalized row model shared by the Subframe and mock renderers. */
|
||||
export interface MembersListModelRow {
|
||||
readonly tenantUserId: string;
|
||||
readonly name: string;
|
||||
readonly email: string;
|
||||
readonly statusLabelKey: string;
|
||||
readonly mfaEnabled: boolean;
|
||||
readonly roleNames: readonly string[];
|
||||
readonly canDeactivate: boolean;
|
||||
readonly canReactivate: boolean;
|
||||
}
|
||||
|
||||
export interface MembersListModel {
|
||||
readonly titleKey: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
readonly canInvite: boolean;
|
||||
readonly rows: readonly MembersListModelRow[];
|
||||
readonly rowCount: number;
|
||||
}
|
||||
|
||||
export function toMembersListModel(data: MembersListData): MembersListModel {
|
||||
return {
|
||||
titleKey: "settings.members.title",
|
||||
emptyHeadlineKey: data.emptyHeadlineKey,
|
||||
emptyBodyKey: data.emptyBodyKey,
|
||||
canInvite: data.canInvite,
|
||||
rows: data.rows.map((row) => ({
|
||||
tenantUserId: row.tenantUserId,
|
||||
name: row.name,
|
||||
email: row.email,
|
||||
statusLabelKey: row.statusLabelKey,
|
||||
mfaEnabled: row.mfaEnabled,
|
||||
roleNames: row.roles.map((role) => role.name),
|
||||
canDeactivate: row.canDeactivate,
|
||||
canReactivate: row.canReactivate,
|
||||
})),
|
||||
rowCount: data.rows.length,
|
||||
};
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildRoleEditorVM,
|
||||
deriveRoleEditorSectionId,
|
||||
filterRoleEditorSections,
|
||||
parsePermissionScope,
|
||||
togglePermission,
|
||||
ROLE_EDITOR_SECTION_IDS,
|
||||
type RoleEditorInputPermission,
|
||||
} from "../index.js";
|
||||
|
||||
const CATALOG: RoleEditorInputPermission[] = [
|
||||
{ name: "app.dashboard.view", description: "Default permission app.dashboard.view" },
|
||||
{ name: "app.settings.members.view", description: "Default permission app.settings.members.view" },
|
||||
{ name: "app.settings.members.update", description: "Default permission app.settings.members.update" },
|
||||
{ name: "app.settings.groups.full", description: "Default permission app.settings.groups.full" },
|
||||
{ name: "app.settings.roles.set", description: "Default permission app.settings.roles.set" },
|
||||
{ name: "app.settings.subscription.update", description: "Default permission app.settings.subscription.update" },
|
||||
{ name: "app.settings.subscription.invoices.view", description: "Default permission app.settings.subscription.invoices.view" },
|
||||
{ name: "app.settings.auditTrails.view", description: "Default permission app.settings.auditTrails.view" },
|
||||
{ name: "privacy.user_export.self", description: "Default permission privacy.user_export.self" },
|
||||
{ name: "app.settings.apiKeys.view", description: "Default permission app.settings.apiKeys.view" },
|
||||
{ name: "integrations.connect", description: "Default permission integrations.connect" },
|
||||
{ name: "files.read_all", description: "Default permission files.read_all" },
|
||||
{ name: "tasks.write", description: "Default permission tasks.write" },
|
||||
{ name: "crm.read_all", description: "Default permission crm.read_all" },
|
||||
];
|
||||
|
||||
describe("parsePermissionScope / deriveRoleEditorSectionId", () => {
|
||||
it("strips the trailing action", () => {
|
||||
expect(parsePermissionScope("app.settings.members.view")).toBe("app.settings.members");
|
||||
expect(parsePermissionScope("files.read_all")).toBe("files");
|
||||
expect(parsePermissionScope("weird")).toBe("weird");
|
||||
});
|
||||
|
||||
it("maps scopes to David's M02 sections with longest-prefix precedence", () => {
|
||||
expect(deriveRoleEditorSectionId("app.dashboard.view")).toBe("general");
|
||||
expect(deriveRoleEditorSectionId("app.settings.members.update")).toBe("members");
|
||||
expect(deriveRoleEditorSectionId("app.settings.groups.full")).toBe("members");
|
||||
expect(deriveRoleEditorSectionId("app.settings.roles.set")).toBe("roles");
|
||||
expect(deriveRoleEditorSectionId("app.settings.subscription.invoices.view")).toBe("billing");
|
||||
expect(deriveRoleEditorSectionId("app.settings.auditTrails.view")).toBe("auditSecurity");
|
||||
expect(deriveRoleEditorSectionId("privacy.user_export.self")).toBe("auditSecurity");
|
||||
expect(deriveRoleEditorSectionId("app.settings.apiKeys.view")).toBe("integrations");
|
||||
expect(deriveRoleEditorSectionId("files.read_all")).toBe("files");
|
||||
expect(deriveRoleEditorSectionId("tasks.write")).toBe("tasks");
|
||||
});
|
||||
|
||||
it("sends unknown scopes to otherModules instead of hiding them", () => {
|
||||
expect(deriveRoleEditorSectionId("crm.read_all")).toBe("otherModules");
|
||||
expect(deriveRoleEditorSectionId("automation.run")).toBe("otherModules");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildRoleEditorVM", () => {
|
||||
it("groups the catalog into ordered sections with enabled state", () => {
|
||||
const vm = buildRoleEditorVM({
|
||||
role: { id: "r1", name: "Monteur", description: "SHK" },
|
||||
appPermissions: CATALOG,
|
||||
assignedPermissionNames: ["app.dashboard.view", "tasks.write"],
|
||||
});
|
||||
expect(vm.status).toBe("ready");
|
||||
const data = vm.data!;
|
||||
expect(data.roleId).toBe("r1");
|
||||
const ids = data.sections.map((s) => s.id);
|
||||
// Order must follow ROLE_EDITOR_SECTION_IDS (David's sidebar order).
|
||||
expect(ids).toEqual(ROLE_EDITOR_SECTION_IDS.filter((id) => ids.includes(id)));
|
||||
expect(ids).toContain("otherModules");
|
||||
const general = data.sections.find((s) => s.id === "general")!;
|
||||
expect(general.labelKey).toBe("settings.rolesAndPermissions.editor.sections.general");
|
||||
expect(general.enabledCount).toBe(1);
|
||||
expect(data.enabledTotal).toBe(2);
|
||||
expect(data.permissionTotal).toBe(CATALOG.length);
|
||||
});
|
||||
|
||||
it("supports the create (M04A) and duplicate (M04B) entries", () => {
|
||||
const created = buildRoleEditorVM({ role: null, appPermissions: CATALOG, assignedPermissionNames: [] });
|
||||
expect(created.data!.roleId).toBeNull();
|
||||
expect(created.data!.name).toBe("");
|
||||
|
||||
const duplicated = buildRoleEditorVM({
|
||||
role: null,
|
||||
duplicatedFromName: "Monteur",
|
||||
appPermissions: CATALOG,
|
||||
assignedPermissionNames: ["files.read_all"],
|
||||
});
|
||||
expect(duplicated.data!.duplicatedFromName).toBe("Monteur");
|
||||
expect(duplicated.data!.enabledTotal).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterRoleEditorSections", () => {
|
||||
const sections = buildRoleEditorVM({ role: null, appPermissions: CATALOG, assignedPermissionNames: ["tasks.write"] }).data!.sections;
|
||||
|
||||
it("filters permissions across sections and drops empty sections", () => {
|
||||
const filtered = filterRoleEditorSections(sections, "subscription");
|
||||
expect(filtered.map((s) => s.id)).toEqual(["billing"]);
|
||||
expect(filtered[0].permissions.length).toBe(2);
|
||||
});
|
||||
|
||||
it("recomputes enabledCount and passes through on empty query", () => {
|
||||
expect(filterRoleEditorSections(sections, "tasks")[0].enabledCount).toBe(1);
|
||||
expect(filterRoleEditorSections(sections, " ").length).toBe(sections.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe("togglePermission", () => {
|
||||
it("adds and removes without mutating the source set", () => {
|
||||
const base = new Set(["a"]);
|
||||
const withB = togglePermission(base, "b", true);
|
||||
expect([...withB].sort()).toEqual(["a", "b"]);
|
||||
const withoutA = togglePermission(withB, "a", false);
|
||||
expect([...withoutA]).toEqual(["b"]);
|
||||
expect([...base]).toEqual(["a"]);
|
||||
});
|
||||
});
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* Role editor view-model (R-P2b, David's D-P2 `WF-P2 Admin RBAC` M02/M04A/M04B).
|
||||
* Pure function, no React/Prisma/app imports.
|
||||
*
|
||||
* The big editor groups the existing app permission catalog into David's
|
||||
* sidebar sections purely by permission-name scope (the part before the last
|
||||
* dot) — NO new permission keys and no schema change. Unknown scopes fall into
|
||||
* the "Weitere Module" section so nothing becomes invisible when new modules
|
||||
* land their permissions.
|
||||
*/
|
||||
|
||||
export type RoleEditorPermissionRow = {
|
||||
readonly name: string;
|
||||
/** Raw catalog description (screen upgrades it via permissionDisplayName(t)). */
|
||||
readonly description: string;
|
||||
readonly enabled: boolean;
|
||||
};
|
||||
|
||||
export type RoleEditorSection = {
|
||||
readonly id: string;
|
||||
/** i18n key: `settings.rolesAndPermissions.editor.sections.<id>` */
|
||||
readonly labelKey: string;
|
||||
readonly permissions: readonly RoleEditorPermissionRow[];
|
||||
readonly enabledCount: number;
|
||||
};
|
||||
|
||||
export interface RoleEditorData {
|
||||
/** null = creating a new role (M04A) — the editor posts to the create action. */
|
||||
readonly roleId: string | null;
|
||||
readonly name: string;
|
||||
readonly description: string;
|
||||
/** Duplicated-from source (M04B) shown in the hint block, null otherwise. */
|
||||
readonly duplicatedFromName: string | null;
|
||||
readonly sections: readonly RoleEditorSection[];
|
||||
readonly enabledTotal: number;
|
||||
readonly permissionTotal: number;
|
||||
}
|
||||
|
||||
export type RoleEditorVM = VMState<RoleEditorData>;
|
||||
|
||||
export interface RoleEditorInputPermission {
|
||||
readonly name: string;
|
||||
readonly description: string;
|
||||
}
|
||||
|
||||
export interface BuildRoleEditorVMInput {
|
||||
readonly role: { readonly id: string; readonly name: string; readonly description: string } | null;
|
||||
readonly duplicatedFromName?: string | null;
|
||||
readonly appPermissions: readonly RoleEditorInputPermission[];
|
||||
readonly assignedPermissionNames: readonly string[];
|
||||
}
|
||||
|
||||
/** Ordered section ids — mirrors David's M02 sidebar order. */
|
||||
export const ROLE_EDITOR_SECTION_IDS = [
|
||||
"general",
|
||||
"members",
|
||||
"roles",
|
||||
"workspace",
|
||||
"billing",
|
||||
"auditSecurity",
|
||||
"integrations",
|
||||
"files",
|
||||
"tasks",
|
||||
"otherModules",
|
||||
] as const;
|
||||
|
||||
export type RoleEditorSectionId = (typeof ROLE_EDITOR_SECTION_IDS)[number];
|
||||
|
||||
/**
|
||||
* scope (permission name without the trailing action) → section id. Longest
|
||||
* prefix wins so `app.settings.subscription.invoices` beats `app.settings`.
|
||||
*/
|
||||
const SCOPE_SECTIONS: ReadonlyArray<readonly [string, RoleEditorSectionId]> = [
|
||||
["app.dashboard", "general"],
|
||||
["dashboard", "general"],
|
||||
["search", "general"],
|
||||
["app.settings.members", "members"],
|
||||
["app.settings.groups", "members"],
|
||||
["app.settings.roles", "roles"],
|
||||
["app.settings.account", "workspace"],
|
||||
["app.settings.accounts", "workspace"],
|
||||
["app.plugins", "workspace"],
|
||||
["app.onboarding", "workspace"],
|
||||
["app.settings.subscription", "billing"],
|
||||
["app.settings.auditTrails", "auditSecurity"],
|
||||
["privacy", "auditSecurity"],
|
||||
["app.settings.apiKeys", "integrations"],
|
||||
["integrations", "integrations"],
|
||||
["email.domain", "integrations"],
|
||||
["files", "files"],
|
||||
["tasks", "tasks"],
|
||||
];
|
||||
|
||||
/** Splits a permission name into scope + trailing action (pure re-implementation). */
|
||||
export function parsePermissionScope(name: string): string {
|
||||
const parts = name.split(".");
|
||||
return parts.length < 2 ? name : parts.slice(0, -1).join(".");
|
||||
}
|
||||
|
||||
export function deriveRoleEditorSectionId(permissionName: string): RoleEditorSectionId {
|
||||
const scope = parsePermissionScope(permissionName);
|
||||
let match: RoleEditorSectionId | null = null;
|
||||
let matchLength = -1;
|
||||
for (const [prefix, sectionId] of SCOPE_SECTIONS) {
|
||||
if ((scope === prefix || scope.startsWith(`${prefix}.`)) && prefix.length > matchLength) {
|
||||
match = sectionId;
|
||||
matchLength = prefix.length;
|
||||
}
|
||||
}
|
||||
return match ?? "otherModules";
|
||||
}
|
||||
|
||||
export function buildRoleEditorVM(input: BuildRoleEditorVMInput): RoleEditorVM {
|
||||
const assigned = new Set(input.assignedPermissionNames);
|
||||
const grouped = new Map<RoleEditorSectionId, RoleEditorPermissionRow[]>();
|
||||
for (const permission of input.appPermissions) {
|
||||
const sectionId = deriveRoleEditorSectionId(permission.name);
|
||||
const rows = grouped.get(sectionId) ?? [];
|
||||
rows.push({
|
||||
name: permission.name,
|
||||
description: permission.description,
|
||||
enabled: assigned.has(permission.name),
|
||||
});
|
||||
grouped.set(sectionId, rows);
|
||||
}
|
||||
|
||||
const sections: RoleEditorSection[] = ROLE_EDITOR_SECTION_IDS.filter((id) => grouped.has(id)).map((id) => {
|
||||
const permissions = grouped.get(id) ?? [];
|
||||
return {
|
||||
id,
|
||||
labelKey: `settings.rolesAndPermissions.editor.sections.${id}`,
|
||||
permissions,
|
||||
enabledCount: permissions.filter((row) => row.enabled).length,
|
||||
};
|
||||
});
|
||||
|
||||
const permissionTotal = sections.reduce((sum, section) => sum + section.permissions.length, 0);
|
||||
const enabledTotal = sections.reduce((sum, section) => sum + section.enabledCount, 0);
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
roleId: input.role?.id ?? null,
|
||||
name: input.role?.name ?? "",
|
||||
description: input.role?.description ?? "",
|
||||
duplicatedFromName: input.duplicatedFromName ?? null,
|
||||
sections,
|
||||
enabledTotal,
|
||||
permissionTotal,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Editor search (M02): filters permission rows by a normalized query across the
|
||||
* raw name and description; sections without matches disappear. Display-label
|
||||
* search happens screen-side (needs `t`) — this pure filter covers the
|
||||
* name/description base so the behaviour is unit-testable.
|
||||
*/
|
||||
export function filterRoleEditorSections(sections: readonly RoleEditorSection[], query: string): RoleEditorSection[] {
|
||||
const normalized = query.trim().toUpperCase();
|
||||
if (!normalized) return [...sections];
|
||||
return sections
|
||||
.map((section) => {
|
||||
const permissions = section.permissions.filter((row) => `${row.name} ${row.description}`.toUpperCase().includes(normalized));
|
||||
return { ...section, permissions, enabledCount: permissions.filter((row) => row.enabled).length };
|
||||
})
|
||||
.filter((section) => section.permissions.length > 0);
|
||||
}
|
||||
|
||||
/** Applies a toggle to the (screen-held) enabled-set — pure helper for tests. */
|
||||
export function togglePermission(enabledNames: ReadonlySet<string>, permissionName: string, enabled: boolean): Set<string> {
|
||||
const next = new Set(enabledNames);
|
||||
if (enabled) next.add(permissionName);
|
||||
else next.delete(permissionName);
|
||||
return next;
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildRolesListVM,
|
||||
deriveRoleTypeKey,
|
||||
filterRolesRows,
|
||||
toRolesListModel,
|
||||
EMPTY_ROLES_FILTER,
|
||||
type RolesListInputRow,
|
||||
} from "../index.js";
|
||||
|
||||
const TENANT = "t1";
|
||||
|
||||
function inputRow(overrides: Partial<RolesListInputRow> = {}): RolesListInputRow {
|
||||
return {
|
||||
id: "r1",
|
||||
name: "Monteur",
|
||||
description: "SHK Monteur",
|
||||
isDefault: false,
|
||||
tenantId: TENANT,
|
||||
memberCount: 0,
|
||||
permissionCount: 4,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildVM(rows: RolesListInputRow[], canManageRoles = true) {
|
||||
return buildRolesListVM({ rows, tenantId: TENANT, canManageRoles });
|
||||
}
|
||||
|
||||
describe("deriveRoleTypeKey", () => {
|
||||
it("marks defaults and foreign/shared roles as system", () => {
|
||||
expect(deriveRoleTypeKey({ isDefault: true, tenantId: null }, TENANT)).toBe("system");
|
||||
expect(deriveRoleTypeKey({ isDefault: false, tenantId: null }, TENANT)).toBe("system");
|
||||
expect(deriveRoleTypeKey({ isDefault: false, tenantId: "other" }, TENANT)).toBe("system");
|
||||
expect(deriveRoleTypeKey({ isDefault: false, tenantId: TENANT }, TENANT)).toBe("custom");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildRolesListVM", () => {
|
||||
it("protects system roles and enables custom-role actions", () => {
|
||||
const vm = buildVM([inputRow({ id: "sys", name: "SuperUser", isDefault: true, tenantId: null }), inputRow()]);
|
||||
const [system, custom] = vm.data!.rows;
|
||||
expect(system.typeKey).toBe("system");
|
||||
expect(system.typeLabelKey).toBe("settings.rolesAndPermissions.type.system");
|
||||
expect(system.canEdit).toBe(false);
|
||||
expect(system.canDelete).toBe(false);
|
||||
expect(custom.typeKey).toBe("custom");
|
||||
expect(custom.canEdit).toBe(true);
|
||||
expect(custom.canDelete).toBe(true);
|
||||
expect(custom.deleteBlockedInUse).toBe(false);
|
||||
});
|
||||
|
||||
it("blocks delete when members are assigned (D03)", () => {
|
||||
const vm = buildVM([inputRow({ memberCount: 3 })]);
|
||||
const row = vm.data!.rows[0];
|
||||
expect(row.canDelete).toBe(true);
|
||||
expect(row.deleteBlockedInUse).toBe(true);
|
||||
});
|
||||
|
||||
it("removes all mutations without the manage permission", () => {
|
||||
const vm = buildVM([inputRow()], false);
|
||||
const row = vm.data!.rows[0];
|
||||
expect(row.canEdit).toBe(false);
|
||||
expect(row.canDuplicate).toBe(false);
|
||||
expect(row.canDelete).toBe(false);
|
||||
expect(vm.data!.canCreate).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterRolesRows", () => {
|
||||
const rows = buildVM([
|
||||
inputRow({ id: "sys", name: "SuperUser", description: "Has all app permissions", isDefault: true, tenantId: null, memberCount: 2 }),
|
||||
inputRow(),
|
||||
inputRow({ id: "r2", name: "Verwaltung", description: "Backoffice", memberCount: 1 }),
|
||||
]).data!.rows;
|
||||
|
||||
it("searches name and description", () => {
|
||||
expect(filterRolesRows(rows, { ...EMPTY_ROLES_FILTER, query: "backoffice" }).map((r) => r.id)).toEqual(["r2"]);
|
||||
});
|
||||
|
||||
it("filters by type and in-use", () => {
|
||||
expect(filterRolesRows(rows, { ...EMPTY_ROLES_FILTER, type: "system" }).map((r) => r.id)).toEqual(["sys"]);
|
||||
expect(filterRolesRows(rows, { ...EMPTY_ROLES_FILTER, inUse: true }).map((r) => r.id)).toEqual(["sys", "r2"]);
|
||||
expect(filterRolesRows(rows, { ...EMPTY_ROLES_FILTER, inUse: false }).map((r) => r.id)).toEqual(["r1"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toRolesListModel", () => {
|
||||
it("normalizes rows for the hot-swap renderers", () => {
|
||||
const model = toRolesListModel(buildVM([inputRow({ memberCount: 2 })]).data!);
|
||||
expect(model.titleKey).toBe("settings.members.tabs.rolesAndPermissions");
|
||||
expect(model.rows[0]).toMatchObject({ name: "Monteur", memberCount: 2, deleteBlockedInUse: true });
|
||||
expect(model.rowCount).toBe(1);
|
||||
});
|
||||
});
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* Roles & permissions admin list view-model (R-P2b, David's D-P2
|
||||
* `WF-P2 Admin RBAC` S02). Pure function, no React/Prisma/app imports.
|
||||
*
|
||||
* "System" rows are the seeded default roles (tenant-less, immutable per
|
||||
* `getTenantMutableAppRole`); everything the tenant owns is "custom" and can
|
||||
* be edited/duplicated/deleted. Deleting a role that still has members is
|
||||
* blocked (D03 dialog) — reassign flows are Backlog/V2 by design decision.
|
||||
*/
|
||||
|
||||
export type RoleTypeKey = "system" | "custom";
|
||||
|
||||
export type RolesListRow = {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly description: string;
|
||||
readonly typeKey: RoleTypeKey;
|
||||
/** i18n key for the type column badge. */
|
||||
readonly typeLabelKey: string;
|
||||
readonly memberCount: number;
|
||||
readonly permissionCount: number;
|
||||
readonly canEdit: boolean;
|
||||
readonly canDuplicate: boolean;
|
||||
/** Delete visible at all (custom roles only). */
|
||||
readonly canDelete: boolean;
|
||||
/** Delete visible but blocked because members are assigned (D03). */
|
||||
readonly deleteBlockedInUse: boolean;
|
||||
};
|
||||
|
||||
export type RolesListFilterState = {
|
||||
readonly query: string;
|
||||
readonly type: RoleTypeKey | null;
|
||||
/** true = only roles with members, false = only unused, null = all. */
|
||||
readonly inUse: boolean | null;
|
||||
};
|
||||
|
||||
export const EMPTY_ROLES_FILTER: RolesListFilterState = {
|
||||
query: "",
|
||||
type: null,
|
||||
inUse: null,
|
||||
};
|
||||
|
||||
export interface RolesListData {
|
||||
readonly rows: readonly RolesListRow[];
|
||||
readonly canCreate: boolean;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
readonly noMatchesKey: string;
|
||||
}
|
||||
|
||||
export type RolesListVM = VMState<RolesListData>;
|
||||
|
||||
/** Raw role row the loader passes in. */
|
||||
export interface RolesListInputRow {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly description: string;
|
||||
readonly isDefault: boolean;
|
||||
/** Owning tenant id, null for shared/seeded defaults. */
|
||||
readonly tenantId: string | null;
|
||||
readonly memberCount: number;
|
||||
readonly permissionCount: number;
|
||||
}
|
||||
|
||||
export interface BuildRolesListVMInput {
|
||||
readonly rows: readonly RolesListInputRow[];
|
||||
readonly tenantId: string;
|
||||
readonly canManageRoles: boolean;
|
||||
}
|
||||
|
||||
export function deriveRoleTypeKey(row: Pick<RolesListInputRow, "isDefault" | "tenantId">, tenantId: string): RoleTypeKey {
|
||||
return row.isDefault || row.tenantId === null || row.tenantId !== tenantId ? "system" : "custom";
|
||||
}
|
||||
|
||||
export function buildRolesListVM(input: BuildRolesListVMInput): RolesListVM {
|
||||
const rows: RolesListRow[] = input.rows.map((row) => {
|
||||
const typeKey = deriveRoleTypeKey(row, input.tenantId);
|
||||
const mutable = typeKey === "custom" && input.canManageRoles;
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
description: row.description,
|
||||
typeKey,
|
||||
typeLabelKey: `settings.rolesAndPermissions.type.${typeKey}`,
|
||||
memberCount: row.memberCount,
|
||||
permissionCount: row.permissionCount,
|
||||
canEdit: mutable,
|
||||
// System roles are read-only sources; duplicating them is allowed except for
|
||||
// protected defaults — David only protects the admin system role, but every
|
||||
// duplicate lands as a tenant-owned custom role anyway, so copying is safe.
|
||||
canDuplicate: input.canManageRoles,
|
||||
canDelete: mutable,
|
||||
deleteBlockedInUse: mutable && row.memberCount > 0,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows,
|
||||
canCreate: input.canManageRoles,
|
||||
emptyHeadlineKey: "settings.rolesAndPermissions.empty.title",
|
||||
emptyBodyKey: "settings.rolesAndPermissions.empty.description",
|
||||
noMatchesKey: "settings.rolesAndPermissions.empty.noMatches",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Client-side filter for S02 (search on name/description + type/in-use selects). */
|
||||
export function filterRolesRows(rows: readonly RolesListRow[], filter: RolesListFilterState): RolesListRow[] {
|
||||
const query = filter.query.trim().toUpperCase();
|
||||
return rows.filter((row) => {
|
||||
if (query) {
|
||||
const haystack = `${row.name} ${row.description}`.toUpperCase();
|
||||
if (!haystack.includes(query)) return false;
|
||||
}
|
||||
if (filter.type && row.typeKey !== filter.type) return false;
|
||||
if (filter.inUse !== null && row.memberCount > 0 !== filter.inUse) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
// --- Hot-swap component model (M015/M017) ---
|
||||
|
||||
export interface RolesListModelRow {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly typeLabelKey: string;
|
||||
readonly memberCount: number;
|
||||
readonly permissionCount: number;
|
||||
readonly canEdit: boolean;
|
||||
readonly canDelete: boolean;
|
||||
readonly deleteBlockedInUse: boolean;
|
||||
}
|
||||
|
||||
export interface RolesListModel {
|
||||
readonly titleKey: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
readonly canCreate: boolean;
|
||||
readonly rows: readonly RolesListModelRow[];
|
||||
readonly rowCount: number;
|
||||
}
|
||||
|
||||
export function toRolesListModel(data: RolesListData): RolesListModel {
|
||||
return {
|
||||
titleKey: "settings.members.tabs.rolesAndPermissions",
|
||||
emptyHeadlineKey: data.emptyHeadlineKey,
|
||||
emptyBodyKey: data.emptyBodyKey,
|
||||
canCreate: data.canCreate,
|
||||
rows: data.rows.map((row) => ({
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
typeLabelKey: row.typeLabelKey,
|
||||
memberCount: row.memberCount,
|
||||
permissionCount: row.permissionCount,
|
||||
canEdit: row.canEdit,
|
||||
canDelete: row.canDelete,
|
||||
deleteBlockedInUse: row.deleteBlockedInUse,
|
||||
})),
|
||||
rowCount: data.rows.length,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user