Artikel DB struktur geändert von CODEX

This commit is contained in:
Marco_205 committed 2026-10-12 14:42:28 +00:00
1 parent 0c0a678eaa
commit 9c18234efe
95 files changed
+3872 -2316

No files matched your search

@@ -1,106 +1,329 @@
"use client";
'use client';
import { emptyArticleDto, Article, ArticleCreate, Category, Manufacturer, ArticleUpsert } from "../../types/catalog"
import { FormProvider, useForm } from "react-hook-form"
import { ArticleBaseForm } from "./articleBase.form";
import { ArticleVariantForm } from "./articleVariants.form";
import { articleCreate, articleUpdate } from "../../actions/article.actions";
import { useEffect, useState } from "react";
import Modal from "../ui/modal";
import { ManufactuererForm } from "../manufacturer/manufacturer.form";
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 Params {
categories: Category[]
manufacturer: Manufacturer[]
initData?: ArticleUpsert
debug?: boolean
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]);
export const ArticleMainForm = ({ categories, manufacturer, initData, debug }: Params) => {
const methods = useForm<ArticleUpsert>({ defaultValues: emptyArticleDto });
const [errMsg, setErrorMsg] = useState<string[]>([])
const [error, setError] = useState(false)
const [creatManufacturer, setCreatManufacturer] = useState(-1);
const [hersteller,setHersteller] = useState<Manufacturer[]>([])
useEffect(() => {
setHersteller(manufacturer);
if (initData && initData._id) {
methods.reset(initData);
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;
}
}, [initData])
const handlerCreatManufacturer = (data: Manufacturer) => {
console.log('Create')
setHersteller((cur)=>([...cur,data]));
methods.setValue(
`variants.${creatManufacturer}.manufacturerId`,
data._id,
{ shouldDirty: true, shouldValidate: true }
);
setCreatManufacturer(-1)
attributes[key] = Number(property.value);
} else
attributes[key] =
property.type === 'boolean'
? property.value === 'true'
: property.value;
}
const onSubmit = async (data: ArticleUpsert) => {
if (initData?._id) {
const result = await articleUpdate(initData._id, data)
if (!result.success) {
setError(true)
setErrorMsg(() => result.errors)
console.log(result)
} else {
setError(false)
}
} else {
console.log('create')
const { name, categoryId, variants, attributes } = data;
if (categoryId) {
const create = {
name,
categoryId,
variants,
attributes
}
articleCreate(create);
}
}
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();
}
};
return (
<div className="me-30 flex flex-col p-4 pt-10 ps-10" >
<FormProvider {...methods}>
{initData?._id && <div>{initData._id}</div>}
<form onSubmit={methods.handleSubmit(onSubmit)}>
<ArticleBaseForm categories={categories}></ArticleBaseForm>
<ArticleVariantForm manufacturer={hersteller} onOpenManufacturer={(index) => setCreatManufacturer(index)}></ArticleVariantForm>
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);
}
};
<div>{methods.watch("name")}</div>
<pre>{JSON.stringify(methods.watch(), null, 2)}</pre>
<button type="submit">Absenden</button>
</form>
</FormProvider>
<Modal open={creatManufacturer >= 0} onClose={() => setCreatManufacturer(-1)}>
<ManufactuererForm onChangeData={(d) => handlerCreatManufacturer(d)}></ManufactuererForm>
<button onClick={() => setCreatManufacturer(-1)}>Abbruch</button>
</Modal>
{error && <div className="border-1 border-red-400 bg-red-200">
Error
{errMsg.map((msg, id) => (<div key={id}>{msg}</div>))}
</div>}
</div>
)
}
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>
);
};