Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,52 @@
import { ready, type VMState } from "../index.js";
/**
* Lead anti-spam config view-model (R-P7, P7 Lead-Inbox). Pure function: the
* loader builds it from `leadService.getLeadAntiSpamConfig`. Mirrors the editable
* config fields 1:1 so the admin screen can render controls without re-deriving.
* No React / Prisma / server imports (DoD A.3).
*/
export type LeadAntiSpamMode = "quarantine" | "spam";
export interface LeadAntiSpamData {
readonly perSourcePerHourLimit: number;
readonly perIpPerHourLimit: number;
readonly anomalySpikeFactor: number;
readonly mode: LeadAntiSpamMode;
readonly disposableDomainEnabled: boolean;
readonly honeypotEnabled: boolean;
readonly fastSubmitEnabled: boolean;
readonly lostAutoDeleteDays: number;
readonly canWrite: boolean;
}
export type LeadAntiSpamVM = VMState<LeadAntiSpamData>;
export interface BuildLeadAntiSpamVMInput {
readonly config: {
readonly perSourcePerHourLimit: number;
readonly perIpPerHourLimit: number;
readonly anomalySpikeFactor: number;
readonly mode: LeadAntiSpamMode;
readonly disposableDomainEnabled: boolean;
readonly honeypotEnabled: boolean;
readonly fastSubmitEnabled: boolean;
readonly lostAutoDeleteDays: number;
};
readonly canWrite: boolean;
}
export function buildLeadAntiSpamVM(input: BuildLeadAntiSpamVMInput): LeadAntiSpamVM {
return ready<LeadAntiSpamData>({
perSourcePerHourLimit: input.config.perSourcePerHourLimit,
perIpPerHourLimit: input.config.perIpPerHourLimit,
anomalySpikeFactor: input.config.anomalySpikeFactor,
mode: input.config.mode,
disposableDomainEnabled: input.config.disposableDomainEnabled,
honeypotEnabled: input.config.honeypotEnabled,
fastSubmitEnabled: input.config.fastSubmitEnabled,
lostAutoDeleteDays: input.config.lostAutoDeleteDays,
canWrite: input.canWrite,
});
}
@@ -0,0 +1,159 @@
import { describe, expect, it } from "vitest";
import { buildLeadBoardVM, canTransitionLeadBoardStatus, isLeadBoardStatus, LEAD_BOARD_STATUSES, type LeadBoardCardSource } from "./lead-board.vm.js";
function row(id: string, over: Partial<LeadBoardCardSource> = {}): LeadBoardCardSource {
return {
id,
vorname: "Anna",
nachname: "Muster",
email: "anna@example.test",
telefon: null,
quelle: "form",
status: "new",
zustaendigerUserId: null,
createdAt: new Date("2026-07-01T08:00:00.000Z"),
...over,
};
}
describe("lead board view-model", () => {
it("returns an empty VM when rows are null", () => {
const vm = buildLeadBoardVM({
rows: null,
userLabels: new Map(),
perms: { canWrite: true },
listHref: "/acme/leads",
buildDetailHref: (id) => `/acme/leads/${id}`,
generatedAtIso: "2026-07-09T00:00:00.000Z",
});
expect(vm.status).toBe("empty");
});
it("maps rows into the four board columns and drops spam/quarantine leads", () => {
const vm = buildLeadBoardVM({
rows: [
row("l1", { status: "new" }),
row("l2", { status: "qualified", zustaendigerUserId: "u1" }),
row("l3", { status: "converted" }),
row("l4", { status: "lost" }),
row("l5", { status: "spam" }),
],
userLabels: new Map([["u1", "Raffael"]]),
perms: { canWrite: true },
listHref: "/acme/leads",
buildDetailHref: (id) => `/acme/leads/${id}`,
generatedAtIso: "2026-07-09T00:00:00.000Z",
countsByStatus: { new: 73, qualified: 1, converted: 1, lost: 1 },
});
if (vm.status !== "ready") throw new Error("expected ready");
expect(vm.data.columns.map((column) => column.status)).toEqual([...LEAD_BOARD_STATUSES]);
const counts = Object.fromEntries(vm.data.columns.map((column) => [column.status, column.count]));
expect(counts).toEqual({ new: 73, qualified: 1, converted: 1, lost: 1 });
expect(vm.data.columns.find((column) => column.status === "new")).toMatchObject({ loadedCount: 1, truncated: true });
// spam lead is not on any column
const allCardIds = vm.data.columns.flatMap((column) => column.cards.map((card) => card.id));
expect(allCardIds).not.toContain("l5");
});
it("builds card fields (display name, contact, quelle key, owner label) and detail hrefs", () => {
const vm = buildLeadBoardVM({
rows: [row("l2", { status: "qualified", zustaendigerUserId: "u1", email: null, telefon: "+49 30 1", vorname: null, nachname: null })],
userLabels: new Map([["u1", "Raffael"]]),
perms: { canWrite: true },
listHref: "/acme/leads",
buildDetailHref: (id) => `/acme/leads/${id}`,
generatedAtIso: "2026-07-09T00:00:00.000Z",
});
if (vm.status !== "ready") throw new Error("expected ready");
const card = vm.data.columns.find((column) => column.status === "qualified")!.cards[0];
expect(card).toMatchObject({
id: "l2",
displayName: "+49 30 1", // falls back to phone when no name/email
contact: "+49 30 1",
quelleLabelKey: "leads.quelle.form",
ownerLabel: "Raffael",
detailHref: "/acme/leads/l2",
allowedTargetStatuses: ["converted", "lost"],
});
});
it("exposes only the direct (non-spam) status transitions per card", () => {
const vm = buildLeadBoardVM({
rows: [row("n", { status: "new" }), row("q", { status: "qualified" }), row("c", { status: "converted" }), row("l", { status: "lost" })],
userLabels: new Map(),
perms: { canWrite: true },
listHref: "/acme/leads",
buildDetailHref: (id) => `/acme/leads/${id}`,
generatedAtIso: "2026-07-09T00:00:00.000Z",
});
if (vm.status !== "ready") throw new Error("expected ready");
const byId = new Map(vm.data.columns.flatMap((column) => column.cards).map((card) => [card.id, card.allowedTargetStatuses]));
expect(byId.get("n")).toEqual(["qualified", "lost"]);
expect(byId.get("q")).toEqual(["converted", "lost"]);
expect(byId.get("c")).toEqual([]); // terminal
expect(byId.get("l")).toEqual([]); // terminal
});
it("carries the write permission through", () => {
const vm = buildLeadBoardVM({
rows: [],
userLabels: new Map(),
perms: { canWrite: false },
listHref: "/acme/leads",
buildDetailHref: (id) => `/acme/leads/${id}`,
generatedAtIso: "2026-07-09T00:00:00.000Z",
});
if (vm.status !== "ready") throw new Error("expected ready");
expect(vm.data.canWrite).toBe(false);
});
it("appends a spam column only when asked for", () => {
const rows = [row("l1", { status: "new" }), row("l5", { status: "spam" })];
const base = {
userLabels: new Map(),
perms: { canWrite: true },
listHref: "/acme/leads",
buildDetailHref: (id: string) => `/acme/leads/${id}`,
generatedAtIso: "2026-07-09T00:00:00.000Z",
};
const hidden = buildLeadBoardVM({ ...base, rows });
if (hidden.status !== "ready") throw new Error("expected ready");
expect(hidden.data.includeSpam).toBe(false);
expect(hidden.data.columns.map((column) => column.status)).toEqual([...LEAD_BOARD_STATUSES]);
expect(hidden.data.columns.flatMap((column) => column.cards.map((card) => card.id))).not.toContain("l5");
const shown = buildLeadBoardVM({ ...base, rows, includeSpam: true });
if (shown.status !== "ready") throw new Error("expected ready");
expect(shown.data.includeSpam).toBe(true);
// Rightmost column, after the four draggable ones.
expect(shown.data.columns.map((column) => column.status)).toEqual([...LEAD_BOARD_STATUSES, "spam"]);
expect(shown.data.columns.at(-1)!.cards.map((card) => card.id)).toEqual(["l5"]);
});
it("lets nothing move into or out of the spam column", () => {
// Spam is terminal, and marking as spam schedules deletion — the list owns it.
const vm = buildLeadBoardVM({
rows: [row("l5", { status: "spam" })],
includeSpam: true,
userLabels: new Map(),
perms: { canWrite: true },
listHref: "/acme/leads",
buildDetailHref: (id) => `/acme/leads/${id}`,
generatedAtIso: "2026-07-09T00:00:00.000Z",
});
if (vm.status !== "ready") throw new Error("expected ready");
expect(vm.data.columns.at(-1)!.cards[0].allowedTargetStatuses).toEqual([]);
const targets = vm.data.columns.flatMap((column) => column.cards.flatMap((card) => card.allowedTargetStatuses));
expect(targets).not.toContain("spam");
});
it("guards transitions and status membership as pure helpers", () => {
expect(canTransitionLeadBoardStatus("new", "qualified")).toBe(true);
expect(canTransitionLeadBoardStatus("new", "converted")).toBe(false);
expect(canTransitionLeadBoardStatus("qualified", "new")).toBe(false); // backward
expect(canTransitionLeadBoardStatus("converted", "lost")).toBe(false); // terminal
expect(isLeadBoardStatus("spam")).toBe(false);
expect(isLeadBoardStatus("new")).toBe(true);
});
});
@@ -0,0 +1,165 @@
// R-P7 (P7 Lead-Inbox) Interim-UI (AD-28) — incoming-leads Kanban board VM.
// Pure function: the loader pulls the non-spam lead rows via leadService and this
// shapes them into the four board columns (Neu / Qualifiziert / Gewonnen /
// Verloren) the LeadBoardPage renders on top of the shared SortableKanbanBoard.
//
// Spam/quarantine leads are intentionally NOT a column and are dropped here. The
// board never moves a lead to "converted" silently — that stays a detail-page
// project conversion — so the VM only exposes the *direct* status transitions
// (`allowedTargetStatuses`) as a client-side pre-check. The server
// (setLeadStatus/assertStatusTransition) remains the source of truth and
// re-validates every move. No React / Prisma / server imports (DoD A.3).
import { empty, ready, type VMState } from "../index.js";
import { buildLeadDisplayName, leadQuelleLabelKey, type LeadQuelle, type LeadStatus } from "./lead-list.vm.js";
/** The four non-spam statuses that get a board column, in display order. */
export const LEAD_BOARD_STATUSES = ["new", "qualified", "converted", "lost"] as const;
/** Optional fifth column, appended on the right when the screen asks for it. */
export const LEAD_BOARD_SPAM_STATUS = "spam" as const;
export type LeadBoardDraggableStatus = (typeof LEAD_BOARD_STATUSES)[number];
export type LeadBoardStatus = LeadBoardDraggableStatus | typeof LEAD_BOARD_SPAM_STATUS;
/**
* Mirror of the leadService `ALLOWED_STATUS_TRANSITIONS`, restricted to the board
* columns (the `spam` target is excluded — leads become spam through the list, not
* the board). This only powers the client-side pre-check so an invalid drag snaps
* back without a round-trip; the server re-validates every accepted move.
*/
const BOARD_TRANSITIONS: Readonly<Record<LeadBoardStatus, readonly LeadBoardStatus[]>> = {
new: ["qualified", "lost"],
qualified: ["converted", "lost"],
converted: [],
lost: [],
// Marking a lead as spam schedules its deletion, so it stays a deliberate act
// in the list rather than something a drag does in passing. Spam itself is
// terminal, so nothing leaves the column either.
spam: [],
};
export function canTransitionLeadBoardStatus(from: LeadBoardStatus, to: LeadBoardStatus): boolean {
return from === to || BOARD_TRANSITIONS[from].includes(to);
}
export function isLeadBoardStatus(status: LeadStatus): status is LeadBoardStatus {
return (LEAD_BOARD_STATUSES as readonly string[]).includes(status);
}
interface LeadBoardColumnMeta {
readonly status: LeadBoardStatus;
readonly labelKey: string;
}
function boardColumnMeta(includeSpam: boolean): readonly LeadBoardColumnMeta[] {
const statuses: readonly LeadBoardStatus[] = includeSpam ? [...LEAD_BOARD_STATUSES, LEAD_BOARD_SPAM_STATUS] : LEAD_BOARD_STATUSES;
return statuses.map((status) => ({ status, labelKey: `leads.status.${status}` }));
}
/** Minimal lead row the board needs (mirrors the leadService `LeadRow` subset). */
export interface LeadBoardCardSource {
readonly id: string;
readonly vorname: string | null;
readonly nachname: string | null;
readonly email: string | null;
readonly telefon: string | null;
readonly quelle: LeadQuelle;
readonly status: LeadStatus;
readonly zustaendigerUserId: string | null;
readonly createdAt: Date;
}
export interface LeadBoardCard {
readonly id: string;
readonly displayName: string;
/** Secondary contact line (email, else phone). InboxLead has no company field. */
readonly contact: string | null;
readonly quelle: LeadQuelle;
readonly quelleLabelKey: string;
readonly status: LeadBoardStatus;
readonly ownerLabel: string | null;
readonly detailHref: string;
readonly createdAtIso: string;
/** Direct status targets allowed from this card (board columns only). */
readonly allowedTargetStatuses: readonly LeadBoardStatus[];
}
export interface LeadBoardColumn {
readonly status: LeadBoardStatus;
readonly labelKey: string;
readonly count: number;
readonly loadedCount: number;
readonly truncated: boolean;
readonly cards: readonly LeadBoardCard[];
}
export interface LeadBoardData {
readonly columns: readonly LeadBoardColumn[];
/** Whether the spam column is part of `columns` — drives the screen's checkbox. */
readonly includeSpam: boolean;
readonly canWrite: boolean;
readonly listHref: string;
readonly generatedAtIso: string;
}
export type LeadBoardVM = VMState<LeadBoardData>;
export interface BuildLeadBoardVMInput {
/** `null` => board never loaded (empty VM). Empty array => loaded, no leads. */
readonly rows: readonly LeadBoardCardSource[] | null;
/** Server-side totals per status. Cards may be windowed independently. */
readonly countsByStatus?: Readonly<Partial<Record<LeadBoardStatus, number>>>;
readonly userLabels: ReadonlyMap<string, string>;
readonly perms: { readonly canWrite: boolean };
/** Appends the spam column; mirrors the inbox's "Spam einblenden" checkbox. */
readonly includeSpam?: boolean;
readonly listHref: string;
readonly buildDetailHref: (leadId: string) => string;
readonly generatedAtIso: string;
}
export function buildLeadBoardVM(input: BuildLeadBoardVMInput): LeadBoardVM {
if (!input.rows) return empty<LeadBoardData>();
const includeSpam = input.includeSpam ?? false;
const columnMeta = boardColumnMeta(includeSpam);
const cardsByStatus = new Map<LeadBoardStatus, LeadBoardCard[]>(columnMeta.map((meta) => [meta.status, []]));
for (const row of input.rows) {
// Rows without a column are dropped — spam only gets one when asked for.
if (!cardsByStatus.has(row.status as LeadBoardStatus)) continue;
const card: LeadBoardCard = {
id: row.id,
displayName: buildLeadDisplayName(row),
contact: row.email ?? row.telefon ?? null,
quelle: row.quelle,
quelleLabelKey: leadQuelleLabelKey(row.quelle),
status: row.status as LeadBoardStatus,
ownerLabel: row.zustaendigerUserId ? (input.userLabels.get(row.zustaendigerUserId) ?? null) : null,
detailHref: input.buildDetailHref(row.id),
createdAtIso: row.createdAt.toISOString(),
allowedTargetStatuses: BOARD_TRANSITIONS[row.status as LeadBoardStatus],
};
cardsByStatus.get(row.status as LeadBoardStatus)!.push(card);
}
const columns: LeadBoardColumn[] = columnMeta.map((meta) => {
const cards = cardsByStatus.get(meta.status)!;
const count = input.countsByStatus?.[meta.status] ?? cards.length;
return {
status: meta.status,
labelKey: meta.labelKey,
count,
loadedCount: cards.length,
truncated: count > cards.length,
cards,
};
});
return ready<LeadBoardData>({
columns,
includeSpam,
canWrite: input.perms.canWrite,
listHref: input.listHref,
generatedAtIso: input.generatedAtIso,
});
}
@@ -0,0 +1,168 @@
import { empty, ready, type VMState } from "../index.js";
import {
buildLeadDisplayName,
leadFreigabeLabelKey,
leadQuelleLabelKey,
leadStatusLabelKey,
type LeadQuelle,
type LeadStatus,
type LeadWeiterverarbeitungFreigabe,
} from "./lead-list.vm.js";
/**
* Lead detail view-model (R-P7, P7 Lead-Inbox). Pure function: the loader builds
* it once server-side from the leadService `LeadRow`. All static texts are i18n
* KEYS; resolved values (zustaendigerLabel, source detail) are data. No React /
* Prisma / server imports (DoD A.3).
*/
export type LeadDetailMarker = "duplicate" | "spam" | "converted" | "quarantined";
/** One board stage the converted project can start in. */
export interface LeadConvertStageOption {
readonly id: string;
readonly label: string;
}
/** A board (Pipeline) the converted project can land on. */
export interface LeadConvertPipelineOption {
readonly id: string;
readonly label: string;
readonly stages: readonly LeadConvertStageOption[];
}
export interface LeadConvertContactOption {
readonly id: string;
readonly label: string;
}
/**
* Everything the convert dialog needs to create a Projekt from this lead.
*
* Board and stage are what the schema actually requires (`Projekt.pipelineId` /
* `stageId` are non-null); before this the conversion silently used the tenant's
* default sales pipeline, so every converted lead landed on the same board.
*/
export interface LeadConvertOptions {
readonly defaultProjektname: string;
readonly pipelines: readonly LeadConvertPipelineOption[];
readonly contacts: readonly LeadConvertContactOption[];
/** Contact matched by the lead's e-mail; preselected in the dialog. */
readonly suggestedKontaktId: string | null;
/** True when the contact list hit its cap — the dialog says so instead of
* pretending it shows every contact. */
readonly contactsTruncated: boolean;
}
export interface LeadDetailData {
readonly id: string;
readonly displayName: string;
readonly quelle: LeadQuelle;
readonly quelleLabelKey: string;
/** Free-form source origin (form name / mailbox / call id), if any. */
readonly sourceOrigin: string | null;
readonly status: LeadStatus;
readonly statusLabelKey: string;
readonly weiterverarbeitungFreigabe: LeadWeiterverarbeitungFreigabe;
readonly freigabeLabelKey: string;
readonly vorname: string | null;
readonly nachname: string | null;
readonly email: string | null;
readonly telefon: string | null;
readonly message: string | null;
readonly spamScore: number;
readonly spamReason: string | null;
readonly isQuarantined: boolean;
readonly markers: readonly LeadDetailMarker[];
readonly konvertiertProjektId: string | null;
readonly verknuepfterKontaktId: string | null;
/** DSGVO auto-delete deadline (ISO) — null = never. */
readonly autoDeleteAtIso: string | null;
readonly zustaendigerLabel: string | null;
readonly zustaendigerUserId: string | null;
readonly createdAtIso: string;
readonly updatedAtIso: string;
readonly listHref: string;
readonly canWrite: boolean;
/** null when the lead cannot be converted (or the boards are unreachable). */
readonly convert: LeadConvertOptions | null;
}
export type LeadDetailVM = VMState<LeadDetailData>;
/** Minimal lead source row (mirrors the leadService `LeadRow` fields the detail
* needs). Timestamps arrive as `Date` and are converted deterministically. */
export interface LeadDetailSource {
readonly id: string;
readonly quelle: LeadQuelle;
readonly sourceOrigin: string | null;
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 spamScore: number;
readonly spamReason: string | null;
readonly isQuarantined: boolean;
readonly konvertiertProjektId: string | null;
readonly verknuepfterKontaktId: string | null;
readonly autoDeleteAt: Date | null;
readonly zustaendigerUserId: string | null;
readonly createdAt: Date;
readonly updatedAt: Date;
}
export interface BuildLeadDetailVMInput {
readonly lead: LeadDetailSource | null;
readonly userLabels: ReadonlyMap<string, string>;
readonly isDuplicate?: boolean;
readonly perms: { readonly canWrite: boolean };
readonly tenantSlug: string;
readonly convert?: LeadConvertOptions | null;
}
export function buildLeadDetailVM(input: BuildLeadDetailVMInput): LeadDetailVM {
const lead = input.lead;
if (!lead) {
return empty<LeadDetailData>();
}
const markers: LeadDetailMarker[] = [];
if (input.isDuplicate) markers.push("duplicate");
if (lead.status === "spam" || lead.spamScore >= 50) markers.push("spam");
if (lead.isQuarantined) markers.push("quarantined");
if (lead.konvertiertProjektId || lead.status === "converted") markers.push("converted");
return ready<LeadDetailData>({
id: lead.id,
displayName: buildLeadDisplayName(lead),
quelle: lead.quelle,
quelleLabelKey: leadQuelleLabelKey(lead.quelle),
sourceOrigin: lead.sourceOrigin,
status: lead.status,
statusLabelKey: leadStatusLabelKey(lead.status),
weiterverarbeitungFreigabe: lead.weiterverarbeitungFreigabe,
freigabeLabelKey: leadFreigabeLabelKey(lead.weiterverarbeitungFreigabe),
vorname: lead.vorname,
nachname: lead.nachname,
email: lead.email,
telefon: lead.telefon,
message: lead.message,
spamScore: lead.spamScore,
spamReason: lead.spamReason,
isQuarantined: lead.isQuarantined,
markers,
konvertiertProjektId: lead.konvertiertProjektId,
verknuepfterKontaktId: lead.verknuepfterKontaktId,
autoDeleteAtIso: lead.autoDeleteAt ? lead.autoDeleteAt.toISOString() : null,
zustaendigerLabel: lead.zustaendigerUserId ? (input.userLabels.get(lead.zustaendigerUserId) ?? null) : null,
zustaendigerUserId: lead.zustaendigerUserId,
createdAtIso: lead.createdAt.toISOString(),
updatedAtIso: lead.updatedAt.toISOString(),
listHref: `/${input.tenantSlug}/leads`,
canWrite: input.perms.canWrite,
convert: input.convert ?? null,
});
}
@@ -14,7 +14,6 @@ describe("lead list view-model", () => {
const vm = buildLeadListVM({
tenantSlug: "acme",
createHref: "/acme/leads/new",
statisticsHref: "/acme/leads/statistics",
userLabels: new Map([["u1", "Raffael"]]),
duplicateLeadIds: new Set(["l1"]),
total: 2,
@@ -50,7 +50,6 @@ export interface LeadListData {
readonly canDelete: boolean;
readonly canReadAll: boolean;
readonly createHref: string;
readonly statisticsHref: string;
readonly emptyHeadlineKey: string;
readonly emptyBodyKey: string;
}
@@ -66,7 +65,6 @@ export interface BuildLeadListVMInput {
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 {
@@ -122,7 +120,6 @@ export function buildLeadListVM(input: BuildLeadListVMInput): LeadListVM {
canDelete: input.perms.canDelete,
canReadAll: input.perms.canReadAll,
createHref: input.createHref,
statisticsHref: input.statisticsHref,
emptyHeadlineKey: "leads.list.empty.headline",
emptyBodyKey: "leads.list.empty.body",
},
@@ -0,0 +1,83 @@
import { ready, type VMState } from "../index.js";
/**
* Lead source admin view-model (R-P7, P7 Lead-Inbox). Pure function: the loader
* builds it from `leadService.listLeadSources`. The webhook token itself is only
* stored hashed, so the VM surfaces whether a token exists (hasWebhookToken), not
* the plaintext. No React / Prisma / server imports (DoD A.3).
*/
export type LeadSourceType = "system" | "custom";
export interface LeadSourceAdminRow {
readonly id: string;
readonly type: LeadSourceType;
readonly typeLabelKey: string;
readonly key: string;
readonly name: string;
readonly displayLabel: string;
readonly defaultZustaendigerUserId: string | null;
/** Resolved name of the default owner, null when none is set. */
readonly defaultZustaendigerLabel: string | null;
readonly isPaused: boolean;
readonly hasWebhookToken: boolean;
readonly isDemoData: boolean;
}
export interface LeadSourceAdminOption {
readonly id: string;
readonly label: string;
}
export interface LeadSourceAdminData {
readonly rows: readonly LeadSourceAdminRow[];
/** Tenant members that can be picked as a source's default owner. */
readonly assignableUsers: readonly LeadSourceAdminOption[];
readonly canWrite: boolean;
}
export type LeadSourceAdminVM = VMState<LeadSourceAdminData>;
export interface LeadSourceAdminSourceRow {
readonly id: string;
readonly type: LeadSourceType;
readonly key: string;
readonly name: string;
readonly displayLabel: string;
readonly defaultZustaendigerUserId: string | null;
readonly webhookTokenHash: string | null;
readonly pausedAt: Date | null;
readonly isDemoData: boolean;
}
export interface BuildLeadSourceAdminVMInput {
readonly rows: readonly LeadSourceAdminSourceRow[];
readonly assignableUsers?: readonly LeadSourceAdminOption[];
readonly canWrite: boolean;
}
export function leadSourceTypeLabelKey(type: LeadSourceType): string {
return `leads.sources.type.${type}`;
}
export function buildLeadSourceAdminVM(input: BuildLeadSourceAdminVMInput): LeadSourceAdminVM {
const assignableUsers = input.assignableUsers ?? [];
const userLabel = new Map(assignableUsers.map((user) => [user.id, user.label]));
return ready<LeadSourceAdminData>({
rows: input.rows.map((row) => ({
id: row.id,
type: row.type,
typeLabelKey: leadSourceTypeLabelKey(row.type),
key: row.key,
name: row.name,
displayLabel: row.displayLabel,
defaultZustaendigerUserId: row.defaultZustaendigerUserId,
defaultZustaendigerLabel: row.defaultZustaendigerUserId ? (userLabel.get(row.defaultZustaendigerUserId) ?? null) : null,
isPaused: row.pausedAt !== null,
hasWebhookToken: row.webhookTokenHash !== null,
isDemoData: row.isDemoData,
})),
assignableUsers,
canWrite: input.canWrite,
});
}
@@ -0,0 +1,66 @@
import { ready, type VMState } from "../index.js";
import { leadQuelleLabelKey, leadStatusLabelKey, type LeadQuelle, type LeadStatus } from "./lead-list.vm.js";
/**
* Lead statistics view-model (R-P7, P7 Lead-Inbox). Pure function: the loader
* builds it from `leadService.getLeadStatistics` (total/new/converted/spam +
* by-source + by-status breakdowns). Richer breakdowns from the designer brief
* (reaction time, per-owner, weekday, trends) are NOT yet provided by the service
* and stay a tracked design-nachzug — this VM renders exactly what the backend
* exposes (no invented aggregates). No React / Prisma / server imports (DoD A.3).
*/
export type LeadStatKpi = "total" | "new" | "converted" | "spam";
export interface LeadStatKpiTile {
readonly key: LeadStatKpi;
readonly labelKey: string;
readonly value: number;
}
export interface LeadStatBreakdownRow {
readonly key: string;
readonly labelKey: string;
readonly count: number;
}
export interface LeadStatisticsData {
readonly kpis: readonly LeadStatKpiTile[];
readonly byQuelle: readonly LeadStatBreakdownRow[];
readonly byStatus: readonly LeadStatBreakdownRow[];
/** Verantwortlichen-breakdown is only shown with leads.read_all (brief). */
readonly canReadAll: boolean;
readonly listHref: string;
}
export type LeadStatisticsVM = VMState<LeadStatisticsData>;
export interface BuildLeadStatisticsVMInput {
readonly stats: {
readonly total: number;
readonly new: number;
readonly converted: number;
readonly spam: number;
readonly byQuelle: readonly { readonly quelle: LeadQuelle; readonly count: number }[];
readonly byStatus: readonly { readonly status: LeadStatus; readonly count: number }[];
};
readonly canReadAll: boolean;
readonly listHref: string;
}
export function buildLeadStatisticsVM(input: BuildLeadStatisticsVMInput): LeadStatisticsVM {
const { stats } = input;
const kpis: LeadStatKpiTile[] = [
{ key: "total", labelKey: "leads.statistics.card.total", value: stats.total },
{ key: "new", labelKey: "leads.statistics.card.new", value: stats.new },
{ key: "converted", labelKey: "leads.statistics.card.converted", value: stats.converted },
{ key: "spam", labelKey: "leads.statistics.card.spam", value: stats.spam },
];
return ready<LeadStatisticsData>({
kpis,
byQuelle: stats.byQuelle.map((row) => ({ key: row.quelle, labelKey: leadQuelleLabelKey(row.quelle), count: row.count })),
byStatus: stats.byStatus.map((row) => ({ key: row.status, labelKey: leadStatusLabelKey(row.status), count: row.count })),
canReadAll: input.canReadAll,
listHref: input.listHref,
});
}
@@ -0,0 +1,99 @@
// R-P7 interim-UI (AD-28) — unit tests for the four new Lead view-models
// (detail / statistics / source-admin / anti-spam). Pure fixture -> assert.
import { describe, expect, it } from "vitest";
import { buildLeadDetailVM, type LeadDetailSource } from "./lead-detail.vm.js";
import { buildLeadStatisticsVM } from "./lead-statistics.vm.js";
import { buildLeadSourceAdminVM } from "./lead-source-admin.vm.js";
import { buildLeadAntiSpamVM } from "./lead-anti-spam.vm.js";
function leadSource(over: Partial<LeadDetailSource> = {}): LeadDetailSource {
return {
id: "l1",
quelle: "form",
sourceOrigin: "Kontaktformular",
status: "new",
weiterverarbeitungFreigabe: "unklar",
vorname: "Anna",
nachname: "Muster",
email: "anna@example.com",
telefon: null,
message: "Bitte um Rückruf",
spamScore: 10,
spamReason: null,
isQuarantined: false,
konvertiertProjektId: null,
verknuepfterKontaktId: null,
autoDeleteAt: null,
zustaendigerUserId: "u1",
createdAt: new Date("2026-06-01T10:00:00.000Z"),
updatedAt: new Date("2026-06-02T10:00:00.000Z"),
...over,
};
}
describe("buildLeadDetailVM", () => {
it("maps a lead into a ready VM with label keys + resolved owner", () => {
const vm = buildLeadDetailVM({ lead: leadSource(), userLabels: new Map([["u1", "Owner One"]]), perms: { canWrite: true }, tenantSlug: "acme" });
expect(vm.status).toBe("ready");
expect(vm.data?.displayName).toBe("Anna Muster");
expect(vm.data?.statusLabelKey).toBe("leads.status.new");
expect(vm.data?.zustaendigerLabel).toBe("Owner One");
expect(vm.data?.listHref).toBe("/acme/leads");
});
it("returns empty when the lead is missing", () => {
const vm = buildLeadDetailVM({ lead: null, userLabels: new Map(), perms: { canWrite: false }, tenantSlug: "acme" });
expect(vm.status).toBe("empty");
});
it("flags spam + converted markers and the DSGVO deadline", () => {
const vm = buildLeadDetailVM({
lead: leadSource({ status: "converted", konvertiertProjektId: "p1", spamScore: 70, autoDeleteAt: new Date("2026-07-01T00:00:00.000Z") }),
userLabels: new Map(),
perms: { canWrite: true },
tenantSlug: "acme",
});
expect(vm.data?.markers).toEqual(expect.arrayContaining(["spam", "converted"]));
expect(vm.data?.autoDeleteAtIso).toBe("2026-07-01T00:00:00.000Z");
});
});
describe("buildLeadStatisticsVM", () => {
it("builds the four KPI tiles + breakdowns from the service shape", () => {
const vm = buildLeadStatisticsVM({
stats: { total: 10, new: 4, converted: 3, spam: 1, byQuelle: [{ quelle: "form", count: 6 }], byStatus: [{ status: "new", count: 4 }] },
canReadAll: true,
listHref: "/acme/leads",
});
expect(vm.data?.kpis.map((k) => k.key)).toEqual(["total", "new", "converted", "spam"]);
expect(vm.data?.kpis[0].value).toBe(10);
expect(vm.data?.byQuelle[0]).toEqual({ key: "form", labelKey: "leads.quelle.form", count: 6 });
expect(vm.data?.byStatus[0].labelKey).toBe("leads.status.new");
expect(vm.data?.canReadAll).toBe(true);
});
});
describe("buildLeadSourceAdminVM", () => {
it("derives paused + webhook-token presence from the raw rows", () => {
const vm = buildLeadSourceAdminVM({
rows: [
{ id: "s1", type: "custom", key: "landingpage", name: "Landingpage", displayLabel: "Landingpage", webhookTokenHash: "abc", pausedAt: new Date("2026-06-01"), isDemoData: false },
{ id: "s2", type: "system", key: "form", name: "Formular", displayLabel: "Formular", webhookTokenHash: null, pausedAt: null, isDemoData: false },
],
canWrite: true,
});
expect(vm.data?.rows[0]).toEqual(expect.objectContaining({ id: "s1", isPaused: true, hasWebhookToken: true, typeLabelKey: "leads.sources.type.custom" }));
expect(vm.data?.rows[1]).toEqual(expect.objectContaining({ isPaused: false, hasWebhookToken: false }));
});
});
describe("buildLeadAntiSpamVM", () => {
it("mirrors the config fields for the admin form", () => {
const vm = buildLeadAntiSpamVM({
config: { perSourcePerHourLimit: 60, perIpPerHourLimit: 20, anomalySpikeFactor: 10, mode: "quarantine", disposableDomainEnabled: true, honeypotEnabled: true, fastSubmitEnabled: false, lostAutoDeleteDays: 90 },
canWrite: true,
});
expect(vm.data).toEqual(expect.objectContaining({ perSourcePerHourLimit: 60, mode: "quarantine", fastSubmitEnabled: false, lostAutoDeleteDays: 90, canWrite: true }));
});
});