Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/components/screens/leads/LeadInboxPage.tsx
T

469 lines
22 KiB
TypeScript

// R-P7 (P7 Lead-Inbox) Interim-UI (AD-28) — lead triage inbox (D-P7 "Lead-Inbox",
// archetype A2 + Triage), composed from ~/ui. Pure/presentational: renders the
// server-built LeadListVM (filter/sort/cursor server-side) and turns every action
// into a callback the route drives (navigation for filter/page, POST for status/
// bulk). SSE realtime hint stays on the root via `sseHref`. No useLoaderData/
// useFetcher. Final Subframe optics = tracked design-nachzug.
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherActivity, FeatherChevronDown, FeatherColumns, FeatherEye, FeatherInbox, FeatherList, FeatherPlus, FeatherTrendingUp } from "@subframe/core";
import * as SubframeCore from "@subframe/core";
import type { LeadListVM } from "@hivegrid/view-models";
import { canTransitionLeadStatus, leadStatusFilterFromQuery, leadStatusFilterToQuery } from "~/utils/integrations/leads/leadListQuery";
import type { LeadListQuery, LeadQuelle, LeadStatus, LeadStatusFilterValue } from "~/utils/integrations/leads/leadListQuery";
import * as SubframeUtils from "~/ui/utils";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { FacetFilterBar, type ClientFacet } from "../shared/FacetFilterBar";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Checkbox } from "~/ui/components/Checkbox";
import { DropdownMenu } from "~/ui/components/DropdownMenu";
import { EmptyState } from "~/ui/components/EmptyState";
import { Select } from "~/ui/components/Select";
import { Table } from "~/ui/components/Table";
import { ToggleGroup } from "~/ui/components/ToggleGroup";
import { LeadNewDialog } from "./LeadNewDialog";
import { APP_TIME_ZONE } from "~/locale/format";
import { useLiveFilter } from "~/hooks/use-live-filter";
import { AppLink } from "~/components/app/AppLink";
const QUELLEN: readonly LeadQuelle[] = ["form", "email", "aircall", "manual", "custom"];
const STATUSES: readonly LeadStatus[] = ["new", "qualified", "converted", "lost", "spam"];
const FILTER_ANY = "__any__";
const markerColor: Record<string, "subtle-warning" | "subtle-negative" | "subtle-positive"> = {
duplicate: "subtle-warning",
spam: "subtle-negative",
converted: "subtle-positive",
};
export type LeadInboxActions = {
onApplyFilter: (query: LeadListQuery) => void;
onSetStatus: (leadId: string, status: LeadStatus) => void;
onBulkStatus: (leadIds: string[], status: LeadStatus) => void;
onNextPage: () => void;
onOpenBoard: () => void;
};
export type LeadInboxPageProps = {
vm: LeadListVM;
moduleActive: boolean;
query: LeadListQuery;
hasNextPage: boolean;
sseHref: string | null;
submitting: boolean;
errorKey?: string | null;
language?: string;
actions: LeadInboxActions;
};
export function LeadInboxPage(props: LeadInboxPageProps) {
const { t, i18n } = useTranslation();
const { query } = props;
const [search, setSearch] = useState(query.filter.search ?? "");
const [quelle, setQuelle] = useState<string>(query.filter.quelle ?? FILTER_ANY);
// Single-select in the UI, a list in the query — the mapping lives in
// leadListQuery so writing and reading it back always agree.
const [statusFilter, setStatusFilter] = useState<LeadStatusFilterValue>(leadStatusFilterFromQuery(query.filter.status));
// "Spam einblenden" mirrors includeSpam directly, like "Konvertierte
// einblenden" does — both read as "additionally show these".
const [showSpam, setShowSpam] = useState<boolean>(query.filter.includeSpam);
const [showConverted, setShowConverted] = useState<boolean>(query.filter.includeConverted);
const [selected, setSelected] = useState<ReadonlySet<string>>(new Set());
// "" = nothing preselected. That is the state for a mixed selection: showing
// one row's status there would claim the others share it.
const [bulkStatus, setBulkStatus] = useState<LeadStatus | "">("");
// Creating a lead is a short form, so the CTA opens a modal (like "Neue
// Automation") instead of navigating to the standalone create page.
const [createOpen, setCreateOpen] = useState(false);
// Live filter: dropdowns/checkboxes apply immediately (fresh value passed as
// override, state updates are async), the search input debounced. Defined
// before the module-inactive early return so the hook order stays stable.
function applyFilter(overrides?: Partial<{ quelle: string; statusFilter: LeadStatusFilterValue; showSpam: boolean; showConverted: boolean }>) {
const next = { quelle, statusFilter, showSpam, showConverted, ...overrides };
// Filtering for spam/converted while they are hidden would always yield an
// empty table, so an explicit pick wins over the two visibility checkboxes.
if (next.statusFilter === "spam") next.showSpam = true;
if (next.statusFilter === "converted") next.showConverted = true;
props.actions.onApplyFilter({
filter: {
...query.filter,
search: search.trim() || null,
status: leadStatusFilterToQuery(next.statusFilter),
quelle: next.quelle === FILTER_ANY ? null : (next.quelle as LeadQuelle),
includeSpam: next.showSpam,
includeConverted: next.showConverted,
},
sort: query.sort,
cursor: null,
});
}
useLiveFilter(search.trim(), query.filter.search ?? "", () => applyFilter());
// The controls both write AND read the query: arriving with a filter already
// in the URL (a statistics tile links here pre-filtered, or the user shares
// the link) has to show up in the dropdowns, not just in the table. Guarded by
// the signature so typing in the search box is never overwritten mid-keystroke.
const filterSignature = JSON.stringify(query.filter);
const lastFilterSignature = useRef(filterSignature);
useEffect(() => {
if (lastFilterSignature.current === filterSignature) return;
lastFilterSignature.current = filterSignature;
setSearch(query.filter.search ?? "");
setQuelle(query.filter.quelle ?? FILTER_ANY);
setStatusFilter(leadStatusFilterFromQuery(query.filter.status));
setShowSpam(query.filter.includeSpam);
setShowConverted(query.filter.includeConverted);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [filterSignature]);
const data = props.vm.status === "ready" ? props.vm.data : null;
const rows = useMemo(() => data?.rows ?? [], [data]);
const dateFormatter = new Intl.DateTimeFormat(props.language ?? i18n.language, { timeZone: APP_TIME_ZONE, dateStyle: "medium", timeStyle: "short" });
const someSelected = selected.size > 0;
const allSelected = rows.length > 0 && rows.every((row) => selected.has(row.id));
// Re-seed the bulk dropdown whenever the selection changes: exactly one row
// preselects that row's current status, anything else leaves it empty. Seeding
// on selection (not on every render) keeps a deliberate pick by the user from
// being overwritten while the same rows stay selected.
const selectionSignature = [...selected].sort().join(",");
useEffect(() => {
const onlyId = selected.size === 1 ? [...selected][0] : null;
const onlyRow = onlyId ? rows.find((row) => row.id === onlyId) : null;
setBulkStatus(onlyRow ? onlyRow.status : "");
// rows/selected are read through the signature; re-running on row identity
// would clobber the user's pick on every list refresh.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectionSignature]);
if (!props.moduleActive) {
return (
<PageShell uiId="ui.leads.list">
<PageHeader
icon={<FeatherTrendingUp className={PAGE_HEADER_ICON_CLASS} />}
title={t("leads.list.title")}
subtitle={t("leads.list.subtitle")}
/>
<PageBody>
<EmptyState title={t("leads.list.locked")} />
</PageBody>
</PageShell>
);
}
const facets: ClientFacet[] = [
{
key: "quelle",
label: t("leads.filter.source"),
icon: <FeatherInbox />,
tone: "violet-subtle",
options: QUELLEN.map((q) => ({ value: q, label: t(`leads.quelle.${q}`) })),
selected: new Set(quelle === FILTER_ANY ? [] : [quelle]),
},
{
key: "status",
label: t("leads.list.column.status"),
icon: <FeatherActivity />,
tone: "blue-subtle",
options: STATUSES.map((status) => ({ value: status, label: t(`leads.status.${status}`) })),
selected: new Set(statusFilter === "any" ? [] : [statusFilter]),
},
{
key: "visibility",
label: t("leads.filter.visibility"),
icon: <FeatherEye />,
tone: "sand-subtle",
options: [
{ value: "spam", label: t("leads.filter.showSpam") },
{ value: "converted", label: t("leads.filter.showConverted") },
],
selected: new Set([...(showSpam ? ["spam"] : []), ...(showConverted ? ["converted"] : [])]),
},
];
function toggleFacet(facetKey: string, value: string) {
if (facetKey === "quelle") {
const next = quelle === value ? FILTER_ANY : value;
setQuelle(next);
return applyFilter({ quelle: next });
}
if (facetKey === "status") {
const next: LeadStatusFilterValue = statusFilter === value ? "any" : (value as LeadStatusFilterValue);
setStatusFilter(next);
return applyFilter({ statusFilter: next });
}
if (facetKey === "visibility") {
if (value === "spam") {
const next = !showSpam;
setShowSpam(next);
return applyFilter({ showSpam: next });
}
const next = !showConverted;
setShowConverted(next);
return applyFilter({ showConverted: next });
}
return undefined;
}
function resetFilters() {
setSearch("");
setQuelle(FILTER_ANY);
setStatusFilter("any");
setShowSpam(false);
setShowConverted(false);
props.actions.onApplyFilter({
filter: {
...query.filter,
search: null,
status: leadStatusFilterToQuery("any"),
quelle: null,
includeSpam: false,
includeConverted: false,
},
sort: query.sort,
cursor: null,
});
}
function toggleRow(id: string, checked: boolean) {
setSelected((prev) => {
const next = new Set(prev);
if (checked) next.add(id);
else next.delete(id);
return next;
});
}
return (
<PageShell uiId="ui.leads.list" sseHref={props.sseHref}>
<PageHeader
icon={<FeatherTrendingUp className={PAGE_HEADER_ICON_CLASS} />}
title={t("leads.list.title")}
subtitle={t("leads.list.subtitle")}
actions={
<>
{/* Labelled board/list switch, same shape as the projects boards. */}
<ToggleGroup value="list" onValueChange={(value: string) => value === "board" && props.actions.onOpenBoard()} data-ui-id="ui.leads.list.viewToggle">
<ToggleGroup.Item icon={<FeatherColumns />} value="board" aria-label={t("leads.viewMode.board")} data-ui-id="ui.leads.list.viewToggle.board">
{t("leads.viewMode.board")}
</ToggleGroup.Item>
<ToggleGroup.Item icon={<FeatherList />} value="list" aria-label={t("leads.viewMode.list")} data-ui-id="ui.leads.list.viewToggle.list">
{t("leads.viewMode.list")}
</ToggleGroup.Item>
</ToggleGroup>
{data?.canWrite ? (
<Button icon={<FeatherPlus />} onClick={() => setCreateOpen(true)} data-ui-id="ui.leads.list.new">
{t("leads.actions.new")}
</Button>
) : null}
</>
}
/>
{/* Admin links (Quellen/Anti-Spam) live in the leads sub-sidenav, not here. */}
{/* --- Filter bar: the shared facet strip the boards and the settings
lists wear. Quelle and Status are single-select (picking the active
option again clears it, as the chip's X does); "Einblenden" is the
genuinely multi-select facet that replaced the two loose checkboxes.
Filtering stays server-side — the bar only reports the toggle and
`applyFilter` rewrites the query. --- */}
<FacetFilterBar
uiId="ui.leads.list.filter"
facets={facets}
onToggle={toggleFacet}
search={search}
onSearchChange={setSearch}
searchPlaceholder={t("leads.filter.searchPlaceholder")}
onReset={resetFilters}
labels={{ reset: t("leads.filter.resetAll"), removeChip: t("leads.filter.removeChip") }}
trailing={
/* Bulk status rides in the same strip as the filters: both narrow or
act on the same list, so splitting them over two rows made the page
read like there were two unrelated toolbars. Only shown when there
is a selection to act on — an always-visible bulk control that does
nothing most of the time only adds noise. */
data?.canWrite && someSelected ? (
<div className="flex shrink-0 items-end gap-2" data-ui-id="ui.leads.list.bulk">
<Select
className="max-w-[200px]"
placeholder={t("leads.actions.chooseStatus")}
value={bulkStatus}
onValueChange={(v) => setBulkStatus(v as LeadStatus)}
>
{STATUSES.map((s) => (
<Select.Item key={s} value={s}>
{t(`leads.status.${s}`)}
</Select.Item>
))}
</Select>
<Button
variant="neutral"
size="small"
disabled={!bulkStatus}
loading={props.submitting}
onClick={() => bulkStatus && props.actions.onBulkStatus([...selected], bulkStatus)}
data-ui-id="ui.leads.list.bulk.apply"
>
{t("leads.actions.applyBulk")}
</Button>
</div>
) : null
}
/>
<PageBody>
{props.errorKey ? <BadgeFeedback farbe="subtle-negative">{t(props.errorKey)}</BadgeFeedback> : null}
{rows.length === 0 ? (
<div data-ui-id="ui.leads.list.empty">
<EmptyState title={t(data?.emptyHeadlineKey ?? "leads.list.empty.headline")} body={t(data?.emptyBodyKey ?? "leads.list.empty.body")} />
</div>
) : (
<>
<div className="w-full overflow-x-auto">
<Table
data-ui-id="ui.leads.list.table"
header={
<Table.HeaderRow>
<Table.HeaderCell>
{data?.canWrite ? (
<Checkbox
checked={allSelected}
indeterminate={someSelected && !allSelected}
onCheckedChange={(c) => setSelected(c ? new Set(rows.map((r) => r.id)) : new Set())}
hideLabel
label={t("leads.list.column.select")}
/>
) : null}
</Table.HeaderCell>
<Table.HeaderCell>{t("leads.list.column.identity")}</Table.HeaderCell>
<Table.HeaderCell>{t("leads.list.column.source")}</Table.HeaderCell>
<Table.HeaderCell>{t("leads.list.column.status")}</Table.HeaderCell>
<Table.HeaderCell>{t("leads.list.column.owner")}</Table.HeaderCell>
<Table.HeaderCell>{t("leads.list.column.createdAt")}</Table.HeaderCell>
</Table.HeaderRow>
}
>
{rows.map((row) => (
<Table.Row key={row.id} data-row-id={row.id} data-markers={row.markers.join(",")}>
<Table.Cell>
{data?.canWrite ? (
<Checkbox
checked={selected.has(row.id)}
onCheckedChange={(c) => toggleRow(row.id, c)}
hideLabel
label={t("leads.list.column.select")}
data-ui-id={`ui.leads.list.row.select.${row.id}`}
/>
) : null}
</Table.Cell>
<Table.Cell>
<div className="flex flex-col gap-0.5">
<div className="flex items-center gap-2">
<AppLink href={row.detailHref} className="text-body-default-medium-0 font-body-default-medium-0 text-text-feedback-link-default">
{row.displayName}
</AppLink>
{row.markers.map((marker) => (
<BadgeFeedback key={marker} farbe={markerColor[marker]} size="small">
{t(`leads.marker.${marker}`)}
</BadgeFeedback>
))}
</div>
{row.preview ? (
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary line-clamp-1">{row.preview}</span>
) : null}
</div>
</Table.Cell>
<Table.Cell>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">{t(row.quelleLabelKey)}</span>
</Table.Cell>
<Table.Cell>
{/* The status badge is the edit control: clicking it opens the
status list and picking one saves right away. That replaced
the per-row quick-action column, which only ever offered
two of the five statuses. */}
{data?.canWrite ? (
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<button
type="button"
className="focus-visible:shadow-focus flex items-center gap-1 rounded-sm outline-none"
aria-label={t("leads.actions.changeStatus")}
data-ui-id={`ui.leads.list.row.status.${row.id}`}
>
<BadgeFeedback farbe="subtle-neutral" size="small">
{t(row.statusLabelKey)}
</BadgeFeedback>
<FeatherChevronDown className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
</button>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="start" sideOffset={4} asChild>
<DropdownMenu className="gap-1">
{STATUSES.map((status) => {
// Every status stays visible, but the ones the
// server would reject (converted/lost/spam are
// terminal) are not selectable — offering them
// would only produce an error banner.
const allowed = canTransitionLeadStatus(row.status, status);
return (
<DropdownMenu.DropdownItem
key={status}
showCheckbox
selected={row.status === status}
disabled={!allowed}
className={SubframeUtils.twClassNames(
"bg-surface-neutral-primary hover:bg-surface-neutral-tertiary active:bg-surface-neutral-secondary",
{ "pointer-events-none opacity-40": !allowed }
)}
onSelect={() => allowed && status !== row.status && props.actions.onSetStatus(row.id, status)}
data-ui-id={`ui.leads.list.row.status.${row.id}.${status}`}
>
{t(`leads.status.${status}`)}
</DropdownMenu.DropdownItem>
);
})}
</DropdownMenu>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
) : (
<BadgeFeedback farbe="subtle-neutral" size="small">
{t(row.statusLabelKey)}
</BadgeFeedback>
)}
</Table.Cell>
<Table.Cell>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">{row.zustaendigerLabel ?? "—"}</span>
</Table.Cell>
<Table.Cell>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">
{dateFormatter.format(new Date(row.createdAtIso))}
</span>
</Table.Cell>
</Table.Row>
))}
</Table>
</div>
{props.hasNextPage ? (
<div className="flex">
<Button variant="neutral" size="small" onClick={props.actions.onNextPage} data-ui-id="ui.leads.list.next">
{t("leads.actions.nextPage")}
</Button>
</div>
) : null}
</>
)}
{data?.canWrite ? <LeadNewDialog open={createOpen} onOpenChange={setCreateOpen} createHref={data.createHref} /> : null}
</PageBody>
</PageShell>
);
}
export default LeadInboxPage;