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:
@@ -11,15 +11,18 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
|
||||
import { useOfferingCategories } from '../services/useOfferingCategories';
|
||||
import { slugifyPreview } from '@/lib/slugify';
|
||||
import { offeringFormSchema, type OfferingFormData } from '../schemas/offering';
|
||||
import { toLocalInput } from '../schemas/offeringBanner';
|
||||
import type { OfferingDto } from '../services/types';
|
||||
|
||||
interface OfferingFormProps {
|
||||
initialValues?: OfferingDto;
|
||||
onSubmit: (values: OfferingFormData) => void;
|
||||
/** Leaves the form without saving (back to the list). */
|
||||
onCancel: () => void;
|
||||
isSubmitting: boolean;
|
||||
}
|
||||
|
||||
export function OfferingForm({ initialValues, onSubmit, isSubmitting }: OfferingFormProps) {
|
||||
export function OfferingForm({ initialValues, onSubmit, onCancel, isSubmitting }: OfferingFormProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const {
|
||||
@@ -32,7 +35,14 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering
|
||||
} = useForm<OfferingFormData>({
|
||||
resolver: zodResolver(offeringFormSchema),
|
||||
mode: 'onTouched',
|
||||
defaultValues: initialValues ?? {
|
||||
defaultValues: initialValues
|
||||
? {
|
||||
...initialValues,
|
||||
isActive: initialValues.isActive ?? true,
|
||||
startsAt: toLocalInput(initialValues.startsAt ?? null),
|
||||
endsAt: toLocalInput(initialValues.endsAt ?? null),
|
||||
}
|
||||
: {
|
||||
title: '',
|
||||
description: '',
|
||||
price: '',
|
||||
@@ -42,6 +52,9 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering
|
||||
featured: false,
|
||||
slug: '',
|
||||
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>
|
||||
</div>
|
||||
|
||||
<Button type="submit" disabled={isSubmitting} data-testid="offering-form-submit">
|
||||
{isSubmitting ? '…' : t('offerings.form.submitButton')}
|
||||
</Button>
|
||||
<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">
|
||||
{isSubmitting ? '…' : t('offerings.form.submitButton')}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,21 @@
|
||||
import { useSortable } from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
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 { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { TableCell, TableRow } from '@/components/ui/table';
|
||||
import { useUpdateOffering } from '../services/useUpdateOffering';
|
||||
import { useMoveOffering } from '../services/useMoveOffering';
|
||||
import { scheduleStatus } from '../schemas/offeringBanner';
|
||||
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 {
|
||||
offering: OfferingDto;
|
||||
isFirst: boolean;
|
||||
@@ -23,6 +29,26 @@ export function OfferingRow({ offering, isFirst, isLast, onDeleteRequested }: Of
|
||||
const updateOffering = useUpdateOffering();
|
||||
const moveUp = useMoveOffering('up');
|
||||
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
|
||||
// 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}
|
||||
</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>{offering.price}</TableCell>
|
||||
<TableCell>
|
||||
@@ -61,20 +100,7 @@ export function OfferingRow({ offering, isFirst, isLast, onDeleteRequested }: Of
|
||||
size="icon"
|
||||
data-testid={`offering-row-${offering.id}-featured-toggle`}
|
||||
aria-label={offering.featured ? t('offerings.actions.unmarkFeatured') : t('offerings.actions.markFeatured')}
|
||||
onClick={() =>
|
||||
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,
|
||||
})
|
||||
}
|
||||
onClick={() => updateOffering.mutate({ ...fullBody, featured: !offering.featured })}
|
||||
>
|
||||
<Star className={`size-4 ${offering.featured ? 'fill-yellow-400 text-yellow-400' : ''}`} />
|
||||
</Button>
|
||||
@@ -101,6 +127,17 @@ export function OfferingRow({ offering, isFirst, isLast, onDeleteRequested }: Of
|
||||
>
|
||||
<ChevronDown className="size-4" />
|
||||
</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`}>
|
||||
<Link to="/offerings/$id/edit" params={{ id: offering.id }} aria-label={t('offerings.actions.edit')}>
|
||||
<Pencil className="size-4" />
|
||||
|
||||
@@ -30,6 +30,9 @@ const seed: OfferingDto[] = [
|
||||
ctaLabel: 'Get started',
|
||||
featured: false,
|
||||
displayOrder: 0,
|
||||
isActive: true,
|
||||
startsAt: null,
|
||||
endsAt: null,
|
||||
},
|
||||
{
|
||||
id: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
|
||||
@@ -42,6 +45,9 @@ const seed: OfferingDto[] = [
|
||||
ctaLabel: 'Get started',
|
||||
featured: true,
|
||||
displayOrder: 1,
|
||||
isActive: true,
|
||||
startsAt: null,
|
||||
endsAt: null,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -119,7 +125,23 @@ export const offeringsHandlers = [
|
||||
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 }) => {
|
||||
const body = (await request.json()) as CreateOfferingRequest;
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useCreateOffering } from '../services/useCreateOffering';
|
||||
import { useUpdateOffering } from '../services/useUpdateOffering';
|
||||
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
|
||||
import type { OfferingFormData } from '../schemas/offering';
|
||||
import { fromLocalInput } from '../schemas/offeringBanner';
|
||||
|
||||
export function OfferingFormPage() {
|
||||
const { t } = useTranslation();
|
||||
@@ -25,11 +26,12 @@ export function OfferingFormPage() {
|
||||
|
||||
const onSubmit = async (values: OfferingFormData) => {
|
||||
setServerError(null);
|
||||
const body = { ...values, startsAt: fromLocalInput(values.startsAt), endsAt: fromLocalInput(values.endsAt) };
|
||||
try {
|
||||
if (isEdit && id !== undefined) {
|
||||
await updateOffering.mutateAsync({ id, ...values });
|
||||
await updateOffering.mutateAsync({ id, ...body });
|
||||
} else {
|
||||
await createOffering.mutateAsync(values);
|
||||
await createOffering.mutateAsync(body);
|
||||
}
|
||||
toast.success(t('offerings.form.successToast'));
|
||||
navigate({ to: '/offerings' });
|
||||
@@ -61,7 +63,12 @@ export function OfferingFormPage() {
|
||||
onDismiss={() => setServerError(null)}
|
||||
/>
|
||||
|
||||
<OfferingForm initialValues={existingOffering} onSubmit={onSubmit} isSubmitting={isSubmitting} />
|
||||
<OfferingForm
|
||||
initialValues={existingOffering}
|
||||
onSubmit={onSubmit}
|
||||
onCancel={() => navigate({ to: '/offerings' })}
|
||||
isSubmitting={isSubmitting}
|
||||
/>
|
||||
</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();
|
||||
});
|
||||
|
||||
const OFFERINGS_URL = `${API_BASE}/api/v1/offerings`;
|
||||
const OFFERINGS_URL = `${API_BASE}/api/v1/offerings/all`;
|
||||
|
||||
describe('OfferingsListPage', () => {
|
||||
it('renders the page title and Add button', async () => {
|
||||
@@ -90,7 +90,7 @@ describe('OfferingsListPage', () => {
|
||||
mockAuthenticated();
|
||||
let sentBody: { orderedIds: string[] } | undefined;
|
||||
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[] };
|
||||
return new HttpResponse(null, { status: 204 });
|
||||
}),
|
||||
|
||||
@@ -10,6 +10,9 @@ function validOffering() {
|
||||
features: ['1 page'],
|
||||
ctaLabel: 'Get started',
|
||||
featured: false,
|
||||
isActive: true,
|
||||
startsAt: '',
|
||||
endsAt: '',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -48,4 +51,19 @@ describe('offeringFormSchema', () => {
|
||||
const result = offeringFormSchema.safeParse({ ...validOffering(), title: '' });
|
||||
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,31 +1,41 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const offeringFormSchema = z.object({
|
||||
title: z.string().min(1, 'Title is required').max(100, 'Title must be 100 characters or fewer'),
|
||||
description: z
|
||||
.string()
|
||||
.min(1, 'Description is required')
|
||||
.max(500, 'Description must be 500 characters or fewer'),
|
||||
price: z.string().min(1, 'Price is required').max(50, 'Price must be 50 characters or fewer'),
|
||||
priceNote: z
|
||||
.string()
|
||||
.min(1, 'Price note is required')
|
||||
.max(100, 'Price note must be 100 characters or fewer'),
|
||||
features: z
|
||||
.array(z.string().min(1, 'Feature cannot be empty').max(200, 'Feature must be 200 characters or fewer'))
|
||||
.min(1, 'At least 1 feature is required')
|
||||
.max(10, 'At most 10 features are allowed'),
|
||||
ctaLabel: z.string().min(1, 'CTA label is required').max(50, 'CTA label must be 50 characters or fewer'),
|
||||
featured: z.boolean(),
|
||||
slug: z
|
||||
.string()
|
||||
.max(130, 'Slug must be 130 characters or fewer')
|
||||
.regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, 'Slug may only contain lowercase letters, digits and hyphens')
|
||||
.optional()
|
||||
.or(z.literal('')),
|
||||
/** Id of the chosen category; null/absent = no category. */
|
||||
categoryId: z.string().nullable().optional(),
|
||||
});
|
||||
export const offeringFormSchema = z
|
||||
.object({
|
||||
title: z.string().min(1, 'Title is required').max(100, 'Title must be 100 characters or fewer'),
|
||||
description: z
|
||||
.string()
|
||||
.min(1, 'Description is required')
|
||||
.max(500, 'Description must be 500 characters or fewer'),
|
||||
price: z.string().min(1, 'Price is required').max(50, 'Price must be 50 characters or fewer'),
|
||||
priceNote: z
|
||||
.string()
|
||||
.min(1, 'Price note is required')
|
||||
.max(100, 'Price note must be 100 characters or fewer'),
|
||||
features: z
|
||||
.array(z.string().min(1, 'Feature cannot be empty').max(200, 'Feature must be 200 characters or fewer'))
|
||||
.min(1, 'At least 1 feature is required')
|
||||
.max(10, 'At most 10 features are allowed'),
|
||||
ctaLabel: z.string().min(1, 'CTA label is required').max(50, 'CTA label must be 50 characters or fewer'),
|
||||
featured: z.boolean(),
|
||||
slug: z
|
||||
.string()
|
||||
.max(130, 'Slug must be 130 characters or fewer')
|
||||
.regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, 'Slug may only contain lowercase letters, digits and hyphens')
|
||||
.optional()
|
||||
.or(z.literal('')),
|
||||
/** Id of the chosen category; null/absent = no category. */
|
||||
categoryId: z.string().nullable().optional(),
|
||||
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>;
|
||||
|
||||
|
||||
@@ -88,3 +88,9 @@ export function bannerStatus(b: { isActive: boolean; startsAt: string | null; en
|
||||
if (b.endsAt && new Date(b.endsAt) <= now) return 'expired';
|
||||
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;
|
||||
/** Name of the category (renames show up here automatically). */
|
||||
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 {
|
||||
@@ -27,6 +33,9 @@ export interface CreateOfferingRequest {
|
||||
slug?: string;
|
||||
/** Category id; null clears the category. */
|
||||
categoryId?: string | null;
|
||||
isActive: boolean;
|
||||
startsAt: string | null;
|
||||
endsAt: string | null;
|
||||
}
|
||||
|
||||
export type UpdateOfferingRequest = CreateOfferingRequest;
|
||||
|
||||
@@ -5,6 +5,6 @@ import type { OfferingDto } from './types';
|
||||
export function useOfferings() {
|
||||
return useQuery<OfferingDto[], Error>({
|
||||
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": {
|
||||
"turnOff": "Switch package off",
|
||||
"turnOn": "Switch package on",
|
||||
"drag": "Drag to reorder",
|
||||
"edit": "Edit",
|
||||
"delete": "Delete",
|
||||
@@ -418,6 +420,11 @@
|
||||
"form": {
|
||||
"createTitle": "New 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",
|
||||
"slugLabel": "Slug",
|
||||
"slugAutoHint": "Auto-generated from the title",
|
||||
@@ -430,7 +437,7 @@
|
||||
"featuresLabel": "Features",
|
||||
"addFeatureButton": "Add feature",
|
||||
"removeFeatureButton": "Remove",
|
||||
"ctaLabelLabel": "Button text",
|
||||
"ctaLabelLabel": "Button text",
|
||||
"featuredLabel": "Featured",
|
||||
"categoryLabel": "Category",
|
||||
"noCategory": "No category",
|
||||
|
||||
@@ -401,6 +401,8 @@
|
||||
"actions": "Acties"
|
||||
},
|
||||
"actions": {
|
||||
"turnOff": "Pakket uitzetten",
|
||||
"turnOn": "Pakket aanzetten",
|
||||
"drag": "Sleep om te herordenen",
|
||||
"edit": "Bewerken",
|
||||
"delete": "Verwijderen",
|
||||
@@ -418,6 +420,11 @@
|
||||
"form": {
|
||||
"createTitle": "Nieuwe aanbieding",
|
||||
"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",
|
||||
"slugLabel": "Slug",
|
||||
"slugAutoHint": "Wordt automatisch gegenereerd uit de titel",
|
||||
@@ -430,7 +437,7 @@
|
||||
"featuresLabel": "Kenmerken",
|
||||
"addFeatureButton": "Kenmerk toevoegen",
|
||||
"removeFeatureButton": "Verwijderen",
|
||||
"ctaLabelLabel": "Knoptekst",
|
||||
"ctaLabelLabel": "Knoptekst",
|
||||
"featuredLabel": "Uitgelicht",
|
||||
"categoryLabel": "Categorie",
|
||||
"noCategory": "Geen categorie",
|
||||
|
||||
Reference in New Issue
Block a user