349 lines
16 KiB
TypeScript
349 lines
16 KiB
TypeScript
import { useEffect, useState } from 'react';
|
|
import { useForm, useWatch } from 'react-hook-form';
|
|
import { zodResolver } from '@hookform/resolvers/zod';
|
|
import { useTranslation } from 'react-i18next';
|
|
import { Check, Pencil, Plus, Trash2, X } from 'lucide-react';
|
|
import { Button } from '@/components/ui/button';
|
|
import { Input } from '@/components/ui/input';
|
|
import { Label } from '@/components/ui/label';
|
|
import { FieldError } from '@/components/ui/FieldError';
|
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
|
import { useOfferingCategories } from '../services/useOfferingCategories';
|
|
import { slugifyPreview } from '@/lib/slugify';
|
|
import { offeringFormSchema, type OfferingFormData } from '../schemas/offering';
|
|
import { 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, onCancel, isSubmitting }: OfferingFormProps) {
|
|
const { t } = useTranslation();
|
|
|
|
const {
|
|
register,
|
|
control,
|
|
handleSubmit,
|
|
setValue,
|
|
resetField,
|
|
formState: { errors, dirtyFields },
|
|
} = useForm<OfferingFormData>({
|
|
resolver: zodResolver(offeringFormSchema),
|
|
mode: 'onTouched',
|
|
defaultValues: initialValues
|
|
? {
|
|
...initialValues,
|
|
isActive: initialValues.isActive ?? true,
|
|
startsAt: toLocalInput(initialValues.startsAt ?? null),
|
|
endsAt: toLocalInput(initialValues.endsAt ?? null),
|
|
}
|
|
: {
|
|
title: '',
|
|
description: '',
|
|
price: '',
|
|
priceNote: '',
|
|
features: [''],
|
|
ctaLabel: '',
|
|
featured: false,
|
|
slug: '',
|
|
categoryId: null,
|
|
isActive: true,
|
|
startsAt: '',
|
|
endsAt: '',
|
|
},
|
|
});
|
|
|
|
// Radix Select does not allow an empty value, so "no category" is the sentinel 'none' here
|
|
// and is mapped back to null for the form value.
|
|
const NO_CATEGORY = 'none';
|
|
const { data: categories, isFetching: isFetchingCategories } = useOfferingCategories();
|
|
const categoryId = useWatch({ control, name: 'categoryId' });
|
|
const selectedCategory =
|
|
categoryId != null && categories?.some((c) => c.id === categoryId) ? categoryId : NO_CATEGORY;
|
|
|
|
// A category that no longer exists (deleted meanwhile) falls back to "no category" so the
|
|
// form never submits an id the API would reject. Only judged on fresh data: a cached list
|
|
// that is being refetched may still be missing a category that does exist.
|
|
useEffect(() => {
|
|
if (
|
|
categories !== undefined &&
|
|
!isFetchingCategories &&
|
|
categoryId != null &&
|
|
!categories.some((c) => c.id === categoryId)
|
|
) {
|
|
setValue('categoryId', null);
|
|
}
|
|
}, [categories, isFetchingCategories, categoryId, setValue]);
|
|
|
|
// useFieldArray requires object-shaped array items — features is a plain string[],
|
|
// so add/remove are handled directly via setValue instead.
|
|
const features = useWatch({ control, name: 'features' });
|
|
const title = useWatch({ control, name: 'title' });
|
|
const slug = useWatch({ control, name: 'slug' });
|
|
const [isEditingSlug, setIsEditingSlug] = useState(false);
|
|
|
|
// Once the admin has manually set a non-empty slug, it stops tracking the title — mirrors
|
|
// OfferingsService: an explicit Slug always wins, an untouched one keeps auto-regenerating.
|
|
const isManuallySet = dirtyFields.slug === true && slug !== undefined && slug.length > 0;
|
|
const displaySlug = isManuallySet ? slug : slugifyPreview(title ?? '');
|
|
|
|
function confirmSlugEdit() {
|
|
setIsEditingSlug(false);
|
|
}
|
|
|
|
function cancelSlugEdit() {
|
|
resetField('slug');
|
|
setIsEditingSlug(false);
|
|
}
|
|
|
|
// Slug is auto-generated from the title server-side unless explicitly overridden here —
|
|
// only send it along when the admin actually touched this field, so an untouched slug
|
|
// keeps auto-regenerating when the title changes (see OfferingsService.UpdateAsync).
|
|
function submitWithSlugPolicy(values: OfferingFormData) {
|
|
const payload = { ...values };
|
|
if (!isManuallySet) {
|
|
delete payload.slug;
|
|
}
|
|
onSubmit(payload);
|
|
}
|
|
|
|
function addFeature() {
|
|
setValue('features', [...features, ''], { shouldValidate: true });
|
|
}
|
|
|
|
function removeFeature(index: number) {
|
|
setValue('features', features.filter((_, i) => i !== index), { shouldValidate: true });
|
|
}
|
|
|
|
return (
|
|
<form onSubmit={handleSubmit(submitWithSlugPolicy)} noValidate className="space-y-4">
|
|
<div className="space-y-2">
|
|
<Label htmlFor="offering-title">{t('offerings.form.titleLabel')}</Label>
|
|
<Input id="offering-title" data-testid="offering-title" aria-invalid={errors.title !== undefined} {...register('title')} />
|
|
{errors.title && <FieldError message={errors.title.message} testId="offering-title-error" />}
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
{isEditingSlug ? (
|
|
<div className="flex items-center gap-2 text-sm">
|
|
<Label htmlFor="offering-slug" className="text-muted-foreground">
|
|
{t('offerings.form.slugLabel')}:
|
|
</Label>
|
|
<Input
|
|
id="offering-slug"
|
|
data-testid="offering-slug"
|
|
autoFocus
|
|
className="h-8 max-w-xs"
|
|
aria-invalid={errors.slug !== undefined}
|
|
{...register('slug')}
|
|
/>
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon"
|
|
data-testid="offering-slug-confirm"
|
|
aria-label={t('offerings.form.confirmSlugButton')}
|
|
onClick={confirmSlugEdit}
|
|
>
|
|
<Check className="size-4" />
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon"
|
|
data-testid="offering-slug-cancel"
|
|
aria-label={t('offerings.form.cancelSlugEditButton')}
|
|
onClick={cancelSlugEdit}
|
|
>
|
|
<X className="size-4" />
|
|
</Button>
|
|
</div>
|
|
) : (
|
|
<div className="flex items-center gap-2 text-sm">
|
|
<span className="text-muted-foreground">{t('offerings.form.slugLabel')}:</span>
|
|
<code data-testid="offering-slug-display" className="font-mono">
|
|
{displaySlug.length > 0 ? displaySlug : t('offerings.form.slugAutoHint')}
|
|
</code>
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon"
|
|
data-testid="offering-slug-edit"
|
|
aria-label={t('offerings.form.editSlugButton')}
|
|
onClick={() => setIsEditingSlug(true)}
|
|
>
|
|
<Pencil className="size-4" />
|
|
</Button>
|
|
</div>
|
|
)}
|
|
{errors.slug && <FieldError message={errors.slug.message} testId="offering-slug-error" />}
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<Label htmlFor="offering-description">{t('offerings.form.descriptionLabel')}</Label>
|
|
<textarea
|
|
id="offering-description"
|
|
data-testid="offering-description"
|
|
aria-invalid={errors.description !== undefined}
|
|
className="flex min-h-24 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
|
|
{...register('description')}
|
|
/>
|
|
{errors.description && <FieldError message={errors.description.message} testId="offering-description-error" />}
|
|
</div>
|
|
|
|
<div className="grid grid-cols-2 gap-4">
|
|
<div className="space-y-2">
|
|
<Label htmlFor="offering-price">{t('offerings.form.priceLabel')}</Label>
|
|
<Input id="offering-price" data-testid="offering-price" aria-invalid={errors.price !== undefined} {...register('price')} />
|
|
{errors.price && <FieldError message={errors.price.message} testId="offering-price-error" />}
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<Label htmlFor="offering-price-note">{t('offerings.form.priceNoteLabel')}</Label>
|
|
<Input
|
|
id="offering-price-note"
|
|
data-testid="offering-price-note"
|
|
aria-invalid={errors.priceNote !== undefined}
|
|
{...register('priceNote')}
|
|
/>
|
|
{errors.priceNote && <FieldError message={errors.priceNote.message} testId="offering-price-note-error" />}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<Label htmlFor="offering-category">{t('offerings.form.categoryLabel')}</Label>
|
|
<Select
|
|
value={selectedCategory}
|
|
onValueChange={(value) => {
|
|
// Radix reports an empty value while its options are still loading (the
|
|
// chosen category is not in the list yet); that is not a user choice.
|
|
if (value === '') return;
|
|
setValue('categoryId', value === NO_CATEGORY ? null : value, { shouldDirty: true });
|
|
}}
|
|
>
|
|
<SelectTrigger id="offering-category" data-testid="offering-category">
|
|
<SelectValue />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
<SelectItem value={NO_CATEGORY} data-testid="offering-category-none">
|
|
{t('offerings.form.noCategory')}
|
|
</SelectItem>
|
|
{categories?.map((category) => (
|
|
<SelectItem
|
|
key={category.id}
|
|
value={category.id}
|
|
data-testid={`offering-category-option-${category.id}`}
|
|
>
|
|
{category.name}
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<Label>{t('offerings.form.featuresLabel')}</Label>
|
|
{features.map((_, index) => (
|
|
<div key={index} className="flex items-center gap-2">
|
|
<Input
|
|
data-testid={`offering-feature-${index}`}
|
|
aria-invalid={errors.features?.[index] !== undefined}
|
|
{...register(`features.${index}` as const)}
|
|
/>
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon"
|
|
data-testid={`offering-feature-${index}-remove`}
|
|
aria-label={t('offerings.form.removeFeatureButton')}
|
|
disabled={features.length <= 1}
|
|
onClick={() => removeFeature(index)}
|
|
>
|
|
<Trash2 className="size-4" />
|
|
</Button>
|
|
</div>
|
|
))}
|
|
{errors.features?.message && <FieldError message={errors.features.message} testId="offering-features-error" />}
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
size="sm"
|
|
data-testid="offering-add-feature"
|
|
disabled={features.length >= 10}
|
|
onClick={addFeature}
|
|
>
|
|
<Plus className="size-4" />
|
|
{t('offerings.form.addFeatureButton')}
|
|
</Button>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<Label htmlFor="offering-cta-label">{t('offerings.form.ctaLabelLabel')}</Label>
|
|
<Input
|
|
id="offering-cta-label"
|
|
data-testid="offering-cta-label"
|
|
aria-invalid={errors.ctaLabel !== undefined}
|
|
{...register('ctaLabel')}
|
|
/>
|
|
{errors.ctaLabel && <FieldError message={errors.ctaLabel.message} testId="offering-cta-label-error" />}
|
|
</div>
|
|
|
|
<div className="flex items-center gap-2">
|
|
<input
|
|
id="offering-featured"
|
|
type="checkbox"
|
|
data-testid="offering-featured"
|
|
className="size-4 rounded border-input"
|
|
{...register('featured')}
|
|
/>
|
|
<Label htmlFor="offering-featured">{t('offerings.form.featuredLabel')}</Label>
|
|
</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">
|
|
{isSubmitting ? '…' : t('offerings.form.submitButton')}
|
|
</Button>
|
|
</div>
|
|
</form>
|
|
);
|
|
}
|