Aanbiedingen: planning en aan/uit per pakket, admin-lijst /offerings/all, Annuleren op het pakketformulier

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 11:42:26 +01:00
co-authored by Claude Sonnet 5.5
parent 321234dfa6
commit 8af156c238
29 changed files with 916 additions and 73 deletions
@@ -11,15 +11,18 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
import { useOfferingCategories } from '../services/useOfferingCategories'; import { useOfferingCategories } from '../services/useOfferingCategories';
import { slugifyPreview } from '@/lib/slugify'; import { slugifyPreview } from '@/lib/slugify';
import { offeringFormSchema, type OfferingFormData } from '../schemas/offering'; import { offeringFormSchema, type OfferingFormData } from '../schemas/offering';
import { toLocalInput } from '../schemas/offeringBanner';
import type { OfferingDto } from '../services/types'; import type { OfferingDto } from '../services/types';
interface OfferingFormProps { interface OfferingFormProps {
initialValues?: OfferingDto; initialValues?: OfferingDto;
onSubmit: (values: OfferingFormData) => void; onSubmit: (values: OfferingFormData) => void;
/** Leaves the form without saving (back to the list). */
onCancel: () => void;
isSubmitting: boolean; isSubmitting: boolean;
} }
export function OfferingForm({ initialValues, onSubmit, isSubmitting }: OfferingFormProps) { export function OfferingForm({ initialValues, onSubmit, onCancel, isSubmitting }: OfferingFormProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const { const {
@@ -32,7 +35,14 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering
} = useForm<OfferingFormData>({ } = useForm<OfferingFormData>({
resolver: zodResolver(offeringFormSchema), resolver: zodResolver(offeringFormSchema),
mode: 'onTouched', mode: 'onTouched',
defaultValues: initialValues ?? { defaultValues: initialValues
? {
...initialValues,
isActive: initialValues.isActive ?? true,
startsAt: toLocalInput(initialValues.startsAt ?? null),
endsAt: toLocalInput(initialValues.endsAt ?? null),
}
: {
title: '', title: '',
description: '', description: '',
price: '', price: '',
@@ -42,6 +52,9 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering
featured: false, featured: false,
slug: '', slug: '',
categoryId: null, categoryId: null,
isActive: true,
startsAt: '',
endsAt: '',
}, },
}); });
@@ -291,9 +304,45 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering
<Label htmlFor="offering-featured">{t('offerings.form.featuredLabel')}</Label> <Label htmlFor="offering-featured">{t('offerings.form.featuredLabel')}</Label>
</div> </div>
<div className="space-y-3 rounded-md border p-3" data-testid="offering-schedule">
<div className="flex items-center gap-2">
<input
id="offering-active"
type="checkbox"
data-testid="offering-active"
className="size-4 rounded border-input"
{...register('isActive')}
/>
<Label htmlFor="offering-active">{t('offerings.form.activeLabel')}</Label>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="offering-starts">{t('offerings.form.startsLabel')}</Label>
<Input id="offering-starts" type="datetime-local" data-testid="offering-starts" {...register('startsAt')} />
</div>
<div className="space-y-2">
<Label htmlFor="offering-ends">{t('offerings.form.endsLabel')}</Label>
<Input
id="offering-ends"
type="datetime-local"
data-testid="offering-ends"
aria-invalid={errors.endsAt !== undefined}
{...register('endsAt')}
/>
{errors.endsAt && <FieldError message={t('offerings.form.endBeforeStart')} testId="offering-ends-error" />}
</div>
</div>
<p className="text-xs text-muted-foreground">{t('offerings.form.scheduleHint')}</p>
</div>
<div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
<Button type="button" variant="outline" onClick={onCancel} disabled={isSubmitting} data-testid="offering-form-cancel">
{t('common.cancel')}
</Button>
<Button type="submit" disabled={isSubmitting} data-testid="offering-form-submit"> <Button type="submit" disabled={isSubmitting} data-testid="offering-form-submit">
{isSubmitting ? '…' : t('offerings.form.submitButton')} {isSubmitting ? '…' : t('offerings.form.submitButton')}
</Button> </Button>
</div>
</form> </form>
); );
} }
@@ -1,15 +1,21 @@
import { useSortable } from '@dnd-kit/sortable'; import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities'; import { CSS } from '@dnd-kit/utilities';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { GripVertical, Star, ChevronUp, ChevronDown, Pencil, Trash2 } from 'lucide-react'; import { GripVertical, Star, ChevronUp, ChevronDown, Pencil, Power, Trash2 } from 'lucide-react';
import { Link } from '@tanstack/react-router'; import { Link } from '@tanstack/react-router';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { TableCell, TableRow } from '@/components/ui/table'; import { TableCell, TableRow } from '@/components/ui/table';
import { useUpdateOffering } from '../services/useUpdateOffering'; import { useUpdateOffering } from '../services/useUpdateOffering';
import { useMoveOffering } from '../services/useMoveOffering'; import { useMoveOffering } from '../services/useMoveOffering';
import { scheduleStatus } from '../schemas/offeringBanner';
import type { OfferingDto } from '../services/types'; import type { OfferingDto } from '../services/types';
const fmt = (iso: string | null) =>
iso ? new Date(iso).toLocaleString('nl-NL', { dateStyle: 'short', timeStyle: 'short' }) : null;
const statusVariant = { live: 'default', scheduled: 'secondary', expired: 'outline', off: 'outline' } as const;
interface OfferingRowProps { interface OfferingRowProps {
offering: OfferingDto; offering: OfferingDto;
isFirst: boolean; isFirst: boolean;
@@ -23,6 +29,26 @@ export function OfferingRow({ offering, isFirst, isLast, onDeleteRequested }: Of
const updateOffering = useUpdateOffering(); const updateOffering = useUpdateOffering();
const moveUp = useMoveOffering('up'); const moveUp = useMoveOffering('up');
const moveDown = useMoveOffering('down'); const moveDown = useMoveOffering('down');
const status = scheduleStatus(offering);
// PUT replaces the whole offering: everything that is not changed has to be sent along, the
// switch and the schedule included, or a click on the star or the power button would reset them.
const fullBody = {
id: offering.id,
title: offering.title,
description: offering.description,
price: offering.price,
priceNote: offering.priceNote,
features: offering.features,
ctaLabel: offering.ctaLabel,
// Leaving the category out would clear it.
categoryId: offering.categoryId ?? null,
featured: offering.featured,
isActive: offering.isActive,
startsAt: offering.startsAt,
endsAt: offering.endsAt,
};
const toggleLabel = t(offering.isActive ? 'offerings.actions.turnOff' : 'offerings.actions.turnOn');
// The moving visual is rendered by <DragOverlay> instead (see OfferingsList) — a portal // The moving visual is rendered by <DragOverlay> instead (see OfferingsList) — a portal
// outside the document flow, so it can't grow the page's scrollable area the way // outside the document flow, so it can't grow the page's scrollable area the way
@@ -53,6 +79,19 @@ export function OfferingRow({ offering, isFirst, isLast, onDeleteRequested }: Of
{offering.category} {offering.category}
</Badge> </Badge>
)} )}
<div className="mt-1 flex flex-wrap items-center gap-2">
<Badge variant={statusVariant[status]} data-testid={`offering-row-${offering.id}-status`}>
{t(`offerings.banners.status.${status}`)}
</Badge>
{status === 'live' && (
<Badge data-testid={`offering-row-${offering.id}-shown`}>{t('offerings.banners.shownBadge')}</Badge>
)}
{(offering.startsAt || offering.endsAt) && (
<span className="text-xs text-muted-foreground" data-testid={`offering-row-${offering.id}-period`}>
{fmt(offering.startsAt) ?? '…'} – {fmt(offering.endsAt) ?? '…'}
</span>
)}
</div>
</TableCell> </TableCell>
<TableCell>{offering.price}</TableCell> <TableCell>{offering.price}</TableCell>
<TableCell> <TableCell>
@@ -61,20 +100,7 @@ export function OfferingRow({ offering, isFirst, isLast, onDeleteRequested }: Of
size="icon" size="icon"
data-testid={`offering-row-${offering.id}-featured-toggle`} data-testid={`offering-row-${offering.id}-featured-toggle`}
aria-label={offering.featured ? t('offerings.actions.unmarkFeatured') : t('offerings.actions.markFeatured')} aria-label={offering.featured ? t('offerings.actions.unmarkFeatured') : t('offerings.actions.markFeatured')}
onClick={() => onClick={() => updateOffering.mutate({ ...fullBody, featured: !offering.featured })}
updateOffering.mutate({
id: offering.id,
title: offering.title,
description: offering.description,
price: offering.price,
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,
})
}
> >
<Star className={`size-4 ${offering.featured ? 'fill-yellow-400 text-yellow-400' : ''}`} /> <Star className={`size-4 ${offering.featured ? 'fill-yellow-400 text-yellow-400' : ''}`} />
</Button> </Button>
@@ -101,6 +127,17 @@ export function OfferingRow({ offering, isFirst, isLast, onDeleteRequested }: Of
> >
<ChevronDown className="size-4" /> <ChevronDown className="size-4" />
</Button> </Button>
<Button
variant="ghost"
size="icon"
data-testid={`offering-row-${offering.id}-toggle-active`}
aria-label={toggleLabel}
title={toggleLabel}
disabled={updateOffering.isPending}
onClick={() => updateOffering.mutate({ ...fullBody, isActive: !offering.isActive })}
>
<Power className={`size-4 ${offering.isActive ? '' : 'text-muted-foreground'}`} aria-hidden="true" />
</Button>
<Button variant="ghost" size="icon" asChild data-testid={`offering-row-${offering.id}-edit-link`}> <Button variant="ghost" size="icon" asChild data-testid={`offering-row-${offering.id}-edit-link`}>
<Link to="/offerings/$id/edit" params={{ id: offering.id }} aria-label={t('offerings.actions.edit')}> <Link to="/offerings/$id/edit" params={{ id: offering.id }} aria-label={t('offerings.actions.edit')}>
<Pencil className="size-4" /> <Pencil className="size-4" />
@@ -30,6 +30,9 @@ const seed: OfferingDto[] = [
ctaLabel: 'Get started', ctaLabel: 'Get started',
featured: false, featured: false,
displayOrder: 0, displayOrder: 0,
isActive: true,
startsAt: null,
endsAt: null,
}, },
{ {
id: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', id: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
@@ -42,6 +45,9 @@ const seed: OfferingDto[] = [
ctaLabel: 'Get started', ctaLabel: 'Get started',
featured: true, featured: true,
displayOrder: 1, displayOrder: 1,
isActive: true,
startsAt: null,
endsAt: null,
}, },
]; ];
@@ -119,7 +125,23 @@ export const offeringsHandlers = [
return new HttpResponse(null, { status: 204 }); return new HttpResponse(null, { status: 204 });
}), }),
http.get(`${API_BASE}/api/v1/offerings`, () => HttpResponse.json(mockOfferings.map(withCategoryName))), // The administrator list: everything, including switched-off, planned and expired offerings.
http.get(`${API_BASE}/api/v1/offerings/all`, () => HttpResponse.json(mockOfferings.map(withCategoryName))),
// The public list: only what is switched on and inside its schedule.
http.get(`${API_BASE}/api/v1/offerings`, () => {
const now = Date.now();
return HttpResponse.json(
mockOfferings
.filter(
(o) =>
o.isActive &&
(!o.startsAt || new Date(o.startsAt).getTime() <= now) &&
(!o.endsAt || now < new Date(o.endsAt).getTime()),
)
.map(withCategoryName),
);
}),
http.post(`${API_BASE}/api/v1/offerings`, async ({ request }) => { http.post(`${API_BASE}/api/v1/offerings`, async ({ request }) => {
const body = (await request.json()) as CreateOfferingRequest; const body = (await request.json()) as CreateOfferingRequest;
@@ -9,6 +9,7 @@ import { useCreateOffering } from '../services/useCreateOffering';
import { useUpdateOffering } from '../services/useUpdateOffering'; import { useUpdateOffering } from '../services/useUpdateOffering';
import { NetworkError, ProblemDetailsError } from '@/lib/api-client'; import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
import type { OfferingFormData } from '../schemas/offering'; import type { OfferingFormData } from '../schemas/offering';
import { fromLocalInput } from '../schemas/offeringBanner';
export function OfferingFormPage() { export function OfferingFormPage() {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -25,11 +26,12 @@ export function OfferingFormPage() {
const onSubmit = async (values: OfferingFormData) => { const onSubmit = async (values: OfferingFormData) => {
setServerError(null); setServerError(null);
const body = { ...values, startsAt: fromLocalInput(values.startsAt), endsAt: fromLocalInput(values.endsAt) };
try { try {
if (isEdit && id !== undefined) { if (isEdit && id !== undefined) {
await updateOffering.mutateAsync({ id, ...values }); await updateOffering.mutateAsync({ id, ...body });
} else { } else {
await createOffering.mutateAsync(values); await createOffering.mutateAsync(body);
} }
toast.success(t('offerings.form.successToast')); toast.success(t('offerings.form.successToast'));
navigate({ to: '/offerings' }); navigate({ to: '/offerings' });
@@ -61,7 +63,12 @@ export function OfferingFormPage() {
onDismiss={() => setServerError(null)} onDismiss={() => setServerError(null)}
/> />
<OfferingForm initialValues={existingOffering} onSubmit={onSubmit} isSubmitting={isSubmitting} /> <OfferingForm
initialValues={existingOffering}
onSubmit={onSubmit}
onCancel={() => navigate({ to: '/offerings' })}
isSubmitting={isSubmitting}
/>
</div> </div>
); );
} }
@@ -0,0 +1,135 @@
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 { getMockOfferings, resetMockOfferings } from '@/features/offerings/mocks/handlers';
import { _resetSetupStatusCache } from '@/router';
const T = { timeout: 10000 };
const STARTER = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
const PRO = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';
beforeEach(() => {
_resetSetupStatusCache();
resetMockOfferings();
});
describe('Offering form: Annuleren', () => {
it('has a cancel button that leaves a new offering without saving', async () => {
mockAuthenticated();
renderApp('/offerings/new');
await screen.findByTestId('offering-form-cancel', {}, T);
await userEvent.type(screen.getByTestId('offering-title'), 'Niet bewaren');
await userEvent.click(screen.getByTestId('offering-form-cancel'));
expect(await screen.findByTestId('offerings-title', {}, T)).toBeInTheDocument();
expect(screen.queryByText('Niet bewaren')).not.toBeInTheDocument();
expect(getMockOfferings()).toHaveLength(2);
});
it('has a cancel button when editing too, and does not change the offering', async () => {
mockAuthenticated();
renderApp(`/offerings/${STARTER}/edit`);
const title = await screen.findByTestId('offering-title', {}, T);
await userEvent.clear(title);
await userEvent.type(title, 'Aangepast');
await userEvent.click(screen.getByTestId('offering-form-cancel'));
expect(await screen.findByTestId('offerings-title', {}, T)).toBeInTheDocument();
expect(getMockOfferings().find((o) => o.id === STARTER)?.title).toBe('Starter');
});
});
describe('Offering form: planning', () => {
it('defaults to switched on without a schedule', async () => {
mockAuthenticated();
renderApp('/offerings/new');
await screen.findByTestId('offering-active', {}, T);
expect(screen.getByTestId('offering-active')).toBeChecked();
expect(screen.getByTestId('offering-starts')).toHaveValue('');
expect(screen.getByTestId('offering-ends')).toHaveValue('');
});
it('saves the switch and the schedule', async () => {
mockAuthenticated();
renderApp(`/offerings/${STARTER}/edit`);
await screen.findByTestId('offering-active', {}, T);
await userEvent.click(screen.getByTestId('offering-active'));
await userEvent.type(screen.getByTestId('offering-starts'), '2030-01-01T10:00');
await userEvent.type(screen.getByTestId('offering-ends'), '2030-02-01T10:00');
await userEvent.click(screen.getByTestId('offering-form-submit'));
await screen.findByTestId('offerings-title', {}, T);
const saved = getMockOfferings().find((o) => o.id === STARTER)!;
expect(saved.isActive).toBe(false);
expect(saved.startsAt).toBe(new Date('2030-01-01T10:00').toISOString());
expect(saved.endsAt).toBe(new Date('2030-02-01T10:00').toISOString());
});
it('refuses an end before the start', async () => {
mockAuthenticated();
renderApp(`/offerings/${STARTER}/edit`);
await screen.findByTestId('offering-active', {}, T);
await userEvent.type(screen.getByTestId('offering-starts'), '2030-02-01T10:00');
await userEvent.type(screen.getByTestId('offering-ends'), '2030-01-01T10:00');
await userEvent.click(screen.getByTestId('offering-form-submit'));
expect(await screen.findByTestId('offering-ends-error')).toBeInTheDocument();
expect(getMockOfferings().find((o) => o.id === STARTER)?.endsAt).toBeNull();
});
});
describe('Offerings list: status and switch', () => {
it('shows Actief and Live for a normal offering', async () => {
mockAuthenticated();
renderApp('/offerings');
expect(await screen.findByTestId(`offering-row-${STARTER}-status`, {}, T)).toHaveTextContent(/actief|active/i);
expect(screen.getByTestId(`offering-row-${STARTER}-shown`)).toBeInTheDocument();
});
it('turns an offering off with the power button, keeping everything else, and shows it as Uit without Live', async () => {
mockAuthenticated();
renderApp('/offerings');
await userEvent.click(await screen.findByTestId(`offering-row-${STARTER}-toggle-active`, {}, T));
await waitFor(() => expect(getMockOfferings().find((o) => o.id === STARTER)?.isActive).toBe(false));
expect(await screen.findByTestId(`offering-row-${STARTER}-status`)).toHaveTextContent(/uit|off/i);
expect(screen.queryByTestId(`offering-row-${STARTER}-shown`)).not.toBeInTheDocument();
expect(getMockOfferings().find((o) => o.id === STARTER)?.featured).toBe(false);
});
it('keeps the schedule when the featured star is clicked', async () => {
mockAuthenticated();
const start = '2030-01-01T10:00:00.000Z';
const end = '2030-03-01T10:00:00.000Z';
const pro = getMockOfferings().find((o) => o.id === PRO)!;
pro.startsAt = start;
pro.endsAt = end;
pro.isActive = false;
renderApp('/offerings');
await userEvent.click(await screen.findByTestId(`offering-row-${PRO}-featured-toggle`, {}, T));
await waitFor(() => expect(getMockOfferings().find((o) => o.id === PRO)?.featured).toBe(false));
const after = getMockOfferings().find((o) => o.id === PRO)!;
expect(after.isActive).toBe(false);
expect(after.startsAt).toBe(start);
expect(after.endsAt).toBe(end);
});
it('shows Gepland for a future start and the period', async () => {
mockAuthenticated();
getMockOfferings().find((o) => o.id === STARTER)!.startsAt = '2099-01-01T10:00:00.000Z';
renderApp('/offerings');
expect(await screen.findByTestId(`offering-row-${STARTER}-status`, {}, T)).toHaveTextContent(/gepland|scheduled/i);
expect(screen.queryByTestId(`offering-row-${STARTER}-shown`)).not.toBeInTheDocument();
expect(screen.getByTestId(`offering-row-${STARTER}-period`)).toBeInTheDocument();
});
});
@@ -13,7 +13,7 @@ beforeEach(() => {
resetMockOfferings(); resetMockOfferings();
}); });
const OFFERINGS_URL = `${API_BASE}/api/v1/offerings`; const OFFERINGS_URL = `${API_BASE}/api/v1/offerings/all`;
describe('OfferingsListPage', () => { describe('OfferingsListPage', () => {
it('renders the page title and Add button', async () => { it('renders the page title and Add button', async () => {
@@ -90,7 +90,7 @@ describe('OfferingsListPage', () => {
mockAuthenticated(); mockAuthenticated();
let sentBody: { orderedIds: string[] } | undefined; let sentBody: { orderedIds: string[] } | undefined;
server.use( server.use(
http.put(`${OFFERINGS_URL}/order`, async ({ request }) => { http.put(`${API_BASE}/api/v1/offerings/order`, async ({ request }) => {
sentBody = (await request.json()) as { orderedIds: string[] }; sentBody = (await request.json()) as { orderedIds: string[] };
return new HttpResponse(null, { status: 204 }); return new HttpResponse(null, { status: 204 });
}), }),
@@ -10,6 +10,9 @@ function validOffering() {
features: ['1 page'], features: ['1 page'],
ctaLabel: 'Get started', ctaLabel: 'Get started',
featured: false, featured: false,
isActive: true,
startsAt: '',
endsAt: '',
}; };
} }
@@ -48,4 +51,19 @@ describe('offeringFormSchema', () => {
const result = offeringFormSchema.safeParse({ ...validOffering(), title: '' }); const result = offeringFormSchema.safeParse({ ...validOffering(), title: '' });
expect(result.success).toBe(false); expect(result.success).toBe(false);
}); });
it('accepts an empty schedule and a valid one', () => {
expect(offeringFormSchema.safeParse(validOffering()).success).toBe(true);
expect(
offeringFormSchema.safeParse({ ...validOffering(), startsAt: '2026-11-15T10:00', endsAt: '2026-11-16T10:00' }).success,
).toBe(true);
});
it('rejects an end that is not after the start', () => {
const same = offeringFormSchema.safeParse({ ...validOffering(), startsAt: '2026-11-15T10:00', endsAt: '2026-11-15T10:00' });
const before = offeringFormSchema.safeParse({ ...validOffering(), startsAt: '2026-11-15T10:00', endsAt: '2026-11-14T10:00' });
expect(same.success).toBe(false);
expect(before.success).toBe(false);
});
}); });
@@ -1,6 +1,7 @@
import { z } from 'zod'; import { z } from 'zod';
export const offeringFormSchema = z.object({ export const offeringFormSchema = z
.object({
title: z.string().min(1, 'Title is required').max(100, 'Title must be 100 characters or fewer'), title: z.string().min(1, 'Title is required').max(100, 'Title must be 100 characters or fewer'),
description: z description: z
.string() .string()
@@ -25,7 +26,16 @@ export const offeringFormSchema = z.object({
.or(z.literal('')), .or(z.literal('')),
/** Id of the chosen category; null/absent = no category. */ /** Id of the chosen category; null/absent = no category. */
categoryId: z.string().nullable().optional(), categoryId: z.string().nullable().optional(),
}); 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) => {
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 OfferingFormData = z.infer<typeof offeringFormSchema>; export type OfferingFormData = z.infer<typeof offeringFormSchema>;
@@ -88,3 +88,9 @@ export function bannerStatus(b: { isActive: boolean; startsAt: string | null; en
if (b.endsAt && new Date(b.endsAt) <= now) return 'expired'; if (b.endsAt && new Date(b.endsAt) <= now) return 'expired';
return 'live'; return 'live';
} }
/** Same rule for packages: switched on, started and not yet ended. */
export const scheduleStatus = (
b: { isActive: boolean; startsAt: string | null; endsAt: string | null },
now = new Date(),
) => bannerStatus(b, now);
@@ -13,6 +13,12 @@ export interface OfferingDto {
categoryId?: string | null; categoryId?: string | null;
/** Name of the category (renames show up here automatically). */ /** Name of the category (renames show up here automatically). */
category?: string | null; category?: string | null;
/** Switched on. A switched-off offering is never shown on the website. */
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;
} }
export interface CreateOfferingRequest { export interface CreateOfferingRequest {
@@ -27,6 +33,9 @@ export interface CreateOfferingRequest {
slug?: string; slug?: string;
/** Category id; null clears the category. */ /** Category id; null clears the category. */
categoryId?: string | null; categoryId?: string | null;
isActive: boolean;
startsAt: string | null;
endsAt: string | null;
} }
export type UpdateOfferingRequest = CreateOfferingRequest; export type UpdateOfferingRequest = CreateOfferingRequest;
@@ -5,6 +5,6 @@ import type { OfferingDto } from './types';
export function useOfferings() { export function useOfferings() {
return useQuery<OfferingDto[], Error>({ return useQuery<OfferingDto[], Error>({
queryKey: ['offerings', 'list'], queryKey: ['offerings', 'list'],
queryFn: () => api.get<OfferingDto[]>('/api/v1/offerings'), queryFn: () => api.get<OfferingDto[]>('/api/v1/offerings/all'),
}); });
} }
@@ -401,6 +401,8 @@
"actions": "Actions" "actions": "Actions"
}, },
"actions": { "actions": {
"turnOff": "Switch package off",
"turnOn": "Switch package on",
"drag": "Drag to reorder", "drag": "Drag to reorder",
"edit": "Edit", "edit": "Edit",
"delete": "Delete", "delete": "Delete",
@@ -418,6 +420,11 @@
"form": { "form": {
"createTitle": "New Offering", "createTitle": "New Offering",
"editTitle": "Edit Offering", "editTitle": "Edit Offering",
"activeLabel": "Switched on",
"startsLabel": "Visible from (optional)",
"endsLabel": "Visible until (optional)",
"scheduleHint": "A switched-off or planned package is not shown on the website. Times are in your time zone. On Andrea's website the schedule applies at the next (nightly) build.",
"endBeforeStart": "The end must be after the start.",
"titleLabel": "Title", "titleLabel": "Title",
"slugLabel": "Slug", "slugLabel": "Slug",
"slugAutoHint": "Auto-generated from the title", "slugAutoHint": "Auto-generated from the title",
@@ -401,6 +401,8 @@
"actions": "Acties" "actions": "Acties"
}, },
"actions": { "actions": {
"turnOff": "Pakket uitzetten",
"turnOn": "Pakket aanzetten",
"drag": "Sleep om te herordenen", "drag": "Sleep om te herordenen",
"edit": "Bewerken", "edit": "Bewerken",
"delete": "Verwijderen", "delete": "Verwijderen",
@@ -418,6 +420,11 @@
"form": { "form": {
"createTitle": "Nieuwe aanbieding", "createTitle": "Nieuwe aanbieding",
"editTitle": "Aanbieding bewerken", "editTitle": "Aanbieding bewerken",
"activeLabel": "Ingeschakeld",
"startsLabel": "Zichtbaar vanaf (optioneel)",
"endsLabel": "Zichtbaar tot (optioneel)",
"scheduleHint": "Een uitgeschakeld of gepland pakket wordt niet op de website getoond. Tijden gelden in jouw tijdzone. Bij de website van Andrea geldt de planning bij de eerstvolgende (nachtelijke) build.",
"endBeforeStart": "Het einde moet na het begin liggen.",
"titleLabel": "Titel", "titleLabel": "Titel",
"slugLabel": "Slug", "slugLabel": "Slug",
"slugAutoHint": "Wordt automatisch gegenereerd uit de titel", "slugAutoHint": "Wordt automatisch gegenereerd uit de titel",
+48
View File
@@ -427,6 +427,13 @@
"description": { "description": {
"type": "string" "type": "string"
}, },
"endsAt": {
"format": "date-time",
"type": [
"null",
"string"
]
},
"featured": { "featured": {
"default": false, "default": false,
"type": "boolean" "type": "boolean"
@@ -437,6 +444,10 @@
}, },
"type": "array" "type": "array"
}, },
"isActive": {
"default": true,
"type": "boolean"
},
"price": { "price": {
"type": "string" "type": "string"
}, },
@@ -449,6 +460,13 @@
"string" "string"
] ]
}, },
"startsAt": {
"format": "date-time",
"type": [
"null",
"string"
]
},
"title": { "title": {
"type": "string" "type": "string"
} }
@@ -816,6 +834,13 @@
"description": { "description": {
"type": "string" "type": "string"
}, },
"endsAt": {
"format": "date-time",
"type": [
"null",
"string"
]
},
"featured": { "featured": {
"default": false, "default": false,
"type": "boolean" "type": "boolean"
@@ -826,6 +851,10 @@
}, },
"type": "array" "type": "array"
}, },
"isActive": {
"default": true,
"type": "boolean"
},
"price": { "price": {
"type": "string" "type": "string"
}, },
@@ -838,6 +867,13 @@
"string" "string"
] ]
}, },
"startsAt": {
"format": "date-time",
"type": [
"null",
"string"
]
},
"title": { "title": {
"type": "string" "type": "string"
} }
@@ -2260,6 +2296,18 @@
] ]
} }
}, },
"/api/v1/offerings/all": {
"get": {
"responses": {
"200": {
"description": "OK"
}
},
"tags": [
"Offerings"
]
}
},
"/api/v1/offerings/banner": { "/api/v1/offerings/banner": {
"get": { "get": {
"parameters": [ "parameters": [
@@ -27,6 +27,10 @@ public class OfferingsControllerTests
private static OfferingDto Dto(int displayOrder = 0) => new( private static OfferingDto Dto(int displayOrder = 0) => new(
Guid.NewGuid().ToString(), "title", "Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact", false, displayOrder); Guid.NewGuid().ToString(), "title", "Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact", false, displayOrder);
private static OfferingAdminDto AdminDto(int displayOrder = 0) => new(
Guid.NewGuid().ToString(), "title", "Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact", false, displayOrder,
null, null, true, null, null);
private static CreateOfferingRequest CreateRequest() => new( private static CreateOfferingRequest CreateRequest() => new(
"Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact"); "Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact");
@@ -50,7 +54,7 @@ public class OfferingsControllerTests
[Fact] [Fact]
public async Task Create_Returns201Created() public async Task Create_Returns201Created()
{ {
_service.CreateAsync(Arg.Any<CreateOfferingRequest>(), Arg.Any<Guid>()).Returns(Dto()); _service.CreateAsync(Arg.Any<CreateOfferingRequest>(), Arg.Any<Guid>()).Returns(AdminDto());
var result = await CreateSut().Create(CreateRequest()); var result = await CreateSut().Create(CreateRequest());
@@ -73,7 +77,7 @@ public class OfferingsControllerTests
[Fact] [Fact]
public async Task Update_Returns200_WhenFound() public async Task Update_Returns200_WhenFound()
{ {
_service.UpdateAsync(Arg.Any<Guid>(), Arg.Any<UpdateOfferingRequest>(), Arg.Any<Guid>()).Returns(Dto()); _service.UpdateAsync(Arg.Any<Guid>(), Arg.Any<UpdateOfferingRequest>(), Arg.Any<Guid>()).Returns(AdminDto());
var result = await CreateSut().Update(Guid.NewGuid(), UpdateRequest()); var result = await CreateSut().Update(Guid.NewGuid(), UpdateRequest());
@@ -84,7 +88,7 @@ public class OfferingsControllerTests
public async Task Update_Returns404_WhenNotFound() public async Task Update_Returns404_WhenNotFound()
{ {
_service.UpdateAsync(Arg.Any<Guid>(), Arg.Any<UpdateOfferingRequest>(), Arg.Any<Guid>()) _service.UpdateAsync(Arg.Any<Guid>(), Arg.Any<UpdateOfferingRequest>(), Arg.Any<Guid>())
.Returns((OfferingDto?)null); .Returns((OfferingAdminDto?)null);
var result = await CreateSut().Update(Guid.NewGuid(), UpdateRequest()); var result = await CreateSut().Update(Guid.NewGuid(), UpdateRequest());
@@ -46,8 +46,9 @@ public class OfferingsRoutesTests
foreach (var (action, http) in Actions()) foreach (var (action, http) in Actions())
{ {
var anonymous = action.GetCustomAttribute<AllowAnonymousAttribute>() is not null; var anonymous = action.GetCustomAttribute<AllowAnonymousAttribute>() is not null;
// "GET all" is the administrator list (switched-off/planned/expired included): never anonymous.
anonymous.Should().Be( anonymous.Should().Be(
http.HttpMethods.Single() == "GET", http.HttpMethods.Single() == "GET" && http.Template != "all",
$"{http.HttpMethods.Single()} {http.Template} must be anonymous only when it is a GET"); $"{http.HttpMethods.Single()} {http.Template} must be anonymous only when it is a GET");
} }
} }
@@ -71,6 +72,7 @@ public class OfferingsRoutesTests
.Should().BeEquivalentTo( .Should().BeEquivalentTo(
[ [
"GET", "GET",
"GET all",
"POST", "POST",
"PUT {id:guid}", "PUT {id:guid}",
"DELETE {id:guid}", "DELETE {id:guid}",
@@ -81,7 +83,7 @@ public class OfferingsRoutesTests
[Fact] [Fact]
public async Task Create_Returns201_WithLocationOfTheNewResource() public async Task Create_Returns201_WithLocationOfTheNewResource()
{ {
var dto = new OfferingDto(Guid.NewGuid().ToString(), "t", "T", "D", "p", "n", ["f"], "c", false, 0); var dto = new OfferingAdminDto(Guid.NewGuid().ToString(), "t", "T", "D", "p", "n", ["f"], "c", false, 0, null, null, true, null, null);
_service.CreateAsync(Arg.Any<CreateOfferingRequest>(), Arg.Any<Guid>()).Returns(dto); _service.CreateAsync(Arg.Any<CreateOfferingRequest>(), Arg.Any<Guid>()).Returns(dto);
var result = await CreateSut().Create(new CreateOfferingRequest("T", "D", "p", "n", ["f"], "c")); var result = await CreateSut().Create(new CreateOfferingRequest("T", "D", "p", "n", ["f"], "c"));
@@ -0,0 +1,124 @@
using System.ComponentModel.DataAnnotations;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using NSubstitute;
using SlpModularCms.Modules.Offerings.Data.Entities;
using SlpModularCms.Modules.Offerings.Models;
using SlpModularCms.Modules.Offerings.Repositories;
using SlpModularCms.Modules.Offerings.Services;
namespace SlpModularCms.Modules.Offerings.Tests.Services;
public class OfferingsScheduleTests
{
private sealed class FakeTimeProvider(DateTimeOffset now) : TimeProvider
{
public override DateTimeOffset GetUtcNow() => now;
}
private static readonly DateTimeOffset Now = new(2026, 11, 15, 12, 0, 0, TimeSpan.Zero);
private readonly IOfferingRepository _repo = Substitute.For<IOfferingRepository>();
private OfferingsService Sut() => new(
_repo, Substitute.For<IOfferingCategoryRepository>(), Substitute.For<ILogger<OfferingsService>>(),
null, new FakeTimeProvider(Now));
private static Offering Offer(string title, bool active = true, DateTimeOffset? starts = null, DateTimeOffset? ends = null) => new()
{
Id = Guid.NewGuid(), Slug = title.ToLowerInvariant(), Title = title, Description = "d", Price = "p", PriceNote = "n",
Features = ["f"], CtaLabel = "c", IsActive = active, StartsAt = starts, EndsAt = ends,
};
[Fact]
public async Task Public_list_shows_unscheduled_active_offering_so_existing_packages_stay_visible()
{
_repo.GetAllAsync().Returns([Offer("Plain")]);
(await Sut().GetOfferingsAsync()).Select(o => o.Title).Should().Equal("Plain");
}
[Fact]
public async Task Public_list_hides_switched_off_planned_and_expired_but_keeps_order()
{
_repo.GetAllAsync().Returns([
Offer("A"),
Offer("Off", active: false),
Offer("Planned", starts: Now.AddMinutes(1)),
Offer("Expired", ends: Now),
Offer("B", starts: Now, ends: Now.AddDays(1)),
]);
(await Sut().GetOfferingsAsync()).Select(o => o.Title).Should().Equal("A", "B");
}
[Fact]
public async Task Public_list_never_exposes_switch_or_schedule()
{
_repo.GetAllAsync().Returns([Offer("A")]);
var dto = (await Sut().GetOfferingsAsync()).Single();
dto.GetType().Should().Be(typeof(OfferingDto));
}
[Fact]
public async Task Admin_list_returns_everything_with_switch_and_schedule()
{
_repo.GetAllAsync().Returns([Offer("Off", active: false), Offer("Planned", starts: Now.AddDays(1), ends: Now.AddDays(2))]);
var list = await Sut().ListAllAsync();
list.Should().HaveCount(2);
list[0].IsActive.Should().BeFalse();
list[1].StartsAt.Should().Be(Now.AddDays(1));
list[1].EndsAt.Should().Be(Now.AddDays(2));
}
[Fact]
public async Task Create_without_schedule_fields_defaults_to_active_and_unscheduled()
{
_repo.GetMaxDisplayOrderAsync().Returns(0);
var request = new CreateOfferingRequest("T", "d", "p", "n", ["f"], "c");
var dto = await Sut().CreateAsync(request, Guid.NewGuid());
dto.IsActive.Should().BeTrue();
dto.StartsAt.Should().BeNull();
dto.EndsAt.Should().BeNull();
}
[Fact]
public async Task Create_and_update_store_switch_and_schedule()
{
_repo.GetMaxDisplayOrderAsync().Returns(0);
var create = new CreateOfferingRequest("T", "d", "p", "n", ["f"], "c", IsActive: false, StartsAt: Now, EndsAt: Now.AddDays(1));
var created = await Sut().CreateAsync(create, Guid.NewGuid());
created.IsActive.Should().BeFalse();
await _repo.Received(1).AddAsync(Arg.Is<Offering>(o => !o.IsActive && o.StartsAt == Now && o.EndsAt == Now.AddDays(1)));
var existing = Offer("E");
_repo.GetByIdAsync(existing.Id).Returns(existing);
var update = new UpdateOfferingRequest("E", "d", "p", "n", ["f"], "c", IsActive: false, StartsAt: Now, EndsAt: Now.AddHours(2));
var updated = await Sut().UpdateAsync(existing.Id, update, Guid.NewGuid());
updated!.IsActive.Should().BeFalse();
existing.EndsAt.Should().Be(Now.AddHours(2));
}
[Fact]
public void End_must_be_after_start_for_create_and_update()
{
var bad = new CreateOfferingRequest("T", "d", "p", "n", ["f"], "c", StartsAt: Now, EndsAt: Now);
var badUpdate = new UpdateOfferingRequest("T", "d", "p", "n", ["f"], "c", StartsAt: Now, EndsAt: Now.AddSeconds(-1));
var ok = new CreateOfferingRequest("T", "d", "p", "n", ["f"], "c", StartsAt: Now, EndsAt: Now.AddSeconds(1));
var ctx = new ValidationContext(bad);
bad.Validate(ctx).Should().ContainSingle();
badUpdate.Validate(ctx).Should().ContainSingle();
ok.Validate(ctx).Should().BeEmpty();
}
}
@@ -29,6 +29,10 @@ public class OfferingsController(IOfferingsService service) : ControllerBase
return Ok(offerings); return Ok(offerings);
} }
/// <summary>Administrator list including switched-off, planned and expired offerings.</summary>
[HttpGet("all")]
public async Task<IActionResult> ListAll() => Ok(await service.ListAllAsync());
[HttpPost] [HttpPost]
public async Task<IActionResult> Create([FromBody] CreateOfferingRequest request) public async Task<IActionResult> Create([FromBody] CreateOfferingRequest request)
{ {
@@ -14,6 +14,12 @@ public class Offering
public Guid? CategoryId { get; set; } public Guid? CategoryId { get; set; }
public OfferingCategory? Category { get; set; } public OfferingCategory? Category { get; set; }
public int DisplayOrder { get; set; } public int DisplayOrder { get; set; }
/// <summary>Switched on. A switched-off offering is never shown publicly (it stays in the admin list).</summary>
public bool IsActive { get; set; } = true;
/// <summary>First moment it is shown (inclusive); null = no start limit.</summary>
public DateTimeOffset? StartsAt { get; set; }
/// <summary>First moment it is no longer shown (exclusive); null = no end limit.</summary>
public DateTimeOffset? EndsAt { get; set; }
public bool IsDeleted { get; set; } public bool IsDeleted { get; set; }
public DateTimeOffset? DeletedAt { get; set; } public DateTimeOffset? DeletedAt { get; set; }
public DateTimeOffset CreatedAt { get; set; } public DateTimeOffset CreatedAt { get; set; }
@@ -26,6 +26,7 @@ public class OfferingsDbContext(DbContextOptions<OfferingsDbContext> options) :
entity.Property(e => e.PriceNote).IsRequired().HasMaxLength(100); entity.Property(e => e.PriceNote).IsRequired().HasMaxLength(100);
entity.Property(e => e.CtaLabel).IsRequired().HasMaxLength(50); entity.Property(e => e.CtaLabel).IsRequired().HasMaxLength(50);
entity.Property(e => e.DisplayOrder).IsRequired(); entity.Property(e => e.DisplayOrder).IsRequired();
entity.Property(e => e.IsActive).IsRequired().HasDefaultValue(true);
entity.Property(e => e.IsDeleted).IsRequired(); entity.Property(e => e.IsDeleted).IsRequired();
entity.Property(e => e.CreatedAt).IsRequired(); entity.Property(e => e.CreatedAt).IsRequired();
entity.Property(e => e.UpdatedAt).IsRequired(); entity.Property(e => e.UpdatedAt).IsRequired();
@@ -0,0 +1,200 @@
// <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("20261115100000_AddOfferingSchedule")]
partial class AddOfferingSchedule
{
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<DateTimeOffset?>("EndsAt")
.HasColumnType("datetime");
b.Property<bool>("Featured")
.HasColumnType("tinyint(1)");
b.Property<string>("Features")
.IsRequired()
.HasColumnType("longtext");
b.Property<bool>("IsActive")
.ValueGeneratedOnAdd()
.HasColumnType("tinyint(1)")
.HasDefaultValue(true);
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<DateTimeOffset?>("StartsAt")
.HasColumnType("datetime");
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,43 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SlpModularCms.Modules.Offerings.Migrations
{
/// <inheritdoc />
public partial class AddOfferingSchedule : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
// Existing offerings stay switched on without a schedule: nothing changes for the websites.
migrationBuilder.AddColumn<bool>(
name: "IsActive",
table: "OfferingsOfferings",
type: "tinyint(1)",
nullable: false,
defaultValue: true);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "StartsAt",
table: "OfferingsOfferings",
type: "datetime",
nullable: true);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "EndsAt",
table: "OfferingsOfferings",
type: "datetime",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(name: "EndsAt", table: "OfferingsOfferings");
migrationBuilder.DropColumn(name: "StartsAt", table: "OfferingsOfferings");
migrationBuilder.DropColumn(name: "IsActive", table: "OfferingsOfferings");
}
}
}
@@ -1,4 +1,4 @@
// <auto-generated /> // <auto-generated />
using System; using System;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Infrastructure;
@@ -101,6 +101,9 @@ namespace SlpModularCms.Modules.Offerings.Migrations
b.Property<int>("DisplayOrder") b.Property<int>("DisplayOrder")
.HasColumnType("int"); .HasColumnType("int");
b.Property<DateTimeOffset?>("EndsAt")
.HasColumnType("datetime");
b.Property<bool>("Featured") b.Property<bool>("Featured")
.HasColumnType("tinyint(1)"); .HasColumnType("tinyint(1)");
@@ -108,6 +111,11 @@ namespace SlpModularCms.Modules.Offerings.Migrations
.IsRequired() .IsRequired()
.HasColumnType("longtext"); .HasColumnType("longtext");
b.Property<bool>("IsActive")
.ValueGeneratedOnAdd()
.HasColumnType("tinyint(1)")
.HasDefaultValue(true);
b.Property<bool>("IsDeleted") b.Property<bool>("IsDeleted")
.HasColumnType("tinyint(1)"); .HasColumnType("tinyint(1)");
@@ -129,6 +137,9 @@ namespace SlpModularCms.Modules.Offerings.Migrations
.HasMaxLength(130) .HasMaxLength(130)
.HasColumnType("varchar(130)"); .HasColumnType("varchar(130)");
b.Property<DateTimeOffset?>("StartsAt")
.HasColumnType("datetime");
b.Property<string>("Title") b.Property<string>("Title")
.IsRequired() .IsRequired()
.HasMaxLength(100) .HasMaxLength(100)
@@ -11,5 +11,12 @@ public record CreateOfferingRequest(
[Required(AllowEmptyStrings = true), MaxLength(50)] string CtaLabel, [Required(AllowEmptyStrings = true), MaxLength(50)] string CtaLabel,
bool Featured = false, bool Featured = false,
[MaxLength(130)] string? Slug = null, [MaxLength(130)] string? Slug = null,
Guid? CategoryId = null Guid? CategoryId = null,
); bool IsActive = true,
DateTimeOffset? StartsAt = null,
DateTimeOffset? EndsAt = null
) : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
=> OfferingSchedule.Validate(StartsAt, EndsAt);
}
@@ -21,3 +21,26 @@ public record OfferingDto(
string? CategoryId = null, string? CategoryId = null,
string? Category = null string? Category = null
); );
/// <summary>
/// Administrator view: the public representation plus the switch and the schedule. Never returned by the
/// public endpoint, whose JSON shape stays as websites expect it.
/// </summary>
[ExcludeFromCodeCoverage]
public record OfferingAdminDto(
string Id,
string Slug,
string Title,
string Description,
string Price,
string PriceNote,
IReadOnlyList<string> Features,
string CtaLabel,
bool Featured,
int DisplayOrder,
string? CategoryId,
string? Category,
bool IsActive,
DateTimeOffset? StartsAt,
DateTimeOffset? EndsAt
) : OfferingDto(Id, Slug, Title, Description, Price, PriceNote, Features, CtaLabel, Featured, DisplayOrder, CategoryId, Category);
@@ -0,0 +1,18 @@
using System.ComponentModel.DataAnnotations;
using SlpModularCms.Modules.Offerings.Data.Entities;
namespace SlpModularCms.Modules.Offerings.Models;
/// <summary>The one rule for "is this offering shown right now", shared by the public list and the SEO injection.</summary>
public static class OfferingSchedule
{
public static IEnumerable<ValidationResult> Validate(DateTimeOffset? startsAt, DateTimeOffset? endsAt)
{
if (startsAt is not null && endsAt is not null && endsAt <= startsAt)
yield return new ValidationResult("EndsAt must be after StartsAt.", [nameof(OfferingBanner.EndsAt)]);
}
/// <summary>Switched on, started (inclusive) and not yet ended (exclusive).</summary>
public static bool IsLive(Offering o, DateTimeOffset now)
=> o.IsActive && (o.StartsAt is null || o.StartsAt <= now) && (o.EndsAt is null || now < o.EndsAt);
}
@@ -11,5 +11,12 @@ public record UpdateOfferingRequest(
[Required(AllowEmptyStrings = true), MaxLength(50)] string CtaLabel, [Required(AllowEmptyStrings = true), MaxLength(50)] string CtaLabel,
bool Featured = false, bool Featured = false,
[MaxLength(130)] string? Slug = null, [MaxLength(130)] string? Slug = null,
Guid? CategoryId = null Guid? CategoryId = null,
); bool IsActive = true,
DateTimeOffset? StartsAt = null,
DateTimeOffset? EndsAt = null
) : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
=> OfferingSchedule.Validate(StartsAt, EndsAt);
}
@@ -4,9 +4,14 @@ namespace SlpModularCms.Modules.Offerings.Services;
public interface IOfferingsService public interface IOfferingsService
{ {
/// <summary>What visitors get: only offerings switched on and inside their schedule right now.</summary>
Task<IReadOnlyList<OfferingDto>> GetOfferingsAsync(); Task<IReadOnlyList<OfferingDto>> GetOfferingsAsync();
Task<OfferingDto> CreateAsync(CreateOfferingRequest request, Guid callerId);
Task<OfferingDto?> UpdateAsync(Guid id, UpdateOfferingRequest request, Guid callerId); /// <summary>What administrators get: every offering with its switch and schedule.</summary>
Task<IReadOnlyList<OfferingAdminDto>> ListAllAsync();
Task<OfferingAdminDto> CreateAsync(CreateOfferingRequest request, Guid callerId);
Task<OfferingAdminDto?> UpdateAsync(Guid id, UpdateOfferingRequest request, Guid callerId);
Task<bool> DeleteAsync(Guid id, Guid callerId); Task<bool> DeleteAsync(Guid id, Guid callerId);
/// <summary> /// <summary>
@@ -10,15 +10,24 @@ public class OfferingsService(
IOfferingRepository repository, IOfferingRepository repository,
IOfferingCategoryRepository categories, IOfferingCategoryRepository categories,
ILogger<OfferingsService> logger, ILogger<OfferingsService> logger,
IIndexHtmlCache? indexCache = null) : IOfferingsService IIndexHtmlCache? indexCache = null,
TimeProvider? time = null) : IOfferingsService
{ {
private readonly TimeProvider _time = time ?? TimeProvider.System;
/// <summary>Public list: only offerings that are switched on and inside their schedule right now.</summary>
public async Task<IReadOnlyList<OfferingDto>> GetOfferingsAsync() public async Task<IReadOnlyList<OfferingDto>> GetOfferingsAsync()
{ {
var now = _time.GetUtcNow();
var offerings = await repository.GetAllAsync(); var offerings = await repository.GetAllAsync();
return offerings.Select(ToDto).ToList(); return offerings.Where(o => OfferingSchedule.IsLive(o, now)).Select(ToDto).ToList();
} }
public async Task<OfferingDto> CreateAsync(CreateOfferingRequest request, Guid callerId) /// <summary>Administrator list: everything, including switched-off, planned and expired offerings.</summary>
public async Task<IReadOnlyList<OfferingAdminDto>> ListAllAsync()
=> (await repository.GetAllAsync()).Select(ToAdminDto).ToList();
public async Task<OfferingAdminDto> CreateAsync(CreateOfferingRequest request, Guid callerId)
{ {
var category = await ResolveCategoryAsync(request.CategoryId); var category = await ResolveCategoryAsync(request.CategoryId);
var now = DateTimeOffset.UtcNow; var now = DateTimeOffset.UtcNow;
@@ -35,6 +44,9 @@ public class OfferingsService(
CategoryId = category?.Id, CategoryId = category?.Id,
Category = category, Category = category,
Featured = request.Featured, Featured = request.Featured,
IsActive = request.IsActive,
StartsAt = request.StartsAt,
EndsAt = request.EndsAt,
DisplayOrder = await repository.GetMaxDisplayOrderAsync() + 1, DisplayOrder = await repository.GetMaxDisplayOrderAsync() + 1,
CreatedAt = now, CreatedAt = now,
UpdatedAt = now, UpdatedAt = now,
@@ -64,10 +76,10 @@ public class OfferingsService(
"Offering {OfferingId} {Action} by user {LastModifiedByUserId}", "Offering {OfferingId} {Action} by user {LastModifiedByUserId}",
offering.Id, "Created", callerId); offering.Id, "Created", callerId);
return ToDto(offering); return ToAdminDto(offering);
} }
public async Task<OfferingDto?> UpdateAsync(Guid id, UpdateOfferingRequest request, Guid callerId) public async Task<OfferingAdminDto?> UpdateAsync(Guid id, UpdateOfferingRequest request, Guid callerId)
{ {
var offering = await repository.GetByIdAsync(id); var offering = await repository.GetByIdAsync(id);
if (offering is null) if (offering is null)
@@ -93,6 +105,9 @@ public class OfferingsService(
offering.CategoryId = category?.Id; offering.CategoryId = category?.Id;
offering.Category = category; offering.Category = category;
offering.Featured = request.Featured; offering.Featured = request.Featured;
offering.IsActive = request.IsActive;
offering.StartsAt = request.StartsAt;
offering.EndsAt = request.EndsAt;
offering.UpdatedAt = DateTimeOffset.UtcNow; offering.UpdatedAt = DateTimeOffset.UtcNow;
offering.LastModifiedByUserId = callerId; offering.LastModifiedByUserId = callerId;
@@ -115,7 +130,7 @@ public class OfferingsService(
"Offering {OfferingId} {Action} by user {LastModifiedByUserId}", "Offering {OfferingId} {Action} by user {LastModifiedByUserId}",
offering.Id, "Updated", callerId); offering.Id, "Updated", callerId);
return ToDto(offering); return ToAdminDto(offering);
} }
public async Task<bool> DeleteAsync(Guid id, Guid callerId) public async Task<bool> DeleteAsync(Guid id, Guid callerId)
@@ -245,4 +260,22 @@ public class OfferingsService(
o.CategoryId?.ToString(), o.CategoryId?.ToString(),
o.Category?.Name o.Category?.Name
); );
private static OfferingAdminDto ToAdminDto(Offering o) => new(
o.Id.ToString(),
o.Slug,
o.Title,
o.Description,
o.Price,
o.PriceNote,
o.Features,
o.CtaLabel,
o.Featured,
o.DisplayOrder,
o.CategoryId?.ToString(),
o.Category?.Name,
o.IsActive,
o.StartsAt,
o.EndsAt
);
} }