Offerings: banner-tabblad in de admin (lijst, formulier, planning), layout uit de frontend; gate-test bijgewerkt
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,190 @@
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { toast } from 'sonner';
|
||||
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 { FormErrorBanner } from '@/components/ui/FormErrorBanner';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { NetworkError } from '@/lib/api-client';
|
||||
import {
|
||||
fromLocalInput,
|
||||
offeringBannerFormSchema,
|
||||
toLocalInput,
|
||||
type OfferingBannerFormData,
|
||||
} from '../schemas/offeringBanner';
|
||||
import { useSaveOfferingBanner } from '../services/useSaveOfferingBanner';
|
||||
import type { OfferingBannerDto } from '../services/types';
|
||||
|
||||
interface OfferingBannerDialogProps {
|
||||
/** Open for editing this banner; null with `creating` = a new one. */
|
||||
banner: OfferingBannerDto | null;
|
||||
creating: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const EMPTY: OfferingBannerFormData = {
|
||||
title: '',
|
||||
text: '',
|
||||
linkLabel: '',
|
||||
linkUrl: '',
|
||||
isActive: true,
|
||||
startsAt: '',
|
||||
endsAt: '',
|
||||
};
|
||||
|
||||
function toForm(banner: OfferingBannerDto | null): OfferingBannerFormData {
|
||||
if (!banner) return EMPTY;
|
||||
return {
|
||||
title: banner.title,
|
||||
text: banner.text,
|
||||
linkLabel: banner.linkLabel ?? '',
|
||||
linkUrl: banner.linkUrl ?? '',
|
||||
isActive: banner.isActive,
|
||||
startsAt: toLocalInput(banner.startsAt),
|
||||
endsAt: toLocalInput(banner.endsAt),
|
||||
};
|
||||
}
|
||||
|
||||
export function OfferingBannerDialog({ banner, creating, onClose }: OfferingBannerDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const open = creating || banner !== null;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(next) => { if (!next) onClose(); }}>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle data-testid="banner-dialog-title">
|
||||
{banner ? t('offerings.banners.editTitle') : t('offerings.banners.createTitle')}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
{/* Content is unmounted while closed, so every opening starts from fresh form state. */}
|
||||
<OfferingBannerForm banner={banner} onClose={onClose} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function OfferingBannerForm({ banner, onClose }: { banner: OfferingBannerDto | null; onClose: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
const save = useSaveOfferingBanner();
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<OfferingBannerFormData>({
|
||||
resolver: zodResolver(offeringBannerFormSchema),
|
||||
mode: 'onTouched',
|
||||
defaultValues: toForm(banner),
|
||||
});
|
||||
|
||||
const onSubmit = async (values: OfferingBannerFormData) => {
|
||||
setServerError(null);
|
||||
try {
|
||||
await save.mutateAsync({
|
||||
id: banner?.id,
|
||||
body: {
|
||||
title: values.title,
|
||||
text: values.text,
|
||||
linkLabel: values.linkLabel || null,
|
||||
linkUrl: values.linkUrl || null,
|
||||
isActive: values.isActive,
|
||||
startsAt: fromLocalInput(values.startsAt),
|
||||
endsAt: fromLocalInput(values.endsAt),
|
||||
},
|
||||
});
|
||||
toast.success(t('offerings.banners.savedToast'));
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setServerError(err instanceof NetworkError ? t('errors.network') : t('errors.generic'));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<FormErrorBanner
|
||||
error={serverError !== null ? { message: serverError } : null}
|
||||
onDismiss={() => setServerError(null)}
|
||||
/>
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate data-testid="banner-form">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="banner-title">{t('offerings.banners.titleLabel')}</Label>
|
||||
<Input id="banner-title" data-testid="banner-title" maxLength={100} {...register('title')} />
|
||||
<FieldError message={errors.title?.message} testId="banner-title-error" />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="banner-text">{t('offerings.banners.textLabel')}</Label>
|
||||
<textarea
|
||||
id="banner-text"
|
||||
data-testid="banner-text"
|
||||
rows={3}
|
||||
maxLength={300}
|
||||
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||
{...register('text')}
|
||||
/>
|
||||
<FieldError message={errors.text?.message} testId="banner-text-error" />
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="banner-link-label">{t('offerings.banners.linkLabelLabel')}</Label>
|
||||
<Input id="banner-link-label" data-testid="banner-link-label" maxLength={50} {...register('linkLabel')} />
|
||||
<FieldError message={errors.linkLabel?.message} testId="banner-link-label-error" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="banner-link-url">{t('offerings.banners.linkUrlLabel')}</Label>
|
||||
<Input
|
||||
id="banner-link-url"
|
||||
data-testid="banner-link-url"
|
||||
maxLength={500}
|
||||
placeholder="https://… of /pad"
|
||||
{...register('linkUrl')}
|
||||
/>
|
||||
<FieldError message={errors.linkUrl?.message} testId="banner-link-url-error" />
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{t('offerings.banners.linkHint')}</p>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="banner-starts">{t('offerings.banners.startsLabel')}</Label>
|
||||
<Input id="banner-starts" type="datetime-local" data-testid="banner-starts" {...register('startsAt')} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="banner-ends">{t('offerings.banners.endsLabel')}</Label>
|
||||
<Input id="banner-ends" type="datetime-local" data-testid="banner-ends" {...register('endsAt')} />
|
||||
<FieldError message={errors.endsAt?.message} testId="banner-ends-error" />
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{t('offerings.banners.scheduleHint')}</p>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
id="banner-active"
|
||||
type="checkbox"
|
||||
data-testid="banner-active"
|
||||
className="size-4 rounded border-input"
|
||||
{...register('isActive')}
|
||||
/>
|
||||
<Label htmlFor="banner-active">{t('offerings.banners.activeLabel')}</Label>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button type="button" variant="outline" onClick={onClose} data-testid="banner-cancel">
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button type="submit" disabled={save.isPending} data-testid="banner-submit">
|
||||
{save.isPending ? '…' : t('common.save')}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Megaphone, Pencil, Plus, Trash2 } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { useOfferingBanners } from '../services/useOfferingBanners';
|
||||
import { useDeleteOfferingBanner } from '../services/useDeleteOfferingBanner';
|
||||
import { bannerStatus } from '../schemas/offeringBanner';
|
||||
import { OfferingBannerDialog } from './OfferingBannerDialog';
|
||||
import type { OfferingBannerDto } from '../services/types';
|
||||
|
||||
const fmt = (iso: string | null) =>
|
||||
iso ? new Date(iso).toLocaleString('nl-NL', { dateStyle: 'short', timeStyle: 'short' }) : null;
|
||||
|
||||
export function OfferingBannersTab() {
|
||||
const { t } = useTranslation();
|
||||
const { data: banners, isPending, isError } = useOfferingBanners();
|
||||
const [editing, setEditing] = useState<OfferingBannerDto | null>(null);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [pendingDelete, setPendingDelete] = useState<OfferingBannerDto | null>(null);
|
||||
const remove = useDeleteOfferingBanner();
|
||||
|
||||
const statusVariant = { live: 'default', scheduled: 'secondary', expired: 'outline', off: 'outline' } as const;
|
||||
|
||||
return (
|
||||
<div className="space-y-4" data-testid="banners-tab">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<p className="text-sm text-muted-foreground">{t('offerings.banners.intro')}</p>
|
||||
<Button type="button" onClick={() => setCreating(true)} data-testid="banner-add-button">
|
||||
<Plus className="mr-1 size-4" aria-hidden="true" />
|
||||
{t('offerings.banners.addButton')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isPending && <p className="text-sm text-muted-foreground">{t('common.loading')}</p>}
|
||||
{isError && <p className="text-sm text-destructive">{t('errors.generic')}</p>}
|
||||
|
||||
{!isPending && !isError && banners?.length === 0 && (
|
||||
<div className="flex flex-col items-center space-y-2 py-12 text-center" data-testid="banners-empty">
|
||||
<Megaphone className="size-10 text-muted-foreground" aria-hidden="true" />
|
||||
<p className="text-muted-foreground">{t('offerings.banners.empty')}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{banners && banners.length > 0 && (
|
||||
<ul className="space-y-2" data-testid="banners-list">
|
||||
{banners.map((b) => {
|
||||
const status = bannerStatus(b);
|
||||
return (
|
||||
<li
|
||||
key={b.id}
|
||||
className="flex flex-col gap-2 rounded-md border p-3 sm:flex-row sm:items-center sm:justify-between"
|
||||
data-testid={`banner-row-${b.id}`}
|
||||
>
|
||||
<div className="min-w-0 space-y-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-medium">{b.title}</span>
|
||||
<Badge variant={statusVariant[status]} data-testid={`banner-status-${b.id}`}>
|
||||
{t(`offerings.banners.status.${status}`)}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="truncate text-sm text-muted-foreground">{b.text}</p>
|
||||
{(b.startsAt || b.endsAt) && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{fmt(b.startsAt) ?? '…'} – {fmt(b.endsAt) ?? '…'}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="size-11"
|
||||
aria-label={t('offerings.banners.editButton')}
|
||||
title={t('offerings.banners.editButton')}
|
||||
data-testid={`banner-edit-${b.id}`}
|
||||
onClick={() => setEditing(b)}
|
||||
>
|
||||
<Pencil className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="size-11"
|
||||
aria-label={t('offerings.banners.deleteButton')}
|
||||
title={t('offerings.banners.deleteButton')}
|
||||
data-testid={`banner-delete-${b.id}`}
|
||||
onClick={() => setPendingDelete(b)}
|
||||
>
|
||||
<Trash2 className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<OfferingBannerDialog
|
||||
banner={editing}
|
||||
creating={creating}
|
||||
onClose={() => {
|
||||
setEditing(null);
|
||||
setCreating(false);
|
||||
}}
|
||||
/>
|
||||
|
||||
<Dialog open={pendingDelete !== null} onOpenChange={(open) => { if (!open) setPendingDelete(null); }}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('offerings.banners.deleteTitle')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-sm text-muted-foreground" data-testid="banner-delete-message">
|
||||
{t('offerings.banners.deleteMessage', { title: pendingDelete?.title ?? '' })}
|
||||
</p>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" onClick={() => setPendingDelete(null)} data-testid="banner-delete-cancel">
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
disabled={remove.isPending}
|
||||
data-testid="banner-delete-confirm"
|
||||
onClick={() => {
|
||||
if (!pendingDelete) return;
|
||||
remove.mutate(pendingDelete.id, {
|
||||
onSuccess: () => {
|
||||
setPendingDelete(null);
|
||||
toast.success(t('offerings.banners.deletedToast'));
|
||||
},
|
||||
onError: () => toast.error(t('errors.generic')),
|
||||
});
|
||||
}}
|
||||
>
|
||||
{remove.isPending ? '…' : t('offerings.banners.deleteConfirm')}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -42,7 +42,6 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering
|
||||
featured: false,
|
||||
slug: '',
|
||||
categoryId: null,
|
||||
layout: 'card',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -51,7 +50,6 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering
|
||||
const NO_CATEGORY = 'none';
|
||||
const { data: categories, isFetching: isFetchingCategories } = useOfferingCategories();
|
||||
const categoryId = useWatch({ control, name: 'categoryId' });
|
||||
const layout = useWatch({ control, name: 'layout' });
|
||||
const selectedCategory =
|
||||
categoryId != null && categories?.some((c) => c.id === categoryId) ? categoryId : NO_CATEGORY;
|
||||
|
||||
@@ -293,24 +291,6 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering
|
||||
<Label htmlFor="offering-featured">{t('offerings.form.featuredLabel')}</Label>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="offering-layout">{t('offerings.form.layoutLabel')}</Label>
|
||||
<select
|
||||
id="offering-layout"
|
||||
data-testid="offering-layout"
|
||||
className="h-11 w-full rounded-md border border-input bg-background px-3 text-sm"
|
||||
{...register('layout')}
|
||||
>
|
||||
<option value="card">{t('offerings.form.layoutCard')}</option>
|
||||
<option value="banner">{t('offerings.form.layoutBanner')}</option>
|
||||
</select>
|
||||
{layout === 'banner' && (
|
||||
<p className="text-sm text-muted-foreground" data-testid="offering-layout-banner-hint">
|
||||
{t('offerings.form.layoutBannerHint')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button type="submit" disabled={isSubmitting} data-testid="offering-form-submit">
|
||||
{isSubmitting ? '…' : t('offerings.form.submitButton')}
|
||||
</Button>
|
||||
|
||||
@@ -2,6 +2,8 @@ import { http, HttpResponse } from 'msw';
|
||||
import type {
|
||||
OfferingDto,
|
||||
OfferingCategoryDto,
|
||||
OfferingBannerDto,
|
||||
OfferingBannerRequest,
|
||||
CreateOfferingRequest,
|
||||
UpdateOfferingRequest,
|
||||
} from '@/features/offerings/services/types';
|
||||
@@ -49,7 +51,15 @@ let mockOfferings: OfferingDto[] = [...seed];
|
||||
type MockCategory = Omit<OfferingCategoryDto, 'offeringCount'>;
|
||||
let mockCategories: MockCategory[] = [];
|
||||
|
||||
/** Banners; nothing is seeded. Handlers are registered before the /:id routes so 'banners' is not read as an id. */
|
||||
let mockBanners: OfferingBannerDto[] = [];
|
||||
export const getMockBanners = () => mockBanners;
|
||||
export const setMockBanners = (banners: OfferingBannerDto[]) => {
|
||||
mockBanners = [...banners];
|
||||
};
|
||||
|
||||
export const resetMockOfferings = () => {
|
||||
mockBanners = [];
|
||||
mockOfferings = [...seed];
|
||||
mockCategories = [];
|
||||
};
|
||||
@@ -79,6 +89,35 @@ 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/banners`, () => HttpResponse.json(mockBanners)),
|
||||
|
||||
http.post(`${API_BASE}/api/v1/offerings/banners`, async ({ request }) => {
|
||||
const body = (await request.json()) as OfferingBannerRequest;
|
||||
const created: OfferingBannerDto = {
|
||||
id: crypto.randomUUID(),
|
||||
...body,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
mockBanners = [created, ...mockBanners];
|
||||
return HttpResponse.json(created, { status: 201 });
|
||||
}),
|
||||
|
||||
http.put(`${API_BASE}/api/v1/offerings/banners/:id`, async ({ params, request }) => {
|
||||
const { id } = params as { id: string };
|
||||
const existing = mockBanners.find((b) => b.id === id);
|
||||
if (!existing) return new HttpResponse(null, { status: 404 });
|
||||
const body = (await request.json()) as OfferingBannerRequest;
|
||||
const updated: OfferingBannerDto = { ...existing, ...body, updatedAt: new Date().toISOString() };
|
||||
mockBanners = mockBanners.map((b) => (b.id === id ? updated : b));
|
||||
return HttpResponse.json(updated);
|
||||
}),
|
||||
|
||||
http.delete(`${API_BASE}/api/v1/offerings/banners/:id`, ({ params }) => {
|
||||
const { id } = params as { id: string };
|
||||
mockBanners = mockBanners.filter((b) => b.id !== id);
|
||||
return new HttpResponse(null, { status: 204 });
|
||||
}),
|
||||
|
||||
http.get(`${API_BASE}/api/v1/offerings`, () => HttpResponse.json(mockOfferings.map(withCategoryName))),
|
||||
|
||||
http.post(`${API_BASE}/api/v1/offerings`, async ({ request }) => {
|
||||
@@ -100,7 +139,6 @@ export const offeringsHandlers = [
|
||||
const newOffering: OfferingDto = {
|
||||
id: crypto.randomUUID(),
|
||||
...body,
|
||||
layout: body.layout ?? 'card',
|
||||
slug,
|
||||
displayOrder: mockOfferings.length,
|
||||
};
|
||||
@@ -195,12 +233,8 @@ export const offeringsHandlers = [
|
||||
...body,
|
||||
slug,
|
||||
categoryId: body.categoryId ?? null,
|
||||
layout: body.layout ?? existing.layout ?? 'card',
|
||||
};
|
||||
// At most one banner: promoting this one turns the current banner back into a card.
|
||||
mockOfferings = mockOfferings.map((o) =>
|
||||
o.id === id ? updated : updated.layout === 'banner' && o.layout === 'banner' ? { ...o, layout: 'card' } : o,
|
||||
);
|
||||
mockOfferings = mockOfferings.map((o) => (o.id === id ? updated : o));
|
||||
return HttpResponse.json(withCategoryName(updated));
|
||||
}),
|
||||
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { renderApp, mockAuthenticated } from '@/test/utils';
|
||||
import { getMockBanners, resetMockOfferings, setMockBanners } from '@/features/offerings/mocks/handlers';
|
||||
import { bannerStatus, fromLocalInput, isAllowedBannerLink, toLocalInput } from '@/features/offerings/schemas/offeringBanner';
|
||||
import { _resetSetupStatusCache } from '@/router';
|
||||
|
||||
beforeEach(() => {
|
||||
_resetSetupStatusCache();
|
||||
resetMockOfferings();
|
||||
});
|
||||
|
||||
const T = { timeout: 10000 };
|
||||
|
||||
async function openBannerTab() {
|
||||
mockAuthenticated();
|
||||
renderApp('/offerings');
|
||||
await userEvent.click(await screen.findByTestId('offerings-tab-banner', {}, T));
|
||||
}
|
||||
|
||||
describe('Banner tab', () => {
|
||||
it('switches between the offerings and the banner tab, hiding the add-offering actions on the banner tab', async () => {
|
||||
mockAuthenticated();
|
||||
renderApp('/offerings');
|
||||
expect(await screen.findByTestId('offerings-add-button', {}, T)).toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByTestId('offerings-tab-banner'));
|
||||
expect(await screen.findByTestId('banners-tab')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('offerings-tab-banner')).toHaveAttribute('aria-selected', 'true');
|
||||
expect(screen.queryByTestId('offerings-add-button')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('offerings-add-fab')).not.toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByTestId('offerings-tab-offerings'));
|
||||
expect(await screen.findByTestId('offerings-add-button')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows an empty state, then creates a banner with a link and a schedule', async () => {
|
||||
await openBannerTab();
|
||||
expect(await screen.findByTestId('banners-empty', {}, T)).toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByTestId('banner-add-button'));
|
||||
await userEvent.type(await screen.findByTestId('banner-title'), 'Zomeractie');
|
||||
await userEvent.type(screen.getByTestId('banner-text'), '10% korting in juli');
|
||||
await userEvent.type(screen.getByTestId('banner-link-label'), 'Bekijk');
|
||||
await userEvent.type(screen.getByTestId('banner-link-url'), '/privacy');
|
||||
await userEvent.type(screen.getByTestId('banner-starts'), '2030-07-01T09:00');
|
||||
await userEvent.type(screen.getByTestId('banner-ends'), '2030-07-31T23:00');
|
||||
await userEvent.click(screen.getByTestId('banner-submit'));
|
||||
|
||||
await waitFor(() => expect(getMockBanners()).toHaveLength(1));
|
||||
const saved = getMockBanners()[0];
|
||||
expect(saved).toMatchObject({ title: 'Zomeractie', linkLabel: 'Bekijk', linkUrl: '/privacy', isActive: true });
|
||||
expect(saved.startsAt).toBe(fromLocalInput('2030-07-01T09:00'));
|
||||
expect(await screen.findByText('Zomeractie')).toBeInTheDocument();
|
||||
expect(screen.getByTestId(`banner-status-${saved.id}`)).toHaveTextContent(/Gepland|Scheduled/);
|
||||
});
|
||||
|
||||
it('rejects an unsafe link and a link without button text, and an end before the start', async () => {
|
||||
await openBannerTab();
|
||||
await userEvent.click(await screen.findByTestId('banner-add-button', {}, T));
|
||||
await userEvent.type(await screen.findByTestId('banner-title'), 'X');
|
||||
await userEvent.type(screen.getByTestId('banner-text'), 'Y');
|
||||
|
||||
await userEvent.type(screen.getByTestId('banner-link-label'), 'Go');
|
||||
await userEvent.type(screen.getByTestId('banner-link-url'), 'javascript:alert(1)');
|
||||
await userEvent.click(screen.getByTestId('banner-submit'));
|
||||
expect(await screen.findByTestId('banner-link-url-error')).toBeInTheDocument();
|
||||
|
||||
await userEvent.clear(screen.getByTestId('banner-link-label'));
|
||||
await userEvent.clear(screen.getByTestId('banner-link-url'));
|
||||
await userEvent.type(screen.getByTestId('banner-link-url'), '/ok');
|
||||
await userEvent.click(screen.getByTestId('banner-submit'));
|
||||
expect(await screen.findByTestId('banner-link-label-error')).toBeInTheDocument();
|
||||
|
||||
await userEvent.clear(screen.getByTestId('banner-link-url'));
|
||||
await userEvent.type(screen.getByTestId('banner-starts'), '2030-07-31T09:00');
|
||||
await userEvent.type(screen.getByTestId('banner-ends'), '2030-07-01T09:00');
|
||||
await userEvent.click(screen.getByTestId('banner-submit'));
|
||||
expect(await screen.findByTestId('banner-ends-error')).toBeInTheDocument();
|
||||
expect(getMockBanners()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('edits and deletes an existing banner', async () => {
|
||||
setMockBanners([
|
||||
{
|
||||
id: 'b1', title: 'Oud', text: 'Tekst', linkLabel: null, linkUrl: null, isActive: true,
|
||||
startsAt: null, endsAt: null, updatedAt: '2026-01-01T00:00:00Z',
|
||||
},
|
||||
]);
|
||||
await openBannerTab();
|
||||
expect(await screen.findByTestId('banner-status-b1', {}, T)).toHaveTextContent(/Actief|Active/);
|
||||
|
||||
await userEvent.click(screen.getByTestId('banner-edit-b1'));
|
||||
const title = await screen.findByTestId('banner-title');
|
||||
expect(title).toHaveValue('Oud');
|
||||
await userEvent.clear(title);
|
||||
await userEvent.type(title, 'Nieuw');
|
||||
await userEvent.click(screen.getByTestId('banner-active'));
|
||||
await userEvent.click(screen.getByTestId('banner-submit'));
|
||||
await waitFor(() => expect(getMockBanners()[0]).toMatchObject({ title: 'Nieuw', isActive: false }));
|
||||
expect(await screen.findByTestId('banner-status-b1')).toHaveTextContent(/Uit|Off/);
|
||||
|
||||
await userEvent.click(screen.getByTestId('banner-delete-b1'));
|
||||
expect(await screen.findByTestId('banner-delete-message')).toHaveTextContent('Nieuw');
|
||||
await userEvent.click(screen.getByTestId('banner-delete-confirm'));
|
||||
await waitFor(() => expect(getMockBanners()).toHaveLength(0));
|
||||
expect(await screen.findByTestId('banners-empty')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('banner helpers', () => {
|
||||
it.each([
|
||||
['https://slpsoftware.nl/actie', true],
|
||||
['/aanbieding', true],
|
||||
['/', true],
|
||||
['http://x.nl', false],
|
||||
['//evil.example', false],
|
||||
['/\\evil', false],
|
||||
['javascript:alert(1)', false],
|
||||
['mailto:a@b.nl', false],
|
||||
['actie', false],
|
||||
['/with space', false],
|
||||
])('link %s → %s', (url, ok) => {
|
||||
expect(isAllowedBannerLink(url)).toBe(ok);
|
||||
});
|
||||
|
||||
it('derives the status from switch and schedule', () => {
|
||||
const now = new Date('2026-11-12T12:00:00Z');
|
||||
expect(bannerStatus({ isActive: false, startsAt: null, endsAt: null }, now)).toBe('off');
|
||||
expect(bannerStatus({ isActive: true, startsAt: '2026-11-13T00:00:00Z', endsAt: null }, now)).toBe('scheduled');
|
||||
expect(bannerStatus({ isActive: true, startsAt: null, endsAt: '2026-11-12T12:00:00Z' }, now)).toBe('expired');
|
||||
expect(bannerStatus({ isActive: true, startsAt: '2026-11-01T00:00:00Z', endsAt: '2026-12-01T00:00:00Z' }, now)).toBe('live');
|
||||
});
|
||||
|
||||
it('round-trips datetime-local values', () => {
|
||||
expect(toLocalInput(fromLocalInput('2030-07-01T09:00'))).toBe('2030-07-01T09:00');
|
||||
expect(fromLocalInput('')).toBeNull();
|
||||
expect(toLocalInput(null)).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { screen, waitFor } from '@testing-library/react';
|
||||
import { screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { renderApp, mockAuthenticated } from '@/test/utils';
|
||||
import { getMockOfferings, resetMockOfferings } from '@/features/offerings/mocks/handlers';
|
||||
import { resetMockOfferings } from '@/features/offerings/mocks/handlers';
|
||||
import { _resetSetupStatusCache } from '@/router';
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -119,34 +119,4 @@ describe('OfferingFormPage', () => {
|
||||
|
||||
expect(await screen.findByText(/pro.*al in gebruik|already.*taken/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('defaults the layout to card and shows a hint only when banner is chosen', async () => {
|
||||
mockAuthenticated();
|
||||
renderApp('/offerings/new');
|
||||
|
||||
const select = await screen.findByTestId('offering-layout', {}, { timeout: 10000 });
|
||||
expect(select).toHaveValue('card');
|
||||
expect(screen.queryByTestId('offering-layout-banner-hint')).not.toBeInTheDocument();
|
||||
|
||||
await userEvent.selectOptions(select, 'banner');
|
||||
expect(await screen.findByTestId('offering-layout-banner-hint')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('saves a banner and turns the previous banner back into a card', async () => {
|
||||
mockAuthenticated();
|
||||
const first = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
|
||||
const second = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';
|
||||
|
||||
renderApp(`/offerings/${first}/edit`);
|
||||
await userEvent.selectOptions(await screen.findByTestId('offering-layout', {}, { timeout: 10000 }), 'banner');
|
||||
await userEvent.click(screen.getByTestId('offering-form-submit'));
|
||||
await waitFor(() => expect(getMockOfferings().find((o) => o.id === first)?.layout).toBe('banner'));
|
||||
await screen.findByTestId('offerings-title', {}, { timeout: 10000 });
|
||||
|
||||
renderApp(`/offerings/${second}/edit`);
|
||||
await userEvent.selectOptions(await screen.findByTestId('offering-layout', {}, { timeout: 10000 }), 'banner');
|
||||
await userEvent.click(screen.getByTestId('offering-form-submit'));
|
||||
await waitFor(() => expect(getMockOfferings().find((o) => o.id === second)?.layout).toBe('banner'));
|
||||
expect(getMockOfferings().find((o) => o.id === first)?.layout).toBe('card');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Button } from '@/components/ui/button';
|
||||
import { OfferingsList } from '../components/OfferingsList';
|
||||
import { DeleteOfferingDialog } from '../components/DeleteOfferingDialog';
|
||||
import { CategoriesDialog } from '../components/CategoriesDialog';
|
||||
import { OfferingBannersTab } from '../components/OfferingBannersTab';
|
||||
import { useOfferings } from '../services/useOfferings';
|
||||
import { useDeleteOffering } from '../services/useDeleteOffering';
|
||||
import type { OfferingDto } from '../services/types';
|
||||
@@ -14,6 +15,7 @@ export function OfferingsListPage() {
|
||||
const { t } = useTranslation();
|
||||
const [offeringPendingDelete, setOfferingPendingDelete] = useState<OfferingDto | null>(null);
|
||||
const [categoriesOpen, setCategoriesOpen] = useState(false);
|
||||
const [tab, setTab] = useState<'offerings' | 'banner'>('offerings');
|
||||
const { data: offerings, isPending, isError } = useOfferings();
|
||||
const deleteOffering = useDeleteOffering({
|
||||
onSuccess: () => setOfferingPendingDelete(null),
|
||||
@@ -25,6 +27,7 @@ export function OfferingsListPage() {
|
||||
<h1 className="text-2xl font-semibold" data-testid="offerings-title">
|
||||
{t('offerings.title')}
|
||||
</h1>
|
||||
{tab === 'offerings' && (
|
||||
<div className="flex items-center gap-2">
|
||||
{/* From sm up: text buttons. Below sm: icon-only categories button; the add action is the FAB below. */}
|
||||
<Button
|
||||
@@ -52,8 +55,39 @@ export function OfferingsListPage() {
|
||||
<Link to="/offerings/new">{t('offerings.addButton')}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div role="tablist" aria-label={t('offerings.banners.tabsLabel')} className="flex gap-1 border-b" data-testid="offerings-tabs">
|
||||
{(['offerings', 'banner'] as const).map((key) => (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
role="tab"
|
||||
id={`offerings-tab-${key}`}
|
||||
aria-selected={tab === key}
|
||||
aria-controls={`offerings-panel-${key}`}
|
||||
data-testid={`offerings-tab-${key}`}
|
||||
onClick={() => setTab(key)}
|
||||
className={`-mb-px min-h-11 border-b-2 px-4 text-sm font-medium transition-colors ${
|
||||
tab === key
|
||||
? 'border-primary text-foreground'
|
||||
: 'border-transparent text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
{key === 'offerings' ? t('offerings.banners.tabPackages') : t('offerings.banners.tabBanner')}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{tab === 'banner' && (
|
||||
<div role="tabpanel" id="offerings-panel-banner" aria-labelledby="offerings-tab-banner">
|
||||
<OfferingBannersTab />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === 'offerings' && (
|
||||
<div role="tabpanel" id="offerings-panel-offerings" aria-labelledby="offerings-tab-offerings" className="space-y-4">
|
||||
{isPending && <p className="text-sm text-muted-foreground">{t('common.loading')}</p>}
|
||||
|
||||
{isError && <p className="text-sm text-destructive">{t('errors.generic')}</p>}
|
||||
@@ -76,6 +110,10 @@ export function OfferingsListPage() {
|
||||
<OfferingsList offerings={offerings} onDeleteRequested={setOfferingPendingDelete} />
|
||||
)}
|
||||
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === 'offerings' && (
|
||||
<Link
|
||||
to="/offerings/new"
|
||||
aria-label={t('offerings.addButton')}
|
||||
@@ -85,6 +123,7 @@ export function OfferingsListPage() {
|
||||
>
|
||||
<Plus className="size-6" aria-hidden="true" />
|
||||
</Link>
|
||||
)}
|
||||
|
||||
<CategoriesDialog open={categoriesOpen} onOpenChange={setCategoriesOpen} />
|
||||
|
||||
|
||||
@@ -25,8 +25,6 @@ export const offeringFormSchema = z.object({
|
||||
.or(z.literal('')),
|
||||
/** Id of the chosen category; null/absent = no category. */
|
||||
categoryId: z.string().nullable().optional(),
|
||||
/** 'banner' = the wide strip under the cards; at most one per site. */
|
||||
layout: z.enum(['card', 'banner']).optional(),
|
||||
});
|
||||
|
||||
export type OfferingFormData = z.infer<typeof offeringFormSchema>;
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
/** https:// address or a site path with a single leading slash; mirrors the API rule. */
|
||||
export function isAllowedBannerLink(url: string): boolean {
|
||||
if (/[\s\\]/.test(url) || [...url].some((c) => c.charCodeAt(0) < 32)) return false;
|
||||
if (url.startsWith('/')) return !url.startsWith('//');
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return parsed.protocol === 'https:' && parsed.hostname !== '';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export const offeringBannerFormSchema = z
|
||||
.object({
|
||||
title: z.string().trim().min(1, 'Title is required').max(100, 'Title must be 100 characters or fewer'),
|
||||
text: z.string().trim().min(1, 'Text is required').max(300, 'Text must be 300 characters or fewer'),
|
||||
linkLabel: z.string().trim().max(50, 'Button text must be 50 characters or fewer'),
|
||||
linkUrl: z.string().trim().max(500, 'Link must be 500 characters or fewer'),
|
||||
isActive: z.boolean(),
|
||||
/** datetime-local value ("YYYY-MM-DDTHH:mm") in the browser's time zone, or ''. */
|
||||
startsAt: z.string(),
|
||||
endsAt: z.string(),
|
||||
})
|
||||
.superRefine((v, ctx) => {
|
||||
const hasLabel = v.linkLabel !== '';
|
||||
const hasUrl = v.linkUrl !== '';
|
||||
if (hasLabel !== hasUrl) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: [hasUrl ? 'linkLabel' : 'linkUrl'],
|
||||
message: 'Button text and link must be given together',
|
||||
});
|
||||
} else if (hasUrl && !isAllowedBannerLink(v.linkUrl)) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['linkUrl'],
|
||||
message: 'Link must start with https:// or be a path starting with /',
|
||||
});
|
||||
}
|
||||
if (v.startsAt && v.endsAt && new Date(v.endsAt).getTime() <= new Date(v.startsAt).getTime()) {
|
||||
ctx.addIssue({ code: 'custom', path: ['endsAt'], message: 'End must be after start' });
|
||||
}
|
||||
});
|
||||
|
||||
export type OfferingBannerFormData = z.infer<typeof offeringBannerFormSchema>;
|
||||
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
|
||||
/** ISO (UTC) → value for <input type="datetime-local"> in the browser's time zone. */
|
||||
export function toLocalInput(iso: string | null): string {
|
||||
if (!iso) return '';
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return '';
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
/** datetime-local value → ISO (UTC), '' → null. */
|
||||
export function fromLocalInput(value: string): string | null {
|
||||
if (!value) return null;
|
||||
const d = new Date(value);
|
||||
return Number.isNaN(d.getTime()) ? null : d.toISOString();
|
||||
}
|
||||
|
||||
export type BannerStatus = 'off' | 'scheduled' | 'expired' | 'live';
|
||||
|
||||
export function bannerStatus(b: { isActive: boolean; startsAt: string | null; endsAt: string | null }, now = new Date()): BannerStatus {
|
||||
if (!b.isActive) return 'off';
|
||||
if (b.startsAt && new Date(b.startsAt) > now) return 'scheduled';
|
||||
if (b.endsAt && new Date(b.endsAt) <= now) return 'expired';
|
||||
return 'live';
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
export type OfferingLayout = 'card' | 'banner';
|
||||
|
||||
export interface OfferingDto {
|
||||
id: string;
|
||||
slug: string;
|
||||
@@ -15,8 +13,6 @@ export interface OfferingDto {
|
||||
categoryId?: string | null;
|
||||
/** Name of the category (renames show up here automatically). */
|
||||
category?: string | null;
|
||||
/** Presentation on the website; absent (older API) means 'card'. */
|
||||
layout?: OfferingLayout;
|
||||
}
|
||||
|
||||
export interface CreateOfferingRequest {
|
||||
@@ -31,8 +27,6 @@ export interface CreateOfferingRequest {
|
||||
slug?: string;
|
||||
/** Category id; null clears the category. */
|
||||
categoryId?: string | null;
|
||||
/** Omit to keep the current value (older clients do). */
|
||||
layout?: OfferingLayout;
|
||||
}
|
||||
|
||||
export type UpdateOfferingRequest = CreateOfferingRequest;
|
||||
@@ -45,3 +39,27 @@ export interface OfferingCategoryDto {
|
||||
}
|
||||
|
||||
export type MoveDirection = 'up' | 'down';
|
||||
|
||||
export interface OfferingBannerDto {
|
||||
id: string;
|
||||
title: string;
|
||||
text: string;
|
||||
linkLabel: string | null;
|
||||
linkUrl: string | null;
|
||||
isActive: boolean;
|
||||
/** ISO date-time (UTC) or null = no start limit. */
|
||||
startsAt: string | null;
|
||||
/** ISO date-time (UTC) or null = no end limit. */
|
||||
endsAt: string | null;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface OfferingBannerRequest {
|
||||
title: string;
|
||||
text: string;
|
||||
linkLabel: string | null;
|
||||
linkUrl: string | null;
|
||||
isActive: boolean;
|
||||
startsAt: string | null;
|
||||
endsAt: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api-client';
|
||||
import { OFFERING_BANNERS_KEY } from './useOfferingBanners';
|
||||
|
||||
export function useDeleteOfferingBanner() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<void, Error, string>({
|
||||
mutationFn: (id) => api.delete<void>(`/api/v1/offerings/banners/${id}`),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: OFFERING_BANNERS_KEY });
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api-client';
|
||||
import type { OfferingBannerDto } from './types';
|
||||
|
||||
export const OFFERING_BANNERS_KEY = ['offerings', 'banners'];
|
||||
|
||||
export function useOfferingBanners() {
|
||||
return useQuery<OfferingBannerDto[], Error>({
|
||||
queryKey: OFFERING_BANNERS_KEY,
|
||||
queryFn: () => api.get<OfferingBannerDto[]>('/api/v1/offerings/banners'),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api-client';
|
||||
import { OFFERING_BANNERS_KEY } from './useOfferingBanners';
|
||||
import type { OfferingBannerDto, OfferingBannerRequest } from './types';
|
||||
|
||||
/** Creates a banner, or replaces it when an id is given. */
|
||||
export function useSaveOfferingBanner() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<OfferingBannerDto, Error, { id?: string; body: OfferingBannerRequest }>({
|
||||
mutationFn: ({ id, body }) =>
|
||||
id
|
||||
? api.put<OfferingBannerDto>(`/api/v1/offerings/banners/${id}`, body)
|
||||
: api.post<OfferingBannerDto>('/api/v1/offerings/banners', body),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: OFFERING_BANNERS_KEY });
|
||||
},
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -160,6 +160,7 @@ public class PublicSiteEndpointGateTests
|
||||
private static readonly string[] AllowedPublicActions =
|
||||
[
|
||||
$"{nameof(OfferingsController)}.{nameof(OfferingsController.GetOfferings)}",
|
||||
$"{nameof(PublicOfferingBannerController)}.{nameof(PublicOfferingBannerController.Get)}",
|
||||
$"{nameof(ContactMessagesController)}.{nameof(ContactMessagesController.GetToken)}",
|
||||
$"{nameof(ContactMessagesController)}.{nameof(ContactMessagesController.Submit)}",
|
||||
$"{nameof(SystemController)}.{nameof(SystemController.GetCapabilities)}",
|
||||
|
||||
Reference in New Issue
Block a user