Contactformulier-module, banners, thema's, taalbestanden en CI-herstructurering #15
@@ -5,7 +5,7 @@
|
||||
- **Feature Slug**: contact-forms-module
|
||||
- **Project Type**: Brownfield
|
||||
- **Start Date**: 2026-11-09
|
||||
- **Current Stage**: CONSTRUCTION - CMS-U1 built and committed (awaiting review); next CMS-U1b
|
||||
- **Current Stage**: CONSTRUCTION - CMS-U1b built and committed (awaiting review); next CMS-U2
|
||||
- **Branch**: feature/contact-forms-module (worktree ..SlpModularCms-contact-forms, from master d9cc539; main checkout stays on feature/identity-email-notifications — never switch it)
|
||||
|
||||
## Workspace State
|
||||
|
||||
@@ -71,3 +71,15 @@
|
||||
**Context**: awaiting approval.
|
||||
|
||||
---
|
||||
|
||||
## CMS-U1b plan
|
||||
|
||||
**Timestamp**: 2026-11-09
|
||||
|
||||
**User Input**: "CMS-U1 v2 geaccepteerd ... stash mag verwijderd ... stuur het plan voor CMS-U1b" (via Redesign - SLS)
|
||||
|
||||
**AI Response**: stash dropped (e5e3652); U1b plan written; approval requested.
|
||||
|
||||
**Context**: Code Generation Part 1.
|
||||
|
||||
---
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
# CMS-U1b offerings-categories-ui: code summary
|
||||
|
||||
## What changed (frontend/src/features/offerings + nl/en translations only)
|
||||
- Offerings list page: button "Categorieën beheren" opens CategoriesDialog (no new route). The dialog lists categories with their offering count, adds, renames (inline; Enter confirms, Escape cancels the rename and keeps the dialog open) and deletes (inline confirmation). Errors are shown in Dutch from i18n, not from the API's English titles: duplicate name (409), category in use (409, count from the list), blank/too long name (client side), network, generic.
|
||||
- OfferingForm: "Categorie" select with "Geen categorie" first. Create sends categoryId or null; edit preselects; a category that no longer exists falls back to none (only judged on fresh data).
|
||||
- OfferingRow: category badge; the featured toggle now sends categoryId too (PUT replaces the whole offering, so omitting it would have cleared the category).
|
||||
- Query keys: ['offerings','admin'] renamed to ['offerings','list'] (there is no admin endpoint anymore); category mutations invalidate ['offerings','categories'] and, for rename/delete, ['offerings','list'], so a rename shows up in the list and form without a reload (tested).
|
||||
- Mocks follow the backend (409 duplicate/in use, 404, counts, 400 invalid categoryId); no seed. The mock `PUT /offerings/order` handler is registered before `/:id` (it was shadowed by `/:id` before).
|
||||
|
||||
## Notes
|
||||
- Radix Select reports an empty value while its options load; the form ignores that (otherwise it wiped the preselected category). Covered by the preselect test.
|
||||
- Escape during a rename is handled via DialogContent onEscapeKeyDown (Radix closes dialogs on a document listener).
|
||||
|
||||
## Verification (real output)
|
||||
pnpm lint: clean. npx tsc -b: clean. vitest: 42 test files, 278 tests passed (new: 18 in OfferingCategories.test.tsx: dialog 9, list 2, form 5 + schema 1... plus 1 earlier move test). New files formatted with prettier; the 15 pre-existing prettier warnings in this feature folder remain (tech debt, unchanged).
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
# Code Generation Plan — CMS-U1b offerings-categories-ui
|
||||
|
||||
Frontend only, `frontend/src/features/offerings` (plus the two locale files). Backend routes come from CMS-U1 (commit f2ac377). Wishes from Bryan (via Redesign - SLS): no new page, part of Offerings management; a "Categorieën beheren" button opening a dialog/panel with list + add + rename + delete (409 in understandable Dutch); a "geen categorie" option in the select in the offering form.
|
||||
|
||||
## Behaviour
|
||||
1. **Offerings list page**: a secondary button "Categorieën beheren" next to "Aanbieding toevoegen" opens a dialog. No route change.
|
||||
2. **Categories dialog** (`CategoriesDialog`): lists categories in API order with the number of offerings (e.g. "Websites · 2 aanbiedingen"); an input + "Toevoegen" at the bottom; each row has rename (pencil: inline input with confirm/cancel, Enter confirms, Escape cancels) and delete (trash: inline "Weet je het zeker? Verwijderen / Annuleren"). Empty state: "Nog geen categorieën. Voeg de eerste toe." Mutation errors show as an inline `role="alert"` message in the dialog.
|
||||
3. **Error messages (Dutch, not taken from the English API titles)**: create/rename `409` => "Er bestaat al een categorie met de naam '{{name}}'." ; delete `409` => "Deze categorie wordt nog gebruikt door {{count}} aanbieding(en). Verplaats die eerst naar een andere categorie." (count from the list data); network => existing `errors.network`; other => `errors.generic`. Blank name is rejected client-side ("Vul een naam in.", max 100 characters).
|
||||
4. **Offering form**: a "Categorie" select with the categories and a first option "Geen categorie" (internal value `none`, because Radix Select forbids an empty value). Create sends `categoryId: null` or the id; edit preselects the current category; if the category list is empty the select still shows only "Geen categorie". A stale/unknown `categoryId` from the server falls back to "Geen categorie".
|
||||
5. **Offering row** shows the category name as a small badge when present.
|
||||
6. Everything stays consistent through query invalidation: category mutations invalidate `['offerings','categories']` and `['offerings','admin']` (a rename shows in the list and form immediately).
|
||||
|
||||
## Steps
|
||||
- [x] **Step 1 — Types and schema**: `services/types.ts`: `OfferingDto` gains `categoryId?: string | null` and `category?: string | null`; `CreateOfferingRequest` gains `categoryId?: string | null`; new `OfferingCategoryDto { id, name, sortOrder, offeringCount }`. `schemas/offering.ts`: `categoryId: z.string().nullable().optional()`; new `categoryNameSchema` (trimmed, 1..100).
|
||||
- [x] **Step 2 — Services**: `useOfferingCategories` (GET `/api/v1/offerings/categories`), `useCreateOfferingCategory` (POST), `useRenameOfferingCategory` (PUT `/{id}`), `useDeleteOfferingCategory` (DELETE `/{id}`), same pattern as the existing hooks.
|
||||
- [x] **Step 3 — Components**: `components/CategoriesDialog.tsx` (state: editing id, delete-pending id, new name, error), reuse `Dialog`, `Button`, `Input`, `FieldError`; `OfferingForm.tsx`: category select (Radix `Select` from `components/ui/select.tsx`); `OfferingRow.tsx`: badge; `OfferingsListPage.tsx`: the button + dialog.
|
||||
- [x] **Step 4 — i18n**: add `offerings.categories.*` and `offerings.form.categoryLabel/noCategory` to `nl` and `en` translation files (Dutch is the primary wording above; English counterparts provided).
|
||||
- [x] **Step 5 — Mocks**: `mocks/handlers.ts`: category endpoints with the real behaviours (409 duplicate case-insensitive, 409 in use with counts from the mock offerings, 404 unknown) and offering POST/PUT accepting `categoryId` and returning `categoryId`/`category`. Seed: no categories (nothing is seeded in the real system either); tests add their own.
|
||||
- [x] **Step 6 — Tests (Vitest + Testing Library + msw)**: dialog (empty state; add; blank name rejected; duplicate name shows the Dutch message; rename; delete unused; delete in-use shows the count message and keeps the row), form (select lists categories and "Geen categorie"; submit sends the chosen `categoryId` or `null`; edit preselects; unknown id falls back), list page (button opens the dialog; the category badge renders), schema test.
|
||||
- [x] **Step 7 — Verification (automatic)**: `pnpm lint`, `npx tsc -b`, `pnpm test` (full suite). New files are formatted with prettier; the 15 pre-existing prettier warnings are left alone (tech debt, already reported).
|
||||
- [x] **Step 8 — Docs and commit**: `construction/cms-u1b-offerings-categories-ui/code/summary.md`; one commit; no push.
|
||||
|
||||
## Explicitly NOT touched
|
||||
Backend, ASF-owned frontend areas (auth/refresh, users, theme assets), router, other features, shared UI primitives except by using them (no edits to `components/ui`).
|
||||
|
||||
## Traceability
|
||||
Bryan's category decision, contract § 7 (v2), CMS-U1 handoff (routes, 409 semantics, `offeringCount`).
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -323,6 +323,27 @@
|
||||
"offerings": {
|
||||
"title": "Offerings",
|
||||
"addButton": "Add Offering",
|
||||
"categories": {
|
||||
"manageButton": "Manage categories",
|
||||
"title": "Manage categories",
|
||||
"emptyState": "No categories yet. Add the first one.",
|
||||
"offeringCount_one": "{{count}} offering",
|
||||
"offeringCount_other": "{{count}} offerings",
|
||||
"newLabel": "New category",
|
||||
"addButton": "Add",
|
||||
"editButton": "Rename category",
|
||||
"confirmEditButton": "Confirm name",
|
||||
"cancelButton": "Cancel",
|
||||
"deleteButton": "Delete category",
|
||||
"deleteConfirm": "Are you sure?",
|
||||
"deleteConfirmButton": "Delete",
|
||||
"errors": {
|
||||
"nameRequired": "Enter a name.",
|
||||
"nameTooLong": "The name can be at most 100 characters.",
|
||||
"duplicate": "A category named '{{name}}' already exists.",
|
||||
"inUse": "This category is still used by {{count}} offering(s). Move them to another category first."
|
||||
}
|
||||
},
|
||||
"emptyState": {
|
||||
"heading": "No offerings yet",
|
||||
"description": "Add your first offering to get started."
|
||||
@@ -365,6 +386,8 @@
|
||||
"removeFeatureButton": "Remove",
|
||||
"ctaLabelLabel": "Button text",
|
||||
"featuredLabel": "Featured",
|
||||
"categoryLabel": "Category",
|
||||
"noCategory": "No category",
|
||||
"submitButton": "Save",
|
||||
"successToast": "Offering saved successfully"
|
||||
}
|
||||
|
||||
@@ -323,6 +323,27 @@
|
||||
"offerings": {
|
||||
"title": "Aanbiedingen",
|
||||
"addButton": "Aanbieding toevoegen",
|
||||
"categories": {
|
||||
"manageButton": "Categorieën beheren",
|
||||
"title": "Categorieën beheren",
|
||||
"emptyState": "Nog geen categorieën. Voeg de eerste toe.",
|
||||
"offeringCount_one": "{{count}} aanbieding",
|
||||
"offeringCount_other": "{{count}} aanbiedingen",
|
||||
"newLabel": "Nieuwe categorie",
|
||||
"addButton": "Toevoegen",
|
||||
"editButton": "Categorie hernoemen",
|
||||
"confirmEditButton": "Naam bevestigen",
|
||||
"cancelButton": "Annuleren",
|
||||
"deleteButton": "Categorie verwijderen",
|
||||
"deleteConfirm": "Weet je het zeker?",
|
||||
"deleteConfirmButton": "Verwijderen",
|
||||
"errors": {
|
||||
"nameRequired": "Vul een naam in.",
|
||||
"nameTooLong": "De naam mag maximaal 100 tekens bevatten.",
|
||||
"duplicate": "Er bestaat al een categorie met de naam '{{name}}'.",
|
||||
"inUse": "Deze categorie wordt nog gebruikt door {{count}} aanbieding(en). Verplaats die eerst naar een andere categorie."
|
||||
}
|
||||
},
|
||||
"emptyState": {
|
||||
"heading": "Nog geen aanbiedingen",
|
||||
"description": "Voeg je eerste aanbieding toe om te beginnen."
|
||||
@@ -365,6 +386,8 @@
|
||||
"removeFeatureButton": "Verwijderen",
|
||||
"ctaLabelLabel": "Knoptekst",
|
||||
"featuredLabel": "Uitgelicht",
|
||||
"categoryLabel": "Categorie",
|
||||
"noCategory": "Geen categorie",
|
||||
"submitButton": "Opslaan",
|
||||
"successToast": "Aanbieding succesvol opgeslagen"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user