Adds frontend for cms page
This commit is contained in:
@@ -82,6 +82,35 @@ export interface ChangeRolePayload {
|
||||
|
||||
export type AvailabilityStatus = 'Available' | 'Maintenance' | 'NotAvailable';
|
||||
|
||||
export type CmsInstanceStatus = 'Available' | 'NotAvailable' | 'Inactive';
|
||||
|
||||
export interface CmsInstance {
|
||||
id: string;
|
||||
name: string;
|
||||
url: string;
|
||||
status: CmsInstanceStatus;
|
||||
disableMessage: string | null;
|
||||
lastContactedAt: string | null;
|
||||
lastStatusPushedAt: string | null;
|
||||
lastIntegrityCheckFailedAt: string | null;
|
||||
}
|
||||
|
||||
export interface CreateCmsInstanceRequest {
|
||||
name: string;
|
||||
url: string;
|
||||
apiKey: string;
|
||||
}
|
||||
|
||||
export interface UpdateCmsInstanceStatusRequest {
|
||||
status: CmsInstanceStatus;
|
||||
disableMessage: string | null;
|
||||
}
|
||||
|
||||
export interface UpdateStatusResult {
|
||||
success: boolean;
|
||||
slaveContactSuccess: boolean;
|
||||
}
|
||||
|
||||
export interface AvailabilityResponse {
|
||||
status: AvailabilityStatus;
|
||||
checkedAt: string; // ISO 8601
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { renderHook, waitFor, act } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { createElement } from 'react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { server } from '@/mocks/server';
|
||||
import { API_BASE } from '@/mocks/auth/fixtures';
|
||||
import { useAddCmsInstance } from './useAddCmsInstance';
|
||||
|
||||
function createWrapper() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
return ({ children }: { children: React.ReactNode }) =>
|
||||
createElement(QueryClientProvider, { client: queryClient }, children);
|
||||
}
|
||||
|
||||
const CMS_URL = `${API_BASE}/api/v1/CmsInstances`;
|
||||
|
||||
describe('useAddCmsInstance', () => {
|
||||
it('returns created instance on success', async () => {
|
||||
const { result } = renderHook(() => useAddCmsInstance(), { wrapper: createWrapper() });
|
||||
|
||||
await act(async () => {
|
||||
await result.current.mutateAsync({
|
||||
name: 'Test CMS',
|
||||
url: 'http://test.example.com',
|
||||
apiKey: 'secret',
|
||||
});
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
expect(result.current.data?.name).toBe('Test CMS');
|
||||
});
|
||||
|
||||
it('calls onError callback on HTTP 400', async () => {
|
||||
server.use(http.post(CMS_URL, () => HttpResponse.json({}, { status: 400 })));
|
||||
|
||||
const onError = vi.fn();
|
||||
const { result } = renderHook(() => useAddCmsInstance({ onError }), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
try {
|
||||
await result.current.mutateAsync({ name: 'X', url: 'http://x.com', apiKey: 'k' });
|
||||
} catch {
|
||||
// expected
|
||||
}
|
||||
});
|
||||
|
||||
await waitFor(() => expect(onError).toHaveBeenCalled());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api-client';
|
||||
import type { CmsInstance, CreateCmsInstanceRequest } from './types';
|
||||
|
||||
export function useAddCmsInstance(
|
||||
options?: Pick<UseMutationOptions<CmsInstance, Error, CreateCmsInstanceRequest>, 'onError'>,
|
||||
) {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<CmsInstance, Error, CreateCmsInstanceRequest>({
|
||||
mutationFn: (data) => api.post<CmsInstance>('/api/v1/CmsInstances', data),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['cmsInstances'] }),
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { createElement } from 'react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { server } from '@/mocks/server';
|
||||
import { API_BASE } from '@/mocks/auth/fixtures';
|
||||
import { getMockCmsInstances } from '@/mocks/cms/handlers';
|
||||
import { useCmsInstances } from './useCmsInstances';
|
||||
|
||||
function createWrapper() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
return ({ children }: { children: React.ReactNode }) =>
|
||||
createElement(QueryClientProvider, { client: queryClient }, children);
|
||||
}
|
||||
|
||||
const CMS_URL = `${API_BASE}/api/v1/CmsInstances`;
|
||||
|
||||
describe('useCmsInstances', () => {
|
||||
it('starts in loading state', () => {
|
||||
const { result } = renderHook(() => useCmsInstances(), { wrapper: createWrapper() });
|
||||
expect(result.current.isPending).toBe(true);
|
||||
});
|
||||
|
||||
it('returns the instances list on success', async () => {
|
||||
const { result } = renderHook(() => useCmsInstances(), { wrapper: createWrapper() });
|
||||
await waitFor(() => expect(result.current.isPending).toBe(false));
|
||||
|
||||
expect(result.current.isError).toBe(false);
|
||||
expect(result.current.data).toHaveLength(getMockCmsInstances().length);
|
||||
expect(result.current.data?.[0].name).toBe(getMockCmsInstances()[0].name);
|
||||
});
|
||||
|
||||
it('enters error state on network error', async () => {
|
||||
server.use(http.get(CMS_URL, () => HttpResponse.json({}, { status: 500 })));
|
||||
|
||||
const { result } = renderHook(() => useCmsInstances(), { wrapper: createWrapper() });
|
||||
await waitFor(() => expect(result.current.isPending).toBe(false));
|
||||
|
||||
expect(result.current.isError).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api-client';
|
||||
import type { CmsInstance } from './types';
|
||||
|
||||
export function useCmsInstances() {
|
||||
return useQuery<CmsInstance[], Error>({
|
||||
queryKey: ['cmsInstances'],
|
||||
queryFn: () => api.get<CmsInstance[]>('/api/v1/CmsInstances'),
|
||||
staleTime: 30_000,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { renderHook, waitFor, act } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { createElement } from 'react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { server } from '@/mocks/server';
|
||||
import { API_BASE } from '@/mocks/auth/fixtures';
|
||||
import { useUpdateCmsInstanceStatus } from './useUpdateCmsInstanceStatus';
|
||||
|
||||
function createWrapper() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
});
|
||||
return ({ children }: { children: React.ReactNode }) =>
|
||||
createElement(QueryClientProvider, { client: queryClient }, children);
|
||||
}
|
||||
|
||||
const INSTANCE_ID = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
|
||||
const STATUS_URL = `${API_BASE}/api/v1/CmsInstances/${INSTANCE_ID}/status`;
|
||||
|
||||
describe('useUpdateCmsInstanceStatus', () => {
|
||||
it('returns UpdateStatusResult on success', async () => {
|
||||
const onSuccess = vi.fn();
|
||||
const { result } = renderHook(() => useUpdateCmsInstanceStatus({ onSuccess }), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.mutateAsync({
|
||||
id: INSTANCE_ID,
|
||||
status: 'NotAvailable',
|
||||
disableMessage: 'Under maintenance',
|
||||
});
|
||||
});
|
||||
|
||||
await waitFor(() => expect(onSuccess).toHaveBeenCalled());
|
||||
const callArg = onSuccess.mock.calls[0][0];
|
||||
expect(callArg.success).toBe(true);
|
||||
expect(callArg.slaveContactSuccess).toBe(true);
|
||||
});
|
||||
|
||||
it('calls onError on network failure', async () => {
|
||||
server.use(http.put(STATUS_URL, () => HttpResponse.json({}, { status: 500 })));
|
||||
|
||||
const onError = vi.fn();
|
||||
const { result } = renderHook(() => useUpdateCmsInstanceStatus({ onError }), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
try {
|
||||
await result.current.mutateAsync({
|
||||
id: INSTANCE_ID,
|
||||
status: 'Available',
|
||||
disableMessage: null,
|
||||
});
|
||||
} catch {
|
||||
// expected
|
||||
}
|
||||
});
|
||||
|
||||
await waitFor(() => expect(onError).toHaveBeenCalled());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api-client';
|
||||
import type { UpdateCmsInstanceStatusRequest, UpdateStatusResult } from './types';
|
||||
|
||||
type UpdateVariables = { id: string } & UpdateCmsInstanceStatusRequest;
|
||||
|
||||
export function useUpdateCmsInstanceStatus(
|
||||
options?: Pick<UseMutationOptions<UpdateStatusResult, Error, UpdateVariables>, 'onSuccess' | 'onError'>,
|
||||
) {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<UpdateStatusResult, Error, UpdateVariables>({
|
||||
mutationFn: ({ id, ...body }) =>
|
||||
api.put<UpdateStatusResult>(`/api/v1/CmsInstances/${id}/status`, body),
|
||||
onSuccess: (data, variables, context) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['cmsInstances'] });
|
||||
options?.onSuccess?.(data, variables, context);
|
||||
},
|
||||
onError: options?.onError,
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useQuery, useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api-client';
|
||||
import type { UserListItem, InviteUserPayload, InviteUserResponse, ChangeRolePayload, UserRole } from './types';
|
||||
|
||||
@@ -10,11 +10,14 @@ export function useUsers() {
|
||||
});
|
||||
}
|
||||
|
||||
export function useInviteUser() {
|
||||
export function useInviteUser(
|
||||
options?: Pick<UseMutationOptions<InviteUserResponse, Error, InviteUserPayload>, 'onError'>,
|
||||
) {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<InviteUserResponse, Error, InviteUserPayload>({
|
||||
mutationFn: (data) => api.post<InviteUserResponse>('/api/v1/Users/invite', data),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['users'] }),
|
||||
...options,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { renderApp, mockAuthenticated } from '@/test/utils';
|
||||
import { server } from '@/mocks/server';
|
||||
import { API_BASE } from '@/mocks/auth/fixtures';
|
||||
import { resetMockCmsInstances } from '@/mocks/cms/handlers';
|
||||
import { _resetSetupStatusCache } from '@/router';
|
||||
|
||||
beforeEach(() => {
|
||||
_resetSetupStatusCache();
|
||||
resetMockCmsInstances();
|
||||
});
|
||||
|
||||
async function openDialog() {
|
||||
mockAuthenticated();
|
||||
renderApp('/cms');
|
||||
await screen.findByTestId('cms-add-button', {}, { timeout: 5000 });
|
||||
await userEvent.click(screen.getByTestId('cms-add-button'));
|
||||
expect(screen.getByTestId('add-cms-name')).toBeInTheDocument();
|
||||
}
|
||||
|
||||
describe('AddCmsInstanceDialog', () => {
|
||||
it('shows name, url and apiKey fields on open', async () => {
|
||||
await openDialog();
|
||||
expect(screen.getByTestId('add-cms-name')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('add-cms-url')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('add-cms-apikey-input')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('add-cms-submit')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows field error when name is empty', async () => {
|
||||
await openDialog();
|
||||
await userEvent.click(screen.getByTestId('add-cms-url'));
|
||||
await userEvent.click(screen.getByTestId('add-cms-name'));
|
||||
await userEvent.tab();
|
||||
expect(await screen.findByTestId('add-cms-name-error')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows field error when URL has no protocol', async () => {
|
||||
await openDialog();
|
||||
await userEvent.type(screen.getByTestId('add-cms-url'), 'cms.example.com');
|
||||
await userEvent.tab();
|
||||
expect(await screen.findByTestId('add-cms-url-error')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows FormErrorBanner on HTTP 400', async () => {
|
||||
server.use(
|
||||
http.post(`${API_BASE}/api/v1/CmsInstances`, () =>
|
||||
HttpResponse.json({ title: 'Bad Request' }, { status: 400 }),
|
||||
),
|
||||
);
|
||||
await openDialog();
|
||||
await userEvent.type(screen.getByTestId('add-cms-name'), 'CMS');
|
||||
await userEvent.type(screen.getByTestId('add-cms-url'), 'http://example.com');
|
||||
await userEvent.type(screen.getByTestId('add-cms-apikey-input'), 'key');
|
||||
await userEvent.click(screen.getByTestId('add-cms-submit'));
|
||||
|
||||
expect(await screen.findByTestId('form-error-banner')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('add-cms-name')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('resets form when dialog is closed and reopened', async () => {
|
||||
await openDialog();
|
||||
await userEvent.type(screen.getByTestId('add-cms-name'), 'Typed value');
|
||||
await userEvent.keyboard('{Escape}');
|
||||
await userEvent.click(screen.getByTestId('cms-add-button'));
|
||||
expect((screen.getByTestId('add-cms-name') as HTMLInputElement).value).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { toast } from 'sonner';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { PasswordField } from '@/components/ui/PasswordField';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
|
||||
import { FieldError } from '@/components/ui/FieldError';
|
||||
import { useAddCmsInstance } from '@/api/useAddCmsInstance';
|
||||
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
|
||||
import { addCmsInstanceSchema, type AddCmsInstanceFormData } from '@/lib/schemas/cms';
|
||||
|
||||
interface AddCmsInstanceDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function AddCmsInstanceDialog({ open, onOpenChange }: AddCmsInstanceDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
|
||||
const addInstance = useAddCmsInstance({
|
||||
onError: (err) => {
|
||||
if (err instanceof ProblemDetailsError && err.status === 409) {
|
||||
setServerError(t('cms.add.errors.conflict'));
|
||||
} else if (err instanceof NetworkError) {
|
||||
setServerError(t('errors.network'));
|
||||
} else {
|
||||
setServerError(t('errors.generic'));
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
reset,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<AddCmsInstanceFormData>({
|
||||
resolver: zodResolver(addCmsInstanceSchema),
|
||||
mode: 'onTouched',
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setServerError(null);
|
||||
addInstance.reset();
|
||||
reset();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open]);
|
||||
|
||||
const onSubmit = handleSubmit(async (values) => {
|
||||
setServerError(null);
|
||||
try {
|
||||
await addInstance.mutateAsync(values);
|
||||
toast.success(t('cms.add.successToast'));
|
||||
onOpenChange(false);
|
||||
} catch {
|
||||
// error shown via serverError state
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('cms.add.title')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={onSubmit} noValidate className="space-y-4">
|
||||
<FormErrorBanner
|
||||
error={serverError !== null ? { message: serverError } : null}
|
||||
onDismiss={() => setServerError(null)}
|
||||
/>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="add-cms-name">{t('cms.add.nameLabel')}</Label>
|
||||
<Input
|
||||
id="add-cms-name"
|
||||
type="text"
|
||||
data-testid="add-cms-name"
|
||||
aria-invalid={errors.name !== undefined}
|
||||
{...register('name')}
|
||||
/>
|
||||
{errors.name && (
|
||||
<FieldError message={errors.name.message} testId="add-cms-name-error" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="add-cms-url">{t('cms.add.urlLabel')}</Label>
|
||||
<Input
|
||||
id="add-cms-url"
|
||||
type="text"
|
||||
placeholder="http://cms.example.com"
|
||||
data-testid="add-cms-url"
|
||||
aria-invalid={errors.url !== undefined}
|
||||
{...register('url')}
|
||||
/>
|
||||
{errors.url && (
|
||||
<FieldError message={errors.url.message} testId="add-cms-url-error" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="add-cms-apikey">{t('cms.add.apiKeyLabel')}</Label>
|
||||
<PasswordField
|
||||
id="add-cms-apikey"
|
||||
{...register('apiKey')}
|
||||
/>
|
||||
{errors.apiKey && (
|
||||
<FieldError message={errors.apiKey.message} testId="add-cms-apikey-error" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={isSubmitting || addInstance.isPending}
|
||||
data-testid="add-cms-submit"
|
||||
>
|
||||
{isSubmitting || addInstance.isPending ? '…' : t('cms.add.submitButton')}
|
||||
</Button>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { MoreHorizontal } from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import type { CmsInstance, CmsInstanceStatus } from '@/api/types';
|
||||
|
||||
function statusBadgeVariant(status: CmsInstanceStatus) {
|
||||
if (status === 'Available') return 'secondary';
|
||||
if (status === 'NotAvailable') return 'destructive';
|
||||
return 'outline';
|
||||
}
|
||||
|
||||
function formatDate(iso: string | null): string {
|
||||
if (!iso) return '—';
|
||||
return new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
|
||||
}
|
||||
|
||||
interface CmsInstanceListProps {
|
||||
instances: CmsInstance[];
|
||||
onSetStatus: (instance: CmsInstance) => void;
|
||||
}
|
||||
|
||||
export function CmsInstanceList({ instances, onSetStatus }: CmsInstanceListProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>{t('cms.table.name')}</TableHead>
|
||||
<TableHead>{t('cms.table.url')}</TableHead>
|
||||
<TableHead>{t('cms.table.status')}</TableHead>
|
||||
<TableHead>{t('cms.table.lastContact')}</TableHead>
|
||||
<TableHead>{t('cms.table.disableMessage')}</TableHead>
|
||||
<TableHead>{t('cms.table.actions')}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{instances.map((instance) => (
|
||||
<TableRow
|
||||
key={instance.id}
|
||||
data-testid="cms-instance-row"
|
||||
className={instance.status === 'Inactive' ? 'opacity-50' : ''}
|
||||
>
|
||||
<TableCell>{instance.name}</TableCell>
|
||||
<TableCell>{instance.url}</TableCell>
|
||||
<TableCell>
|
||||
<Badge
|
||||
variant={statusBadgeVariant(instance.status)}
|
||||
data-testid="cms-instance-status-badge"
|
||||
>
|
||||
{t(`cms.status.${instance.status}`)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{formatDate(instance.lastContactedAt)}</TableCell>
|
||||
<TableCell>{instance.disableMessage ?? '—'}</TableCell>
|
||||
<TableCell>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
data-testid="cms-instance-actions-trigger"
|
||||
>
|
||||
<MoreHorizontal className="size-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
data-testid="cms-instance-set-status"
|
||||
onClick={() => onSetStatus(instance)}
|
||||
>
|
||||
{t('cms.actions.setStatus')}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { renderApp, mockAuthenticated } from '@/test/utils';
|
||||
import { resetMockCmsInstances } from '@/mocks/cms/handlers';
|
||||
import { _resetSetupStatusCache } from '@/router';
|
||||
|
||||
beforeEach(() => {
|
||||
_resetSetupStatusCache();
|
||||
resetMockCmsInstances();
|
||||
});
|
||||
|
||||
async function openSetStatusDialog() {
|
||||
mockAuthenticated();
|
||||
renderApp('/cms');
|
||||
const triggers = await screen.findAllByTestId('cms-instance-actions-trigger', {}, { timeout: 5000 });
|
||||
await userEvent.click(triggers[0]);
|
||||
await userEvent.click(await screen.findByTestId('cms-instance-set-status'));
|
||||
expect(screen.getByTestId('set-status-select')).toBeInTheDocument();
|
||||
}
|
||||
|
||||
describe('SetStatusDialog', () => {
|
||||
it('opens with status select and submit button', async () => {
|
||||
await openSetStatusDialog();
|
||||
expect(screen.getByTestId('set-status-select')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('set-status-submit')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not show DisableMessage field when status is Available', async () => {
|
||||
await openSetStatusDialog();
|
||||
expect(screen.queryByTestId('set-status-disable-message')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows DisableMessage field when NotAvailable is selected', async () => {
|
||||
await openSetStatusDialog();
|
||||
await userEvent.click(screen.getByTestId('set-status-select'));
|
||||
await userEvent.click(await screen.findByRole('option', { name: 'Unavailable' }));
|
||||
expect(await screen.findByTestId('set-status-disable-message')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('blocks submit when NotAvailable is selected but DisableMessage is empty', async () => {
|
||||
await openSetStatusDialog();
|
||||
await userEvent.click(screen.getByTestId('set-status-select'));
|
||||
await userEvent.click(await screen.findByRole('option', { name: 'Unavailable' }));
|
||||
await screen.findByTestId('set-status-disable-message');
|
||||
await userEvent.click(screen.getByTestId('set-status-submit'));
|
||||
expect(await screen.findByTestId('set-status-disable-message-error')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,181 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm, Controller } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { toast } from 'sonner';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
|
||||
import { FieldError } from '@/components/ui/FieldError';
|
||||
import { useUpdateCmsInstanceStatus } from '@/api/useUpdateCmsInstanceStatus';
|
||||
import { NetworkError } from '@/lib/api-client';
|
||||
import { setStatusSchema, type SetStatusFormData } from '@/lib/schemas/cms';
|
||||
import type { CmsInstance, CmsInstanceStatus } from '@/api/types';
|
||||
|
||||
interface SetStatusDialogProps {
|
||||
instance: CmsInstance | null;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
const statusOptions: CmsInstanceStatus[] = ['Available', 'NotAvailable', 'Inactive'];
|
||||
|
||||
export function SetStatusDialog({ instance, open, onOpenChange }: SetStatusDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
|
||||
const updateStatus = useUpdateCmsInstanceStatus({
|
||||
onSuccess: (result) => {
|
||||
if (result.slaveContactSuccess) {
|
||||
toast.success(t('cms.setStatus.successContactedToast'));
|
||||
} else {
|
||||
toast.success(t('cms.setStatus.successUnreachableToast'));
|
||||
}
|
||||
onOpenChange(false);
|
||||
},
|
||||
onError: (err) => {
|
||||
if (err instanceof NetworkError) {
|
||||
setServerError(t('errors.network'));
|
||||
} else {
|
||||
setServerError(t('errors.generic'));
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
control,
|
||||
watch,
|
||||
reset,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<SetStatusFormData>({
|
||||
resolver: zodResolver(setStatusSchema),
|
||||
mode: 'onTouched',
|
||||
defaultValues: { status: 'Available', disableMessage: '' },
|
||||
});
|
||||
|
||||
const selectedStatus = watch('status');
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !instance) {
|
||||
setServerError(null);
|
||||
updateStatus.reset();
|
||||
reset({ status: 'Available', disableMessage: '' });
|
||||
} else {
|
||||
reset({
|
||||
status: instance.status,
|
||||
disableMessage: instance.disableMessage ?? '',
|
||||
});
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open, instance]);
|
||||
|
||||
const onSubmit = handleSubmit(async (values) => {
|
||||
if (!instance) return;
|
||||
setServerError(null);
|
||||
try {
|
||||
await updateStatus.mutateAsync({
|
||||
id: instance.id,
|
||||
status: values.status,
|
||||
disableMessage: values.status === 'NotAvailable' ? (values.disableMessage ?? null) : null,
|
||||
});
|
||||
} catch {
|
||||
// error shown via serverError state
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('cms.setStatus.title')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={onSubmit} noValidate className="space-y-4">
|
||||
<FormErrorBanner
|
||||
error={serverError !== null ? { message: serverError } : null}
|
||||
onDismiss={() => setServerError(null)}
|
||||
/>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="set-status-status">{t('cms.setStatus.statusLabel')}</Label>
|
||||
<Controller
|
||||
name="status"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
value={field.value}
|
||||
onValueChange={(val) => field.onChange(val as CmsInstanceStatus)}
|
||||
>
|
||||
<SelectTrigger
|
||||
id="set-status-status"
|
||||
data-testid="set-status-select"
|
||||
aria-invalid={errors.status !== undefined}
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{statusOptions.map((s) => (
|
||||
<SelectItem key={s} value={s}>
|
||||
{t(`cms.status.${s}`)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
{errors.status && (
|
||||
<FieldError message={errors.status.message} testId="set-status-status-error" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{selectedStatus === 'NotAvailable' && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="set-status-disable-message">
|
||||
{t('cms.setStatus.disableMessageLabel')}
|
||||
</Label>
|
||||
<Input
|
||||
id="set-status-disable-message"
|
||||
type="text"
|
||||
placeholder={t('cms.setStatus.disableMessagePlaceholder')}
|
||||
data-testid="set-status-disable-message"
|
||||
aria-invalid={errors.disableMessage !== undefined}
|
||||
{...register('disableMessage')}
|
||||
/>
|
||||
{errors.disableMessage && (
|
||||
<FieldError
|
||||
message={errors.disableMessage.message}
|
||||
testId="set-status-disable-message-error"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={isSubmitting || updateStatus.isPending}
|
||||
data-testid="set-status-submit"
|
||||
>
|
||||
{isSubmitting || updateStatus.isPending ? '…' : t('cms.setStatus.submitButton')}
|
||||
</Button>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import { toast } from 'sonner';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -23,12 +22,8 @@ import {
|
||||
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
|
||||
import { FieldError } from '@/components/ui/FieldError';
|
||||
import { useInviteUser } from '@/api/useUsers';
|
||||
|
||||
const inviteSchema = z.object({
|
||||
email: z.string().email(),
|
||||
role: z.enum(['Administrator', 'User']),
|
||||
});
|
||||
type InviteFormData = z.infer<typeof inviteSchema>;
|
||||
import { inviteUserSchema, type InviteUserFormData } from '@/lib/schemas/users';
|
||||
import { NetworkError } from '@/lib/api-client';
|
||||
|
||||
interface InviteUserDialogProps {
|
||||
open: boolean;
|
||||
@@ -39,12 +34,22 @@ export function InviteUserDialog({ open, onOpenChange }: InviteUserDialogProps)
|
||||
const { t } = useTranslation();
|
||||
const [step, setStep] = useState<1 | 2>(1);
|
||||
const [inviteLink, setInviteLink] = useState<string | null>(null);
|
||||
const inviteUser = useInviteUser();
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
const inviteUser = useInviteUser({
|
||||
onError: (err) => {
|
||||
if (err instanceof NetworkError) {
|
||||
setServerError(t('errors.network'));
|
||||
} else {
|
||||
setServerError(t('errors.generic'));
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setStep(1);
|
||||
setInviteLink(null);
|
||||
setServerError(null);
|
||||
inviteUser.reset();
|
||||
reset();
|
||||
}
|
||||
@@ -57,17 +62,18 @@ export function InviteUserDialog({ open, onOpenChange }: InviteUserDialogProps)
|
||||
setValue,
|
||||
reset,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<InviteFormData>({
|
||||
resolver: zodResolver(inviteSchema),
|
||||
} = useForm<InviteUserFormData>({
|
||||
resolver: zodResolver(inviteUserSchema),
|
||||
});
|
||||
|
||||
const onSubmit = handleSubmit(async (values) => {
|
||||
setServerError(null);
|
||||
try {
|
||||
const response = await inviteUser.mutateAsync(values);
|
||||
setInviteLink(response.inviteLink);
|
||||
setStep(2);
|
||||
} catch {
|
||||
// error shown via inviteUser.error
|
||||
// error shown via serverError state
|
||||
}
|
||||
});
|
||||
|
||||
@@ -89,8 +95,8 @@ export function InviteUserDialog({ open, onOpenChange }: InviteUserDialogProps)
|
||||
{step === 1 && (
|
||||
<form onSubmit={onSubmit} noValidate className="space-y-4">
|
||||
<FormErrorBanner
|
||||
error={inviteUser.error ? { message: inviteUser.error.message } : null}
|
||||
onDismiss={() => inviteUser.reset()}
|
||||
error={serverError !== null ? { message: serverError } : null}
|
||||
onDismiss={() => setServerError(null)}
|
||||
/>
|
||||
|
||||
<div className="space-y-2">
|
||||
|
||||
@@ -184,8 +184,48 @@
|
||||
"branding": { "title": "Branding / Theme", "comingSoon": "Coming soon" }
|
||||
},
|
||||
"cms": {
|
||||
"title": "Content Management System",
|
||||
"description": "This is where you will manage your CMS content. This feature is coming soon."
|
||||
"title": "CMS Instances",
|
||||
"addButton": "Add CMS",
|
||||
"emptyState": {
|
||||
"heading": "No CMS instances yet",
|
||||
"description": "Add your first CMS instance to get started."
|
||||
},
|
||||
"table": {
|
||||
"name": "Name",
|
||||
"url": "URL",
|
||||
"status": "Status",
|
||||
"lastContact": "Last Contact",
|
||||
"disableMessage": "Disable Message",
|
||||
"actions": "Actions"
|
||||
},
|
||||
"status": {
|
||||
"Available": "Available",
|
||||
"NotAvailable": "Unavailable",
|
||||
"Inactive": "Inactive"
|
||||
},
|
||||
"actions": {
|
||||
"setStatus": "Set Status"
|
||||
},
|
||||
"add": {
|
||||
"title": "Add CMS Instance",
|
||||
"nameLabel": "Name",
|
||||
"urlLabel": "URL",
|
||||
"apiKeyLabel": "API Key",
|
||||
"submitButton": "Add",
|
||||
"successToast": "CMS instance added successfully",
|
||||
"errors": {
|
||||
"conflict": "A CMS instance with this name or URL already exists."
|
||||
}
|
||||
},
|
||||
"setStatus": {
|
||||
"title": "Set Status",
|
||||
"statusLabel": "Status",
|
||||
"disableMessageLabel": "Disable Message",
|
||||
"disableMessagePlaceholder": "Reason for disabling…",
|
||||
"submitButton": "Save",
|
||||
"successContactedToast": "Status updated — cliënt confirmed",
|
||||
"successUnreachableToast": "Status saved — cliënt unreachable"
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"403": {
|
||||
|
||||
@@ -184,8 +184,48 @@
|
||||
"branding": { "title": "Huisstijl / Thema", "comingSoon": "Binnenkort beschikbaar" }
|
||||
},
|
||||
"cms": {
|
||||
"title": "Content Management Systeem",
|
||||
"description": "Hier beheert u straks uw CMS-inhoud. Deze functie is binnenkort beschikbaar."
|
||||
"title": "CMS-instanties",
|
||||
"addButton": "CMS toevoegen",
|
||||
"emptyState": {
|
||||
"heading": "Nog geen CMS-instanties",
|
||||
"description": "Voeg uw eerste CMS-instantie toe om aan de slag te gaan."
|
||||
},
|
||||
"table": {
|
||||
"name": "Naam",
|
||||
"url": "URL",
|
||||
"status": "Status",
|
||||
"lastContact": "Laatste contact",
|
||||
"disableMessage": "Uitschakelreden",
|
||||
"actions": "Acties"
|
||||
},
|
||||
"status": {
|
||||
"Available": "Beschikbaar",
|
||||
"NotAvailable": "Niet beschikbaar",
|
||||
"Inactive": "Inactief"
|
||||
},
|
||||
"actions": {
|
||||
"setStatus": "Status instellen"
|
||||
},
|
||||
"add": {
|
||||
"title": "CMS-instantie toevoegen",
|
||||
"nameLabel": "Naam",
|
||||
"urlLabel": "URL",
|
||||
"apiKeyLabel": "API-sleutel",
|
||||
"submitButton": "Toevoegen",
|
||||
"successToast": "CMS-instantie succesvol toegevoegd",
|
||||
"errors": {
|
||||
"conflict": "Er bestaat al een CMS-instantie met deze naam of URL."
|
||||
}
|
||||
},
|
||||
"setStatus": {
|
||||
"title": "Status instellen",
|
||||
"statusLabel": "Status",
|
||||
"disableMessageLabel": "Uitschakelreden",
|
||||
"disableMessagePlaceholder": "Reden voor uitschakelen…",
|
||||
"submitButton": "Opslaan",
|
||||
"successContactedToast": "Status bijgewerkt — cliënt bevestigd",
|
||||
"successUnreachableToast": "Status opgeslagen — cliënt niet bereikbaar"
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"403": {
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { addCmsInstanceSchema, setStatusSchema } from './cms';
|
||||
|
||||
describe('addCmsInstanceSchema', () => {
|
||||
it('accepts valid data', () => {
|
||||
const result = addCmsInstanceSchema.safeParse({
|
||||
name: 'My CMS',
|
||||
url: 'http://192.168.1.5:8080',
|
||||
apiKey: 'secret-key',
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('accepts https URLs', () => {
|
||||
const result = addCmsInstanceSchema.safeParse({
|
||||
name: 'My CMS',
|
||||
url: 'https://cms.example.com',
|
||||
apiKey: 'secret-key',
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects missing name', () => {
|
||||
const result = addCmsInstanceSchema.safeParse({ name: '', url: 'http://example.com', apiKey: 'k' });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects URL without protocol', () => {
|
||||
const result = addCmsInstanceSchema.safeParse({ name: 'CMS', url: 'cms.example.com', apiKey: 'k' });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects bare IP without protocol', () => {
|
||||
const result = addCmsInstanceSchema.safeParse({ name: 'CMS', url: '192.168.1.5:8080', apiKey: 'k' });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects missing apiKey', () => {
|
||||
const result = addCmsInstanceSchema.safeParse({ name: 'CMS', url: 'http://example.com', apiKey: '' });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('setStatusSchema', () => {
|
||||
it('accepts Available without disableMessage', () => {
|
||||
const result = setStatusSchema.safeParse({ status: 'Available' });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('accepts Inactive without disableMessage', () => {
|
||||
const result = setStatusSchema.safeParse({ status: 'Inactive' });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('accepts NotAvailable with a disableMessage', () => {
|
||||
const result = setStatusSchema.safeParse({ status: 'NotAvailable', disableMessage: 'System down' });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects NotAvailable without disableMessage', () => {
|
||||
const result = setStatusSchema.safeParse({ status: 'NotAvailable' });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects NotAvailable with blank disableMessage', () => {
|
||||
const result = setStatusSchema.safeParse({ status: 'NotAvailable', disableMessage: ' ' });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const addCmsInstanceSchema = z.object({
|
||||
name: z.string().min(1, 'Name is required').max(255, 'Name must be 255 characters or fewer'),
|
||||
url: z.string().url('Must be a valid URL (include http:// or https://)'),
|
||||
apiKey: z.string().min(1, 'API key is required'),
|
||||
});
|
||||
|
||||
export type AddCmsInstanceFormData = z.infer<typeof addCmsInstanceSchema>;
|
||||
|
||||
export const setStatusSchema = z
|
||||
.object({
|
||||
status: z.enum(['Available', 'NotAvailable', 'Inactive']),
|
||||
disableMessage: z.string().optional(),
|
||||
})
|
||||
.refine(
|
||||
(data) =>
|
||||
data.status !== 'NotAvailable' || (data.disableMessage?.trim().length ?? 0) > 0,
|
||||
{
|
||||
message: 'Disable message is required when status is Not Available',
|
||||
path: ['disableMessage'],
|
||||
},
|
||||
);
|
||||
|
||||
export type SetStatusFormData = z.infer<typeof setStatusSchema>;
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { inviteUserSchema } from './users';
|
||||
|
||||
describe('inviteUserSchema', () => {
|
||||
it('accepts valid email and role', () => {
|
||||
const result = inviteUserSchema.safeParse({ email: 'user@example.com', role: 'Administrator' });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects invalid email', () => {
|
||||
const result = inviteUserSchema.safeParse({ email: 'not-an-email', role: 'User' });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects missing role', () => {
|
||||
const result = inviteUserSchema.safeParse({ email: 'user@example.com' });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects invalid role value', () => {
|
||||
const result = inviteUserSchema.safeParse({ email: 'user@example.com', role: 'Owner' });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const inviteUserSchema = z.object({
|
||||
email: z.string().email(),
|
||||
role: z.enum(['Administrator', 'User']),
|
||||
});
|
||||
|
||||
export type InviteUserFormData = z.infer<typeof inviteUserSchema>;
|
||||
@@ -0,0 +1,66 @@
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import type { CmsInstance, UpdateStatusResult } from '@/api/types';
|
||||
import { API_BASE } from '../auth/fixtures';
|
||||
|
||||
const seed: CmsInstance[] = [
|
||||
{
|
||||
id: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
|
||||
name: 'Main CMS',
|
||||
url: 'http://cms.example.com',
|
||||
status: 'Available',
|
||||
disableMessage: null,
|
||||
lastContactedAt: '2026-06-30T10:00:00.000Z',
|
||||
lastStatusPushedAt: '2026-06-30T10:00:00.000Z',
|
||||
lastIntegrityCheckFailedAt: null,
|
||||
},
|
||||
{
|
||||
id: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
|
||||
name: 'Legacy CMS',
|
||||
url: 'http://legacy.example.com',
|
||||
status: 'Inactive',
|
||||
disableMessage: null,
|
||||
lastContactedAt: null,
|
||||
lastStatusPushedAt: null,
|
||||
lastIntegrityCheckFailedAt: null,
|
||||
},
|
||||
];
|
||||
|
||||
let mockCmsInstances: CmsInstance[] = [...seed];
|
||||
|
||||
export const resetMockCmsInstances = () => {
|
||||
mockCmsInstances = [...seed];
|
||||
};
|
||||
|
||||
export const getMockCmsInstances = () => mockCmsInstances;
|
||||
|
||||
export const cmsHandlers = [
|
||||
http.get(`${API_BASE}/api/v1/CmsInstances`, () => HttpResponse.json(mockCmsInstances)),
|
||||
|
||||
http.post(`${API_BASE}/api/v1/CmsInstances`, async ({ request }) => {
|
||||
const body = (await request.json()) as { name: string; url: string; apiKey: string };
|
||||
const newInstance: CmsInstance = {
|
||||
id: crypto.randomUUID(),
|
||||
name: body.name,
|
||||
url: body.url,
|
||||
status: 'Available',
|
||||
disableMessage: null,
|
||||
lastContactedAt: null,
|
||||
lastStatusPushedAt: null,
|
||||
lastIntegrityCheckFailedAt: null,
|
||||
};
|
||||
mockCmsInstances = [...mockCmsInstances, newInstance];
|
||||
return HttpResponse.json(newInstance, { status: 201 });
|
||||
}),
|
||||
|
||||
http.put(`${API_BASE}/api/v1/CmsInstances/:id/status`, async ({ params, request }) => {
|
||||
const { id } = params as { id: string };
|
||||
const body = (await request.json()) as { status: CmsInstance['status']; disableMessage: string | null };
|
||||
mockCmsInstances = mockCmsInstances.map((instance) =>
|
||||
instance.id === id
|
||||
? { ...instance, status: body.status, disableMessage: body.disableMessage }
|
||||
: instance,
|
||||
);
|
||||
const result: UpdateStatusResult = { success: true, slaveContactSuccess: true };
|
||||
return HttpResponse.json(result);
|
||||
}),
|
||||
];
|
||||
@@ -3,13 +3,15 @@ import { userHandlers } from './users/handlers';
|
||||
import { setupHandlers } from './setup/handlers';
|
||||
import { invitationHandlers } from './invitation/handlers';
|
||||
import { availabilityHandlers } from './availability/handlers';
|
||||
import { cmsHandlers } from './cms/handlers';
|
||||
|
||||
/** All default MSW handlers, composed from feature folders (Q3-B). */
|
||||
export const handlers = [...authHandlers, ...userHandlers, ...setupHandlers, ...invitationHandlers, ...availabilityHandlers];
|
||||
export const handlers = [...authHandlers, ...userHandlers, ...setupHandlers, ...invitationHandlers, ...availabilityHandlers, ...cmsHandlers];
|
||||
|
||||
export { authHandlers } from './auth/handlers';
|
||||
export { userHandlers } from './users/handlers';
|
||||
export { setupHandlers, setupUninitializedHandlers, setupConflictHandlers, setupNetworkErrorHandlers } from './setup/handlers';
|
||||
export { invitationHandlers } from './invitation/handlers';
|
||||
export { availabilityHandlers } from './availability/handlers';
|
||||
export { cmsHandlers, resetMockCmsInstances, getMockCmsInstances } from './cms/handlers';
|
||||
export * from './auth/fixtures';
|
||||
|
||||
@@ -1,19 +1,70 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { renderApp, mockAuthenticated, mockGuest } from '@/test/utils';
|
||||
import { server } from '@/mocks/server';
|
||||
import { API_BASE } from '@/mocks/auth/fixtures';
|
||||
import { resetMockCmsInstances } from '@/mocks/cms/handlers';
|
||||
import { _resetSetupStatusCache } from '@/router';
|
||||
|
||||
beforeEach(() => {
|
||||
_resetSetupStatusCache();
|
||||
resetMockCmsInstances();
|
||||
});
|
||||
|
||||
const CMS_URL = `${API_BASE}/api/v1/CmsInstances`;
|
||||
|
||||
describe('CmsPage', () => {
|
||||
it('renders the CMS page title and placeholder', async () => {
|
||||
it('renders the page title and Add button', async () => {
|
||||
mockAuthenticated();
|
||||
renderApp('/cms');
|
||||
|
||||
expect(await screen.findByTestId('cms-title', {}, { timeout: 5000 })).toBeInTheDocument();
|
||||
expect(screen.getByTestId('cms-placeholder')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('cms-add-button')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders list of CMS instances from seed data', async () => {
|
||||
mockAuthenticated();
|
||||
renderApp('/cms');
|
||||
|
||||
const rows = await screen.findAllByTestId('cms-instance-row', {}, { timeout: 5000 });
|
||||
expect(rows.length).toBe(2);
|
||||
});
|
||||
|
||||
it('renders empty state when no instances exist', async () => {
|
||||
mockAuthenticated();
|
||||
server.use(http.get(CMS_URL, () => HttpResponse.json([])));
|
||||
renderApp('/cms');
|
||||
|
||||
expect(await screen.findByTestId('cms-empty-state', {}, { timeout: 5000 })).toBeInTheDocument();
|
||||
expect(screen.getByTestId('cms-empty-add-button')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens AddCmsInstanceDialog when Add button is clicked', async () => {
|
||||
mockAuthenticated();
|
||||
renderApp('/cms');
|
||||
|
||||
await screen.findByTestId('cms-add-button', {}, { timeout: 5000 });
|
||||
await userEvent.click(screen.getByTestId('cms-add-button'));
|
||||
|
||||
expect(await screen.findByTestId('add-cms-name')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('adds a CMS instance successfully', async () => {
|
||||
mockAuthenticated();
|
||||
renderApp('/cms');
|
||||
|
||||
await screen.findByTestId('cms-add-button', {}, { timeout: 5000 });
|
||||
await userEvent.click(screen.getByTestId('cms-add-button'));
|
||||
|
||||
await userEvent.type(screen.getByTestId('add-cms-name'), 'New CMS');
|
||||
await userEvent.type(screen.getByTestId('add-cms-url'), 'http://new.example.com');
|
||||
await userEvent.type(screen.getByTestId('add-cms-apikey-input'), 'secret-key');
|
||||
await userEvent.click(screen.getByTestId('add-cms-submit'));
|
||||
|
||||
const rows = await screen.findAllByTestId('cms-instance-row', {}, { timeout: 5000 });
|
||||
expect(rows.length).toBe(3);
|
||||
});
|
||||
|
||||
it('redirects unauthenticated users to login', async () => {
|
||||
|
||||
@@ -1,17 +1,72 @@
|
||||
import { useState } from 'react';
|
||||
import { LayoutGrid } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { CmsInstanceList } from '@/components/cms/CmsInstanceList';
|
||||
import { AddCmsInstanceDialog } from '@/components/cms/AddCmsInstanceDialog';
|
||||
import { SetStatusDialog } from '@/components/cms/SetStatusDialog';
|
||||
import { useCmsInstances } from '@/api/useCmsInstances';
|
||||
import type { CmsInstance } from '@/api/types';
|
||||
|
||||
export function CmsPage() {
|
||||
const { t } = useTranslation();
|
||||
const [addDialogOpen, setAddDialogOpen] = useState(false);
|
||||
const [statusTarget, setStatusTarget] = useState<CmsInstance | null>(null);
|
||||
const { data: instances, isPending, isError } = useCmsInstances();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-16 text-center space-y-4">
|
||||
<LayoutGrid className="size-12 text-muted-foreground" />
|
||||
<h1 className="text-2xl font-semibold" data-testid="cms-title">
|
||||
{t('cms.title')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground max-w-sm" data-testid="cms-placeholder">
|
||||
{t('cms.description')}
|
||||
</p>
|
||||
<div className="space-y-4 p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-semibold" data-testid="cms-title">
|
||||
{t('cms.title')}
|
||||
</h1>
|
||||
<Button
|
||||
onClick={() => setAddDialogOpen(true)}
|
||||
data-testid="cms-add-button"
|
||||
>
|
||||
{t('cms.addButton')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isPending && (
|
||||
<p className="text-sm text-muted-foreground">{t('common.loading')}</p>
|
||||
)}
|
||||
|
||||
{isError && (
|
||||
<p className="text-sm text-destructive">{t('errors.generic')}</p>
|
||||
)}
|
||||
|
||||
{!isPending && !isError && instances?.length === 0 && (
|
||||
<div
|
||||
className="flex flex-col items-center justify-center py-16 text-center space-y-4"
|
||||
data-testid="cms-empty-state"
|
||||
>
|
||||
<LayoutGrid className="size-12 text-muted-foreground" />
|
||||
<h2 className="text-xl font-semibold">{t('cms.emptyState.heading')}</h2>
|
||||
<p className="text-muted-foreground max-w-sm">{t('cms.emptyState.description')}</p>
|
||||
<Button onClick={() => setAddDialogOpen(true)} data-testid="cms-empty-add-button">
|
||||
{t('cms.addButton')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isPending && !isError && instances && instances.length > 0 && (
|
||||
<CmsInstanceList
|
||||
instances={instances}
|
||||
onSetStatus={(instance) => setStatusTarget(instance)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<AddCmsInstanceDialog
|
||||
open={addDialogOpen}
|
||||
onOpenChange={setAddDialogOpen}
|
||||
/>
|
||||
|
||||
<SetStatusDialog
|
||||
instance={statusTarget}
|
||||
open={statusTarget !== null}
|
||||
onOpenChange={(open) => { if (!open) setStatusTarget(null); }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user