feat(frontend): Voelker-Views (Modul 3) + Refresh-Token-Race-Fix
/colonies: Liste; /colonies/new: Anlegeformular mit Bienenstand-/
Volkstyp-Auswahl; /colonies/[id]: Bearbeiten, Aktionen (Umsetzen,
Ableger bilden, Vereinigen, Aufloesen je als Dialog/Button) und
Historie-Anzeige. Aktionen deaktiviert, sobald das Volk nicht mehr
ACTIVE ist (Frontend-Pendant zum neuen Backend-Guard).
Beim Live-Testen im Browser gefunden und behoben:
- Echter Root-Cause fuer den fruehren Session-Abbruch nach Reload: der
Refresh-Token ist einmalig/rotierend, und React StrictMode ruft den
Session-Restore-Effect im Dev-Modus doppelt auf. Der vorherige
AbortController-Fix verhinderte nur, dass der Client die verworfene
Antwort nutzt - er verhinderte NICHT, dass die zweite Anfrage bereits
serverseitig verarbeitet wurde, bevor abort() griff. Fix: echtes
Request-Deduplizieren in refreshRequest() (gemeinsames In-Flight-
Promise) statt Abbruchversuch - der Standardansatz fuer rotierende
Refresh-Token.
- Historie-Text beim Vereinigen war fuer die aufnehmende Seite falsch
("Entstanden durch Vereinigung" impliziert Neuanlage) - jetzt
"Anderes Volk eingegliedert".
Nav-Leiste und proxy.ts-Matcher um /colonies erweitert.
9 Vitest-Tests, Lint, Typecheck und Build gruen. Kompletter Flow
(Anlegen, Umsetzen, Ableger bilden, Vereinigen, Aufloesen, Historie)
live im Browser gegen den echten Server verifiziert, inkl. Rollen-
filterung in den Aktions-Dialogen.
This commit is contained in:
1 parent
a71b31df38
commit
6e328cdacb
14 files changed
+903
-17
No files matched your search
@@ -22,5 +22,5 @@ export function proxy(request: NextRequest) {
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: ["/login", "/settings/:path*", "/apiaries/:path*"],
|
||||
matcher: ["/login", "/settings/:path*", "/apiaries/:path*", "/colonies/:path*"],
|
||||
};
|
||||
@@ -0,0 +1,274 @@
|
||||
"use client";
|
||||
|
||||
import { FormEvent, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { dissolveColony, mergeColony, moveColony, splitColony } from "@/lib/colonies/api";
|
||||
import { Colony, ColonyType } from "@/lib/colonies/types";
|
||||
import { fetchApiaries } from "@/lib/apiaries/api";
|
||||
import { fetchColonies } from "@/lib/colonies/api";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
|
||||
const COLONY_TYPES: ColonyType[] = [
|
||||
"PRODUCTION_COLONY",
|
||||
"NUCLEUS_COLONY",
|
||||
"YOUNG_COLONY",
|
||||
"CARETAKER_COLONY",
|
||||
"MATING_NUCLEUS",
|
||||
"RESERVE_COLONY",
|
||||
];
|
||||
|
||||
function invalidateColony(
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
colonyId: string,
|
||||
): void {
|
||||
void queryClient.invalidateQueries({ queryKey: ["colonies"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["colonies", colonyId] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["colonies", colonyId, "history"] });
|
||||
}
|
||||
|
||||
function MoveDialog({ colony }: { colony: Colony }) {
|
||||
const queryClient = useQueryClient();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [apiaryId, setApiaryId] = useState("");
|
||||
const { data: apiaries } = useQuery({ queryKey: ["apiaries"], queryFn: fetchApiaries });
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: () => moveColony(colony.id, { apiaryId }),
|
||||
onSuccess: () => {
|
||||
invalidateColony(queryClient, colony.id);
|
||||
setOpen(false);
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger
|
||||
render={
|
||||
<Button variant="outline" disabled={colony.status !== "ACTIVE"}>
|
||||
Umsetzen
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Volk umsetzen</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={(event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
mutation.mutate();
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="move-apiary">Neuer Bienenstand</Label>
|
||||
<Select value={apiaryId} onValueChange={(value) => setApiaryId(value ?? "")}>
|
||||
<SelectTrigger id="move-apiary">
|
||||
<SelectValue placeholder="Bienenstand wählen" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(apiaries ?? [])
|
||||
.filter((apiary) => apiary.id !== colony.apiaryId)
|
||||
.map((apiary) => (
|
||||
<SelectItem key={apiary.id} value={apiary.id}>
|
||||
{apiary.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={!apiaryId || mutation.isPending}>
|
||||
Umsetzen
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function SplitDialog({ colony }: { colony: Colony }) {
|
||||
const queryClient = useQueryClient();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [code, setCode] = useState("");
|
||||
const [colonyType, setColonyType] = useState<ColonyType>("NUCLEUS_COLONY");
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: () => splitColony(colony.id, { code, colonyType }),
|
||||
onSuccess: () => {
|
||||
invalidateColony(queryClient, colony.id);
|
||||
void queryClient.invalidateQueries({ queryKey: ["colonies"] });
|
||||
setOpen(false);
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger
|
||||
render={
|
||||
<Button variant="outline" disabled={colony.status !== "ACTIVE"}>
|
||||
Ableger bilden
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Ableger bilden</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={(event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
mutation.mutate();
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="split-code">Code des Ablegers</Label>
|
||||
<Input
|
||||
id="split-code"
|
||||
required
|
||||
value={code}
|
||||
onChange={(event) => setCode(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="split-type">Volkstyp</Label>
|
||||
<Select
|
||||
value={colonyType}
|
||||
onValueChange={(value) => setColonyType(value as ColonyType)}
|
||||
>
|
||||
<SelectTrigger id="split-type">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{COLONY_TYPES.map((type) => (
|
||||
<SelectItem key={type} value={type}>
|
||||
{type}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={mutation.isPending}>
|
||||
Ableger anlegen
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function MergeDialog({ colony }: { colony: Colony }) {
|
||||
const queryClient = useQueryClient();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [mergedColonyId, setMergedColonyId] = useState("");
|
||||
const { data: colonies } = useQuery({ queryKey: ["colonies"], queryFn: fetchColonies });
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: () => mergeColony(colony.id, { mergedColonyIds: [mergedColonyId] }),
|
||||
onSuccess: () => {
|
||||
invalidateColony(queryClient, colony.id);
|
||||
void queryClient.invalidateQueries({ queryKey: ["colonies"] });
|
||||
setOpen(false);
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger
|
||||
render={
|
||||
<Button variant="outline" disabled={colony.status !== "ACTIVE"}>
|
||||
Vereinigen
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Völker vereinigen</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={(event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
mutation.mutate();
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="merge-colony">Zu vereinigendes Volk</Label>
|
||||
<Select
|
||||
value={mergedColonyId}
|
||||
onValueChange={(value) => setMergedColonyId(value ?? "")}
|
||||
>
|
||||
<SelectTrigger id="merge-colony">
|
||||
<SelectValue placeholder="Volk wählen" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(colonies ?? [])
|
||||
.filter((c) => c.id !== colony.id && c.status === "ACTIVE")
|
||||
.map((c) => (
|
||||
<SelectItem key={c.id} value={c.id}>
|
||||
{c.code}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={!mergedColonyId || mutation.isPending}>
|
||||
Vereinigen
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function DissolveButton({ colony }: { colony: Colony }) {
|
||||
const queryClient = useQueryClient();
|
||||
const mutation = useMutation({
|
||||
mutationFn: () => dissolveColony(colony.id),
|
||||
onSuccess: () => invalidateColony(queryClient, colony.id),
|
||||
});
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={colony.status !== "ACTIVE" || mutation.isPending}
|
||||
onClick={() => mutation.mutate()}
|
||||
>
|
||||
Auflösen
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
export function ColonyActions({ colony }: { colony: Colony }) {
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<MoveDialog colony={colony} />
|
||||
<SplitDialog colony={colony} />
|
||||
<MergeDialog colony={colony} />
|
||||
<DissolveButton colony={colony} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
"use client";
|
||||
|
||||
import { FormEvent, useState } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { updateColony } from "@/lib/colonies/api";
|
||||
import { Colony } from "@/lib/colonies/types";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
|
||||
export function ColonyEditCard({ colony }: { colony: Colony }) {
|
||||
const queryClient = useQueryClient();
|
||||
const [strength, setStrength] = useState(colony.strength?.toString() ?? "");
|
||||
const [broodStatus, setBroodStatus] = useState(colony.broodStatus ?? "");
|
||||
const [feedStatus, setFeedStatus] = useState(colony.feedStatus ?? "");
|
||||
const [healthStatus, setHealthStatus] = useState(colony.healthStatus ?? "");
|
||||
const [notes, setNotes] = useState(colony.notes ?? "");
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: () =>
|
||||
updateColony(colony.id, {
|
||||
strength: strength ? Number(strength) : undefined,
|
||||
broodStatus: broodStatus || undefined,
|
||||
feedStatus: feedStatus || undefined,
|
||||
healthStatus: healthStatus || undefined,
|
||||
notes: notes || undefined,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ["colonies"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["colonies", colony.id] });
|
||||
},
|
||||
});
|
||||
|
||||
function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
updateMutation.mutate();
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="max-w-lg">
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle>{colony.code}</CardTitle>
|
||||
<Badge variant={colony.status === "ACTIVE" ? "default" : "secondary"}>
|
||||
{colony.status}
|
||||
</Badge>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="flex flex-col gap-4" onSubmit={handleSubmit}>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="colony-strength">Volksstärke</Label>
|
||||
<Input
|
||||
id="colony-strength"
|
||||
type="number"
|
||||
value={strength}
|
||||
onChange={(event) => setStrength(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="colony-brood">Brutstatus</Label>
|
||||
<Input
|
||||
id="colony-brood"
|
||||
value={broodStatus}
|
||||
onChange={(event) => setBroodStatus(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="colony-feed">Futterstatus</Label>
|
||||
<Input
|
||||
id="colony-feed"
|
||||
value={feedStatus}
|
||||
onChange={(event) => setFeedStatus(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="colony-health">Gesundheitsstatus</Label>
|
||||
<Input
|
||||
id="colony-health"
|
||||
value={healthStatus}
|
||||
onChange={(event) => setHealthStatus(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="colony-notes">Notizen</Label>
|
||||
<Textarea
|
||||
id="colony-notes"
|
||||
value={notes}
|
||||
onChange={(event) => setNotes(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" disabled={updateMutation.isPending}>
|
||||
{updateMutation.isPending ? "Speichert…" : "Speichern"}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { fetchColonyHistory } from "@/lib/colonies/api";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
|
||||
export function ColonyHistoryCard({ colonyId }: { colonyId: string }) {
|
||||
const { data: history, isLoading } = useQuery({
|
||||
queryKey: ["colonies", colonyId, "history"],
|
||||
queryFn: () => fetchColonyHistory(colonyId),
|
||||
});
|
||||
|
||||
if (isLoading || !history) {
|
||||
return <p className="text-sm text-muted-foreground">Historie lädt…</p>;
|
||||
}
|
||||
|
||||
const hasHistory =
|
||||
history.apiaryHistory.length > 0 ||
|
||||
history.lineageAsSource.length > 0 ||
|
||||
history.lineageAsResult.length > 0;
|
||||
|
||||
return (
|
||||
<Card className="max-w-lg">
|
||||
<CardHeader>
|
||||
<CardTitle>Historie</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3 text-sm">
|
||||
{!hasHistory ? (
|
||||
<p className="text-muted-foreground">Noch keine Historie vorhanden.</p>
|
||||
) : null}
|
||||
{history.apiaryHistory.map((entry) => (
|
||||
<p key={entry.id}>
|
||||
Standortwechsel am {new Date(entry.movedAt).toLocaleDateString("de-DE")}
|
||||
{entry.notes ? ` – ${entry.notes}` : ""}
|
||||
</p>
|
||||
))}
|
||||
{history.lineageAsResult.map((entry) => (
|
||||
<p key={entry.id}>
|
||||
{entry.type === "SPLIT" ? "Als Ableger entstanden" : "Anderes Volk eingegliedert"} am{" "}
|
||||
{new Date(entry.date).toLocaleDateString("de-DE")}
|
||||
</p>
|
||||
))}
|
||||
{history.lineageAsSource.map((entry) => (
|
||||
<p key={entry.id}>
|
||||
{entry.type === "SPLIT" ? "Ableger gebildet" : "Vereinigt in anderes Volk"} am{" "}
|
||||
{new Date(entry.date).toLocaleDateString("de-DE")}
|
||||
</p>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
"use client";
|
||||
|
||||
import { useParams } from "next/navigation";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { fetchColony } from "@/lib/colonies/api";
|
||||
import { ColonyEditCard } from "./colony-edit-card";
|
||||
import { ColonyActions } from "./colony-actions";
|
||||
import { ColonyHistoryCard } from "./colony-history";
|
||||
|
||||
export default function ColonyDetailPage() {
|
||||
const params = useParams<{ id: string }>();
|
||||
const { data: colony, isLoading, isError } = useQuery({
|
||||
queryKey: ["colonies", params.id],
|
||||
queryFn: () => fetchColony(params.id),
|
||||
});
|
||||
|
||||
if (isLoading) {
|
||||
return <p className="p-4 text-sm text-muted-foreground sm:p-6">Lädt…</p>;
|
||||
}
|
||||
if (isError || !colony) {
|
||||
return (
|
||||
<p role="alert" className="p-4 text-sm text-red-600 sm:p-6">
|
||||
Volk konnte nicht geladen werden.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex flex-col gap-4 p-4 sm:p-6">
|
||||
<ColonyEditCard key={colony.id} colony={colony} />
|
||||
<ColonyActions colony={colony} />
|
||||
<ColonyHistoryCard colonyId={colony.id} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
"use client";
|
||||
|
||||
import { FormEvent, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { createColony } from "@/lib/colonies/api";
|
||||
import { ColonyType } from "@/lib/colonies/types";
|
||||
import { fetchApiaries } from "@/lib/apiaries/api";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
|
||||
const COLONY_TYPES: ColonyType[] = [
|
||||
"PRODUCTION_COLONY",
|
||||
"NUCLEUS_COLONY",
|
||||
"YOUNG_COLONY",
|
||||
"CARETAKER_COLONY",
|
||||
"MATING_NUCLEUS",
|
||||
"RESERVE_COLONY",
|
||||
];
|
||||
|
||||
export default function NewColonyPage() {
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
const { data: apiaries } = useQuery({ queryKey: ["apiaries"], queryFn: fetchApiaries });
|
||||
|
||||
const [code, setCode] = useState("");
|
||||
const [apiaryId, setApiaryId] = useState("");
|
||||
const [colonyType, setColonyType] = useState<ColonyType>("PRODUCTION_COLONY");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: createColony,
|
||||
onSuccess: (colony) => {
|
||||
void queryClient.invalidateQueries({ queryKey: ["colonies"] });
|
||||
router.push(`/colonies/${colony.id}`);
|
||||
},
|
||||
onError: () => {
|
||||
setError("Volk konnte nicht angelegt werden.");
|
||||
},
|
||||
});
|
||||
|
||||
function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
if (!apiaryId) {
|
||||
setError("Bitte einen Bienenstand auswählen.");
|
||||
return;
|
||||
}
|
||||
mutation.mutate({ code, apiaryId, colonyType });
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="p-4 sm:p-6">
|
||||
<Card className="max-w-lg">
|
||||
<CardHeader>
|
||||
<CardTitle>Neues Volk</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="flex flex-col gap-4" onSubmit={handleSubmit}>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="colony-code">Code</Label>
|
||||
<Input
|
||||
id="colony-code"
|
||||
required
|
||||
value={code}
|
||||
onChange={(event) => setCode(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="colony-apiary">Bienenstand</Label>
|
||||
<Select value={apiaryId} onValueChange={(value) => setApiaryId(value ?? "")}>
|
||||
<SelectTrigger id="colony-apiary">
|
||||
<SelectValue placeholder="Bienenstand wählen" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(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="colony-type">Volkstyp</Label>
|
||||
<Select
|
||||
value={colonyType}
|
||||
onValueChange={(value) => setColonyType(value as ColonyType)}
|
||||
>
|
||||
<SelectTrigger id="colony-type">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{COLONY_TYPES.map((type) => (
|
||||
<SelectItem key={type} value={type}>
|
||||
{type}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{error ? (
|
||||
<p role="alert" className="text-sm text-red-600">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<Button type="submit" disabled={mutation.isPending}>
|
||||
{mutation.isPending ? "Wird angelegt…" : "Anlegen"}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import type { ReactElement } from "react";
|
||||
import ColoniesPage from "./page";
|
||||
import { fetchColonies } from "@/lib/colonies/api";
|
||||
|
||||
vi.mock("@/lib/colonies/api", () => ({
|
||||
fetchColonies: vi.fn(),
|
||||
}));
|
||||
|
||||
function renderWithClient(ui: ReactElement) {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>);
|
||||
}
|
||||
|
||||
describe("ColoniesPage", () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(fetchColonies).mockReset();
|
||||
});
|
||||
|
||||
it("renders the fetched colonies", async () => {
|
||||
vi.mocked(fetchColonies).mockResolvedValueOnce([
|
||||
{
|
||||
id: "1",
|
||||
code: "V-001",
|
||||
apiaryId: "apiary-1",
|
||||
hiveType: null,
|
||||
originText: null,
|
||||
colonyType: "PRODUCTION_COLONY",
|
||||
status: "ACTIVE",
|
||||
strength: null,
|
||||
broodStatus: null,
|
||||
feedStatus: null,
|
||||
healthStatus: null,
|
||||
notes: null,
|
||||
currentQueenId: null,
|
||||
createdAt: "",
|
||||
updatedAt: "",
|
||||
deactivatedAt: null,
|
||||
},
|
||||
]);
|
||||
|
||||
renderWithClient(<ColoniesPage />);
|
||||
|
||||
expect(await screen.findByText("V-001")).toBeInTheDocument();
|
||||
expect(screen.getByText("PRODUCTION_COLONY")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { fetchColonies } from "@/lib/colonies/api";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
|
||||
export default function ColoniesPage() {
|
||||
const { data: colonies, isLoading, isError } = useQuery({
|
||||
queryKey: ["colonies"],
|
||||
queryFn: fetchColonies,
|
||||
});
|
||||
|
||||
return (
|
||||
<main className="flex flex-col gap-4 p-4 sm:p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold">Völker</h1>
|
||||
<Button nativeButton={false} render={<Link href="/colonies/new" />}>
|
||||
+ Neues Volk
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isLoading ? <p className="text-sm text-muted-foreground">Lädt…</p> : null}
|
||||
{isError ? (
|
||||
<p role="alert" className="text-sm text-red-600">
|
||||
Völker konnten nicht geladen werden.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{colonies ? (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Code</TableHead>
|
||||
<TableHead>Typ</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{colonies.map((colony) => (
|
||||
<TableRow key={colony.id}>
|
||||
<TableCell>
|
||||
<Link className="underline" href={`/colonies/${colony.id}`}>
|
||||
{colony.code}
|
||||
</Link>
|
||||
</TableCell>
|
||||
<TableCell>{colony.colonyType}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={colony.status === "ACTIVE" ? "default" : "secondary"}>
|
||||
{colony.status}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
) : null}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -28,6 +28,9 @@ export default function AppLayout({ children }: { children: ReactNode }) {
|
||||
<Link className="text-sm text-muted-foreground hover:text-foreground" href="/apiaries">
|
||||
Bienenstände
|
||||
</Link>
|
||||
<Link className="text-sm text-muted-foreground hover:text-foreground" href="/colonies">
|
||||
Völker
|
||||
</Link>
|
||||
{user.role === "ADMIN" ? (
|
||||
<Link
|
||||
className="text-sm text-muted-foreground hover:text-foreground"
|
||||
|
||||
@@ -17,11 +17,18 @@ export async function loginRequest(email: string, password: string): Promise<Acc
|
||||
return response.json() as Promise<AccessTokenResponse>;
|
||||
}
|
||||
|
||||
export async function refreshRequest(signal?: AbortSignal): Promise<AccessTokenResponse | null> {
|
||||
// The refresh token is single-use and rotates on every call. If two callers
|
||||
// (e.g. React StrictMode's dev double-invoke, or two components hitting a 401
|
||||
// at once) both call refresh at the same time, the second one always fails
|
||||
// because the first already rotated the cookie. Deduplicating into one
|
||||
// shared in-flight request makes concurrent callers share the same result
|
||||
// instead of racing each other.
|
||||
let inFlightRefresh: Promise<AccessTokenResponse | null> | null = null;
|
||||
|
||||
async function performRefresh(): Promise<AccessTokenResponse | null> {
|
||||
const response = await fetch(`${API_URL}/auth/refresh`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
return null;
|
||||
@@ -29,6 +36,15 @@ export async function refreshRequest(signal?: AbortSignal): Promise<AccessTokenR
|
||||
return response.json() as Promise<AccessTokenResponse>;
|
||||
}
|
||||
|
||||
export function refreshRequest(): Promise<AccessTokenResponse | null> {
|
||||
if (!inFlightRefresh) {
|
||||
inFlightRefresh = performRefresh().finally(() => {
|
||||
inFlightRefresh = null;
|
||||
});
|
||||
}
|
||||
return inFlightRefresh;
|
||||
}
|
||||
|
||||
export async function logoutRequest(): Promise<void> {
|
||||
await fetch(`${API_URL}/auth/logout`, { method: 'POST', credentials: 'include' });
|
||||
}
|
||||
@@ -34,28 +34,16 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
refreshRequest(controller.signal)
|
||||
refreshRequest()
|
||||
.then((result) => {
|
||||
if (!result) {
|
||||
return;
|
||||
}
|
||||
setUser(applyAccessToken(result.accessToken));
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (error instanceof DOMException && error.name === "AbortError") {
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setIsLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
controller.abort();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const login = useCallback(async (email: string, password: string) => {
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { apiFetch } from "@/lib/auth/api-client";
|
||||
import {
|
||||
Colony,
|
||||
ColonyHistory,
|
||||
CreateColonyInput,
|
||||
MergeColonyInput,
|
||||
MoveColonyInput,
|
||||
SplitColonyInput,
|
||||
UpdateColonyInput,
|
||||
} from "./types";
|
||||
|
||||
export function fetchColonies(): Promise<Colony[]> {
|
||||
return apiFetch<Colony[]>("/colonies");
|
||||
}
|
||||
|
||||
export function fetchColony(id: string): Promise<Colony> {
|
||||
return apiFetch<Colony>(`/colonies/${id}`);
|
||||
}
|
||||
|
||||
export function fetchColonyHistory(id: string): Promise<ColonyHistory> {
|
||||
return apiFetch<ColonyHistory>(`/colonies/${id}/history`);
|
||||
}
|
||||
|
||||
export function createColony(input: CreateColonyInput): Promise<Colony> {
|
||||
return apiFetch<Colony>("/colonies", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export function updateColony(id: string, input: UpdateColonyInput): Promise<Colony> {
|
||||
return apiFetch<Colony>(`/colonies/${id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export function moveColony(id: string, input: MoveColonyInput): Promise<Colony> {
|
||||
return apiFetch<Colony>(`/colonies/${id}/move`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export function splitColony(id: string, input: SplitColonyInput): Promise<Colony> {
|
||||
return apiFetch<Colony>(`/colonies/${id}/split`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export function mergeColony(id: string, input: MergeColonyInput): Promise<Colony> {
|
||||
return apiFetch<Colony>(`/colonies/${id}/merge`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export function dissolveColony(id: string): Promise<Colony> {
|
||||
return apiFetch<Colony>(`/colonies/${id}/dissolve`, { method: "POST" });
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
export type ColonyType =
|
||||
| "PRODUCTION_COLONY"
|
||||
| "NUCLEUS_COLONY"
|
||||
| "YOUNG_COLONY"
|
||||
| "CARETAKER_COLONY"
|
||||
| "MATING_NUCLEUS"
|
||||
| "RESERVE_COLONY";
|
||||
|
||||
export type ColonyStatus =
|
||||
| "ACTIVE"
|
||||
| "WEAK"
|
||||
| "CONSPICUOUS"
|
||||
| "QUEENLESS"
|
||||
| "DISSOLVED"
|
||||
| "SOLD"
|
||||
| "DECEASED"
|
||||
| "MERGED";
|
||||
|
||||
export interface Colony {
|
||||
id: string;
|
||||
code: string;
|
||||
apiaryId: string;
|
||||
hiveType: string | null;
|
||||
originText: string | null;
|
||||
colonyType: ColonyType;
|
||||
status: ColonyStatus;
|
||||
strength: number | null;
|
||||
broodStatus: string | null;
|
||||
feedStatus: string | null;
|
||||
healthStatus: string | null;
|
||||
notes: string | null;
|
||||
currentQueenId: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
deactivatedAt: string | null;
|
||||
}
|
||||
|
||||
export interface CreateColonyInput {
|
||||
code: string;
|
||||
apiaryId: string;
|
||||
colonyType: ColonyType;
|
||||
hiveType?: string;
|
||||
originText?: string;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export interface UpdateColonyInput {
|
||||
hiveType?: string;
|
||||
originText?: string;
|
||||
colonyType?: ColonyType;
|
||||
strength?: number;
|
||||
broodStatus?: string;
|
||||
feedStatus?: string;
|
||||
healthStatus?: string;
|
||||
notes?: string;
|
||||
status?: ColonyStatus;
|
||||
}
|
||||
|
||||
export interface MoveColonyInput {
|
||||
apiaryId: string;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export interface SplitColonyInput {
|
||||
code: string;
|
||||
colonyType: ColonyType;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export interface MergeColonyInput {
|
||||
mergedColonyIds: string[];
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export interface ColonyHistory {
|
||||
apiaryHistory: {
|
||||
id: string;
|
||||
apiaryId: string;
|
||||
movedAt: string;
|
||||
notes: string | null;
|
||||
}[];
|
||||
queenHistory: {
|
||||
id: string;
|
||||
queenId: string;
|
||||
startDate: string;
|
||||
endDate: string | null;
|
||||
}[];
|
||||
lineageAsSource: {
|
||||
id: string;
|
||||
type: "SPLIT" | "MERGE";
|
||||
toColonyId: string;
|
||||
date: string;
|
||||
}[];
|
||||
lineageAsResult: {
|
||||
id: string;
|
||||
type: "SPLIT" | "MERGE";
|
||||
fromColonyId: string;
|
||||
date: string;
|
||||
}[];
|
||||
}
|
||||
@@ -35,7 +35,7 @@ Abgeleitet aus [`docs/lastenheft.md`](docs/lastenheft.md) Abschnitt 26. Reihenfo
|
||||
- Endpunkte: `GET/POST /api/v1/colonies`, `GET/PATCH /api/v1/colonies/:id`, `POST /api/v1/colonies/:id/move`, `POST /api/v1/colonies/:id/split`, `POST /api/v1/colonies/:id/merge`, `POST /api/v1/colonies/:id/dissolve`, `GET /api/v1/colonies/:id/history`
|
||||
- Frontend: `/colonies`, `/colonies/[id]`, `/colonies/new`
|
||||
- [x] Backend-Modul fertig, getestet, grün, committet
|
||||
- [ ] Frontend-Views fertig, getestet, grün, committet
|
||||
- [x] Frontend-Views fertig, getestet, grün, committet
|
||||
|
||||
### 4. Königinnen
|
||||
|
||||
|
||||
Reference in new issue
Block a user