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,57 @@
// R-P6 interim-UI (AD-28) — CustomFieldAdminPage unit test. Fixture VM via the
// real buildCustomFieldAdminVM; asserts the create/archive callbacks. i18n mocked.
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildCustomFieldAdminVM } from "@hivegrid/view-models";
import { CustomFieldAdminPage, type CustomFieldAdminPageActions } from "./CustomFieldAdminPage";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }) }));
const vm = buildCustomFieldAdminVM({
rows: [{ id: "cf1", entityType: "kontakt", key: "budget", label: "Budget", datentyp: "waehrung", optionen: null, archiviert: false, isDemoData: false }],
entityType: "kontakt",
canWrite: true,
});
function actions(over: Partial<CustomFieldAdminPageActions> = {}): CustomFieldAdminPageActions {
return { onCreate: vi.fn(), onArchive: vi.fn(), ...over };
}
function renderPage(acts = actions()) {
render(<CustomFieldAdminPage vm={vm} moduleActive submitting={false} errorKey={null} actions={acts} />);
return acts;
}
describe("CustomFieldAdminPage", () => {
it("renders the definition row", () => {
renderPage();
expect(document.querySelector("[data-ui-id='ui.crm.admin.customFields.table']")).not.toBeNull();
expect(screen.getByText("Budget")).toBeTruthy();
});
it("soft-deletes a definition via the delete button", () => {
const onArchive = vi.fn();
renderPage(actions({ onArchive }));
fireEvent.click(screen.getByText("crm.actions.delete"));
expect(onArchive).toHaveBeenCalledWith("cf1");
});
it("creates a definition with key + label", () => {
const onCreate = vi.fn();
renderPage(actions({ onCreate }));
fireEvent.change(document.querySelector("[data-ui-id='ui.crm.admin.customFields.create.key']")!, { target: { value: "leadsource" } });
fireEvent.change(document.querySelector("[data-ui-id='ui.crm.admin.customFields.create.label']")!, { target: { value: "Lead source" } });
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.admin.customFields.create.submit']")!);
expect(onCreate).toHaveBeenCalledWith(expect.objectContaining({ key: "leadsource", label: "Lead source", datentyp: "text" }));
});
it("puts the create form above the table", () => {
// The page exists to add fields and the list only grows, so the form must
// not drift below it.
renderPage(actions());
const form = document.querySelector("[data-ui-id='ui.crm.admin.customFields.create']")!;
const table = document.querySelector("[data-ui-id='ui.crm.admin.customFields.table']")!;
expect(form.compareDocumentPosition(table) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
});
@@ -0,0 +1,194 @@
// R-P6 (P6 CRM core) Interim-UI (AD-28) — contact custom-field admin (D-CRM
// "Custom-Felder", archetype A2), composed from ~/ui. Pure/presentational: renders
// the server-built CustomFieldAdminVM and calls actions.onArchive / onCreate; the
// route POSTs the intents. Final Subframe optics = tracked design-nachzug.
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherSlidersHorizontal } from "@subframe/core";
import type { CustomFieldAdminVM, CustomFieldDatentyp } from "@hivegrid/view-models";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
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";
const DATENTYPEN: readonly CustomFieldDatentyp[] = [
"text",
"textarea",
"zahl",
"waehrung",
"datum",
"datum_range",
"select",
"multiselect",
"boolean",
"email",
"telefon",
"datei",
"prozent",
"datum_zeit",
"person_team",
"adresse",
"link",
];
export type CustomFieldCreateInput = { key: string; label: string; datentyp: string; optionen: string };
export type CustomFieldAdminPageActions = {
onCreate: (input: CustomFieldCreateInput) => void;
onArchive: (definitionId: string) => void;
};
export type CustomFieldAdminPageProps = {
vm: CustomFieldAdminVM;
moduleActive: boolean;
submitting: boolean;
errorKey?: string | null;
actions: CustomFieldAdminPageActions;
};
const sectionHeading = "text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary";
export function CustomFieldAdminPage(props: CustomFieldAdminPageProps) {
const { t } = useTranslation();
const [draft, setDraft] = useState<CustomFieldCreateInput>({ key: "", label: "", datentyp: "text", optionen: "" });
const set = (patch: Partial<CustomFieldCreateInput>) => setDraft((s) => ({ ...s, ...patch }));
if (!props.moduleActive) {
return (
<PageShell uiId="ui.crm.admin.customFields">
<PageHeader
icon={<FeatherSlidersHorizontal className={PAGE_HEADER_ICON_CLASS} />}
title={t("crm.admin.customFields.title")}
subtitle={t("crm.admin.customFields.subtitle")}
/>
<PageBody>
<div data-ui-id="ui.crm.admin.customFields.locked">
<EmptyState title={t("crm.locked.headline")} body={t("crm.locked.body")} />
</div>
</PageBody>
</PageShell>
);
}
const rows = props.vm.status === "ready" && props.vm.data ? props.vm.data.rows : [];
return (
<PageShell uiId="ui.crm.admin.customFields">
<PageHeader
icon={<FeatherSlidersHorizontal className={PAGE_HEADER_ICON_CLASS} />}
title={t("crm.admin.customFields.title")}
subtitle={t("crm.admin.customFields.subtitle")}
/>
<PageBody>
{props.errorKey ? <BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback> : null}
{/* Create first, list below: this page exists to add fields, and the
table grows over time — a form pushed below it drifts out of reach. */}
<Card data-ui-id="ui.crm.admin.customFields.create">
<span className={sectionHeading}>{t("crm.admin.customFields.addHeading")}</span>
{/* The inputs share the card's full width evenly (basis-0 + grow), so
they line up as one band instead of sizing themselves by content. */}
<div className="flex w-full flex-col items-stretch gap-4 sm:flex-row sm:items-end">
<TextInput className="w-full min-w-0 sm:w-auto sm:shrink sm:grow sm:basis-0" label={t("crm.admin.customFields.colKey")} showLabel>
<TextInput.Input value={draft.key} onChange={(e) => set({ key: e.target.value })} data-ui-id="ui.crm.admin.customFields.create.key" />
</TextInput>
<TextInput className="w-full min-w-0 sm:w-auto sm:shrink sm:grow sm:basis-0" label={t("crm.admin.customFields.colLabel")} showLabel>
<TextInput.Input value={draft.label} onChange={(e) => set({ label: e.target.value })} data-ui-id="ui.crm.admin.customFields.create.label" />
</TextInput>
<Select
className="w-full min-w-0 sm:w-auto sm:shrink sm:grow sm:basis-0"
label={t("crm.admin.customFields.colType")}
showLabel
value={draft.datentyp}
onValueChange={(v) => set({ datentyp: v })}
>
{DATENTYPEN.map((dt) => (
<Select.Item key={dt} value={dt}>
{t(`crm.datentyp.${dt}`)}
</Select.Item>
))}
</Select>
<TextInput className="w-full min-w-0 sm:w-auto sm:shrink sm:grow sm:basis-0" label={t("crm.admin.customFields.colOptions")} showLabel>
<TextInput.Input
value={draft.optionen}
onChange={(e) => set({ optionen: e.target.value })}
placeholder={t("crm.admin.customFields.optionsPlaceholder")}
/>
</TextInput>
<Button
className="shrink-0"
disabled={!draft.key.trim() || !draft.label.trim()}
onClick={() => {
props.actions.onCreate(draft);
setDraft({ key: "", label: "", datentyp: "text", optionen: "" });
}}
data-ui-id="ui.crm.admin.customFields.create.submit"
>
{t("crm.actions.create")}
</Button>
</div>
</Card>
{rows.length > 0 ? (
<div className="w-full overflow-hidden rounded-lg border border-solid border-border-default shadow-sm overflow-x-auto">
<Table
data-ui-id="ui.crm.admin.customFields.table"
header={
<Table.HeaderRow>
<Table.HeaderCell>{t("crm.admin.customFields.colKey")}</Table.HeaderCell>
<Table.HeaderCell>{t("crm.admin.customFields.colLabel")}</Table.HeaderCell>
<Table.HeaderCell>{t("crm.admin.customFields.colType")}</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-regular-0 font-body-default-regular-0 text-text-neutral-secondary">{row.key}</span>
</Table.Cell>
<Table.Cell>
<div className="flex items-center gap-2">
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-primary">{row.label}</span>
{row.isDemoData ? <BadgeFeedback farbe="subtle-neutral" size="small">{t("crm.admin.demoBadge")}</BadgeFeedback> : null}
{row.archiviert ? <BadgeFeedback farbe="subtle-neutral" size="small">{t("crm.admin.archivedBadge")}</BadgeFeedback> : null}
</div>
</Table.Cell>
<Table.Cell>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">{t(row.datentypLabelKey)}</span>
</Table.Cell>
<Table.Cell className="w-24">
{!row.archiviert ? (
<div className="flex w-full justify-center">
{/* Labelled "delete" but backed by the archive intent: the
definition keeps existing so the values already stored
on contacts are never dropped. */}
<Button
variant="tertiary"
size="small"
loading={props.submitting}
onClick={() => props.actions.onArchive(row.id)}
data-ui-id={`ui.crm.admin.customFields.row.delete.${row.id}`}
>
{t("crm.actions.delete")}
</Button>
</div>
) : null}
</Table.Cell>
</Table.Row>
))}
</Table>
</div>
) : null}
</PageBody>
</PageShell>
);
}
export default CustomFieldAdminPage;
@@ -0,0 +1,75 @@
// R-P6 interim-UI (AD-28) — DuplicateToolPage unit test. Fixture VM via the real
// buildDuplicateVM; asserts the pairs render side-by-side + the empty state. Read-
// only screen (no actions). i18n mocked.
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildDuplicateVM, type DuplicateCardSource } from "@hivegrid/view-models";
import { DuplicateToolPage } from "./DuplicateToolPage";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }) }));
function card(id: string, name: string): DuplicateCardSource {
return {
id,
kontaktTyp: "privatperson",
kontaktStatus: "kontakt",
vorname: name,
nachname: "Muster",
orgName: null,
primaerEmail: "same@example.com",
primaerTelefon: null,
zustaendigerUserId: null,
createdAt: new Date("2026-06-01T10:00:00.000Z"),
};
}
const withPair = buildDuplicateVM({
pairs: [{ matchType: "hard", matchReason: "email", a: card("k1", "Anna"), b: card("k2", "Anna") }],
userLabels: new Map(),
canMerge: false,
tenantSlug: "acme",
});
const empty = buildDuplicateVM({ pairs: [], userLabels: new Map(), canMerge: false, tenantSlug: "acme" });
describe("DuplicateToolPage", () => {
it("renders a side-by-side candidate pair", () => {
render(<DuplicateToolPage vm={withPair} moduleActive detailHrefFor={(id) => `/acme/contacts/${id}`} />);
expect(document.querySelector("[data-ui-id='ui.crm.admin.duplicates.list']")).not.toBeNull();
expect(screen.getAllByText("Anna Muster").length).toBe(2);
});
it("shows the empty state when no duplicates", () => {
render(<DuplicateToolPage vm={empty} moduleActive detailHrefFor={(id) => `/acme/contacts/${id}`} />);
expect(document.querySelector("[data-ui-id='ui.crm.admin.duplicates.empty']")).not.toBeNull();
});
it("hides the delete affordance without crm.delete", () => {
render(<DuplicateToolPage vm={withPair} moduleActive detailHrefFor={(id) => `/acme/contacts/${id}`} actions={{ onDelete: vi.fn() }} />);
expect(document.querySelector("[data-ui-id='ui.crm.admin.duplicates.delete.k1']")).toBeNull();
});
it("confirms before deleting: opens the dialog, then reports the confirmed id", () => {
const onDelete = vi.fn();
render(<DuplicateToolPage vm={withPair} moduleActive canDelete detailHrefFor={(id) => `/acme/contacts/${id}`} actions={{ onDelete }} />);
// The dialog stays closed until the row's delete icon is pressed.
expect(document.querySelector("[data-ui-id='ui.crm.admin.duplicates.delete.dialog']")).toBeNull();
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.admin.duplicates.delete.k1']")!);
expect(document.querySelector("[data-ui-id='ui.crm.admin.duplicates.delete.dialog']")).not.toBeNull();
// Nothing is deleted just by opening the confirm.
expect(onDelete).not.toHaveBeenCalled();
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.admin.duplicates.delete.confirm']")!);
expect(onDelete).toHaveBeenCalledWith("k1");
});
it("cancels without deleting", () => {
const onDelete = vi.fn();
render(<DuplicateToolPage vm={withPair} moduleActive canDelete detailHrefFor={(id) => `/acme/contacts/${id}`} actions={{ onDelete }} />);
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.admin.duplicates.delete.k2']")!);
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.admin.duplicates.delete.cancel']")!);
expect(onDelete).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,152 @@
// R-P6 (P6 CRM core) Interim-UI (AD-28) — duplicate tool (D-CRM "Duplikat-Tool",
// archetype A5), composed from ~/ui. Presentational: renders the server-built
// DuplicateVM candidate pairs side-by-side (DoD 4 surface). Each contact carries a
// destructive delete affordance (permission-gated) that opens an in-app confirm
// dialog before the route hard-deletes it. The actual merge lands in a later phase
// (VM exposes canMerge, kept false). Final Subframe optics = tracked design-nachzug.
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherCopy, FeatherTrash2 } from "@subframe/core";
import type { DuplicateVM } from "@hivegrid/view-models";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Card } from "~/ui/components/Card";
import { Dialog } from "~/ui/components/Dialog";
import { EmptyState } from "~/ui/components/EmptyState";
import { IconButton } from "~/ui/components/IconButton";
import { AppLink } from "~/components/app/AppLink";
export type DuplicateToolPageActions = {
/** Hard-delete a single contact (route POSTs the intent, then revalidates). */
onDelete: (kontaktId: string) => void;
};
export type DuplicateToolPageProps = {
vm: DuplicateVM;
moduleActive: boolean;
detailHrefFor: (kontaktId: string) => string;
/** Gate the destructive affordance on crm.delete (loader-provided). */
canDelete?: boolean;
submitting?: boolean;
actions?: DuplicateToolPageActions;
};
const mutedSmall = "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary";
export function DuplicateToolPage(props: DuplicateToolPageProps) {
const { t } = useTranslation();
// The contact currently pending confirmation (null = dialog closed).
const [pendingDelete, setPendingDelete] = useState<{ id: string; name: string } | null>(null);
if (!props.moduleActive) {
return (
<PageShell uiId="ui.crm.admin.duplicates">
<PageHeader icon={<FeatherCopy className={PAGE_HEADER_ICON_CLASS} />} title={t("crm.admin.duplicates.title")} subtitle={t("crm.admin.duplicates.subtitle")} />
<PageBody>
<div data-ui-id="ui.crm.admin.duplicates.locked">
<EmptyState title={t("crm.locked.headline")} body={t("crm.locked.body")} />
</div>
</PageBody>
</PageShell>
);
}
const pairs = props.vm.status === "ready" && props.vm.data ? props.vm.data.pairs : [];
const canDelete = props.canDelete === true && Boolean(props.actions?.onDelete);
const confirmDelete = () => {
if (pendingDelete) props.actions?.onDelete(pendingDelete.id);
setPendingDelete(null);
};
return (
<PageShell uiId="ui.crm.admin.duplicates">
<PageHeader icon={<FeatherCopy className={PAGE_HEADER_ICON_CLASS} />} title={t("crm.admin.duplicates.title")} subtitle={t("crm.admin.duplicates.subtitle")} />
<PageBody>
{pairs.length === 0 ? (
<div data-ui-id="ui.crm.admin.duplicates.empty">
<EmptyState title={t("crm.admin.duplicates.empty")} />
</div>
) : (
<div className="flex w-full flex-col gap-4" data-ui-id="ui.crm.admin.duplicates.list">
{pairs.map((pair, index) => (
<Card key={`${pair.a.id}-${pair.b.id}-${index}`} data-row-id={`${pair.a.id}-${pair.b.id}`}>
<div className="flex items-center gap-2">
<BadgeFeedback farbe={pair.matchType === "hard" ? "subtle-negative" : "subtle-warning"} size="small">
{t(`crm.duplicate.matchType.${pair.matchType}`)}
</BadgeFeedback>
<span className={mutedSmall}>{t(pair.matchReasonKey)}</span>
</div>
<div className="grid w-full gap-3 sm:grid-cols-2">
{[pair.a, pair.b].map((card) => (
<div key={card.id} className="flex flex-col gap-1 rounded-sm border border-solid border-border-default p-3">
<div className="flex w-full items-start justify-between gap-2">
<AppLink href={props.detailHrefFor(card.id)} className="text-body-default-medium-0 font-body-default-medium-0 text-text-feedback-link-default">
{card.displayName}
</AppLink>
{canDelete ? (
<IconButton
variant="destructive"
size="small"
icon={<FeatherTrash2 />}
loading={props.submitting}
aria-label={t("crm.admin.duplicates.delete.action")}
onClick={() => setPendingDelete({ id: card.id, name: card.displayName })}
data-ui-id={`ui.crm.admin.duplicates.delete.${card.id}`}
/>
) : null}
</div>
<span className={mutedSmall}>{t(card.statusLabelKey)}</span>
{card.primaerEmail ? <span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">{card.primaerEmail}</span> : null}
{card.primaerTelefon ? <span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">{card.primaerTelefon}</span> : null}
{card.zustaendigerLabel ? <span className={mutedSmall}>{card.zustaendigerLabel}</span> : null}
</div>
))}
</div>
</Card>
))}
</div>
)}
</PageBody>
<Dialog open={pendingDelete !== null} onOpenChange={(open) => (open ? undefined : setPendingDelete(null))}>
<Dialog.Content className="w-[420px] max-w-[92vw] p-6" data-ui-id="ui.crm.admin.duplicates.delete.dialog">
<div className="flex w-full flex-col gap-6">
<div className="flex w-full flex-col gap-2">
<span className="text-heading-0 font-heading-0 text-text-neutral-primary">{t("crm.admin.duplicates.delete.title")}</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t("crm.admin.duplicates.delete.body", { name: pendingDelete?.name ?? "" })}
</span>
</div>
<div className="flex w-full items-center justify-end gap-2 mobile:flex-col-reverse mobile:items-stretch">
<Button
type="button"
variant="tertiary"
className="mobile:w-full"
onClick={() => setPendingDelete(null)}
data-ui-id="ui.crm.admin.duplicates.delete.cancel"
>
{t("shared.cancel")}
</Button>
<Button
type="button"
variant="destructive"
className="mobile:w-full"
icon={<FeatherTrash2 />}
loading={props.submitting}
onClick={confirmDelete}
data-ui-id="ui.crm.admin.duplicates.delete.confirm"
>
{t("crm.admin.duplicates.delete.action")}
</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
</PageShell>
);
}
export default DuplicateToolPage;
@@ -0,0 +1,143 @@
// R-P6 interim-UI (AD-28) — KontaktDetailPage unit test. Fixture data built via
// the real buildKontaktDetailVM / buildActivityStreamVM; interactions asserted on
// the injected onSubmit callback. i18n mocked so `t` echoes the key.
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildActivityStreamVM, buildKontaktDetailVM, type BuildKontaktDetailVMInput, type KontaktDetailData } from "@hivegrid/view-models";
import { KontaktDetailPage, type KontaktDetailPageActions } from "./KontaktDetailPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }),
}));
const emptyActivity = buildActivityStreamVM({ rows: [], userLabels: new Map(), hasMore: false });
function detailData(over: Partial<BuildKontaktDetailVMInput> = {}, perms = { canWrite: true, canDelete: true, canInviteToPortal: true }): KontaktDetailData {
const vm = buildKontaktDetailVM({
detail: {
kontakt: {
id: "k1",
kontaktTyp: "privatperson",
kontaktStatus: "kontakt",
vorname: "Anna",
nachname: "Muster",
orgName: null,
orgMerkmal: null,
primaerEmail: "anna@example.com",
zustaendigerUserId: null,
archivedAt: null,
createdAt: new Date("2026-06-01T10:00:00.000Z"),
updatedAt: new Date("2026-06-02T10:00:00.000Z"),
},
emails: [{ id: "e1", email: "anna@example.com", primaer: true }],
telefone: [],
relationen: [],
adresse: null,
},
customFields: [],
tags: [],
userLabels: new Map(),
perms,
tenantSlug: "acme",
...over,
});
if (vm.status !== "ready" || !vm.data) throw new Error("fixture not ready");
return vm.data;
}
function actions(over: Partial<KontaktDetailPageActions> = {}): KontaktDetailPageActions {
return { onSubmit: vi.fn(), ...over };
}
function renderPage(props: Partial<Parameters<typeof KontaktDetailPage>[0]> = {}) {
const acts = props.actions ?? actions();
render(
<KontaktDetailPage
data={props.data ?? detailData()}
activity={props.activity ?? emptyActivity}
allTags={props.allTags ?? []}
customFieldDefs={props.customFieldDefs ?? []}
ownerOptions={props.ownerOptions ?? [{ id: "u1", label: "Owner One" }]}
backHref="/acme/contacts"
listLabelKey="crm.contacts.title"
submitting={false}
errorKey={null}
actions={acts}
{...props}
/>
);
return acts;
}
describe("KontaktDetailPage", () => {
it("renders the name and the main sections", () => {
renderPage();
expect(screen.getAllByText("Anna Muster").length).toBeGreaterThan(0);
expect(document.querySelector("[data-ui-id='ui.crm.detail.basics']")).not.toBeNull();
expect(document.querySelector("[data-ui-id='ui.crm.detail.activity']")).not.toBeNull();
});
it("saves the inline-edited basics via updateBasics", () => {
const onSubmit = vi.fn();
renderPage({ actions: actions({ onSubmit }) });
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.detail.basics.save']")!);
expect(onSubmit).toHaveBeenCalledWith("updateBasics", expect.objectContaining({ vorname: "Anna", nachname: "Muster", kontaktStatus: "kontakt" }));
});
it("adds an email via addEmail", () => {
const onSubmit = vi.fn();
renderPage({ actions: actions({ onSubmit }) });
fireEvent.change(document.querySelector("[data-ui-id='ui.crm.detail.emails.new']")!, { target: { value: "neu@example.com" } });
const addButtons = screen.getAllByText("crm.actions.add");
fireEvent.click(addButtons[0]);
expect(onSubmit).toHaveBeenCalledWith("addEmail", expect.objectContaining({ email: "neu@example.com" }));
});
it("archives and deletes via the quick actions", () => {
const onSubmit = vi.fn();
renderPage({ actions: actions({ onSubmit }) });
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.detail.archive']")!);
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.detail.delete']")!);
expect(onSubmit).toHaveBeenCalledWith("archive");
expect(onSubmit).toHaveBeenCalledWith("delete");
});
it("offers the gated portal invitation through the injected route action", () => {
const onSubmit = vi.fn();
renderPage({ actions: actions({ onSubmit }) });
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.detail.portalInvite']")!);
expect(onSubmit).toHaveBeenCalledWith("invitePortalContact");
});
it("shows clear feedback after the setup invitation was queued", () => {
renderPage({ messageKey: "customerPortal.invitation.sent" });
expect(document.querySelector("[data-ui-id='ui.crm.detail.portalInviteSuccess']")).not.toBeNull();
expect(screen.getByText("customerPortal.invitation.sent")).toBeTruthy();
});
it("hides write affordances without canWrite", () => {
renderPage({ data: detailData({}, { canWrite: false, canDelete: false, canInviteToPortal: false }) });
expect(document.querySelector("[data-ui-id='ui.crm.detail.basics.save']")).toBeNull();
expect(document.querySelector("[data-ui-id='ui.crm.detail.actions']")).toBeNull();
expect(document.querySelector("[data-ui-id='ui.crm.detail.portalInvite']")).toBeNull();
});
it("exposes click-to-call only through the optional VM and callback prop", () => {
const onCall = vi.fn();
const number = { id: "phone-1", label: "Mobil", e164: "+491701234567", primary: true } as const;
renderPage({
clickToCall: {
vm: { mode: "provider", numbers: [number], requiresSelection: false, reasonKey: null },
onCall,
},
});
fireEvent.click(screen.getByRole("button", { name: "telephony.clickToCall.open" }));
fireEvent.click(screen.getByRole("button", { name: "telephony.clickToCall.startCall" }));
expect(onCall).toHaveBeenCalledWith(number, "provider");
});
});
@@ -0,0 +1,551 @@
// R-P6 (P6 CRM core) Interim-UI (AD-28) — contact/organisation detail screen
// (D-CRM "Kontakt-Detail"/"Organisation-Detail", archetype A3, master template),
// composed from ~/ui. Pure/presentational: it renders the server-built
// KontaktDetailVM data + ActivityStreamVM and turns every inline-edit into a
// single typed onSubmit(intent, fields) callback the route POSTs. No
// useLoaderData/useFetcher, no server imports. Final Subframe optics = tracked
// design-nachzug.
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { AppLink } from "~/components/app/AppLink";
import { FeatherBuilding2, FeatherUser } from "@subframe/core";
import type { ActivityStreamVM, KontaktDetailData } from "@hivegrid/view-models";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { Alert } from "~/ui/components/Alert";
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 { EmptyState } from "~/ui/components/EmptyState";
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";
/** POST a detail-edit intent with its string fields. The route builds the
* FormData + submits; unknown fields are ignored server-side. */
export type KontaktDetailSubmit = (intent: string, fields?: Record<string, string>) => void;
export type KontaktDetailPageActions = { onSubmit: KontaktDetailSubmit };
export type KontaktDetailTagOption = { id: string; name: string; farbe: string };
export type KontaktDetailCustomFieldDef = { id: string; key: string; label: string; datentyp: string; datentypLabelKey: string };
export type KontaktDetailOwnerOption = { id: string; label: string };
export type KontaktDetailPageProps = {
data: KontaktDetailData;
activity: ActivityStreamVM;
allTags: readonly KontaktDetailTagOption[];
customFieldDefs: readonly KontaktDetailCustomFieldDef[];
ownerOptions: readonly KontaktDetailOwnerOption[];
listLabelKey: string;
backHref: string;
/** Tag-Verwaltung link, shown as next action when the tenant has no tags yet. */
tagsAdminHref?: string;
submitting: boolean;
errorKey?: string | null;
messageKey?: string | null;
language?: string;
/** Optional telephony affordance; omitted when the feature or permission gate is closed. */
clickToCall?: ClickToCallEntryPointProps;
actions: KontaktDetailPageActions;
};
const sectionHeading = "text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary";
const subHeading = "text-body-small-semibold-150 font-body-small-semibold-150 text-text-neutral-primary";
const mutedText = "text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary";
export function KontaktDetailPage(props: KontaktDetailPageProps) {
const { t, i18n } = useTranslation();
const { data } = props;
const isOrg = data.kontaktTyp === "organisation";
const submit = props.actions.onSubmit;
const dateTime = new Intl.DateTimeFormat(props.language ?? i18n.language, { timeZone: APP_TIME_ZONE, dateStyle: "medium", timeStyle: "short" });
// Inline-edit basics draft.
const [basics, setBasics] = useState({
vorname: data.vorname ?? "",
nachname: data.nachname ?? "",
orgName: data.orgName ?? "",
orgMerkmal: data.orgMerkmal ?? "",
kontaktStatus: data.kontaktStatus as string,
});
// Add-form drafts.
const [newEmail, setNewEmail] = useState({ email: "", primaer: false });
const [newTelefon, setNewTelefon] = useState({ telefon: "", primaer: false });
const [newRelation, setNewRelation] = useState({ zuKontaktId: "", rolle: "hauptkontakt", kontext: "" });
const [tagToAdd, setTagToAdd] = useState(props.allTags[0]?.id ?? "");
const [cf, setCf] = useState({ definitionId: props.customFieldDefs[0]?.id ?? "", wert: "" });
const [reassignTo, setReassignTo] = useState(data.zustaendigerUserId ?? "");
const [note, setNote] = useState("");
// Single top-right "Speichern": persists the basics form and, when the owner
// actually changed, the reassignment too — server folds both into one
// updateBasics intent (no separate "Zuweisen" button anymore).
function saveAll() {
const ownerChanged = reassignTo !== (data.zustaendigerUserId ?? "");
submit("updateBasics", {
...(isOrg
? { orgName: basics.orgName, orgMerkmal: basics.orgMerkmal, kontaktStatus: basics.kontaktStatus }
: { vorname: basics.vorname, nachname: basics.nachname, kontaktStatus: basics.kontaktStatus }),
...(ownerChanged && reassignTo ? { zustaendigerUserId: reassignTo } : {}),
});
}
return (
<PageShell uiId="ui.crm.detail" className="bg-surface-neutral-primary">
<PageHeader
icon={isOrg ? <FeatherBuilding2 className={PAGE_HEADER_ICON_CLASS} /> : <FeatherUser className={PAGE_HEADER_ICON_CLASS} />}
title={
<span className="inline-flex flex-wrap items-center gap-2">
{data.displayName}
{data.isArchived ? (
<BadgeFeedback farbe="subtle-negative" size="small">
{t("crm.detail.archivedBadge")}
</BadgeFeedback>
) : null}
</span>
}
subtitle={`${t(data.typLabelKey)} · ${t(data.statusLabelKey)}`}
actions={
props.clickToCall || data.canInviteToPortal || data.canWrite ? (
<>
{props.clickToCall ? <ClickToCallEntryPoint {...props.clickToCall} /> : null}
{data.canInviteToPortal ? (
<Button
variant="neutral"
loading={props.submitting}
onClick={() => submit("invitePortalContact")}
data-ui-id="ui.crm.detail.portalInvite"
>
{t("customerPortal.admin.users.invite")}
</Button>
) : null}
{data.canWrite ? (
<Button loading={props.submitting} onClick={saveAll} data-ui-id="ui.crm.detail.basics.save">
{t("crm.actions.save")}
</Button>
) : null}
</>
) : undefined
}
/>
<PageBody>
<div className="mx-auto flex w-full max-w-7xl flex-col gap-6">
{props.errorKey ? (
<div data-ui-id="ui.crm.detail.error">
<BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback>
</div>
) : null}
{props.messageKey ? (
<Alert
variant="success"
title={t("customerPortal.invitation.successTitle")}
description={t(props.messageKey)}
data-ui-id="ui.crm.detail.portalInviteSuccess"
/>
) : null}
{/* --- Basics (inline edit) --- */}
<Card data-ui-id="ui.crm.detail.basics">
<span className={sectionHeading}>{t("crm.detail.section.basics")}</span>
{data.canWrite ? (
<div className="grid w-full gap-4 sm:grid-cols-2">
{isOrg ? (
<>
<TextInput label={t("crm.fields.orgName")} showLabel>
<TextInput.Input value={basics.orgName} onChange={(e) => setBasics((s) => ({ ...s, orgName: e.target.value }))} />
</TextInput>
<Select
label={t("crm.fields.orgMerkmal")}
showLabel
value={basics.orgMerkmal || "__none__"}
onValueChange={(v) => setBasics((s) => ({ ...s, orgMerkmal: v === "__none__" ? "" : v }))}
>
<Select.Item value="__none__">{t("crm.fields.none")}</Select.Item>
{(["gmbh", "kg", "oeffentliche_einrichtung", "sonstige"] as const).map((m) => (
<Select.Item key={m} value={m}>
{t(`crm.orgMerkmal.${m}`)}
</Select.Item>
))}
</Select>
</>
) : (
<>
<TextInput label={t("crm.fields.vorname")} showLabel>
<TextInput.Input value={basics.vorname} onChange={(e) => setBasics((s) => ({ ...s, vorname: e.target.value }))} />
</TextInput>
<TextInput label={t("crm.fields.nachname")} showLabel>
<TextInput.Input value={basics.nachname} onChange={(e) => setBasics((s) => ({ ...s, nachname: e.target.value }))} />
</TextInput>
</>
)}
<Select label={t("crm.fields.status")} showLabel value={basics.kontaktStatus} onValueChange={(v) => setBasics((s) => ({ ...s, kontaktStatus: v }))}>
{(["kontakt", "kunde", "bestandskunde"] as const).map((st) => (
<Select.Item key={st} value={st}>
{t(`crm.kontaktStatus.${st}`)}
</Select.Item>
))}
</Select>
</div>
) : (
<div className="flex flex-col gap-1">
<span className={mutedText}>
{t("crm.fields.status")}: {t(data.statusLabelKey)}
</span>
{data.orgMerkmalLabelKey ? (
<span className={mutedText}>
{t("crm.fields.orgMerkmal")}: {t(data.orgMerkmalLabelKey)}
</span>
) : null}
</div>
)}
</Card>
{/* --- Contact data: emails / phones / address / relations / tags / custom
fields combined into one wide card with a 2-column grid so each section
uses the horizontal space instead of leaving the right half empty. --- */}
<Card data-ui-id="ui.crm.detail.contactData">
<div className="grid w-full grid-cols-1 items-start gap-x-8 gap-y-6 lg:grid-cols-2">
{/* Left column: communication channels (emails, phones, address). Two
independent flex columns keep each section's height self-contained,
so no empty gaps appear from grid row-height coupling. */}
<div className="flex w-full flex-col gap-6">
{/* --- Emails --- */}
<section className="flex w-full flex-col gap-3" data-ui-id="ui.crm.detail.emails">
<span className={subHeading}>{t("crm.detail.section.emails")}</span>
<div className="flex w-full flex-col gap-2">
{data.emails.map((email) => (
<div key={email.id} className="flex items-center gap-2" data-row-id={email.id}>
<span className={mutedText}>{email.email}</span>
{email.primaer ? (
<BadgeFeedback farbe="subtle-brand-primary" size="small">
{t("crm.detail.primary")}
</BadgeFeedback>
) : null}
{data.canWrite && !email.primaer ? (
<Button variant="tertiary" size="small" onClick={() => submit("setPrimaryEmail", { emailId: email.id })}>
{t("crm.actions.makePrimary")}
</Button>
) : null}
{data.canWrite ? (
<Button variant="tertiary" size="small" onClick={() => submit("removeEmail", { emailId: email.id })}>
{t("crm.actions.remove")}
</Button>
) : null}
</div>
))}
</div>
{data.canWrite ? (
<div className="flex flex-wrap items-end gap-2">
<TextInput label={t("crm.fields.email")} showLabel>
<TextInput.Input
type="email"
value={newEmail.email}
onChange={(e) => setNewEmail((s) => ({ ...s, email: e.target.value }))}
data-ui-id="ui.crm.detail.emails.new"
/>
</TextInput>
<div className="flex h-9 items-center">
<Checkbox checked={newEmail.primaer} onCheckedChange={(c) => setNewEmail((s) => ({ ...s, primaer: c }))} label={t("crm.detail.primary")} />
</div>
<Button
variant="neutral"
disabled={!newEmail.email.trim()}
onClick={() => {
submit("addEmail", { email: newEmail.email.trim(), ...(newEmail.primaer ? { primaer: "1" } : {}) });
setNewEmail({ email: "", primaer: false });
}}
>
{t("crm.actions.add")}
</Button>
</div>
) : null}
</section>
{/* --- Phones --- */}
<section className="flex w-full flex-col gap-3" data-ui-id="ui.crm.detail.telefone">
<span className={subHeading}>{t("crm.detail.section.telefone")}</span>
<div className="flex w-full flex-col gap-2">
{data.telefone.map((tel) => (
<div key={tel.id} className="flex items-center gap-2" data-row-id={tel.id}>
<span className={mutedText}>{tel.telefon}</span>
{tel.primaer ? (
<BadgeFeedback farbe="subtle-brand-primary" size="small">
{t("crm.detail.primary")}
</BadgeFeedback>
) : null}
{data.canWrite && !tel.primaer ? (
<Button variant="tertiary" size="small" onClick={() => submit("setPrimaryTelefon", { telefonId: tel.id })}>
{t("crm.actions.makePrimary")}
</Button>
) : null}
{data.canWrite ? (
<Button variant="tertiary" size="small" onClick={() => submit("removeTelefon", { telefonId: tel.id })}>
{t("crm.actions.remove")}
</Button>
) : null}
</div>
))}
</div>
{data.canWrite ? (
<div className="flex flex-wrap items-end gap-2">
<TextInput label={t("crm.fields.telefon")} showLabel>
<TextInput.Input
value={newTelefon.telefon}
onChange={(e) => setNewTelefon((s) => ({ ...s, telefon: e.target.value }))}
data-ui-id="ui.crm.detail.telefone.new"
/>
</TextInput>
<div className="flex h-9 items-center">
<Checkbox checked={newTelefon.primaer} onCheckedChange={(c) => setNewTelefon((s) => ({ ...s, primaer: c }))} label={t("crm.detail.primary")} />
</div>
<Button
variant="neutral"
disabled={!newTelefon.telefon.trim()}
onClick={() => {
submit("addTelefon", { telefon: newTelefon.telefon.trim(), ...(newTelefon.primaer ? { primaer: "1" } : {}) });
setNewTelefon({ telefon: "", primaer: false });
}}
>
{t("crm.actions.add")}
</Button>
</div>
) : null}
</section>
{/* --- Address (read-only) --- */}
{data.adresse ? (
<section className="flex w-full flex-col gap-3" data-ui-id="ui.crm.detail.adresse">
<span className={subHeading}>{t("crm.detail.section.adresse")}</span>
<span className={mutedText}>
{[data.adresse.strasse, data.adresse.hausnummer].filter(Boolean).join(" ")}
{data.adresse.plz || data.adresse.ort ? `, ${[data.adresse.plz, data.adresse.ort].filter(Boolean).join(" ")}` : ""}
{`, ${data.adresse.land}`}
</span>
</section>
) : null}
</div>
{/* Right column: relations, tags and custom fields. */}
<div className="flex w-full flex-col gap-6">
{/* --- Relations --- */}
<section className="flex w-full flex-col gap-3" data-ui-id="ui.crm.detail.relations">
<span className={subHeading}>{t("crm.detail.section.relations")}</span>
<div className="flex w-full flex-col gap-2">
{data.relationen.map((rel) => (
<div key={rel.id} className="flex items-center gap-2" data-row-id={rel.id}>
<span className={mutedText}>{rel.otherKontaktId}</span>
<BadgeFeedback farbe="subtle-neutral" size="small">
{t(rel.rolleLabelKey)}
</BadgeFeedback>
{rel.kontext ? <span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">{rel.kontext}</span> : null}
{data.canWrite ? (
<Button variant="tertiary" size="small" onClick={() => submit("removeRelation", { relationId: rel.id })}>
{t("crm.actions.remove")}
</Button>
) : null}
</div>
))}
</div>
{data.canWrite ? (
<div className="flex flex-wrap items-end gap-2">
<TextInput label={t("crm.fields.relationTarget")} showLabel>
<TextInput.Input value={newRelation.zuKontaktId} onChange={(e) => setNewRelation((s) => ({ ...s, zuKontaktId: e.target.value }))} />
</TextInput>
<Select label={t("crm.fields.relationRole")} showLabel value={newRelation.rolle} onValueChange={(v) => setNewRelation((s) => ({ ...s, rolle: v }))}>
{(["hauptkontakt", "sekundaerkontakt", "mitarbeiter", "sonstige"] as const).map((r) => (
<Select.Item key={r} value={r}>
{t(`crm.kontaktArt.${r}`)}
</Select.Item>
))}
</Select>
<TextInput label={t("crm.fields.relationContext")} showLabel>
<TextInput.Input value={newRelation.kontext} onChange={(e) => setNewRelation((s) => ({ ...s, kontext: e.target.value }))} />
</TextInput>
<Button
variant="neutral"
disabled={!newRelation.zuKontaktId.trim()}
onClick={() => {
submit("addRelation", { zuKontaktId: newRelation.zuKontaktId.trim(), rolle: newRelation.rolle, kontext: newRelation.kontext });
setNewRelation({ zuKontaktId: "", rolle: "hauptkontakt", kontext: "" });
}}
>
{t("crm.actions.add")}
</Button>
</div>
) : null}
</section>
{/* --- Tags --- */}
<section className="flex w-full flex-col gap-3" data-ui-id="ui.crm.detail.tags">
<span className={subHeading}>{t("crm.detail.section.tags")}</span>
<div className="flex w-full flex-wrap gap-2">
{data.tags.map((tag) => (
<span key={tag.id} className="border-border-default inline-flex items-center gap-1 rounded-sm border border-solid px-2 py-1" data-row-id={tag.id}>
<span aria-hidden className="inline-block h-2 w-2 rounded-full" style={{ backgroundColor: tag.farbe }} />
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">{tag.name}</span>
{data.canWrite ? (
<button
type="button"
className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary underline"
onClick={() => submit("removeTag", { tagId: tag.id })}
>
{t("crm.actions.remove")}
</button>
) : null}
</span>
))}
</div>
{data.canWrite && props.allTags.length === 0 ? (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("crm.detail.tags.emptyHint")}{" "}
{props.tagsAdminHref ? (
<AppLink href={props.tagsAdminHref} className="text-text-feedback-link-default underline">
{t("crm.admin.tags.title")}
</AppLink>
) : null}
</span>
) : null}
{data.canWrite && props.allTags.length > 0 ? (
<div className="flex items-end gap-2">
<Select label={t("crm.fields.tag")} showLabel value={tagToAdd} onValueChange={setTagToAdd}>
{props.allTags.map((tag) => (
<Select.Item key={tag.id} value={tag.id}>
{tag.name}
</Select.Item>
))}
</Select>
<Button variant="neutral" disabled={!tagToAdd} onClick={() => submit("addTag", { tagId: tagToAdd })}>
{t("crm.actions.add")}
</Button>
</div>
) : null}
</section>
{/* --- Custom fields --- */}
<section className="flex w-full flex-col gap-3" data-ui-id="ui.crm.detail.customFields">
<span className={subHeading}>{t("crm.detail.section.customFields")}</span>
<div className="flex w-full flex-col gap-1">
{data.customFields.map((field) => (
<div key={field.definitionId} className="flex items-center gap-2" data-row-id={field.definitionId}>
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-tertiary">{field.label}:</span>
<span className={mutedText}>{field.wert == null ? "—" : String(field.wert)}</span>
</div>
))}
</div>
{data.canWrite && props.customFieldDefs.length > 0 ? (
<div className="flex flex-wrap items-end gap-2">
<Select label={t("crm.fields.customField")} showLabel value={cf.definitionId} onValueChange={(v) => setCf((s) => ({ ...s, definitionId: v }))}>
{props.customFieldDefs.map((def) => (
<Select.Item key={def.id} value={def.id}>
{def.label}
</Select.Item>
))}
</Select>
<TextInput label={t("crm.fields.value")} showLabel>
<TextInput.Input value={cf.wert} onChange={(e) => setCf((s) => ({ ...s, wert: e.target.value }))} />
</TextInput>
<Button variant="neutral" disabled={!cf.definitionId} onClick={() => submit("setCustomField", { definitionId: cf.definitionId, wert: cf.wert })}>
{t("crm.actions.save")}
</Button>
</div>
) : null}
</section>
</div>
</div>
</Card>
{/* --- Quick actions --- */}
{data.canWrite || data.canDelete ? (
<Card data-ui-id="ui.crm.detail.actions">
<span className={sectionHeading}>{t("crm.detail.section.actions")}</span>
{data.canWrite ? (
<div className="flex flex-wrap items-end gap-2">
<Select
label={t("crm.fields.owner")}
showLabel
value={reassignTo || "__none__"}
onValueChange={(v) => setReassignTo(v === "__none__" ? "" : v)}
>
<Select.Item value="__none__">{t("crm.fields.none")}</Select.Item>
{props.ownerOptions.map((option) => (
<Select.Item key={option.id} value={option.id}>
{option.label}
</Select.Item>
))}
</Select>
</div>
) : null}
{data.canWrite ? (
<div className="flex w-full flex-col gap-2">
<TextArea label={t("crm.fields.note")} showLabel>
<TextArea.Input value={note} onChange={(e) => setNote(e.target.value)} data-ui-id="ui.crm.detail.note" />
</TextArea>
<div className="flex">
<Button
variant="neutral"
disabled={!note.trim()}
onClick={() => {
submit("addNote", { note: note.trim() });
setNote("");
}}
data-ui-id="ui.crm.detail.addNote"
>
{t("crm.actions.addNote")}
</Button>
</div>
</div>
) : null}
<div className="flex flex-wrap gap-3">
{data.canWrite ? (
<Button variant="neutral" onClick={() => submit(data.isArchived ? "reactivate" : "archive")} data-ui-id="ui.crm.detail.archive">
{t(data.isArchived ? "crm.actions.reactivate" : "crm.actions.archive")}
</Button>
) : null}
{data.canDelete ? (
<Button variant="destructive" onClick={() => submit("delete")} data-ui-id="ui.crm.detail.delete">
{t("crm.actions.delete")}
</Button>
) : null}
</div>
</Card>
) : null}
{/* --- Activity stream --- */}
<Card data-ui-id="ui.crm.detail.activity">
<span className={sectionHeading}>{t("crm.detail.section.activity")}</span>
{props.activity.status === "ready" && props.activity.data && props.activity.data.entries.length > 0 ? (
<div className="flex w-full flex-col gap-3">
{props.activity.data.entries.map((entry) => (
<div key={entry.id} className="border-border-default flex flex-col gap-0.5 border-l-2 border-solid pl-3" data-row-id={entry.id}>
<span className={mutedText}>{entry.summaryKey ? t(entry.summaryKey) : entry.summaryText}</span>
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{t(entry.activityLabelKey)}
{entry.actorLabel ? ` · ${entry.actorLabel}` : ""} · {dateTime.format(new Date(entry.createdAtIso))}
</span>
</div>
))}
</div>
) : (
<div className="w-full" data-ui-id="ui.crm.detail.activity.empty">
<EmptyState title={t("crm.detail.activityEmpty")} />
</div>
)}
</Card>
</div>
</PageBody>
</PageShell>
);
}
export default KontaktDetailPage;
@@ -0,0 +1,365 @@
// R-P6 interim-UI (AD-28) — KontaktListPage unit test. Fixture VM built via the
// real buildKontaktListVM, rendered, interactions asserted on the injected action
// callbacks (not on rendered copy). i18n is mocked so `t` echoes the key.
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import "@testing-library/jest-dom/vitest";
import { describe, expect, it, vi } from "vitest";
import { buildKontaktListVM, type KontaktListSourceRow } from "@hivegrid/view-models";
import type { KontaktListQuery } from "~/utils/integrations/crm/kontaktListQuery";
import { KontaktListPage, type KontaktListPageActions } from "./KontaktListPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }),
}));
const QUERY: KontaktListQuery = {
filter: {
kontaktTyp: null,
kontaktStatus: null,
zustaendigerUserId: null,
search: null,
tagIds: null,
tagMatch: "or",
includeArchived: false,
includeDemoData: false,
},
sort: { field: "createdAt", dir: "desc" },
page: 1,
};
function sourceRow(id: string, over: Partial<KontaktListSourceRow> = {}): KontaktListSourceRow {
return {
id,
kontaktTyp: "privatperson",
kontaktStatus: "kontakt",
vorname: "Anna",
nachname: "Muster",
orgName: null,
orgMerkmal: null,
primaerEmail: "anna@example.com",
primaerTelefon: "+49 30 1234",
zustaendigerUserId: null,
createdAt: new Date("2026-06-01T10:00:00.000Z"),
archivedAt: null,
...over,
};
}
function vm(rows: KontaktListSourceRow[], perms = { canWrite: true, canDelete: true, canReadAll: true }) {
return buildKontaktListVM({
rows,
userLabels: new Map(),
tagsByKontakt: new Map(),
pagination: { page: 1, pageCount: 1, total: rows.length },
sort: QUERY.sort,
filter: QUERY.filter,
perms,
tenantSlug: "acme",
});
}
function actions(over: Partial<KontaktListPageActions> = {}): KontaktListPageActions {
return {
onApplyFilter: vi.fn(),
onGoToPage: vi.fn(),
onBulk: vi.fn(),
onExport: vi.fn(),
onNavigate: vi.fn(),
onAssignTag: vi.fn(),
onRemoveTag: vi.fn(),
...over,
};
}
function pageElement(props: Partial<Parameters<typeof KontaktListPage>[0]>, acts: KontaktListPageActions) {
return (
<KontaktListPage
vm={props.vm ?? vm([sourceRow("k1")])}
variant="contacts"
moduleActive
query={QUERY}
tagOptions={[{ id: "t1", name: "VIP", farbe: "#f00" }]}
ownerOptions={[{ id: "u1", label: "Owner One" }]}
canWrite
canAdmin
nav={{ contactsHref: "/acme/contacts", companiesHref: "/acme/contacts/companies", customFieldsHref: "/acme/contacts/admin/custom-fields", tagsHref: "/acme/contacts/admin/tags", duplicatesHref: "/acme/contacts/admin/duplicates" }}
newHref="/acme/contacts/new"
defaultOwnerId="u1"
errorKey={null}
actions={acts}
{...props}
/>
);
}
function renderPage(props: Partial<Parameters<typeof KontaktListPage>[0]> = {}) {
const acts = props.actions ?? actions();
render(pageElement(props, acts));
return acts;
}
describe("KontaktListPage", () => {
it("renders the locked state when the module is inactive", () => {
renderPage({ moduleActive: false });
expect(document.querySelector("[data-ui-id='ui.crm.list.locked']")).not.toBeNull();
expect(document.querySelector("[data-ui-id='ui.crm.list.table']")).toBeNull();
});
it("renders a row and the table for a ready VM", () => {
renderPage();
expect(document.querySelector("[data-ui-id='ui.crm.list.table']")).not.toBeNull();
expect(screen.getByText("Anna Muster")).toBeTruthy();
});
it("replaces the contact/company nav pills with a Typ filter dropdown", () => {
renderPage();
// The two list pills are gone — the type split is now a filter dropdown.
expect(document.querySelector("[data-ui-id='ui.crm.list.nav.contacts']")).toBeNull();
expect(document.querySelector("[data-ui-id='ui.crm.list.nav.companies']")).toBeNull();
expect(document.querySelector("[data-ui-id='ui.crm.list.filter.typ']")).not.toBeNull();
});
it("exposes the admin entry points as header buttons and navigates on click", () => {
const onNavigate = vi.fn();
renderPage({ actions: actions({ onNavigate }) });
const customFields = document.querySelector("[data-ui-id='ui.crm.list.admin.customFields']");
const tags = document.querySelector("[data-ui-id='ui.crm.list.admin.tags']");
const duplicates = document.querySelector("[data-ui-id='ui.crm.list.admin.duplicates']");
expect(customFields).not.toBeNull();
expect(tags).not.toBeNull();
expect(duplicates).not.toBeNull();
// The body no longer carries the secondary nav row.
expect(document.querySelector("[data-ui-id='ui.crm.list.nav']")).toBeNull();
fireEvent.click(customFields!);
expect(onNavigate).toHaveBeenCalledWith("/acme/contacts/admin/custom-fields");
fireEvent.click(tags!);
expect(onNavigate).toHaveBeenCalledWith("/acme/contacts/admin/tags");
fireEvent.click(duplicates!);
expect(onNavigate).toHaveBeenCalledWith("/acme/contacts/admin/duplicates");
});
it("hides the admin header buttons without admin permission", () => {
renderPage({ canAdmin: false });
expect(document.querySelector("[data-ui-id='ui.crm.list.admin.customFields']")).toBeNull();
expect(document.querySelector("[data-ui-id='ui.crm.list.admin.tags']")).toBeNull();
expect(document.querySelector("[data-ui-id='ui.crm.list.admin.duplicates']")).toBeNull();
// The Typ filter stays — it is a filter, not an admin affordance.
expect(document.querySelector("[data-ui-id='ui.crm.list.filter.typ']")).not.toBeNull();
});
it("fires onExport from the header actions", () => {
const acts = renderPage();
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.export']")!);
expect(acts.onExport).toHaveBeenCalledTimes(1);
});
it("opens the create dialog instead of navigating to the create page", () => {
renderPage();
expect(document.querySelector("[data-ui-id='ui.crm.new.dialog']")).toBeNull();
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.new']")!);
const form = document.querySelector("[data-ui-id='ui.crm.new.dialog']") as HTMLFormElement;
expect(form.getAttribute("action")).toBe("/acme/contacts/new");
expect(form.getAttribute("method")).toBe("post");
// A contact needs a name before it can be submitted.
const submit = document.querySelector("[data-ui-id='ui.crm.new.dialog.submit']") as HTMLButtonElement;
expect(submit.disabled).toBe(true);
fireEvent.change(document.querySelector("[data-ui-id='ui.crm.new.dialog.vorname']")!, { target: { value: "Anna" } });
expect((document.querySelector("[data-ui-id='ui.crm.new.dialog.submit']") as HTMLButtonElement).disabled).toBe(false);
});
it("applies a filter with the current draft (search + reset to page 1)", async () => {
const onApplyFilter = vi.fn();
renderPage({ actions: actions({ onApplyFilter }) });
// The shared bar's box has no Enter key of its own: the term settles and
// applies itself, the same way it does on the files browser and the boards.
fireEvent.change(document.querySelector("[data-ui-id='ui.crm.list.filter.search']")!, { target: { value: "berlin" } });
await waitFor(() => expect(onApplyFilter).toHaveBeenCalledTimes(1));
const arg = onApplyFilter.mock.calls[0][0] as KontaktListQuery;
expect(arg.filter.search).toBe("berlin");
expect(arg.page).toBe(1);
});
it("resets search, facets and order through the bar's reset pill", () => {
const onApplyFilter = vi.fn();
renderPage({ actions: actions({ onApplyFilter }), query: { ...QUERY, filter: { ...QUERY.filter, kontaktStatus: "kunde" } } });
fireEvent.click(screen.getByText("crm.filter.reset"));
const arg = onApplyFilter.mock.calls[0][0] as KontaktListQuery;
expect(arg.filter.kontaktStatus).toBeNull();
expect(arg.filter.kontaktTyp).toBeNull();
expect(arg.filter.search).toBeNull();
expect(arg.filter.includeArchived).toBe(false);
expect(arg.page).toBe(1);
});
it("puts the sorting button directly behind the facets", () => {
renderPage();
const owner = document.querySelector("[data-ui-id='ui.crm.list.filter.owner']");
const sort = document.querySelector("[data-ui-id='ui.crm.list.filter.sort']");
expect(sort).not.toBeNull();
// Same row, nothing of the bar in between - sorting orders exactly the rows
// the facets narrow.
expect(owner?.nextElementSibling).toBe(sort);
});
it("bulk-archives only the selected rows", () => {
const onBulk = vi.fn();
renderPage({ vm: vm([sourceRow("k1"), sourceRow("k2", { vorname: "Bea" })]), actions: actions({ onBulk }) });
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.row.select.k2']")!);
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.bulk.archive']")!);
expect(onBulk).toHaveBeenCalledTimes(1);
expect(onBulk.mock.calls[0][0]).toBe("bulkArchive");
expect(onBulk.mock.calls[0][1]).toEqual(["k2"]);
});
it("offers a + trigger to attach an unassigned tag", () => {
// Default fixture: tagOptions has VIP, the row carries no tags yet.
renderPage();
expect(document.querySelector("[data-ui-id='ui.crm.list.tag.add.k1']")).not.toBeNull();
});
it("removes an assigned tag from a row via its X", () => {
const onRemoveTag = vi.fn();
const built = buildKontaktListVM({
rows: [sourceRow("k1")],
userLabels: new Map(),
tagsByKontakt: new Map([["k1", [{ id: "t1", name: "VIP", farbe: "#f00" }]]]),
pagination: { page: 1, pageCount: 1, total: 1 },
sort: QUERY.sort,
filter: QUERY.filter,
perms: { canWrite: true, canDelete: true, canReadAll: true },
tenantSlug: "acme",
});
renderPage({ vm: built, actions: actions({ onRemoveTag }) });
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.tag.remove.k1.t1']")!);
expect(onRemoveTag).toHaveBeenCalledWith("k1", "t1");
});
it("hides tag add/remove affordances without write permission", () => {
renderPage({ canWrite: false, vm: vm([sourceRow("k1")], { canWrite: false, canDelete: false, canReadAll: true }) });
expect(document.querySelector("[data-ui-id='ui.crm.list.tag.add.k1']")).toBeNull();
});
it("shows no bulk bar at all while nothing is selected", () => {
renderPage();
// The bar carries an action; with an empty selection there is nothing to
// act on, so it stays away instead of standing there greyed out.
expect(document.querySelector("[data-ui-id='ui.crm.list.selection']")).toBeNull();
expect(document.querySelector("[data-ui-id='ui.crm.list.bulk.archive']")).toBeNull();
});
it("flips the archive button to un-archive when the whole selection is archived", () => {
const onBulk = vi.fn();
renderPage({ vm: vm([sourceRow("k1", { archivedAt: new Date("2026-06-02T00:00:00.000Z") })]), actions: actions({ onBulk }) });
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.row.select.k1']")!);
const btn = document.querySelector("[data-ui-id='ui.crm.list.bulk.archive']") as HTMLButtonElement;
expect(btn.textContent).toContain("crm.actions.bulkReactivate");
fireEvent.click(btn);
expect(onBulk).toHaveBeenCalledWith("bulkReactivate", ["k1"]);
});
it("keeps archiving (forces archived=true) for a mixed selection", () => {
const onBulk = vi.fn();
renderPage({
vm: vm([sourceRow("k1"), sourceRow("k2", { vorname: "Bea", archivedAt: new Date("2026-06-02T00:00:00.000Z") })]),
actions: actions({ onBulk }),
});
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.row.select.k1']")!);
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.row.select.k2']")!);
const btn = document.querySelector("[data-ui-id='ui.crm.list.bulk.archive']") as HTMLButtonElement;
expect(btn.textContent).toContain("crm.actions.bulkArchive");
fireEvent.click(btn);
expect(onBulk).toHaveBeenCalledWith("bulkArchive", ["k1", "k2"]);
});
it("never puts the archive button into its loading state", () => {
renderPage();
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.row.select.k1']")!);
const btn = document.querySelector("[data-ui-id='ui.crm.list.bulk.archive']") as HTMLButtonElement;
// Button renders its spinner slot always but only unhides it (class `flex`)
// while `loading` is set, which this button no longer passes.
expect(btn.disabled).toBe(false);
expect(btn.querySelector("div.hidden.h-4.w-4")!).not.toHaveClass("flex");
});
it("clears the selection when a bulk runs, so archived rows do not stay checked", () => {
const acts = actions();
const { rerender } = render(pageElement({ vm: vm([sourceRow("k1"), sourceRow("k2", { vorname: "Bea" })]) }, acts));
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.row.select.k2']")!);
const btn = () => document.querySelector("[data-ui-id='ui.crm.list.bulk.archive']") as HTMLButtonElement | null;
expect(btn()!.disabled).toBe(false);
fireEvent.click(btn()!);
expect(btn()).toBeNull();
// k2 leaves the archived-hidden list, then comes back via "Archivierte
// anzeigen" — it must not be pre-checked either way.
rerender(pageElement({ vm: vm([sourceRow("k1")]) }, acts));
expect(btn()).toBeNull();
rerender(pageElement({ vm: vm([sourceRow("k1"), sourceRow("k2", { vorname: "Bea", archivedAt: new Date("2026-06-02T00:00:00.000Z") })]) }, acts));
expect(btn()).toBeNull();
expect(document.querySelector("[data-ui-id='ui.crm.list.selection']")).toBeNull();
});
it("keeps the selection across pages and bulk-archives the off-page rows too", () => {
const onBulk = vi.fn();
const acts = actions({ onBulk });
const { rerender } = render(pageElement({ vm: vm([sourceRow("k1"), sourceRow("k2", { vorname: "Bea" })]) }, acts));
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.row.select.k1']")!);
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.row.select.k2']")!);
// Page 2: same filter/sort, different rows. k1/k2 stay selected.
rerender(pageElement({ vm: vm([sourceRow("k3", { vorname: "Cem" })]) }, acts));
expect(document.querySelector("[data-ui-id='ui.crm.list.selection.count']")?.textContent).toContain("crm.selection.count");
expect(document.querySelector("[data-ui-id='ui.crm.list.selection.offPage']")?.textContent).toContain("crm.selection.offPage");
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.row.select.k3']")!);
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.bulk.archive']")!);
expect(onBulk).toHaveBeenCalledWith("bulkArchive", ["k1", "k2", "k3"]);
});
it("decides archive vs un-archive over the whole selection, not just the visible page", () => {
const onBulk = vi.fn();
const acts = actions({ onBulk });
const archived = new Date("2026-06-02T00:00:00.000Z");
const { rerender } = render(pageElement({ vm: vm([sourceRow("k1", { archivedAt: archived })]) }, acts));
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.row.select.k1']")!);
// Page 2 holds an unarchived row — adding it must flip the button back to
// "Archivieren" even though k1's row is no longer rendered.
rerender(pageElement({ vm: vm([sourceRow("k2", { vorname: "Bea" })]) }, acts));
const btn = () => document.querySelector("[data-ui-id='ui.crm.list.bulk.archive']") as HTMLButtonElement;
expect(btn().textContent).toContain("crm.actions.bulkReactivate");
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.row.select.k2']")!);
expect(btn().textContent).toContain("crm.actions.bulkArchive");
fireEvent.click(btn());
expect(onBulk).toHaveBeenCalledWith("bulkArchive", ["k1", "k2"]);
});
it("drops the selection when the filter changes, since the result set is a different one", () => {
const acts = actions();
const { rerender } = render(pageElement({ vm: vm([sourceRow("k1")]) }, acts));
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.row.select.k1']")!);
expect(document.querySelector("[data-ui-id='ui.crm.list.selection']")).not.toBeNull();
const nextQuery: KontaktListQuery = { ...QUERY, filter: { ...QUERY.filter, includeArchived: true } };
rerender(pageElement({ vm: vm([sourceRow("k1")]), query: nextQuery }, acts));
expect(document.querySelector("[data-ui-id='ui.crm.list.selection']")).toBeNull();
expect(document.querySelector("[data-ui-id='ui.crm.list.bulk.archive']")).toBeNull();
});
it("lets the user clear a selection that spans pages", () => {
const acts = actions();
render(pageElement({ vm: vm([sourceRow("k1"), sourceRow("k2", { vorname: "Bea" })]) }, acts));
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.selectAll']")!);
expect(document.querySelector("[data-ui-id='ui.crm.list.selection.count']")).not.toBeNull();
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.list.selection.clear']")!);
expect(document.querySelector("[data-ui-id='ui.crm.list.selection']")).toBeNull();
expect(document.querySelector("[data-ui-id='ui.crm.list.bulk.archive']")).toBeNull();
});
});
@@ -0,0 +1,665 @@
// R-P6 (P6 CRM core) Interim-UI (AD-28) — contact/organisation browser screen
// (D-CRM "Kontakt-Liste"/"Organisationen-Liste", archetype A2), composed from
// ~/ui. Pure/presentational: it renders the server-built KontaktListVM
// (filter/sort/paginate/bulk/CSV, DoD 2) and turns every mutation into an action
// callback the route drives (navigation for filter/sort/page, POST for bulk).
// No useLoaderData/useFetcher, no server imports. Filter/sort/page state stays in
// the URL — the screen only holds a local draft + the current row selection.
// Final Subframe optics = tracked design-nachzug.
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import * as SubframeCore from "@subframe/core";
import {
FeatherArrowDown,
FeatherArrowUp,
FeatherArrowUpDown,
FeatherContact,
FeatherDownload,
FeatherPlus,
FeatherTag,
FeatherUser,
FeatherUserCheck,
FeatherX,
} from "@subframe/core";
import type { KontaktListVM } from "@hivegrid/view-models";
import type { KontaktListQuery } from "~/utils/integrations/crm/kontaktListQuery";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { FacetFilterBar, type ClientFacet } from "../shared/FacetFilterBar";
import { BulkActionBar } from "../shared/BulkActionBar";
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 { DropdownMenuMultiSelect } from "~/ui/components/DropdownMenuMultiSelect";
import { EmptyState } from "~/ui/components/EmptyState";
import { FilterBar } from "~/ui/components/FilterBar";
import { Table } from "~/ui/components/Table";
import { useLiveFilter } from "~/hooks/use-live-filter";
import { KontaktNewDialog } from "./KontaktNewDialog";
import type { KontaktNewDuplicates, KontaktNewFields } from "./KontaktNewPage";
import { AppLink } from "~/components/app/AppLink";
export type KontaktListVariant = "contacts" | "companies";
export type KontaktListTagOption = { id: string; name: string; farbe: string };
export type KontaktListOwnerOption = { id: string; label: string };
export type KontaktBulkIntent = "bulkArchive" | "bulkReactivate";
export type KontaktListPageActions = {
/** Apply a new filter/sort query — the route serialises it and navigates (GET). */
onApplyFilter: (query: KontaktListQuery) => void;
/** Jump to a page (keeps the current filter/sort). */
onGoToPage: (page: number) => void;
/** Archive (or un-archive) the selected ids in one go (route POSTs the intent). */
onBulk: (intent: KontaktBulkIntent, ids: string[]) => void;
/** Live duplicate check while typing in the create dialog (route runs the fetcher). */
onCheckDuplicates?: (fields: KontaktNewFields) => void;
/** Trigger the CSV export (route does a full GET to the export endpoint). */
onExport: () => void;
/** Client-navigate to an admin sub-page (custom fields / tags / duplicates). */
onNavigate: (href: string) => void;
/** Assign an existing tag to a single contact from the list (route POSTs). */
onAssignTag: (kontaktId: string, tagId: string) => void;
/** Remove a tag from a single contact from the list (route POSTs). */
onRemoveTag: (kontaktId: string, tagId: string) => void;
};
export type KontaktListNav = {
contactsHref: string;
companiesHref: string;
customFieldsHref: string;
tagsHref: string;
duplicatesHref: string;
};
export type KontaktListPageProps = {
vm: KontaktListVM;
variant: KontaktListVariant;
moduleActive: boolean;
query: KontaktListQuery;
tagOptions: readonly KontaktListTagOption[];
ownerOptions: readonly KontaktListOwnerOption[];
/** Top-level perms (not vm-derived) so the CTA + admin nav survive an empty list. */
canWrite: boolean;
canAdmin: boolean;
nav: KontaktListNav;
/** Create route the "Neuer Kontakt" dialog posts to. */
newHref: string;
/** Current user — pre-selected owner in the create dialog. */
defaultOwnerId: string;
/** Duplicate hits for the create dialog (route-provided fetcher data). */
duplicates?: KontaktNewDuplicates | null;
errorKey?: string | null;
actions: KontaktListPageActions;
};
const FILTER_ANY = "__any__";
// Combined sort dropdown: field + direction in one control (value = "field:dir").
// The label reads "<field> · <direction>", e.g. "Erstellt · Absteigend".
const SORT_OPTIONS = [
{ field: "createdAt", dir: "desc", fieldKey: "crm.filter.sortCreated" },
{ field: "createdAt", dir: "asc", fieldKey: "crm.filter.sortCreated" },
{ field: "name", dir: "asc", fieldKey: "crm.filter.sortName" },
{ field: "name", dir: "desc", fieldKey: "crm.filter.sortName" },
{ field: "kontaktStatus", dir: "desc", fieldKey: "crm.filter.sortStatus" },
{ field: "kontaktStatus", dir: "asc", fieldKey: "crm.filter.sortStatus" },
] as const;
export function KontaktListPage(props: KontaktListPageProps) {
const { t } = useTranslation();
const { variant, query } = props;
const isCompanies = variant === "companies";
const titleKey = isCompanies ? "crm.companies.title" : "crm.contacts.title";
const emptyHeadlineKey = isCompanies ? "crm.empty.companies.headline" : "crm.empty.contacts.headline";
const emptyBodyKey = isCompanies ? "crm.empty.companies.body" : "crm.empty.contacts.body";
// Local filter draft (mirrors the URL-derived query until "Apply").
// Creating a contact 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);
const [search, setSearch] = useState(query.filter.search ?? "");
const [typ, setTyp] = useState<string>(query.filter.kontaktTyp ?? FILTER_ANY);
const [status, setStatus] = useState<string>(query.filter.kontaktStatus ?? FILTER_ANY);
const [owner, setOwner] = useState<string>(query.filter.zustaendigerUserId ?? FILTER_ANY);
const [sortField, setSortField] = useState<string>(query.sort.field);
const [sortDir, setSortDir] = useState<string>(query.sort.dir);
const [includeArchived, setIncludeArchived] = useState<boolean>(query.filter.includeArchived);
// Row selection — the archive toggle is the only bulk action left. Selection
// survives paging, so it stores each row's archived flag alongside the id:
// the archive/un-archive decision has to cover rows that are no longer on
// screen, and their VM row is gone by then.
const [selected, setSelected] = useState<ReadonlyMap<string, boolean>>(new Map());
// 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<{ typ: string; status: string; owner: string; sortField: string; sortDir: string; includeArchived: boolean }>) {
const next = { typ, status, owner, sortField, sortDir, includeArchived, ...overrides };
props.actions.onApplyFilter({
filter: {
...query.filter,
search: search.trim() || null,
kontaktTyp: next.typ === FILTER_ANY ? null : (next.typ as KontaktListQuery["filter"]["kontaktTyp"]),
kontaktStatus: next.status === FILTER_ANY ? null : (next.status as KontaktListQuery["filter"]["kontaktStatus"]),
zustaendigerUserId: next.owner === FILTER_ANY ? null : next.owner,
includeArchived: next.includeArchived,
},
sort: { field: next.sortField as KontaktListQuery["sort"]["field"], dir: next.sortDir as KontaktListQuery["sort"]["dir"] },
page: 1,
});
}
useLiveFilter(search.trim(), query.filter.search ?? "", () => applyFilter());
const data = props.vm.status === "ready" ? props.vm.data : null;
const rows = useMemo(() => data?.rows ?? [], [data]);
const allSelected = rows.length > 0 && rows.every((row) => selected.has(row.id));
const someSelected = selected.size > 0;
// The archive button flips to "un-archive" ONLY when every selected row is
// already archived. A mixed selection stays "Archivieren" and forces all to
// archived=true (per product spec). Evaluated over the whole selection, not
// just the visible part, so paging cannot change what the button does.
const allSelectedArchived = selected.size > 0 && [...selected.values()].every(Boolean);
const selectedOffPage = selected.size - rows.filter((row) => selected.has(row.id)).length;
// A new filter/sort produces a different result set, so any selection carried
// into it would be invisible and unreviewable — drop it. Paging deliberately
// does NOT clear: the selection is meant to span pages. Selections are also
// cleared right when a bulk runs (see the archive button), which is what keeps
// archived rows from staying checked in the background.
const querySignature = JSON.stringify({ filter: query.filter, sort: query.sort });
const lastQuerySignature = useRef(querySignature);
useEffect(() => {
if (lastQuerySignature.current === querySignature) return;
lastQuerySignature.current = querySignature;
setSelected((prev) => (prev.size === 0 ? prev : new Map()));
}, [querySignature]);
if (!props.moduleActive) {
return (
<PageShell uiId="ui.crm.list">
<PageHeader
icon={<FeatherContact className={PAGE_HEADER_ICON_CLASS} />}
title={t(titleKey)}
subtitle={t("crm.contacts.subtitle")}
/>
<PageBody>
<div data-ui-id="ui.crm.list.locked">
<EmptyState title={t("crm.locked.headline")} body={t("crm.locked.body")} />
</div>
</PageBody>
</PageShell>
);
}
function toggleRow(id: string, isArchived: boolean, checked: boolean) {
setSelected((prev) => {
const next = new Map(prev);
if (checked) next.set(id, isArchived);
else next.delete(id);
return next;
});
}
// Header checkbox acts on the current page only — it adds/removes the visible
// rows and leaves selections made on other pages untouched.
function toggleAll(checked: boolean) {
setSelected((prev) => {
const next = new Map(prev);
for (const row of rows) {
if (checked) next.set(row.id, row.isArchived);
else next.delete(row.id);
}
return next;
});
}
const selectedIds = () => [...selected.keys()];
/** Resolved caption of a sort option, so the bar's button states the order. */
function sortLabel(field: string, dir: string): string {
const option = SORT_OPTIONS.find((entry) => entry.field === field && entry.dir === dir) ?? SORT_OPTIONS[0];
return `${t(option.fieldKey)} · ${t(dir === "asc" ? "crm.filter.dirAsc" : "crm.filter.dirDesc")}`;
}
// Single-select facets on a multi-select control: picking the active option
// again clears it, which is what the chip's X does too — same behaviour the
// files browser has.
const allFacets: ClientFacet[] = [
{
key: "typ",
label: t("crm.filter.type"),
icon: <FeatherTag />,
tone: "violet-subtle",
options: [
{ value: "organisation", label: t("crm.kontaktTyp.organisation") },
{ value: "privatperson", label: t("crm.kontaktTyp.privatperson") },
],
selected: new Set(typ === FILTER_ANY ? [] : [typ]),
},
{
key: "status",
label: t("crm.filter.status"),
icon: <FeatherUserCheck />,
tone: "blue-subtle",
options: (["kontakt", "kunde", "bestandskunde"] as const).map((entry) => ({ value: entry, label: t(`crm.kontaktStatus.${entry}`) })),
selected: new Set(status === FILTER_ANY ? [] : [status]),
},
{
key: "owner",
label: t("crm.filter.owner"),
icon: <FeatherUser />,
tone: "sky-subtle",
options: props.ownerOptions.map((option) => ({ value: option.id, label: option.label })),
selected: new Set(owner === FILTER_ANY ? [] : [owner]),
},
];
// A facet with nothing to pick is a dead button; a fresh tenant may simply
// have no owners to choose from yet.
const facets = allFacets.filter((facet) => facet.options.length > 0);
function toggleFacet(facetKey: string, value: string) {
if (facetKey === "typ") {
const next = typ === value ? FILTER_ANY : value;
setTyp(next);
return applyFilter({ typ: next });
}
if (facetKey === "status") {
const next = status === value ? FILTER_ANY : value;
setStatus(next);
return applyFilter({ status: next });
}
if (facetKey === "owner") {
const next = owner === value ? FILTER_ANY : value;
setOwner(next);
return applyFilter({ owner: next });
}
return undefined;
}
/** Back to an unfiltered list in its default order, search box included. */
function resetFilter() {
setSearch("");
setTyp(FILTER_ANY);
setStatus(FILTER_ANY);
setOwner(FILTER_ANY);
setIncludeArchived(false);
setSortField(SORT_OPTIONS[0].field);
setSortDir(SORT_OPTIONS[0].dir);
props.actions.onApplyFilter({
filter: {
...query.filter,
search: null,
kontaktTyp: null,
kontaktStatus: null,
zustaendigerUserId: null,
includeArchived: false,
},
sort: { field: SORT_OPTIONS[0].field, dir: SORT_OPTIONS[0].dir },
page: 1,
});
}
// A bulk consumes its selection: clearing here keeps the button from staying
// enabled over rows that just left the list, and stops them from coming back
// pre-checked via "Archivierte anzeigen".
function runBulk(intent: KontaktBulkIntent) {
props.actions.onBulk(intent, selectedIds());
setSelected(new Map());
}
return (
<PageShell uiId="ui.crm.list">
<PageHeader
icon={<FeatherContact className={PAGE_HEADER_ICON_CLASS} />}
title={t(titleKey)}
subtitle={t("crm.contacts.subtitle")}
actions={
<>
{/* Admin entry points (custom fields / tags / duplicates) live in the
header now, white/outline style, to the left of the export CTA. */}
{props.canAdmin ? (
<>
<Button variant="tertiary" onClick={() => props.actions.onNavigate(props.nav.customFieldsHref)} data-ui-id="ui.crm.list.admin.customFields">
{t("crm.admin.customFields.title")}
</Button>
<Button variant="tertiary" onClick={() => props.actions.onNavigate(props.nav.tagsHref)} data-ui-id="ui.crm.list.admin.tags">
{t("crm.admin.tags.title")}
</Button>
<Button variant="tertiary" onClick={() => props.actions.onNavigate(props.nav.duplicatesHref)} data-ui-id="ui.crm.list.admin.duplicates">
{t("crm.admin.duplicates.title")}
</Button>
</>
) : null}
<Button variant="neutral" icon={<FeatherDownload />} onClick={props.actions.onExport} data-ui-id="ui.crm.list.export">
{t("crm.actions.exportCsv")}
</Button>
{props.canWrite ? (
<Button icon={<FeatherPlus />} onClick={() => setCreateOpen(true)} data-ui-id="ui.crm.list.new">
{t("crm.actions.newContact")}
</Button>
) : null}
</>
}
/>
{/* --- Filter bar: the shared facet strip the files browser, the boards
and the plantafel wear - free-text box, facet buttons, sorting right
behind them, chips for what is active and one reset. --- */}
<FacetFilterBar
uiId="ui.crm.list.filter"
facets={facets}
onToggle={toggleFacet}
search={search}
onSearchChange={setSearch}
searchPlaceholder={t("crm.filter.searchPlaceholder")}
onReset={resetFilter}
labels={{ reset: t("crm.filter.reset"), removeChip: t("crm.filter.removeChip") }}
afterFacets={
<FilterBar.StatusFilterButton
icon={<FeatherArrowUpDown />}
label={sortLabel(sortField, sortDir)}
count=""
data-ui-id="ui.crm.list.filter.sort"
dropdown={
<DropdownMenuMultiSelect>
{SORT_OPTIONS.map((option) => (
<DropdownMenuMultiSelect.DropdownItem
key={`${option.field}:${option.dir}`}
showCheckbox
selected={option.field === sortField && option.dir === sortDir}
onClick={() => {
setSortField(option.field);
setSortDir(option.dir);
applyFilter({ sortField: option.field, sortDir: option.dir });
}}
data-ui-id={`ui.crm.list.filter.sort.${option.field}.${option.dir}`}
>
<span className="inline-flex items-center gap-1">
{t(option.fieldKey)}
{option.dir === "asc" ? (
<FeatherArrowUp className="text-body-small-regular-0 font-body-small-regular-0" />
) : (
<FeatherArrowDown className="text-body-small-regular-0 font-body-small-regular-0" />
)}
</span>
</DropdownMenuMultiSelect.DropdownItem>
))}
</DropdownMenuMultiSelect>
}
/>
}
trailing={
<Checkbox
checked={includeArchived}
onCheckedChange={(checked) => {
setIncludeArchived(checked);
applyFilter({ includeArchived: checked });
}}
label={t("crm.filter.includeArchived")}
data-ui-id="ui.crm.list.filter.includeArchived"
/>
}
/>
<PageBody>
{props.errorKey ? (
<div data-ui-id="ui.crm.list.error">
<BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback>
</div>
) : null}
{/* --- Bulk bar: appears above the table once rows are checked, in the
shape every list uses. The selection spans pages, so the off-page
note stays part of it - otherwise the reader cannot tell what the
archive button would actually touch. --- */}
{props.canWrite ? (
<BulkActionBar
uiId="ui.crm.list.selection"
selectedCount={selected.size}
countLabel={t("crm.selection.count", { n: selected.size })}
offPageLabel={selectedOffPage > 0 ? t("crm.selection.offPage", { n: selectedOffPage }) : null}
clearLabel={t("crm.selection.clear")}
onClear={() => setSelected(new Map())}
>
{/* Flips to "un-archive" only when the whole selection is already
archived; a mixed selection archives all of it. */}
<Button
variant="neutral"
size="small"
onClick={() => runBulk(allSelectedArchived ? "bulkReactivate" : "bulkArchive")}
data-ui-id="ui.crm.list.bulk.archive"
>
{t(allSelectedArchived ? "crm.actions.bulkReactivate" : "crm.actions.bulkArchive")}
</Button>
</BulkActionBar>
) : null}
{rows.length === 0 ? (
<div data-ui-id="ui.crm.list.empty">
<EmptyState title={t(emptyHeadlineKey)} body={t(emptyBodyKey)} />
</div>
) : (
<>
<div className="w-full overflow-x-auto">
<Table
data-ui-id="ui.crm.list.table"
header={
<Table.HeaderRow>
<Table.HeaderCell>
{data?.canWrite ? (
<Checkbox
checked={allSelected}
indeterminate={someSelected && !allSelected}
onCheckedChange={toggleAll}
hideLabel
label={t("crm.actions.selectAll")}
data-ui-id="ui.crm.list.selectAll"
/>
) : null}
</Table.HeaderCell>
<Table.HeaderCell>{t("crm.column.name")}</Table.HeaderCell>
<Table.HeaderCell>{t("crm.column.type")}</Table.HeaderCell>
<Table.HeaderCell>{t("crm.column.status")}</Table.HeaderCell>
<Table.HeaderCell>{t("crm.column.email")}</Table.HeaderCell>
<Table.HeaderCell>{t("crm.column.telefon")}</Table.HeaderCell>
<Table.HeaderCell>{t("crm.column.owner")}</Table.HeaderCell>
<Table.HeaderCell>{t("crm.column.tags")}</Table.HeaderCell>
</Table.HeaderRow>
}
>
{rows.map((row) => (
<Table.Row key={row.id} data-row-id={row.id}>
<Table.Cell>
{data?.canWrite ? (
<Checkbox
checked={selected.has(row.id)}
onCheckedChange={(checked) => toggleRow(row.id, row.isArchived, checked)}
hideLabel
label={t("crm.actions.select")}
data-ui-id={`ui.crm.list.row.select.${row.id}`}
/>
) : null}
</Table.Cell>
<Table.Cell>
<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.isArchived ? (
<BadgeFeedback farbe="subtle-neutral" size="small">
{t("crm.detail.archivedBadge")}
</BadgeFeedback>
) : null}
</div>
</Table.Cell>
<Table.Cell>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">
{t(row.typLabelKey)}
</span>
</Table.Cell>
<Table.Cell>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">
{t(row.statusLabelKey)}
</span>
</Table.Cell>
<Table.Cell>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">
{row.primaerEmail ?? "—"}
</span>
</Table.Cell>
<Table.Cell>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">
{row.primaerTelefon ?? "—"}
</span>
</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>
<KontaktTagCell
kontaktId={row.id}
chips={row.tagChips}
tagOptions={props.tagOptions}
canWrite={props.canWrite}
onAssign={props.actions.onAssignTag}
onRemove={props.actions.onRemoveTag}
/>
</Table.Cell>
</Table.Row>
))}
</Table>
</div>
{/* --- Pagination --- */}
<div className="flex items-center gap-4" data-ui-id="ui.crm.list.pagination">
<Button
variant="neutral"
size="small"
disabled={!data?.pagination.hasPrev}
onClick={() => data && props.actions.onGoToPage(data.pagination.page - 1)}
>
{t("crm.pagination.prev")}
</Button>
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{t("crm.pagination.page", {
page: data?.pagination.page ?? 1,
pageCount: Math.max(data?.pagination.pageCount ?? 1, 1),
total: data?.pagination.total ?? 0,
})}
</span>
<Button
variant="neutral"
size="small"
disabled={!data?.pagination.hasNext}
onClick={() => data && props.actions.onGoToPage(data.pagination.page + 1)}
>
{t("crm.pagination.next")}
</Button>
</div>
</>
)}
{props.canWrite ? (
<KontaktNewDialog
open={createOpen}
onOpenChange={setCreateOpen}
createHref={props.newHref}
ownerOptions={props.ownerOptions}
defaultOwnerId={props.defaultOwnerId}
defaultKontaktTyp={isCompanies ? "organisation" : "privatperson"}
duplicates={props.duplicates ?? null}
onCheckDuplicates={props.actions.onCheckDuplicates}
/>
) : null}
</PageBody>
</PageShell>
);
}
/**
* Tags cell for a contact row: highlighted chips (each removable via an X when the
* user can write) plus a "+" dropdown that assigns any not-yet-attached tenant tag.
* The colour tint mirrors the /forms status column; color-mix keeps it robust for
* any hex colour. Assign/remove are single-contact POSTs the route owns.
*/
function KontaktTagCell(props: {
kontaktId: string;
chips: readonly { id: string; name: string; farbe: string }[];
tagOptions: readonly KontaktListTagOption[];
canWrite: boolean;
onAssign: (kontaktId: string, tagId: string) => void;
onRemove: (kontaktId: string, tagId: string) => void;
}) {
const { t } = useTranslation();
const assignedIds = new Set(props.chips.map((chip) => chip.id));
const available = props.tagOptions.filter((tag) => !assignedIds.has(tag.id));
return (
<div className="flex flex-wrap items-center gap-1.5" data-ui-id={`ui.crm.list.tags.${props.kontaktId}`}>
{props.chips.map((tag) => (
<span
key={tag.id}
className="inline-flex h-5 items-center gap-1 rounded-round py-0.5 pl-2 pr-1 text-body-small-medium-0 font-body-small-medium-0 whitespace-nowrap"
style={{ backgroundColor: `color-mix(in srgb, ${tag.farbe} 16%, transparent)`, color: tag.farbe }}
>
{tag.name}
{props.canWrite ? (
<button
type="button"
className="inline-flex h-3.5 w-3.5 items-center justify-center rounded-round hover:bg-[color-mix(in_srgb,currentColor_24%,transparent)]"
aria-label={t("crm.tags.remove", { name: tag.name })}
onClick={() => props.onRemove(props.kontaktId, tag.id)}
data-ui-id={`ui.crm.list.tag.remove.${props.kontaktId}.${tag.id}`}
>
<FeatherX className="h-3 w-3" />
</button>
) : (
<span className="pr-1" />
)}
</span>
))}
{props.canWrite && available.length > 0 ? (
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<button
type="button"
className="inline-flex h-5 w-5 items-center justify-center rounded-round border border-solid border-border-default bg-surface-neutral-primary text-text-neutral-tertiary hover:bg-surface-neutral-tertiary"
aria-label={t("crm.tags.add")}
data-ui-id={`ui.crm.list.tag.add.${props.kontaktId}`}
>
<FeatherPlus className="h-3 w-3" />
</button>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="start" sideOffset={4} asChild>
<DropdownMenu>
{available.map((tag) => (
<DropdownMenu.DropdownItem
key={tag.id}
icon={<span className="h-2.5 w-2.5 rounded-round" style={{ backgroundColor: tag.farbe }} />}
onSelect={() => props.onAssign(props.kontaktId, tag.id)}
data-ui-id={`ui.crm.list.tag.option.${props.kontaktId}.${tag.id}`}
>
{tag.name}
</DropdownMenu.DropdownItem>
))}
</DropdownMenu>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
) : null}
</div>
);
}
export default KontaktListPage;
@@ -0,0 +1,241 @@
// R-P6 Interim-UI (AD-28) — "Neuer Kontakt" as a modal on the contact/organisation
// browser, mirroring the automation list pattern ("Neue Automation starten").
// Presentational only: it holds the form draft, reports blur events through
// actions.onCheckDuplicates (live hard/soft hits, DoD 4) and posts to the create
// route (`createHref`) with the same field contract as the standalone KontaktNewPage,
// so the route action stays untouched. No useLoaderData / useFetcher (DoD A.5).
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherPlus, FeatherX } from "@subframe/core";
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";
import type { KontaktNewDuplicates, KontaktNewFields } from "./KontaktNewPage";
import { AppLink } from "~/components/app/AppLink";
const ORG_MERKMAL_NONE = "__none__";
export type KontaktNewDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
/** Route that owns the create action (the standalone /contacts/new route). */
createHref: string;
ownerOptions: readonly { id: string; label: string }[];
defaultOwnerId: string;
/** Organisation browser pre-selects the organisation type. */
defaultKontaktTyp?: string;
duplicates?: KontaktNewDuplicates | null;
onCheckDuplicates?: (fields: KontaktNewFields) => void;
};
export function KontaktNewDialog({
open,
onOpenChange,
createHref,
ownerOptions,
defaultOwnerId,
defaultKontaktTyp = "privatperson",
duplicates = null,
onCheckDuplicates,
}: KontaktNewDialogProps) {
const { t } = useTranslation();
const [fields, setFields] = useState<KontaktNewFields>({
kontaktTyp: defaultKontaktTyp,
kontaktStatus: "kontakt",
vorname: "",
nachname: "",
orgName: "",
orgMerkmal: "",
email: "",
telefon: "",
zustaendigerUserId: defaultOwnerId,
});
const set = (patch: Partial<KontaktNewFields>) => setFields((state) => ({ ...state, ...patch }));
const checkDuplicates = () => onCheckDuplicates?.(fields);
const isOrg = fields.kontaktTyp === "organisation";
const hasIdentity = Boolean(isOrg ? fields.orgName.trim() : fields.vorname.trim() || fields.nachname.trim());
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" data-ui-id="ui.crm.new.dialog">
<input type="hidden" name="intent" value="create" />
<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("crm.new.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("crm.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">
{duplicates && (duplicates.hard.length > 0 || duplicates.soft.length > 0) ? (
<div
className="flex w-full flex-col gap-2 rounded-md border border-solid border-border-default bg-surface-neutral-primary px-4 py-3"
data-ui-id="ui.crm.new.dialog.duplicates"
>
{duplicates.hard.length > 0 ? (
<div className="flex flex-col gap-1">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-feedback-negative">{t("crm.new.duplicates.hard")}</span>
{duplicates.hard.map((card) => (
<AppLink key={card.id} href={card.detailHref} className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-link-default">
{card.displayName}
{card.primaerEmail ? ` · ${card.primaerEmail}` : ""}
</AppLink>
))}
</div>
) : null}
{duplicates.soft.length > 0 ? (
<div className="flex flex-col gap-1">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{t("crm.new.duplicates.soft")}</span>
{duplicates.soft.map((card) => (
<AppLink key={card.id} href={card.detailHref} className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-link-default">
{card.displayName}
{card.primaerEmail ? ` · ${card.primaerEmail}` : ""}
</AppLink>
))}
</div>
) : null}
</div>
) : null}
<div className="grid w-full gap-4 sm:grid-cols-2">
<Select
name="kontaktTyp"
label={t("crm.fields.type")}
showLabel
value={fields.kontaktTyp}
onValueChange={(value: string) => set({ kontaktTyp: value })}
>
<Select.Item value="privatperson">{t("crm.kontaktTyp.privatperson")}</Select.Item>
<Select.Item value="organisation">{t("crm.kontaktTyp.organisation")}</Select.Item>
</Select>
<Select
name="kontaktStatus"
label={t("crm.fields.status")}
showLabel
value={fields.kontaktStatus}
onValueChange={(value: string) => set({ kontaktStatus: value })}
>
{(["kontakt", "kunde", "bestandskunde"] as const).map((status) => (
<Select.Item key={status} value={status}>
{t(`crm.kontaktStatus.${status}`)}
</Select.Item>
))}
</Select>
{isOrg ? (
<>
<TextInput label={t("crm.fields.orgName")} showLabel>
<TextInput.Input
name="orgName"
autoFocus
value={fields.orgName}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => set({ orgName: event.target.value })}
onBlur={checkDuplicates}
data-ui-id="ui.crm.new.dialog.orgName"
/>
</TextInput>
<Select
name="orgMerkmal"
label={t("crm.fields.orgMerkmal")}
showLabel
value={fields.orgMerkmal || ORG_MERKMAL_NONE}
onValueChange={(value: string) => set({ orgMerkmal: value === ORG_MERKMAL_NONE ? "" : value })}
>
<Select.Item value={ORG_MERKMAL_NONE}>{t("crm.fields.none")}</Select.Item>
{(["gmbh", "kg", "oeffentliche_einrichtung", "sonstige"] as const).map((merkmal) => (
<Select.Item key={merkmal} value={merkmal}>
{t(`crm.orgMerkmal.${merkmal}`)}
</Select.Item>
))}
</Select>
</>
) : (
<>
<TextInput label={t("crm.fields.vorname")} showLabel>
<TextInput.Input
name="vorname"
autoFocus
value={fields.vorname}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => set({ vorname: event.target.value })}
onBlur={checkDuplicates}
data-ui-id="ui.crm.new.dialog.vorname"
/>
</TextInput>
<TextInput label={t("crm.fields.nachname")} showLabel>
<TextInput.Input
name="nachname"
value={fields.nachname}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => set({ nachname: event.target.value })}
onBlur={checkDuplicates}
data-ui-id="ui.crm.new.dialog.nachname"
/>
</TextInput>
</>
)}
<TextInput label={t("crm.fields.email")} showLabel>
<TextInput.Input
name="email"
type="email"
value={fields.email}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => set({ email: event.target.value })}
onBlur={checkDuplicates}
data-ui-id="ui.crm.new.dialog.email"
/>
</TextInput>
<TextInput label={t("crm.fields.telefon")} showLabel>
<TextInput.Input
name="telefon"
value={fields.telefon}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => set({ telefon: event.target.value })}
onBlur={checkDuplicates}
data-ui-id="ui.crm.new.dialog.telefon"
/>
</TextInput>
<Select
name="zustaendigerUserId"
label={t("crm.fields.owner")}
showLabel
value={fields.zustaendigerUserId}
onValueChange={(value: string) => set({ zustaendigerUserId: value })}
>
{ownerOptions.map((option) => (
<Select.Item key={option.id} value={option.id}>
{option.label}
</Select.Item>
))}
</Select>
</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={() => onOpenChange(false)}
data-ui-id="ui.crm.new.dialog.cancel"
>
{t("shared.cancel")}
</Button>
<Button type="submit" className="mobile:w-full" icon={<FeatherPlus />} disabled={!hasIdentity} data-ui-id="ui.crm.new.dialog.submit">
{t("crm.actions.create")}
</Button>
</div>
</form>
</Dialog.Content>
</Dialog>
);
}
@@ -0,0 +1,53 @@
// R-P6 interim-UI (AD-28) — KontaktNewPage unit test. Pure props (no VM); asserts
// the create/duplicate-check callbacks and the duplicate banner. i18n mocked.
import { fireEvent, render } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { KontaktNewPage, type KontaktNewPageActions } from "./KontaktNewPage";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }) }));
function actions(over: Partial<KontaktNewPageActions> = {}): KontaktNewPageActions {
return { onCheckDuplicates: vi.fn(), onCreate: vi.fn(), ...over };
}
function renderPage(props: Partial<Parameters<typeof KontaktNewPage>[0]> = {}) {
const acts = props.actions ?? actions();
render(
<KontaktNewPage
moduleActive
ownerOptions={[{ id: "u1", label: "Owner One" }]}
defaultOwnerId="u1"
backHref="/acme/contacts"
listLabelKey="crm.contacts.title"
duplicates={props.duplicates ?? null}
submitting={false}
errorKey={null}
actions={acts}
{...props}
/>,
);
return acts;
}
describe("KontaktNewPage", () => {
it("creates a contact with the typed fields", () => {
const onCreate = vi.fn();
renderPage({ actions: actions({ onCreate }) });
fireEvent.change(document.querySelector("[data-ui-id='ui.crm.new.vorname']")!, { target: { value: "Anna" } });
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.new.submit']")!);
expect(onCreate).toHaveBeenCalledWith(expect.objectContaining({ kontaktTyp: "privatperson", vorname: "Anna", zustaendigerUserId: "u1" }));
});
it("runs the live duplicate check on blur", () => {
const onCheckDuplicates = vi.fn();
renderPage({ actions: actions({ onCheckDuplicates }) });
fireEvent.blur(document.querySelector("[data-ui-id='ui.crm.new.email']")!);
expect(onCheckDuplicates).toHaveBeenCalledTimes(1);
});
it("shows the hard-duplicate banner", () => {
renderPage({ duplicates: { hard: [{ id: "k9", displayName: "Anna Muster", primaerEmail: "a@b.de", primaerTelefon: null, detailHref: "/acme/contacts/k9" }], soft: [] } });
expect(document.querySelector("[data-ui-id='ui.crm.new.duplicates.hard']")).not.toBeNull();
});
});
@@ -0,0 +1,174 @@
// R-P6 (P6 CRM core) Interim-UI (AD-28) — create-contact screen (D-CRM
// "Kontakt anlegen", archetype A4), composed from ~/ui. Pure/presentational: it
// holds the form draft and calls actions.onCheckDuplicates (live hard/soft hits,
// DoD 4) + actions.onCreate; the route runs the fetcher/submit. No useLoaderData/
// useFetcher. Final Subframe optics = tracked design-nachzug.
import { useState } from "react";
import { useTranslation } from "react-i18next";
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 { TextInput } from "~/ui/components/TextInput";
import { AppLink } from "~/components/app/AppLink";
export type KontaktNewDuplicateCard = { id: string; displayName: string; primaerEmail: string | null; primaerTelefon: string | null; detailHref: string };
export type KontaktNewDuplicates = { hard: readonly KontaktNewDuplicateCard[]; soft: readonly KontaktNewDuplicateCard[] };
export type KontaktNewFields = {
kontaktTyp: string;
kontaktStatus: string;
vorname: string;
nachname: string;
orgName: string;
orgMerkmal: string;
email: string;
telefon: string;
zustaendigerUserId: string;
};
export type KontaktNewPageActions = {
onCheckDuplicates: (fields: KontaktNewFields) => void;
onCreate: (fields: KontaktNewFields) => void;
};
export type KontaktNewPageProps = {
moduleActive: boolean;
ownerOptions: readonly { id: string; label: string }[];
defaultOwnerId: string;
backHref: string;
listLabelKey: string;
duplicates: KontaktNewDuplicates | null;
submitting: boolean;
errorKey?: string | null;
actions: KontaktNewPageActions;
};
export function KontaktNewPage(props: KontaktNewPageProps) {
const { t } = useTranslation();
const [fields, setFields] = useState<KontaktNewFields>({
kontaktTyp: "privatperson",
kontaktStatus: "kontakt",
vorname: "",
nachname: "",
orgName: "",
orgMerkmal: "",
email: "",
telefon: "",
zustaendigerUserId: props.defaultOwnerId,
});
const set = (patch: Partial<KontaktNewFields>) => setFields((s) => ({ ...s, ...patch }));
const isOrg = fields.kontaktTyp === "organisation";
const dup = props.duplicates;
if (!props.moduleActive) {
return (
<div className="flex w-full flex-col gap-6 p-6" data-ui-id="ui.crm.new">
<div data-ui-id="ui.crm.new.locked">
<BadgeFeedback farbe="subtle-neutral">{t("crm.locked.headline")}</BadgeFeedback>
</div>
</div>
);
}
return (
<div className="flex w-full flex-col gap-6 p-6" data-ui-id="ui.crm.new">
<span className="text-heading-2 font-heading-2 text-text-neutral-primary">{t("crm.new.title")}</span>
{props.errorKey ? (
<div data-ui-id="ui.crm.new.error">
<BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback>
</div>
) : null}
{dup && (dup.hard.length > 0 || dup.soft.length > 0) ? (
<Card variant={dup.hard.length > 0 ? "negative" : "warning"} data-ui-id="ui.crm.new.duplicates">
{dup.hard.length > 0 ? (
<div className="flex flex-col gap-1" data-ui-id="ui.crm.new.duplicates.hard">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-feedback-negative">{t("crm.new.duplicates.hard")}</span>
{dup.hard.map((card) => (
<AppLink key={card.id} href={card.detailHref} className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-link-default">
{card.displayName}
{card.primaerEmail ? ` · ${card.primaerEmail}` : ""}
{card.primaerTelefon ? ` · ${card.primaerTelefon}` : ""}
</AppLink>
))}
</div>
) : null}
{dup.soft.length > 0 ? (
<div className="flex flex-col gap-1" data-ui-id="ui.crm.new.duplicates.soft">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{t("crm.new.duplicates.soft")}</span>
{dup.soft.map((card) => (
<AppLink key={card.id} href={card.detailHref} className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-link-default">
{card.displayName}
{card.primaerEmail ? ` · ${card.primaerEmail}` : ""}
</AppLink>
))}
</div>
) : null}
</Card>
) : null}
<Card data-ui-id="ui.crm.new.form">
<div className="grid w-full gap-4 sm:grid-cols-2">
<Select label={t("crm.fields.type")} showLabel value={fields.kontaktTyp} onValueChange={(v) => set({ kontaktTyp: v })}>
<Select.Item value="privatperson">{t("crm.kontaktTyp.privatperson")}</Select.Item>
<Select.Item value="organisation">{t("crm.kontaktTyp.organisation")}</Select.Item>
</Select>
<Select label={t("crm.fields.status")} showLabel value={fields.kontaktStatus} onValueChange={(v) => set({ kontaktStatus: v })}>
{(["kontakt", "kunde", "bestandskunde"] as const).map((st) => (
<Select.Item key={st} value={st}>{t(`crm.kontaktStatus.${st}`)}</Select.Item>
))}
</Select>
{isOrg ? (
<>
<TextInput label={t("crm.fields.orgName")} showLabel>
<TextInput.Input value={fields.orgName} onChange={(e) => set({ orgName: e.target.value })} onBlur={() => props.actions.onCheckDuplicates(fields)} data-ui-id="ui.crm.new.orgName" />
</TextInput>
<Select label={t("crm.fields.orgMerkmal")} showLabel value={fields.orgMerkmal || "__none__"} onValueChange={(v) => set({ orgMerkmal: v === "__none__" ? "" : v })}>
<Select.Item value="__none__">{t("crm.fields.none")}</Select.Item>
{(["gmbh", "kg", "oeffentliche_einrichtung", "sonstige"] as const).map((m) => (
<Select.Item key={m} value={m}>{t(`crm.orgMerkmal.${m}`)}</Select.Item>
))}
</Select>
</>
) : (
<>
<TextInput label={t("crm.fields.vorname")} showLabel>
<TextInput.Input value={fields.vorname} onChange={(e) => set({ vorname: e.target.value })} onBlur={() => props.actions.onCheckDuplicates(fields)} data-ui-id="ui.crm.new.vorname" />
</TextInput>
<TextInput label={t("crm.fields.nachname")} showLabel>
<TextInput.Input value={fields.nachname} onChange={(e) => set({ nachname: e.target.value })} onBlur={() => props.actions.onCheckDuplicates(fields)} data-ui-id="ui.crm.new.nachname" />
</TextInput>
</>
)}
<TextInput label={t("crm.fields.email")} showLabel>
<TextInput.Input type="email" value={fields.email} onChange={(e) => set({ email: e.target.value })} onBlur={() => props.actions.onCheckDuplicates(fields)} data-ui-id="ui.crm.new.email" />
</TextInput>
<TextInput label={t("crm.fields.telefon")} showLabel>
<TextInput.Input value={fields.telefon} onChange={(e) => set({ telefon: e.target.value })} onBlur={() => props.actions.onCheckDuplicates(fields)} data-ui-id="ui.crm.new.telefon" />
</TextInput>
<Select label={t("crm.fields.owner")} showLabel value={fields.zustaendigerUserId} onValueChange={(v) => set({ zustaendigerUserId: v })}>
{props.ownerOptions.map((option) => (
<Select.Item key={option.id} value={option.id}>{option.label}</Select.Item>
))}
</Select>
</div>
<div className="flex items-center gap-2">
<Button loading={props.submitting} onClick={() => props.actions.onCreate(fields)} data-ui-id="ui.crm.new.submit">
{t("crm.actions.create")}
</Button>
<Button variant="neutral" onClick={() => props.actions.onCheckDuplicates(fields)} data-ui-id="ui.crm.new.checkDuplicates">
{t("crm.actions.checkDuplicates")}
</Button>
</div>
</Card>
</div>
);
}
export default KontaktNewPage;
@@ -0,0 +1,42 @@
// R-P6 interim-UI (AD-28) — TagAdminPage unit test. Fixture VM via the real
// buildTagAdminVM; asserts create/update/delete callbacks. i18n mocked.
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildTagAdminVM } from "@hivegrid/view-models";
import { TagAdminPage, type TagAdminPageActions } from "./TagAdminPage";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }) }));
const vm = buildTagAdminVM({
tags: [{ id: "t1", name: "VIP", farbe: "#ff0000" }],
usageCounts: new Map([["t1", 3]]),
canWrite: true,
});
function actions(over: Partial<TagAdminPageActions> = {}): TagAdminPageActions {
return { onCreate: vi.fn(), onUpdate: vi.fn(), onDelete: vi.fn(), ...over };
}
function renderPage(acts = actions()) {
render(<TagAdminPage vm={vm} moduleActive submitting={false} errorKey={null} actions={acts} />);
return acts;
}
describe("TagAdminPage", () => {
it("renders the tag row and deletes it", () => {
const onDelete = vi.fn();
renderPage(actions({ onDelete }));
expect(document.querySelector("[data-ui-id='ui.crm.admin.tags.list']")).not.toBeNull();
fireEvent.click(screen.getByText("crm.actions.delete"));
expect(onDelete).toHaveBeenCalledWith("t1");
});
it("creates a tag with the drafted name", () => {
const onCreate = vi.fn();
renderPage(actions({ onCreate }));
fireEvent.change(document.querySelector("[data-ui-id='ui.crm.admin.tags.create.name']")!, { target: { value: "Neu" } });
fireEvent.click(document.querySelector("[data-ui-id='ui.crm.admin.tags.create.submit']")!);
expect(onCreate).toHaveBeenCalledWith(expect.objectContaining({ name: "Neu" }));
});
});
@@ -0,0 +1,126 @@
// R-P6 (P6 CRM core) Interim-UI (AD-28) — tag admin (D-CRM "Tag-Verwaltung",
// archetype A2), composed from ~/ui. Pure/presentational: renders the server-built
// TagAdminVM and calls actions.onCreate / onUpdate / onDelete; the route POSTs the
// intents. Colour uses a native <input type="color"> (no ~/ui equivalent). Final
// Subframe optics = tracked design-nachzug.
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherTag } from "@subframe/core";
import type { TagAdminRowData, TagAdminVM } from "@hivegrid/view-models";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
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 { TextInput } from "~/ui/components/TextInput";
export type TagAdminPageActions = {
onCreate: (input: { name: string; farbe: string }) => void;
onUpdate: (input: { tagId: string; name: string; farbe: string }) => void;
onDelete: (tagId: string) => void;
};
export type TagAdminPageProps = {
vm: TagAdminVM;
moduleActive: boolean;
submitting: boolean;
errorKey?: string | null;
actions: TagAdminPageActions;
};
const colorInputClass = "h-9 w-12 rounded-sm border border-solid border-border-strong bg-surface-neutral-primary";
const fieldLabel = "text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-tertiary";
function TagAdminRow({ row, submitting, actions }: { row: TagAdminRowData; submitting: boolean; actions: TagAdminPageActions }) {
const { t } = useTranslation();
const [name, setName] = useState(row.name);
const [farbe, setFarbe] = useState(row.farbe);
return (
<div className="flex flex-wrap items-end gap-2 rounded-sm border border-solid border-border-default px-3 py-2" data-row-id={row.id}>
<TextInput label={t("crm.admin.tags.colName")} showLabel>
<TextInput.Input value={name} onChange={(e) => setName(e.target.value)} />
</TextInput>
<label className="flex flex-col gap-1">
<span className={fieldLabel}>{t("crm.admin.tags.colColor")}</span>
<input type="color" value={farbe} onChange={(e) => setFarbe(e.target.value)} className={colorInputClass} aria-label={t("crm.admin.tags.colColor")} />
</label>
<span className="flex h-9 items-center text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{t("crm.admin.tags.usage", { n: row.usageCount })}
</span>
<Button variant="neutral" size="small" loading={submitting} onClick={() => actions.onUpdate({ tagId: row.id, name: name.trim(), farbe })}>
{t("crm.actions.save")}
</Button>
<Button variant="tertiary" size="small" onClick={() => actions.onDelete(row.id)}>
{t("crm.actions.delete")}
</Button>
</div>
);
}
export function TagAdminPage(props: TagAdminPageProps) {
const { t } = useTranslation();
const [draft, setDraft] = useState({ name: "", farbe: "#888888" });
if (!props.moduleActive) {
return (
<PageShell uiId="ui.crm.admin.tags">
<PageHeader icon={<FeatherTag className={PAGE_HEADER_ICON_CLASS} />} title={t("crm.admin.tags.title")} subtitle={t("crm.admin.tags.subtitle")} />
<PageBody>
<div data-ui-id="ui.crm.admin.tags.locked">
<EmptyState title={t("crm.locked.headline")} body={t("crm.locked.body")} />
</div>
</PageBody>
</PageShell>
);
}
const rows = props.vm.status === "ready" && props.vm.data ? props.vm.data.rows : [];
return (
<PageShell uiId="ui.crm.admin.tags">
<PageHeader icon={<FeatherTag className={PAGE_HEADER_ICON_CLASS} />} title={t("crm.admin.tags.title")} subtitle={t("crm.admin.tags.subtitle")} />
<PageBody>
{props.errorKey ? <BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback> : null}
{/* Create first, existing tags below (both in their own white card). */}
<Card data-ui-id="ui.crm.admin.tags.create">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{t("crm.admin.tags.addHeading")}</span>
{/* One row on desktop; wraps only on narrow/mobile widths. */}
<div className="flex flex-col items-stretch gap-2 sm:flex-row sm:items-end">
<TextInput className="min-w-0 sm:flex-1" label={t("crm.admin.tags.colName")} showLabel>
<TextInput.Input value={draft.name} onChange={(e) => setDraft((s) => ({ ...s, name: e.target.value }))} data-ui-id="ui.crm.admin.tags.create.name" />
</TextInput>
<label className="flex flex-none flex-col gap-1">
<span className={fieldLabel}>{t("crm.admin.tags.colColor")}</span>
<input type="color" value={draft.farbe} onChange={(e) => setDraft((s) => ({ ...s, farbe: e.target.value }))} className={colorInputClass} aria-label={t("crm.admin.tags.colColor")} />
</label>
<Button
disabled={!draft.name.trim()}
onClick={() => {
props.actions.onCreate({ name: draft.name.trim(), farbe: draft.farbe });
setDraft({ name: "", farbe: "#888888" });
}}
data-ui-id="ui.crm.admin.tags.create.submit"
>
{t("crm.actions.create")}
</Button>
</div>
</Card>
{rows.length > 0 ? (
<Card data-ui-id="ui.crm.admin.tags.list">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{t("crm.admin.tags.existingHeading")}</span>
<div className="flex w-full flex-col gap-2">
{rows.map((row) => (
<TagAdminRow key={row.id} row={row} submitting={props.submitting} actions={props.actions} />
))}
</div>
</Card>
) : null}
</PageBody>
</PageShell>
);
}
export default TagAdminPage;