Contactformulier-module, banners, thema's, taalbestanden en CI-herstructurering #15

Merged
Sluijsens merged 84 commits from feature/contact-forms-module into master 2026-11-16 11:51:12 +01:00
19 changed files with 781 additions and 138 deletions
Showing only changes of commit 4b09089ffb - Show all commits
@@ -1,5 +1,5 @@
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { useForm, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
@@ -12,21 +12,23 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/u
import { NetworkError } from '@/lib/api-client';
import {
fromLocalInput,
bannerTextMaxLength,
offeringBannerFormSchema,
toLocalInput,
type OfferingBannerFormData,
} from '../schemas/offeringBanner';
import { useSaveOfferingBanner } from '../services/useSaveOfferingBanner';
import type { OfferingBannerDto } from '../services/types';
import type { BannerPosition, OfferingBannerDto } from '../services/types';
interface OfferingBannerDialogProps {
/** Open for editing this banner; null with `creating` = a new one. */
/** Open for editing this banner (its own position applies); null with `creatingPosition` = a new one there. */
banner: OfferingBannerDto | null;
creating: boolean;
creatingPosition: BannerPosition | null;
onClose: () => void;
}
const EMPTY: OfferingBannerFormData = {
const emptyForm = (position: BannerPosition): OfferingBannerFormData => ({
position,
title: '',
text: '',
linkLabel: '',
@@ -34,11 +36,12 @@ const EMPTY: OfferingBannerFormData = {
isActive: true,
startsAt: '',
endsAt: '',
};
});
function toForm(banner: OfferingBannerDto | null): OfferingBannerFormData {
if (!banner) return EMPTY;
function toForm(banner: OfferingBannerDto | null, position: BannerPosition): OfferingBannerFormData {
if (!banner) return emptyForm(position);
return {
position: banner.position,
title: banner.title,
text: banner.text,
linkLabel: banner.linkLabel ?? '',
@@ -49,26 +52,35 @@ function toForm(banner: OfferingBannerDto | null): OfferingBannerFormData {
};
}
export function OfferingBannerDialog({ banner, creating, onClose }: OfferingBannerDialogProps) {
export function OfferingBannerDialog({ banner, creatingPosition, onClose }: OfferingBannerDialogProps) {
const { t } = useTranslation();
const open = creating || banner !== null;
const open = creatingPosition !== null || banner !== null;
const position: BannerPosition = banner?.position ?? creatingPosition ?? 'bottom';
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')}
{banner ? t(`offerings.banners.editTitle_${position}`) : t(`offerings.banners.createTitle_${position}`)}
</DialogTitle>
</DialogHeader>
{/* Content is unmounted while closed, so every opening starts from fresh form state. */}
<OfferingBannerForm banner={banner} onClose={onClose} />
<OfferingBannerForm banner={banner} position={position} onClose={onClose} />
</DialogContent>
</Dialog>
);
}
function OfferingBannerForm({ banner, onClose }: { banner: OfferingBannerDto | null; onClose: () => void }) {
function OfferingBannerForm({
banner,
position,
onClose,
}: {
banner: OfferingBannerDto | null;
position: BannerPosition;
onClose: () => void;
}) {
const { t } = useTranslation();
const [serverError, setServerError] = useState<string | null>(null);
const save = useSaveOfferingBanner();
@@ -76,12 +88,15 @@ function OfferingBannerForm({ banner, onClose }: { banner: OfferingBannerDto | n
const {
register,
handleSubmit,
control,
formState: { errors },
} = useForm<OfferingBannerFormData>({
resolver: zodResolver(offeringBannerFormSchema),
mode: 'onTouched',
defaultValues: toForm(banner),
defaultValues: toForm(banner, position),
});
const textMax = bannerTextMaxLength(position);
const textLength = (useWatch({ control, name: 'text' }) ?? '').length;
const onSubmit = async (values: OfferingBannerFormData) => {
setServerError(null);
@@ -89,6 +104,7 @@ function OfferingBannerForm({ banner, onClose }: { banner: OfferingBannerDto | n
await save.mutateAsync({
id: banner?.id,
body: {
position: values.position,
title: values.title,
text: values.text,
linkLabel: values.linkLabel || null,
@@ -114,7 +130,7 @@ function OfferingBannerForm({ banner, onClose }: { banner: OfferingBannerDto | n
<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>
<Label htmlFor="banner-title">{t(position === 'top' ? 'offerings.banners.titleLabelOptional' : '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>
@@ -124,11 +140,18 @@ function OfferingBannerForm({ banner, onClose }: { banner: OfferingBannerDto | n
<textarea
id="banner-text"
data-testid="banner-text"
rows={3}
maxLength={300}
rows={position === 'top' ? 2 : 3}
maxLength={textMax}
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
{...register('text')}
/>
<p
className={`text-xs ${textLength >= textMax ? 'text-destructive' : 'text-muted-foreground'}`}
data-testid="banner-text-counter"
>
{textLength}/{textMax}
{position === 'top' && ` · ${t('offerings.banners.textHintTop')}`}
</p>
<FieldError message={errors.text?.message} testId="banner-text-error" />
</div>
@@ -1,111 +1,182 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Megaphone, Pencil, Plus, Trash2 } from 'lucide-react';
import { Megaphone, Pencil, Plus, Power, 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 { useSaveOfferingBanner } from '../services/useSaveOfferingBanner';
import { bannerStatus } from '../schemas/offeringBanner';
import { OfferingBannerDialog } from './OfferingBannerDialog';
import type { OfferingBannerDto } from '../services/types';
import type { BannerPosition, OfferingBannerDto } from '../services/types';
const fmt = (iso: string | null) =>
iso ? new Date(iso).toLocaleString('nl-NL', { dateStyle: 'short', timeStyle: 'short' }) : null;
const POSITIONS: BannerPosition[] = ['top', 'bottom'];
const statusVariant = { live: 'default', scheduled: 'secondary', expired: 'outline', off: 'outline' } as const;
/** The banner shown now for one position: among the live ones, the most recently changed wins. */
function liveBannerOf(banners: OfferingBannerDto[], now = new Date()): OfferingBannerDto | null {
const live = banners.filter((b) => bannerStatus(b, now) === 'live');
if (live.length === 0) return null;
return live.reduce((a, b) => (new Date(b.updatedAt) > new Date(a.updatedAt) ? b : a));
}
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 [creating, setCreating] = useState<BannerPosition | null>(null);
const [pendingDelete, setPendingDelete] = useState<OfferingBannerDto | null>(null);
const remove = useDeleteOfferingBanner();
const save = useSaveOfferingBanner();
const statusVariant = { live: 'default', scheduled: 'secondary', expired: 'outline', off: 'outline' } as const;
const toggleActive = (b: OfferingBannerDto) =>
save.mutate(
{
id: b.id,
body: {
position: b.position,
title: b.title,
text: b.text,
linkLabel: b.linkLabel,
linkUrl: b.linkUrl,
isActive: !b.isActive,
startsAt: b.startsAt,
endsAt: b.endsAt,
},
},
{
onSuccess: () => toast.success(t('offerings.banners.savedToast')),
onError: () => toast.error(t('errors.generic')),
},
);
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>
<div className="space-y-6" data-testid="banners-tab">
<p className="text-sm text-muted-foreground">{t('offerings.banners.intro')}</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 && 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>
)}
{!isPending &&
!isError &&
POSITIONS.map((position) => {
const items = (banners ?? []).filter((b) => b.position === position);
const live = liveBannerOf(items);
return (
<section key={position} className="space-y-3" data-testid={`banners-section-${position}`}>
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="space-y-1">
<h2 className="text-base font-semibold">{t(`offerings.banners.section.${position}.title`)}</h2>
<p className="text-sm text-muted-foreground">
{t(`offerings.banners.section.${position}.description`)}
</p>
<p className="text-xs text-muted-foreground" data-testid={`banner-live-hint-${position}`}>
{live
? t('offerings.banners.liveNow', { title: live.title || live.text })
: t('offerings.banners.nothingActive')}
</p>
</div>
<Button type="button" onClick={() => setCreating(position)} data-testid={`banner-add-${position}`}>
<Plus className="mr-1 size-4" aria-hidden="true" />
{t(`offerings.banners.section.${position}.addButton`)}
</Button>
</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>
)}
{items.length === 0 ? (
<div
className="flex flex-col items-center space-y-2 py-8 text-center"
data-testid={`banners-empty-${position}`}
>
<Megaphone className="size-8 text-muted-foreground" aria-hidden="true" />
<p className="text-muted-foreground">{t('offerings.banners.empty')}</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>
)}
) : (
<ul className="space-y-2" data-testid={`banners-list-${position}`}>
{items.map((b) => {
const status = bannerStatus(b);
const toggleLabel = t(
b.isActive ? 'offerings.banners.turnOffButton' : 'offerings.banners.turnOnButton',
);
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">
{b.title && <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={toggleLabel}
title={toggleLabel}
disabled={save.isPending}
data-testid={`banner-toggle-${b.id}`}
onClick={() => toggleActive(b)}
>
<Power className="size-4" aria-hidden="true" />
</Button>
<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>
)}
</section>
);
})}
<OfferingBannerDialog
banner={editing}
creating={creating}
creatingPosition={creating}
onClose={() => {
setEditing(null);
setCreating(false);
setCreating(null);
}}
/>
@@ -115,7 +186,7 @@ export function OfferingBannersTab() {
<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 ?? '' })}
{t('offerings.banners.deleteMessage', { title: pendingDelete?.title || pendingDelete?.text || '' })}
</p>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setPendingDelete(null)} data-testid="banner-delete-cancel">
@@ -96,6 +96,7 @@ export const offeringsHandlers = [
const created: OfferingBannerDto = {
id: crypto.randomUUID(),
...body,
position: body.position ?? 'bottom',
updatedAt: new Date().toISOString(),
};
mockBanners = [created, ...mockBanners];
@@ -1,9 +1,16 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { screen, waitFor } from '@testing-library/react';
import { screen, waitFor, within } 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 {
bannerStatus,
fromLocalInput,
isAllowedBannerLink,
offeringBannerFormSchema,
toLocalInput,
} from '@/features/offerings/schemas/offeringBanner';
import type { OfferingBannerDto } from '@/features/offerings/services/types';
import { _resetSetupStatusCache } from '@/router';
beforeEach(() => {
@@ -19,6 +26,19 @@ async function openBannerTab() {
await userEvent.click(await screen.findByTestId('offerings-tab-banner', {}, T));
}
const banner = (over: Partial<OfferingBannerDto> & { id: string }): OfferingBannerDto => ({
position: 'bottom',
title: 'Titel',
text: 'Tekst',
linkLabel: null,
linkUrl: null,
isActive: true,
startsAt: null,
endsAt: null,
updatedAt: '2026-01-01T00:00:00Z',
...over,
});
describe('Banner tab', () => {
it('switches between the offerings and the banner tab, hiding the add-offering actions on the banner tab', async () => {
mockAuthenticated();
@@ -35,11 +55,23 @@ describe('Banner tab', () => {
expect(await screen.findByTestId('offerings-add-button')).toBeInTheDocument();
});
it('shows an empty state, then creates a banner with a link and a schedule', async () => {
it('shows two sections (top and bottom), each with its own empty state and "nothing active" hint', async () => {
await openBannerTab();
expect(await screen.findByTestId('banners-empty', {}, T)).toBeInTheDocument();
const top = await screen.findByTestId('banners-section-top', {}, T);
const bottom = screen.getByTestId('banners-section-bottom');
expect(within(top).getByTestId('banners-empty-top')).toBeInTheDocument();
expect(within(bottom).getByTestId('banners-empty-bottom')).toBeInTheDocument();
expect(within(top).getByTestId('banner-add-top')).toBeInTheDocument();
expect(within(bottom).getByTestId('banner-add-bottom')).toBeInTheDocument();
expect(screen.getByTestId('banner-live-hint-top')).toHaveTextContent(/niets actief|Nothing is active/);
expect(screen.getByTestId('banner-live-hint-bottom')).toHaveTextContent(/niets actief|Nothing is active/);
});
await userEvent.click(screen.getByTestId('banner-add-button'));
it('creates a bottom banner with a link and a schedule, sending position bottom', async () => {
await openBannerTab();
expect(await screen.findByTestId('banners-empty-bottom', {}, T)).toBeInTheDocument();
await userEvent.click(screen.getByTestId('banner-add-bottom'));
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');
@@ -50,15 +82,50 @@ describe('Banner tab', () => {
await waitFor(() => expect(getMockBanners()).toHaveLength(1));
const saved = getMockBanners()[0];
expect(saved).toMatchObject({ title: 'Zomeractie', linkLabel: 'Bekijk', linkUrl: '/privacy', isActive: true });
expect(saved).toMatchObject({
position: 'bottom',
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/);
expect(within(screen.getByTestId('banners-section-bottom')).getByTestId(`banner-status-${saved.id}`)).toHaveTextContent(
/Gepland|Scheduled/,
);
expect(screen.getByTestId('banners-empty-top')).toBeInTheDocument();
});
it('requires a title for a bottom banner', async () => {
await openBannerTab();
await userEvent.click(await screen.findByTestId('banner-add-bottom', {}, T));
await userEvent.type(await screen.findByTestId('banner-text'), 'Alleen tekst');
await userEvent.click(screen.getByTestId('banner-submit'));
expect(await screen.findByTestId('banner-title-error')).toBeInTheDocument();
expect(getMockBanners()).toHaveLength(0);
});
it('creates a top banner without a title, limited to 120 characters with a counter', async () => {
await openBannerTab();
await userEvent.click(await screen.findByTestId('banner-add-top', {}, T));
expect(await screen.findByTestId('banner-text')).toHaveAttribute('maxlength', '120');
expect(screen.getByTestId('banner-text-counter')).toHaveTextContent('0/120');
await userEvent.type(screen.getByTestId('banner-text'), 'Gratis verzending deze week');
expect(screen.getByTestId('banner-text-counter')).toHaveTextContent('27/120');
await userEvent.click(screen.getByTestId('banner-submit'));
await waitFor(() => expect(getMockBanners()).toHaveLength(1));
expect(getMockBanners()[0]).toMatchObject({ position: 'top', title: '', text: 'Gratis verzending deze week' });
const top = screen.getByTestId('banners-section-top');
expect(await within(top).findByText('Gratis verzending deze week')).toBeInTheDocument();
expect(screen.getByTestId('banners-empty-bottom')).toBeInTheDocument();
});
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.click(await screen.findByTestId('banner-add-bottom', {}, T));
await userEvent.type(await screen.findByTestId('banner-title'), 'X');
await userEvent.type(screen.getByTestId('banner-text'), 'Y');
@@ -81,14 +148,43 @@ describe('Banner tab', () => {
expect(getMockBanners()).toHaveLength(0);
});
it('edits and deletes an existing banner', async () => {
it('lists banners under their own position and shows which one is live (most recently changed wins)', async () => {
setMockBanners([
{
id: 'b1', title: 'Oud', text: 'Tekst', linkLabel: null, linkUrl: null, isActive: true,
startsAt: null, endsAt: null, updatedAt: '2026-01-01T00:00:00Z',
},
banner({ id: 'b-old', title: 'Oud', updatedAt: '2026-01-01T00:00:00Z' }),
banner({ id: 'b-new', title: 'Nieuw', updatedAt: '2026-02-01T00:00:00Z' }),
banner({ id: 't1', position: 'top', title: '', text: 'Balktekst' }),
]);
await openBannerTab();
const top = await screen.findByTestId('banners-section-top', {}, T);
const bottom = screen.getByTestId('banners-section-bottom');
expect(within(top).getByTestId('banner-row-t1')).toBeInTheDocument();
expect(within(top).queryByTestId('banner-row-b-new')).not.toBeInTheDocument();
expect(within(bottom).getByTestId('banner-row-b-old')).toBeInTheDocument();
expect(within(bottom).getByTestId('banner-row-b-new')).toBeInTheDocument();
expect(screen.getByTestId('banner-live-hint-bottom')).toHaveTextContent(/Nu live: Nieuw|Live now: Nieuw/);
expect(screen.getByTestId('banner-live-hint-top')).toHaveTextContent(/Balktekst/);
});
it('turns a banner off and on from its section', async () => {
setMockBanners([banner({ id: 't1', position: 'top', title: '', text: 'Balktekst' })]);
await openBannerTab();
expect(await screen.findByTestId('banner-status-t1', {}, T)).toHaveTextContent(/Actief|Active/);
await userEvent.click(screen.getByTestId('banner-toggle-t1'));
await waitFor(() => expect(getMockBanners()[0].isActive).toBe(false));
expect(getMockBanners()[0].position).toBe('top');
expect(await screen.findByTestId('banner-status-t1')).toHaveTextContent(/Uit|Off/);
expect(screen.getByTestId('banner-live-hint-top')).toHaveTextContent(/niets actief|Nothing is active/);
await userEvent.click(screen.getByTestId('banner-toggle-t1'));
await waitFor(() => expect(getMockBanners()[0].isActive).toBe(true));
});
it('edits and deletes an existing banner, keeping its position', async () => {
setMockBanners([banner({ id: 'b1', title: 'Oud' })]);
await openBannerTab();
expect(await screen.findByTestId('banner-status-b1', {}, T)).toHaveTextContent(/Actief|Active/);
await userEvent.click(screen.getByTestId('banner-edit-b1'));
@@ -98,14 +194,46 @@ describe('Banner tab', () => {
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 }));
await waitFor(() => expect(getMockBanners()[0]).toMatchObject({ title: 'Nieuw', isActive: false, position: 'bottom' }));
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();
expect(await screen.findByTestId('banners-empty-bottom')).toBeInTheDocument();
});
});
describe('banner form schema', () => {
const base = {
position: 'bottom' as const,
title: 'T',
text: 'X',
linkLabel: '',
linkUrl: '',
isActive: true,
startsAt: '',
endsAt: '',
};
const fieldErrors = (v: object) => {
const r = offeringBannerFormSchema.safeParse(v);
return r.success ? [] : r.error.issues.map((i) => i.path[0]);
};
it('bottom: title required, text up to 300', () => {
expect(fieldErrors(base)).toEqual([]);
expect(fieldErrors({ ...base, title: '' })).toContain('title');
expect(fieldErrors({ ...base, text: 'x'.repeat(300) })).toEqual([]);
expect(fieldErrors({ ...base, text: 'x'.repeat(301) })).toContain('text');
});
it('top: title optional, text up to 120', () => {
const top = { ...base, position: 'top' as const, title: '' };
expect(fieldErrors(top)).toEqual([]);
expect(fieldErrors({ ...top, text: 'x'.repeat(120) })).toEqual([]);
expect(fieldErrors({ ...top, text: 'x'.repeat(121) })).toContain('text');
expect(fieldErrors({ ...top, text: '' })).toContain('text');
});
});
@@ -1,4 +1,5 @@
import { z } from 'zod';
import type { BannerPosition } from '../services/types';
/** https:// address or a site path with a single leading slash; mirrors the API rule. */
export function isAllowedBannerLink(url: string): boolean {
@@ -12,10 +13,19 @@ export function isAllowedBannerLink(url: string): boolean {
}
}
export const BANNER_TOP_TEXT_MAX = 120;
export const BANNER_BOTTOM_TEXT_MAX = 300;
export const bannerTextMaxLength = (position: BannerPosition) =>
position === 'top' ? BANNER_TOP_TEXT_MAX : BANNER_BOTTOM_TEXT_MAX;
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'),
position: z.enum(['top', 'bottom']),
/** Required for 'bottom', optional for 'top' (checked in superRefine). */
title: z.string().trim().max(100, 'Title must be 100 characters or fewer'),
/** Max length depends on the position (checked in superRefine). */
text: z.string().trim().min(1, 'Text is required'),
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(),
@@ -24,6 +34,13 @@ export const offeringBannerFormSchema = z
endsAt: z.string(),
})
.superRefine((v, ctx) => {
if (v.position === 'bottom' && v.title === '') {
ctx.addIssue({ code: 'custom', path: ['title'], message: 'Title is required' });
}
const maxText = bannerTextMaxLength(v.position);
if (v.text.length > maxText) {
ctx.addIssue({ code: 'custom', path: ['text'], message: `Text must be ${maxText} characters or fewer` });
}
const hasLabel = v.linkLabel !== '';
const hasUrl = v.linkUrl !== '';
if (hasLabel !== hasUrl) {
@@ -40,8 +40,11 @@ export interface OfferingCategoryDto {
export type MoveDirection = 'up' | 'down';
export type BannerPosition = 'top' | 'bottom';
export interface OfferingBannerDto {
id: string;
position: BannerPosition;
title: string;
text: string;
linkLabel: string | null;
@@ -55,6 +58,7 @@ export interface OfferingBannerDto {
}
export interface OfferingBannerRequest {
position: BannerPosition;
title: string;
text: string;
linkLabel: string | null;
+23 -1
View File
@@ -325,7 +325,29 @@
"title": "Offerings",
"addButton": "Add Offering",
"banners": {
"intro": "A banner is a wide announcement or promotion on the website. Plan ahead with a start and end time; at most one banner is shown at any time.",
"intro": "A banner is a wide announcement or promotion on the website. Plan ahead with a start and end time. At most one banner is shown per spot (top and bottom) at any time: the most recently changed active one.",
"section": {
"top": {
"title": "Top",
"description": "Narrow bar at the top of the website, one line of text.",
"addButton": "Add top banner"
},
"bottom": {
"title": "Bottom",
"description": "Large banner at the bottom of the page with title, text and button.",
"addButton": "Add bottom banner"
}
},
"liveNow": "Live now: {{title}}",
"nothingActive": "Nothing is active in this spot right now.",
"turnOffButton": "Turn banner off",
"turnOnButton": "Turn banner on",
"createTitle_top": "New banner (top)",
"createTitle_bottom": "New banner (bottom)",
"editTitle_top": "Edit banner (top)",
"editTitle_bottom": "Edit banner (bottom)",
"titleLabelOptional": "Title (optional)",
"textHintTop": "One short line, up to 120 characters.",
"addButton": "Add banner",
"empty": "No banners yet.",
"editButton": "Edit banner",
+23 -1
View File
@@ -325,7 +325,29 @@
"title": "Aanbiedingen",
"addButton": "Aanbieding toevoegen",
"banners": {
"intro": "Een banner is een brede mededeling of actie op de website. Plan vooruit met een begin- en eindtijd; er wordt altijd maximaal één banner getoond.",
"intro": "Een banner is een brede mededeling of actie op de website. Plan vooruit met een begin- en eindtijd. Per plek (boven en onder) wordt altijd maximaal één banner getoond: de laatst gewijzigde actieve.",
"section": {
"top": {
"title": "Boven",
"description": "Smalle balk bovenaan de website, één regel tekst.",
"addButton": "Banner boven toevoegen"
},
"bottom": {
"title": "Onder",
"description": "Grote banner onderaan de pagina met titel, tekst en knop.",
"addButton": "Banner onder toevoegen"
}
},
"liveNow": "Nu live: {{title}}",
"nothingActive": "Er is nu niets actief op deze plek.",
"turnOffButton": "Banner uitzetten",
"turnOnButton": "Banner aanzetten",
"createTitle_top": "Nieuwe banner (boven)",
"createTitle_bottom": "Nieuwe banner (onder)",
"editTitle_top": "Banner bewerken (boven)",
"editTitle_bottom": "Banner bewerken (onder)",
"titleLabelOptional": "Titel (optioneel)",
"textHintTop": "Eén korte regel, maximaal 120 tekens.",
"addButton": "Banner toevoegen",
"empty": "Nog geen banners.",
"editButton": "Banner bewerken",
+13
View File
@@ -554,6 +554,10 @@
"string"
]
},
"position": {
"default": "bottom",
"type": "string"
},
"startsAt": {
"format": "date-time",
"type": [
@@ -2258,6 +2262,15 @@
},
"/api/v1/offerings/banner": {
"get": {
"parameters": [
{
"in": "query",
"name": "position",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK"
@@ -48,6 +48,11 @@ public class HostPipelineTests : IClassFixture<AsfWebApplicationFactory>
var banner = await client.GetAsync("/api/v1/offerings/banner");
banner.StatusCode.Should().Be(HttpStatusCode.NoContent);
// Position: top works the same, no parameter means bottom, anything else is rejected.
(await client.GetAsync("/api/v1/offerings/banner?position=top")).StatusCode.Should().Be(HttpStatusCode.NoContent);
(await client.GetAsync("/api/v1/offerings/banner?position=bottom")).StatusCode.Should().Be(HttpStatusCode.NoContent);
(await client.GetAsync("/api/v1/offerings/banner?position=left")).StatusCode.Should().Be(HttpStatusCode.BadRequest);
(await client.GetAsync("/api/v1/offerings")).StatusCode.Should().Be(HttpStatusCode.OK);
(await client.GetAsync("/api/v1/offerings/banners")).StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}
@@ -28,9 +28,9 @@ public class OfferingBannersServiceTests
new(_repo, Substitute.For<ILogger<OfferingBannersService>>(), _time, _cache);
private static OfferingBanner Banner(string title, bool active = true, DateTimeOffset? from = null, DateTimeOffset? to = null,
DateTimeOffset? updated = null) => new()
DateTimeOffset? updated = null, string position = "bottom") => new()
{
Id = Guid.NewGuid(), Title = title, Text = "Tekst", IsActive = active, StartsAt = from, EndsAt = to,
Id = Guid.NewGuid(), Position = position, Title = title, Text = "Tekst", IsActive = active, StartsAt = from, EndsAt = to,
UpdatedAt = updated ?? Now.AddDays(-1),
};
@@ -40,7 +40,7 @@ public class OfferingBannersServiceTests
public async Task GetActive_ReturnsNull_WhenNothingIsSwitchedOn()
{
Switched();
(await Sut().GetActiveAsync()).Should().BeNull();
(await Sut().GetActiveAsync("bottom")).Should().BeNull();
}
[Fact]
@@ -51,9 +51,9 @@ public class OfferingBannersServiceTests
banner.LinkUrl = "/aanbieding";
Switched(banner);
var result = await Sut().GetActiveAsync();
var result = await Sut().GetActiveAsync("bottom");
result.Should().Be(new PublicOfferingBannerDto("Actie", "Tekst", "Bekijk", "/aanbieding"));
result.Should().Be(new PublicOfferingBannerDto("Actie", "Tekst", "Bekijk", "/aanbieding", "bottom"));
}
[Fact]
@@ -64,24 +64,24 @@ public class OfferingBannersServiceTests
Banner("past", to: Now.AddHours(-1)),
Banner("ended-exactly-now", to: Now));
(await Sut().GetActiveAsync()).Should().BeNull();
(await Sut().GetActiveAsync("bottom")).Should().BeNull();
_time.Advance(TimeSpan.FromHours(2));
(await Sut().GetActiveAsync())!.Title.Should().Be("future");
(await Sut().GetActiveAsync("bottom"))!.Title.Should().Be("future");
}
[Fact]
public async Task GetActive_StartsInclusive()
{
Switched(Banner("now", from: Now));
(await Sut().GetActiveAsync())!.Title.Should().Be("now");
(await Sut().GetActiveAsync("bottom"))!.Title.Should().Be("now");
}
[Fact]
public async Task GetActive_PicksTheMostRecentlyChanged_WhenSeveralQualify()
{
Switched(Banner("old", updated: Now.AddDays(-5)), Banner("new", updated: Now.AddDays(-1)));
(await Sut().GetActiveAsync())!.Title.Should().Be("new");
(await Sut().GetActiveAsync("bottom"))!.Title.Should().Be("new");
}
[Fact]
@@ -176,12 +176,79 @@ public class OfferingBannersServiceTests
maxLength.Length.Should().Be(max);
}
[Theory]
[InlineData("Title")]
[InlineData("Text")]
public void TitleAndText_AreRequired(string name)
[Fact]
public async Task GetActive_FiltersOnPosition_SoTopAndBottomCanBeActiveAtTheSameTime()
{
var parameter = typeof(OfferingBannerRequest).GetConstructors()[0].GetParameters().Single(p => p.Name == name);
Switched(Banner("beneden", position: "bottom"), Banner("boven", position: "top"));
var top = await Sut().GetActiveAsync("top");
var bottom = await Sut().GetActiveAsync("bottom");
top.Should().Be(new PublicOfferingBannerDto("boven", "Tekst", null, null, "top"));
bottom!.Title.Should().Be("beneden");
bottom.Position.Should().Be("bottom");
}
[Fact]
public async Task GetActive_MaxOnePerPosition_MostRecentlyChangedWinsWithinThePosition()
{
Switched(
Banner("top-old", updated: Now.AddDays(-5), position: "top"),
Banner("top-new", updated: Now.AddDays(-1), position: "top"),
Banner("bottom-newest", updated: Now, position: "bottom"));
(await Sut().GetActiveAsync("top"))!.Title.Should().Be("top-new");
}
[Fact]
public async Task GetActive_ScheduleAppliesPerPosition()
{
Switched(Banner("top-future", from: Now.AddHours(1), position: "top"), Banner("bottom-now"));
(await Sut().GetActiveAsync("top")).Should().BeNull();
(await Sut().GetActiveAsync("bottom"))!.Title.Should().Be("bottom-now");
}
[Fact]
public async Task Create_StoresThePosition_AndAllowsAnEmptyTitleOnTop()
{
OfferingBanner? saved = null;
await _repo.AddAsync(Arg.Do<OfferingBanner>(b => saved = b));
var dto = await Sut().CreateAsync(new OfferingBannerRequest("", "Korte tekst", Position: "top"), Guid.NewGuid());
saved!.Position.Should().Be("top");
saved.Title.Should().BeEmpty();
dto.Position.Should().Be("top");
}
[Fact]
public void Position_DefaultsToBottom_AndOnlyTopAndBottomAreValid()
{
new OfferingBannerRequest("T", "X").Position.Should().Be("bottom");
Validate(new OfferingBannerRequest("T", "X", Position: "top")).Should().BeEmpty();
Validate(new OfferingBannerRequest("T", "X", Position: "left")).Should().HaveCount(1);
Validate(new OfferingBannerRequest("T", "X", Position: "")).Should().HaveCount(1);
}
[Fact]
public void Top_TextIsLimitedTo120_TitleMayBeEmpty()
{
Validate(new OfferingBannerRequest("", new string('a', 120), Position: "top")).Should().BeEmpty();
Validate(new OfferingBannerRequest("", new string('a', 121), Position: "top")).Should().HaveCount(1);
Validate(new OfferingBannerRequest("T", new string('a', 300), Position: "bottom")).Should().BeEmpty();
}
[Theory]
[InlineData("")]
[InlineData(" ")]
public void Bottom_NeedsATitle(string title)
=> Validate(new OfferingBannerRequest(title, "X", Position: "bottom")).Should().HaveCount(1);
[Fact]
public void Text_IsRequired()
{
var parameter = typeof(OfferingBannerRequest).GetConstructors()[0].GetParameters().Single(p => p.Name == "Text");
var required = (RequiredAttribute)parameter.GetCustomAttributes(typeof(RequiredAttribute), false).Single();
required.IsValid("").Should().BeFalse();
@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using SlpModularCms.Core.Availability;
using SlpModularCms.Modules.Offerings.Data.Entities;
using SlpModularCms.Modules.Offerings.Models;
using SlpModularCms.Modules.Offerings.Services;
@@ -42,7 +43,10 @@ public class OfferingBannersController(IOfferingBannersService service) : Contro
}
}
/// <summary>The banner visitors see: 200 with the one active banner, otherwise 204.</summary>
/// <summary>
/// The banner visitors see at a position (<c>?position=top|bottom</c>, default bottom):
/// 200 with the one active banner, 204 when none, 400 for an unknown position.
/// </summary>
[ApiController]
[Route("offerings/banner")]
public class PublicOfferingBannerController(IOfferingBannersService service) : ControllerBase
@@ -51,10 +55,14 @@ public class PublicOfferingBannerController(IOfferingBannersService service) : C
[AllowAnonymous]
[PublicSiteEndpoint]
[EnableRateLimiting("offerings-public")]
public async Task<IActionResult> Get()
public async Task<IActionResult> Get([FromQuery] string? position = null)
{
position = string.IsNullOrEmpty(position) ? OfferingBannerPositions.Bottom : position;
if (!OfferingBannerPositions.IsValid(position))
return BadRequest(new { error = "Position must be 'top' or 'bottom'." });
Response.Headers.CacheControl = "public, max-age=60";
var current = await service.GetActiveAsync();
var current = await service.GetActiveAsync(position);
return current is null ? NoContent() : Ok(current);
}
}
@@ -1,5 +1,19 @@
namespace SlpModularCms.Modules.Offerings.Data.Entities;
/// <summary>The two places a banner can be shown.</summary>
public static class OfferingBannerPositions
{
/// <summary>Narrow bar above the page, one line.</summary>
public const string Top = "top";
/// <summary>Large banner; also the default for banners that existed before positions did.</summary>
public const string Bottom = "bottom";
public const int TopTextMaxLength = 120;
public static bool IsValid(string? position) => position is Top or Bottom;
}
/// <summary>
/// A site-wide banner for offers and campaigns. Several can be stored (for example
/// planned ones with a start and end); the public API shows the one that is active right now.
@@ -7,6 +21,10 @@ namespace SlpModularCms.Modules.Offerings.Data.Entities;
public class OfferingBanner
{
public Guid Id { get; set; }
/// <summary>Where the banner is shown: see <see cref="OfferingBannerPositions"/>.</summary>
public string Position { get; set; } = OfferingBannerPositions.Bottom;
/// <summary>Required for a bottom banner; may be empty for a top banner.</summary>
public string Title { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty;
@@ -58,6 +58,7 @@ public class OfferingsDbContext(DbContextOptions<OfferingsDbContext> options) :
{
entity.ToTable("OfferingsBanners");
entity.HasKey(e => e.Id);
entity.Property(e => e.Position).IsRequired().HasMaxLength(10).HasDefaultValue(OfferingBannerPositions.Bottom);
entity.Property(e => e.Title).IsRequired().HasMaxLength(100);
entity.Property(e => e.Text).IsRequired().HasMaxLength(300);
entity.Property(e => e.LinkLabel).HasMaxLength(50);
@@ -0,0 +1,189 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SlpModularCms.Modules.Offerings.Data;
#nullable disable
namespace SlpModularCms.Modules.Offerings.Migrations
{
[DbContext(typeof(OfferingsDbContext))]
[Migration("20261114100000_AddOfferingBannerPosition")]
partial class AddOfferingBannerPosition
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.9")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.OfferingBanner", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime");
b.Property<DateTimeOffset?>("EndsAt")
.HasColumnType("datetime");
b.Property<bool>("IsActive")
.HasColumnType("tinyint(1)");
b.Property<Guid>("LastModifiedByUserId")
.HasColumnType("char(36)");
b.Property<string>("LinkLabel")
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<string>("LinkUrl")
.HasMaxLength(500)
.HasColumnType("varchar(500)");
b.Property<DateTimeOffset?>("StartsAt")
.HasColumnType("datetime");
b.Property<string>("Position")
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(10)
.HasColumnType("varchar(10)")
.HasDefaultValue("bottom");
b.Property<string>("Text")
.IsRequired()
.HasMaxLength(300)
.HasColumnType("varchar(300)");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("datetime");
b.HasKey("Id");
b.ToTable("OfferingsBanners", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.Offering", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<Guid?>("CategoryId")
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime");
b.Property<string>("CtaLabel")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<DateTimeOffset?>("DeletedAt")
.HasColumnType("datetime");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("varchar(500)");
b.Property<int>("DisplayOrder")
.HasColumnType("int");
b.Property<bool>("Featured")
.HasColumnType("tinyint(1)");
b.Property<string>("Features")
.IsRequired()
.HasColumnType("longtext");
b.Property<bool>("IsDeleted")
.HasColumnType("tinyint(1)");
b.Property<Guid>("LastModifiedByUserId")
.HasColumnType("char(36)");
b.Property<string>("Price")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<string>("PriceNote")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("Slug")
.IsRequired()
.HasMaxLength(130)
.HasColumnType("varchar(130)");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("datetime");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.ToTable("OfferingsOfferings", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.OfferingCategory", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<int>("SortOrder")
.HasColumnType("int");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("datetime");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("OfferingsCategories", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.Offering", b =>
{
b.HasOne("SlpModularCms.Modules.Offerings.Data.Entities.OfferingCategory", "Category")
.WithMany()
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Restrict);
b.Navigation("Category");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,31 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SlpModularCms.Modules.Offerings.Migrations
{
/// <inheritdoc />
public partial class AddOfferingBannerPosition : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
// Existing banners were the large one: they become 'bottom'.
migrationBuilder.AddColumn<string>(
name: "Position",
table: "OfferingsBanners",
type: "varchar(10)",
maxLength: 10,
nullable: false,
defaultValue: "bottom");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Position",
table: "OfferingsBanners");
}
}
}
@@ -48,6 +48,13 @@ namespace SlpModularCms.Modules.Offerings.Migrations
b.Property<DateTimeOffset?>("StartsAt")
.HasColumnType("datetime");
b.Property<string>("Position")
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(10)
.HasColumnType("varchar(10)")
.HasDefaultValue("bottom");
b.Property<string>("Text")
.IsRequired()
.HasMaxLength(300)
@@ -1,5 +1,6 @@
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using SlpModularCms.Modules.Offerings.Data.Entities;
namespace SlpModularCms.Modules.Offerings.Models;
@@ -7,6 +8,7 @@ namespace SlpModularCms.Modules.Offerings.Models;
[ExcludeFromCodeCoverage]
public record OfferingBannerDto(
string Id,
string Position,
string Title,
string Text,
string? LinkLabel,
@@ -18,20 +20,31 @@ public record OfferingBannerDto(
/// <summary>What visitors get: only the content to show, never the scheduling.</summary>
[ExcludeFromCodeCoverage]
public record PublicOfferingBannerDto(string Title, string Text, string? LinkLabel, string? LinkUrl);
public record PublicOfferingBannerDto(string Title, string Text, string? LinkLabel, string? LinkUrl, string Position);
/// <summary>Create and full-replace (PUT) body. Empty link fields are stored as null.</summary>
public record OfferingBannerRequest(
[Required, MaxLength(100)] string Title,
[MaxLength(100)] string Title,
[Required, MaxLength(300)] string Text,
[MaxLength(50)] string? LinkLabel = null,
[MaxLength(500)] string? LinkUrl = null,
bool IsActive = true,
DateTimeOffset? StartsAt = null,
DateTimeOffset? EndsAt = null) : IValidatableObject
DateTimeOffset? EndsAt = null,
string Position = OfferingBannerPositions.Bottom) : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (!OfferingBannerPositions.IsValid(Position))
yield return new ValidationResult("Position must be 'top' or 'bottom'.", [nameof(Position)]);
else if (Position == OfferingBannerPositions.Top)
{
if (Text?.Trim().Length > OfferingBannerPositions.TopTextMaxLength)
yield return new ValidationResult($"A top banner text can be at most {OfferingBannerPositions.TopTextMaxLength} characters.", [nameof(Text)]);
}
else if (string.IsNullOrWhiteSpace(Title))
yield return new ValidationResult("A bottom banner needs a title.", [nameof(Title)]);
var hasLabel = !string.IsNullOrWhiteSpace(LinkLabel);
var hasUrl = !string.IsNullOrWhiteSpace(LinkUrl);
@@ -10,8 +10,8 @@ public interface IOfferingBannersService
{
Task<IReadOnlyList<OfferingBannerDto>> ListAsync();
/// <summary>The one banner that is switched on and inside its schedule right now, or null.</summary>
Task<PublicOfferingBannerDto?> GetActiveAsync();
/// <summary>The one banner at <paramref name="position"/> that is switched on and inside its schedule right now, or null.</summary>
Task<PublicOfferingBannerDto?> GetActiveAsync(string position);
Task<OfferingBannerDto> CreateAsync(OfferingBannerRequest request, Guid callerId);
Task<OfferingBannerDto?> UpdateAsync(Guid id, OfferingBannerRequest request, Guid callerId);
@@ -29,17 +29,19 @@ public class OfferingBannersService(
public async Task<IReadOnlyList<OfferingBannerDto>> ListAsync()
=> (await repository.GetAllAsync()).Select(ToDto).ToList();
public async Task<PublicOfferingBannerDto?> GetActiveAsync()
public async Task<PublicOfferingBannerDto?> GetActiveAsync(string position)
{
var now = _time.GetUtcNow();
// Several can be switched on (planned ones, overlaps); the most recently changed wins.
// Several can be switched on (planned ones, overlaps); per position the most recently changed wins,
// so a top and a bottom banner can be shown at the same time.
var current = (await repository.GetSwitchedOnAsync())
.Where(b => b.Position == position)
.Where(b => (b.StartsAt is null || b.StartsAt <= now) && (b.EndsAt is null || now < b.EndsAt))
.OrderByDescending(b => b.UpdatedAt)
.FirstOrDefault();
return current is null ? null : new PublicOfferingBannerDto(current.Title, current.Text, current.LinkLabel, current.LinkUrl);
return current is null ? null : new PublicOfferingBannerDto(current.Title, current.Text, current.LinkLabel, current.LinkUrl, current.Position);
}
public async Task<OfferingBannerDto> CreateAsync(OfferingBannerRequest request, Guid callerId)
@@ -83,7 +85,8 @@ public class OfferingBannersService(
private static void Apply(OfferingBanner b, OfferingBannerRequest r, DateTimeOffset now, Guid callerId)
{
var hasLink = !string.IsNullOrWhiteSpace(r.LinkUrl) && !string.IsNullOrWhiteSpace(r.LinkLabel);
b.Title = r.Title.Trim();
b.Position = r.Position;
b.Title = (r.Title ?? string.Empty).Trim();
b.Text = r.Text.Trim();
b.LinkLabel = hasLink ? r.LinkLabel!.Trim() : null;
b.LinkUrl = hasLink ? r.LinkUrl!.Trim() : null;
@@ -101,5 +104,5 @@ public class OfferingBannersService(
}
private static OfferingBannerDto ToDto(OfferingBanner b) => new(
b.Id.ToString(), b.Title, b.Text, b.LinkLabel, b.LinkUrl, b.IsActive, b.StartsAt, b.EndsAt, b.UpdatedAt);
b.Id.ToString(), b.Position, b.Title, b.Text, b.LinkLabel, b.LinkUrl, b.IsActive, b.StartsAt, b.EndsAt, b.UpdatedAt);
}