feat(tenants): UI fuer Mandanten-Verwaltung — Modul 4/16 des UI-Backlogs

Backend existierte vollstaendig (list, create, list users, assign user;
tenants:read/write), Frontend hatte 0% Abdeckung.

- api/tenants.ts: TanStack-Hooks (useTenants, useTenantUsers mit
  enabled-Gating, create, assignUser mit Cache-Invalidierung)
- pages/Tenants.tsx: Tenant-Karten (Name, Slug, Standard-Badge),
  expandierbare User-Liste pro Tenant (Rolle, E-Mail), Create-Dialog
  (Name + Slug mit Auto-Normalisierung), Assign-User-Dialog mit
  User-Picker (bereits zugewiesene gefiltert) — Create/Users/Assign
  hinter tenants:write gegated
- Platzierung: Settings-Subpage /settings/tenants (statisch, Core-Route)
  + Settings-Nav-Item
- i18n tenants.* de/en

Verifikation: Vitest 8/8 (Rendering, Standard-Badge, Expand-User-Liste,
Create-Flow, Assign-Flow, Permission-Gating, Empty/Error) · tsc exit 0 ·
production build exit 0.
This commit is contained in:
Agent Zero
2026-09-13 09:29:42 +02:00
parent 8d8beebd38
commit 79ca1cbe6d
7 changed files with 655 additions and 0 deletions
@@ -0,0 +1,194 @@
/**
* Tenants page tests — multi-tenant management (module 4/16).
*
* Covers: rendering, tenant cards with default badge, expandable user list,
* create dialog, assign user flow, permission gating (tenants: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 { TenantsPage } from '@/pages/Tenants';
import type { Tenant } from '@/api/tenants';
import type { UserResponse } from '@/api/users';
const createMut = vi.fn().mockImplementation((_payload, opts) => {
opts?.onSuccess?.({});
return Promise.resolve({});
});
const assignMut = vi.fn().mockImplementation((_payload, opts) => {
opts?.onSuccess?.({ message: 'ok' });
return Promise.resolve({});
});
const makeTenant = (overrides: Partial<Tenant> = {}): Tenant => ({
id: 'tn-1',
name: 'Default Org',
slug: 'default-org',
is_default: true,
...overrides,
});
const TENANT_USER = {
id: '11111111-1111-1111-1111-111111111111',
email: 'admin@example.com',
name: 'Administrator',
role: 'admin',
is_active: true,
};
const ALL_USER: UserResponse = {
id: '22222222-2222-2222-2222-222222222222',
email: 'other@example.com',
name: 'Other User',
first_name: null,
last_name: null,
avatar_url: null,
role: 'viewer',
role_id: null,
is_active: true,
tenant_id: 'tn-1',
};
let mockTenants: Tenant[] = [];
let mockTenantUsers: typeof TENANT_USER[] = [];
let mockCanWrite = true;
let mockError = false;
vi.mock('@/api/tenants', () => ({
useTenants: () => ({
data: { items: mockTenants },
isLoading: false,
isError: mockError,
isFetching: false,
refetch: vi.fn(),
}),
useTenantUsers: (tenantId: string | null) => ({
data: tenantId ? { items: mockTenantUsers } : undefined,
isLoading: false,
}),
useCreateTenant: () => ({
mutate: createMut,
isPending: false,
}),
useAssignUserToTenant: () => ({
mutate: assignMut,
isPending: false,
}),
}));
vi.mock('@/api/users', () => ({
useUsers: () => ({
data: { items: [ALL_USER], total: 1, page: 1, page_size: 100 },
isLoading: false,
}),
}));
vi.mock('@/hooks/usePermission', () => ({
usePermission: () => ({
hasPermission: (perm: string) => mockCanWrite || perm !== 'tenants:write',
}),
}));
function renderPage() {
return render(
<MemoryRouter>
<TenantsPage />
</MemoryRouter>,
);
}
beforeEach(() => {
vi.clearAllMocks();
mockTenants = [];
mockTenantUsers = [];
mockCanWrite = true;
mockError = false;
});
describe('TenantsPage', () => {
it('renders the page with title', () => {
renderPage();
expect(screen.getByTestId('tenants-page')).toBeInTheDocument();
});
it('shows empty state when no tenants exist', () => {
renderPage();
expect(screen.getByTestId('tenants-empty')).toBeInTheDocument();
});
it('shows error state on load failure', () => {
mockError = true;
renderPage();
expect(screen.getByTestId('tenants-error')).toBeInTheDocument();
});
it('renders tenant cards with name, slug and default badge', () => {
mockTenants = [makeTenant()];
renderPage();
expect(screen.getByTestId('tenant-card-tn-1')).toBeInTheDocument();
expect(screen.getByText('Default Org')).toBeInTheDocument();
expect(screen.getByText('default-org')).toBeInTheDocument();
// Default badge — 'Standard' appears exactly once (the tenant name
// 'Default Org' would also match a /default/i regex, so match exactly)
expect(screen.getByText(/^standard$/i)).toBeInTheDocument();
});
it('expands the user list via the toggle', async () => {
mockTenants = [makeTenant()];
mockTenantUsers = [TENANT_USER];
renderPage();
fireEvent.click(screen.getByTestId('tenant-users-toggle-tn-1'));
expect(await screen.findByTestId('tenant-users-list-tn-1')).toBeInTheDocument();
expect(screen.getByTestId(`tenant-user-tn-1-${TENANT_USER.id}`)).toBeInTheDocument();
expect(screen.getByText('Administrator')).toBeInTheDocument();
});
it('creates a tenant via the dialog', async () => {
renderPage();
fireEvent.click(screen.getByTestId('tenant-create-open'));
expect(screen.getByTestId('tenant-create-submit')).toBeInTheDocument();
const nameInput = screen.getByLabelText(/name/i, { selector: 'input' }) as HTMLInputElement;
fireEvent.change(nameInput, { target: { value: 'Zweite Firma' } });
const slugInput = screen.getByLabelText(/slug/i, { selector: 'input' }) as HTMLInputElement;
fireEvent.change(slugInput, { target: { value: 'zweite-firma' } });
fireEvent.click(screen.getByTestId('tenant-create-submit'));
await waitFor(() => {
expect(createMut).toHaveBeenCalledWith(
{ name: 'Zweite Firma', slug: 'zweite-firma' },
expect.anything(),
);
});
});
it('hides create and toggles without tenants:write', () => {
mockTenants = [makeTenant()];
mockCanWrite = false;
renderPage();
expect(screen.queryByTestId('tenant-create-open')).not.toBeInTheDocument();
expect(screen.queryByTestId('tenant-users-toggle-tn-1')).not.toBeInTheDocument();
});
it('assigns a user to the expanded tenant', async () => {
mockTenants = [makeTenant()];
mockTenantUsers = [TENANT_USER];
renderPage();
fireEvent.click(screen.getByTestId('tenant-users-toggle-tn-1'));
fireEvent.click(await screen.findByTestId('tenant-assign-open'));
const select = screen.getByRole('combobox');
fireEvent.change(select, { target: { value: ALL_USER.id } });
fireEvent.click(screen.getByTestId('tenant-assign-submit'));
await waitFor(() => {
expect(assignMut).toHaveBeenCalledWith(
{ tenantId: 'tn-1', userId: ALL_USER.id },
expect.anything(),
);
});
});
});