feat(templates): UI fuer Berechtigungs-Vorlagen — Modul 6/16 des UI-Backlogs
Backend existierte vollstaendig (list mit entity_type-Filter, create, update, delete, apply — templates:read/write, seit Audit-Fix im Katalog), Frontend hatte 0% Abdeckung. - api/permissionTemplates.ts: TanStack-Hooks (usePermissionTemplates, create/update/delete/apply mit Cache-Invalidierung, TemplateLevel-Typ) - pages/PermissionTemplates.tsx: Template-Karten (Name, Level-Badge, Entity-Type, Auto-Share-Zusammenfassung), Create/Edit-Dialog mit Level-Select und JSON-Textarea inkl. Array-Validierung mit Fehlertext, Apply-Dialog (Entity-Type vorbelegt, Entity-ID), Ergebnis-Banner mit Anzahl erstellter Berechtigungen, Delete mit Confirm — alle Aktionen hinter templates:write gegated - Platzierung: Settings-Subpage /settings/permission-templates (statisch, Core-Route) + Settings-Nav-Item - i18n permissionTemplates.* de/en Verifikation: Vitest 10/10 (Rendering, Level-Badges, Create mit validem + invalidem JSON, Edit prefilled, Apply mit Ergebnis, Delete-Confirm, Permission-Gating, Empty/Error) · tsc exit 0 · production build exit 0.
This commit is contained in:
@@ -0,0 +1,240 @@
|
||||
/**
|
||||
* PermissionTemplates page tests — reusable permission presets (module 6/16).
|
||||
*
|
||||
* Covers: rendering, template cards with level badges, create flow with
|
||||
* JSON validation, edit flow, apply flow, delete with confirmation,
|
||||
* permission gating (templates:write), empty and error states.
|
||||
*/
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { PermissionTemplatesPage } from '@/pages/PermissionTemplates';
|
||||
import type { PermissionTemplate } from '@/api/permissionTemplates';
|
||||
|
||||
const createMut = vi.fn().mockImplementation((_payload, opts) => {
|
||||
opts?.onSuccess?.({});
|
||||
return Promise.resolve({});
|
||||
});
|
||||
const updateMut = vi.fn().mockImplementation((_payload, opts) => {
|
||||
opts?.onSuccess?.({});
|
||||
return Promise.resolve({});
|
||||
});
|
||||
const deleteMut = vi.fn().mockResolvedValue({});
|
||||
const applyMut = vi.fn().mockImplementation((_payload, opts) => {
|
||||
opts?.onSuccess?.({ applied: [{ id: 'ep-1' }], count: 1 });
|
||||
return Promise.resolve({});
|
||||
});
|
||||
|
||||
const makeTemplate = (overrides: Partial<PermissionTemplate> = {}): PermissionTemplate => ({
|
||||
id: 'tp-1',
|
||||
name: 'Standard-Freigabe Kontakte',
|
||||
entity_type: 'contact',
|
||||
trigger_condition: null,
|
||||
auto_share_with: [
|
||||
{ principal_type: 'user', principal_id: '22222222-2222-2222-2222-222222222222', level: 'read' },
|
||||
],
|
||||
level: 'read',
|
||||
tenant_id: 't-1',
|
||||
created_at: '2026-09-01T10:00:00Z',
|
||||
updated_at: null,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
let mockItems: PermissionTemplate[] = [];
|
||||
let mockCanWrite = true;
|
||||
let mockError = false;
|
||||
|
||||
vi.mock('@/api/permissionTemplates', () => ({
|
||||
usePermissionTemplates: () => ({
|
||||
data: { items: mockItems, total: mockItems.length },
|
||||
isLoading: false,
|
||||
isError: mockError,
|
||||
isFetching: false,
|
||||
refetch: vi.fn(),
|
||||
}),
|
||||
useCreatePermissionTemplate: () => ({
|
||||
mutate: createMut,
|
||||
isPending: false,
|
||||
}),
|
||||
useUpdatePermissionTemplate: () => ({
|
||||
mutate: updateMut,
|
||||
isPending: false,
|
||||
}),
|
||||
useDeletePermissionTemplate: () => ({
|
||||
mutate: deleteMut,
|
||||
isPending: false,
|
||||
}),
|
||||
useApplyPermissionTemplate: () => ({
|
||||
mutate: applyMut,
|
||||
isPending: false,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/usePermission', () => ({
|
||||
usePermission: () => ({
|
||||
hasPermission: (perm: string) => mockCanWrite || perm !== 'templates:write',
|
||||
}),
|
||||
}));
|
||||
|
||||
function renderPage() {
|
||||
return render(
|
||||
<MemoryRouter>
|
||||
<PermissionTemplatesPage />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockItems = [];
|
||||
mockCanWrite = true;
|
||||
mockError = false;
|
||||
});
|
||||
|
||||
describe('PermissionTemplatesPage', () => {
|
||||
it('renders the page with title', () => {
|
||||
renderPage();
|
||||
expect(screen.getByTestId('permission-templates-page')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows empty state when no templates exist', () => {
|
||||
renderPage();
|
||||
expect(screen.getByTestId('templates-empty')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows error state on load failure', () => {
|
||||
mockError = true;
|
||||
renderPage();
|
||||
expect(screen.getByTestId('templates-error')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders template cards with level badge and entity type', () => {
|
||||
mockItems = [makeTemplate()];
|
||||
renderPage();
|
||||
expect(screen.getByTestId('template-card-tp-1')).toBeInTheDocument();
|
||||
expect(screen.getByText('Standard-Freigabe Kontakte')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('template-level-tp-1')).toBeInTheDocument();
|
||||
expect(screen.getByText('contact')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides action buttons without templates:write', () => {
|
||||
mockItems = [makeTemplate()];
|
||||
mockCanWrite = false;
|
||||
renderPage();
|
||||
expect(screen.queryByTestId('template-create-open')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('template-edit-tp-1')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('template-delete-tp-1')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('template-apply-tp-1')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('creates a template via the dialog with valid JSON', async () => {
|
||||
renderPage();
|
||||
fireEvent.click(screen.getByTestId('template-create-open'));
|
||||
expect(screen.getByTestId('template-form-submit')).toBeInTheDocument();
|
||||
|
||||
const nameInput = screen.getByLabelText(/name/i, { selector: 'input' }) as HTMLInputElement;
|
||||
fireEvent.change(nameInput, { target: { value: 'Neue Vorlage' } });
|
||||
const typeInputs = screen.getAllByLabelText(/entit/i, { selector: 'input' });
|
||||
fireEvent.change(typeInputs[0], { target: { value: 'contact' } });
|
||||
|
||||
const jsonArea = screen.getByTestId('template-share-json') as HTMLTextAreaElement;
|
||||
fireEvent.change(jsonArea, {
|
||||
target: { value: '[{"principal_type": "user", "principal_id": "abc", "level": "read"}]' },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByTestId('template-form-submit'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(createMut).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: 'Neue Vorlage',
|
||||
entity_type: 'contact',
|
||||
auto_share_with: [{ principal_type: 'user', principal_id: 'abc', level: 'read' }],
|
||||
}),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects invalid JSON in the create dialog', () => {
|
||||
renderPage();
|
||||
fireEvent.click(screen.getByTestId('template-create-open'));
|
||||
|
||||
const nameInput = screen.getByLabelText(/name/i, { selector: 'input' }) as HTMLInputElement;
|
||||
fireEvent.change(nameInput, { target: { value: 'Neue Vorlage' } });
|
||||
const typeInputs = screen.getAllByLabelText(/entit/i, { selector: 'input' });
|
||||
fireEvent.change(typeInputs[0], { target: { value: 'contact' } });
|
||||
|
||||
const jsonArea = screen.getByTestId('template-share-json') as HTMLTextAreaElement;
|
||||
fireEvent.change(jsonArea, { target: { value: '{invalid json' } });
|
||||
|
||||
fireEvent.click(screen.getByTestId('template-form-submit'));
|
||||
|
||||
expect(createMut).not.toHaveBeenCalled();
|
||||
expect(screen.getByRole('alert')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens the edit dialog prefilled and submits the update', async () => {
|
||||
mockItems = [makeTemplate()];
|
||||
renderPage();
|
||||
fireEvent.click(screen.getByTestId('template-edit-tp-1'));
|
||||
|
||||
const nameInput = screen.getByLabelText(/name/i, { selector: 'input' }) as HTMLInputElement;
|
||||
expect(nameInput).toHaveValue('Standard-Freigabe Kontakte');
|
||||
fireEvent.change(nameInput, { target: { value: 'Geänderte Vorlage' } });
|
||||
|
||||
fireEvent.click(screen.getByTestId('template-form-submit'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(updateMut).toHaveBeenCalledWith(
|
||||
{
|
||||
templateId: 'tp-1',
|
||||
payload: expect.objectContaining({
|
||||
name: 'Geänderte Vorlage',
|
||||
entity_type: 'contact',
|
||||
}),
|
||||
},
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('applies a template to an entity and shows the result count', async () => {
|
||||
mockItems = [makeTemplate()];
|
||||
renderPage();
|
||||
fireEvent.click(screen.getByTestId('template-apply-tp-1'));
|
||||
|
||||
const entityInputs = screen.getAllByLabelText(/entit/i, { selector: 'input' });
|
||||
const entityIdInput = entityInputs.find(
|
||||
(el) => (el as HTMLInputElement).placeholder?.includes('00000000'),
|
||||
) as HTMLInputElement;
|
||||
fireEvent.change(entityIdInput, {
|
||||
target: { value: '11111111-1111-1111-1111-111111111111' },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByTestId('template-apply-submit'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(applyMut).toHaveBeenCalledWith(
|
||||
{
|
||||
entity_type: 'contact',
|
||||
entity_id: '11111111-1111-1111-1111-111111111111',
|
||||
template_id: 'tp-1',
|
||||
},
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
expect(await screen.findByTestId('templates-result')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('deletes a template after confirmation', async () => {
|
||||
mockItems = [makeTemplate()];
|
||||
window.confirm = vi.fn(() => true);
|
||||
renderPage();
|
||||
fireEvent.click(screen.getByTestId('template-delete-tp-1'));
|
||||
await waitFor(() => {
|
||||
expect(deleteMut).toHaveBeenCalledWith('tp-1');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* Permission Templates API client — reusable permission presets.
|
||||
*
|
||||
* Backend: /api/v1/permission-templates (list, create, update, delete,
|
||||
* apply). Templates define default sharing rules; applying them creates
|
||||
* entity_permissions entries automatically.
|
||||
* Permissions: templates:read (list) / templates:write (everything else).
|
||||
*/
|
||||
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { apiGet, apiPost, apiPut, apiDelete } from '@/api/client';
|
||||
|
||||
export type TemplateLevel = 'read' | 'write' | 'admin' | 'delete';
|
||||
|
||||
export interface ShareEntry {
|
||||
principal_type?: string;
|
||||
principal_id?: string;
|
||||
level?: string;
|
||||
}
|
||||
|
||||
export interface PermissionTemplate {
|
||||
id: string;
|
||||
name: string;
|
||||
entity_type: string;
|
||||
trigger_condition: Record<string, unknown> | null;
|
||||
auto_share_with: ShareEntry[] | null;
|
||||
level: TemplateLevel;
|
||||
tenant_id: string;
|
||||
created_at: string | null;
|
||||
updated_at: string | null;
|
||||
}
|
||||
|
||||
export interface TemplateListResponse {
|
||||
items: PermissionTemplate[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface TemplateCreatePayload {
|
||||
name: string;
|
||||
entity_type: string;
|
||||
level?: TemplateLevel;
|
||||
trigger_condition?: Record<string, unknown> | null;
|
||||
auto_share_with?: ShareEntry[] | null;
|
||||
}
|
||||
|
||||
export type TemplateUpdatePayload = Partial<TemplateCreatePayload>;
|
||||
|
||||
export interface TemplateApplyPayload {
|
||||
entity_type: string;
|
||||
entity_id: string;
|
||||
template_id?: string | null;
|
||||
}
|
||||
|
||||
export interface TemplateApplyResponse {
|
||||
applied: Array<Record<string, unknown>>;
|
||||
count: number;
|
||||
}
|
||||
|
||||
// ─── Query hooks ─────────────────────────────────────────────
|
||||
|
||||
export function usePermissionTemplates(entityType?: string) {
|
||||
const qs = entityType ? `?entity_type=${encodeURIComponent(entityType)}` : '';
|
||||
return useQuery<TemplateListResponse>({
|
||||
queryKey: ['permission-templates', entityType ?? null],
|
||||
queryFn: () => apiGet<TemplateListResponse>(`/permission-templates${qs}`),
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Mutation hooks ──────────────────────────────────────────
|
||||
|
||||
function useInvalidateTemplates() {
|
||||
const qc = useQueryClient();
|
||||
return () => {
|
||||
qc.invalidateQueries({ queryKey: ['permission-templates'] });
|
||||
};
|
||||
}
|
||||
|
||||
export function useCreatePermissionTemplate() {
|
||||
const invalidate = useInvalidateTemplates();
|
||||
return useMutation<PermissionTemplate, Error, TemplateCreatePayload>({
|
||||
mutationFn: (data) => apiPost<PermissionTemplate>('/permission-templates', data),
|
||||
onSuccess: invalidate,
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdatePermissionTemplate() {
|
||||
const invalidate = useInvalidateTemplates();
|
||||
return useMutation<
|
||||
PermissionTemplate,
|
||||
Error,
|
||||
{ templateId: string; payload: TemplateUpdatePayload }
|
||||
>({
|
||||
mutationFn: ({ templateId, payload }) =>
|
||||
apiPut<PermissionTemplate>(`/permission-templates/${templateId}`, payload),
|
||||
onSuccess: invalidate,
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeletePermissionTemplate() {
|
||||
const invalidate = useInvalidateTemplates();
|
||||
return useMutation<void, Error, string>({
|
||||
mutationFn: (templateId) => apiDelete(`/permission-templates/${templateId}`),
|
||||
onSuccess: invalidate,
|
||||
});
|
||||
}
|
||||
|
||||
export function useApplyPermissionTemplate() {
|
||||
return useMutation<TemplateApplyResponse, Error, TemplateApplyPayload>({
|
||||
mutationFn: (data) => apiPost<TemplateApplyResponse>('/permission-templates/apply', data),
|
||||
});
|
||||
}
|
||||
@@ -1723,5 +1723,40 @@
|
||||
"empty": "Keine Plugins gefunden.",
|
||||
"loadError": "Marketplace konnte nicht geladen werden.",
|
||||
"noAccess": "Kein Zugriff auf den Marketplace (marketplace:read noetig)."
|
||||
},
|
||||
"permissionTemplates": {
|
||||
"title": "Berechtigungs-Vorlagen",
|
||||
"create": "Vorlage erstellen",
|
||||
"createTitle": "Neue Berechtigungs-Vorlage",
|
||||
"createSubmit": "Erstellen",
|
||||
"editTitle": "Vorlage bearbeiten",
|
||||
"save": "Speichern",
|
||||
"name": "Name",
|
||||
"namePlaceholder": "z.B. Standard-Freigabe Kontakte",
|
||||
"entityType": "Entitaets-Typ",
|
||||
"entityTypePlaceholder": "z.B. contact",
|
||||
"entityId": "Entitaets-ID",
|
||||
"level": "Standard-Level",
|
||||
"levelRead": "Lesen",
|
||||
"levelWrite": "Schreiben",
|
||||
"levelAdmin": "Admin",
|
||||
"levelDelete": "Loeschen",
|
||||
"level_read": "Lesen",
|
||||
"level_write": "Schreiben",
|
||||
"level_admin": "Admin",
|
||||
"level_delete": "Loeschen",
|
||||
"autoShareWith": "Automatisch teilen mit",
|
||||
"autoShareJson": "Freigaben (JSON)",
|
||||
"autoShareHelper": "Liste von {principal_type, principal_id, level}. Leer = keine Auto-Freigaben.",
|
||||
"jsonInvalid": "Ungueltiges JSON",
|
||||
"jsonMustBeArray": "Das JSON muss eine Liste sein",
|
||||
"apply": "Anwenden",
|
||||
"applyTitle": "Vorlage '{{name}}' anwenden",
|
||||
"applySubmit": "Anwenden",
|
||||
"appliedCount": "{{count}} Berechtigung(en) erstellt",
|
||||
"delete": "Loeschen",
|
||||
"deleteConfirm": "Vorlage '{{name}}' wirklich loeschen?",
|
||||
"empty": "Keine Berechtigungs-Vorlagen vorhanden.",
|
||||
"loadError": "Vorlagen konnten nicht geladen werden."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1723,5 +1723,40 @@
|
||||
"empty": "No plugins found.",
|
||||
"loadError": "Failed to load the marketplace.",
|
||||
"noAccess": "No marketplace access (marketplace:read required)."
|
||||
},
|
||||
"permissionTemplates": {
|
||||
"title": "Permission Templates",
|
||||
"create": "Create template",
|
||||
"createTitle": "New permission template",
|
||||
"createSubmit": "Create",
|
||||
"editTitle": "Edit template",
|
||||
"save": "Save",
|
||||
"name": "Name",
|
||||
"namePlaceholder": "e.g. Standard contact sharing",
|
||||
"entityType": "Entity type",
|
||||
"entityTypePlaceholder": "e.g. contact",
|
||||
"entityId": "Entity ID",
|
||||
"level": "Default level",
|
||||
"levelRead": "Read",
|
||||
"levelWrite": "Write",
|
||||
"levelAdmin": "Admin",
|
||||
"levelDelete": "Delete",
|
||||
"level_read": "Read",
|
||||
"level_write": "Write",
|
||||
"level_admin": "Admin",
|
||||
"level_delete": "Delete",
|
||||
"autoShareWith": "Auto-share with",
|
||||
"autoShareJson": "Share entries (JSON)",
|
||||
"autoShareHelper": "List of {principal_type, principal_id, level}. Empty = no auto-shares.",
|
||||
"jsonInvalid": "Invalid JSON",
|
||||
"jsonMustBeArray": "The JSON must be an array",
|
||||
"apply": "Apply",
|
||||
"applyTitle": "Apply template '{{name}}'",
|
||||
"applySubmit": "Apply",
|
||||
"appliedCount": "{{count}} permission(s) created",
|
||||
"delete": "Delete",
|
||||
"deleteConfirm": "Really delete template '{{name}}'?",
|
||||
"empty": "No permission templates yet.",
|
||||
"loadError": "Failed to load templates."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,456 @@
|
||||
/**
|
||||
* Permission Templates settings page — reusable permission presets
|
||||
* (UI-Backlog module 6/16).
|
||||
*
|
||||
* Backend: /api/v1/permission-templates (list, create, update, delete,
|
||||
* apply). Applying a template creates entity_permissions entries from its
|
||||
* auto_share_with list.
|
||||
* Permissions: templates:read (list) / templates:write (CRUD + apply).
|
||||
*/
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
LayoutTemplate,
|
||||
Plus,
|
||||
Pencil,
|
||||
Trash2,
|
||||
Play,
|
||||
KeyRound,
|
||||
AlertTriangle,
|
||||
Inbox,
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
usePermissionTemplates,
|
||||
useCreatePermissionTemplate,
|
||||
useUpdatePermissionTemplate,
|
||||
useDeletePermissionTemplate,
|
||||
useApplyPermissionTemplate,
|
||||
type PermissionTemplate,
|
||||
type TemplateLevel,
|
||||
type ShareEntry,
|
||||
} from '@/api/permissionTemplates';
|
||||
import { usePermission } from '@/hooks/usePermission';
|
||||
import { Card } from '@/components/ui/Card';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Modal } from '@/components/ui/Modal';
|
||||
import { Select } from '@/components/ui/Select';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { Badge } from '@/components/ui/Badge';
|
||||
|
||||
const LEVELS: { value: TemplateLevel; labelKey: string }[] = [
|
||||
{ value: 'read', labelKey: 'permissionTemplates.levelRead' },
|
||||
{ value: 'write', labelKey: 'permissionTemplates.levelWrite' },
|
||||
{ value: 'admin', labelKey: 'permissionTemplates.levelAdmin' },
|
||||
{ value: 'delete', labelKey: 'permissionTemplates.levelDelete' },
|
||||
];
|
||||
|
||||
const LEVEL_BADGE: Record<TemplateLevel, string> = {
|
||||
read: 'bg-secondary-200 text-secondary-800',
|
||||
write: 'bg-primary-100 text-primary-800',
|
||||
admin: 'bg-warning-100 text-warning-800',
|
||||
delete: 'bg-danger-100 text-danger-800',
|
||||
};
|
||||
|
||||
function summarizeShare(share: ShareEntry[] | null): string {
|
||||
if (!share || share.length === 0) return '—';
|
||||
return share
|
||||
.map((s) => `${s.principal_type ?? 'user'}:${(s.principal_id ?? '').slice(0, 8)} (${s.level ?? 'read'})`)
|
||||
.join(', ');
|
||||
}
|
||||
|
||||
function TemplateCard({
|
||||
template,
|
||||
canWrite,
|
||||
onEdit,
|
||||
onApply,
|
||||
onDelete,
|
||||
isMutating,
|
||||
}: {
|
||||
template: PermissionTemplate;
|
||||
canWrite: boolean;
|
||||
onEdit: (t: PermissionTemplate) => void;
|
||||
onApply: (t: PermissionTemplate) => void;
|
||||
onDelete: (t: PermissionTemplate) => void;
|
||||
isMutating: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Card className="p-4" data-testid={`template-card-${template.id}`}>
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<LayoutTemplate className="w-4 h-4 text-primary-600 flex-shrink-0" aria-hidden="true" />
|
||||
<span className="text-sm font-medium text-secondary-900 dark:text-secondary-100">
|
||||
{template.name}
|
||||
</span>
|
||||
<span data-testid={`template-level-${template.id}`}>
|
||||
<Badge className={LEVEL_BADGE[template.level]}>
|
||||
{t(`permissionTemplates.level_${template.level}`)}
|
||||
</Badge>
|
||||
</span>
|
||||
<Badge variant="secondary">{template.entity_type}</Badge>
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-secondary-500 dark:text-secondary-400" data-testid={`template-share-${template.id}`}>
|
||||
{t('permissionTemplates.autoShareWith')}: {summarizeShare(template.auto_share_with)}
|
||||
</div>
|
||||
</div>
|
||||
{canWrite && (
|
||||
<div className="flex gap-2 flex-shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => onApply(template)}
|
||||
disabled={isMutating}
|
||||
aria-label={t('permissionTemplates.apply')}
|
||||
data-testid={`template-apply-${template.id}`}
|
||||
>
|
||||
<Play className="w-4 h-4" aria-hidden="true" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => onEdit(template)}
|
||||
disabled={isMutating}
|
||||
aria-label={t('permissionTemplates.edit')}
|
||||
data-testid={`template-edit-${template.id}`}
|
||||
>
|
||||
<Pencil className="w-4 h-4" aria-hidden="true" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => onDelete(template)}
|
||||
disabled={isMutating}
|
||||
aria-label={t('permissionTemplates.delete')}
|
||||
data-testid={`template-delete-${template.id}`}
|
||||
className="text-danger-600 hover:text-danger-700"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" aria-hidden="true" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function TemplateFormDialog({
|
||||
open,
|
||||
template,
|
||||
onClose,
|
||||
onSubmit,
|
||||
isSubmitting,
|
||||
}: {
|
||||
open: boolean;
|
||||
template: PermissionTemplate | null;
|
||||
onClose: () => void;
|
||||
onSubmit: (payload: {
|
||||
name: string;
|
||||
entity_type: string;
|
||||
level: TemplateLevel;
|
||||
auto_share_with?: ShareEntry[] | null;
|
||||
}) => void;
|
||||
isSubmitting: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [name, setName] = useState(template?.name ?? '');
|
||||
const [entityType, setEntityType] = useState(template?.entity_type ?? '');
|
||||
const [level, setLevel] = useState<TemplateLevel>(template?.level ?? 'read');
|
||||
const [shareJson, setShareJson] = useState(
|
||||
template?.auto_share_with ? JSON.stringify(template.auto_share_with, null, 2) : '',
|
||||
);
|
||||
const [jsonError, setJsonError] = useState<string | null>(null);
|
||||
|
||||
// Reset on open (template may change between open/edit)
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
setName(template?.name ?? '');
|
||||
setEntityType(template?.entity_type ?? '');
|
||||
setLevel(template?.level ?? 'read');
|
||||
setShareJson(template?.auto_share_with ? JSON.stringify(template.auto_share_with, null, 2) : '');
|
||||
setJsonError(null);
|
||||
}
|
||||
}, [open, template]);
|
||||
|
||||
const parsedShare = (): ShareEntry[] | null | undefined => {
|
||||
if (!shareJson.trim()) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(shareJson);
|
||||
if (!Array.isArray(parsed)) {
|
||||
setJsonError(t('permissionTemplates.jsonMustBeArray'));
|
||||
return undefined;
|
||||
}
|
||||
setJsonError(null);
|
||||
return parsed as ShareEntry[];
|
||||
} catch {
|
||||
setJsonError(t('permissionTemplates.jsonInvalid'));
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const valid = name.trim().length > 0 && entityType.trim().length > 0;
|
||||
|
||||
const submit = () => {
|
||||
if (!valid) return;
|
||||
const share = parsedShare();
|
||||
if (share === undefined) return;
|
||||
onSubmit({ name: name.trim(), entity_type: entityType.trim(), level, auto_share_with: share });
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title={template ? t('permissionTemplates.editTitle') : t('permissionTemplates.createTitle')}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<Input
|
||||
label={t('permissionTemplates.name')}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
required
|
||||
placeholder={t('permissionTemplates.namePlaceholder')}
|
||||
/>
|
||||
<Input
|
||||
label={t('permissionTemplates.entityType')}
|
||||
value={entityType}
|
||||
onChange={(e) => setEntityType(e.target.value)}
|
||||
required
|
||||
placeholder={t('permissionTemplates.entityTypePlaceholder')}
|
||||
/>
|
||||
<Select
|
||||
label={t('permissionTemplates.level')}
|
||||
options={LEVELS.map((l) => ({ value: l.value, label: t(l.labelKey) }))}
|
||||
value={level}
|
||||
onChange={(e) => setLevel(e.target.value as TemplateLevel)}
|
||||
required
|
||||
/>
|
||||
<div>
|
||||
<label htmlFor="pt-share-json" className="block text-sm font-medium text-secondary-700 mb-1">
|
||||
{t('permissionTemplates.autoShareJson')}
|
||||
</label>
|
||||
<textarea
|
||||
id="pt-share-json"
|
||||
value={shareJson}
|
||||
onChange={(e) => setShareJson(e.target.value)}
|
||||
rows={4}
|
||||
className="block w-full rounded-md border border-secondary-300 px-3 py-2 text-xs font-mono min-h-touch"
|
||||
placeholder='[{"principal_type": "user", "principal_id": "<uuid>", "level": "read"}]'
|
||||
aria-label={t('permissionTemplates.autoShareJson')}
|
||||
data-testid="template-share-json"
|
||||
/>
|
||||
<p className={`mt-1 text-xs ${jsonError ? 'text-danger-600' : 'text-secondary-500'}`} role={jsonError ? 'alert' : undefined}>
|
||||
{jsonError ?? t('permissionTemplates.autoShareHelper')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button variant="ghost" onClick={onClose}>{t('common.cancel')}</Button>
|
||||
<Button onClick={submit} disabled={!valid || isSubmitting} data-testid="template-form-submit">
|
||||
{template ? t('permissionTemplates.save') : t('permissionTemplates.createSubmit')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function ApplyDialog({
|
||||
open,
|
||||
template,
|
||||
onClose,
|
||||
onSubmit,
|
||||
isSubmitting,
|
||||
}: {
|
||||
open: boolean;
|
||||
template: PermissionTemplate | null;
|
||||
onClose: () => void;
|
||||
onSubmit: (payload: { entity_type: string; entity_id: string; template_id: string }) => void;
|
||||
isSubmitting: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [entityId, setEntityId] = useState('');
|
||||
const [entityType, setEntityType] = useState('');
|
||||
|
||||
React.useEffect(() => {
|
||||
if (open && template) {
|
||||
setEntityType(template.entity_type);
|
||||
setEntityId('');
|
||||
}
|
||||
}, [open, template]);
|
||||
|
||||
const valid = entityId.trim().length > 0 && entityType.trim().length > 0;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title={t('permissionTemplates.applyTitle', { name: template?.name ?? '' })}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<Input
|
||||
label={t('permissionTemplates.entityType')}
|
||||
value={entityType}
|
||||
onChange={(e) => setEntityType(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<Input
|
||||
label={t('permissionTemplates.entityId')}
|
||||
value={entityId}
|
||||
onChange={(e) => setEntityId(e.target.value)}
|
||||
required
|
||||
placeholder="00000000-0000-0000-0000-000000000000"
|
||||
/>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button variant="ghost" onClick={onClose}>{t('common.cancel')}</Button>
|
||||
<Button onClick={() => valid && onSubmit({ entity_type: entityType.trim(), entity_id: entityId.trim(), template_id: template!.id })} disabled={!valid || isSubmitting} data-testid="template-apply-submit">
|
||||
{t('permissionTemplates.applySubmit')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
export function PermissionTemplatesPage() {
|
||||
const { t } = useTranslation();
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
const [editTemplate, setEditTemplate] = useState<PermissionTemplate | null>(null);
|
||||
const [applyTemplate, setApplyTemplate] = useState<PermissionTemplate | null>(null);
|
||||
const [resultMessage, setResultMessage] = useState<string | null>(null);
|
||||
|
||||
const { data, isLoading, isError } = usePermissionTemplates();
|
||||
const createMut = useCreatePermissionTemplate();
|
||||
const updateMut = useUpdatePermissionTemplate();
|
||||
const deleteMut = useDeletePermissionTemplate();
|
||||
const applyMut = useApplyPermissionTemplate();
|
||||
const { hasPermission } = usePermission();
|
||||
|
||||
const canWrite = hasPermission('templates:write');
|
||||
const isMutating = createMut.isPending || updateMut.isPending || deleteMut.isPending || applyMut.isPending;
|
||||
|
||||
const handleCreate = (payload: { name: string; entity_type: string; level: TemplateLevel; auto_share_with?: ShareEntry[] | null }) => {
|
||||
createMut.mutate(payload, {
|
||||
onSuccess: () => {
|
||||
setShowCreate(false);
|
||||
setResultMessage(null);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const handleEdit = (payload: { name: string; entity_type: string; level: TemplateLevel; auto_share_with?: ShareEntry[] | null }) => {
|
||||
if (!editTemplate) return;
|
||||
updateMut.mutate(
|
||||
{ templateId: editTemplate.id, payload },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setEditTemplate(null);
|
||||
setResultMessage(null);
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const handleDelete = (template: PermissionTemplate) => {
|
||||
if (window.confirm(t('permissionTemplates.deleteConfirm', { name: template.name }))) {
|
||||
deleteMut.mutate(template.id);
|
||||
}
|
||||
};
|
||||
|
||||
const handleApply = (payload: { entity_type: string; entity_id: string; template_id: string }) => {
|
||||
applyMut.mutate(payload, {
|
||||
onSuccess: (result) => {
|
||||
setApplyTemplate(null);
|
||||
setResultMessage(t('permissionTemplates.appliedCount', { count: result.count }));
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const items = data?.items ?? [];
|
||||
|
||||
return (
|
||||
<div className="max-w-3xl mx-auto p-4 sm:p-6 space-y-4" data-testid="permission-templates-page">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<KeyRound className="w-6 h-6 text-primary-600" aria-hidden="true" />
|
||||
<h1 className="text-2xl font-bold text-secondary-900 dark:text-secondary-100">
|
||||
{t('permissionTemplates.title')}
|
||||
</h1>
|
||||
</div>
|
||||
{canWrite && (
|
||||
<Button onClick={() => setShowCreate(true)} data-testid="template-create-open">
|
||||
<Plus className="w-4 h-4 mr-2" aria-hidden="true" />
|
||||
{t('permissionTemplates.create')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{resultMessage && (
|
||||
<div role="status">
|
||||
<Card className="p-3 text-sm text-success-700" data-testid="templates-result">
|
||||
{resultMessage}
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLoading && (
|
||||
<div className="flex items-center justify-center min-h-[30vh]" role="status" data-testid="templates-loading">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-500" aria-hidden="true" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isError && (
|
||||
<Card className="p-6 flex items-center gap-3 text-danger-600" data-testid="templates-error">
|
||||
<AlertTriangle className="w-5 h-5" aria-hidden="true" />
|
||||
<span>{t('permissionTemplates.loadError')}</span>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{!isLoading && !isError && items.length === 0 && (
|
||||
<Card className="p-8 flex flex-col items-center gap-3 text-secondary-500" data-testid="templates-empty">
|
||||
<Inbox className="w-10 h-10" aria-hidden="true" />
|
||||
<p>{t('permissionTemplates.empty')}</p>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
{items.map((template) => (
|
||||
<TemplateCard
|
||||
key={template.id}
|
||||
template={template}
|
||||
canWrite={canWrite}
|
||||
onEdit={setEditTemplate}
|
||||
onApply={setApplyTemplate}
|
||||
onDelete={handleDelete}
|
||||
isMutating={isMutating}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<TemplateFormDialog
|
||||
open={showCreate}
|
||||
template={null}
|
||||
onClose={() => setShowCreate(false)}
|
||||
onSubmit={handleCreate}
|
||||
isSubmitting={createMut.isPending}
|
||||
/>
|
||||
<TemplateFormDialog
|
||||
open={!!editTemplate}
|
||||
template={editTemplate}
|
||||
onClose={() => setEditTemplate(null)}
|
||||
onSubmit={handleEdit}
|
||||
isSubmitting={updateMut.isPending}
|
||||
/>
|
||||
<ApplyDialog
|
||||
open={!!applyTemplate}
|
||||
template={applyTemplate}
|
||||
onClose={() => setApplyTemplate(null)}
|
||||
onSubmit={handleApply}
|
||||
isSubmitting={applyMut.isPending}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default PermissionTemplatesPage;
|
||||
@@ -50,6 +50,7 @@ export function SettingsPage() {
|
||||
{ to: '/settings/backup', label: 'Backup & Restore', icon: '\ud83d\udcbe' },
|
||||
{ to: '/settings/api-tokens', label: 'API-Tokens', icon: '\ud83d\udd11' },
|
||||
{ to: '/settings/tenants', label: 'Mandanten', icon: '\ud83c\udfe2' },
|
||||
{ to: '/settings/permission-templates', label: 'Berechtigungs-Vorlagen', icon: '\ud83d\udd11' },
|
||||
];
|
||||
|
||||
const existingPaths = new Set(hardcodedNavItems.map(item => item.to));
|
||||
|
||||
@@ -47,6 +47,7 @@ const ApprovalsPage = React.lazy(() => import('@/pages/Approvals').then(m => ({
|
||||
const DelegationsPage = React.lazy(() => import('@/pages/Delegations').then(m => ({ default: m.DelegationsPage })));
|
||||
const ApiTokensPage = React.lazy(() => import('@/pages/ApiTokens').then(m => ({ default: m.ApiTokensPage })));
|
||||
const TenantsPage = React.lazy(() => import('@/pages/Tenants').then(m => ({ default: m.TenantsPage })));
|
||||
const PermissionTemplatesPage = React.lazy(() => import('@/pages/PermissionTemplates').then(m => ({ default: m.PermissionTemplatesPage })));
|
||||
const SettingsWebhooksPage = React.lazy(() => import('@/pages/SettingsWebhooks').then(m => ({ default: m.SettingsWebhooksPage })));
|
||||
const SettingsBackupPage = React.lazy(() => import('@/pages/SettingsBackup').then(m => ({ default: m.SettingsBackupPage })));
|
||||
const WorkspaceManagerPage = React.lazy(() => import('@/pages/SettingsWorkspaces').then(m => ({ default: m.WorkspaceManagerPage })));
|
||||
@@ -208,6 +209,7 @@ const router = createBrowserRouter([
|
||||
{ path: 'backup', element: withSuspense(<SettingsBackupPage />) },
|
||||
{ path: 'api-tokens', element: withSuspense(<ApiTokensPage />) },
|
||||
{ path: 'tenants', element: withSuspense(<TenantsPage />) },
|
||||
{ path: 'permission-templates', element: withSuspense(<PermissionTemplatesPage />) },
|
||||
{ path: 'rechte', element: <PermissionRoute permission="settings:read">{withSuspense(<SettingsRechtePage />)}</PermissionRoute> },
|
||||
// Phase Q2: plugin settings sub-pages render with bare sub-segments
|
||||
{ path: '*', element: <ErrorBoundary>{<PluginRouteRenderer variant="settings" />}</ErrorBoundary> },
|
||||
|
||||
Reference in New Issue
Block a user