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

+83 -80
View File
@@ -1,94 +1,97 @@
'use server'
'use server';
import { revalidatePath } from 'next/cache'
import { Article, ArticleCreate, ArticleUpsert } from "@/apps/frontend/types/catalog";
import { revalidatePath } from 'next/cache';
import {
Article,
ArticleCreate,
ArticleGroup,
ArticleUpsert,
} from '../types/catalog';
import { sites } from '../_config/sites';
import { endpoints } from '../_config/endpoints';
export async function articleCreate(data: ArticleCreate) {
console.log(data);
const result = await fetch('http://192.168.50.205/api/articles', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
const resultData = await result.json();
const api = endpoints.apiServer.url;
if (!result.ok) {
async function mutate(
url: string,
method: string,
data?: unknown,
): Promise<ActionResult> {
try {
const response = await fetch(`${api}${url}`, {
method,
headers: { 'Content-Type': 'application/json' },
body: data === undefined ? undefined : JSON.stringify(data),
});
const result = await response.json();
if (!response.ok) {
return {
success: false,
errors: Array.isArray(result.message)
? result.message
: [result.message ?? 'Speichern fehlgeschlagen'],
};
}
revalidatePath(sites.article.url);
return { success: true, data: result };
} catch {
return {
success: false,
errors: resultData.message, // kommt aus NestJS
errors: [
'Der Artikelserver ist nicht erreichbar. Bitte erneut versuchen.',
],
};
}
revalidatePath(sites.article.new.url)
}
export async function articleUpdate(id: string, data: ArticleUpsert): Promise<ActionResult> {
const result = await fetch(`http://192.168.50.205/api/articles/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
const resultData = await result.json();
if (!result.ok) {
return {
success: false,
errors: resultData.message, // kommt aus NestJS
};
}
revalidatePath(sites.article.update.url + '/' + id);
return { success: true };
export async function articleCreate(
data: ArticleCreate,
): Promise<ActionResult> {
return mutate('/articles', 'POST', data);
}
export async function articleUpdate(
id: string,
data: ArticleUpsert,
): Promise<ActionResult> {
const result = await mutate(`/articles/${id}`, 'PATCH', data);
if (result.success) revalidatePath(`${sites.article.update.url}/${id}`);
return result;
}
export async function articleFindAll(): Promise<Article[]> {
const result = await fetch(`http://192.168.50.205/api/articles`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
})
const data = await result.json() as Article[];
return data;
const response = await fetch(`${api}/articles`, { cache: 'no-store' });
if (!response.ok) throw new Error('Artikel konnten nicht geladen werden');
return response.json();
}
export async function articleFindById(id: string): Promise<Article | null> {
const response = await fetch(`${api}/articles/${id}`, { cache: 'no-store' });
if (response.status === 404) return null;
if (!response.ok) throw new Error('Artikel konnte nicht geladen werden');
return response.json();
}
export async function articleDelete(
id: string,
revalidateUrl?: string,
): Promise<ActionResult> {
const result = await mutate(`/articles/${id}`, 'DELETE');
if (result.success && revalidateUrl) revalidatePath(revalidateUrl);
return result;
}
export async function articleGroupsFindAll(): Promise<ArticleGroup[]> {
const response = await fetch(`${api}/article-groups`, { cache: 'no-store' });
if (!response.ok)
throw new Error('Produktgruppen konnten nicht geladen werden');
return response.json();
}
export async function articleGroupCreate(name: string): Promise<ActionResult> {
return mutate('/article-groups', 'POST', { name });
}
export async function articleFindById(id: string): Promise<any> {
const result = await fetch(`http://192.168.50.205/api/articles/${id}`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
})
const data = await result.json() as Article
console.log('getArticle', data)
return data;
export async function articleMigrationStatus(): Promise<{
pendingLegacyArticles: number;
}> {
const response = await fetch(`${api}/articles/migration-status`, {
cache: 'no-store',
});
if (!response.ok)
throw new Error('Migrationsstatus konnte nicht geladen werden');
return response.json();
}
export async function articleDelete(id: string,revalidateUrl?:string): Promise<ActionResult> {
const result = await fetch(`http://192.168.50.205/api/articles/${id}`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' }
})
const resultData = await result.json();
if (!result.ok) {
return {
success: false,
errors: resultData.message, // kommt aus NestJS
};
}
if(revalidateUrl) revalidatePath(revalidateUrl);
return { success: true };
}
+70 -85
View File
@@ -1,94 +1,79 @@
'use server'
'use server';
import { revalidatePath } from 'next/cache'
import { revalidatePath } from 'next/cache';
import { sites } from '../_config/sites';
import { Stock, StockCreate, StockUpdate } from '../types/inventory/stockContent.types';
import { endpoints } from '../_config/endpoints';
import {
Stock,
StockCreate,
StockUpdate,
} from '../types/inventory/stock.types';
import { StockContent } from '../types/inventory/stockContent.types';
import {
StockMovementIn,
StockMovementOut,
StockMovementTransfer,
} from '../types/inventory/stockMovement.types';
const api = endpoints.apiServer.url;
async function mutate(
path: string,
method: string,
data?: unknown,
): Promise<ActionResult> {
try {
const response = await fetch(`${api}${path}`, {
method,
headers: { 'Content-Type': 'application/json' },
body: data === undefined ? undefined : JSON.stringify(data),
});
const result = await response.json();
if (!response.ok)
return {
success: false,
errors: Array.isArray(result.message)
? result.message
: [result.message ?? 'Buchung fehlgeschlagen'],
};
revalidatePath(sites.stock.new.url);
return { success: true, data: result };
} catch {
return {
success: false,
errors: ['Der Lagerserver ist nicht erreichbar. Bitte erneut versuchen.'],
};
}
}
export async function stockCreate(data: StockCreate) {
const result = await fetch('http://192.168.50.205/api/stock', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
const resultData = await result.json();
if (!result.ok) {
return {
success: false,
errors: resultData.message, // kommt aus NestJS
};
}
revalidatePath(sites.stock.new.url)
return mutate('/stock', 'POST', data);
}
export async function stockUpdate(id: string, data: StockUpdate): Promise<ActionResult> {
const result = await fetch(`http://192.168.50.205/api/stocks/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
const resultData = await result.json();
if (!result.ok) {
return {
success: false,
errors: resultData.message, // kommt aus NestJS
};
}
revalidatePath(sites.stock.update.url + '/' + id);
return { success: true };
export async function stockUpdate(id: string, data: StockUpdate) {
return mutate(`/stock/${id}`, 'PATCH', data);
}
export async function stockDelete(id: string) {
return mutate(`/stock/${id}`, 'DELETE');
}
export async function stockFindAll(): Promise<Stock[]> {
const result = await fetch(`http://192.168.50.205/api/stocks`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
})
const data = await result.json() as Stock[];
return data;
const response = await fetch(`${api}/stock`, { cache: 'no-store' });
if (!response.ok) throw new Error('Lager konnten nicht geladen werden');
return response.json();
}
export async function stockFindById(id: string): Promise<any> {
const result = await fetch(`http://192.168.50.205/api/stocks/${id}`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
})
const data = await result.json() as Stock
console.log('getArticle', data)
return data;
export async function stockFindById(id: string) {
const response = await fetch(`${api}/stock/${id}`, { cache: 'no-store' });
if (!response.ok) throw new Error('Lager konnte nicht geladen werden');
return response.json();
}
export async function stockContentFindAll(): Promise<StockContent[]> {
const response = await fetch(`${api}/stock-content`, { cache: 'no-store' });
if (!response.ok) throw new Error('Bestände konnten nicht geladen werden');
return response.json();
}
export async function stockMoveIn(data: StockMovementIn) {
return mutate('/stock-movements/in', 'POST', data);
}
export async function stockMoveOut(data: StockMovementOut) {
return mutate('/stock-movements/out', 'POST', data);
}
export async function stockTransfer(data: StockMovementTransfer) {
return mutate('/stock-movements/transfer', 'POST', data);
}
export async function stockDelete(id: string,revalidateUrl?:string): Promise<ActionResult> {
const result = await fetch(`http://192.168.50.205/api/stocks/${id}`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' }
})
const resultData = await result.json();
if (!result.ok) {
return {
success: false,
errors: resultData.message, // kommt aus NestJS
};
}
if(revalidateUrl) revalidatePath(revalidateUrl);
return { success: true };
}
+35 -32
View File
@@ -1,37 +1,40 @@
import Link from "next/link";
import { sites } from "../../../../_config/sites";
import { articleFindById } from "../../../../actions/article.actions";
import { ArticleMainForm } from "../../../../components/article/articleMain.form";
import { categoryFindAll } from "../../../../actions/category.actions";
import { manufacturerFindAll } from "../../../../actions/manufacturer.actions";
interface PageProps {
params: Promise<{ id: string }>
}
export default async function CatergoryUpdate({ params }: PageProps) {
const { id } = await params
const article = await articleFindById(id);
const cats = await categoryFindAll();
const manufacturer = await manufacturerFindAll();
if(!article._id) {
return (<div>
<div>Artikel nicht gefunden</div>
<div>
<Link className="cursor-pointer p-2 border-1 border-sky-500 bg-sky-500 text-white rounded-full m-1 hover:bg-sky-700 " href={sites.article.url}>zurück1</Link>
</div>
</div>)
}
const {name,category,variants} = article;
console.log('Varianten:',article.variants)
import Link from 'next/link';
import { sites } from '../../../../_config/sites';
import {
articleFindById,
articleGroupsFindAll,
} from '../../../../actions/article.actions';
import { ArticleMainForm } from '../../../../components/article/articleMain.form';
import { categoryFindAll } from '../../../../actions/category.actions';
import { manufacturerFindAll } from '../../../../actions/manufacturer.actions';
export default async function ArticleUpdatePage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const [article, categories, manufacturer, groups] = await Promise.all([
articleFindById(id),
categoryFindAll(),
manufacturerFindAll(),
articleGroupsFindAll(),
]);
return (
<div className="h-screen">
<ArticleMainForm initData={article} categories={cats} manufacturer={manufacturer}></ArticleMainForm>
<Link className="cursor-pointer p-2 border-1 border-sky-500 bg-sky-500 text-white rounded-full m-1 hover:bg-sky-700 " href={sites.article.url}>zurück</Link>
<div>
{article ? (
<ArticleMainForm
initData={article}
categories={categories}
manufacturer={manufacturer}
groups={groups}
/>
) : (
<p>Artikel nicht gefunden.</p>
)}
<Link className="text-sky-700 p-6" href={sites.article.url}>
Zurück zu den Artikeln
</Link>
</div>
);
}
+24 -25
View File
@@ -1,27 +1,26 @@
import { manufacturerFindAll } from "../../../../actions/manufacturer.actions";
import { categoryFindAll } from "../../../../actions/category.actions";
import { ArticleMainForm } from "../../../../components/article/articleMain.form";
import { articleCreate, articleFindAll } from "../../../../actions/article.actions";
import Link from "next/link";
import { sites } from "../../../../../../apps/frontend/_config/sites";
//import { sites } from "@/";
import { manufacturerFindAll } from '../../../../actions/manufacturer.actions';
import { categoryFindAll } from '../../../../actions/category.actions';
import { articleGroupsFindAll } from '../../../../actions/article.actions';
import { ArticleMainForm } from '../../../../components/article/articleMain.form';
import Link from 'next/link';
import { sites } from '../../../../_config/sites';
interface Props {
}
export default async function ArticlePage({ }: Props) {
const cats = await categoryFindAll();
const manufacturer = await manufacturerFindAll();
const artikel = await articleFindAll();
if(!manufacturer) return <div>Keine Hersteller gefunden</div>
return <>
<ArticleMainForm categories={cats} manufacturer={manufacturer}></ArticleMainForm>
<Link href={`${sites.article.url}`} className="text-sky-300">zurück</Link>
export default async function ArticleNewPage() {
const [categories, manufacturer, groups] = await Promise.all([
categoryFindAll(),
manufacturerFindAll(),
articleGroupsFindAll(),
]);
return (
<>
<ArticleMainForm
categories={categories}
manufacturer={manufacturer}
groups={groups}
/>
<Link className="text-sky-700 p-6" href={sites.article.url}>
Zurück zu den Artikeln
</Link>
</>
}
);
}
+32 -25
View File
@@ -1,26 +1,33 @@
import { manufacturerFindAll } from "../../../actions/manufacturer.actions";
import { articleFindAll } from "../../../actions/article.actions";
import Link from "next/link";
import { sites } from "../../../../../apps/frontend/_config/sites";
import { ArticleList } from "../../../components/article/articleList";
import { Icon, CirclePlus } from "lucide-react";
import {
articleFindAll,
articleMigrationStatus,
} from '../../../actions/article.actions';
import Link from 'next/link';
import { sites } from '../../../_config/sites';
import { ArticleList } from '../../../components/article/articleList';
interface Props { }
export default async function ArticlePage({ }: Props) {
const manufacturer = await manufacturerFindAll();
const artikel = await articleFindAll();
if (!manufacturer) return <div>Keine Hersteller gefunden</div>
return <div className="p-4 mb-4">
<div className="">
<Link href={`${sites.article.new.url}`} className="text-sky-300 text-black"><CirclePlus color="green" />neu </Link>
</div>
<ArticleList articles={artikel}></ArticleList>
<Link href={`${sites.main.url}`} className="text-sky-300">zurück</Link>
</div>
}
export default async function ArticlePage() {
const [articles, migration] = await Promise.all([
articleFindAll(),
articleMigrationStatus(),
]);
return (
<main className="p-6">
<h1 className="text-xl mb-4">Artikel</h1>
<Link className="text-sky-700" href={sites.article.new.url}>
Artikel anlegen
</Link>
{migration.pendingLegacyArticles > 0 && (
<p role="status" className="border rounded p-3 my-3">
Es gibt noch {migration.pendingLegacyArticles} bisherige Artikel, die
vor ihrer Nutzung in die neue Artikelstruktur übernommen werden
müssen.
</p>
)}
<ArticleList articles={articles} />
<Link className="text-sky-700" href={sites.main.url}>
Zurück
</Link>
</main>
);
}
+29 -25
View File
@@ -1,27 +1,31 @@
import Link from "next/link";
import { sites } from "../../../../_config/sites";
import { LocationForm } from "../../../../components/location/location.form";
import { articleFindAll } from "../../../../actions/article.actions";
import { locationFindAll, locationTree } from "../../../../actions/location.actions";
import { StockForm } from "../../../../components/stock/stock.form";
import { categoryFindAll } from "../../../../actions/category.actions";
import Link from 'next/link';
import { sites } from '../../../../_config/sites';
import { articleFindAll } from '../../../../actions/article.actions';
import { locationTree } from '../../../../actions/location.actions';
import {
stockContentFindAll,
stockFindAll,
} from '../../../../actions/stock.actions';
import { StockForm } from '../../../../components/stock/stock.form';
export default async function StockMovmentNewPage() {
const artikel = await articleFindAll();
const orte = await locationTree();
const kategorien = await categoryFindAll();
return (
<div className="h-screen flex flex-col gap-4">
<div>
{sites.location.new.name}
<StockForm article={artikel} orte={orte} categories={kategorien}></StockForm>
</div>
<Link href={sites.location.url}>zurück zu {sites.location.name}</Link>
</div>
);
export default async function StockMovementPage() {
const [article, orte, stocks, contents] = await Promise.all([
articleFindAll(),
locationTree(),
stockFindAll(),
stockContentFindAll(),
]);
return (
<main>
<StockForm
article={article}
orte={orte}
stocks={stocks}
contents={contents}
/>
<Link className="text-sky-700 p-6" href={sites.main.url}>
Zurück
</Link>
</main>
);
}
@@ -1,26 +1,131 @@
"use client";
'use client';
import { ArticleCreate, ArticleUpsert, Category } from "../../types/catalog"
import { useFormContext } from "react-hook-form"
import { InputTextR } from "../ui/inputTextR";
import ComboBoxR from "../ui/ComboBoxR";
import {
ArticleCreate,
ArticleGroup,
Category,
Manufacturer,
} from '../../types/catalog';
import { useFormContext } from 'react-hook-form';
import { InputTextR } from '../ui/inputTextR';
interface Params {
categories: Category[]
interface Props {
categories: Category[];
manufacturer: Manufacturer[];
groups: ArticleGroup[];
}
export const ArticleBaseForm = ({ categories }: Params) => {
const { register, control } = useFormContext<ArticleUpsert>();
const values = categories.map((i) => ({ id: i._id, value: i.name }))
return (
<>
<InputTextR label="Artikename" {...register("name", { required: "Pflichtfeld" })} />
<ComboBoxR name="categoryId" control={control} options={values} placeholder="wählen..." />
</>
)
}
export const ArticleBaseForm = ({
categories,
manufacturer,
groups,
}: Props) => {
const {
register,
watch,
setValue,
formState: { errors },
} = useFormContext<ArticleCreate>();
const trackingMode = watch('trackingMode');
return (
<div className="grid gap-3 md:grid-cols-2">
<InputTextR
label="Artikelnummer"
{...register('articleNumber', {
required: 'Artikelnummer erforderlich',
})}
/>
<InputTextR
label="Artikelname"
{...register('name', { required: 'Name erforderlich' })}
/>
<InputTextR label="Beschreibung" {...register('description')} />
<label>
Kategorie
<select
className="block w-full border rounded p-1"
{...register('categoryId')}
>
<option value="">Keine Kategorie</option>
{categories.map((item) => (
<option key={item._id} value={item._id}>
{item.name}
</option>
))}
</select>
</label>
<label>
Produktgruppe
<select
className="block w-full border rounded p-1"
{...register('groupId')}
>
<option value="">Keine Gruppe</option>
{groups.map((item) => (
<option key={item._id} value={item._id}>
{item.name}
</option>
))}
</select>
</label>
<label>
Hersteller
<select
className="block w-full border rounded p-1"
{...register('manufacturerId')}
>
<option value="">Unbekannt / kein Hersteller</option>
{manufacturer.map((item) => (
<option key={item._id} value={item._id}>
{item.name}
</option>
))}
</select>
</label>
<InputTextR
label="Herstellerartikelnummer"
{...register('manufacturerArticleNumber')}
/>
<InputTextR label="Barcode" {...register('barcode')} />
<InputTextR
label="Basiseinheit (z. B. Stück, kg, Liter)"
{...register('baseUnit', { required: 'Einheit erforderlich' })}
/>
<label>
Bestandsführung
<select
className="block w-full border rounded p-1"
{...register('trackingMode', {
onChange: (event) => {
if (event.target.value !== 'batch')
setValue('tracksExpiryDate', false);
if (event.target.value === 'individual')
setValue('baseUnit', 'Stück');
},
})}
>
<option value="quantity">Menge</option>
<option value="batch">Charge</option>
<option value="individual">Einzelstücke</option>
</select>
</label>
<label className="flex items-center gap-2">
<input type="checkbox" {...register('isConsumable')} />
Verbrauchsartikel
</label>
<label className="flex items-center gap-2">
<input
type="checkbox"
disabled={trackingMode !== 'batch'}
{...register('tracksExpiryDate')}
/>
Ablaufdatum je Charge erfassen
</label>
<p className="text-sm text-red-700 md:col-span-2" role="alert">
{Object.values(errors)
.map((error) => error?.message)
.filter(Boolean)
.join(' · ')}
</p>
</div>
);
};
@@ -1,57 +1,86 @@
"use client";
'use client';
import { useRouter } from 'next/navigation'
import { Article } from "../../types/catalog"
import { articleDelete } from "../../actions/article.actions";
import { sites } from "../../_config/sites";
import Link from "next/link";
import { Eye, OctagonX } from 'lucide-react';
interface Params {
articles: Article[]
}
export const ArticleList = ({ articles }: Params) => {
const router = useRouter()
const handlerOnDelete = (id: string) => {
articleDelete(id)
router.refresh();
}
return (
<div className='p-4 '>
{articles.map((a) => (
<div key={a._id} className="flex gap-4 border-b-1 p-4 border-gray-200">
<div className='flex gap-4 wa'>
<div className='w-32'>
{a.name}
</div>
<div className='w-8'>
<Link href={`${sites.article.update.url}/${a._id}`}>
<Eye className=''></Eye>
</Link>
</div>
<div className='w-8 '>
<button className='flex gap-2' onClick={() => handlerOnDelete(a._id)}>
<OctagonX className='' enableBackground={'green'} color='red'></OctagonX>
</button>
</div>
</div>
</div>))}
</div>
)
}
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { Article } from '../../types/catalog';
import { articleDelete } from '../../actions/article.actions';
import { sites } from '../../_config/sites';
import Link from 'next/link';
export const ArticleList = ({ articles }: { articles: Article[] }) => {
const router = useRouter();
const [error, setError] = useState('');
const [pendingId, setPendingId] = useState<string | null>(null);
const archive = async (id: string) => {
setPendingId(id);
setError('');
const result = await articleDelete(id);
if (!result.success) setError(result.errors.join(' · '));
else router.refresh();
setPendingId(null);
};
return (
<div className="overflow-auto">
{error && (
<p role="alert" className="text-red-700">
{error}
</p>
)}
<table className="w-full text-left">
<thead>
<tr>
<th>Nummer</th>
<th>Artikel</th>
<th>Hersteller</th>
<th>Einheit</th>
<th>Bestandsführung</th>
<th>Aktionen</th>
</tr>
</thead>
<tbody>
{articles.map((article) => (
<tr key={article._id} className="border-b">
<td className="p-2">{article.articleNumber}</td>
<td className="p-2">
{article.name}
{article.group && (
<span className="block text-sm text-gray-500">
{article.group.name}
</span>
)}
</td>
<td className="p-2">{article.manufacturer?.name ?? '–'}</td>
<td className="p-2">{article.baseUnit}</td>
<td className="p-2">
{
{
quantity: 'Menge',
batch: 'Charge',
individual: 'Einzelstücke',
}[article.trackingMode]
}
</td>
<td className="p-2">
<Link
className="text-sky-700 mr-3"
href={`${sites.article.update.url}/${article._id}`}
>
Bearbeiten
</Link>
<button
disabled={pendingId !== null}
onClick={() => archive(article._id)}
>
{pendingId === article._id ? 'Archiviert …' : 'Archivieren'}
</button>
</td>
</tr>
))}
</tbody>
</table>
{articles.length === 0 && (
<p className="py-4">Noch keine Artikel vorhanden.</p>
)}
</div>
);
};
@@ -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>
);
};
@@ -1,85 +1,65 @@
"use client";
'use client';
import { ArticleCreate, ArticleUpsert, Manufacturer } from "../../types/catalog"
import { useFieldArray, useFormContext } from "react-hook-form"
import { InputTextR } from "../ui/inputTextR";
import ComboBoxRHF from "../ui/ComboBoxR";
import { useState } from "react";
import Modal from "../ui/modal";
import { ManufactuererForm } from "../manufacturer/manufacturer.form";
import SelectAndSearch2 from "../ui/SelectAndSearch2";
interface Params {
manufacturer: Manufacturer[]
onOpenManufacturer: (index: number) => void
}
export const ArticleVariantForm = ({ manufacturer, onOpenManufacturer }: Params) => {
const { control, register, getValues, setValue } = useFormContext<ArticleUpsert>();
const { fields, append, remove } = useFieldArray({ control, name: "variants", });
const [creatManufacturer, setCreatManufacturer] = useState(false);
const handleRemove = (index: number) => {
const id = getValues(`variants.${index}._id`);
if (!id) {
remove(index);
return;
}
const x = getValues(`variants.${index}.deleted`) ? true : false;
setValue(`variants.${index}.deleted`, !x, { shouldDirty: true })
}
const hersteller = manufacturer.map((i) => ({ id: i._id, value: i.name }))
return (
<div className="mt-4 border-1 rounded border-gray-200 p-2">
<div>
<button type="button" onClick={() => append({ manufacturerId: "", packagingUnit: "1" })} className="bg-sky-400 rounded-md p-1 mt-2 mb-2 ps-2 pe-2">
+ Neue Variante
</button>
</div>
<div className="flex flex-col gap-2 mb-2">
<div className="grid grid-cols-12 gap-4 ">
<div className="col-span-4" >
Hersteller
</div>
<div className="col-span-3" >
Packungseinheit
</div>
<div className="col-span-3" >
Aktion
</div>
</div>
<div className="border-1"></div>
{fields.map((field, index) => (
<div key={field.id} className="grid grid-cols-12 gap-4 ">
<div className="col-span-4" >
<ComboBoxRHF name={`variants.${index}.manufacturerId`} control={control} options={hersteller} placeholder="wählen..." />
<button onClick={() => onOpenManufacturer(index)}>+</button>
</div>
<div className="col-span-3" >
<InputTextR {...register(`variants.${index}.packagingUnit`)} />
</div>
<div className="col-span-3" >
<button type="button" onClick={() => handleRemove(index)} className={`bg-gray-200 rounded-md ps-2 pe-2 `}>
löschen
</button>
</div>
</div>
))}
</div>
import { ArticleCreate } from '../../types/catalog';
import { useFieldArray, useFormContext } from 'react-hook-form';
import { InputTextR } from '../ui/inputTextR';
export const ArticlePackagingForm = () => {
const {
control,
register,
watch,
formState: { errors },
} = useFormContext<ArticleCreate>();
const { fields, append, remove } = useFieldArray({
control,
name: 'packaging',
});
return (
<fieldset className="border rounded p-3 mt-4">
<legend>Verpackungen (optional)</legend>
<p className="text-sm mb-2">
Der Bestand wird in {watch('baseUnit') || 'der Basiseinheit'} geführt.
Hier hinterlegst du den Inhalt einer Verpackung.
</p>
{fields.map((field, index) => (
<div key={field.id} className="grid gap-2 md:grid-cols-4 mb-3">
<InputTextR
label="Bezeichnung"
{...register(`packaging.${index}.name`, { required: true })}
/>
<InputTextR
label="Inhalt in Basiseinheiten"
type="number"
step="any"
min="0.000001"
{...register(`packaging.${index}.quantityInBaseUnits`, {
valueAsNumber: true,
required: true,
min: Number.MIN_VALUE,
})}
/>
<InputTextR
label="Barcode"
{...register(`packaging.${index}.barcode`)}
/>
<button type="button" onClick={() => remove(index)}>
Verpackung entfernen
</button>
</div>
)
}
))}
{errors.packaging && (
<p role="alert" className="text-red-700">
Jede Verpackung benötigt eine Bezeichnung und einen positiven Inhalt.
</p>
)}
<button
type="button"
className="border rounded px-3 py-1"
onClick={() => append({ name: '', quantityInBaseUnits: 1 })}
>
Verpackung hinzufügen
</button>
</fieldset>
);
};
+431 -103
View File
@@ -1,109 +1,437 @@
"use client";
'use client';
import { emptyArticleDto, Article, ArticleCreate, Category, Manufacturer, ArticleVariant } from "../../types/catalog"
import { FormProvider, useForm } from "react-hook-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 { Location, LocationTreeNode } from "../../types/inventory";
import { emptyStock, Stock, StockCreate } from "../../types/inventory/stockContent.types";
import { stockCreate, stockUpdate } from "../../actions/stock.actions";
import { InputTextR } from "../ui/inputTextR";
import { LocationView } from "../location/location.view";
import { LocationTreeView } from "../location/location.treeView";
import { Article } from '../../types/catalog';
import { useForm } from 'react-hook-form';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { Stock } from '../../types/inventory/stock.types';
import { StockContent } from '../../types/inventory/stockContent.types';
import { StockMovementIn } from '../../types/inventory/stockMovement.types';
import { LocationTreeNode } from '../../types/inventory';
import {
stockCreate,
stockMoveIn,
stockMoveOut,
stockTransfer,
} from '../../actions/stock.actions';
import { InputTextR } from '../ui/inputTextR';
import { LocationTreeView } from '../location/location.treeView';
import Modal from '../ui/modal';
interface Params {
categories: Category[]
article: Article[],
orte: LocationTreeNode[]
initData?: Stock
debug?: boolean
interface Props {
article: Article[];
stocks: Stock[];
contents: StockContent[];
orte: LocationTreeNode[];
}
export const StockForm = ({ article, stocks, contents, orte }: Props) => {
const router = useRouter();
const {
register,
watch,
reset,
setValue,
handleSubmit,
formState: { isSubmitting, errors: formErrors },
} = useForm<StockMovementIn>({
shouldUnregister: true,
defaultValues: { articleId: '', stockId: '', quantity: 1 },
});
const selectedArticle = article.find(
(item) => item._id === watch('articleId'),
);
const [errors, setErrors] = useState<string[]>([]);
const [notice, setNotice] = useState('');
const [stockOpen, setStockOpen] = useState(false);
const [stockName, setStockName] = useState('');
const [location, setLocation] = useState<LocationTreeNode | null>(null);
const [busy, setBusy] = useState(false);
const [selectedContent, setSelectedContent] = useState<StockContent | null>(
null,
);
const [operation, setOperation] = useState<'out' | 'transfer'>('out');
const [quantity, setQuantity] = useState(1);
const [targetStock, setTargetStock] = useState('');
const [targetArea, setTargetArea] = useState('');
export const StockForm = ({ article, categories, initData, orte, debug }: Params) => {
const { register, reset, formState: { errors }, handleSubmit } = useForm<StockCreate>({ defaultValues: emptyStock });
const [errMsg, setErrorMsg] = useState<string[]>([])
const [selectetCategory, setSelectedCategory] = useState<Category>()
const [selectetArticle, setSelectedArticle] = useState<Article>()
const [selectetArticleVariant, setSelectedArticleVariant] = useState<ArticleVariant>()
const [selectetOrt, setSelectedOrt] = useState<Location>()
const [error, setError] = useState(false)
useEffect(() => {
if (initData && initData.id) {
reset(initData);
}
}, [initData])
const onSubmit = async (data: StockCreate) => {
if (initData?.id) {
const result = await stockUpdate(initData.id, data)
if (!result.success) {
setError(true)
setErrorMsg(() => result.errors)
console.log(result)
} else {
setError(false)
}
} else {
console.log('create')
const { articleVariantId, locationId, quantity, expiryDate, batchNumber } = data;
if (true) {
const create = {
articleVariantId,
locationId,
quantity,
expiryDate,
batchNumber
}
stockCreate(create);
}
}
};
const handleLocationSelect = (ort: LocationTreeNode) => {
setSelectedOrt(ort);
const feedback = (result: ActionResult) => {
if (!result.success) {
setErrors(result.errors);
return false;
}
setErrors([]);
setNotice('Gespeichert.');
router.refresh();
return true;
};
const onSubmit = async (data: StockMovementIn) => {
setNotice('');
const payload: StockMovementIn = {
articleId: data.articleId,
stockId: data.stockId,
quantity: data.quantity,
area: data.area || undefined,
};
if (selectedArticle?.trackingMode === 'batch') {
payload.batchNumber = data.batchNumber;
if (selectedArticle.tracksExpiryDate && data.expiryDate)
payload.expiryDate = data.expiryDate;
}
if (selectedArticle?.trackingMode === 'individual') {
payload.inventoryNumber = data.inventoryNumber;
payload.serialNumber = data.serialNumber || undefined;
payload.condition = data.condition || undefined;
payload.purpose = data.purpose || undefined;
payload.acquiredAt = data.acquiredAt || undefined;
}
if (feedback(await stockMoveIn(payload)))
reset({
articleId: data.articleId,
stockId: data.stockId,
quantity: 1,
batchNumber: '',
inventoryNumber: '',
serialNumber: '',
expiryDate: '',
});
};
const addStock = async () => {
if (!location || !stockName.trim()) return;
setBusy(true);
try {
if (
feedback(
await stockCreate({
name: stockName.trim(),
locationId: location._id,
}),
)
) {
setStockOpen(false);
setStockName('');
setLocation(null);
}
} finally {
setBusy(false);
}
};
const book = async () => {
if (!selectedContent) return;
setBusy(true);
setNotice('');
try {
const data = { stockContentId: selectedContent._id, quantity };
const result =
operation === 'out'
? await stockMoveOut(data)
: await stockTransfer({
...data,
toStockId: targetStock,
toArea: targetArea || undefined,
});
if (feedback(result)) setSelectedContent(null);
} finally {
setBusy(false);
}
};
return (
<div className="me-30 flex flex-col p-4 pt-10 ps-10" >
{initData?.id && <div>{initData.id}</div>}
<form onSubmit={handleSubmit(onSubmit)}>
<InputTextR
label="Menge"
{...register("quantity", { required: "Pflichtfeld" })}
error={errors.quantity?.message}
/>
<button type="submit">Absenden</button>
</form>
<LocationTreeView data={orte} onSelect={(item) => handleLocationSelect(item)}></LocationTreeView>
{error && <div className="border-1 border-red-400 bg-red-200">
Error
{errMsg.map((msg, id) => (<div key={id}>{msg}</div>))}
</div>}
{selectetOrt && <div>{selectetOrt.name}</div>}
</div>
)
}
return (
<div className="max-w-5xl p-6">
<h1 className="text-xl mb-4">Lager und Bestände</h1>
<button
className="border rounded px-3 py-1 mb-4"
type="button"
onClick={() => setStockOpen(true)}
>
Lager anlegen
</button>
<form
onSubmit={handleSubmit(onSubmit)}
className="grid gap-3 md:grid-cols-2"
>
<label>
Artikel
<select
className="block w-full border rounded p-1"
{...register('articleId', {
required: 'Artikel auswählen',
onChange: (event) => {
if (
article.find((item) => item._id === event.target.value)
?.trackingMode === 'individual'
)
setValue('quantity', 1);
},
})}
>
<option value="">Artikel auswählen</option>
{article.map((item) => (
<option key={item._id} value={item._id}>
{item.articleNumber} – {item.name}
</option>
))}
</select>
</label>
<label>
Lager
<select
className="block w-full border rounded p-1"
{...register('stockId', {
required: 'Lager auswählen',
onChange: () => setValue('area', ''),
})}
>
<option value="">Lager auswählen</option>
{stocks.map((item) => (
<option key={item._id} value={item._id}>
{item.name}
</option>
))}
</select>
</label>
<InputTextR
label={`Menge (${selectedArticle?.baseUnit ?? 'Basiseinheit'})`}
type="number"
step={selectedArticle?.trackingMode === 'individual' ? '1' : 'any'}
{...register('quantity', {
valueAsNumber: true,
required: true,
min: Number.MIN_VALUE,
validate: (value) =>
selectedArticle?.trackingMode !== 'individual' ||
value === 1 ||
'Einzelstücke benötigen Menge 1',
})}
/>
<label>
Lagerbereich
<select
className="block w-full border rounded p-1"
{...register('area')}
>
<option value="">Kein Bereich</option>
{stocks
.find((item) => item._id === watch('stockId'))
?.areas?.map((area) => (
<option key={area} value={area}>
{area}
</option>
))}
</select>
</label>
{selectedArticle?.trackingMode === 'batch' && (
<>
<InputTextR
label="Chargennummer"
{...register('batchNumber', {
validate: (value) =>
selectedArticle?.trackingMode !== 'batch' ||
Boolean(value?.trim()) ||
'Chargennummer erforderlich',
})}
/>
{selectedArticle.tracksExpiryDate && (
<InputTextR
label="Mindesthaltbar / Ablaufdatum"
type="date"
{...register('expiryDate')}
/>
)}
</>
)}
{selectedArticle?.trackingMode === 'individual' && (
<>
<InputTextR
label="Inventarnummer"
{...register('inventoryNumber', {
validate: (value) =>
selectedArticle?.trackingMode !== 'individual' ||
Boolean(value?.trim()) ||
'Inventarnummer erforderlich',
})}
/>
<InputTextR label="Seriennummer" {...register('serialNumber')} />
<InputTextR label="Zustand" {...register('condition')} />
<InputTextR label="Verwendung" {...register('purpose')} />
<InputTextR
label="Anschaffungsdatum"
type="date"
{...register('acquiredAt')}
/>
</>
)}
<p role="alert" className="text-red-700 md:col-span-2">
{Object.values(formErrors)
.map((error) => error.message)
.filter(Boolean)
.join(' · ')}
</p>
<button
className="bg-sky-700 text-white rounded p-2"
type="submit"
disabled={isSubmitting || stocks.length === 0 || article.length === 0}
>
{isSubmitting ? 'Bucht …' : 'Einlagern'}
</button>
</form>
{errors.length > 0 && (
<ul role="alert" className="text-red-700 mt-3">
{errors.map((error, index) => (
<li key={index}>{error}</li>
))}
</ul>
)}
{notice && (
<p role="status" className="mt-3">
{notice}
</p>
)}
<h2 className="text-lg mt-6 mb-3">Bestände</h2>
<div className="overflow-auto">
<table className="w-full text-left">
<thead>
<tr>
<th>Artikel</th>
<th>Lager</th>
<th>Menge</th>
<th>Charge / Exemplar</th>
<th>Aktionen</th>
</tr>
</thead>
<tbody>
{contents.map((content) => (
<tr key={content._id} className="border-b">
<td className="p-2">
{content.articleId?.name ?? 'Artikel fehlt'}
</td>
<td className="p-2">
{content.stockId?.name ?? 'Lager fehlt'} {content.area}
</td>
<td className="p-2">
{content.quantity} {content.articleId?.baseUnit}
</td>
<td className="p-2">
{content.batchId?.batchNumber ??
content.assetId?.inventoryNumber ??
'–'}
{content.batchId?.expiryDate && (
<span className="block text-sm">
{new Date(content.batchId.expiryDate).toLocaleDateString(
'de-DE',
{ timeZone: 'UTC' },
)}
</span>
)}
</td>
<td className="p-2">
{(['out', 'transfer'] as const).map((action) => (
<button
key={action}
type="button"
className="text-sky-700 mr-3"
onClick={() => {
setSelectedContent(content);
setOperation(action);
setQuantity(content.assetId ? 1 : content.quantity);
setTargetStock('');
setTargetArea('');
}}
>
{action === 'out' ? 'Entnehmen' : 'Umlagern'}
</button>
))}
</td>
</tr>
))}
</tbody>
</table>
</div>
{contents.length === 0 && <p>Keine Bestände vorhanden.</p>}
<Modal open={stockOpen} onClose={() => setStockOpen(false)}>
<InputTextR
label="Lagername"
value={stockName}
onChange={(event) => setStockName(event.target.value)}
/>
<p>Lagerort auswählen: {location?.name}</p>
<LocationTreeView data={orte} onSelect={setLocation} />
<button
type="button"
disabled={busy || !location || !stockName.trim()}
onClick={addStock}
>
Lager speichern
</button>
</Modal>
<Modal
open={selectedContent !== null}
onClose={() => setSelectedContent(null)}
>
<h2>
{operation === 'out' ? 'Entnehmen' : 'Umlagern'}:{' '}
{selectedContent?.articleId?.name}
</h2>
<InputTextR
label="Menge"
type="number"
step="any"
value={quantity}
onChange={(event) => setQuantity(Number(event.target.value))}
/>
{operation === 'transfer' && (
<>
<label>
Ziellager
<select
className="block border rounded p-1"
value={targetStock}
onChange={(event) => {
setTargetStock(event.target.value);
setTargetArea('');
}}
>
<option value="">Auswählen</option>
{stocks.map((stock) => (
<option key={stock._id} value={stock._id}>
{stock.name}
</option>
))}
</select>
</label>
<label>
Zielbereich
<select
className="block border rounded p-1"
value={targetArea}
onChange={(event) => setTargetArea(event.target.value)}
>
<option value="">Kein Bereich</option>
{stocks
.find((stock) => stock._id === targetStock)
?.areas?.map((area) => (
<option key={area} value={area}>
{area}
</option>
))}
</select>
</label>
</>
)}
<button
type="button"
disabled={
busy ||
!Number.isFinite(quantity) ||
quantity <= 0 ||
quantity > (selectedContent?.quantity ?? 0) ||
Boolean(selectedContent?.assetId && quantity !== 1) ||
(operation === 'transfer' && !targetStock)
}
onClick={book}
>
Buchen
</button>
</Modal>
</div>
);
};
+50 -87
View File
@@ -1,93 +1,56 @@
import { Category } from "./category.types";
import {Manufacturer,emptyManufacturer} from "./manufacturer.types"
import { Category } from './category.types';
import { Manufacturer } from './manufacturer.types';
export interface Article {
_id: string,
name: string,
category: Category;
attributes?: Record<string, any>;
variants: Variant[],
export type TrackingMode = 'quantity' | 'batch' | 'individual';
export type ArticleAttributes = Record<string, string | number | boolean>;
export interface ArticleGroup {
_id: string;
name: string;
description?: string;
}
export interface ArticlePackaging {
name: string;
quantityInBaseUnits: number;
barcode?: string;
}
export interface ArticleCreate {
name: string;
categoryId: string;
attributes?: Record<string, any>;
variants: Variant[],
articleNumber: string;
name: string;
description?: string;
categoryId?: string | null;
groupId?: string | null;
manufacturerId?: string | null;
manufacturerArticleNumber?: string;
barcode?: string;
baseUnit: string;
isConsumable: boolean;
trackingMode: TrackingMode;
tracksExpiryDate: boolean;
attributes?: ArticleAttributes;
packaging?: ArticlePackaging[];
}
//--- Artikel Variante
export interface ArticleVariant {
_id: string;
article: Article;
manufacturer: Manufacturer;
supplierArticleNumber?: string;
packagingUnit?: string;
extra?: Record<string, any>;
export type ArticleUpsert = ArticleCreate;
export interface Article extends ArticleCreate {
_id: string;
category?: Category;
manufacturer?: Manufacturer;
group?: ArticleGroup;
archivedAt?: string | null;
}
export interface ArticleVariantCreate {
articleId: string;
manufacturerId: string;
supplierArticleNumber?: string;
packagingUnit?: string;
extra?: Record<string, any>;
}
export interface Variant {
_id?: string;
manufacturerId: string;
supplierArticleNumber?: string;
packagingUnit?: string;
extra?: Record<string, any>;
}
export interface VariantCreate {
manufacturerId: string;
supplierArticleNumber?: string;
packagingUnit?: string;
extra?: Record<string, any>;
}
export const emptyArticle = {
name: '',
}
export const emptyArticleVariant = {
article: emptyArticle,
manufacturer: emptyManufacturer
}
export const emptyArticleDto:ArticleCreate = {
name:'',
categoryId:'',
variants:[]
}
//Upsert
export interface ArticleUpsert {
_id:string,
name: string;
categoryId?: string;
attributes?: Record<string, any>;
variants: VariantUpsert[],
}
export interface VariantUpsert {
_id?:string
manufacturerId: string;
supplierArticleNumber?: string;
packagingUnit?: string;
extra?: Record<string, any>;
deleted?:boolean;
}
export const emptyArticleDto: ArticleCreate = {
articleNumber: '',
name: '',
description: '',
categoryId: null,
groupId: null,
manufacturerId: null,
manufacturerArticleNumber: '',
barcode: '',
baseUnit: 'Stück',
isConsumable: false,
trackingMode: 'quantity',
tracksExpiryDate: false,
attributes: {},
packaging: [],
};
+11 -15
View File
@@ -1,20 +1,16 @@
import { Location } from "./location.types";
export interface StockCreate {
name: string;
locationId: string;
areas?:string[]
name: string;
locationId: string;
areas?: string[];
}
export interface StockUpdate {
name?: string;
locationId?: string;
areas?:string[]
name?: string;
locationId?: string;
areas?: string[];
}
export interface Stock {
id: string
name: string;
location: Location;
areas?:string[]
}
_id: string;
name: string;
locationId: string;
areas?: string[];
}
@@ -1,36 +1,25 @@
import { Article } from '../catalog';
import { Stock } from './stock.types';
export interface Stock {
id: string
articleVariantId: string
locationId: string
quantity: number
expiryDate?: Date
batchNumber: string
export interface Batch {
_id: string;
batchNumber: string;
expiryDate?: string;
}
export interface StockCreate {
articleVariantId: string
locationId: string
quantity: number
expiryDate?: Date
batchNumber: string
export interface Asset {
_id: string;
inventoryNumber: string;
serialNumber?: string;
condition?: string;
purpose?: string;
acquiredAt?: string;
}
export interface StockUpdate {
articleVariantId?: string
locationId?: string
quantity?: number
expiryDate?: Date
batchNumber?: string
export interface StockContent {
_id: string;
articleId: Article;
stockId: Stock;
quantity: number;
area: string;
batchId?: Batch | null;
assetId?: Asset | null;
}
export const emptyStock:StockCreate = {
articleVariantId: '',
locationId: '',
quantity: 0,
expiryDate: new Date(),
batchNumber: '1'
}
@@ -1,28 +1,21 @@
export interface StockMovementIn {
stockId: string;
articleVariantId: string;
articleId: string;
quantity: number;
batchNumber?: string;
expiryDate?: Date;
expiryDate?: string;
area?: string;
inventoryNumber?: string;
serialNumber?: string;
condition?: string;
purpose?: string;
acquiredAt?: string;
}
export interface StockMovementOut {
stockContentId: string;
quantity: number;
}
export interface StockMovementTransfer {
articleVariantId: string;
fromStockId: string;
export interface StockMovementTransfer extends StockMovementOut {
toStockId: string;
toArea?: string;
quantity: number;
batchNumber?: string;
}