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,92 @@
// R-P7 interim-UI (AD-28) — LeadAntiSpamAdminPage unit test. Fixture VM via the real
// buildLeadAntiSpamVM; asserts the save callback carries edited values + the "on"
// boolean convention. i18n mocked.
import { fireEvent, render } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildLeadAntiSpamVM } from "@hivegrid/view-models";
import { LeadAntiSpamAdminPage, type LeadAntiSpamAdminActions } from "./LeadAntiSpamAdminPage";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }) }));
const vm = buildLeadAntiSpamVM({
config: { perSourcePerHourLimit: 60, perIpPerHourLimit: 20, anomalySpikeFactor: 10, mode: "quarantine", disposableDomainEnabled: true, honeypotEnabled: true, fastSubmitEnabled: false, lostAutoDeleteDays: 0 },
canWrite: true,
});
function actions(over: Partial<LeadAntiSpamAdminActions> = {}): LeadAntiSpamAdminActions {
return { onSave: vi.fn(), ...over };
}
describe("LeadAntiSpamAdminPage", () => {
it("saves the edited config with the 'on' boolean convention", () => {
const onSave = vi.fn();
render(<LeadAntiSpamAdminPage vm={vm} submitting={false} errorKey={null} actions={actions({ onSave })} />);
fireEvent.change(document.querySelector("[data-ui-id='ui.leads.antiSpam.perSourcePerHourLimit']")!, { target: { value: "80" } });
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.antiSpam.save']")!);
expect(onSave).toHaveBeenCalledTimes(1);
const arg = onSave.mock.calls[0][0];
expect(arg.perSourcePerHourLimit).toBe("80");
expect(arg.disposableDomainEnabled).toBe("on");
expect(arg.fastSubmitEnabled).toBeUndefined();
});
it("groups the settings by what they do", () => {
// Detection signals, hourly limits, the reaction to a high score and the
// retention field are four different decisions — a flat list gave no clue
// which knob does what.
render(<LeadAntiSpamAdminPage vm={vm} submitting={false} errorKey={null} actions={actions()} />);
for (const section of ["detection", "limits", "reaction", "retention"]) {
expect(document.querySelector(`[data-ui-id='ui.leads.antiSpam.${section}']`)).not.toBeNull();
}
});
it("puts the save button in the header row, not below the last section", () => {
// Four sections deep, a footer button sits below the fold — the header row
// is where the black primary action lives on the other pages.
render(<LeadAntiSpamAdminPage vm={vm} submitting={false} errorKey={null} actions={actions()} />);
const save = document.querySelector("[data-ui-id='ui.leads.antiSpam.save']")!;
const firstSection = document.querySelector("[data-ui-id='ui.leads.antiSpam.detection']")!;
expect(save.compareDocumentPosition(firstSection) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
it("keeps the checkbox label pinned to the start so hover cannot shift it", () => {
// The Subframe checkbox is a justify-between button: stretched to full width
// the label sits flush right and snaps left on hover.
render(<LeadAntiSpamAdminPage vm={vm} submitting={false} errorKey={null} actions={actions()} />);
const box = document.querySelector("[data-ui-id='ui.leads.antiSpam.honeypotEnabled']")!;
expect(box.className).toContain("justify-start");
});
it("mirrors the server-side minimums on the number inputs", () => {
// updateLeadAntiSpamConfig clamps instead of rejecting, so without a min the
// browser would happily send a value that is silently stored as another one.
render(<LeadAntiSpamAdminPage vm={vm} submitting={false} errorKey={null} actions={actions()} />);
expect(document.querySelector("[data-ui-id='ui.leads.antiSpam.anomalySpikeFactor']")!.getAttribute("min")).toBe("2");
expect(document.querySelector("[data-ui-id='ui.leads.antiSpam.lostAutoDeleteDays']")!.getAttribute("min")).toBe("0");
});
it("follows the view-model when the server stored something else", () => {
const { rerender } = render(<LeadAntiSpamAdminPage vm={vm} submitting={false} errorKey={null} actions={actions()} />);
const input = () => document.querySelector("[data-ui-id='ui.leads.antiSpam.anomalySpikeFactor']") as HTMLInputElement;
fireEvent.change(input(), { target: { value: "1" } });
expect(input().value).toBe("1");
// What the server clamped 1 up to. The form must show that, not the rejected input.
const saved = buildLeadAntiSpamVM({
config: { perSourcePerHourLimit: 60, perIpPerHourLimit: 20, anomalySpikeFactor: 2, mode: "quarantine", disposableDomainEnabled: true, honeypotEnabled: true, fastSubmitEnabled: false, lostAutoDeleteDays: 0 },
canWrite: true,
});
rerender(<LeadAntiSpamAdminPage vm={saved} submitting={false} errorKey={null} actions={actions()} />);
expect(input().value).toBe("2");
});
it("does not offer saving without write permission", () => {
const readOnly = buildLeadAntiSpamVM({
config: { perSourcePerHourLimit: 60, perIpPerHourLimit: 20, anomalySpikeFactor: 10, mode: "quarantine", disposableDomainEnabled: true, honeypotEnabled: true, fastSubmitEnabled: false, lostAutoDeleteDays: 0 },
canWrite: false,
});
render(<LeadAntiSpamAdminPage vm={readOnly} submitting={false} errorKey={null} actions={actions()} />);
expect(document.querySelector("[data-ui-id='ui.leads.antiSpam.save']")!.hasAttribute("disabled")).toBe(true);
});
});
@@ -0,0 +1,233 @@
// R-P7 (P7 Lead-Inbox) Interim-UI (AD-28) — lead anti-spam settings (D-P7
// "Anti-Spam-Settings", archetype A6), composed from ~/ui. Pure: renders the
// server-built LeadAntiSpamVM and calls actions.onSave with the edited config; the
// route POSTs it. No useLoaderData. Final Subframe optics = tracked design-nachzug.
//
// The settings are grouped the way the scoring pipeline actually works, because a
// flat list of seven fields gave no clue which knob does what: signals raise a
// lead's spam score (detection + limits), the mode decides what happens once the
// score is high, and the retention field is not spam detection at all.
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherShieldCheck } from "@subframe/core";
import type { LeadAntiSpamData, LeadAntiSpamVM } from "@hivegrid/view-models";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Card } from "~/ui/components/Card";
import { Checkbox } from "~/ui/components/Checkbox";
import { Select } from "~/ui/components/Select";
import { TextInput } from "~/ui/components/TextInput";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
/** Config fields for the anti-spam save action. Numbers arrive as strings;
* booleans as "on" (checked) so the route's `=== "on"` check matches. */
export type LeadAntiSpamSaveInput = {
mode: string;
perSourcePerHourLimit: string;
perIpPerHourLimit: string;
anomalySpikeFactor: string;
lostAutoDeleteDays: string;
disposableDomainEnabled?: string;
honeypotEnabled?: string;
fastSubmitEnabled?: string;
};
export type LeadAntiSpamAdminActions = { onSave: (input: LeadAntiSpamSaveInput) => void };
export type LeadAntiSpamAdminPageProps = {
vm: LeadAntiSpamVM;
submitting: boolean;
errorKey?: string | null;
actions: LeadAntiSpamAdminActions;
};
const MODES = ["quarantine", "spam"] as const;
const sectionHeading = "text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary";
const mutedText = "text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary";
// Number inputs share the card width evenly instead of sizing themselves by
// content — same rule as the lead-source and custom-field admin forms.
const fieldWidth = "w-full min-w-0 sm:w-auto sm:shrink sm:grow sm:basis-0";
// The Subframe checkbox is a `justify-between` button, so in a stretch container
// the label sits flush right and jumps left on hover (the label wrapper only gets
// its `grow/basis-0` in the hover state). Pinning it to the start kills the jump.
const checkboxRow = "w-full justify-start";
// Server-side clamps in leadService.updateLeadAntiSpamConfig. Mirrored here so the
// browser rejects the value instead of the server silently storing a different one.
const NUMBER_MIN = { perSourcePerHourLimit: 1, perIpPerHourLimit: 1, anomalySpikeFactor: 2, lostAutoDeleteDays: 0 } as const;
type NumberField = keyof typeof NUMBER_MIN;
function formFromVm(data: LeadAntiSpamData) {
return {
mode: data.mode,
perSourcePerHourLimit: String(data.perSourcePerHourLimit),
perIpPerHourLimit: String(data.perIpPerHourLimit),
anomalySpikeFactor: String(data.anomalySpikeFactor),
lostAutoDeleteDays: String(data.lostAutoDeleteDays),
disposableDomainEnabled: data.disposableDomainEnabled,
honeypotEnabled: data.honeypotEnabled,
fastSubmitEnabled: data.fastSubmitEnabled,
};
}
export function LeadAntiSpamAdminPage(props: LeadAntiSpamAdminPageProps) {
const { t } = useTranslation();
const data = props.vm.status === "ready" ? props.vm.data : null;
const [form, setForm] = useState(() =>
data
? formFromVm(data)
: {
mode: "quarantine" as const satisfies (typeof MODES)[number],
perSourcePerHourLimit: "60",
perIpPerHourLimit: "20",
anomalySpikeFactor: "10",
lostAutoDeleteDays: "0",
disposableDomainEnabled: true,
honeypotEnabled: true,
fastSubmitEnabled: false,
}
);
const set = (patch: Partial<typeof form>) => setForm((s) => ({ ...s, ...patch }));
// Read back what the server actually stored. It clamps (a spike factor of 1
// becomes 2) and drops unparseable numbers, so without this the form would keep
// showing a value that was never saved.
const vmSignature = data ? JSON.stringify(data) : null;
const lastVmSignature = useRef(vmSignature);
useEffect(() => {
if (!data || lastVmSignature.current === vmSignature) return;
lastVmSignature.current = vmSignature;
setForm(formFromVm(data));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [vmSignature]);
if (!data) {
return <div className="flex w-full flex-col gap-6 p-6" data-ui-id="ui.leads.antiSpam" />;
}
const numberField = (key: NumberField, labelKey: string, hintKey: string) => (
<TextInput className={fieldWidth} label={t(labelKey)} showLabel helpText={t(hintKey)}>
<TextInput.Input
type="number"
min={NUMBER_MIN[key]}
value={form[key]}
onChange={(e) => set({ [key]: e.target.value } as Partial<typeof form>)}
data-ui-id={`ui.leads.antiSpam.${key}`}
/>
</TextInput>
);
function save() {
props.actions.onSave({
mode: form.mode,
perSourcePerHourLimit: form.perSourcePerHourLimit,
perIpPerHourLimit: form.perIpPerHourLimit,
anomalySpikeFactor: form.anomalySpikeFactor,
lostAutoDeleteDays: form.lostAutoDeleteDays,
...(form.disposableDomainEnabled ? { disposableDomainEnabled: "on" } : {}),
...(form.honeypotEnabled ? { honeypotEnabled: "on" } : {}),
...(form.fastSubmitEnabled ? { fastSubmitEnabled: "on" } : {}),
});
}
return (
<PageShell uiId="ui.leads.antiSpam">
<PageHeader
icon={<FeatherShieldCheck className={PAGE_HEADER_ICON_CLASS} />}
title={t("leads.antiSpam.title")}
subtitle={t("leads.antiSpam.subtitle")}
actions={
<Button loading={props.submitting} disabled={!data.canWrite} onClick={save} data-ui-id="ui.leads.antiSpam.save">
{t("leads.actions.save")}
</Button>
}
/>
<PageBody>
{props.errorKey ? <BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback> : null}
{/* --- Signals: what makes a lead suspicious --- */}
<Card data-ui-id="ui.leads.antiSpam.detection">
<span className={sectionHeading}>{t("leads.antiSpam.section.detection")}</span>
<span className={mutedText}>{t("leads.antiSpam.section.detectionHint")}</span>
<div className="flex w-full flex-col gap-3">
<Checkbox
className={checkboxRow}
checked={form.disposableDomainEnabled}
onCheckedChange={(c) => set({ disposableDomainEnabled: c })}
label={t("leads.antiSpam.field.disposable")}
description={t("leads.antiSpam.hint.disposable")}
data-ui-id="ui.leads.antiSpam.disposableDomainEnabled"
/>
<Checkbox
className={checkboxRow}
checked={form.honeypotEnabled}
onCheckedChange={(c) => set({ honeypotEnabled: c })}
label={t("leads.antiSpam.field.honeypot")}
description={t("leads.antiSpam.hint.honeypot")}
data-ui-id="ui.leads.antiSpam.honeypotEnabled"
/>
<Checkbox
className={checkboxRow}
checked={form.fastSubmitEnabled}
onCheckedChange={(c) => set({ fastSubmitEnabled: c })}
label={t("leads.antiSpam.field.fastSubmit")}
description={t("leads.antiSpam.hint.fastSubmit")}
data-ui-id="ui.leads.antiSpam.fastSubmitEnabled"
/>
</div>
</Card>
{/* --- Rate signals: same scoring pipeline, but counted per hour --- */}
<Card data-ui-id="ui.leads.antiSpam.limits">
<span className={sectionHeading}>{t("leads.antiSpam.section.limits")}</span>
<span className={mutedText}>{t("leads.antiSpam.section.limitsHint")}</span>
{/* items-start, not items-end: the help texts differ in length and would
otherwise drag the inputs off a shared baseline. */}
<div className="flex w-full flex-col items-stretch gap-4 sm:flex-row sm:items-start">
{numberField("perSourcePerHourLimit", "leads.antiSpam.field.perSource", "leads.antiSpam.hint.perSource")}
{numberField("perIpPerHourLimit", "leads.antiSpam.field.perIp", "leads.antiSpam.hint.perIp")}
{numberField("anomalySpikeFactor", "leads.antiSpam.field.spike", "leads.antiSpam.hint.spike")}
</div>
</Card>
{/* --- Reaction: what a high score does --- */}
<Card data-ui-id="ui.leads.antiSpam.reaction">
<span className={sectionHeading}>{t("leads.antiSpam.section.reaction")}</span>
<span className={mutedText}>{t("leads.antiSpam.section.reactionHint")}</span>
<Select
className="w-full sm:max-w-[280px]"
label={t("leads.antiSpam.field.mode")}
showLabel
value={form.mode}
onValueChange={(v) => set({ mode: v as typeof form.mode })}
data-ui-id="ui.leads.antiSpam.mode"
>
{MODES.map((m) => (
<Select.Item key={m} value={m}>
{t(`leads.antiSpam.mode.${m}`)}
</Select.Item>
))}
</Select>
</Card>
{/* --- Retention: not spam detection, hence its own section --- */}
<Card data-ui-id="ui.leads.antiSpam.retention">
<span className={sectionHeading}>{t("leads.antiSpam.section.retention")}</span>
<span className={mutedText}>{t("leads.antiSpam.section.retentionHint")}</span>
<div className="flex w-full flex-col items-stretch gap-4 sm:flex-row sm:items-start">
{numberField("lostAutoDeleteDays", "leads.antiSpam.field.lostDelete", "leads.antiSpam.hint.lostDelete")}
{/* Keeps the single field at the same width as the limit row above. */}
<div className={`hidden sm:block ${fieldWidth}`} />
<div className={`hidden sm:block ${fieldWidth}`} />
</div>
</Card>
</PageBody>
</PageShell>
);
}
export default LeadAntiSpamAdminPage;
@@ -0,0 +1,186 @@
// R-P7 interim-UI (AD-28) — LeadBoardPage unit test. Fixture built via the real
// buildLeadBoardVM; interactions asserted on injected callbacks. i18n mocked.
// SortableKanbanBoard is stubbed so a "drag-end" is simulated by invoking its
// onCardMove prop directly — this keeps the test deterministic (no dnd-kit layout
// math in jsdom) while still exercising the screen's requestMove routing.
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildLeadBoardVM, type LeadBoardData, type LeadBoardCardSource } from "@hivegrid/view-models";
import { LeadBoardPage, type LeadBoardActions } from "./LeadBoardPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }),
}));
// Radix dropdowns neither open nor provide their menu context in jsdom, so the
// filter bar's facet options would be unreachable. Both the SubframeCore wrapper
// and the ~/ui menu are swapped for passthroughs; the entries stay real buttons.
vi.mock("@subframe/core", async () => {
const actual = await vi.importActual<Record<string, unknown>>("@subframe/core");
const Pass = ({ children }: { children?: React.ReactNode }) => <>{children}</>;
return { ...actual, DropdownMenu: { Root: Pass, Trigger: Pass, Portal: Pass, Content: Pass, Item: Pass } };
});
vi.mock("~/ui/components/DropdownMenuMultiSelect", () => {
const DropdownMenuMultiSelect = ({ children }: { children?: React.ReactNode }) => <div>{children}</div>;
DropdownMenuMultiSelect.DropdownItem = ({ children, onClick, selected, ...rest }: any) => (
<button type="button" onClick={onClick} aria-pressed={Boolean(selected)} data-ui-id={rest["data-ui-id"]}>
{children}
</button>
);
DropdownMenuMultiSelect.DropdownCustomItem = ({ children }: any) => <div>{children}</div>;
DropdownMenuMultiSelect.DropdownUserItem = ({ title }: any) => <div>{title}</div>;
DropdownMenuMultiSelect.DropdownDivider = () => <hr />;
return { DropdownMenuMultiSelect };
});
// Stub the shared board: render each card via the real renderCard slot and expose
// one "move" button per (card, target column) that fires onCardMove — the same
// signal a real drag-end emits.
vi.mock("~/components/ui/kanban/SortableKanbanBoard", () => ({
SortableKanbanBoard: (p: {
columns: { id: string; name: React.ReactNode; sumMode?: "visible" | "locked" | "hidden"; cards: { id: string }[] }[];
renderCard: (card: { id: string }) => React.ReactNode;
onCardMove: (cardId: string, toColumnId: string, toIndex: number) => void;
}) => (
<div data-ui-id="ui.leads.board.columns">
{p.columns.map((col) => (
<div key={col.id} data-ui-id={`stub.col.${col.id}`} data-sum-mode={col.sumMode}>
<span>{col.name}</span>
{col.cards.map((card) => (
<div key={card.id}>
{p.renderCard(card)}
{p.columns
.filter((target) => target.id !== col.id)
.map((target) => (
<button key={target.id} type="button" data-ui-id={`stub.move.${card.id}.${target.id}`} onClick={() => p.onCardMove(card.id, target.id, 0)} />
))}
</div>
))}
</div>
))}
</div>
),
}));
const byUiId = (id: string) => document.querySelector(`[data-ui-id='${id}']`) as HTMLElement;
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,
};
}
function boardData(includeSpam = false): LeadBoardData {
const vm = buildLeadBoardVM({
rows: [row("l1", { status: "new" }), row("l2", { status: "qualified" }), row("l3", { status: "converted" }), row("l5", { status: "spam" })],
includeSpam,
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("fixture not ready");
return vm.data;
}
function renderPage(over: Partial<LeadBoardActions> = {}, includeSpam = false) {
const actions: LeadBoardActions = {
onSetStatus: vi.fn(),
onOpenList: vi.fn(),
onNew: vi.fn(),
onSearch: vi.fn(),
onToggleSpam: vi.fn(),
onResetFilters: vi.fn(),
...over,
};
render(<LeadBoardPage data={boardData(includeSpam)} search="" submitting={false} actions={actions} />);
return actions;
}
describe("LeadBoardPage", () => {
it("hides the spam column until the checkbox asks for it", () => {
renderPage();
expect(byUiId("ui.leads.board.card.l5")).toBeNull();
expect(document.querySelector("[data-ui-id='stub.col.spam']")).toBeNull();
});
it("shows the spam column as the rightmost one when enabled", () => {
renderPage({}, true);
expect(byUiId("ui.leads.board.card.l5")).toBeTruthy();
const columns = [...document.querySelectorAll("[data-sum-mode]")].map((node) => node.getAttribute("data-ui-id"));
expect(columns.at(-1)).toBe("stub.col.spam");
});
it("toggles the spam column through the injected callback", () => {
const { onToggleSpam } = renderPage();
fireEvent.click(byUiId("ui.leads.board.filter.visibility.spam"));
expect(onToggleSpam).toHaveBeenCalledWith(true);
});
it("takes the spam visibility back off once it is on", () => {
const { onToggleSpam } = renderPage({}, true);
fireEvent.click(byUiId("ui.leads.board.filter.visibility.spam"));
expect(onToggleSpam).toHaveBeenCalledWith(false);
});
it("wears the same shared filter bar as the list view", () => {
const { onResetFilters } = renderPage({}, true);
expect(byUiId("ui.leads.board.filter")).toBeTruthy();
expect(byUiId("ui.leads.board.filter.search")).toBeTruthy();
// Search and spam visibility clear in ONE navigation, not two racing ones.
fireEvent.click(screen.getByText("leads.filter.resetAll"));
expect(onResetFilters).toHaveBeenCalledTimes(1);
});
it("renders the four columns and a lead card", () => {
renderPage();
expect(screen.getAllByText("leads.status.new").length).toBeGreaterThan(0);
expect(screen.getAllByText("leads.status.converted").length).toBeGreaterThan(0);
expect(byUiId("ui.leads.board")).toBeTruthy();
expect(byUiId("ui.leads.board.card.l1")).toBeTruthy();
expect(byUiId("stub.col.new").getAttribute("data-sum-mode")).toBe("hidden");
});
it("submits a valid transition (new -> qualified) via onSetStatus", () => {
const actions = renderPage();
fireEvent.click(byUiId("stub.move.l1.qualified"));
expect(actions.onSetStatus).toHaveBeenCalledWith("l1", "qualified");
expect(byUiId("ui.leads.board.error")).toBeFalsy();
});
it("rejects an invalid transition from a terminal card (no submit, shows error)", () => {
const actions = renderPage();
fireEvent.click(byUiId("stub.move.l3.qualified"));
expect(actions.onSetStatus).not.toHaveBeenCalled();
expect(byUiId("ui.leads.board.error")).toBeTruthy();
});
it("routes a drag into 'Gewonnen' (converted) to the detail conversion, never a silent flip", () => {
const actions = renderPage();
fireEvent.click(byUiId("stub.move.l1.converted"));
expect(actions.onSetStatus).not.toHaveBeenCalled();
const hint = byUiId("ui.leads.board.convertHint");
expect(hint).toBeTruthy();
const link = byUiId("ui.leads.board.convertHint.link") as HTMLAnchorElement;
expect(link.getAttribute("href")).toBe("/acme/leads/l1");
});
it("navigates back to the list via the list/board toggle", () => {
const actions = renderPage();
fireEvent.click(screen.getByLabelText("leads.viewMode.list"));
expect(actions.onOpenList).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,270 @@
// R-P7 (P7 Lead-Inbox) Interim-UI (AD-28) — incoming-leads Kanban board, composed
// from ~/ui (KanbanCard) on top of the shared SortableKanbanBoard (dnd-kit).
// Pure/presentational: renders the server-built LeadBoardData and turns a valid
// column move into a single onSetStatus callback the route POSTs (intent
// `setStatus`). Every drag funnels through requestMove so:
// - a drop into "Gewonnen" (converted) is NEVER a silent flip — it points the
// user at the detail page project conversion (createProjectFromQualifiedLead);
// - an invalid transition (backward / from a terminal status) is rejected
// client-side with a plaintext error and the card snaps back (resetToken);
// - a valid move (new->qualified, ->lost) submits and the server re-validates.
// No useLoaderData/useFetcher, no server imports. Final Subframe optics = tracked
// design-nachzug.
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { FeatherColumns, FeatherEye, FeatherList, FeatherPlus, FeatherTrendingUp } from "@subframe/core";
import type { LeadBoardData, LeadBoardStatus } from "@hivegrid/view-models";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { EmptyState } from "~/ui/components/EmptyState";
import { KanbanCard } from "~/ui/components/KanbanCard";
import { ToggleGroup } from "~/ui/components/ToggleGroup";
import { SortableKanbanBoard, type SortableKanbanColumn } from "~/components/ui/kanban/SortableKanbanBoard";
import { useRecommendedSidebarCollapse } from "~/components/app/AppShellSidebarContext";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { FacetFilterBar, type ClientFacet } from "../shared/FacetFilterBar";
import { useLiveFilter } from "~/hooks/use-live-filter";
import { AppLink } from "~/components/app/AppLink";
export type LeadBoardActions = {
onSetStatus: (leadId: string, status: LeadBoardStatus) => void;
onOpenList: () => void;
onNew: () => void;
onSearch: (value: string) => void;
onToggleSpam: (checked: boolean) => void;
/**
* Clears search and spam visibility in ONE navigation. Calling onSearch and
* onToggleSpam back to back would not do: both derive their next params from
* the same render's snapshot, so the second would resurrect what the first
* dropped.
*/
onResetFilters: () => void;
};
export type LeadBoardPageProps = {
data: LeadBoardData;
submitting: boolean;
errorKey?: string | null;
language?: string;
search: string;
actions: LeadBoardActions;
};
type BoardCard = LeadBoardData["columns"][number]["cards"][number];
const mutedText = "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary";
export function LeadBoardPage(props: LeadBoardPageProps) {
const { t } = useTranslation();
const { data } = props;
useRecommendedSidebarCollapse("leads");
// Client-side rejection feedback + snap-back trigger for the shared board.
const [localError, setLocalError] = useState<string | null>(null);
const [convertHint, setConvertHint] = useState<{ name: string; href: string } | null>(null);
const [resetToken, setResetToken] = useState(0);
const [searchDraft, setSearchDraft] = useState(props.search);
useEffect(() => setSearchDraft(props.search), [props.search]);
// The shared bar has no Enter affordance, so the term applies debounced —
// exactly as it does in the list view.
useLiveFilter(searchDraft.trim(), props.search, () => props.actions.onSearch(searchDraft.trim()));
const cardById = useMemo(() => {
const map = new Map<string, BoardCard>();
for (const column of data.columns) for (const card of column.cards) map.set(card.id, card);
return map;
}, [data.columns]);
function snapBack() {
setResetToken((token) => token + 1); // revert the optimistic drop to server truth
}
// Every drag-end (mouse or keyboard) funnels through here.
function requestMove(leadId: string, targetStatus: LeadBoardStatus) {
const card = cardById.get(leadId);
if (!card || targetStatus === card.status) return;
setLocalError(null);
setConvertHint(null);
if (targetStatus === "spam") {
// Marking as spam schedules the lead for deletion — too consequential to
// happen from a drag. Same stance as "Gewonnen" below.
setLocalError("leads.board.error.spamViaList");
snapBack();
return;
}
if (targetStatus === "converted") {
// "Gewonnen" means a Projekt was created from the lead — never do that
// silently from a drag. Point the user at the detail page conversion.
setConvertHint({ name: card.displayName, href: card.detailHref });
snapBack();
return;
}
if (!card.allowedTargetStatuses.includes(targetStatus)) {
setLocalError("leads.board.error.invalidTransition");
snapBack();
return;
}
props.actions.onSetStatus(leadId, targetStatus);
}
function renderLeadCard(card: BoardCard, dragHandle?: ReactNode): ReactNode {
return (
<KanbanCard
titleSlot={
<AppLink href={card.detailHref} className="text-text-feedback-link-default">
{card.displayName}
</AppLink>
}
valueSlot={<span className={mutedText}>{card.ownerLabel ?? t("leads.board.card.unassigned")}</span>}
tagsSlot={
<div className="flex w-full items-center justify-between gap-2">
<BadgeFeedback farbe="subtle-neutral" size="small">
{t(card.quelleLabelKey)}
</BadgeFeedback>
{dragHandle}
</div>
}
footerLeftSlot={card.contact ? <span className={`${mutedText} truncate`}>{card.contact}</span> : undefined}
data-row-id={card.id}
data-ui-id={`ui.leads.board.card.${card.id}`}
/>
);
}
const boardColumns: SortableKanbanColumn<BoardCard>[] = data.columns.map((column) => ({
id: column.status,
label: t(column.labelKey),
name: t(column.labelKey),
badge: (
<BadgeFeedback farbe="subtle-neutral" size="small">
{String(column.count)}
</BadgeFeedback>
),
sumMode: "hidden",
accentColor: {
new: "#3B82F6",
qualified: "#8B5CF6",
converted: "#16A34A",
lost: "#64748B",
spam: "#DC2626",
}[column.status],
emptyContent: (
<div className="flex min-h-20 w-72 flex-col items-center justify-center gap-1 rounded-md border border-dashed border-border-default px-4 text-center">
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-secondary">
{t("leads.board.columnEmpty.title", { status: t(column.labelKey) })}
</span>
<span className={mutedText}>{t("leads.board.columnEmpty.body")}</span>
</div>
),
cards: column.cards,
}));
const isEmpty = data.columns.every((column) => column.cards.length === 0);
const facets: ClientFacet[] = [
{
key: "visibility",
label: t("leads.filter.visibility"),
icon: <FeatherEye />,
tone: "sand-subtle",
options: [{ value: "spam", label: t("leads.filter.showSpam") }],
selected: new Set(data.includeSpam ? ["spam"] : []),
},
];
return (
<PageShell uiId="ui.leads.board">
<PageHeader
icon={<FeatherTrendingUp className={PAGE_HEADER_ICON_CLASS} />}
title={t("leads.board.title")}
subtitle={t("leads.board.subtitle")}
actions={
<>
{/* Labelled board/list switch, same shape as the projects boards. */}
<ToggleGroup value="board" onValueChange={(value: string) => value === "list" && props.actions.onOpenList()} data-ui-id="ui.leads.board.viewToggle">
<ToggleGroup.Item icon={<FeatherColumns />} value="board" aria-label={t("leads.viewMode.board")} data-ui-id="ui.leads.board.viewToggle.board">
{t("leads.viewMode.board")}
</ToggleGroup.Item>
<ToggleGroup.Item icon={<FeatherList />} value="list" aria-label={t("leads.viewMode.list")} data-ui-id="ui.leads.board.viewToggle.list">
{t("leads.viewMode.list")}
</ToggleGroup.Item>
</ToggleGroup>
{data.canWrite ? (
<Button icon={<FeatherPlus />} onClick={props.actions.onNew} data-ui-id="ui.leads.board.new">
{t("leads.actions.new")}
</Button>
) : null}
</>
}
/>
{/* --- Filter bar: the same shared facet strip the list view wears, so
switching between board and list does not change what the filter
chrome looks like. The board has no status facet — its columns ARE
the statuses — so it carries the search plus the Einblenden facet,
which here holds spam alone. --- */}
<FacetFilterBar
uiId="ui.leads.board.filter"
facets={facets}
onToggle={(_facetKey, value) => value === "spam" && props.actions.onToggleSpam(!data.includeSpam)}
search={searchDraft}
onSearchChange={setSearchDraft}
searchPlaceholder={t("leads.filter.searchPlaceholder")}
onReset={() => {
setSearchDraft("");
props.actions.onResetFilters();
}}
labels={{ reset: t("leads.filter.resetAll"), removeChip: t("leads.filter.removeChip") }}
/>
<PageBody className="max-w-none">
{props.errorKey ? (
<div data-ui-id="ui.leads.board.serverError">
<BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback>
</div>
) : null}
{localError ? (
<div data-ui-id="ui.leads.board.error">
<BadgeFeedback farbe="subtle-negative">{t(localError)}</BadgeFeedback>
</div>
) : null}
{convertHint ? (
<div className="flex flex-wrap items-center gap-2" data-ui-id="ui.leads.board.convertHint">
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">
{t("leads.board.convertHint", { name: convertHint.name })}
</span>
<AppLink href={convertHint.href} className="text-text-feedback-link-default" data-ui-id="ui.leads.board.convertHint.link">
{t("leads.board.convertLink")}
</AppLink>
</div>
) : null}
{/* No "saving" line here: it rode on the router's navigation state, so it
also flashed for a filter toggle, and the drop is optimistic anyway. */}
{data.columns.some((column) => column.truncated) ? (
<span className={mutedText} data-ui-id="ui.leads.board.truncatedHint">
{t("leads.board.truncatedHint", { count: Math.max(...data.columns.map((column) => column.loadedCount)) })}
</span>
) : null}
{isEmpty ? (
<div data-ui-id="ui.leads.board.empty">
<EmptyState title={t("leads.board.empty.headline")} body={t("leads.board.empty.body")} />
</div>
) : (
<SortableKanbanBoard<BoardCard>
columns={boardColumns}
renderCard={renderLeadCard}
getCardLabel={(card) => card.displayName}
onCardMove={(cardId, toColumnId) => requestMove(cardId, toColumnId as LeadBoardStatus)}
disabled={!data.canWrite}
errorKey={props.errorKey ?? localError}
resetToken={resetToken}
dragHandlePlacement="inline"
data-ui-id="ui.leads.board.columns"
/>
)}
</PageBody>
</PageShell>
);
}
export default LeadBoardPage;
@@ -0,0 +1,222 @@
// R-P7 Interim-UI (AD-28) — "Lead zu Projekt konvertieren" as a modal on the lead
// detail page, same shape as the "Neuer Lead" dialog. Presentational only: it
// renders the server-built LeadConvertOptions and hands the picked values to the
// injected onConvert; the route POSTs them. No useLoaderData / useFetcher
// (DoD A.5). Final Subframe optics = tracked design-nachzug.
//
// Board + stage are asked for because the schema requires them: Projekt.pipelineId
// and Projekt.stageId are non-null, and the conversion used to fill them silently
// with the default sales pipeline — so every converted lead landed on one board.
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherArrowRight, FeatherSearch, FeatherX } from "@subframe/core";
import type { LeadConvertOptions } from "@hivegrid/view-models";
import { Button } from "~/ui/components/Button";
import { Dialog } from "~/ui/components/Dialog";
import { IconButton } from "~/ui/components/IconButton";
import { Select } from "~/ui/components/Select";
import { TextInput } from "~/ui/components/TextInput";
/** Select needs a non-empty value, so "no contact" gets its own sentinel. */
const NO_CONTACT = "__none__";
/** Keeps the contact dropdown navigable when a tenant has hundreds of contacts. */
const CONTACT_RENDER_LIMIT = 50;
export type LeadConvertSubmitInput = {
projektname: string;
pipelineId: string;
stageId: string;
kontaktId: string;
};
export type LeadConvertDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
options: LeadConvertOptions;
submitting: boolean;
onConvert: (input: LeadConvertSubmitInput) => void;
};
export function LeadConvertDialog(props: LeadConvertDialogProps) {
const { t } = useTranslation();
const { options } = props;
const [projektname, setProjektname] = useState(options.defaultProjektname);
const [pipelineId, setPipelineId] = useState(options.pipelines[0]?.id ?? "");
const [stageId, setStageId] = useState(options.pipelines[0]?.stages[0]?.id ?? "");
const [kontaktId, setKontaktId] = useState(options.suggestedKontaktId ?? NO_CONTACT);
const [contactSearch, setContactSearch] = useState("");
// Reopening must not show what a previous, abandoned attempt had typed.
useEffect(() => {
if (!props.open) return;
setProjektname(options.defaultProjektname);
setPipelineId(options.pipelines[0]?.id ?? "");
setStageId(options.pipelines[0]?.stages[0]?.id ?? "");
setKontaktId(options.suggestedKontaktId ?? NO_CONTACT);
setContactSearch("");
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [props.open]);
const pipeline = options.pipelines.find((entry) => entry.id === pipelineId) ?? options.pipelines[0];
const stages = pipeline?.stages ?? [];
function pickPipeline(nextId: string) {
setPipelineId(nextId);
// The stage belongs to the board — carrying the old one over would post a
// stage the target board does not own, which the server rejects.
const next = options.pipelines.find((entry) => entry.id === nextId);
setStageId(next?.stages[0]?.id ?? "");
}
const visibleContacts = useMemo(() => {
const needle = contactSearch.trim().toLowerCase();
const matches = needle ? options.contacts.filter((contact) => contact.label.toLowerCase().includes(needle)) : options.contacts;
const shown = matches.slice(0, CONTACT_RENDER_LIMIT);
// The picked contact must stay in the list, or the Select would show a blank.
if (kontaktId !== NO_CONTACT && !shown.some((contact) => contact.id === kontaktId)) {
const picked = options.contacts.find((contact) => contact.id === kontaktId);
if (picked) return [picked, ...shown];
}
return shown;
}, [contactSearch, options.contacts, kontaktId]);
const hiddenContacts = Math.max(0, options.contacts.length - visibleContacts.length);
const canSubmit = Boolean(projektname.trim() && pipelineId && stageId) && !props.submitting;
return (
<Dialog open={props.open} onOpenChange={props.onOpenChange}>
<Dialog.Content className="w-[560px] max-w-[92vw] p-0">
<div className="flex w-full flex-col" data-ui-id="ui.leads.detail.convert.dialog">
<div className="flex w-full items-start justify-between gap-3 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-5 mobile:px-4">
<div className="flex flex-col items-start gap-1">
<span className="text-heading- font-heading- text-text-neutral-primary">{t("leads.detail.convert.dialogTitle")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("leads.detail.convert.hint")}</span>
</div>
<IconButton
type="button"
variant="ghost"
size="small"
icon={<FeatherX />}
aria-label={t("shared.cancel")}
onClick={() => props.onOpenChange(false)}
/>
</div>
<div className="flex max-h-[65vh] w-full flex-col gap-4 overflow-y-auto px-6 py-5 mobile:px-4">
{options.pipelines.length === 0 ? (
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-feedback-negative" data-ui-id="ui.leads.detail.convert.dialog.noPipelines">
{t("leads.detail.convert.noPipelines")}
</span>
) : (
<>
<TextInput className="max-w-none" label={t("leads.detail.convert.projektname")} showLabel>
<TextInput.Input
value={projektname}
onChange={(event) => setProjektname(event.target.value)}
autoFocus
data-ui-id="ui.leads.detail.convert.dialog.projektname"
/>
</TextInput>
<div className="grid w-full gap-4 sm:grid-cols-2">
<Select
className="max-w-none"
label={t("leads.detail.convert.board")}
showLabel
value={pipelineId}
onValueChange={pickPipeline}
data-ui-id="ui.leads.detail.convert.dialog.pipeline"
>
{options.pipelines.map((entry) => (
<Select.Item key={entry.id} value={entry.id}>
{entry.label}
</Select.Item>
))}
</Select>
<Select
className="max-w-none"
label={t("leads.detail.convert.stage")}
showLabel
value={stageId}
onValueChange={setStageId}
data-ui-id="ui.leads.detail.convert.dialog.stage"
>
{stages.map((stage) => (
<Select.Item key={stage.id} value={stage.id}>
{stage.label}
</Select.Item>
))}
</Select>
</div>
<div className="flex w-full flex-col gap-2">
<TextInput className="max-w-none" label={t("leads.detail.convert.kontakt")} showLabel icon={<FeatherSearch />}>
<TextInput.Input
value={contactSearch}
onChange={(event) => setContactSearch(event.target.value)}
placeholder={t("leads.detail.convert.kontaktSearch")}
data-ui-id="ui.leads.detail.convert.dialog.kontaktSearch"
/>
</TextInput>
<Select
className="max-w-none"
value={kontaktId}
onValueChange={setKontaktId}
data-ui-id="ui.leads.detail.convert.dialog.kontakt"
>
<Select.Item value={NO_CONTACT}>{t("leads.detail.convert.kontaktNone")}</Select.Item>
{visibleContacts.map((contact) => (
<Select.Item key={contact.id} value={contact.id}>
{contact.label}
</Select.Item>
))}
</Select>
{/* Never let a capped list read as "these are all contacts". */}
{hiddenContacts > 0 || options.contactsTruncated ? (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary" data-ui-id="ui.leads.detail.convert.dialog.kontaktHint">
{t("leads.detail.convert.kontaktMore")}
</span>
) : null}
</div>
</>
)}
</div>
<div className="flex w-full items-center justify-end gap-2 border-t border-solid border-border-default bg-surface-neutral-secondary px-6 py-4 mobile:flex-col-reverse mobile:items-stretch mobile:px-4">
<Button
type="button"
className="mobile:w-full"
variant="tertiary"
onClick={() => props.onOpenChange(false)}
data-ui-id="ui.leads.detail.convert.dialog.cancel"
>
{t("shared.cancel")}
</Button>
<Button
type="button"
className="mobile:w-full"
icon={<FeatherArrowRight />}
loading={props.submitting}
disabled={!canSubmit || options.pipelines.length === 0}
onClick={() =>
props.onConvert({
projektname: projektname.trim(),
pipelineId,
stageId,
kontaktId: kontaktId === NO_CONTACT ? "" : kontaktId,
})
}
data-ui-id="ui.leads.detail.convert.dialog.submit"
>
{t("leads.detail.convert.create")}
</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
);
}
export default LeadConvertDialog;
@@ -0,0 +1,250 @@
// R-P7 interim-UI (AD-28) — LeadDetailPage unit test. Fixture VM via the real
// buildLeadDetailVM; interactions asserted on the injected onSubmit. i18n mocked.
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildLeadDetailVM, type LeadDetailSource } from "@hivegrid/view-models";
import { LeadDetailPage, type LeadDetailPageActions } from "./LeadDetailPage";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }) }));
function source(over: Partial<LeadDetailSource> = {}): LeadDetailSource {
return {
id: "l1",
quelle: "form",
sourceOrigin: null,
status: "new",
weiterverarbeitungFreigabe: "unklar",
vorname: "Anna",
nachname: "Muster",
email: "anna@example.com",
telefon: null,
message: "Rückruf",
spamScore: 12,
spamReason: null,
isQuarantined: false,
konvertiertProjektId: null,
verknuepfterKontaktId: null,
autoDeleteAt: null,
zustaendigerUserId: null,
createdAt: new Date("2026-06-01T10:00:00.000Z"),
updatedAt: new Date("2026-06-02T10:00:00.000Z"),
...over,
};
}
const CONVERT_OPTIONS = {
defaultProjektname: "Projekt Anna Muster",
pipelines: [
{ id: "p1", label: "Vertrieb", stages: [{ id: "s1", label: "Erstkontakt" }, { id: "s2", label: "Angebot" }] },
{ id: "p2", label: "Service", stages: [{ id: "s9", label: "Eingang" }] },
],
contacts: [{ id: "k1", label: "Anna Muster · anna@example.com" }, { id: "k2", label: "Bert Bauer · bert@example.com" }],
suggestedKontaktId: "k1",
contactsTruncated: false,
};
function vm(over: Partial<LeadDetailSource> = {}, canWrite = true, convert: typeof CONVERT_OPTIONS | null = CONVERT_OPTIONS) {
return buildLeadDetailVM({ lead: source(over), userLabels: new Map(), perms: { canWrite }, tenantSlug: "acme", convert });
}
function actions(over: Partial<LeadDetailPageActions> = {}): LeadDetailPageActions {
return { onSubmit: vi.fn(), ...over };
}
function renderPage(props: Partial<Parameters<typeof LeadDetailPage>[0]> = {}) {
const acts = props.actions ?? actions();
render(<LeadDetailPage vm={props.vm ?? vm()} submitting={false} errorKey={null} actions={acts} {...props} />);
return acts;
}
describe("LeadDetailPage", () => {
it("saves master data and status through one submit", () => {
// Master data, release flag and status used to be three separate buttons.
const onSubmit = vi.fn();
renderPage({ actions: actions({ onSubmit }) });
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.detail.save']")!);
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(onSubmit).toHaveBeenCalledWith("save", expect.objectContaining({ vorname: "Anna", weiterverarbeitungFreigabe: "unklar", status: "new" }));
});
it("carries an edited status along with the master data", () => {
const onSubmit = vi.fn();
renderPage({ actions: actions({ onSubmit }) });
const trigger = document.querySelector("[data-ui-id='ui.leads.detail.status']")!.querySelector("button")!;
fireEvent.keyDown(trigger, { key: "ArrowDown" });
fireEvent.click(screen.getByText("leads.status.qualified"));
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.detail.save']")!);
expect(onSubmit).toHaveBeenCalledWith("save", expect.objectContaining({ status: "qualified" }));
});
it("keeps the save button in the header, not inside a card", () => {
renderPage();
const save = document.querySelector("[data-ui-id='ui.leads.detail.save']")!;
const basics = document.querySelector("[data-ui-id='ui.leads.detail.basics']")!;
expect(save.compareDocumentPosition(basics) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
it("follows the view-model after the server normalised the input", () => {
// updateLead lower-cases the e-mail. Here it normalises back to the value
// that was already stored, so the view-model returns byte-identical — only
// the finished submit reveals that the raw input is stale.
const acts = actions();
const { rerender } = render(<LeadDetailPage vm={vm()} submitting={false} errorKey={null} actions={acts} />);
const email = () => document.querySelector("[data-ui-id='ui.leads.detail.email']") as HTMLInputElement;
fireEvent.change(email(), { target: { value: "Anna@Example.COM" } });
expect(email().value).toBe("Anna@Example.COM");
rerender(<LeadDetailPage vm={vm()} submitting={true} errorKey={null} actions={acts} />);
rerender(<LeadDetailPage vm={vm()} submitting={false} errorKey={null} actions={acts} />);
expect(email().value).toBe("anna@example.com");
});
it("keeps the entered value when the save failed", () => {
const acts = actions();
const { rerender } = render(<LeadDetailPage vm={vm()} submitting={false} errorKey={null} actions={acts} />);
const email = () => document.querySelector("[data-ui-id='ui.leads.detail.email']") as HTMLInputElement;
fireEvent.change(email(), { target: { value: "kaputt" } });
rerender(<LeadDetailPage vm={vm()} submitting={true} errorKey={null} actions={acts} />);
rerender(<LeadDetailPage vm={vm()} submitting={false} errorKey="leads.error.invalidStatusTransition" actions={acts} />);
expect(email().value).toBe("kaputt");
});
it("does not offer status transitions the server would reject", () => {
// converted is terminal — offering the other statuses only produced an error.
renderPage({ vm: vm({ status: "converted", konvertiertProjektId: "p1" }) });
const trigger = document.querySelector("[data-ui-id='ui.leads.detail.status']")!.querySelector("button")!;
fireEvent.keyDown(trigger, { key: "ArrowDown" });
expect(screen.getByText("leads.status.qualified").closest("[role='option']")!.getAttribute("aria-disabled")).toBe("true");
});
it("does not offer converting a lead that is already converted", () => {
renderPage({ vm: vm({ status: "converted", konvertiertProjektId: "p1" }) });
expect(document.querySelector("[data-ui-id='ui.leads.detail.convert']")).toBeNull();
expect(screen.getByText("leads.detail.convert.done")).toBeTruthy();
});
it("treats a converted status as converted even without a linked project", () => {
// Setting the status directly leaves konvertiertProjektId null; reporting
// that as "cannot be converted" told the user the wrong reason.
renderPage({ vm: vm({ status: "converted", konvertiertProjektId: null }) });
expect(screen.getByText("leads.detail.convert.done")).toBeTruthy();
expect(screen.queryByText("leads.detail.convert.blocked")).toBeNull();
});
it("does not repeat the status as a marker badge", () => {
// The view-model marks a converted lead, which next to the status badge
// rendered the same word twice.
renderPage({ vm: vm({ status: "converted", konvertiertProjektId: "p1" }) });
const heading = document.querySelector("h1")!.textContent!;
expect(heading).not.toContain("leads.marker.converted");
expect(heading).toContain("leads.status.converted");
});
it("does not offer converting a lost lead", () => {
// Converting runs through "qualified", which lost can no longer reach.
renderPage({ vm: vm({ status: "lost" }) });
expect(document.querySelector("[data-ui-id='ui.leads.detail.convert']")).toBeNull();
expect(screen.getByText("leads.detail.convert.blocked")).toBeTruthy();
});
it("shows where the lead came from and when it changed", () => {
renderPage({ vm: vm({ zustaendigerUserId: null }) });
const meta = document.querySelector("[data-ui-id='ui.leads.detail.meta']")!;
expect(meta.textContent).toContain("leads.field.quelle");
expect(meta.textContent).toContain("leads.detail.meta.updated");
});
it("asks for board and stage before creating the project", () => {
// Projekt.pipelineId/stageId are non-null in the schema; the conversion used
// to fill them silently with the default sales board.
const onSubmit = vi.fn();
renderPage({ actions: actions({ onSubmit }) });
expect(document.querySelector("[data-ui-id='ui.leads.detail.convert.dialog']")).toBeNull();
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.detail.convert']")!);
expect(document.querySelector("[data-ui-id='ui.leads.detail.convert.dialog']")).not.toBeNull();
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.detail.convert.dialog.submit']")!);
expect(onSubmit).toHaveBeenCalledWith("convert", {
projektname: "Projekt Anna Muster",
pipelineId: "p1",
stageId: "s1",
kontaktId: "k1",
});
});
it("resets the stage when another board is picked", () => {
// A stage belongs to one board — carrying it over posts a stage the target
// board does not own, which the server rejects.
const onSubmit = vi.fn();
renderPage({ actions: actions({ onSubmit }) });
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.detail.convert']")!);
const pipeline = document.querySelector("[data-ui-id='ui.leads.detail.convert.dialog.pipeline']")!.querySelector("button")!;
fireEvent.keyDown(pipeline, { key: "ArrowDown" });
fireEvent.click(screen.getByText("Service"));
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.detail.convert.dialog.submit']")!);
expect(onSubmit).toHaveBeenCalledWith("convert", expect.objectContaining({ pipelineId: "p2", stageId: "s9" }));
});
it("preselects the contact matched by e-mail and allows dropping it", () => {
const onSubmit = vi.fn();
renderPage({ actions: actions({ onSubmit }) });
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.detail.convert']")!);
const kontakt = document.querySelector("[data-ui-id='ui.leads.detail.convert.dialog.kontakt']")!.querySelector("button")!;
fireEvent.keyDown(kontakt, { key: "ArrowDown" });
fireEvent.click(screen.getByText("leads.detail.convert.kontaktNone"));
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.detail.convert.dialog.submit']")!);
expect(onSubmit).toHaveBeenCalledWith("convert", expect.objectContaining({ kontaktId: "" }));
});
it("filters the contact list by the search field", () => {
renderPage();
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.detail.convert']")!);
fireEvent.change(document.querySelector("[data-ui-id='ui.leads.detail.convert.dialog.kontaktSearch']")!, { target: { value: "bert" } });
const kontakt = document.querySelector("[data-ui-id='ui.leads.detail.convert.dialog.kontakt']")!.querySelector("button")!;
fireEvent.keyDown(kontakt, { key: "ArrowDown" });
expect(screen.getByText("Bert Bauer · bert@example.com")).toBeTruthy();
// The preselected contact stays listed, otherwise the Select would go blank.
expect(screen.getAllByText("Anna Muster · anna@example.com").length).toBeGreaterThan(0);
});
it("says so when there is no board to put the project on", () => {
const empty = { ...CONVERT_OPTIONS, pipelines: [] };
renderPage({ vm: vm({}, true, empty) });
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.detail.convert']")!);
expect(document.querySelector("[data-ui-id='ui.leads.detail.convert.dialog.noPipelines']")).not.toBeNull();
expect((document.querySelector("[data-ui-id='ui.leads.detail.convert.dialog.submit']") as HTMLButtonElement).disabled).toBe(true);
});
it("shows the GDPR deadline card when autoDeleteAt is set", () => {
renderPage({ vm: vm({ status: "spam", autoDeleteAt: new Date("2026-07-01T00:00:00.000Z") }) });
expect(document.querySelector("[data-ui-id='ui.leads.detail.dsgvo']")).not.toBeNull();
});
it("hides the triage/edit affordances without canWrite", () => {
renderPage({ vm: vm({}, false) });
expect(document.querySelector("[data-ui-id='ui.leads.detail.save']")).toBeNull();
expect(document.querySelector("[data-ui-id='ui.leads.detail.convert.section']")).toBeNull();
});
it("exposes click-to-call only through the optional VM and callback prop", () => {
const onCall = vi.fn();
const number = { id: "phone-1", label: "Lead", e164: "+49301234567", primary: true } as const;
renderPage({
clickToCall: {
vm: { mode: "tel-fallback", numbers: [number], requiresSelection: false, reasonKey: "telephony.call.fallback.noConnection" },
onCall,
},
});
fireEvent.click(screen.getByRole("button", { name: "telephony.clickToCall.open" }));
fireEvent.click(screen.getByRole("button", { name: "telephony.clickToCall.openPhoneApp" }));
expect(onCall).toHaveBeenCalledWith(number, "tel-fallback");
});
});
@@ -0,0 +1,279 @@
// R-P7 (P7 Lead-Inbox) Interim-UI (AD-28) — lead detail + triage (D-P7
// "Lead-Detail" A3 + "Lead -> Projekt" A5), composed from ~/ui. Pure/presentational:
// renders LeadDetailVM and turns every mutation into a single onSubmit(intent,
// fields) the route POSTs. Converting Lead -> Projekt opens LeadConvertDialog,
// which asks for the board and stage the schema requires. No useLoaderData /
// useFetcher. Final Subframe optics = tracked design-nachzug.
//
// One save button in the header covers everything that is a plain field edit —
// master data, release flag and status went through three separate submits
// before. Converting to a project stays its own button: it creates a Projekt and
// is not something a "save" should trigger as a side effect.
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherTrendingUp } from "@subframe/core";
import type { LeadDetailData, LeadDetailVM, LeadWeiterverarbeitungFreigabe } from "@hivegrid/view-models";
import { canTransitionLeadStatus, type LeadStatus } from "~/utils/integrations/leads/leadListQuery";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Card } from "~/ui/components/Card";
import { Select } from "~/ui/components/Select";
import { TextArea } from "~/ui/components/TextArea";
import { TextInput } from "~/ui/components/TextInput";
import { APP_TIME_ZONE } from "~/locale/format";
import { ClickToCallEntryPoint, type ClickToCallEntryPointProps } from "../telephony/ClickToCallDialog";
import { LeadConvertDialog, type LeadConvertSubmitInput } from "./LeadConvertDialog";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
const STATUSES: readonly LeadStatus[] = ["new", "qualified", "converted", "lost", "spam"];
const FREIGABEN: readonly LeadWeiterverarbeitungFreigabe[] = ["ja", "nein", "unklar"];
const markerColor: Record<string, "subtle-warning" | "subtle-negative" | "subtle-positive"> = {
duplicate: "subtle-warning",
spam: "subtle-negative",
quarantined: "subtle-warning",
converted: "subtle-positive",
};
const sectionHeading = "text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary";
const mutedText = "text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary";
const metaLabel = "text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary";
export type LeadDetailPageActions = { onSubmit: (intent: string, fields?: Record<string, string>) => void };
export type LeadDetailPageProps = {
vm: LeadDetailVM;
submitting: boolean;
errorKey?: string | null;
language?: string;
/** Optional telephony affordance; omitted when the feature or permission gate is closed. */
clickToCall?: ClickToCallEntryPointProps;
actions: LeadDetailPageActions;
};
function formFromVm(data: LeadDetailData) {
return {
vorname: data.vorname ?? "",
nachname: data.nachname ?? "",
email: data.email ?? "",
telefon: data.telefon ?? "",
message: data.message ?? "",
weiterverarbeitungFreigabe: data.weiterverarbeitungFreigabe as string,
status: data.status as string,
};
}
const EMPTY_FORM = { vorname: "", nachname: "", email: "", telefon: "", message: "", weiterverarbeitungFreigabe: "unklar", status: "new" };
export function LeadDetailPage(props: LeadDetailPageProps) {
const { t, i18n } = useTranslation();
const submit = props.actions.onSubmit;
const data = props.vm.status === "ready" ? props.vm.data : null;
const [form, setForm] = useState(() => (data ? formFromVm(data) : EMPTY_FORM));
const [convertOpen, setConvertOpen] = useState(false);
// Read back what the server actually stored. It normalises on write (e-mail is
// lower-cased, blank strings become null), so the raw input must not stick
// around. Watching the view-model alone is not enough: when the normalised
// value equals what was already stored, the view-model comes back byte-identical
// and only the finished submit tells us to re-seed. A failed save keeps the
// input so the user can correct it.
const vmSignature = data ? JSON.stringify(data) : null;
const lastVmSignature = useRef(vmSignature);
const wasSubmitting = useRef(props.submitting);
useEffect(() => {
const submitFinished = wasSubmitting.current && !props.submitting;
wasSubmitting.current = props.submitting;
const vmChanged = lastVmSignature.current !== vmSignature;
lastVmSignature.current = vmSignature;
if (!data || props.errorKey) return;
if (!submitFinished && !vmChanged) return;
setForm(formFromVm(data));
// A finished conversion re-renders with the project attached, which is the
// signal that the dialog has done its job.
setConvertOpen(false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [props.submitting, props.errorKey, vmSignature]);
if (!data) {
return <div className="flex w-full flex-col gap-6 p-6" data-ui-id="ui.leads.detail" />;
}
const set = (patch: Partial<typeof form>) => setForm((s) => ({ ...s, ...patch }));
const canWrite = data.canWrite;
const dateFormatter = new Intl.DateTimeFormat(props.language ?? i18n.language, { timeZone: APP_TIME_ZONE, dateStyle: "medium", timeStyle: "short" });
// Converting runs through "qualified", so a lead that can no longer reach that
// status cannot be converted either — and one already converted must not be
// sent through a second time. Same rule the view-model uses for the marker: a
// lead counts as converted by status alone, even without a linked project.
const alreadyConverted = Boolean(data.konvertiertProjektId) || data.status === "converted";
const canConvert = canWrite && !alreadyConverted && canTransitionLeadStatus(data.status, "qualified");
// A marker that only repeats the status would render the same word twice.
const markers = data.markers.filter((marker) => marker !== data.status);
const metaRow = (label: string, value: string) => (
<div className="flex flex-col gap-1">
<span className={metaLabel}>{label}</span>
<span className={mutedText}>{value}</span>
</div>
);
return (
<PageShell uiId="ui.leads.detail" className="bg-surface-neutral-primary">
<PageHeader
icon={<FeatherTrendingUp className={PAGE_HEADER_ICON_CLASS} />}
title={
<span className="inline-flex flex-wrap items-center gap-2">
{data.displayName}
<BadgeFeedback farbe="subtle-neutral" size="small">
{t(data.statusLabelKey)}
</BadgeFeedback>
{markers.map((marker) => (
<BadgeFeedback key={marker} farbe={markerColor[marker]} size="small">
{t(`leads.marker.${marker}`)}
</BadgeFeedback>
))}
</span>
}
subtitle={[t(data.quelleLabelKey), data.sourceOrigin].filter(Boolean).join(" · ")}
actions={
props.clickToCall || canWrite ? (
<>
{props.clickToCall ? <ClickToCallEntryPoint {...props.clickToCall} /> : null}
{canWrite ? (
<Button loading={props.submitting} onClick={() => submit("save", { ...form })} data-ui-id="ui.leads.detail.save">
{t("leads.actions.save")}
</Button>
) : null}
</>
) : undefined
}
/>
<PageBody>
{props.errorKey ? (
<div data-ui-id="ui.leads.detail.error">
<BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback>
</div>
) : null}
{/* --- Everything the header's save button writes --- */}
<Card data-ui-id="ui.leads.detail.basics">
<span className={sectionHeading}>{t("leads.detail.section.basics")}</span>
<div className="grid w-full gap-4 sm:grid-cols-2">
<TextInput label={t("leads.field.vorname")} showLabel className="max-w-none">
<TextInput.Input value={form.vorname} disabled={!canWrite} onChange={(e) => set({ vorname: e.target.value })} data-ui-id="ui.leads.detail.vorname" />
</TextInput>
<TextInput label={t("leads.field.nachname")} showLabel className="max-w-none">
<TextInput.Input value={form.nachname} disabled={!canWrite} onChange={(e) => set({ nachname: e.target.value })} data-ui-id="ui.leads.detail.nachname" />
</TextInput>
<TextInput label={t("leads.field.email")} showLabel className="max-w-none">
<TextInput.Input type="email" value={form.email} disabled={!canWrite} onChange={(e) => set({ email: e.target.value })} data-ui-id="ui.leads.detail.email" />
</TextInput>
<TextInput label={t("leads.field.telefon")} showLabel className="max-w-none">
<TextInput.Input value={form.telefon} disabled={!canWrite} onChange={(e) => set({ telefon: e.target.value })} data-ui-id="ui.leads.detail.telefon" />
</TextInput>
{/* Status moved in here: it is saved by the same button as the rest,
so a separate "Status setzen" would have been a second truth. */}
<Select
label={t("leads.list.column.status")}
showLabel
className="max-w-none"
value={form.status}
onValueChange={(v) => set({ status: v })}
disabled={!canWrite}
data-ui-id="ui.leads.detail.status"
>
{STATUSES.map((s) => {
// The server rejects forbidden transitions; offering them as if
// they were possible only produced an error message after saving.
const allowed = canTransitionLeadStatus(data.status, s);
return (
<Select.Item key={s} value={s} disabled={!allowed}>
{t(`leads.status.${s}`)}
</Select.Item>
);
})}
</Select>
<Select
label={t("leads.field.freigabe")}
showLabel
className="max-w-none"
value={form.weiterverarbeitungFreigabe}
onValueChange={(v) => set({ weiterverarbeitungFreigabe: v })}
disabled={!canWrite}
data-ui-id="ui.leads.detail.freigabe"
>
{FREIGABEN.map((f) => (
<Select.Item key={f} value={f}>
{t(`leads.freigabe.${f}`)}
</Select.Item>
))}
</Select>
</div>
<TextArea label={t("leads.field.message")} showLabel className="max-w-none">
<TextArea.Input value={form.message} disabled={!canWrite} onChange={(e) => set({ message: e.target.value })} data-ui-id="ui.leads.detail.message" />
</TextArea>
</Card>
{/* --- Convert: creates a Projekt, hence its own explicit action --- */}
{canWrite ? (
<Card data-ui-id="ui.leads.detail.convert.section">
<div className="flex w-full flex-wrap items-center justify-between gap-3">
<div className="flex flex-col items-start gap-1">
<span className={sectionHeading}>{t("leads.detail.section.convert")}</span>
<span className={mutedText}>
{t(alreadyConverted ? "leads.detail.convert.done" : canConvert ? "leads.detail.convert.hint" : "leads.detail.convert.blocked")}
</span>
</div>
{canConvert ? (
<Button className="shrink-0" onClick={() => setConvertOpen(true)} data-ui-id="ui.leads.detail.convert">
{t("leads.actions.convertToProject")}
</Button>
) : null}
</div>
</Card>
) : null}
{canConvert && data.convert ? (
<LeadConvertDialog
open={convertOpen}
onOpenChange={setConvertOpen}
options={data.convert}
submitting={props.submitting}
onConvert={(input: LeadConvertSubmitInput) => submit("convert", { ...input })}
/>
) : null}
{/* --- Where the lead came from and what happened to it --- */}
<Card data-ui-id="ui.leads.detail.meta">
<span className={sectionHeading}>{t("leads.detail.section.meta")}</span>
<div className="grid w-full gap-4 sm:grid-cols-2 lg:grid-cols-4">
{metaRow(t("leads.field.quelle"), t(data.quelleLabelKey))}
{metaRow(t("leads.list.column.owner"), data.zustaendigerLabel ?? "—")}
{metaRow(t("leads.list.column.createdAt"), dateFormatter.format(new Date(data.createdAtIso)))}
{metaRow(t("leads.detail.meta.updated"), dateFormatter.format(new Date(data.updatedAtIso)))}
</div>
</Card>
{/* --- Spam --- */}
<Card data-ui-id="ui.leads.detail.spam">
<span className={sectionHeading}>{t("leads.detail.spam.title")}</span>
<span className={mutedText}>{t("leads.detail.spam.score", { score: data.spamScore })}</span>
{data.spamReason ? <span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">{data.spamReason}</span> : null}
</Card>
{/* --- DSGVO auto-delete --- */}
{data.autoDeleteAtIso ? (
<Card variant="warning" data-ui-id="ui.leads.detail.dsgvo">
<span className={sectionHeading}>{t("leads.detail.dsgvo.title")}</span>
<span className={mutedText}>{t("leads.detail.dsgvo.deadline", { date: dateFormatter.format(new Date(data.autoDeleteAtIso)) })}</span>
</Card>
) : null}
</PageBody>
</PageShell>
);
}
export default LeadDetailPage;
@@ -0,0 +1,333 @@
// R-P7 interim-UI (AD-28) — LeadInboxPage unit test. Fixture VM via the real
// buildLeadListVM; interactions asserted on injected action callbacks. i18n mocked.
import React from "react";
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildLeadListVM, type LeadListRowSource } from "@hivegrid/view-models";
import type { LeadListQuery } from "~/utils/integrations/leads/leadListQuery";
import { LeadInboxPage, type LeadInboxActions } from "./LeadInboxPage";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }) }));
// Radix dropdowns neither open nor provide their menu context in jsdom, so both
// the filter-bar facet options and the per-row status flyover would be
// unreachable. Root/Trigger/Portal/Content become passthroughs; Item keeps its
// `onSelect` wired to a click so the status flyover assertions stay real.
vi.mock("@subframe/core", async () => {
const actual = await vi.importActual<Record<string, unknown>>("@subframe/core");
const Pass = ({ children }: { children?: React.ReactNode }) => <>{children}</>;
const Item = ({ children, onSelect, asChild, ...rest }: any) =>
asChild && React.isValidElement(children)
? React.cloneElement(children as React.ReactElement<any>, { onClick: onSelect, ...rest })
: (
<button type="button" onClick={onSelect} {...rest}>
{children}
</button>
);
return { ...actual, DropdownMenu: { Root: Pass, Trigger: Pass, Portal: Pass, Content: Pass, Item } };
});
vi.mock("~/ui/components/DropdownMenuMultiSelect", () => {
const DropdownMenuMultiSelect = ({ children }: { children?: React.ReactNode }) => <div>{children}</div>;
DropdownMenuMultiSelect.DropdownItem = ({ children, onClick, selected, ...rest }: any) => (
<button type="button" onClick={onClick} aria-pressed={Boolean(selected)} data-ui-id={rest["data-ui-id"]}>
{children}
</button>
);
DropdownMenuMultiSelect.DropdownCustomItem = ({ children }: any) => <div>{children}</div>;
DropdownMenuMultiSelect.DropdownUserItem = ({ title }: any) => <div>{title}</div>;
DropdownMenuMultiSelect.DropdownDivider = () => <hr />;
return { DropdownMenuMultiSelect };
});
const QUERY: LeadListQuery = {
filter: { status: null, quelle: null, zustaendigerUserId: null, search: null, includeSpam: false, includeConverted: false },
sort: { field: "createdAt", dir: "desc" },
cursor: null,
};
function row(id: string, over: Partial<LeadListRowSource> = {}): LeadListRowSource {
return {
id,
quelle: "form",
status: "new",
weiterverarbeitungFreigabe: "unklar",
vorname: "Anna",
nachname: "Muster",
email: "anna@example.com",
telefon: null,
message: "Rückruf bitte",
zustaendigerUserId: null,
spamScore: 0,
spamReason: null,
isQuarantined: false,
konvertiertProjektId: null,
verknuepfterKontaktId: null,
createdAt: new Date("2026-06-01T10:00:00.000Z"),
...over,
};
}
function vm(rows: LeadListRowSource[]) {
return buildLeadListVM({
rows,
userLabels: new Map(),
total: rows.length,
nextCursor: null,
perms: { canWrite: true, canDelete: true, canReadAll: true },
tenantSlug: "acme",
createHref: "/acme/leads/new",
});
}
function actions(over: Partial<LeadInboxActions> = {}): LeadInboxActions {
return { onApplyFilter: vi.fn(), onSetStatus: vi.fn(), onBulkStatus: vi.fn(), onNextPage: vi.fn(), onOpenBoard: vi.fn(), ...over };
}
function renderPage(props: Partial<Parameters<typeof LeadInboxPage>[0]> = {}) {
const acts = props.actions ?? actions();
render(
<LeadInboxPage
vm={props.vm ?? vm([row("l1")])}
moduleActive
query={QUERY}
hasNextPage={false}
sseHref="/acme/leads/events"
submitting={false}
errorKey={null}
actions={acts}
{...props}
/>
);
return acts;
}
/** Render with a handle to swap the query, the way a navigation would. */
function renderPageWithRerender() {
const acts = actions();
const props = (query: LeadListQuery) => (
<LeadInboxPage
vm={vm([row("l1")])}
moduleActive
query={query}
hasNextPage={false}
sseHref={null}
submitting={false}
errorKey={null}
actions={acts}
/>
);
const view = render(props(QUERY));
return { rerender: (query: LeadListQuery) => view.rerender(props(query)) };
}
const byUiId = (id: string) => document.querySelector(`[data-ui-id='${id}']`) as HTMLElement;
/** A selection shows up as a chip in the bar; that chip is the readable state. */
const chip = (facet: string, value: string) => byUiId(`ui.leads.list.filter.chip.${facet}.${value}`);
describe("LeadInboxPage", () => {
it("renders the triage table + carries the SSE href", () => {
renderPage();
const root = document.querySelector("[data-ui-id='ui.leads.list']") as HTMLElement;
expect(root.getAttribute("data-sse-href")).toBe("/acme/leads/events");
expect(document.querySelector("[data-ui-id='ui.leads.list.table']")).not.toBeNull();
});
it("carries the three facets of the shared filter bar", () => {
renderPage();
expect(byUiId("ui.leads.list.filter.quelle")).toBeTruthy();
expect(byUiId("ui.leads.list.filter.status")).toBeTruthy();
expect(byUiId("ui.leads.list.filter.visibility")).toBeTruthy();
});
it("applies a filter with 'show spam' off mapped to includeSpam=false", () => {
const onApplyFilter = vi.fn();
renderPage({ actions: actions({ onApplyFilter }) });
fireEvent.click(byUiId("ui.leads.list.filter.quelle.email"));
expect(onApplyFilter).toHaveBeenCalledTimes(1);
expect(onApplyFilter.mock.calls[0][0].filter).toMatchObject({ quelle: "email", includeSpam: false });
});
it("reads an incoming status filter back into the bar, not just into the table", () => {
// Arriving from a statistics tile (or a shared link) with the filter already
// in the query — the bar has to show it, otherwise the table looks filtered
// for no visible reason.
const { rerender } = renderPageWithRerender();
expect(chip("status", "new")).toBeNull();
rerender({ ...QUERY, filter: { ...QUERY.filter, status: ["new"] } });
expect(chip("status", "new")).toBeTruthy();
rerender({ ...QUERY, filter: { ...QUERY.filter, status: ["spam"], includeSpam: true } });
expect(chip("status", "new")).toBeNull();
expect(chip("status", "spam")).toBeTruthy();
});
it("reads the two visibility options back out of the query as well", () => {
// Same read/write contract as the other facets: the spam and converted tiles
// link here with those flags set, and the bar has to show it. Both read as
// "additionally show these", so both mirror their flag directly.
const { rerender } = renderPageWithRerender();
expect(chip("visibility", "spam")).toBeNull();
expect(chip("visibility", "converted")).toBeNull();
rerender({ ...QUERY, filter: { ...QUERY.filter, status: ["spam"], includeSpam: true } });
expect(chip("visibility", "spam")).toBeTruthy();
rerender({ ...QUERY, filter: { ...QUERY.filter, status: ["converted"], includeConverted: true } });
expect(chip("visibility", "spam")).toBeNull();
expect(chip("visibility", "converted")).toBeTruthy();
});
it("turns a status pick into the query, opening spam/converted visibility with it", () => {
const onApplyFilter = vi.fn();
renderPage({ actions: actions({ onApplyFilter }) });
fireEvent.click(byUiId("ui.leads.list.filter.status.spam"));
// Filtering for spam while "hide spam" is on would always yield nothing.
expect(onApplyFilter.mock.calls.at(-1)![0].filter).toMatchObject({ status: ["spam"], includeSpam: true });
});
it("takes a status filter back off via its chip", () => {
const onApplyFilter = vi.fn();
renderPage({ actions: actions({ onApplyFilter }) });
fireEvent.click(byUiId("ui.leads.list.filter.status.qualified"));
expect(onApplyFilter.mock.calls.at(-1)![0].filter.status).toEqual(["qualified"]);
fireEvent.click(byUiId("ui.leads.list.filter.chip.status.qualified.remove"));
expect(onApplyFilter.mock.calls.at(-1)![0].filter.status).toBeNull();
});
it("clears search and every facet through the reset pill", () => {
const onApplyFilter = vi.fn();
renderPage({ actions: actions({ onApplyFilter }) });
fireEvent.click(byUiId("ui.leads.list.filter.quelle.email"));
fireEvent.click(byUiId("ui.leads.list.filter.visibility.spam"));
fireEvent.click(screen.getByText("leads.filter.resetAll"));
expect(onApplyFilter.mock.calls.at(-1)![0].filter).toMatchObject({
search: null,
status: null,
quelle: null,
includeSpam: false,
includeConverted: false,
});
});
it("changes a single lead's status from the badge flyover and saves right away", () => {
const onSetStatus = vi.fn();
renderPage({ actions: actions({ onSetStatus }) });
// Addressed by row ui-id, not by label: the status facet in the filter bar
// now carries the same five captions.
fireEvent.click(byUiId("ui.leads.list.row.status.l1.qualified"));
// No confirm step, no separate save button — picking is the write.
expect(onSetStatus).toHaveBeenCalledWith("l1", "qualified");
});
it("shows every status in the flyover but locks the ones the server would reject", () => {
const onSetStatus = vi.fn();
// "converted" is terminal — no transition out of it is allowed.
renderPage({ vm: vm([row("l1", { status: "converted", konvertiertProjektId: "p1" })]), actions: actions({ onSetStatus }) });
// All five are listed, so the user can see where a lead can go at all.
for (const status of ["new", "qualified", "converted", "lost", "spam"]) {
expect(byUiId(`ui.leads.list.row.status.l1.${status}`)).not.toBeNull();
}
fireEvent.click(byUiId("ui.leads.list.row.status.l1.qualified"));
expect(onSetStatus).not.toHaveBeenCalled();
});
it("drops the per-row quick-action column", () => {
renderPage();
expect(document.querySelector("[data-ui-id='ui.leads.list.row.qualify.l1']")).toBeNull();
expect(document.querySelector("[data-ui-id='ui.leads.list.row.spam.l1']")).toBeNull();
});
it("preselects the row's own status for a single selection and stays empty for several", () => {
renderPage({ vm: vm([row("l1", { status: "lost" }), row("l2", { vorname: "Bea" })]) });
const trigger = () => document.querySelector("[data-ui-id='ui.leads.list.bulk'] button") as HTMLElement;
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.list.row.select.l1']")!);
expect(trigger().textContent).toContain("leads.status.lost");
// Two rows with different statuses: showing one of them would misstate the other.
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.list.row.select.l2']")!);
expect(trigger().textContent).not.toContain("leads.status.lost");
expect(trigger().textContent).toContain("leads.actions.chooseStatus");
});
it("bulk-updates only the selected leads", () => {
const onBulkStatus = vi.fn();
renderPage({ vm: vm([row("l1"), row("l2", { vorname: "Bea", status: "lost" })]), actions: actions({ onBulkStatus }) });
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.list.row.select.l2']")!);
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.list.bulk.apply']")!);
// Single selection seeds the dropdown with that row's own status.
expect(onBulkStatus).toHaveBeenCalledWith(["l2"], "lost");
});
it("rides the bulk-status control inside the filter bar, behind the facets", () => {
renderPage();
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.list.row.select.l1']")!);
const bar = byUiId("ui.leads.list.filter");
const bulk = byUiId("ui.leads.list.bulk");
expect(bar.contains(bulk)).toBe(true);
// Both narrow or act on the same list, so they share one strip rather than
// reading as two unrelated toolbars — the bulk control trails the facets.
const facet = byUiId("ui.leads.list.filter.visibility");
expect(facet.compareDocumentPosition(bulk) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
it("shows the bulk-status control only once something is selected", () => {
renderPage();
expect(document.querySelector("[data-ui-id='ui.leads.list.bulk']")).toBeNull();
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.list.row.select.l1']")!);
expect(document.querySelector("[data-ui-id='ui.leads.list.bulk']")).not.toBeNull();
// Deselecting the last row takes the control away again.
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.list.row.select.l1']")!);
expect(document.querySelector("[data-ui-id='ui.leads.list.bulk']")).toBeNull();
});
it("navigates to the board view via the list/board toggle", () => {
const onOpenBoard = vi.fn();
renderPage({ actions: actions({ onOpenBoard }) });
fireEvent.click(screen.getByLabelText("leads.viewMode.board"));
expect(onOpenBoard).toHaveBeenCalledTimes(1);
});
it("opens the create dialog instead of navigating to the create page", () => {
renderPage();
expect(document.querySelector("[data-ui-id='ui.leads.new.dialog']")).toBeNull();
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.list.new']")!);
const form = document.querySelector("[data-ui-id='ui.leads.new.dialog']") as HTMLFormElement;
expect(form.getAttribute("action")).toBe("/acme/leads/new");
expect(form.getAttribute("method")).toBe("post");
// A lead needs at least one identifying detail before it can be submitted.
const submit = document.querySelector("[data-ui-id='ui.leads.new.dialog.submit']") as HTMLButtonElement;
expect(submit.disabled).toBe(true);
fireEvent.input(document.querySelector("[data-ui-id='ui.leads.new.dialog.email']")!, { target: { value: "a@example.com" } });
expect((document.querySelector("[data-ui-id='ui.leads.new.dialog.submit']") as HTMLButtonElement).disabled).toBe(false);
});
it("renders no inline admin nav (sources/anti-spam moved to the leads sub-sidenav)", () => {
renderPage();
expect(document.querySelector("[data-ui-id='ui.leads.list.nav']")).toBeNull();
});
it("shows the locked state when the module is off", () => {
renderPage({ moduleActive: false });
expect(document.querySelector("[data-ui-id='ui.leads.list.table']")).toBeNull();
expect(screen.getByText("leads.list.locked")).toBeTruthy();
});
});
@@ -0,0 +1,468 @@
// R-P7 (P7 Lead-Inbox) Interim-UI (AD-28) — lead triage inbox (D-P7 "Lead-Inbox",
// archetype A2 + Triage), composed from ~/ui. Pure/presentational: renders the
// server-built LeadListVM (filter/sort/cursor server-side) and turns every action
// into a callback the route drives (navigation for filter/page, POST for status/
// bulk). SSE realtime hint stays on the root via `sseHref`. No useLoaderData/
// useFetcher. Final Subframe optics = tracked design-nachzug.
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherActivity, FeatherChevronDown, FeatherColumns, FeatherEye, FeatherInbox, FeatherList, FeatherPlus, FeatherTrendingUp } from "@subframe/core";
import * as SubframeCore from "@subframe/core";
import type { LeadListVM } from "@hivegrid/view-models";
import { canTransitionLeadStatus, leadStatusFilterFromQuery, leadStatusFilterToQuery } from "~/utils/integrations/leads/leadListQuery";
import type { LeadListQuery, LeadQuelle, LeadStatus, LeadStatusFilterValue } from "~/utils/integrations/leads/leadListQuery";
import * as SubframeUtils from "~/ui/utils";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { FacetFilterBar, type ClientFacet } from "../shared/FacetFilterBar";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Checkbox } from "~/ui/components/Checkbox";
import { DropdownMenu } from "~/ui/components/DropdownMenu";
import { EmptyState } from "~/ui/components/EmptyState";
import { Select } from "~/ui/components/Select";
import { Table } from "~/ui/components/Table";
import { ToggleGroup } from "~/ui/components/ToggleGroup";
import { LeadNewDialog } from "./LeadNewDialog";
import { APP_TIME_ZONE } from "~/locale/format";
import { useLiveFilter } from "~/hooks/use-live-filter";
import { AppLink } from "~/components/app/AppLink";
const QUELLEN: readonly LeadQuelle[] = ["form", "email", "aircall", "manual", "custom"];
const STATUSES: readonly LeadStatus[] = ["new", "qualified", "converted", "lost", "spam"];
const FILTER_ANY = "__any__";
const markerColor: Record<string, "subtle-warning" | "subtle-negative" | "subtle-positive"> = {
duplicate: "subtle-warning",
spam: "subtle-negative",
converted: "subtle-positive",
};
export type LeadInboxActions = {
onApplyFilter: (query: LeadListQuery) => void;
onSetStatus: (leadId: string, status: LeadStatus) => void;
onBulkStatus: (leadIds: string[], status: LeadStatus) => void;
onNextPage: () => void;
onOpenBoard: () => void;
};
export type LeadInboxPageProps = {
vm: LeadListVM;
moduleActive: boolean;
query: LeadListQuery;
hasNextPage: boolean;
sseHref: string | null;
submitting: boolean;
errorKey?: string | null;
language?: string;
actions: LeadInboxActions;
};
export function LeadInboxPage(props: LeadInboxPageProps) {
const { t, i18n } = useTranslation();
const { query } = props;
const [search, setSearch] = useState(query.filter.search ?? "");
const [quelle, setQuelle] = useState<string>(query.filter.quelle ?? FILTER_ANY);
// Single-select in the UI, a list in the query — the mapping lives in
// leadListQuery so writing and reading it back always agree.
const [statusFilter, setStatusFilter] = useState<LeadStatusFilterValue>(leadStatusFilterFromQuery(query.filter.status));
// "Spam einblenden" mirrors includeSpam directly, like "Konvertierte
// einblenden" does — both read as "additionally show these".
const [showSpam, setShowSpam] = useState<boolean>(query.filter.includeSpam);
const [showConverted, setShowConverted] = useState<boolean>(query.filter.includeConverted);
const [selected, setSelected] = useState<ReadonlySet<string>>(new Set());
// "" = nothing preselected. That is the state for a mixed selection: showing
// one row's status there would claim the others share it.
const [bulkStatus, setBulkStatus] = useState<LeadStatus | "">("");
// Creating a lead is a short form, so the CTA opens a modal (like "Neue
// Automation") instead of navigating to the standalone create page.
const [createOpen, setCreateOpen] = useState(false);
// Live filter: dropdowns/checkboxes apply immediately (fresh value passed as
// override, state updates are async), the search input debounced. Defined
// before the module-inactive early return so the hook order stays stable.
function applyFilter(overrides?: Partial<{ quelle: string; statusFilter: LeadStatusFilterValue; showSpam: boolean; showConverted: boolean }>) {
const next = { quelle, statusFilter, showSpam, showConverted, ...overrides };
// Filtering for spam/converted while they are hidden would always yield an
// empty table, so an explicit pick wins over the two visibility checkboxes.
if (next.statusFilter === "spam") next.showSpam = true;
if (next.statusFilter === "converted") next.showConverted = true;
props.actions.onApplyFilter({
filter: {
...query.filter,
search: search.trim() || null,
status: leadStatusFilterToQuery(next.statusFilter),
quelle: next.quelle === FILTER_ANY ? null : (next.quelle as LeadQuelle),
includeSpam: next.showSpam,
includeConverted: next.showConverted,
},
sort: query.sort,
cursor: null,
});
}
useLiveFilter(search.trim(), query.filter.search ?? "", () => applyFilter());
// The controls both write AND read the query: arriving with a filter already
// in the URL (a statistics tile links here pre-filtered, or the user shares
// the link) has to show up in the dropdowns, not just in the table. Guarded by
// the signature so typing in the search box is never overwritten mid-keystroke.
const filterSignature = JSON.stringify(query.filter);
const lastFilterSignature = useRef(filterSignature);
useEffect(() => {
if (lastFilterSignature.current === filterSignature) return;
lastFilterSignature.current = filterSignature;
setSearch(query.filter.search ?? "");
setQuelle(query.filter.quelle ?? FILTER_ANY);
setStatusFilter(leadStatusFilterFromQuery(query.filter.status));
setShowSpam(query.filter.includeSpam);
setShowConverted(query.filter.includeConverted);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [filterSignature]);
const data = props.vm.status === "ready" ? props.vm.data : null;
const rows = useMemo(() => data?.rows ?? [], [data]);
const dateFormatter = new Intl.DateTimeFormat(props.language ?? i18n.language, { timeZone: APP_TIME_ZONE, dateStyle: "medium", timeStyle: "short" });
const someSelected = selected.size > 0;
const allSelected = rows.length > 0 && rows.every((row) => selected.has(row.id));
// Re-seed the bulk dropdown whenever the selection changes: exactly one row
// preselects that row's current status, anything else leaves it empty. Seeding
// on selection (not on every render) keeps a deliberate pick by the user from
// being overwritten while the same rows stay selected.
const selectionSignature = [...selected].sort().join(",");
useEffect(() => {
const onlyId = selected.size === 1 ? [...selected][0] : null;
const onlyRow = onlyId ? rows.find((row) => row.id === onlyId) : null;
setBulkStatus(onlyRow ? onlyRow.status : "");
// rows/selected are read through the signature; re-running on row identity
// would clobber the user's pick on every list refresh.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectionSignature]);
if (!props.moduleActive) {
return (
<PageShell uiId="ui.leads.list">
<PageHeader
icon={<FeatherTrendingUp className={PAGE_HEADER_ICON_CLASS} />}
title={t("leads.list.title")}
subtitle={t("leads.list.subtitle")}
/>
<PageBody>
<EmptyState title={t("leads.list.locked")} />
</PageBody>
</PageShell>
);
}
const facets: ClientFacet[] = [
{
key: "quelle",
label: t("leads.filter.source"),
icon: <FeatherInbox />,
tone: "violet-subtle",
options: QUELLEN.map((q) => ({ value: q, label: t(`leads.quelle.${q}`) })),
selected: new Set(quelle === FILTER_ANY ? [] : [quelle]),
},
{
key: "status",
label: t("leads.list.column.status"),
icon: <FeatherActivity />,
tone: "blue-subtle",
options: STATUSES.map((status) => ({ value: status, label: t(`leads.status.${status}`) })),
selected: new Set(statusFilter === "any" ? [] : [statusFilter]),
},
{
key: "visibility",
label: t("leads.filter.visibility"),
icon: <FeatherEye />,
tone: "sand-subtle",
options: [
{ value: "spam", label: t("leads.filter.showSpam") },
{ value: "converted", label: t("leads.filter.showConverted") },
],
selected: new Set([...(showSpam ? ["spam"] : []), ...(showConverted ? ["converted"] : [])]),
},
];
function toggleFacet(facetKey: string, value: string) {
if (facetKey === "quelle") {
const next = quelle === value ? FILTER_ANY : value;
setQuelle(next);
return applyFilter({ quelle: next });
}
if (facetKey === "status") {
const next: LeadStatusFilterValue = statusFilter === value ? "any" : (value as LeadStatusFilterValue);
setStatusFilter(next);
return applyFilter({ statusFilter: next });
}
if (facetKey === "visibility") {
if (value === "spam") {
const next = !showSpam;
setShowSpam(next);
return applyFilter({ showSpam: next });
}
const next = !showConverted;
setShowConverted(next);
return applyFilter({ showConverted: next });
}
return undefined;
}
function resetFilters() {
setSearch("");
setQuelle(FILTER_ANY);
setStatusFilter("any");
setShowSpam(false);
setShowConverted(false);
props.actions.onApplyFilter({
filter: {
...query.filter,
search: null,
status: leadStatusFilterToQuery("any"),
quelle: null,
includeSpam: false,
includeConverted: false,
},
sort: query.sort,
cursor: null,
});
}
function toggleRow(id: string, checked: boolean) {
setSelected((prev) => {
const next = new Set(prev);
if (checked) next.add(id);
else next.delete(id);
return next;
});
}
return (
<PageShell uiId="ui.leads.list" sseHref={props.sseHref}>
<PageHeader
icon={<FeatherTrendingUp className={PAGE_HEADER_ICON_CLASS} />}
title={t("leads.list.title")}
subtitle={t("leads.list.subtitle")}
actions={
<>
{/* Labelled board/list switch, same shape as the projects boards. */}
<ToggleGroup value="list" onValueChange={(value: string) => value === "board" && props.actions.onOpenBoard()} data-ui-id="ui.leads.list.viewToggle">
<ToggleGroup.Item icon={<FeatherColumns />} value="board" aria-label={t("leads.viewMode.board")} data-ui-id="ui.leads.list.viewToggle.board">
{t("leads.viewMode.board")}
</ToggleGroup.Item>
<ToggleGroup.Item icon={<FeatherList />} value="list" aria-label={t("leads.viewMode.list")} data-ui-id="ui.leads.list.viewToggle.list">
{t("leads.viewMode.list")}
</ToggleGroup.Item>
</ToggleGroup>
{data?.canWrite ? (
<Button icon={<FeatherPlus />} onClick={() => setCreateOpen(true)} data-ui-id="ui.leads.list.new">
{t("leads.actions.new")}
</Button>
) : null}
</>
}
/>
{/* Admin links (Quellen/Anti-Spam) live in the leads sub-sidenav, not here. */}
{/* --- Filter bar: the shared facet strip the boards and the settings
lists wear. Quelle and Status are single-select (picking the active
option again clears it, as the chip's X does); "Einblenden" is the
genuinely multi-select facet that replaced the two loose checkboxes.
Filtering stays server-side — the bar only reports the toggle and
`applyFilter` rewrites the query. --- */}
<FacetFilterBar
uiId="ui.leads.list.filter"
facets={facets}
onToggle={toggleFacet}
search={search}
onSearchChange={setSearch}
searchPlaceholder={t("leads.filter.searchPlaceholder")}
onReset={resetFilters}
labels={{ reset: t("leads.filter.resetAll"), removeChip: t("leads.filter.removeChip") }}
trailing={
/* Bulk status rides in the same strip as the filters: both narrow or
act on the same list, so splitting them over two rows made the page
read like there were two unrelated toolbars. Only shown when there
is a selection to act on — an always-visible bulk control that does
nothing most of the time only adds noise. */
data?.canWrite && someSelected ? (
<div className="flex shrink-0 items-end gap-2" data-ui-id="ui.leads.list.bulk">
<Select
className="max-w-[200px]"
placeholder={t("leads.actions.chooseStatus")}
value={bulkStatus}
onValueChange={(v) => setBulkStatus(v as LeadStatus)}
>
{STATUSES.map((s) => (
<Select.Item key={s} value={s}>
{t(`leads.status.${s}`)}
</Select.Item>
))}
</Select>
<Button
variant="neutral"
size="small"
disabled={!bulkStatus}
loading={props.submitting}
onClick={() => bulkStatus && props.actions.onBulkStatus([...selected], bulkStatus)}
data-ui-id="ui.leads.list.bulk.apply"
>
{t("leads.actions.applyBulk")}
</Button>
</div>
) : null
}
/>
<PageBody>
{props.errorKey ? <BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback> : null}
{rows.length === 0 ? (
<div data-ui-id="ui.leads.list.empty">
<EmptyState title={t(data?.emptyHeadlineKey ?? "leads.list.empty.headline")} body={t(data?.emptyBodyKey ?? "leads.list.empty.body")} />
</div>
) : (
<>
<div className="w-full overflow-x-auto">
<Table
data-ui-id="ui.leads.list.table"
header={
<Table.HeaderRow>
<Table.HeaderCell>
{data?.canWrite ? (
<Checkbox
checked={allSelected}
indeterminate={someSelected && !allSelected}
onCheckedChange={(c) => setSelected(c ? new Set(rows.map((r) => r.id)) : new Set())}
hideLabel
label={t("leads.list.column.select")}
/>
) : null}
</Table.HeaderCell>
<Table.HeaderCell>{t("leads.list.column.identity")}</Table.HeaderCell>
<Table.HeaderCell>{t("leads.list.column.source")}</Table.HeaderCell>
<Table.HeaderCell>{t("leads.list.column.status")}</Table.HeaderCell>
<Table.HeaderCell>{t("leads.list.column.owner")}</Table.HeaderCell>
<Table.HeaderCell>{t("leads.list.column.createdAt")}</Table.HeaderCell>
</Table.HeaderRow>
}
>
{rows.map((row) => (
<Table.Row key={row.id} data-row-id={row.id} data-markers={row.markers.join(",")}>
<Table.Cell>
{data?.canWrite ? (
<Checkbox
checked={selected.has(row.id)}
onCheckedChange={(c) => toggleRow(row.id, c)}
hideLabel
label={t("leads.list.column.select")}
data-ui-id={`ui.leads.list.row.select.${row.id}`}
/>
) : null}
</Table.Cell>
<Table.Cell>
<div className="flex flex-col gap-0.5">
<div className="flex items-center gap-2">
<AppLink href={row.detailHref} className="text-body-default-medium-0 font-body-default-medium-0 text-text-feedback-link-default">
{row.displayName}
</AppLink>
{row.markers.map((marker) => (
<BadgeFeedback key={marker} farbe={markerColor[marker]} size="small">
{t(`leads.marker.${marker}`)}
</BadgeFeedback>
))}
</div>
{row.preview ? (
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary line-clamp-1">{row.preview}</span>
) : null}
</div>
</Table.Cell>
<Table.Cell>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">{t(row.quelleLabelKey)}</span>
</Table.Cell>
<Table.Cell>
{/* The status badge is the edit control: clicking it opens the
status list and picking one saves right away. That replaced
the per-row quick-action column, which only ever offered
two of the five statuses. */}
{data?.canWrite ? (
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<button
type="button"
className="focus-visible:shadow-focus flex items-center gap-1 rounded-sm outline-none"
aria-label={t("leads.actions.changeStatus")}
data-ui-id={`ui.leads.list.row.status.${row.id}`}
>
<BadgeFeedback farbe="subtle-neutral" size="small">
{t(row.statusLabelKey)}
</BadgeFeedback>
<FeatherChevronDown className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
</button>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="start" sideOffset={4} asChild>
<DropdownMenu className="gap-1">
{STATUSES.map((status) => {
// Every status stays visible, but the ones the
// server would reject (converted/lost/spam are
// terminal) are not selectable — offering them
// would only produce an error banner.
const allowed = canTransitionLeadStatus(row.status, status);
return (
<DropdownMenu.DropdownItem
key={status}
showCheckbox
selected={row.status === status}
disabled={!allowed}
className={SubframeUtils.twClassNames(
"bg-surface-neutral-primary hover:bg-surface-neutral-tertiary active:bg-surface-neutral-secondary",
{ "pointer-events-none opacity-40": !allowed }
)}
onSelect={() => allowed && status !== row.status && props.actions.onSetStatus(row.id, status)}
data-ui-id={`ui.leads.list.row.status.${row.id}.${status}`}
>
{t(`leads.status.${status}`)}
</DropdownMenu.DropdownItem>
);
})}
</DropdownMenu>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
) : (
<BadgeFeedback farbe="subtle-neutral" size="small">
{t(row.statusLabelKey)}
</BadgeFeedback>
)}
</Table.Cell>
<Table.Cell>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">{row.zustaendigerLabel ?? "—"}</span>
</Table.Cell>
<Table.Cell>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">
{dateFormatter.format(new Date(row.createdAtIso))}
</span>
</Table.Cell>
</Table.Row>
))}
</Table>
</div>
{props.hasNextPage ? (
<div className="flex">
<Button variant="neutral" size="small" onClick={props.actions.onNextPage} data-ui-id="ui.leads.list.next">
{t("leads.actions.nextPage")}
</Button>
</div>
) : null}
</>
)}
{data?.canWrite ? <LeadNewDialog open={createOpen} onOpenChange={setCreateOpen} createHref={data.createHref} /> : null}
</PageBody>
</PageShell>
);
}
export default LeadInboxPage;
@@ -0,0 +1,113 @@
// R-P7 Interim-UI (AD-28) — "Neuer Lead" as a modal on the lead inbox, mirroring
// the automation list pattern ("Neue Automation starten"). Presentational only: the
// form posts to the create route (`createHref`) with the same field contract as the
// standalone LeadNewPage, so the route action stays untouched. No useLoaderData /
// useFetcher (DoD A.5). Final Subframe optics = tracked design-nachzug.
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherPlus, FeatherX } from "@subframe/core";
import type { LeadQuelle } from "~/utils/integrations/leads/leadListQuery";
import { Button } from "~/ui/components/Button";
import { Dialog } from "~/ui/components/Dialog";
import { IconButton } from "~/ui/components/IconButton";
import { Select } from "~/ui/components/Select";
import { TextArea } from "~/ui/components/TextArea";
import { TextInput } from "~/ui/components/TextInput";
const QUELLEN: readonly LeadQuelle[] = ["form", "email", "aircall", "manual", "custom"];
export type LeadNewDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
/** Route that owns the create action (the standalone /leads/new route). */
createHref: string;
};
export function LeadNewDialog({ open, onOpenChange, createHref }: LeadNewDialogProps) {
const { t } = useTranslation();
const [quelle, setQuelle] = useState<string>("manual");
// A lead needs at least one identifying detail — same rule as the standalone page.
const [hasIdentity, setHasIdentity] = useState(false);
function checkIdentity(event: React.FormEvent<HTMLFormElement>) {
const form = event.currentTarget;
const filled = ["vorname", "nachname", "email", "telefon", "message"].some((name) => {
const field = form.elements.namedItem(name);
return field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement ? field.value.trim().length > 0 : false;
});
setHasIdentity(filled);
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<Dialog.Content className="w-[560px] max-w-[92vw] p-0">
<form method="post" action={createHref} className="flex w-full flex-col" onInput={checkIdentity} data-ui-id="ui.leads.new.dialog">
<div className="flex w-full items-start justify-between gap-3 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-5 mobile:px-4">
<div className="flex flex-col items-start gap-1">
<span className="text-heading- font-heading- text-text-neutral-primary">{t("leads.new.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("leads.new.subtitle")}</span>
</div>
<IconButton
type="button"
variant="ghost"
size="small"
icon={<FeatherX />}
aria-label={t("shared.cancel")}
onClick={() => onOpenChange(false)}
/>
</div>
<div className="flex w-full flex-col gap-4 px-6 py-5 max-h-[65vh] overflow-y-auto mobile:px-4">
<Select
className="max-w-[240px]"
name="quelle"
label={t("leads.field.quelle")}
showLabel
value={quelle}
onValueChange={(value: string) => setQuelle(value)}
>
{QUELLEN.map((q) => (
<Select.Item key={q} value={q}>
{t(`leads.quelle.${q}`)}
</Select.Item>
))}
</Select>
<div className="grid w-full gap-4 sm:grid-cols-2">
<TextInput label={t("leads.field.vorname")} showLabel>
<TextInput.Input name="vorname" autoFocus data-ui-id="ui.leads.new.dialog.vorname" />
</TextInput>
<TextInput label={t("leads.field.nachname")} showLabel>
<TextInput.Input name="nachname" />
</TextInput>
<TextInput label={t("leads.field.email")} showLabel>
<TextInput.Input name="email" type="email" data-ui-id="ui.leads.new.dialog.email" />
</TextInput>
<TextInput label={t("leads.field.telefon")} showLabel>
<TextInput.Input name="telefon" />
</TextInput>
</div>
<TextArea label={t("leads.field.message")} showLabel className="max-w-none">
<TextArea.Input name="message" />
</TextArea>
</div>
<div className="flex w-full items-center justify-end gap-2 border-t border-solid border-border-default bg-surface-neutral-secondary px-6 py-4 mobile:flex-col-reverse mobile:items-stretch mobile:px-4">
<Button
type="button"
className="mobile:w-full"
variant="tertiary"
onClick={() => onOpenChange(false)}
data-ui-id="ui.leads.new.dialog.cancel"
>
{t("shared.cancel")}
</Button>
<Button type="submit" className="mobile:w-full" icon={<FeatherPlus />} disabled={!hasIdentity} data-ui-id="ui.leads.new.dialog.submit">
{t("leads.actions.create")}
</Button>
</div>
</form>
</Dialog.Content>
</Dialog>
);
}
@@ -0,0 +1,29 @@
// R-P7 interim-UI (AD-28) — LeadNewPage unit test. Pure props; asserts the create
// callback + the identity guard. i18n mocked.
import { fireEvent, render } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { LeadNewPage, type LeadNewPageActions } from "./LeadNewPage";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }) }));
function actions(over: Partial<LeadNewPageActions> = {}): LeadNewPageActions {
return { onCreate: vi.fn(), ...over };
}
function renderPage(acts = actions()) {
render(<LeadNewPage backHref="/acme/leads" submitting={false} errorKey={null} actions={acts} />);
return acts;
}
describe("LeadNewPage", () => {
it("keeps create disabled until an identity field is filled, then submits", () => {
const onCreate = vi.fn();
renderPage(actions({ onCreate }));
const submit = document.querySelector("[data-ui-id='ui.leads.new.submit']") as HTMLButtonElement;
expect(submit.disabled).toBe(true);
fireEvent.change(document.querySelector("[data-ui-id='ui.leads.new.email']")!, { target: { value: "neu@example.com" } });
fireEvent.click(submit);
expect(onCreate).toHaveBeenCalledWith(expect.objectContaining({ quelle: "manual", email: "neu@example.com" }));
});
});
@@ -0,0 +1,79 @@
// R-P7 (P7 Lead-Inbox) Interim-UI (AD-28) — manual lead entry (D-P7 "Manueller
// Lead-Eintrag", archetype A4), composed from ~/ui. Pure: holds the form draft and
// calls actions.onCreate; the route POSTs it. No useLoaderData. Final Subframe
// optics = tracked design-nachzug.
import { useState } from "react";
import { useTranslation } from "react-i18next";
import type { LeadQuelle } from "~/utils/integrations/leads/leadListQuery";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Card } from "~/ui/components/Card";
import { Select } from "~/ui/components/Select";
import { TextArea } from "~/ui/components/TextArea";
import { TextInput } from "~/ui/components/TextInput";
const QUELLEN: readonly LeadQuelle[] = ["form", "email", "aircall", "manual", "custom"];
export type LeadNewFields = { quelle: string; vorname: string; nachname: string; email: string; telefon: string; message: string };
export type LeadNewPageActions = { onCreate: (fields: LeadNewFields) => void };
export type LeadNewPageProps = {
backHref: string;
submitting: boolean;
errorKey?: string | null;
actions: LeadNewPageActions;
};
export function LeadNewPage(props: LeadNewPageProps) {
const { t } = useTranslation();
const [fields, setFields] = useState<LeadNewFields>({ quelle: "manual", vorname: "", nachname: "", email: "", telefon: "", message: "" });
const set = (patch: Partial<LeadNewFields>) => setFields((s) => ({ ...s, ...patch }));
const hasIdentity = Boolean(fields.vorname.trim() || fields.nachname.trim() || fields.email.trim() || fields.telefon.trim() || fields.message.trim());
return (
<div className="flex w-full flex-col gap-6 p-6" data-ui-id="ui.leads.new">
<span className="text-heading-2 font-heading-2 text-text-neutral-primary">{t("leads.new.title")}</span>
{props.errorKey ? (
<div data-ui-id="ui.leads.new.error">
<BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback>
</div>
) : null}
<Card data-ui-id="ui.leads.new.form">
<div className="grid w-full gap-4 sm:grid-cols-2">
<Select label={t("leads.field.quelle")} showLabel value={fields.quelle} onValueChange={(v) => set({ quelle: v })}>
{QUELLEN.map((q) => (
<Select.Item key={q} value={q}>{t(`leads.quelle.${q}`)}</Select.Item>
))}
</Select>
<div />
<TextInput label={t("leads.field.vorname")} showLabel>
<TextInput.Input value={fields.vorname} onChange={(e) => set({ vorname: e.target.value })} data-ui-id="ui.leads.new.vorname" />
</TextInput>
<TextInput label={t("leads.field.nachname")} showLabel>
<TextInput.Input value={fields.nachname} onChange={(e) => set({ nachname: e.target.value })} />
</TextInput>
<TextInput label={t("leads.field.email")} showLabel>
<TextInput.Input type="email" value={fields.email} onChange={(e) => set({ email: e.target.value })} data-ui-id="ui.leads.new.email" />
</TextInput>
<TextInput label={t("leads.field.telefon")} showLabel>
<TextInput.Input value={fields.telefon} onChange={(e) => set({ telefon: e.target.value })} />
</TextInput>
</div>
<TextArea label={t("leads.field.message")} showLabel className="max-w-none">
<TextArea.Input value={fields.message} onChange={(e) => set({ message: e.target.value })} />
</TextArea>
<div className="flex">
<Button loading={props.submitting} disabled={!hasIdentity} onClick={() => props.actions.onCreate(fields)} data-ui-id="ui.leads.new.submit">
{t("leads.actions.create")}
</Button>
</div>
</Card>
</div>
);
}
export default LeadNewPage;
@@ -0,0 +1,94 @@
// R-P7 interim-UI (AD-28) — LeadSourcesAdminPage unit test. Fixture VM via the real
// buildLeadSourceAdminVM; asserts the upsert/delete callbacks + status badges. i18n mocked.
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildLeadSourceAdminVM, type LeadSourceAdminSourceRow } from "@hivegrid/view-models";
import { LeadSourcesAdminPage, type LeadSourcesAdminActions } from "./LeadSourcesAdminPage";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }) }));
function source(over: Partial<LeadSourceAdminSourceRow> = {}): LeadSourceAdminSourceRow {
return {
id: "s1",
type: "custom",
key: "landingpage",
name: "Landingpage",
displayLabel: "Landingpage",
defaultZustaendigerUserId: null,
webhookTokenHash: "abc",
pausedAt: null,
isDemoData: false,
...over,
};
}
const ASSIGNABLE = [{ id: "u1", label: "Daniel Geschäftsführer" }];
function buildVm(rows: LeadSourceAdminSourceRow[] = [source()]) {
return buildLeadSourceAdminVM({ rows, assignableUsers: ASSIGNABLE, canWrite: true });
}
function actions(over: Partial<LeadSourcesAdminActions> = {}): LeadSourcesAdminActions {
return { onUpsert: vi.fn(), onDelete: vi.fn(), ...over };
}
function renderPage(rows?: LeadSourceAdminSourceRow[], over: Partial<LeadSourcesAdminActions> = {}) {
const acts = actions(over);
render(<LeadSourcesAdminPage vm={buildVm(rows)} submitting={false} errorKey={null} actions={acts} />);
return acts;
}
describe("LeadSourcesAdminPage", () => {
it("renders a source row with its webhook badge", () => {
renderPage();
expect(document.querySelector("[data-ui-id='ui.leads.sources.table']")).not.toBeNull();
expect(screen.getByText("leads.sources.status.webhook")).toBeTruthy();
});
it("puts the create form above the table", () => {
renderPage();
const form = document.querySelector("[data-ui-id='ui.leads.sources.create']")!;
const table = document.querySelector("[data-ui-id='ui.leads.sources.table']")!;
// Node.DOCUMENT_POSITION_FOLLOWING — the table comes after the form.
expect(form.compareDocumentPosition(table) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
it("upserts a source from the create form", () => {
const { onUpsert } = renderPage();
fireEvent.change(document.querySelector("[data-ui-id='ui.leads.sources.create.key']")!, { target: { value: "newsletter" } });
fireEvent.change(document.querySelector("[data-ui-id='ui.leads.sources.create.name']")!, { target: { value: "Newsletter" } });
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.sources.create.submit']")!);
expect(onUpsert).toHaveBeenCalledWith(expect.objectContaining({ key: "newsletter", name: "Newsletter" }));
});
it("sends an empty default owner when none is picked, not the placeholder value", () => {
const { onUpsert } = renderPage();
fireEvent.change(document.querySelector("[data-ui-id='ui.leads.sources.create.key']")!, { target: { value: "newsletter" } });
fireEvent.change(document.querySelector("[data-ui-id='ui.leads.sources.create.name']")!, { target: { value: "Newsletter" } });
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.sources.create.submit']")!);
expect(onUpsert.mock.calls[0][0].defaultZustaendigerUserId).toBe("");
});
it("asks for the name once — no separate display-label input", () => {
// displayLabel is what every screen renders and the service copies the name
// into it, so a second field would collect the same value twice.
renderPage();
expect(document.querySelector("[data-ui-id='ui.leads.sources.create.displayLabel']")).toBeNull();
expect(document.querySelector("[data-ui-id='ui.leads.sources.create.name']")).not.toBeNull();
});
it("shows the resolved default owner in the table, a dash when there is none", () => {
renderPage([source({ id: "s1", defaultZustaendigerUserId: "u1" }), source({ id: "s2", key: "other", displayLabel: "Andere" })]);
expect(screen.getByText("Daniel Geschäftsführer")).toBeTruthy();
expect(screen.getByText("—")).toBeTruthy();
});
it("offers delete for custom sources only — system sources are wired to built-in capture paths", () => {
const { onDelete } = renderPage([source({ id: "s1", type: "custom" }), source({ id: "s2", type: "system", key: "email-inbound" })]);
expect(document.querySelector("[data-ui-id='ui.leads.sources.row.delete.s2']")).toBeNull();
fireEvent.click(document.querySelector("[data-ui-id='ui.leads.sources.row.delete.s1']")!);
expect(onDelete).toHaveBeenCalledWith("s1");
});
});
@@ -0,0 +1,190 @@
// R-P7 (P7 Lead-Inbox) Interim-UI (AD-28) — lead source admin (D-P7
// "Quellen-Verwaltung", archetype A2/A6), composed from ~/ui. Pure: renders the
// server-built LeadSourceAdminVM and calls actions.onUpsert / onDelete; the route
// POSTs the intents. The webhook token is stored hashed, so the table only shows
// whether one exists. No useLoaderData. Final Subframe optics = tracked
// design-nachzug.
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherDatabase } from "@subframe/core";
import type { LeadSourceAdminVM } from "@hivegrid/view-models";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Card } from "~/ui/components/Card";
import { EmptyState } from "~/ui/components/EmptyState";
import { Select } from "~/ui/components/Select";
import { Table } from "~/ui/components/Table";
import { TextInput } from "~/ui/components/TextInput";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
export type LeadSourceUpsertInput = { key: string; name: string; defaultZustaendigerUserId: string };
export type LeadSourcesAdminActions = {
onUpsert: (input: LeadSourceUpsertInput) => void;
onDelete: (sourceId: string) => void;
};
export type LeadSourcesAdminPageProps = {
vm: LeadSourceAdminVM;
submitting: boolean;
errorKey?: string | null;
actions: LeadSourcesAdminActions;
};
const sectionHeading = "text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary";
const cellText = "text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary";
// Inputs share the card width evenly instead of sizing themselves by content.
const fieldWidth = "w-full min-w-0 sm:w-auto sm:shrink sm:grow sm:basis-0";
const NO_OWNER = "__none__";
const EMPTY_DRAFT: LeadSourceUpsertInput = { key: "", name: "", defaultZustaendigerUserId: NO_OWNER };
export function LeadSourcesAdminPage(props: LeadSourcesAdminPageProps) {
const { t } = useTranslation();
const [draft, setDraft] = useState<LeadSourceUpsertInput>(EMPTY_DRAFT);
const set = (patch: Partial<LeadSourceUpsertInput>) => setDraft((s) => ({ ...s, ...patch }));
const data = props.vm.status === "ready" ? props.vm.data : null;
const rows = data?.rows ?? [];
const assignableUsers = data?.assignableUsers ?? [];
return (
<PageShell uiId="ui.leads.sources">
<PageHeader icon={<FeatherDatabase className={PAGE_HEADER_ICON_CLASS} />} title={t("leads.sources.title")} subtitle={t("leads.sources.subtitle")} />
<PageBody>
{props.errorKey ? <BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback> : null}
{/* Create first, list below — same order as the custom-field admin. */}
{data?.canWrite ? (
<Card data-ui-id="ui.leads.sources.create">
<span className={sectionHeading}>{t("leads.sources.createTitle")}</span>
<div className="flex w-full flex-col items-stretch gap-4 sm:flex-row sm:items-end">
{/* The key's format hint rides in the placeholder — as a line of
help text below the field it pushed this input off the shared
baseline and made the row look misaligned. */}
<TextInput className={fieldWidth} label={t("leads.sources.field.key")} showLabel>
<TextInput.Input
value={draft.key}
onChange={(e) => set({ key: e.target.value })}
placeholder={t("leads.sources.keyPlaceholder")}
data-ui-id="ui.leads.sources.create.key"
/>
</TextInput>
{/* One name field only: the row's displayLabel is what every
screen renders, and the service copies the name into it. A
second "display label" input asked for the same thing twice. */}
<TextInput className={fieldWidth} label={t("leads.sources.field.name")} showLabel>
<TextInput.Input value={draft.name} onChange={(e) => set({ name: e.target.value })} data-ui-id="ui.leads.sources.create.name" />
</TextInput>
{/* The service already stores a default owner per source and the
route already reads it — it just had no control until now. */}
<Select
className={fieldWidth}
label={t("leads.sources.field.defaultOwner")}
showLabel
value={draft.defaultZustaendigerUserId}
onValueChange={(value) => set({ defaultZustaendigerUserId: value })}
data-ui-id="ui.leads.sources.create.defaultOwner"
>
<Select.Item value={NO_OWNER}>{t("leads.sources.field.defaultOwnerNone")}</Select.Item>
{assignableUsers.map((user) => (
<Select.Item key={user.id} value={user.id}>
{user.label}
</Select.Item>
))}
</Select>
<Button
className="shrink-0"
loading={props.submitting}
disabled={!draft.key.trim() || !draft.name.trim()}
onClick={() => {
props.actions.onUpsert({ ...draft, defaultZustaendigerUserId: draft.defaultZustaendigerUserId === NO_OWNER ? "" : draft.defaultZustaendigerUserId });
setDraft(EMPTY_DRAFT);
}}
data-ui-id="ui.leads.sources.create.submit"
>
{t("leads.sources.actions.save")}
</Button>
</div>
</Card>
) : null}
{rows.length === 0 ? (
<div data-ui-id="ui.leads.sources.empty">
<EmptyState title={t("leads.sources.empty")} />
</div>
) : (
<div className="w-full overflow-hidden rounded-lg border border-solid border-border-default shadow-sm overflow-x-auto">
<Table
data-ui-id="ui.leads.sources.table"
header={
<Table.HeaderRow>
<Table.HeaderCell>{t("leads.sources.field.name")}</Table.HeaderCell>
<Table.HeaderCell>{t("leads.sources.field.key")}</Table.HeaderCell>
<Table.HeaderCell>{t("leads.sources.field.type")}</Table.HeaderCell>
<Table.HeaderCell>{t("leads.sources.field.defaultOwner")}</Table.HeaderCell>
<Table.HeaderCell>{t("leads.sources.field.status")}</Table.HeaderCell>
{/* Action column: just wide enough for the button, centred. */}
<Table.HeaderCell className="w-24"> </Table.HeaderCell>
</Table.HeaderRow>
}
>
{rows.map((row) => (
<Table.Row key={row.id} data-row-id={row.id}>
<Table.Cell>
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{row.displayLabel}</span>
</Table.Cell>
<Table.Cell>
<span className={cellText}>{row.key}</span>
</Table.Cell>
<Table.Cell>
<BadgeFeedback farbe="subtle-neutral" size="small">
{t(row.typeLabelKey)}
</BadgeFeedback>
</Table.Cell>
<Table.Cell>
<span className={cellText}>{row.defaultZustaendigerLabel ?? "—"}</span>
</Table.Cell>
<Table.Cell>
<div className="flex flex-wrap items-center gap-1">
{row.isPaused ? (
<BadgeFeedback farbe="subtle-warning" size="small">
{t("leads.sources.status.paused")}
</BadgeFeedback>
) : null}
{row.hasWebhookToken ? (
<BadgeFeedback farbe="subtle-positive" size="small">
{t("leads.sources.status.webhook")}
</BadgeFeedback>
) : null}
</div>
</Table.Cell>
<Table.Cell className="w-24">
{/* Only custom sources can go: the system ones are wired to
built-in capture paths and would break if removed. */}
{data?.canWrite && row.type === "custom" ? (
<div className="flex w-full justify-center">
<Button
variant="tertiary"
size="small"
loading={props.submitting}
onClick={() => props.actions.onDelete(row.id)}
data-ui-id={`ui.leads.sources.row.delete.${row.id}`}
>
{t("leads.sources.actions.delete")}
</Button>
</div>
) : null}
</Table.Cell>
</Table.Row>
))}
</Table>
</div>
)}
</PageBody>
</PageShell>
);
}
export default LeadSourcesAdminPage;
@@ -0,0 +1,67 @@
// R-P7 interim-UI (AD-28) — LeadStatisticsPage unit test. Fixture VM via the real
// buildLeadStatisticsVM. i18n mocked.
import { fireEvent, render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { describe, expect, it, vi } from "vitest";
import { buildLeadStatisticsVM, type LeadStatisticsVM } from "@hivegrid/view-models";
import { LeadStatisticsPage } from "./LeadStatisticsPage";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }) }));
const vm = buildLeadStatisticsVM({
stats: { total: 12, new: 5, converted: 4, spam: 1, byQuelle: [{ quelle: "form", count: 8 }], byStatus: [{ status: "new", count: 5 }] },
canReadAll: true,
listHref: "/acme/leads",
});
function renderPage(state: LeadStatisticsVM, onOpenLeads = vi.fn()) {
render(
<MemoryRouter>
<LeadStatisticsPage vm={state} actions={{ onOpenLeads }} />
</MemoryRouter>
);
return { onOpenLeads };
}
describe("LeadStatisticsPage", () => {
it("renders the page header, the four KPI tiles and both breakdowns", () => {
renderPage(vm);
expect(screen.getByRole("heading", { level: 1 }).textContent).toBe("leads.statistics.title");
expect(document.querySelector("[data-ui-id='ui.leads.statistics.kpi.total']")).not.toBeNull();
expect(document.querySelector("[data-ui-id='ui.leads.statistics.kpi.spam']")).not.toBeNull();
expect(document.querySelector("[data-ui-id='ui.leads.statistics.bySource']")).not.toBeNull();
expect(document.querySelector("[data-ui-id='ui.leads.statistics.byStatus']")).not.toBeNull();
expect(document.querySelector("[data-ui-id='ui.leads.statistics.bySource.row.form']")).not.toBeNull();
expect(screen.getByText("12")).toBeTruthy();
});
it("hides the own-scope hint when the user may read all leads", () => {
renderPage(vm);
expect(document.querySelector("[data-ui-id='ui.leads.statistics.scopeHint']")).toBeNull();
renderPage(buildLeadStatisticsVM({ stats: { ...emptyStats, total: 3, new: 3 }, canReadAll: false, listHref: "/acme/leads" }));
expect(document.querySelector("[data-ui-id='ui.leads.statistics.scopeHint']")).not.toBeNull();
});
it("shows the plaintext empty state when the tenant has no leads yet", () => {
renderPage(buildLeadStatisticsVM({ stats: emptyStats, canReadAll: true, listHref: "/acme/leads" }));
expect(document.querySelector("[data-ui-id='ui.leads.statistics.empty']")).not.toBeNull();
expect(screen.getByText("leads.statistics.empty.body")).toBeTruthy();
});
it("shows a plaintext error instead of a bare state", () => {
renderPage({ status: "error", error: { messageKey: "leads.errors.loadFailed" } });
expect(screen.getByText("leads.errors.loadFailed")).toBeTruthy();
});
it("turns each KPI tile into a shortcut to the matching inbox filter", () => {
const { onOpenLeads } = renderPage(vm);
for (const kpi of ["total", "new", "converted", "spam"]) {
fireEvent.click(document.querySelector(`[data-ui-id='ui.leads.statistics.kpi.${kpi}.link']`)!);
}
expect(onOpenLeads.mock.calls.map((call) => call[0])).toEqual(["total", "new", "converted", "spam"]);
});
});
const emptyStats = { total: 0, new: 0, converted: 0, spam: 0, byQuelle: [], byStatus: [] } as const;
@@ -0,0 +1,202 @@
// R-P7 (P7 Lead-Inbox) Interim-UI (AD-28) — lead statistics (D-P7
// "Lead-Statistiken", archetype A2 + KPI-Kit), composed from ~/ui. Pure: renders
// LeadStatisticsVM (KPI tiles + by-source/by-status breakdowns) inside the shared
// PageShell/PageHeader/PageBody chrome, the same page frame the dashboard uses.
// Shares are derived from the counts the VM already carries — no invented
// aggregates. The brief's richer breakdowns (reaction time, per-owner, weekday,
// trend charts) are not yet exposed by the service and stay a tracked
// design-nachzug. No useLoaderData. Final Subframe optics = tracked design-nachzug.
import { useTranslation } from "react-i18next";
import { FeatherBarChart2, FeatherCheckCircle, FeatherInbox, FeatherShieldOff, FeatherTrendingUp } from "@subframe/core";
import type { LeadStatBreakdownRow, LeadStatKpi, LeadStatisticsVM } from "@hivegrid/view-models";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { Alert } from "~/ui/components/Alert";
import { Card } from "~/ui/components/Card";
import { EmptyState } from "~/ui/components/EmptyState";
import { Loader } from "~/ui/components/Loader";
import { Progress } from "~/ui/components/Progress";
import { StatsCard } from "~/ui/components/StatsCard";
import { useLocaleFormatters } from "~/locale/format";
export type LeadStatisticsActions = {
/** Open the inbox filtered to what the tile counts. */
onOpenLeads: (kpi: LeadStatKpi) => void;
};
export type LeadStatisticsPageProps = {
vm: LeadStatisticsVM;
actions: LeadStatisticsActions;
};
const sectionHeading = "text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary";
const mutedText = "text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary";
const kpiIcons: Record<LeadStatKpi, React.ReactNode> = {
total: <FeatherInbox />,
new: <FeatherTrendingUp />,
converted: <FeatherCheckCircle />,
spam: <FeatherShieldOff />,
};
export function LeadStatisticsPage(props: LeadStatisticsPageProps) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const header = (
<PageHeader
icon={<FeatherBarChart2 className={PAGE_HEADER_ICON_CLASS} />}
title={t("leads.statistics.title")}
subtitle={t("leads.statistics.subtitle")}
/>
);
if (props.vm.status === "loading" || props.vm.status === "idle") {
return (
<PageShell uiId="ui.leads.statistics.loading">
{header}
<PageBody className="items-center gap-4">
<Loader size="medium" />
<span className={mutedText}>{t("leads.statistics.loading")}</span>
</PageBody>
</PageShell>
);
}
if (props.vm.status === "error") {
return (
<PageShell uiId="ui.leads.statistics.error">
{header}
<PageBody>
<Alert variant="error" title={t(props.vm.error.messageKey)} />
</PageBody>
</PageShell>
);
}
const data = props.vm.status === "ready" ? props.vm.data : null;
const total = data?.kpis.find((kpi) => kpi.key === "total")?.value ?? 0;
if (!data || total === 0) {
return (
<PageShell uiId="ui.leads.statistics.empty">
{header}
<PageBody>
<EmptyState outlined title={t("leads.statistics.empty.headline")} body={t("leads.statistics.empty.body")} />
</PageBody>
</PageShell>
);
}
/** Share of all leads — the only derivation, straight from the VM counts. */
const share = (count: number) => (total > 0 ? count / total : 0);
return (
<PageShell uiId="ui.leads.statistics">
{header}
<PageBody>
<div className="grid w-full gap-4 sm:grid-cols-2 lg:grid-cols-4" data-ui-id="ui.leads.statistics.kpis">
{data.kpis.map((kpi) => (
// Each tile is a shortcut into the inbox, filtered to exactly what it
// counts — a button, so it is reachable by keyboard like any control.
<button
key={kpi.key}
type="button"
onClick={() => props.actions.onOpenLeads(kpi.key)}
className="focus-visible:shadow-focus h-full rounded-md text-left outline-none"
aria-label={t("leads.statistics.card.openInInbox", { label: t(kpi.labelKey) })}
data-ui-id={`ui.leads.statistics.kpi.${kpi.key}.link`}
>
<StatsCard
trend="neutral"
label={t(kpi.labelKey)}
value={formatters.number(kpi.value)}
comparisonText={
kpi.key === "total"
? t("leads.statistics.card.totalHint")
: t("leads.statistics.shareOfTotal", { percent: formatters.percent(share(kpi.value), { maximumFractionDigits: 0 }) })
}
icon={kpiIcons[kpi.key]}
className="hover:border-brand-brand-border-solid-hover h-full"
data-ui-id={`ui.leads.statistics.kpi.${kpi.key}`}
/>
</button>
))}
</div>
<div className="grid w-full gap-4 lg:grid-cols-2">
<BreakdownCard
uiId="ui.leads.statistics.bySource"
heading={t("leads.statistics.bySource")}
description={t("leads.statistics.bySourceDescription")}
rows={data.byQuelle}
total={total}
/>
<BreakdownCard
uiId="ui.leads.statistics.byStatus"
heading={t("leads.statistics.byStatus")}
description={t("leads.statistics.byStatusDescription")}
rows={data.byStatus}
total={total}
/>
</div>
{data.canReadAll ? null : (
<span className={mutedText} data-ui-id="ui.leads.statistics.scopeHint">
{t("leads.statistics.scopeOwnOnly")}
</span>
)}
</PageBody>
</PageShell>
);
}
function BreakdownCard({
uiId,
heading,
description,
rows,
total,
}: {
uiId: string;
heading: string;
description: string;
rows: readonly LeadStatBreakdownRow[];
total: number;
}) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
return (
<Card className="h-full" data-ui-id={uiId}>
<div className="flex w-full flex-col gap-1">
<span className={sectionHeading}>{heading}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{description}</span>
</div>
{rows.length === 0 ? (
<span className={mutedText}>{t("leads.statistics.breakdown.empty")}</span>
) : (
<div className="flex w-full flex-col gap-4">
{rows.map((row) => (
<Progress
key={row.key}
// The shared Progress track has no own height and its indicator is
// forced to `height: 100%` by the vendor stylesheet, so the bar
// collapses to 0px unless the track gets one here.
className="w-full gap-2 [&>div:nth-of-type(2)]:h-1.5"
value={total > 0 ? Math.round((row.count / total) * 100) : 0}
label={t(row.labelKey)}
statusText={t("leads.statistics.breakdown.count", {
value: formatters.number(row.count),
percent: formatters.percent(total > 0 ? row.count / total : 0, { maximumFractionDigits: 0 }),
})}
data-ui-id={`${uiId}.row.${row.key}`}
/>
))}
</div>
)}
</Card>
);
}
export default LeadStatisticsPage;