Aanbod: categorieën beheren in een dialoog en categorie kiezen in het aanbodformulier

Knop 'Categorieën beheren' op de aanbodlijst opent een dialoog om categorieën toe te voegen, te hernoemen en te verwijderen, met Nederlandse meldingen voor een dubbele naam en een categorie die nog in gebruik is. Het formulier krijgt een keuzelijst met 'Geen categorie', de lijst toont de categorie als badge en de querykey ['offerings','list'] vervangt de oude admin-key zodat een hernoeming direct zichtbaar is.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 13:06:09 +01:00
co-authored by Claude Sonnet 5.5
parent 8bda5629ff
commit 3048cf8084
24 changed files with 1000 additions and 28 deletions
@@ -0,0 +1,320 @@
import { useState, type FormEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { Check, Pencil, Trash2, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
import { categoryNameSchema } from '../schemas/offering';
import { useOfferingCategories } from '../services/useOfferingCategories';
import { useCreateOfferingCategory } from '../services/useCreateOfferingCategory';
import { useRenameOfferingCategory } from '../services/useRenameOfferingCategory';
import { useDeleteOfferingCategory } from '../services/useDeleteOfferingCategory';
import type { OfferingCategoryDto } from '../services/types';
interface CategoriesDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
/**
* Manages the categories offerings can be placed in. Lives inside the Offerings management
* (opened from the list page) rather than on a page of its own.
*/
export function CategoriesDialog({ open, onOpenChange }: CategoriesDialogProps) {
const { t } = useTranslation();
const { data: categories, isPending, isError } = useOfferingCategories();
const createCategory = useCreateOfferingCategory();
const renameCategory = useRenameOfferingCategory();
const deleteCategory = useDeleteOfferingCategory();
const [newName, setNewName] = useState('');
const [editingId, setEditingId] = useState<string | null>(null);
const [editName, setEditName] = useState('');
const [deletePendingId, setDeletePendingId] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
function validate(name: string): string | null {
const result = categoryNameSchema.safeParse(name);
if (result.success) return null;
return result.error.issues[0].code === 'too_big'
? t('offerings.categories.errors.nameTooLong')
: t('offerings.categories.errors.nameRequired');
}
// Server rejections are translated here instead of showing the API's English titles.
function describeError(err: unknown, context: { name?: string; usedBy?: number }): string {
if (err instanceof NetworkError) return t('errors.network');
if (err instanceof ProblemDetailsError && err.status === 409) {
return context.usedBy !== undefined
? t('offerings.categories.errors.inUse', { count: context.usedBy })
: t('offerings.categories.errors.duplicate', { name: context.name ?? '' });
}
return t('errors.generic');
}
async function handleAdd(event: FormEvent) {
event.preventDefault();
const trimmed = newName.trim();
const problem = validate(trimmed);
if (problem) {
setError(problem);
return;
}
setError(null);
try {
await createCategory.mutateAsync(trimmed);
setNewName('');
} catch (err) {
setError(describeError(err, { name: trimmed }));
}
}
function startEdit(category: OfferingCategoryDto) {
setError(null);
setDeletePendingId(null);
setEditingId(category.id);
setEditName(category.name);
}
function cancelEdit() {
setEditingId(null);
setError(null);
}
async function confirmEdit(category: OfferingCategoryDto) {
const trimmed = editName.trim();
const problem = validate(trimmed);
if (problem) {
setError(problem);
return;
}
if (trimmed === category.name) {
cancelEdit();
return;
}
setError(null);
try {
await renameCategory.mutateAsync({ id: category.id, name: trimmed });
setEditingId(null);
} catch (err) {
setError(describeError(err, { name: trimmed }));
}
}
function startDelete(category: OfferingCategoryDto) {
setError(null);
setEditingId(null);
setDeletePendingId(category.id);
}
async function confirmDelete(category: OfferingCategoryDto) {
setError(null);
try {
await deleteCategory.mutateAsync(category.id);
setDeletePendingId(null);
} catch (err) {
setDeletePendingId(null);
setError(describeError(err, { usedBy: category.offeringCount }));
}
}
function handleOpenChange(next: boolean) {
if (!next) {
setEditingId(null);
setDeletePendingId(null);
setError(null);
setNewName('');
}
onOpenChange(next);
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent
className="sm:max-w-lg"
data-testid="categories-dialog"
onEscapeKeyDown={(event) => {
// Escape while renaming only cancels the rename, it does not close the dialog.
if (editingId !== null) {
event.preventDefault();
cancelEdit();
}
}}
>
<DialogHeader>
<DialogTitle>{t('offerings.categories.title')}</DialogTitle>
</DialogHeader>
{error !== null && (
<p
role="alert"
className="text-sm text-destructive"
data-testid="categories-error"
>
{error}
</p>
)}
{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 && categories.length === 0 && (
<p className="text-sm text-muted-foreground" data-testid="categories-empty">
{t('offerings.categories.emptyState')}
</p>
)}
{!isPending && !isError && categories.length > 0 && (
<ul className="divide-y rounded-md border" data-testid="categories-list">
{categories.map((category) => (
<li
key={category.id}
className="flex items-center justify-between gap-2 px-3 py-2"
data-testid={`category-row-${category.id}`}
>
{editingId === category.id ? (
<>
<Input
autoFocus
className="h-8"
value={editName}
aria-label={t('offerings.categories.editButton')}
data-testid={`category-edit-input-${category.id}`}
onChange={(e) => setEditName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
void confirmEdit(category);
} else if (e.key === 'Escape') {
e.stopPropagation();
cancelEdit();
}
}}
/>
<div className="flex gap-1">
<Button
type="button"
variant="ghost"
size="icon"
aria-label={t(
'offerings.categories.confirmEditButton',
)}
data-testid={`category-edit-confirm-${category.id}`}
onClick={() => void confirmEdit(category)}
>
<Check className="size-4" />
</Button>
<Button
type="button"
variant="ghost"
size="icon"
aria-label={t('offerings.categories.cancelButton')}
data-testid={`category-edit-cancel-${category.id}`}
onClick={cancelEdit}
>
<X className="size-4" />
</Button>
</div>
</>
) : (
<>
<div className="min-w-0">
<span
className="font-medium"
data-testid={`category-name-${category.id}`}
>
{category.name}
</span>
<span
className="ml-2 text-sm text-muted-foreground"
data-testid={`category-count-${category.id}`}
>
{t('offerings.categories.offeringCount', {
count: category.offeringCount,
})}
</span>
</div>
{deletePendingId === category.id ? (
<div className="flex items-center gap-2 text-sm">
<span>
{t('offerings.categories.deleteConfirm')}
</span>
<Button
type="button"
variant="destructive"
size="sm"
disabled={deleteCategory.isPending}
data-testid={`category-delete-confirm-${category.id}`}
onClick={() => void confirmDelete(category)}
>
{t('offerings.categories.deleteConfirmButton')}
</Button>
<Button
type="button"
variant="outline"
size="sm"
data-testid={`category-delete-cancel-${category.id}`}
onClick={() => setDeletePendingId(null)}
>
{t('offerings.categories.cancelButton')}
</Button>
</div>
) : (
<div className="flex gap-1">
<Button
type="button"
variant="ghost"
size="icon"
aria-label={t(
'offerings.categories.editButton',
)}
data-testid={`category-edit-${category.id}`}
onClick={() => startEdit(category)}
>
<Pencil className="size-4" />
</Button>
<Button
type="button"
variant="ghost"
size="icon"
aria-label={t(
'offerings.categories.deleteButton',
)}
data-testid={`category-delete-${category.id}`}
onClick={() => startDelete(category)}
>
<Trash2 className="size-4" />
</Button>
</div>
)}
</>
)}
</li>
))}
</ul>
)}
<form onSubmit={handleAdd} className="flex gap-2" noValidate>
<Input
value={newName}
placeholder={t('offerings.categories.newLabel')}
aria-label={t('offerings.categories.newLabel')}
data-testid="category-new-input"
onChange={(e) => setNewName(e.target.value)}
/>
<Button
type="submit"
disabled={createCategory.isPending}
data-testid="category-add-button"
>
{t('offerings.categories.addButton')}
</Button>
</form>
</DialogContent>
</Dialog>
);
}
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useEffect, useState } from 'react';
import { useForm, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useTranslation } from 'react-i18next';
@@ -7,6 +7,8 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { FieldError } from '@/components/ui/FieldError';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useOfferingCategories } from '../services/useOfferingCategories';
import { slugifyPreview } from '@/lib/slugify';
import { offeringFormSchema, type OfferingFormData } from '../schemas/offering';
import type { OfferingDto } from '../services/types';
@@ -39,9 +41,32 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering
ctaLabel: '',
featured: false,
slug: '',
categoryId: null,
},
});
// Radix Select does not allow an empty value, so "no category" is the sentinel 'none' here
// and is mapped back to null for the form value.
const NO_CATEGORY = 'none';
const { data: categories, isFetching: isFetchingCategories } = useOfferingCategories();
const categoryId = useWatch({ control, name: 'categoryId' });
const selectedCategory =
categoryId != null && categories?.some((c) => c.id === categoryId) ? categoryId : NO_CATEGORY;
// A category that no longer exists (deleted meanwhile) falls back to "no category" so the
// form never submits an id the API would reject. Only judged on fresh data: a cached list
// that is being refetched may still be missing a category that does exist.
useEffect(() => {
if (
categories !== undefined &&
!isFetchingCategories &&
categoryId != null &&
!categories.some((c) => c.id === categoryId)
) {
setValue('categoryId', null);
}
}, [categories, isFetchingCategories, categoryId, setValue]);
// useFieldArray requires object-shaped array items — features is a plain string[],
// so add/remove are handled directly via setValue instead.
const features = useWatch({ control, name: 'features' });
@@ -177,6 +202,37 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering
</div>
</div>
<div className="space-y-2">
<Label htmlFor="offering-category">{t('offerings.form.categoryLabel')}</Label>
<Select
value={selectedCategory}
onValueChange={(value) => {
// Radix reports an empty value while its options are still loading (the
// chosen category is not in the list yet); that is not a user choice.
if (value === '') return;
setValue('categoryId', value === NO_CATEGORY ? null : value, { shouldDirty: true });
}}
>
<SelectTrigger id="offering-category" data-testid="offering-category">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={NO_CATEGORY} data-testid="offering-category-none">
{t('offerings.form.noCategory')}
</SelectItem>
{categories?.map((category) => (
<SelectItem
key={category.id}
value={category.id}
data-testid={`offering-category-option-${category.id}`}
>
{category.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>{t('offerings.form.featuresLabel')}</Label>
{features.map((_, index) => (
@@ -3,6 +3,7 @@ import { CSS } from '@dnd-kit/utilities';
import { useTranslation } from 'react-i18next';
import { GripVertical, Star, ChevronUp, ChevronDown, Pencil, Trash2 } from 'lucide-react';
import { Link } from '@tanstack/react-router';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { TableCell, TableRow } from '@/components/ui/table';
import { useUpdateOffering } from '../services/useUpdateOffering';
@@ -45,7 +46,14 @@ export function OfferingRow({ offering, isFirst, isLast, onDeleteRequested }: Of
<GripVertical className="size-4" />
</button>
</TableCell>
<TableCell>{offering.title}</TableCell>
<TableCell>
{offering.title}
{offering.category && (
<Badge variant="secondary" className="ml-2" data-testid={`offering-row-${offering.id}-category`}>
{offering.category}
</Badge>
)}
</TableCell>
<TableCell>{offering.price}</TableCell>
<TableCell>
<Button
@@ -62,6 +70,8 @@ export function OfferingRow({ offering, isFirst, isLast, onDeleteRequested }: Of
priceNote: offering.priceNote,
features: offering.features,
ctaLabel: offering.ctaLabel,
// PUT replaces the whole offering: leaving the category out would clear it.
categoryId: offering.categoryId ?? null,
featured: !offering.featured,
})
}
+106 -16
View File
@@ -1,5 +1,10 @@
import { http, HttpResponse } from 'msw';
import type { OfferingDto, CreateOfferingRequest, UpdateOfferingRequest } from '@/features/offerings/services/types';
import type {
OfferingDto,
OfferingCategoryDto,
CreateOfferingRequest,
UpdateOfferingRequest,
} from '@/features/offerings/services/types';
import { API_BASE } from '@/features/auth/mocks/fixtures';
function slugify(value: string): string {
@@ -40,14 +45,41 @@ const seed: OfferingDto[] = [
let mockOfferings: OfferingDto[] = [...seed];
/** Categories (id, name, sortOrder). Nothing is seeded, like the real system; tests add their own. */
type MockCategory = Omit<OfferingCategoryDto, 'offeringCount'>;
let mockCategories: MockCategory[] = [];
export const resetMockOfferings = () => {
mockOfferings = [...seed];
mockCategories = [];
};
export const getMockOfferings = () => mockOfferings;
export const setMockCategories = (categories: MockCategory[]) => {
mockCategories = [...categories];
};
/** Assigns categories to mock offerings (id -> category id) without going through the API. */
export const assignMockCategories = (assignments: Record<string, string>) => {
mockOfferings = mockOfferings.map((o) =>
assignments[o.id] !== undefined ? { ...o, categoryId: assignments[o.id] } : o,
);
};
const withCategoryName = (o: OfferingDto): OfferingDto => ({
...o,
categoryId: o.categoryId ?? null,
category: mockCategories.find((c) => c.id === o.categoryId)?.name ?? null,
});
const countFor = (categoryId: string) => mockOfferings.filter((o) => o.categoryId === categoryId).length;
const nameTaken = (name: string, exceptId?: string) =>
mockCategories.some((c) => c.id !== exceptId && c.name.toLowerCase() === name.toLowerCase());
export const offeringsHandlers = [
http.get(`${API_BASE}/api/v1/offerings`, () => HttpResponse.json(mockOfferings)),
http.get(`${API_BASE}/api/v1/offerings`, () => HttpResponse.json(mockOfferings.map(withCategoryName))),
http.post(`${API_BASE}/api/v1/offerings`, async ({ request }) => {
const body = (await request.json()) as CreateOfferingRequest;
@@ -58,6 +90,12 @@ export const offeringsHandlers = [
{ status: 409 },
);
}
if (body.categoryId && !mockCategories.some((c) => c.id === body.categoryId)) {
return HttpResponse.json(
{ status: 400, title: 'Invalid category', errors: { categoryId: ['invalid'] } },
{ status: 400 },
);
}
const newOffering: OfferingDto = {
id: crypto.randomUUID(),
@@ -66,7 +104,63 @@ export const offeringsHandlers = [
displayOrder: mockOfferings.length,
};
mockOfferings = [...mockOfferings, newOffering];
return HttpResponse.json(newOffering, { status: 201 });
return HttpResponse.json(withCategoryName(newOffering), { status: 201 });
}),
// Registered before the `:id` routes: `order` would otherwise be matched as an id.
http.put(`${API_BASE}/api/v1/offerings/order`, async ({ request }) => {
const body = (await request.json()) as { orderedIds: string[] };
mockOfferings = body.orderedIds
.map((id, index) => {
const offering = mockOfferings.find((o) => o.id === id);
return offering ? { ...offering, displayOrder: index } : null;
})
.filter((o): o is OfferingDto => o !== null);
return new HttpResponse(null, { status: 204 });
}),
http.get(`${API_BASE}/api/v1/offerings/categories`, () =>
HttpResponse.json(
[...mockCategories]
.sort((a, b) => a.sortOrder - b.sortOrder || a.name.localeCompare(b.name))
.map((c) => ({ ...c, offeringCount: countFor(c.id) })),
),
),
http.post(`${API_BASE}/api/v1/offerings/categories`, async ({ request }) => {
const { name } = (await request.json()) as { name: string };
if (nameTaken(name)) {
return HttpResponse.json({ status: 409, title: `A category named '${name}' already exists.` }, { status: 409 });
}
const created: MockCategory = { id: crypto.randomUUID(), name, sortOrder: mockCategories.length };
mockCategories = [...mockCategories, created];
return HttpResponse.json({ ...created, offeringCount: 0 }, { status: 201 });
}),
http.put(`${API_BASE}/api/v1/offerings/categories/:id`, async ({ params, request }) => {
const { id } = params as { id: string };
const { name } = (await request.json()) as { name: string };
const existing = mockCategories.find((c) => c.id === id);
if (!existing) return new HttpResponse(null, { status: 404 });
if (nameTaken(name, id)) {
return HttpResponse.json({ status: 409, title: `A category named '${name}' already exists.` }, { status: 409 });
}
const renamed = { ...existing, name };
mockCategories = mockCategories.map((c) => (c.id === id ? renamed : c));
return HttpResponse.json({ ...renamed, offeringCount: countFor(id) });
}),
http.delete(`${API_BASE}/api/v1/offerings/categories/:id`, ({ params }) => {
const { id } = params as { id: string };
if (!mockCategories.some((c) => c.id === id)) return new HttpResponse(null, { status: 404 });
if (countFor(id) > 0) {
return HttpResponse.json(
{ status: 409, title: 'The category is still used by offering(s). Move them first.' },
{ status: 409 },
);
}
mockCategories = mockCategories.filter((c) => c.id !== id);
return new HttpResponse(null, { status: 204 });
}),
http.put(`${API_BASE}/api/v1/offerings/:id`, async ({ params, request }) => {
@@ -87,10 +181,17 @@ export const offeringsHandlers = [
{ status: 409 },
);
}
if (body.categoryId && !mockCategories.some((c) => c.id === body.categoryId)) {
return HttpResponse.json(
{ status: 400, title: 'Invalid category', errors: { categoryId: ['invalid'] } },
{ status: 400 },
);
}
const updated: OfferingDto = { ...existing, ...body, slug };
// PUT replaces the offering: an absent categoryId clears the category, as in the real API.
const updated: OfferingDto = { ...existing, ...body, slug, categoryId: body.categoryId ?? null };
mockOfferings = mockOfferings.map((o) => (o.id === id ? updated : o));
return HttpResponse.json(updated);
return HttpResponse.json(withCategoryName(updated));
}),
http.delete(`${API_BASE}/api/v1/offerings/:id`, ({ params }) => {
@@ -98,15 +199,4 @@ export const offeringsHandlers = [
mockOfferings = mockOfferings.filter((o) => o.id !== id);
return new HttpResponse(null, { status: 204 });
}),
http.put(`${API_BASE}/api/v1/offerings/order`, async ({ request }) => {
const body = (await request.json()) as { orderedIds: string[] };
mockOfferings = body.orderedIds
.map((id, index) => {
const offering = mockOfferings.find((o) => o.id === id);
return offering ? { ...offering, displayOrder: index } : null;
})
.filter((o): o is OfferingDto => o !== null);
return new HttpResponse(null, { status: 204 });
}),
];
@@ -0,0 +1,304 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderApp, mockAuthenticated } from '@/test/utils';
import { changeLanguage } from '@/i18n/config';
import {
assignMockCategories,
getMockOfferings,
resetMockOfferings,
setMockCategories,
} from '@/features/offerings/mocks/handlers';
import { categoryNameSchema } from '@/features/offerings/schemas/offering';
import { _resetSetupStatusCache } from '@/router';
const STARTER = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
const PRO = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';
const WEBSITES = { id: 'c1', name: 'Websites', sortOrder: 0 };
const ONDERHOUD = { id: 'c2', name: 'Onderhoud', sortOrder: 1 };
const LONG = { timeout: 10000 };
beforeEach(async () => {
_resetSetupStatusCache();
resetMockOfferings();
await changeLanguage('nl');
});
afterEach(async () => {
await changeLanguage('en');
});
async function openDialog() {
await userEvent.click(await screen.findByTestId('offerings-categories-button', {}, LONG));
return screen.findByTestId('categories-dialog');
}
describe('categories dialog', () => {
it('opens from the list page without leaving it and shows the empty state', async () => {
mockAuthenticated();
renderApp('/offerings');
await openDialog();
expect(screen.getByTestId('categories-empty')).toHaveTextContent(
'Nog geen categorieën. Voeg de eerste toe.',
);
expect(screen.getByTestId('offerings-title')).toBeInTheDocument();
});
it('lists the categories with the number of offerings in each', async () => {
setMockCategories([WEBSITES, ONDERHOUD]);
assignMockCategories({ [STARTER]: 'c1', [PRO]: 'c1' });
mockAuthenticated();
renderApp('/offerings');
await openDialog();
expect(await screen.findByTestId('category-name-c1')).toHaveTextContent('Websites');
expect(screen.getByTestId('category-count-c1')).toHaveTextContent('2 aanbiedingen');
expect(screen.getByTestId('category-count-c2')).toHaveTextContent('0 aanbiedingen');
});
it('adds a category', async () => {
mockAuthenticated();
renderApp('/offerings');
await openDialog();
await userEvent.type(await screen.findByTestId('category-new-input'), 'Websites');
await userEvent.click(screen.getByTestId('category-add-button'));
expect(await screen.findByText('Websites')).toBeInTheDocument();
expect(screen.getByTestId('category-new-input')).toHaveValue('');
expect(screen.queryByTestId('categories-empty')).not.toBeInTheDocument();
});
it('rejects a blank name before calling the API', async () => {
mockAuthenticated();
renderApp('/offerings');
await openDialog();
await userEvent.type(await screen.findByTestId('category-new-input'), ' ');
await userEvent.click(screen.getByTestId('category-add-button'));
expect(await screen.findByTestId('categories-error')).toHaveTextContent('Vul een naam in.');
});
it('shows a Dutch message when the name is already taken', async () => {
setMockCategories([WEBSITES]);
mockAuthenticated();
renderApp('/offerings');
await openDialog();
await userEvent.type(await screen.findByTestId('category-new-input'), 'websites');
await userEvent.click(screen.getByTestId('category-add-button'));
expect(await screen.findByTestId('categories-error')).toHaveTextContent(
"Er bestaat al een categorie met de naam 'websites'.",
);
});
it('renames a category with Enter', async () => {
setMockCategories([WEBSITES]);
mockAuthenticated();
renderApp('/offerings');
await openDialog();
await userEvent.click(await screen.findByTestId('category-edit-c1'));
const input = screen.getByTestId('category-edit-input-c1');
await userEvent.clear(input);
await userEvent.type(input, 'Webdesign{Enter}');
expect(await screen.findByTestId('category-name-c1')).toHaveTextContent('Webdesign');
});
it('cancels a rename with Escape without closing the dialog', async () => {
setMockCategories([WEBSITES]);
mockAuthenticated();
renderApp('/offerings');
await openDialog();
await userEvent.click(await screen.findByTestId('category-edit-c1'));
await userEvent.type(screen.getByTestId('category-edit-input-c1'), 'xyz{Escape}');
expect(await screen.findByTestId('category-name-c1')).toHaveTextContent('Websites');
expect(screen.getByTestId('categories-dialog')).toBeInTheDocument();
});
it('shows the duplicate-name message when renaming to an existing name', async () => {
setMockCategories([WEBSITES, ONDERHOUD]);
mockAuthenticated();
renderApp('/offerings');
await openDialog();
await userEvent.click(await screen.findByTestId('category-edit-c2'));
const input = screen.getByTestId('category-edit-input-c2');
await userEvent.clear(input);
await userEvent.type(input, 'websites{Enter}');
expect(await screen.findByTestId('categories-error')).toHaveTextContent(
"Er bestaat al een categorie met de naam 'websites'.",
);
expect(screen.getByTestId('category-edit-input-c2')).toBeInTheDocument();
});
it('deletes an unused category after confirmation', async () => {
setMockCategories([WEBSITES, ONDERHOUD]);
mockAuthenticated();
renderApp('/offerings');
await openDialog();
await userEvent.click(await screen.findByTestId('category-delete-c2'));
await userEvent.click(screen.getByTestId('category-delete-confirm-c2'));
await waitFor(() =>
expect(screen.queryByTestId('category-row-c2')).not.toBeInTheDocument(),
);
expect(screen.getByTestId('category-row-c1')).toBeInTheDocument();
});
it('explains in Dutch why a category in use cannot be deleted and keeps it', async () => {
setMockCategories([WEBSITES]);
assignMockCategories({ [STARTER]: 'c1' });
mockAuthenticated();
renderApp('/offerings');
await openDialog();
await userEvent.click(await screen.findByTestId('category-delete-c1'));
await userEvent.click(screen.getByTestId('category-delete-confirm-c1'));
expect(await screen.findByTestId('categories-error')).toHaveTextContent(
'Deze categorie wordt nog gebruikt door 1 aanbieding(en). Verplaats die eerst naar een andere categorie.',
);
expect(screen.getByTestId('category-row-c1')).toBeInTheDocument();
});
});
describe('category on the offerings list', () => {
it('shows the category as a badge and a rename appears in the list without a reload', async () => {
setMockCategories([WEBSITES]);
assignMockCategories({ [STARTER]: 'c1' });
mockAuthenticated();
renderApp('/offerings');
expect(
await screen.findByTestId(`offering-row-${STARTER}-category`, {}, LONG),
).toHaveTextContent('Websites');
expect(screen.queryByTestId(`offering-row-${PRO}-category`)).not.toBeInTheDocument();
await openDialog();
await userEvent.click(await screen.findByTestId('category-edit-c1'));
const input = screen.getByTestId('category-edit-input-c1');
await userEvent.clear(input);
await userEvent.type(input, 'Webdesign{Enter}');
await waitFor(() =>
expect(screen.getByTestId(`offering-row-${STARTER}-category`)).toHaveTextContent(
'Webdesign',
),
);
});
it('keeps the category when an offering is marked as featured from the list', async () => {
setMockCategories([WEBSITES]);
assignMockCategories({ [STARTER]: 'c1' });
mockAuthenticated();
renderApp('/offerings');
await userEvent.click(
await screen.findByTestId(`offering-row-${STARTER}-featured-toggle`, {}, LONG),
);
await waitFor(() =>
expect(getMockOfferings().find((o) => o.id === STARTER)?.featured).toBe(true),
);
expect(getMockOfferings().find((o) => o.id === STARTER)?.categoryId).toBe('c1');
});
});
describe('category select in the offering form', () => {
async function fillRequiredFields() {
await userEvent.type(await screen.findByTestId('offering-title', {}, LONG), 'Nieuw');
await userEvent.type(screen.getByTestId('offering-description'), 'Omschrijving');
await userEvent.type(screen.getByTestId('offering-price'), '€ 100');
await userEvent.type(screen.getByTestId('offering-price-note'), 'eenmalig');
await userEvent.type(screen.getByTestId('offering-feature-0'), 'Kenmerk');
await userEvent.type(screen.getByTestId('offering-cta-label'), 'Start');
}
it('offers "Geen categorie" first and then the categories', async () => {
setMockCategories([WEBSITES, ONDERHOUD]);
mockAuthenticated();
renderApp('/offerings/new');
const trigger = await screen.findByTestId('offering-category', {}, LONG);
expect(trigger).toHaveTextContent('Geen categorie');
await userEvent.click(trigger);
const listbox = await screen.findByRole('listbox');
const options = within(listbox)
.getAllByRole('option')
.map((o) => o.textContent);
expect(options).toEqual(['Geen categorie', 'Websites', 'Onderhoud']);
});
it('sends the chosen categoryId when creating', async () => {
setMockCategories([WEBSITES, ONDERHOUD]);
mockAuthenticated();
renderApp('/offerings/new');
await fillRequiredFields();
await userEvent.click(screen.getByTestId('offering-category'));
await userEvent.click(await screen.findByTestId('offering-category-option-c2'));
await userEvent.click(screen.getByTestId('offering-form-submit'));
await waitFor(() => expect(getMockOfferings().some((o) => o.title === 'Nieuw')).toBe(true));
expect(getMockOfferings().find((o) => o.title === 'Nieuw')?.categoryId).toBe('c2');
});
it('sends null when no category is chosen', async () => {
setMockCategories([WEBSITES]);
mockAuthenticated();
renderApp('/offerings/new');
await fillRequiredFields();
await userEvent.click(screen.getByTestId('offering-form-submit'));
await waitFor(() => expect(getMockOfferings().some((o) => o.title === 'Nieuw')).toBe(true));
expect(getMockOfferings().find((o) => o.title === 'Nieuw')?.categoryId ?? null).toBeNull();
});
it('preselects the current category when editing', async () => {
setMockCategories([WEBSITES, ONDERHOUD]);
assignMockCategories({ [STARTER]: 'c2' });
mockAuthenticated();
renderApp(`/offerings/${STARTER}/edit`);
const trigger = await screen.findByTestId('offering-category', {}, LONG);
await waitFor(() => expect(trigger).toHaveTextContent('Onderhoud'));
});
it('falls back to "Geen categorie" for a category that no longer exists and saves it as none', async () => {
setMockCategories([WEBSITES]);
assignMockCategories({ [STARTER]: 'verdwenen' });
mockAuthenticated();
renderApp(`/offerings/${STARTER}/edit`);
const trigger = await screen.findByTestId('offering-category', {}, LONG);
await waitFor(() => expect(trigger).toHaveTextContent('Geen categorie'));
await userEvent.click(screen.getByTestId('offering-form-submit'));
await waitFor(() =>
expect(getMockOfferings().find((o) => o.id === STARTER)?.categoryId).toBeNull(),
);
});
});
describe('categoryNameSchema', () => {
it('accepts 1 to 100 characters and rejects empty or longer names', () => {
expect(categoryNameSchema.safeParse('a').success).toBe(true);
expect(categoryNameSchema.safeParse('a'.repeat(100)).success).toBe(true);
expect(categoryNameSchema.safeParse('').success).toBe(false);
expect(categoryNameSchema.safeParse('a'.repeat(101)).success).toBe(false);
});
});
@@ -5,6 +5,7 @@ import { Package } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { OfferingsList } from '../components/OfferingsList';
import { DeleteOfferingDialog } from '../components/DeleteOfferingDialog';
import { CategoriesDialog } from '../components/CategoriesDialog';
import { useOfferings } from '../services/useOfferings';
import { useDeleteOffering } from '../services/useDeleteOffering';
import type { OfferingDto } from '../services/types';
@@ -12,6 +13,7 @@ import type { OfferingDto } from '../services/types';
export function OfferingsListPage() {
const { t } = useTranslation();
const [offeringPendingDelete, setOfferingPendingDelete] = useState<OfferingDto | null>(null);
const [categoriesOpen, setCategoriesOpen] = useState(false);
const { data: offerings, isPending, isError } = useOfferings();
const deleteOffering = useDeleteOffering({
onSuccess: () => setOfferingPendingDelete(null),
@@ -23,9 +25,19 @@ export function OfferingsListPage() {
<h1 className="text-2xl font-semibold" data-testid="offerings-title">
{t('offerings.title')}
</h1>
<Button asChild data-testid="offerings-add-button">
<Link to="/offerings/new">{t('offerings.addButton')}</Link>
</Button>
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
data-testid="offerings-categories-button"
onClick={() => setCategoriesOpen(true)}
>
{t('offerings.categories.manageButton')}
</Button>
<Button asChild data-testid="offerings-add-button">
<Link to="/offerings/new">{t('offerings.addButton')}</Link>
</Button>
</div>
</div>
{isPending && <p className="text-sm text-muted-foreground">{t('common.loading')}</p>}
@@ -50,6 +62,8 @@ export function OfferingsListPage() {
<OfferingsList offerings={offerings} onDeleteRequested={setOfferingPendingDelete} />
)}
<CategoriesDialog open={categoriesOpen} onOpenChange={setCategoriesOpen} />
<DeleteOfferingDialog
offering={offeringPendingDelete}
isDeleting={deleteOffering.isPending}
@@ -23,6 +23,11 @@ export const offeringFormSchema = z.object({
.regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, 'Slug may only contain lowercase letters, digits and hyphens')
.optional()
.or(z.literal('')),
/** Id of the chosen category; null/absent = no category. */
categoryId: z.string().nullable().optional(),
});
export type OfferingFormData = z.infer<typeof offeringFormSchema>;
/** A category name as typed by an admin (already trimmed by the caller). */
export const categoryNameSchema = z.string().min(1).max(100);
@@ -9,6 +9,10 @@ export interface OfferingDto {
ctaLabel: string;
featured: boolean;
displayOrder: number;
/** Id of the category, or null/absent when the offering has none. */
categoryId?: string | null;
/** Name of the category (renames show up here automatically). */
category?: string | null;
}
export interface CreateOfferingRequest {
@@ -21,8 +25,17 @@ export interface CreateOfferingRequest {
featured: boolean;
/** Omit to auto-generate from title; set to explicitly override. */
slug?: string;
/** Category id; null clears the category. */
categoryId?: string | null;
}
export type UpdateOfferingRequest = CreateOfferingRequest;
export interface OfferingCategoryDto {
id: string;
name: string;
sortOrder: number;
offeringCount: number;
}
export type MoveDirection = 'up' | 'down';
@@ -9,7 +9,7 @@ export function useCreateOffering(
return useMutation<OfferingDto, Error, CreateOfferingRequest>({
mutationFn: (data) => api.post<OfferingDto>('/api/v1/offerings', data),
onSuccess: (data, variables, ...rest) => {
queryClient.invalidateQueries({ queryKey: ['offerings', 'admin'] });
queryClient.invalidateQueries({ queryKey: ['offerings', 'list'] });
options?.onSuccess?.(data, variables, ...rest);
},
onError: options?.onError,
@@ -0,0 +1,15 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api-client';
import { OFFERING_CATEGORIES_KEY } from './useOfferingCategories';
import type { OfferingCategoryDto } from './types';
export function useCreateOfferingCategory() {
const queryClient = useQueryClient();
return useMutation<OfferingCategoryDto, Error, string>({
mutationFn: (name) =>
api.post<OfferingCategoryDto>('/api/v1/offerings/categories', { name }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: OFFERING_CATEGORIES_KEY });
},
});
}
@@ -8,7 +8,7 @@ export function useDeleteOffering(
return useMutation<void, Error, string>({
mutationFn: (id) => api.delete<void>(`/api/v1/offerings/${id}`),
onSuccess: (data, variables, ...rest) => {
queryClient.invalidateQueries({ queryKey: ['offerings', 'admin'] });
queryClient.invalidateQueries({ queryKey: ['offerings', 'list'] });
options?.onSuccess?.(data, variables, ...rest);
},
onError: options?.onError,
@@ -0,0 +1,14 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api-client';
import { OFFERING_CATEGORIES_KEY } from './useOfferingCategories';
export function useDeleteOfferingCategory() {
const queryClient = useQueryClient();
return useMutation<void, Error, string>({
mutationFn: (id) => api.delete<void>(`/api/v1/offerings/categories/${id}`),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: OFFERING_CATEGORIES_KEY });
queryClient.invalidateQueries({ queryKey: ['offerings', 'list'] });
},
});
}
@@ -2,7 +2,7 @@ import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/
import { api } from '@/lib/api-client';
import type { MoveDirection, OfferingDto } from './types';
const OFFERINGS_KEY = ['offerings', 'admin'];
const OFFERINGS_KEY = ['offerings', 'list'];
/**
* Moves one offering a step up or down. The API has no move endpoint (the collection is reordered
@@ -0,0 +1,12 @@
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api-client';
import type { OfferingCategoryDto } from './types';
export const OFFERING_CATEGORIES_KEY = ['offerings', 'categories'];
export function useOfferingCategories() {
return useQuery<OfferingCategoryDto[], Error>({
queryKey: OFFERING_CATEGORIES_KEY,
queryFn: () => api.get<OfferingCategoryDto[]>('/api/v1/offerings/categories'),
});
}
@@ -4,7 +4,7 @@ import type { OfferingDto } from './types';
export function useOfferings() {
return useQuery<OfferingDto[], Error>({
queryKey: ['offerings', 'admin'],
queryKey: ['offerings', 'list'],
queryFn: () => api.get<OfferingDto[]>('/api/v1/offerings'),
});
}
@@ -0,0 +1,19 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api-client';
import { OFFERING_CATEGORIES_KEY } from './useOfferingCategories';
import type { OfferingCategoryDto } from './types';
type RenameVariables = { id: string; name: string };
export function useRenameOfferingCategory() {
const queryClient = useQueryClient();
return useMutation<OfferingCategoryDto, Error, RenameVariables>({
mutationFn: ({ id, name }) =>
api.put<OfferingCategoryDto>(`/api/v1/offerings/categories/${id}`, { name }),
onSuccess: () => {
// The category name is part of every offering that uses it, so refresh both lists.
queryClient.invalidateQueries({ queryKey: OFFERING_CATEGORIES_KEY });
queryClient.invalidateQueries({ queryKey: ['offerings', 'list'] });
},
});
}
@@ -8,7 +8,7 @@ export function useReorderOfferings(
return useMutation<void, Error, string[]>({
mutationFn: (orderedIds) => api.put<void>('/api/v1/offerings/order', { orderedIds }),
onSuccess: (data, variables, ...rest) => {
queryClient.invalidateQueries({ queryKey: ['offerings', 'admin'] });
queryClient.invalidateQueries({ queryKey: ['offerings', 'list'] });
options?.onSuccess?.(data, variables, ...rest);
},
onError: options?.onError,
@@ -11,7 +11,7 @@ export function useUpdateOffering(
return useMutation<OfferingDto, Error, UpdateVariables>({
mutationFn: ({ id, ...body }) => api.put<OfferingDto>(`/api/v1/offerings/${id}`, body),
onSuccess: (data, variables, ...rest) => {
queryClient.invalidateQueries({ queryKey: ['offerings', 'admin'] });
queryClient.invalidateQueries({ queryKey: ['offerings', 'list'] });
options?.onSuccess?.(data, variables, ...rest);
},
onError: options?.onError,