feat(ui): raw material lots and production inputs

- Pages for raw material lots (beeswax, propolis): list, create in grams
  with optional apiary, detail with stock card (harvested / used in
  production / withdrawn / remaining) and "used in" batches.
- Production batch form takes the raw material used (lot + grams) and the
  batch page shows what it was made from - traceability both ways.
- Sidebar entry "Rohstoffe".
- Removes backend files that were committed into ApiCore-Frontend/src by
  mistake in e52a605 (copies of ApiCore-Backend/src/raw-materials).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Nick SzaunigandClaude Opus 5.5 committed 2026-10-06 06:31:07 +02:00
1 parent f9899d5621
commit 569a43d247
22 files changed
+803 -412

No files matched your search

@@ -15,6 +15,10 @@ import { DetailHeader, DetailQueryFallback } from "@/components/detail-header";
import { StockCard } from "@/components/stock/stock-card"; import { StockCard } from "@/components/stock/stock-card";
import { useAuth } from "@/lib/auth/auth-context"; import { useAuth } from "@/lib/auth/auth-context";
import { EditProductionBatchDialog } from "./edit-production-batch-dialog"; import { EditProductionBatchDialog } from "./edit-production-batch-dialog";
import {
RAW_MATERIAL_KIND_LABELS,
formatGrams,
} from "@/lib/raw-materials/labels";
const BACK = { const BACK = {
backHref: "/production-batches", backHref: "/production-batches",
@@ -102,6 +106,25 @@ export default function ProductionBatchDetailPage() {
{batch.notes ? ( {batch.notes ? (
<p className="whitespace-pre-line">Notiz: {batch.notes}</p> <p className="whitespace-pre-line">Notiz: {batch.notes}</p>
) : null} ) : null}
{batch.inputs && batch.inputs.length > 0 ? (
<div className="flex flex-col gap-1">
<p className="font-medium">Hergestellt aus</p>
<ul className="flex flex-col gap-1">
{batch.inputs.map((input) => (
<li key={input.id}>
<Link
className="underline"
href={`/raw-materials/${input.rawMaterialLot.id}`}
>
{RAW_MATERIAL_KIND_LABELS[input.rawMaterialLot.kind]}{" "}
{input.rawMaterialLot.lotNumber}
</Link>
: {formatGrams(input.quantity)}
</li>
))}
</ul>
</div>
) : null}
</CardContent> </CardContent>
</Card> </Card>
<StockCard <StockCard
@@ -7,6 +7,11 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner"; import { toast } from "sonner";
import { createProductionBatch } from "@/lib/production-batches/api"; import { createProductionBatch } from "@/lib/production-batches/api";
import { fetchProducts } from "@/lib/products/api"; import { fetchProducts } from "@/lib/products/api";
import { fetchRawMaterialLots } from "@/lib/raw-materials/api";
import {
RAW_MATERIAL_KIND_LABELS,
formatGrams,
} from "@/lib/raw-materials/labels";
import { PageHeader } from "@/components/page-header"; import { PageHeader } from "@/components/page-header";
import { Card, CardContent } from "@/components/ui/card"; import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -34,13 +39,31 @@ export default function NewProductionBatchPage() {
const [quantity, setQuantity] = useState(""); const [quantity, setQuantity] = useState("");
const [bestBeforeDate, setBestBeforeDate] = useState(""); const [bestBeforeDate, setBestBeforeDate] = useState("");
const [notes, setNotes] = useState(""); const [notes, setNotes] = useState("");
// Verbrauchte Rohstoffe: je Zeile eine Rohstoff-Charge und Gramm.
const [inputs, setInputs] = useState<
{ rawMaterialLotId: string; grams: string }[]
>([]);
const { data: rawLots } = useQuery({
queryKey: ["raw-material-lots"],
queryFn: () => fetchRawMaterialLots(),
});
const availableLots = (rawLots ?? []).filter((lot) => lot.remainingCount > 0);
const updateInput = (
index: number,
change: Partial<{ rawMaterialLotId: string; grams: string }>,
) =>
setInputs((current) =>
current.map((row, i) => (i === index ? { ...row, ...change } : row)),
);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const { data: products } = useQuery({ const { data: products } = useQuery({
queryKey: ["products", { status: "ACTIVE" }], queryKey: ["products", { status: "ACTIVE" }],
queryFn: () => fetchProducts({ status: "ACTIVE" }), queryFn: () => fetchProducts({ status: "ACTIVE" }),
}); });
const manufactured = (products ?? []).filter((product) => product.kind === "MANUFACTURED"); const manufactured = (products ?? []).filter(
(product) => product.kind === "MANUFACTURED",
);
const selected = manufactured.find((product) => product.id === productId); const selected = manufactured.find((product) => product.id === productId);
const mutation = useMutation({ const mutation = useMutation({
@@ -50,8 +73,16 @@ export default function NewProductionBatchPage() {
lotNumber: lotNumber.trim(), lotNumber: lotNumber.trim(),
date: new Date(date).toISOString(), date: new Date(date).toISOString(),
quantity: Number(quantity), quantity: Number(quantity),
bestBeforeDate: bestBeforeDate ? new Date(bestBeforeDate).toISOString() : undefined, bestBeforeDate: bestBeforeDate
? new Date(bestBeforeDate).toISOString()
: undefined,
notes: notes.trim() || undefined, notes: notes.trim() || undefined,
inputs: inputs
.filter((row) => row.rawMaterialLotId && Number(row.grams) > 0)
.map((row) => ({
rawMaterialLotId: row.rawMaterialLotId,
quantity: Number(row.grams),
})),
}), }),
onSuccess: (batch) => { onSuccess: (batch) => {
void queryClient.invalidateQueries({ queryKey: ["production-batches"] }); void queryClient.invalidateQueries({ queryKey: ["production-batches"] });
@@ -59,7 +90,8 @@ export default function NewProductionBatchPage() {
router.push(`/production-batches/${batch.id}`); router.push(`/production-batches/${batch.id}`);
}, },
onError: (mutationError: Error) => { onError: (mutationError: Error) => {
const message = mutationError.message || "Charge konnte nicht angelegt werden"; const message =
mutationError.message || "Charge konnte nicht angelegt werden";
setError(message); setError(message);
toast.error(message); toast.error(message);
}, },
@@ -84,12 +116,20 @@ export default function NewProductionBatchPage() {
/> />
<Card> <Card>
<CardContent> <CardContent>
<form className="flex max-w-xl flex-col gap-4" onSubmit={handleSubmit}> <form
className="flex max-w-xl flex-col gap-4"
onSubmit={handleSubmit}
>
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<Label htmlFor="pb-product">Artikel</Label> <Label htmlFor="pb-product">Artikel</Label>
<Select value={productId} onValueChange={(value) => setProductId(value ?? "")}> <Select
value={productId}
onValueChange={(value) => setProductId(value ?? "")}
>
<SelectTrigger id="pb-product" className="w-full"> <SelectTrigger id="pb-product" className="w-full">
<SelectValue placeholder="Artikel wählen">{selected?.name}</SelectValue> <SelectValue placeholder="Artikel wählen">
{selected?.name}
</SelectValue>
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{manufactured.map((product) => ( {manufactured.map((product) => (
@@ -101,7 +141,8 @@ export default function NewProductionBatchPage() {
</Select> </Select>
{products && manufactured.length === 0 ? ( {products && manufactured.length === 0 ? (
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
Noch kein Artikel der Art &bdquo;Hergestellte Ware&ldquo;. Lege ihn unter Produkte an. Noch kein Artikel der Art &bdquo;Hergestellte Ware&ldquo;.
Lege ihn unter Produkte an.
</p> </p>
) : null} ) : null}
</div> </div>
@@ -138,7 +179,9 @@ export default function NewProductionBatchPage() {
/> />
</div> </div>
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<Label htmlFor="pb-best-before">Mindesthaltbar bis (optional)</Label> <Label htmlFor="pb-best-before">
Mindesthaltbar bis (optional)
</Label>
<Input <Input
id="pb-best-before" id="pb-best-before"
type="date" type="date"
@@ -146,9 +189,108 @@ export default function NewProductionBatchPage() {
onChange={(event) => setBestBeforeDate(event.target.value)} onChange={(event) => setBestBeforeDate(event.target.value)}
/> />
</div> </div>
<fieldset className="flex flex-col gap-3 rounded-lg border p-3">
<legend className="px-1 text-sm font-medium">
Verbrauchte Rohstoffe (optional)
</legend>
<p className="text-xs text-muted-foreground">
Wird beim Anlegen vom Rohstoff abgebucht. So lässt sich später
nachverfolgen, aus welchem Wachs oder Propolis diese Charge
stammt.
</p>
{inputs.map((row, index) => {
const lot = availableLots.find(
(candidate) => candidate.id === row.rawMaterialLotId,
);
return (
<div key={index} className="flex flex-wrap items-end gap-2">
<div className="flex min-w-48 flex-1 flex-col gap-1">
<Label htmlFor={`pb-input-lot-${index}`}>Rohstoff</Label>
<Select
value={row.rawMaterialLotId}
onValueChange={(value) =>
updateInput(index, { rawMaterialLotId: value ?? "" })
}
>
<SelectTrigger
id={`pb-input-lot-${index}`}
className="w-full"
>
<SelectValue placeholder="Charge wählen">
{lot
? `${RAW_MATERIAL_KIND_LABELS[lot.kind]} ${lot.lotNumber}`
: undefined}
</SelectValue>
</SelectTrigger>
<SelectContent>
{availableLots.map((candidate) => (
<SelectItem key={candidate.id} value={candidate.id}>
{RAW_MATERIAL_KIND_LABELS[candidate.kind]}{" "}
{candidate.lotNumber} (noch{" "}
{formatGrams(candidate.remainingCount)})
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex w-28 flex-col gap-1">
<Label htmlFor={`pb-input-grams-${index}`}>Gramm</Label>
<Input
id={`pb-input-grams-${index}`}
type="number"
inputMode="numeric"
min={1}
max={lot?.remainingCount}
step={1}
value={row.grams}
onChange={(event) =>
updateInput(index, { grams: event.target.value })
}
/>
</div>
<Button
type="button"
variant="outline"
size="sm"
onClick={() =>
setInputs((current) =>
current.filter((_, i) => i !== index),
)
}
>
Entfernen
</Button>
</div>
);
})}
<Button
type="button"
variant="outline"
size="sm"
className="self-start"
disabled={availableLots.length === 0}
onClick={() =>
setInputs((current) => [
...current,
{ rawMaterialLotId: "", grams: "" },
])
}
>
+ Rohstoff hinzufügen
</Button>
{rawLots && availableLots.length === 0 ? (
<p className="text-xs text-muted-foreground">
Kein Rohstoff mit Restbestand vorhanden.
</p>
) : null}
</fieldset>
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<Label htmlFor="pb-notes">Notiz (optional, intern)</Label> <Label htmlFor="pb-notes">Notiz (optional, intern)</Label>
<Textarea id="pb-notes" value={notes} onChange={(event) => setNotes(event.target.value)} /> <Textarea
id="pb-notes"
value={notes}
onChange={(event) => setNotes(event.target.value)}
/>
</div> </div>
{error ? ( {error ? (
<p role="alert" className="text-sm text-destructive"> <p role="alert" className="text-sm text-destructive">
@@ -20,7 +20,11 @@ export default function ProductionBatchesPage() {
}); });
const newButton = canCreate ? ( const newButton = canCreate ? (
<Button size="touch" nativeButton={false} render={<Link href="/production-batches/new" />}> <Button
size="touch"
nativeButton={false}
render={<Link href="/production-batches/new" />}
>
+ Neue Herstellungscharge + Neue Herstellungscharge
</Button> </Button>
) : null; ) : null;
@@ -59,9 +63,15 @@ export default function ProductionBatchesPage() {
{ label: "Hergestellt", value: String(batch.quantity) }, { label: "Hergestellt", value: String(batch.quantity) },
{ {
label: "Rest", label: "Rest",
value: batch.remainingCount < 0 ? `${batch.remainingCount} (prüfen)` : String(batch.remainingCount), value:
batch.remainingCount < 0
? `${batch.remainingCount} (prüfen)`
: String(batch.remainingCount),
},
{
label: "Datum",
value: new Date(batch.date).toLocaleDateString("de-DE"),
}, },
{ label: "Datum", value: new Date(batch.date).toLocaleDateString("de-DE") },
]} ]}
/> />
))} ))}
@@ -0,0 +1,136 @@
"use client";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { Boxes } from "lucide-react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import {
deleteRawMaterialLot,
fetchRawMaterialLot,
} from "@/lib/raw-materials/api";
import {
RAW_MATERIAL_KIND_LABELS,
formatGrams,
} from "@/lib/raw-materials/labels";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ConfirmDialog } from "@/components/confirm-dialog";
import { DetailHeader, DetailQueryFallback } from "@/components/detail-header";
import { StockCard } from "@/components/stock/stock-card";
import { useAuth } from "@/lib/auth/auth-context";
const BACK = { backHref: "/raw-materials", backLabel: "Alle Rohstoffe" };
export default function RawMaterialDetailPage() {
const params = useParams<{ id: string }>();
const router = useRouter();
const queryClient = useQueryClient();
const { hasPermission } = useAuth();
const lotQuery = useQuery({
queryKey: ["raw-material-lots", params.id],
queryFn: () => fetchRawMaterialLot(params.id),
});
const lot = lotQuery.data;
const deletion = useMutation({
mutationFn: () => deleteRawMaterialLot(params.id),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["raw-material-lots"] });
toast.success("Rohstoff gelöscht");
router.push("/raw-materials");
},
onError: (error: Error) =>
toast.error(error.message || "Rohstoff konnte nicht gelöscht werden"),
});
if (lotQuery.isLoading || lotQuery.isError || !lot) {
return (
<DetailQueryFallback
query={lotQuery}
what="Daten des Rohstoffs"
{...BACK}
/>
);
}
return (
<main className="flex flex-col gap-4 p-4 sm:p-6">
<DetailHeader
icon={Boxes}
title={`${RAW_MATERIAL_KIND_LABELS[lot.kind]} ${lot.lotNumber}`}
subtitle={`${formatGrams(lot.quantity)} gewonnen am ${new Date(lot.date).toLocaleDateString("de-DE")}`}
{...BACK}
/>
<div className="grid grid-cols-1 items-start gap-4 lg:grid-cols-2">
<div className="flex flex-col gap-4">
<Card>
<CardHeader className="flex flex-row flex-wrap items-center justify-between gap-2.5">
<CardTitle>Angaben</CardTitle>
{hasPermission("raw-material:delete") ? (
<ConfirmDialog
triggerLabel="Löschen"
triggerVariant="outline"
triggerSize="sm"
title="Rohstoff löschen"
description={`${lot.lotNumber} wird entfernt. Das geht nur, solange nichts verbraucht, entnommen oder inventiert wurde.`}
confirmLabel="Endgültig löschen"
onConfirm={() => deletion.mutate()}
isPending={deletion.isPending}
/>
) : null}
</CardHeader>
<CardContent className="flex flex-col gap-2 text-sm">
<p>Art: {RAW_MATERIAL_KIND_LABELS[lot.kind]}</p>
{lot.apiary ? <p>Stand: {lot.apiary.name}</p> : null}
{lot.notes ? (
<p className="whitespace-pre-line">Notiz: {lot.notes}</p>
) : null}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Verwendet in</CardTitle>
</CardHeader>
<CardContent>
{lot.usedIn.length === 0 ? (
<p className="text-sm text-muted-foreground">
Noch in keiner Herstellungscharge verwendet.
</p>
) : (
<ul className="flex flex-col divide-y rounded-lg border text-sm">
{lot.usedIn.map((use) => (
<li key={use.id}>
<Link
href={`/production-batches/${use.productionBatch.id}`}
className="flex items-baseline justify-between gap-2 p-3 hover:bg-muted"
>
<span>
<span className="font-mono font-medium">
{use.productionBatch.lotNumber}
</span>{" "}
<span className="text-muted-foreground">
{use.productionBatch.product.name}
</span>
</span>
<span className="tabular-nums">
{formatGrams(use.quantity)}
</span>
</Link>
</li>
))}
</ul>
)}
</CardContent>
</Card>
</div>
<StockCard
path="raw-material-lots"
id={lot.id}
initialLabel="Gewonnen"
unit="g"
canBook={hasPermission("raw-material:withdraw")}
/>
</div>
</main>
);
}
@@ -0,0 +1,186 @@
"use client";
import { FormEvent, useState } from "react";
import { useRouter } from "next/navigation";
import { Boxes } from "lucide-react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { createRawMaterialLot } from "@/lib/raw-materials/api";
import { RAW_MATERIAL_KIND_LABELS } from "@/lib/raw-materials/labels";
import { RawMaterialKind } from "@/lib/raw-materials/types";
import { fetchApiaries } from "@/lib/apiaries/api";
import { PageHeader } from "@/components/page-header";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
const NO_APIARY = "__none__";
export default function NewRawMaterialPage() {
const router = useRouter();
const queryClient = useQueryClient();
const [kind, setKind] = useState<RawMaterialKind>("BEESWAX");
const [lotNumber, setLotNumber] = useState("");
const [date, setDate] = useState(new Date().toISOString().slice(0, 10));
const [quantity, setQuantity] = useState("");
const [apiaryId, setApiaryId] = useState(NO_APIARY);
const [notes, setNotes] = useState("");
const [error, setError] = useState<string | null>(null);
const { data: apiaries } = useQuery({
queryKey: ["apiaries"],
queryFn: () => fetchApiaries(),
});
const selectedApiary = apiaries?.find((apiary) => apiary.id === apiaryId);
const mutation = useMutation({
mutationFn: () =>
createRawMaterialLot({
kind,
lotNumber: lotNumber.trim(),
date: new Date(date).toISOString(),
quantity: Number(quantity),
apiaryId: apiaryId === NO_APIARY ? undefined : apiaryId,
notes: notes.trim() || undefined,
}),
onSuccess: (lot) => {
void queryClient.invalidateQueries({ queryKey: ["raw-material-lots"] });
toast.success(`Rohstoff ${lot.lotNumber} angelegt`);
router.push(`/raw-materials/${lot.id}`);
},
onError: (mutationError: Error) => {
const message =
mutationError.message || "Rohstoff konnte nicht angelegt werden";
setError(message);
toast.error(message);
},
});
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setError(null);
mutation.mutate();
}
return (
<main className="flex flex-col gap-4 p-4 sm:p-6">
<PageHeader
icon={Boxes}
title="Neuer Rohstoff"
description="Was hast du gewonnen, und wie viel?"
/>
<Card>
<CardContent>
<form
className="flex max-w-xl flex-col gap-4"
onSubmit={handleSubmit}
>
<div className="flex flex-col gap-2">
<Label htmlFor="raw-kind">Art</Label>
<Select
value={kind}
onValueChange={(value) =>
setKind((value ?? kind) as RawMaterialKind)
}
>
<SelectTrigger id="raw-kind" className="w-full">
<SelectValue>{RAW_MATERIAL_KIND_LABELS[kind]}</SelectValue>
</SelectTrigger>
<SelectContent>
{(
Object.keys(RAW_MATERIAL_KIND_LABELS) as RawMaterialKind[]
).map((option) => (
<SelectItem key={option} value={option}>
{RAW_MATERIAL_KIND_LABELS[option]}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="raw-lot">Chargennummer</Label>
<Input
id="raw-lot"
required
value={lotNumber}
onChange={(event) => setLotNumber(event.target.value)}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="raw-date">Gewonnen am</Label>
<Input
id="raw-date"
type="date"
required
value={date}
onChange={(event) => setDate(event.target.value)}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="raw-quantity">Menge (g)</Label>
<Input
id="raw-quantity"
type="number"
inputMode="numeric"
min={1}
step={1}
required
value={quantity}
onChange={(event) => setQuantity(event.target.value)}
/>
<p className="text-xs text-muted-foreground">
In Gramm, z. B. 4200 für 4,2 kg Wachs.
</p>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="raw-apiary">Stand (optional)</Label>
<Select
value={apiaryId}
onValueChange={(value) => setApiaryId(value ?? NO_APIARY)}
>
<SelectTrigger id="raw-apiary" className="w-full">
<SelectValue>
{selectedApiary?.name ?? "Kein Stand"}
</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem value={NO_APIARY}>Kein Stand</SelectItem>
{(apiaries ?? []).map((apiary) => (
<SelectItem key={apiary.id} value={apiary.id}>
{apiary.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="raw-notes">Notiz (optional, intern)</Label>
<Textarea
id="raw-notes"
value={notes}
onChange={(event) => setNotes(event.target.value)}
/>
</div>
{error ? (
<p role="alert" className="text-sm text-destructive">
{error}
</p>
) : null}
<Button type="submit" size="touch" disabled={mutation.isPending}>
{mutation.isPending ? "Speichert…" : "Rohstoff anlegen"}
</Button>
</form>
</CardContent>
</Card>
</main>
);
}
@@ -0,0 +1,88 @@
"use client";
import Link from "next/link";
import { Boxes } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { fetchRawMaterialLots } from "@/lib/raw-materials/api";
import {
RAW_MATERIAL_KIND_LABELS,
formatGrams,
} from "@/lib/raw-materials/labels";
import { Button } from "@/components/ui/button";
import { PageHeader } from "@/components/page-header";
import { EmptyState } from "@/components/empty-state";
import { EntityCard } from "@/components/entity-card";
import { QueryState } from "@/components/query-state";
import { useAuth } from "@/lib/auth/auth-context";
export default function RawMaterialsPage() {
const { hasPermission } = useAuth();
const lotsQuery = useQuery({
queryKey: ["raw-material-lots"],
queryFn: () => fetchRawMaterialLots(),
});
const newButton = hasPermission("raw-material:create") ? (
<Button
size="touch"
nativeButton={false}
render={<Link href="/raw-materials/new" />}
>
+ Neuer Rohstoff
</Button>
) : null;
return (
<main className="flex flex-col gap-4 p-4 sm:p-6">
<PageHeader
icon={Boxes}
title="Rohstoffe"
description="Wachs und Propolis je Charge - mit gewonnener Menge, Verbrauch in der Herstellung und Rest."
actions={newButton}
/>
<QueryState
query={lotsQuery}
what="Rohstoffe"
empty={
<EmptyState
icon={Boxes}
title="Noch keine Rohstoffe"
description="Erfasse Wachs vom Entdeckeln oder Propolis von den Gittern, um daraus Kerzen, Tinkturen oder Salben herzustellen."
action={newButton ?? undefined}
/>
}
>
{(lots) => (
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
{lots.map((lot) => (
<EntityCard
key={lot.id}
href={`/raw-materials/${lot.id}`}
icon={Boxes}
title={<span className="font-mono">{lot.lotNumber}</span>}
subtitle={RAW_MATERIAL_KIND_LABELS[lot.kind]}
fields={[
{ label: "Gewonnen", value: formatGrams(lot.quantity) },
{
label: "Rest",
value:
lot.remainingCount < 0
? `${formatGrams(lot.remainingCount)} (prüfen)`
: formatGrams(lot.remainingCount),
},
{
label: "Datum",
value: new Date(lot.date).toLocaleDateString("de-DE"),
},
{
label: "Verwendet in",
value: `${lot.usedIn.length} Charge(n)`,
},
]}
/>
))}
</div>
)}
</QueryState>
</main>
);
}
+25 -4
View File
@@ -9,6 +9,7 @@ import {
Database, Database,
Droplet, Droplet,
Factory, Factory,
Boxes,
FileClock, FileClock,
FlaskConical, FlaskConical,
Hexagon, Hexagon,
@@ -82,6 +83,12 @@ const NAV_GROUPS: NavGroup[] = [
{ label: "Schleuderungen", href: "/extractions", icon: FlaskConical }, { label: "Schleuderungen", href: "/extractions", icon: FlaskConical },
{ label: "Honigchargen", href: "/honey-batches", icon: Droplet }, { label: "Honigchargen", href: "/honey-batches", icon: Droplet },
{ label: "Abfüllungen", href: "/bottling", icon: Package }, { label: "Abfüllungen", href: "/bottling", icon: Package },
{
label: "Rohstoffe",
href: "/raw-materials",
icon: Boxes,
permission: "raw-material:read",
},
{ {
label: "Herstellungschargen", label: "Herstellungschargen",
href: "/production-batches", href: "/production-batches",
@@ -128,7 +135,12 @@ const ADMIN_GROUP: NavGroup = {
icon: Database, icon: Database,
permission: ["backup:export", "backup:import", "import:execute"], permission: ["backup:export", "backup:import", "import:execute"],
}, },
{ label: "Audit-Log", href: "/settings/audit-log", icon: History, permission: "audit:read" }, {
label: "Audit-Log",
href: "/settings/audit-log",
icon: History,
permission: "audit:read",
},
], ],
}; };
@@ -157,7 +169,10 @@ function SidebarLink({ item, pathname }: { item: NavItem; pathname: string }) {
); );
} }
function hasNavPermission(user: AuthUser, permission: NavItem["permission"]): boolean { function hasNavPermission(
user: AuthUser,
permission: NavItem["permission"],
): boolean {
if (!permission) { if (!permission) {
return true; return true;
} }
@@ -185,13 +200,19 @@ export function Sidebar({ user }: { user: AuthUser }) {
className="flex size-8 items-center justify-center rounded-xl shadow-[var(--shadow-soft)]" className="flex size-8 items-center justify-center rounded-xl shadow-[var(--shadow-soft)]"
style={{ background: "var(--gradient-honey)" }} style={{ background: "var(--gradient-honey)" }}
> >
<Hexagon className="size-4.5 fill-white/25 text-white" strokeWidth={2.25} /> <Hexagon
className="size-4.5 fill-white/25 text-white"
strokeWidth={2.25}
/>
</span> </span>
ApiCore ApiCore
</Link> </Link>
<nav className="flex flex-1 flex-col gap-5"> <nav className="flex flex-1 flex-col gap-5">
{groups.map((group, index) => ( {groups.map((group, index) => (
<div key={group.label ?? `group-${index}`} className="flex flex-col gap-0.5"> <div
key={group.label ?? `group-${index}`}
className="flex flex-col gap-0.5"
>
{group.label ? ( {group.label ? (
<p className="px-3 pb-1 text-xs font-semibold tracking-wide text-muted-foreground/80 uppercase"> <p className="px-3 pb-1 text-xs font-semibold tracking-wide text-muted-foreground/80 uppercase">
{group.label} {group.label}
@@ -35,6 +35,7 @@ function stock(remaining: number): BatchStock {
soldInShop: 30, soldInShop: 30,
withdrawn: 10, withdrawn: 10,
corrected: 0, corrected: 0,
consumed: 0,
remaining, remaining,
}, },
movements: [ movements: [
@@ -52,7 +52,13 @@ interface StockCardProps {
* change by hand. The numbers come from the movement ledger; nothing here is * change by hand. The numbers come from the movement ledger; nothing here is
* stored separately, so they cannot drift. * stored separately, so they cannot drift.
*/ */
export function StockCard({ path, id, initialLabel, unit, canBook }: StockCardProps) { export function StockCard({
path,
id,
initialLabel,
unit,
canBook,
}: StockCardProps) {
const stockQuery = useQuery({ const stockQuery = useQuery({
queryKey: ["stock", path, id], queryKey: ["stock", path, id],
queryFn: () => fetchStock(path, id), queryFn: () => fetchStock(path, id),
@@ -65,8 +71,18 @@ export function StockCard({ path, id, initialLabel, unit, canBook }: StockCardPr
<CardTitle>Bestand</CardTitle> <CardTitle>Bestand</CardTitle>
{canBook && stock ? ( {canBook && stock ? (
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
<WithdrawDialog path={path} id={id} unit={unit} remaining={stock.summary.remaining} /> <WithdrawDialog
<CorrectDialog path={path} id={id} unit={unit} remaining={stock.summary.remaining} /> path={path}
id={id}
unit={unit}
remaining={stock.summary.remaining}
/>
<CorrectDialog
path={path}
id={id}
unit={unit}
remaining={stock.summary.remaining}
/>
</div> </div>
) : null} ) : null}
</CardHeader> </CardHeader>
@@ -79,7 +95,11 @@ export function StockCard({ path, id, initialLabel, unit, canBook }: StockCardPr
<p className="text-sm text-muted-foreground">Lädt…</p> <p className="text-sm text-muted-foreground">Lädt…</p>
) : ( ) : (
<> <>
<SummaryGrid summary={stock.summary} initialLabel={initialLabel} /> <SummaryGrid
summary={stock.summary}
initialLabel={initialLabel}
isRawMaterial={path === "raw-material-lots"}
/>
<MovementList movements={stock.movements} /> <MovementList movements={stock.movements} />
</> </>
)} )}
@@ -91,14 +111,18 @@ export function StockCard({ path, id, initialLabel, unit, canBook }: StockCardPr
function SummaryGrid({ function SummaryGrid({
summary, summary,
initialLabel, initialLabel,
isRawMaterial,
}: { }: {
isRawMaterial: boolean;
summary: StockSummary; summary: StockSummary;
initialLabel: string; initialLabel: string;
}) { }) {
const needsReview = summary.remaining < 0; const needsReview = summary.remaining < 0;
const items = [ const items = [
{ label: initialLabel, value: summary.initial }, { label: initialLabel, value: summary.initial },
{ label: "Webshop verkauft", value: summary.soldInShop }, isRawMaterial
? { label: "In Herstellung verbraucht", value: summary.consumed }
: { label: "Webshop verkauft", value: summary.soldInShop },
{ label: "Entnommen", value: summary.withdrawn }, { label: "Entnommen", value: summary.withdrawn },
]; ];
return ( return (
@@ -120,7 +144,9 @@ function SummaryGrid({
Rest Rest
{needsReview ? <Badge variant="destructive">Prüfen</Badge> : null} {needsReview ? <Badge variant="destructive">Prüfen</Badge> : null}
</dt> </dt>
<dd className="text-xl font-semibold tabular-nums">{summary.remaining}</dd> <dd className="text-xl font-semibold tabular-nums">
{summary.remaining}
</dd>
{summary.corrected !== 0 ? ( {summary.corrected !== 0 ? (
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
inkl. Inventur {summary.corrected > 0 ? "+" : ""} inkl. Inventur {summary.corrected > 0 ? "+" : ""}
@@ -143,18 +169,26 @@ function MovementList({ movements }: { movements: StockMovement[] }) {
return ( return (
<ul className="flex flex-col divide-y rounded-lg border text-sm"> <ul className="flex flex-col divide-y rounded-lg border text-sm">
{movements.map((movement) => ( {movements.map((movement) => (
<li key={movement.id} className="flex flex-wrap items-baseline justify-between gap-2 p-3"> <li
key={movement.id}
className="flex flex-wrap items-baseline justify-between gap-2 p-3"
>
<div className="flex flex-col"> <div className="flex flex-col">
<span className="font-medium"> <span className="font-medium">
{MOVEMENT_TYPE_LABELS[movement.type]} {MOVEMENT_TYPE_LABELS[movement.type]}
{movement.reason ? ` · ${WITHDRAWAL_REASON_LABELS[movement.reason]}` : ""} {movement.reason
? ` · ${WITHDRAWAL_REASON_LABELS[movement.reason]}`
: ""}
</span> </span>
<span className="text-xs text-muted-foreground"> <span className="text-xs text-muted-foreground">
{new Date(movement.createdAt).toLocaleString("de-DE")} ·{" "} {new Date(movement.createdAt).toLocaleString("de-DE")} ·{" "}
{movement.user?.name ?? (movement.shopRequest ? "Webshop" : "System")} {movement.user?.name ??
(movement.shopRequest ? "Webshop" : "System")}
</span> </span>
{movement.notes ? ( {movement.notes ? (
<span className="text-xs text-muted-foreground">{movement.notes}</span> <span className="text-xs text-muted-foreground">
{movement.notes}
</span>
) : null} ) : null}
</div> </div>
<span <span
@@ -214,7 +248,8 @@ function WithdrawDialog({
setNotes(""); setNotes("");
}, },
onError: (mutationError: Error) => { onError: (mutationError: Error) => {
const message = mutationError.message || "Entnahme konnte nicht gebucht werden"; const message =
mutationError.message || "Entnahme konnte nicht gebucht werden";
setError(message); setError(message);
toast.error(message); toast.error(message);
}, },
@@ -242,7 +277,8 @@ function WithdrawDialog({
</DialogHeader> </DialogHeader>
<form className="flex flex-col gap-4" onSubmit={handleSubmit}> <form className="flex flex-col gap-4" onSubmit={handleSubmit}>
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
Noch da: {remaining} {unit}. Die Entnahme mindert auch den Bestand im Webshop. Noch da: {remaining} {unit}. Die Entnahme mindert auch den Bestand
im Webshop.
</p> </p>
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<Label htmlFor="withdraw-quantity">Anzahl ({unit})</Label> <Label htmlFor="withdraw-quantity">Anzahl ({unit})</Label>
@@ -262,13 +298,17 @@ function WithdrawDialog({
<Label htmlFor="withdraw-reason">Grund</Label> <Label htmlFor="withdraw-reason">Grund</Label>
<Select <Select
value={reason} value={reason}
onValueChange={(value) => setReason((value ?? reason) as WithdrawalReason)} onValueChange={(value) =>
setReason((value ?? reason) as WithdrawalReason)
}
> >
<SelectTrigger id="withdraw-reason" className="w-full"> <SelectTrigger id="withdraw-reason" className="w-full">
<SelectValue>{WITHDRAWAL_REASON_LABELS[reason]}</SelectValue> <SelectValue>{WITHDRAWAL_REASON_LABELS[reason]}</SelectValue>
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{(Object.keys(WITHDRAWAL_REASON_LABELS) as WithdrawalReason[]).map((option) => ( {(
Object.keys(WITHDRAWAL_REASON_LABELS) as WithdrawalReason[]
).map((option) => (
<SelectItem key={option} value={option}> <SelectItem key={option} value={option}>
{WITHDRAWAL_REASON_LABELS[option]} {WITHDRAWAL_REASON_LABELS[option]}
</SelectItem> </SelectItem>
@@ -318,7 +358,10 @@ function CorrectDialog({
const mutation = useMutation({ const mutation = useMutation({
mutationFn: () => mutationFn: () =>
correctStock(path, id, { countedQuantity: Number(counted), notes: notes.trim() }), correctStock(path, id, {
countedQuantity: Number(counted),
notes: notes.trim(),
}),
onSuccess: () => { onSuccess: () => {
done(); done();
toast.success("Inventur gebucht"); toast.success("Inventur gebucht");
@@ -326,7 +369,8 @@ function CorrectDialog({
setNotes(""); setNotes("");
}, },
onError: (mutationError: Error) => { onError: (mutationError: Error) => {
const message = mutationError.message || "Inventur konnte nicht gebucht werden"; const message =
mutationError.message || "Inventur konnte nicht gebucht werden";
setError(message); setError(message);
toast.error(message); toast.error(message);
}, },
@@ -360,8 +404,8 @@ function CorrectDialog({
</DialogHeader> </DialogHeader>
<form className="flex flex-col gap-4" onSubmit={handleSubmit}> <form className="flex flex-col gap-4" onSubmit={handleSubmit}>
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
Gebucht sind {remaining} {unit}. Trag ein, wie viele du gezählt hast - gebucht wird die Gebucht sind {remaining} {unit}. Trag ein, wie viele du gezählt hast
Differenz. - gebucht wird die Differenz.
</p> </p>
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<Label htmlFor="correct-counted">Gezählt ({unit})</Label> <Label htmlFor="correct-counted">Gezählt ({unit})</Label>
@@ -396,7 +440,10 @@ function CorrectDialog({
{error} {error}
</p> </p>
) : null} ) : null}
<Button type="submit" disabled={mutation.isPending || difference === 0}> <Button
type="submit"
disabled={mutation.isPending || difference === 0}
>
{mutation.isPending ? "Bucht…" : "Inventur buchen"} {mutation.isPending ? "Bucht…" : "Inventur buchen"}
</Button> </Button>
</form> </form>
@@ -9,6 +9,12 @@ export interface ProductionBatch {
createdAt: string; createdAt: string;
remainingCount: number; remainingCount: number;
product: { id: string; name: string }; product: { id: string; name: string };
/** Raw material this batch was made from (grams). */
inputs?: {
id: string;
quantity: number;
rawMaterialLot: { id: string; lotNumber: string; kind: "BEESWAX" | "PROPOLIS" };
}[];
} }
export interface CreateProductionBatchInput { export interface CreateProductionBatchInput {
@@ -18,6 +24,7 @@ export interface CreateProductionBatchInput {
quantity: number; quantity: number;
bestBeforeDate?: string; bestBeforeDate?: string;
notes?: string; notes?: string;
inputs?: { rawMaterialLotId: string; quantity: number }[];
} }
export interface UpdateProductionBatchInput { export interface UpdateProductionBatchInput {
@@ -0,0 +1,33 @@
import { apiFetch } from "@/lib/auth/api-client";
import {
CreateRawMaterialLotInput,
RawMaterialKind,
RawMaterialLot,
} from "./types";
export function fetchRawMaterialLots(
kind?: RawMaterialKind,
): Promise<RawMaterialLot[]> {
return apiFetch<RawMaterialLot[]>(
`/raw-material-lots${kind ? `?kind=${kind}` : ""}`,
);
}
export function fetchRawMaterialLot(id: string): Promise<RawMaterialLot> {
return apiFetch<RawMaterialLot>(`/raw-material-lots/${id}`);
}
export function createRawMaterialLot(
input: CreateRawMaterialLotInput,
): Promise<RawMaterialLot> {
return apiFetch<RawMaterialLot>("/raw-material-lots", {
method: "POST",
body: JSON.stringify(input),
});
}
export function deleteRawMaterialLot(id: string): Promise<{ id: string }> {
return apiFetch<{ id: string }>(`/raw-material-lots/${id}`, {
method: "DELETE",
});
}
@@ -0,0 +1,13 @@
import { describe, expect, it } from "vitest";
import { formatGrams } from "./labels";
describe("formatGrams", () => {
it("shows kilograms from 1000 g on", () => {
expect(formatGrams(4200)).toBe("4,2 kg");
expect(formatGrams(1000)).toBe("1 kg");
});
it("keeps grams below a kilogram", () => {
expect(formatGrams(180)).toBe("180 g");
});
});
@@ -0,0 +1,14 @@
import { RawMaterialKind } from "./types";
export const RAW_MATERIAL_KIND_LABELS: Record<RawMaterialKind, string> = {
BEESWAX: "Bienenwachs",
PROPOLIS: "Propolis",
};
/** 4200 -> "4,2 kg", 180 -> "180 g". */
export function formatGrams(grams: number): string {
if (Math.abs(grams) >= 1000) {
return `${(grams / 1000).toLocaleString("de-DE", { maximumFractionDigits: 2 })} kg`;
}
return `${grams.toLocaleString("de-DE")} g`;
}
@@ -0,0 +1,36 @@
export type RawMaterialKind = "BEESWAX" | "PROPOLIS";
export interface RawMaterialLot {
id: string;
kind: RawMaterialKind;
lotNumber: string;
date: string;
/** Gewonnene Menge in Gramm. */
quantity: number;
apiaryId: string | null;
harvestId: string | null;
notes: string | null;
createdAt: string;
/** Rest in Gramm (Ausgangsmenge plus alle Bewegungen). */
remainingCount: number;
apiary: { id: string; name: string } | null;
harvest: { id: string; date: string } | null;
usedIn: {
id: string;
quantity: number;
productionBatch: {
id: string;
lotNumber: string;
product: { id: string; name: string };
};
}[];
}
export interface CreateRawMaterialLotInput {
kind: RawMaterialKind;
lotNumber: string;
date: string;
quantity: number;
apiaryId?: string;
notes?: string;
}
+4 -1
View File
@@ -6,7 +6,10 @@ import {
WithdrawInput, WithdrawInput,
} from "./types"; } from "./types";
export function fetchStock(path: StockBatchPath, id: string): Promise<BatchStock> { export function fetchStock(
path: StockBatchPath,
id: string,
): Promise<BatchStock> {
return apiFetch<BatchStock>(`/${path}/${id}/stock`); return apiFetch<BatchStock>(`/${path}/${id}/stock`);
} }
+1
View File
@@ -13,4 +13,5 @@ export const MOVEMENT_TYPE_LABELS: Record<MovementType, string> = {
SHOP_RETURN: "Webshop-Rückbuchung", SHOP_RETURN: "Webshop-Rückbuchung",
WITHDRAWAL: "Entnahme", WITHDRAWAL: "Entnahme",
CORRECTION: "Inventur", CORRECTION: "Inventur",
CONSUMPTION: "Verbrauch in Herstellung",
}; };
+6 -10
View File
@@ -1,18 +1,12 @@
/** Collection path of a batch whose stock is tracked in the movement ledger. */ /** Collection path of a batch whose stock is tracked in the movement ledger. */
export type StockBatchPath = "bottling-batches" | "production-batches"; export type StockBatchPath =
"bottling-batches" | "production-batches" | "raw-material-lots";
export type WithdrawalReason = export type WithdrawalReason =
| "HOFLADEN" "HOFLADEN" | "EIGENBEDARF" | "BRUCH" | "PROBE" | "SONSTIGES";
| "EIGENBEDARF"
| "BRUCH"
| "PROBE"
| "SONSTIGES";
export type MovementType = export type MovementType =
| "SHOP_SALE" "SHOP_SALE" | "SHOP_RETURN" | "WITHDRAWAL" | "CORRECTION" | "CONSUMPTION";
| "SHOP_RETURN"
| "WITHDRAWAL"
| "CORRECTION";
export interface StockSummary { export interface StockSummary {
/** Bottled or produced. */ /** Bottled or produced. */
@@ -22,6 +16,8 @@ export interface StockSummary {
withdrawn: number; withdrawn: number;
/** Net inventory corrections. */ /** Net inventory corrections. */
corrected: number; corrected: number;
/** Raw material used in production (net of give-backs). */
consumed: number;
remaining: number; remaining: number;
} }
@@ -1,49 +0,0 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import {
IsDateString,
IsEnum,
IsInt,
IsNotEmpty,
IsOptional,
IsPositive,
IsString,
MaxLength,
} from 'class-validator';
import { RawMaterialKind } from '../../../generated/prisma';
export class CreateRawMaterialLotDto {
@ApiProperty({ enum: RawMaterialKind })
@IsEnum(RawMaterialKind)
kind!: RawMaterialKind;
@ApiProperty()
@IsString()
@IsNotEmpty()
@MaxLength(100)
lotNumber!: string;
@ApiProperty({ description: 'Gewinnungsdatum' })
@IsDateString()
date!: string;
@ApiProperty({ description: 'Gewonnene Menge in Gramm' })
@IsInt()
@IsPositive()
quantity!: number;
@ApiPropertyOptional({ description: 'Stand, von dem der Rohstoff stammt' })
@IsOptional()
@IsString()
apiaryId?: string;
@ApiPropertyOptional({ description: 'Ernte, bei der er anfiel (z. B. Entdeckelungswachs)' })
@IsOptional()
@IsString()
harvestId?: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
@MaxLength(2000)
notes?: string;
}
@@ -1,54 +0,0 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import {
IsDateString,
IsInt,
IsNotEmpty,
IsOptional,
IsPositive,
IsString,
MaxLength,
ValidateIf,
} from 'class-validator';
/**
* Corrects a raw material lot entered with a typo. The kind stays fixed -
* wax that went into candles does not turn into propolis afterwards.
* `apiaryId: null` / `harvestId: null` remove the origin.
*/
export class UpdateRawMaterialLotDto {
@ApiPropertyOptional()
@IsOptional()
@IsString()
@IsNotEmpty()
@MaxLength(100)
lotNumber?: string;
@ApiPropertyOptional()
@IsOptional()
@IsDateString()
date?: string;
@ApiPropertyOptional({ description: 'Gewonnene Menge in Gramm' })
@IsOptional()
@IsInt()
@IsPositive()
quantity?: number;
@ApiPropertyOptional({ nullable: true })
@IsOptional()
@ValidateIf((_object, value) => value !== null)
@IsString()
apiaryId?: string | null;
@ApiPropertyOptional({ nullable: true })
@IsOptional()
@ValidateIf((_object, value) => value !== null)
@IsString()
harvestId?: string | null;
@ApiPropertyOptional()
@IsOptional()
@IsString()
@MaxLength(2000)
notes?: string;
}
@@ -1,105 +0,0 @@
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
Query,
} from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { RequirePermission } from '../auth/decorators/require-permission.decorator';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import type { AuthenticatedUser } from '../auth/types/authenticated-user';
import { Idempotent } from '../common/idempotency/idempotent.decorator';
import { StockService } from '../stock/stock.service';
import { WithdrawStockDto } from '../stock/dto/withdraw-stock.dto';
import { CorrectStockDto } from '../stock/dto/correct-stock.dto';
import { RawMaterialKind } from '../../generated/prisma';
import { CreateRawMaterialLotDto } from './dto/create-raw-material-lot.dto';
import { UpdateRawMaterialLotDto } from './dto/update-raw-material-lot.dto';
import { RawMaterialsService } from './raw-materials.service';
const KINDS = Object.values(RawMaterialKind) as string[];
@ApiTags('raw-materials')
@ApiBearerAuth()
@Controller('raw-material-lots')
export class RawMaterialsController {
constructor(
private readonly lots: RawMaterialsService,
private readonly stock: StockService,
) {}
@RequirePermission('raw-material:read')
@Get()
findAll(@Query('kind') kind?: string) {
return this.lots.findAll({
kind: kind && KINDS.includes(kind) ? (kind as RawMaterialKind) : undefined,
});
}
@RequirePermission('raw-material:read')
@Get(':id')
findOne(@Param('id') id: string) {
return this.lots.findById(id);
}
@RequirePermission('raw-material:read')
@Get(':id/stock')
async stockOf(@Param('id') id: string) {
await this.lots.findById(id);
return this.stock.stockOf({ kind: 'raw', id });
}
@RequirePermission('raw-material:create')
@Idempotent()
@Post()
create(
@Body() dto: CreateRawMaterialLotDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.lots.create(dto, actor.id);
}
@RequirePermission('raw-material:withdraw')
@Idempotent()
@Post(':id/withdrawals')
async withdraw(
@Param('id') id: string,
@Body() dto: WithdrawStockDto,
@CurrentUser() actor: AuthenticatedUser,
) {
await this.lots.findById(id);
return this.stock.withdraw({ kind: 'raw', id }, dto, actor.id);
}
@RequirePermission('raw-material:withdraw')
@Idempotent()
@Post(':id/corrections')
async correct(
@Param('id') id: string,
@Body() dto: CorrectStockDto,
@CurrentUser() actor: AuthenticatedUser,
) {
await this.lots.findById(id);
return this.stock.correct({ kind: 'raw', id }, dto, actor.id);
}
@RequirePermission('raw-material:update')
@Patch(':id')
update(
@Param('id') id: string,
@Body() dto: UpdateRawMaterialLotDto,
@CurrentUser() actor: AuthenticatedUser,
) {
return this.lots.update(id, dto, actor.id);
}
@RequirePermission('raw-material:delete')
@Delete(':id')
remove(@Param('id') id: string, @CurrentUser() actor: AuthenticatedUser) {
return this.lots.remove(id, actor.id);
}
}
@@ -1,11 +0,0 @@
import { Module } from '@nestjs/common';
import { StockModule } from '../stock/stock.module';
import { RawMaterialsController } from './raw-materials.controller';
import { RawMaterialsService } from './raw-materials.service';
@Module({
imports: [StockModule],
controllers: [RawMaterialsController],
providers: [RawMaterialsService],
})
export class RawMaterialsModule {}
@@ -1,147 +0,0 @@
import {
ConflictException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { AuditLogService } from '../audit/audit-log.service';
import { StockService } from '../stock/stock.service';
import { RawMaterialKind } from '../../generated/prisma';
import { CreateRawMaterialLotDto } from './dto/create-raw-material-lot.dto';
import { UpdateRawMaterialLotDto } from './dto/update-raw-material-lot.dto';
const include = {
apiary: { select: { id: true, name: true } },
harvest: { select: { id: true, date: true } },
// Forward traceability: which production batches this lot went into.
usedIn: {
select: {
id: true,
quantity: true,
productionBatch: {
select: {
id: true,
lotNumber: true,
product: { select: { id: true, name: true } },
},
},
},
orderBy: { createdAt: 'desc' as const },
},
} as const;
export interface RawMaterialLotFilter {
kind?: RawMaterialKind;
}
/**
* Raw material lots (beeswax, propolis) in grams. Their stock lives in the
* same movement ledger as bottlings and production batches: withdrawals and
* inventory counts by hand, consumption when a production batch is made.
*/
@Injectable()
export class RawMaterialsService {
constructor(
private readonly prisma: PrismaService,
private readonly auditLog: AuditLogService,
private readonly stock: StockService,
) {}
async findAll(filter: RawMaterialLotFilter = {}) {
const lots = await this.prisma.rawMaterialLot.findMany({
where: { kind: filter.kind },
include,
orderBy: { date: 'desc' },
});
const remaining = await this.stock.remainingByRawMaterialLot(
lots.map((lot) => lot.id),
);
return lots.map((lot) => ({
...lot,
remainingCount: remaining.get(lot.id) ?? lot.quantity,
}));
}
async findById(id: string) {
const lot = await this.prisma.rawMaterialLot.findUnique({
where: { id },
include,
});
if (!lot) throw new NotFoundException('Raw material lot not found');
const remaining = await this.stock.remainingByRawMaterialLot([id]);
return { ...lot, remainingCount: remaining.get(id) ?? lot.quantity };
}
async create(dto: CreateRawMaterialLotDto, actingUserId: string) {
// A duplicate lotNumber surfaces as P2002 and becomes a 409 in
// AllExceptionsFilter; an unknown apiary/harvest as a foreign-key error.
const lot = await this.prisma.rawMaterialLot.create({
data: {
kind: dto.kind,
lotNumber: dto.lotNumber,
date: new Date(dto.date),
quantity: dto.quantity,
apiaryId: dto.apiaryId,
harvestId: dto.harvestId,
notes: dto.notes,
userId: actingUserId,
},
});
await this.auditLog.record({
entityType: 'RawMaterialLot',
entityId: lot.id,
action: 'CREATE',
userId: actingUserId,
afterData: lot,
});
return this.findById(lot.id);
}
async update(
id: string,
dto: UpdateRawMaterialLotDto,
actingUserId: string,
) {
const before = await this.findById(id);
await this.prisma.rawMaterialLot.update({
where: { id },
data: {
lotNumber: dto.lotNumber,
date: dto.date ? new Date(dto.date) : undefined,
quantity: dto.quantity,
apiaryId: dto.apiaryId,
harvestId: dto.harvestId,
notes: dto.notes,
},
});
const after = await this.findById(id);
await this.auditLog.record({
entityType: 'RawMaterialLot',
entityId: id,
action: 'UPDATE',
userId: actingUserId,
beforeData: before,
afterData: after,
});
return after;
}
/** Only for lots entered by mistake: once anything was booked, it stays. */
async remove(id: string, actingUserId: string) {
const before = await this.findById(id);
if (await this.stock.hasMovements({ kind: 'raw', id })) {
throw new ConflictException(
'Rohstoff-Charge hat bereits Bewegungen (Verbrauch, Entnahme oder Inventur) und kann nicht gelöscht werden',
);
}
await this.prisma.rawMaterialLot.delete({ where: { id } });
await this.auditLog.record({
entityType: 'RawMaterialLot',
entityId: id,
action: 'DELETE',
userId: actingUserId,
beforeData: before,
});
return { id };
}
}