Files

330 lines
11 KiB
TypeScript

'use client';
import {
Article,
ArticleAttributes,
ArticleCreate,
ArticleGroup,
Category,
Manufacturer,
emptyArticleDto,
} from '../../types/catalog';
import { FormProvider, useForm } from 'react-hook-form';
import { ArticleBaseForm } from './articleBase.form';
import { ArticlePackagingForm } from './articleVariants.form';
import {
articleCreate,
articleGroupCreate,
articleUpdate,
} from '../../actions/article.actions';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Modal from '../ui/modal';
import { ManufactuererForm } from '../manufacturer/manufacturer.form';
import { InputTextR } from '../ui/inputTextR';
import { sites } from '../../_config/sites';
interface Props {
categories: Category[];
manufacturer: Manufacturer[];
groups: ArticleGroup[];
initData?: Article;
}
function formValues(article?: Article): ArticleCreate {
if (!article) return emptyArticleDto;
return {
articleNumber: article.articleNumber,
name: article.name,
description: article.description ?? '',
categoryId: article.categoryId ?? '',
manufacturerId: article.manufacturerId ?? '',
groupId: article.groupId ?? '',
manufacturerArticleNumber: article.manufacturerArticleNumber ?? '',
barcode: article.barcode ?? '',
baseUnit: article.baseUnit,
isConsumable: article.isConsumable,
trackingMode: article.trackingMode,
tracksExpiryDate: article.tracksExpiryDate,
packaging: article.packaging ?? [],
attributes: article.attributes ?? {},
};
}
export const ArticleMainForm = ({
categories,
manufacturer,
groups,
initData,
}: Props) => {
const methods = useForm<ArticleCreate>({
defaultValues: formValues(initData),
});
const router = useRouter();
const [errors, setErrors] = useState<string[]>([]);
const [manufacturers, setManufacturers] = useState(manufacturer);
const [productGroups, setProductGroups] = useState(groups);
const [manufacturerOpen, setManufacturerOpen] = useState(false);
const [groupOpen, setGroupOpen] = useState(false);
const [groupName, setGroupName] = useState('');
const [groupSaving, setGroupSaving] = useState(false);
const [properties, setProperties] = useState<
{ key: string; value: string; type: 'string' | 'number' | 'boolean' }[]
>([]);
useEffect(() => {
methods.reset(formValues(initData));
setProperties(
Object.entries(initData?.attributes ?? {}).map(([key, value]) => ({
key,
value: String(value),
type: typeof value as 'string' | 'number' | 'boolean',
})),
);
}, [initData, methods]);
const onSubmit = async (data: ArticleCreate) => {
setErrors([]);
const attributes: ArticleAttributes = {};
for (const property of properties) {
const key = property.key.trim();
if (
!key ||
Object.hasOwn(attributes, key) ||
['__proto__', 'constructor', 'prototype'].includes(key) ||
key.includes('.') ||
key.startsWith('$')
) {
setErrors(['Eigenschaften benötigen unterschiedliche, gültige Namen.']);
return;
}
if (property.type === 'number') {
if (
!property.value.trim() ||
!Number.isFinite(Number(property.value))
) {
setErrors([`${key}: Bitte eine gültige Zahl eingeben.`]);
return;
}
attributes[key] = Number(property.value);
} else
attributes[key] =
property.type === 'boolean'
? property.value === 'true'
: property.value;
}
const payload = {
...data,
categoryId: data.categoryId || null,
manufacturerId: data.manufacturerId || null,
groupId: data.groupId || null,
attributes,
};
const result = initData
? await articleUpdate(initData._id, payload)
: await articleCreate(payload);
if (!result.success) setErrors(result.errors);
else {
router.push(sites.article.url);
router.refresh();
}
};
const addGroup = async () => {
if (!groupName.trim()) return;
setGroupSaving(true);
try {
const result = await articleGroupCreate(groupName.trim());
if (!result.success) {
setErrors(result.errors);
return;
}
const group = result.data as ArticleGroup;
setProductGroups((current) => [...current, group]);
methods.setValue('groupId', group._id);
setGroupOpen(false);
setGroupName('');
} finally {
setGroupSaving(false);
}
};
return (
<div className="max-w-4xl p-6">
<h1 className="text-xl mb-4">
{initData ? 'Artikel bearbeiten' : 'Artikel anlegen'}
</h1>
<FormProvider {...methods}>
<form onSubmit={methods.handleSubmit(onSubmit)}>
<ArticleBaseForm
categories={categories}
manufacturer={manufacturers}
groups={productGroups}
/>
<div className="flex gap-3 mt-3">
<button
type="button"
className="border rounded px-3 py-1"
onClick={() => setManufacturerOpen(true)}
>
Hersteller anlegen
</button>
<button
type="button"
className="border rounded px-3 py-1"
onClick={() => setGroupOpen(true)}
>
Produktgruppe anlegen
</button>
</div>
<fieldset className="border rounded p-3 mt-4">
<legend>Eigenschaften (optional)</legend>
{properties.map((property, index) => (
<div key={index} className="grid gap-2 md:grid-cols-4 mb-2">
<InputTextR
label="Eigenschaft"
value={property.key}
onChange={(event) =>
setProperties((current) =>
current.map((item, i) =>
i === index
? { ...item, key: event.target.value }
: item,
),
)
}
/>
<label>
Typ
<select
className="block border rounded p-1"
value={property.type}
onChange={(event) =>
setProperties((current) =>
current.map((item, i) =>
i === index
? {
...item,
type: event.target
.value as typeof property.type,
value:
event.target.value === 'boolean'
? 'false'
: '',
}
: item,
),
)
}
>
<option value="string">Text</option>
<option value="number">Zahl</option>
<option value="boolean">Ja / Nein</option>
</select>
</label>
{property.type === 'boolean' ? (
<label>
Wert
<select
className="block border rounded p-1"
value={property.value}
onChange={(event) =>
setProperties((current) =>
current.map((item, i) =>
i === index
? { ...item, value: event.target.value }
: item,
),
)
}
>
<option value="true">Ja</option>
<option value="false">Nein</option>
</select>
</label>
) : (
<InputTextR
label="Wert"
type={property.type === 'number' ? 'number' : 'text'}
step="any"
value={property.value}
onChange={(event) =>
setProperties((current) =>
current.map((item, i) =>
i === index
? { ...item, value: event.target.value }
: item,
),
)
}
/>
)}
<button
type="button"
onClick={() =>
setProperties((current) =>
current.filter((_, i) => i !== index),
)
}
>
Entfernen
</button>
</div>
))}
<button
type="button"
className="border rounded px-3 py-1"
onClick={() =>
setProperties((current) => [
...current,
{ key: '', type: 'string', value: '' },
])
}
>
Eigenschaft hinzufügen
</button>
</fieldset>
<ArticlePackagingForm />
<button
className="bg-sky-700 text-white rounded px-4 py-2 mt-4"
type="submit"
disabled={
methods.formState.isSubmitting || Boolean(initData?.archivedAt)
}
>
{methods.formState.isSubmitting ? 'Speichert …' : 'Speichern'}
</button>
</form>
</FormProvider>
{errors.length > 0 && (
<ul role="alert" className="text-red-700 mt-3">
{errors.map((error, index) => (
<li key={index}>{error}</li>
))}
</ul>
)}
<Modal open={manufacturerOpen} onClose={() => setManufacturerOpen(false)}>
<ManufactuererForm
onChangeData={(item) => {
setManufacturers((current) => [...current, item]);
methods.setValue('manufacturerId', item._id);
setManufacturerOpen(false);
}}
/>
</Modal>
<Modal open={groupOpen} onClose={() => setGroupOpen(false)}>
<InputTextR
label="Gruppenname"
value={groupName}
onChange={(event) => setGroupName(event.target.value)}
/>
<button
type="button"
disabled={groupSaving || !groupName.trim()}
onClick={addGroup}
>
Gruppe speichern
</button>
</Modal>
</div>
);
};