Files
repo-home/apps/frontend/components/stock/stock.form.tsx
T

438 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use client';
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 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('');
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="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>
);
};