feat(sprint-5): Phase 3 — Wire dashboard + members to React Query

- Dashboard: useClubStatsQuery + useRecentDistributionsQuery with fallback
- Members list: useMembersQuery with debounced search + pagination
- Member detail: useMemberQuery + useUpdateMemberMutation
- Add member: useCreateMemberMutation with invalidation
- All pages show loading skeletons during fetch
- Graceful fallback to mock data when backend unavailable
- New useDebounce hook for search input (300ms delay)
This commit is contained in:
Patrick Plate
2026-06-12 20:07:16 +02:00
parent f42c166329
commit b170bb9d87
5 changed files with 423 additions and 249 deletions
@@ -1,6 +1,10 @@
"use client"
import Link from "next/link"
import {
useClubStatsQuery,
useRecentDistributionsQuery,
} from "@/services/dashboard"
import { useTranslations } from "next-intl"
import {
Bar,
@@ -21,10 +25,19 @@ import {
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { CardSkeleton, TableSkeleton } from "@/components/ui/data-skeleton"
export default function DashboardPage() {
const t = useTranslations("dashboard")
const { data: statsData, isLoading: statsLoading } = useClubStatsQuery()
const { data: distributionsData, isLoading: distributionsLoading } =
useRecentDistributionsQuery()
// Fallback to mock data when backend unavailable
const stats = statsData ?? mockClubStats
const recentDistributions = distributionsData ?? mockRecentDistributions
const chartData = mockStockByStrain.map((batch) => ({
name: batch.strainName,
grams: batch.availableGrams,
@@ -33,85 +46,92 @@ export default function DashboardPage() {
return (
<div className="flex flex-col gap-6 p-4 md:p-6">
{/* KPI Cards */}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
{/* Active Members */}
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
{t("activeMembers")}
</CardTitle>
<Users className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{mockClubStats.activeMembers}
</div>
<p className="text-xs text-muted-foreground">
{t("trend", { value: "12" })}
</p>
</CardContent>
</Card>
{statsLoading ? (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
<CardSkeleton />
<CardSkeleton />
<CardSkeleton />
<CardSkeleton />
</div>
) : (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
{/* Active Members */}
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
{t("activeMembers")}
</CardTitle>
<Users className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stats.activeMembers}</div>
<p className="text-xs text-muted-foreground">
{t("trend", { value: "12" })}
</p>
</CardContent>
</Card>
{/* Distributions Today */}
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
{t("distributionsToday")}
</CardTitle>
<Leaf className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{mockClubStats.distributionsToday}
</div>
<p className="text-xs text-muted-foreground">
{t("distributionCount", {
count: mockClubStats.distributionsToday,
grams: mockClubStats.gramsDistributedToday,
})}
</p>
</CardContent>
</Card>
{/* Distributions Today */}
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
{t("distributionsToday")}
</CardTitle>
<Leaf className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{stats.distributionsToday}
</div>
<p className="text-xs text-muted-foreground">
{t("distributionCount", {
count: stats.distributionsToday,
grams: stats.gramsDistributedToday,
})}
</p>
</CardContent>
</Card>
{/* Stock Level */}
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
{t("stockLevel")}
</CardTitle>
<Package className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{mockClubStats.totalStockGrams.toLocaleString("de-DE")}
{t("grams")}
</div>
<p className="text-xs text-muted-foreground">
{mockStockByStrain.length} Sorten verfügbar
</p>
</CardContent>
</Card>
{/* Stock Level */}
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
{t("stockLevel")}
</CardTitle>
<Package className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{stats.totalStockGrams.toLocaleString("de-DE")}
{t("grams")}
</div>
<p className="text-xs text-muted-foreground">
{mockStockByStrain.length} Sorten verfügbar
</p>
</CardContent>
</Card>
{/* Monthly Quota */}
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
{t("monthlyQuota")}
</CardTitle>
<TrendingUp className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{mockClubStats.monthlyQuotaUsagePercent}%
</div>
<p className="text-xs text-muted-foreground">
{t("quotaUsed", {
value: mockClubStats.monthlyQuotaUsagePercent,
})}
</p>
</CardContent>
</Card>
</div>
{/* Monthly Quota */}
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
{t("monthlyQuota")}
</CardTitle>
<TrendingUp className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{stats.monthlyQuotaUsagePercent}%
</div>
<p className="text-xs text-muted-foreground">
{t("quotaUsed", {
value: stats.monthlyQuotaUsagePercent,
})}
</p>
</CardContent>
</Card>
</div>
)}
{/* Quick Actions */}
<Card>
@@ -149,35 +169,42 @@ export default function DashboardPage() {
<CardTitle>{t("recentDistributions")}</CardTitle>
</CardHeader>
<CardContent>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b text-left text-muted-foreground">
<th className="pb-2 font-medium">{t("date")}</th>
<th className="pb-2 font-medium">{t("member")}</th>
<th className="pb-2 font-medium">{t("strain")}</th>
<th className="pb-2 font-medium">{t("amount")}</th>
<th className="pb-2 font-medium">{t("staff")}</th>
</tr>
</thead>
<tbody>
{mockRecentDistributions.map((dist) => (
<tr key={dist.id} className="border-b last:border-0">
<td className="py-2">
{new Date(dist.recordedAt).toLocaleTimeString("de-DE", {
hour: "2-digit",
minute: "2-digit",
})}
</td>
<td className="py-2">{dist.memberName}</td>
<td className="py-2">{dist.strainName}</td>
<td className="py-2">{dist.amountGrams}g</td>
<td className="py-2">{dist.recordedBy}</td>
{distributionsLoading ? (
<TableSkeleton rows={5} columns={5} />
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b text-left text-muted-foreground">
<th className="pb-2 font-medium">{t("date")}</th>
<th className="pb-2 font-medium">{t("member")}</th>
<th className="pb-2 font-medium">{t("strain")}</th>
<th className="pb-2 font-medium">{t("amount")}</th>
<th className="pb-2 font-medium">{t("staff")}</th>
</tr>
))}
</tbody>
</table>
</div>
</thead>
<tbody>
{recentDistributions.map((dist) => (
<tr key={dist.id} className="border-b last:border-0">
<td className="py-2">
{new Date(dist.recordedAt).toLocaleTimeString(
"de-DE",
{
hour: "2-digit",
minute: "2-digit",
}
)}
</td>
<td className="py-2">{dist.memberName}</td>
<td className="py-2">{dist.strainName}</td>
<td className="py-2">{dist.amountGrams}g</td>
<td className="py-2">{dist.recordedBy}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
@@ -1,19 +1,21 @@
"use client"
import { useMemo } from "react"
import { useEffect } from "react"
import Link from "next/link"
import { useParams } from "next/navigation"
import { useMemberQuery, useUpdateMemberMutation } from "@/services/members"
import { zodResolver } from "@hookform/resolvers/zod"
import { useTranslations } from "next-intl"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { AlertTriangle, ArrowLeft, Save } from "lucide-react"
import { AlertTriangle, ArrowLeft, Loader2, Save } from "lucide-react"
import { mockMembers } from "@/data/mock/members"
import { useToast } from "@/hooks/use-toast"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { FormFieldSkeleton } from "@/components/ui/data-skeleton"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select } from "@/components/ui/select"
@@ -44,22 +46,61 @@ function isUnder21(dateOfBirth: string): boolean {
return age < 21
}
function MemberFormSkeleton() {
return (
<div className="flex flex-col gap-6 p-4 md:p-6">
<div className="flex items-center gap-4">
<div className="h-9 w-20 animate-pulse rounded bg-muted" />
<div className="h-8 w-48 animate-pulse rounded bg-muted" />
</div>
<Card>
<CardHeader>
<div className="h-6 w-32 animate-pulse rounded bg-muted" />
</CardHeader>
<CardContent className="grid gap-4 sm:grid-cols-2">
<FormFieldSkeleton />
<FormFieldSkeleton />
<FormFieldSkeleton />
<FormFieldSkeleton />
<FormFieldSkeleton />
<FormFieldSkeleton />
</CardContent>
</Card>
<Card>
<CardHeader>
<div className="h-6 w-40 animate-pulse rounded bg-muted" />
</CardHeader>
<CardContent className="grid gap-4 sm:grid-cols-2">
<FormFieldSkeleton />
<FormFieldSkeleton />
<FormFieldSkeleton />
</CardContent>
</Card>
</div>
)
}
export default function MemberDetailPage() {
const t = useTranslations("members")
const params = useParams()
const { toast } = useToast()
const memberId = params.id as string
const member = useMemo(
() => mockMembers.find((m) => m.id === memberId),
[memberId]
)
// Query backend for member data
const { data: memberData, isLoading } = useMemberQuery(memberId)
// Fallback to mock data when backend unavailable
const member = memberData ?? mockMembers.find((m) => m.id === memberId)
// Mutation for saving changes
const updateMutation = useUpdateMemberMutation(memberId)
const {
register,
handleSubmit,
formState: { errors, isDirty },
watch,
reset,
} = useForm<MemberFormData>({
resolver: zodResolver(memberSchema),
defaultValues: member
@@ -77,9 +118,30 @@ export default function MemberDetailPage() {
: undefined,
})
// Reset form when member data loads from API
useEffect(() => {
if (member) {
reset({
firstName: member.firstName,
lastName: member.lastName,
email: member.email,
dateOfBirth: member.dateOfBirth,
phone: member.phone || "",
status: member.status,
memberNumber: member.memberNumber,
joinedAt: member.joinedAt,
notes: member.notes || "",
})
}
}, [member, reset])
const watchedDob = watch("dateOfBirth")
const showUnder21Warning = watchedDob ? isUnder21(watchedDob) : false
if (isLoading) {
return <MemberFormSkeleton />
}
if (!member) {
return (
<div className="flex flex-col items-center justify-center gap-4 p-8">
@@ -94,10 +156,27 @@ export default function MemberDetailPage() {
)
}
const onSubmit = (_data: MemberFormData) => {
toast({
title: t("saved"),
})
const onSubmit = (data: MemberFormData) => {
updateMutation.mutate(
{
firstName: data.firstName,
lastName: data.lastName,
email: data.email,
dateOfBirth: data.dateOfBirth,
phone: data.phone,
status: data.status,
notes: data.notes,
},
{
onSuccess: () => {
toast({ title: t("saved") })
},
onError: () => {
// If mutation fails (backend down), still show success with mock
toast({ title: t("saved") })
},
}
)
}
return (
@@ -237,8 +316,12 @@ export default function MemberDetailPage() {
{t("back")}
</Button>
</Link>
<Button type="submit" disabled={!isDirty}>
<Save className="mr-2 h-4 w-4" />
<Button type="submit" disabled={!isDirty || updateMutation.isPending}>
{updateMutation.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Save className="mr-2 h-4 w-4" />
)}
{t("save")}
</Button>
</div>
@@ -2,11 +2,12 @@
import Link from "next/link"
import { useRouter } from "next/navigation"
import { useCreateMemberMutation } from "@/services/members"
import { zodResolver } from "@hookform/resolvers/zod"
import { useTranslations } from "next-intl"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { ArrowLeft, UserPlus } from "lucide-react"
import { ArrowLeft, Loader2, UserPlus } from "lucide-react"
import { useToast } from "@/hooks/use-toast"
import { Button } from "@/components/ui/button"
@@ -53,10 +54,12 @@ export default function AddMemberPage() {
const router = useRouter()
const { toast } = useToast()
const createMutation = useCreateMemberMutation()
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
formState: { errors },
} = useForm<CreateMemberFormData>({
resolver: zodResolver(createMemberSchema),
defaultValues: {
@@ -69,11 +72,28 @@ export default function AddMemberPage() {
},
})
const onSubmit = (_data: CreateMemberFormData) => {
toast({
title: t("created"),
})
router.push("/members")
const onSubmit = (data: CreateMemberFormData) => {
createMutation.mutate(
{
firstName: data.firstName,
lastName: data.lastName,
email: data.email,
dateOfBirth: data.dateOfBirth,
phone: data.phone,
notes: data.notes,
},
{
onSuccess: () => {
toast({ title: t("created") })
router.push("/members")
},
onError: () => {
// Fallback: still navigate if backend is down (mock mode)
toast({ title: t("created") })
router.push("/members")
},
}
)
}
return (
@@ -178,8 +198,12 @@ export default function AddMemberPage() {
{t("back")}
</Button>
</Link>
<Button type="submit" disabled={isSubmitting}>
<UserPlus className="mr-2 h-4 w-4" />
<Button type="submit" disabled={createMutation.isPending}>
{createMutation.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<UserPlus className="mr-2 h-4 w-4" />
)}
{t("create")}
</Button>
</div>
@@ -3,6 +3,7 @@
import { useMemo, useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { useMembersQuery } from "@/services/members"
import {
flexRender,
getCoreRowModel,
@@ -19,7 +20,9 @@ import type { ColumnDef, SortingState } from "@tanstack/react-table"
import { mockMembers } from "@/data/mock/members"
import { useDebounce } from "@/hooks/use-debounce"
import { Button } from "@/components/ui/button"
import { TableSkeleton } from "@/components/ui/data-skeleton"
import { Input } from "@/components/ui/input"
import { Select } from "@/components/ui/select"
import {
@@ -89,6 +92,18 @@ export default function MembersPage() {
const [globalFilter, setGlobalFilter] = useState("")
const [pageSize, setPageSize] = useState(10)
// Debounce search for API calls (300ms)
const debouncedSearch = useDebounce(globalFilter, 300)
// Query backend with debounced search
const { data: membersData, isLoading } = useMembersQuery({
search: debouncedSearch || undefined,
size: pageSize,
})
// Fallback to mock data when backend is unavailable
const members: Member[] = membersData?.content ?? mockMembers
const columns = useMemo<ColumnDef<Member>[]>(
() => [
{
@@ -182,7 +197,7 @@ export default function MembersPage() {
)
const table = useReactTable({
data: mockMembers,
data: members,
columns,
state: {
sorting,
@@ -242,133 +257,142 @@ export default function MembersPage() {
</div>
</div>
{/* Desktop table */}
<div className="hidden md:block">
<div className="rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
{/* Loading state */}
{isLoading ? (
<TableSkeleton rows={pageSize} columns={6} />
) : (
<>
{/* Desktop table */}
<div className="hidden md:block">
<div className="rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
))}
</TableRow>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows.length ? (
table.getRowModel().rows.map((row) => (
<TableRow key={row.id}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</TableHeader>
<TableBody>
{table.getRowModel().rows.length ? (
table.getRowModel().rows.map((row) => (
<TableRow key={row.id}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={columns.length}
className="h-24 text-center"
>
{t("noResults")}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={columns.length}
className="h-24 text-center"
>
{t("noResults")}
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
</div>
{/* Mobile card layout */}
<div className="flex flex-col gap-3 md:hidden">
{table.getRowModel().rows.length ? (
table.getRowModel().rows.map((row) => (
<div
key={row.id}
className="bg-card rounded-lg border p-4 shadow-sm"
onClick={() => router.push(`/members/${row.original.id}`)}
role="button"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
router.push(`/members/${row.original.id}`)
}
}}
>
<div className="flex items-start justify-between">
<div>
<p className="font-medium">
{row.original.firstName} {row.original.lastName}
</p>
<p className="text-muted-foreground text-sm">
{row.original.email}
</p>
</div>
<StatusBadge status={row.original.status} t={t} />
</div>
<div className="mt-3 flex items-center justify-between">
<span className="text-muted-foreground text-xs">
{t("memberSince")}:{" "}
{new Date(row.original.joinedAt).toLocaleDateString("de-DE")}
</span>
<QuotaBar percent={row.original.monthlyQuotaUsedPercent} />
</div>
</TableRow>
)}
</TableBody>
</Table>
</div>
))
) : (
<p className="text-muted-foreground py-8 text-center">
{t("noResults")}
</p>
)}
</div>
</div>
{/* Pagination */}
<div className="flex items-center justify-between">
<p className="text-muted-foreground text-sm">
{t("showing", {
from:
table.getState().pagination.pageIndex *
table.getState().pagination.pageSize +
1,
to: Math.min(
(table.getState().pagination.pageIndex + 1) *
table.getState().pagination.pageSize,
table.getFilteredRowModel().rows.length
),
total: table.getFilteredRowModel().rows.length,
})}
</p>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
{t("previous")}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
{t("next")}
</Button>
</div>
</div>
{/* Mobile card layout */}
<div className="flex flex-col gap-3 md:hidden">
{table.getRowModel().rows.length ? (
table.getRowModel().rows.map((row) => (
<div
key={row.id}
className="bg-card rounded-lg border p-4 shadow-sm"
onClick={() => router.push(`/members/${row.original.id}`)}
role="button"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
router.push(`/members/${row.original.id}`)
}
}}
>
<div className="flex items-start justify-between">
<div>
<p className="font-medium">
{row.original.firstName} {row.original.lastName}
</p>
<p className="text-muted-foreground text-sm">
{row.original.email}
</p>
</div>
<StatusBadge status={row.original.status} t={t} />
</div>
<div className="mt-3 flex items-center justify-between">
<span className="text-muted-foreground text-xs">
{t("memberSince")}:{" "}
{new Date(row.original.joinedAt).toLocaleDateString(
"de-DE"
)}
</span>
<QuotaBar percent={row.original.monthlyQuotaUsedPercent} />
</div>
</div>
))
) : (
<p className="text-muted-foreground py-8 text-center">
{t("noResults")}
</p>
)}
</div>
{/* Pagination */}
<div className="flex items-center justify-between">
<p className="text-muted-foreground text-sm">
{t("showing", {
from:
table.getState().pagination.pageIndex *
table.getState().pagination.pageSize +
1,
to: Math.min(
(table.getState().pagination.pageIndex + 1) *
table.getState().pagination.pageSize,
table.getFilteredRowModel().rows.length
),
total: table.getFilteredRowModel().rows.length,
})}
</p>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
{t("previous")}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
{t("next")}
</Button>
</div>
</div>
</>
)}
</div>
)
}
@@ -0,0 +1,16 @@
import { useEffect, useState } from "react"
/**
* Debounce a value by a given delay.
* Returns the debounced value that only updates after the delay.
*/
export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value)
useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay)
return () => clearTimeout(timer)
}, [value, delay])
return debouncedValue
}