Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/components/screens/users/RolesPage.tsx
T
2026-07-08 16:15:37 +02:00

532 lines
25 KiB
TypeScript

// R-P2b — D-P2 "WF-P2 Admin RBAC" S02 "Rollen und Berechtigungen" in David's
// Subframe optics. Pure presentational: renders the server-built RolesListVM
// and reports mutations through injected actions (route owns the fetcher).
// S02 — merged roles tab: search + type/in-use filters, Typ/Mitglieder columns
// M04A — "Rolle anlegen" basics step → M02
// M04B — "Rolle duplizieren" basics step (copied permissions) → M02
// M02 — large permission editor (L 1200): section sidebar + search + switches
// D03 — "Rolle in Nutzung blockiert" delete blocker
// David's "Status" column has no data-model backing (no Role.status) and the
// "Bereich/Kategorie" select has no Role.category — both omitted, tracked as
// design-nachzug. Role duplication = create with the source's permission set
// preloaded into the editor (same audited createWorkspaceRole path).
import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router";
import { useTranslation } from "react-i18next";
import * as SubframeCore from "@subframe/core";
import { FeatherCopy, FeatherEdit2, FeatherMoreHorizontal, FeatherPlus, FeatherTrash } from "@subframe/core";
import type { RoleEditorInputPermission, RolesListRow, RolesListVM, RoleTypeKey } from "@hivegrid/view-models";
import { buildRoleEditorVM, filterRoleEditorSections, togglePermission, EMPTY_ROLES_FILTER, filterRolesRows, type RolesListFilterState } from "@hivegrid/view-models";
import { permissionDisplayDescription, permissionDisplayName, roleDisplayDescription, roleDisplayName } from "~/components/core/roles/roleDisplay";
import { useLocaleFormatters } from "~/locale/format";
import { Alert } from "~/ui/components/Alert";
import { Button } from "~/ui/components/Button";
import { Dialog } from "~/ui/components/Dialog";
import { DropdownMenu } from "~/ui/components/DropdownMenu";
import { EmptyState } from "~/ui/components/EmptyState";
import { IconButton } from "~/ui/components/IconButton";
import { SearchInput } from "~/ui/components/SearchInput";
import { Select } from "~/ui/components/Select";
import { Switch } from "~/ui/components/Switch";
import { Table } from "~/ui/components/Table";
import { Tabs } from "~/ui/components/Tabs";
import { TextArea } from "~/ui/components/TextArea";
import { TextInput } from "~/ui/components/TextInput";
const FILTER_ALL = "__all__";
export type RoleMutationInput = { name: string; description: string; permissionNames: string[] };
export type RolesActions = {
/** POSTs the existing create contract (roles/new, action=create). */
onCreate: (input: RoleMutationInput) => void;
/** POSTs the existing update contract (roles/:id, action=edit). */
onUpdate: (roleId: string, input: RoleMutationInput) => void;
/** POSTs the existing delete contract (roles/:id, action=delete). */
onDelete: (roleId: string) => void;
};
export type RolesPageProps = {
vm: RolesListVM;
/** App permission catalog feeding the M02 editor sections. */
editorCatalog: readonly RoleEditorInputPermission[];
/** roleId → assigned permission names (editor prefill + M04B duplication). */
rolePermissionNames: Readonly<Record<string, readonly string[]>>;
/** Tab bar back to S01 (members). */
membersTabHref: string;
actions: RolesActions;
submitting: boolean;
errorMessage: string | null;
/** Increments after a successful mutation — closes any open dialog. */
closeSignal: number;
};
/** M04A/M04B basics step. */
type BasicsState = { source: RolesListRow | null; name: string; description: string };
/** M02 editor state. roleId null = create (after M04A/M04B). */
type EditorState = {
roleId: string | null;
duplicatedFromName: string | null;
name: string;
description: string;
enabled: ReadonlySet<string>;
};
export function RolesPage({ vm, editorCatalog, rolePermissionNames, membersTabHref, actions, submitting, errorMessage, closeSignal }: RolesPageProps) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const [filter, setFilter] = useState<RolesListFilterState>(EMPTY_ROLES_FILTER);
const [basics, setBasics] = useState<BasicsState | null>(null);
const [editor, setEditor] = useState<EditorState | null>(null);
const [deleteRow, setDeleteRow] = useState<RolesListRow | null>(null);
useEffect(() => {
if (closeSignal > 0) {
setBasics(null);
setEditor(null);
setDeleteRow(null);
}
}, [closeSignal]);
if (vm.status !== "ready" || !vm.data) {
return <div className="flex w-full flex-col gap-6" data-ui-id="ui.settings.rolesAndPermissions.roles" />;
}
const data = vm.data;
const rows = filterRolesRows(data.rows, filter);
function openEditorFor(row: RolesListRow) {
setEditor({
roleId: row.id,
duplicatedFromName: null,
name: row.name,
description: row.description,
enabled: new Set(rolePermissionNames[row.id] ?? []),
});
}
function continueToPermissions(state: BasicsState) {
setBasics(null);
setEditor({
roleId: null,
duplicatedFromName: state.source ? state.source.name : null,
name: state.name,
description: state.description,
enabled: new Set(state.source ? (rolePermissionNames[state.source.id] ?? []) : []),
});
}
return (
<div className="flex w-full flex-col gap-6" data-ui-id="ui.settings.rolesAndPermissions.roles">
{/* Header: title + subtitle (0px rhythm) + create CTA (M04A) */}
<div className="flex flex-wrap items-start justify-between gap-4">
<div className="flex flex-col gap-0">
<span className="text-heading-2 font-heading-2 text-text-neutral-primary">{t("settings.members.tabs.rolesAndPermissions")}</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t("settings.rolesAndPermissions.subtitle")}
</span>
</div>
{data.canCreate ? (
<Button
icon={<FeatherPlus />}
onClick={() => setBasics({ source: null, name: "", description: "" })}
data-ui-id="ui.settings.rolesAndPermissions.roles.new"
>
{t("settings.rolesAndPermissions.create")}
</Button>
) : null}
</div>
{/* Tabs: Mitarbeiter | Rollen und Berechtigungen (shared with S01) */}
<Tabs>
<Link to={membersTabHref} className="contents no-underline" data-ui-id="ui.settings.rolesAndPermissions.tab.members">
<Tabs.Item>{t("settings.members.tabs.members")}</Tabs.Item>
</Link>
<Tabs.Item active>{t("settings.members.tabs.rolesAndPermissions")}</Tabs.Item>
</Tabs>
{/* Toolbar: search (name/description) + type/in-use filters */}
<div className="flex flex-wrap items-end gap-4" data-ui-id="ui.settings.rolesAndPermissions.roles.filter">
<SearchInput
className="max-w-[320px]"
placeholder={t("settings.rolesAndPermissions.filters.searchPlaceholder")}
hideShortcut
value={filter.query}
onChange={(event) => setFilter((prev) => ({ ...prev, query: event.target.value }))}
/>
<Select
className="max-w-[200px]"
label={t("settings.rolesAndPermissions.columns.type")}
showLabel
value={filter.type ?? FILTER_ALL}
onValueChange={(value: string) => setFilter((prev) => ({ ...prev, type: value === FILTER_ALL ? null : (value as RoleTypeKey) }))}
>
<Select.Item value={FILTER_ALL}>{t("settings.members.filters.all")}</Select.Item>
<Select.Item value="system">{t("settings.rolesAndPermissions.type.system")}</Select.Item>
<Select.Item value="custom">{t("settings.rolesAndPermissions.type.custom")}</Select.Item>
</Select>
<Select
className="max-w-[200px]"
label={t("settings.rolesAndPermissions.filters.inUse")}
showLabel
value={filter.inUse === null ? FILTER_ALL : filter.inUse ? "yes" : "no"}
onValueChange={(value: string) => setFilter((prev) => ({ ...prev, inUse: value === FILTER_ALL ? null : value === "yes" }))}
>
<Select.Item value={FILTER_ALL}>{t("settings.members.filters.all")}</Select.Item>
<Select.Item value="yes">{t("settings.rolesAndPermissions.filters.inUseYes")}</Select.Item>
<Select.Item value="no">{t("settings.rolesAndPermissions.filters.inUseNo")}</Select.Item>
</Select>
</div>
{data.rows.length === 0 ? (
<div data-ui-id="ui.settings.rolesAndPermissions.roles.empty">
<EmptyState title={t(data.emptyHeadlineKey)} body={t(data.emptyBodyKey)} />
</div>
) : (
<div className="w-full overflow-x-auto">
<Table
header={
<Table.HeaderRow>
<Table.HeaderCell>{t("models.role.object")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.role.description")}</Table.HeaderCell>
<Table.HeaderCell>{t("settings.rolesAndPermissions.columns.type")}</Table.HeaderCell>
<Table.HeaderCell>{t("settings.rolesAndPermissions.columns.members")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.permission.plural")}</Table.HeaderCell>
<Table.HeaderCell> </Table.HeaderCell>
</Table.HeaderRow>
}
>
{rows.map((row) => (
<Table.Row key={row.id} data-ui-id="ui.settings.rolesAndPermissions.roles.row">
<Table.Cell>
<span className="whitespace-nowrap text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{roleDisplayName({ name: row.name, description: row.description }, t)}
</span>
</Table.Cell>
<Table.Cell>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-tertiary">
{roleDisplayDescription({ name: row.name, description: row.description }, t) || "—"}
</span>
</Table.Cell>
<Table.Cell>
<span className="whitespace-nowrap text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">
{t(row.typeLabelKey)}
</span>
</Table.Cell>
<Table.Cell>
<span className="whitespace-nowrap text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">
{formatters.number(row.memberCount)}
</span>
</Table.Cell>
<Table.Cell>
<span className="whitespace-nowrap text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">
{t("models.permission.count", { count: row.permissionCount, formattedCount: formatters.number(row.permissionCount) })}
</span>
</Table.Cell>
<Table.Cell>
<div className="flex grow shrink-0 basis-0 items-center justify-end">
{row.canEdit || row.canDuplicate || row.canDelete ? (
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<IconButton icon={<FeatherMoreHorizontal />} data-ui-id="ui.settings.rolesAndPermissions.roles.rowActions" />
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="end" sideOffset={4} asChild>
<DropdownMenu>
{row.canEdit ? (
<DropdownMenu.DropdownItem icon={<FeatherEdit2 />} onClick={() => openEditorFor(row)}>
{t("shared.edit")}
</DropdownMenu.DropdownItem>
) : null}
{row.canDuplicate ? (
<DropdownMenu.DropdownItem
icon={<FeatherCopy />}
onClick={() =>
setBasics({
source: row,
name: t("settings.rolesAndPermissions.duplicate.copyName", { name: row.name }),
description: row.description,
})
}
>
{t("settings.rolesAndPermissions.duplicate.action")}
</DropdownMenu.DropdownItem>
) : null}
{row.canDelete ? (
<DropdownMenu.DropdownItem icon={<FeatherTrash />} onClick={() => setDeleteRow(row)}>
{t("shared.delete")}
</DropdownMenu.DropdownItem>
) : null}
</DropdownMenu>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
) : null}
</div>
</Table.Cell>
</Table.Row>
))}
</Table>
{rows.length === 0 ? (
<div className="pt-4">
<EmptyState variant="no-results" title={t(data.noMatchesKey)} body={t(data.emptyBodyKey)} />
</div>
) : null}
</div>
)}
{/* M04A / M04B — basics step (S 560) */}
<Dialog open={basics !== null} onOpenChange={(open: boolean) => (open ? undefined : setBasics(null))}>
<Dialog.Content className="w-[560px] max-w-[90vw] p-6">
{basics ? <RoleBasicsDialog state={basics} onChange={setBasics} onContinue={continueToPermissions} onCancel={() => setBasics(null)} /> : <div />}
</Dialog.Content>
</Dialog>
{/* M02 — large permission editor (L 1200) */}
<Dialog open={editor !== null} onOpenChange={(open: boolean) => (open ? undefined : setEditor(null))}>
<Dialog.Content className="w-[1200px] max-w-[95vw] p-6">
{editor ? (
<RoleEditorDialog
state={editor}
onChange={setEditor}
editorCatalog={editorCatalog}
submitting={submitting}
errorMessage={errorMessage}
onCancel={() => setEditor(null)}
onSave={() => {
const input = { name: editor.name, description: editor.description, permissionNames: [...editor.enabled] };
if (editor.roleId) actions.onUpdate(editor.roleId, input);
else actions.onCreate(input);
}}
/>
) : (
<div />
)}
</Dialog.Content>
</Dialog>
{/* Delete confirm / D03 blocker (XS 420) */}
<Dialog open={deleteRow !== null} onOpenChange={(open: boolean) => (open ? undefined : setDeleteRow(null))}>
<Dialog.Content className="w-[420px] max-w-[90vw] p-4">
{deleteRow ? (
<div className="flex w-full flex-col gap-6" data-ui-id="ui.settings.rolesAndPermissions.roles.deleteConfirm">
<div className="flex flex-col gap-2">
<span className="text-heading-3 font-heading-3 text-text-neutral-primary">
{deleteRow.deleteBlockedInUse ? t("settings.rolesAndPermissions.deleteBlocked.title") : t("settings.rolesAndPermissions.delete.title")}
</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{deleteRow.deleteBlockedInUse
? t("settings.rolesAndPermissions.deleteBlocked.description", { name: deleteRow.name, count: deleteRow.memberCount })
: t("settings.rolesAndPermissions.delete.description", { name: deleteRow.name })}
</span>
</div>
<div className="flex w-full items-center justify-end gap-2">
<Button variant="tertiary" onClick={() => setDeleteRow(null)}>
{deleteRow.deleteBlockedInUse ? t("shared.close") : t("shared.cancel")}
</Button>
{!deleteRow.deleteBlockedInUse ? (
<Button
variant="destructive"
loading={submitting}
onClick={() => actions.onDelete(deleteRow.id)}
data-ui-id="ui.settings.rolesAndPermissions.roles.deleteSubmit"
>
{t("shared.delete")}
</Button>
) : null}
</div>
</div>
) : (
<div />
)}
</Dialog.Content>
</Dialog>
</div>
);
}
function RoleBasicsDialog({
state,
onChange,
onContinue,
onCancel,
}: {
state: BasicsState;
onChange: (state: BasicsState) => void;
onContinue: (state: BasicsState) => void;
onCancel: () => void;
}) {
const { t } = useTranslation();
const isDuplicate = state.source !== null;
const nameMissing = state.name.trim().length === 0;
return (
<div className="flex w-full flex-col gap-6" data-ui-id="ui.settings.rolesAndPermissions.roles.basics">
<div className="flex flex-col gap-2">
<span className="text-heading-3 font-heading-3 text-text-neutral-primary">
{isDuplicate ? t("settings.rolesAndPermissions.duplicate.title") : t("settings.rolesAndPermissions.createDialog.title")}
</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{isDuplicate
? t("settings.rolesAndPermissions.duplicate.hint", { name: state.source?.name ?? "" })
: t("settings.rolesAndPermissions.createDialog.description")}
</span>
</div>
<div className="flex w-full flex-col gap-4">
<TextInput className="w-full" label={t("models.role.name")} showLabel>
<TextInput.Input value={state.name} onChange={(event) => onChange({ ...state, name: event.target.value })} required />
</TextInput>
<TextArea className="w-full" label={t("models.role.description")} showLabel>
<TextArea.Input value={state.description} onChange={(event) => onChange({ ...state, description: event.target.value })} />
</TextArea>
</div>
<div className="flex w-full items-center justify-end gap-2">
<Button variant="tertiary" onClick={onCancel}>
{t("shared.cancel")}
</Button>
<Button disabled={nameMissing} onClick={() => onContinue(state)} data-ui-id="ui.settings.rolesAndPermissions.roles.basics.continue">
{t("settings.rolesAndPermissions.editor.continue")}
</Button>
</div>
</div>
);
}
function RoleEditorDialog({
state,
onChange,
editorCatalog,
submitting,
errorMessage,
onCancel,
onSave,
}: {
state: EditorState;
onChange: (state: EditorState) => void;
editorCatalog: readonly RoleEditorInputPermission[];
submitting: boolean;
errorMessage: string | null;
onCancel: () => void;
onSave: () => void;
}) {
const { t } = useTranslation();
const [query, setQuery] = useState("");
const [selectedSection, setSelectedSection] = useState<string | null>(null);
// Pure VM grouping (scope → David's sections); enabled state comes from the dialog.
const sections = useMemo(() => {
const vm = buildRoleEditorVM({
role: state.roleId ? { id: state.roleId, name: state.name, description: state.description } : null,
duplicatedFromName: state.duplicatedFromName,
appPermissions: editorCatalog,
assignedPermissionNames: [...state.enabled],
});
return vm.data?.sections ?? [];
}, [state.roleId, state.name, state.description, state.duplicatedFromName, state.enabled, editorCatalog]);
const searched = useMemo(() => filterRoleEditorSections(sections, query), [sections, query]);
const visible = query.trim() ? searched : selectedSection ? searched.filter((section) => section.id === selectedSection) : searched;
const nameMissing = state.name.trim().length === 0;
return (
<div className="flex w-full flex-col gap-6" data-ui-id="ui.settings.rolesAndPermissions.roles.editor">
<div className="flex flex-col gap-2">
<span className="text-heading-3 font-heading-3 text-text-neutral-primary">
{state.roleId ? t("settings.rolesAndPermissions.editor.title") : t("settings.rolesAndPermissions.createDialog.title")}
</span>
{state.duplicatedFromName ? (
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t("settings.rolesAndPermissions.duplicate.hint", { name: state.duplicatedFromName })}
</span>
) : null}
{errorMessage ? <Alert variant="error" title={errorMessage} /> : null}
</div>
<div className="flex w-full gap-6 mobile:flex-col">
{/* Sidebar: search + sections (Apple-settings pattern from David's M02) */}
<div className="flex w-64 flex-none flex-col gap-4 mobile:w-full">
<SearchInput
placeholder={t("settings.rolesAndPermissions.editor.searchPlaceholder")}
hideShortcut
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
<div className="flex flex-col gap-1">
<Button
variant={selectedSection === null ? "secondary" : "ghost"}
className="justify-start"
onClick={() => setSelectedSection(null)}
>
{t("settings.rolesAndPermissions.editor.allSections")}
</Button>
{sections.map((section) => (
<Button
key={section.id}
variant={selectedSection === section.id ? "secondary" : "ghost"}
className="justify-start"
onClick={() => setSelectedSection(section.id)}
>
{`${t(section.labelKey)} (${section.enabledCount}/${section.permissions.length})`}
</Button>
))}
</div>
</div>
{/* Main: role base data + permission rows as switches */}
<div className="flex max-h-[60vh] w-full flex-col gap-6 overflow-y-auto pr-2">
<div className="flex w-full flex-col gap-4">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{t("settings.rolesAndPermissions.editor.roleSection")}
</span>
<TextInput className="w-full" label={t("models.role.name")} showLabel>
<TextInput.Input value={state.name} onChange={(event) => onChange({ ...state, name: event.target.value })} required />
</TextInput>
<TextArea className="w-full" label={t("models.role.description")} showLabel>
<TextArea.Input value={state.description} onChange={(event) => onChange({ ...state, description: event.target.value })} />
</TextArea>
</div>
{visible.length === 0 ? (
<EmptyState variant="no-results" title={t("settings.rolesAndPermissions.editor.noMatches")} />
) : (
visible.map((section) => (
<div key={section.id} className="flex w-full flex-col gap-4" data-editor-section={section.id}>
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{t(section.labelKey)}</span>
<div className="flex w-full flex-col gap-4">
{section.permissions.map((permission) => (
<div key={permission.name} className="flex w-full items-start justify-between gap-4" data-editor-permission={permission.name}>
<div className="flex flex-col gap-0">
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-primary">
{permissionDisplayName({ name: permission.name, description: permission.description }, t)}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{permissionDisplayDescription({ name: permission.name, description: permission.description }, t) ?? permission.name}
</span>
</div>
<Switch
checked={state.enabled.has(permission.name)}
onCheckedChange={(checked: boolean) => onChange({ ...state, enabled: togglePermission(state.enabled, permission.name, checked) })}
/>
</div>
))}
</div>
</div>
))
)}
</div>
</div>
<div className="flex w-full items-center justify-end gap-2">
<Button variant="tertiary" onClick={onCancel}>
{t("shared.cancel")}
</Button>
<Button loading={submitting} disabled={nameMissing} onClick={onSave} data-ui-id="ui.settings.rolesAndPermissions.roles.editor.save">
{t("shared.save")}
</Button>
</div>
</div>
);
}