Files
website-secure/app/customers/[id]/page.tsx
T
pm 9c14a19a87
DevSecOps Enterprise Pipeline / security-gate-and-deploy (push) Failing after 41s
chore: upload parte 1 - logica
2026-06-01 15:35:53 +01:00

678 lines
27 KiB
TypeScript

"use client";
import { useState } from "react";
import { useParams, useRouter } from "next/navigation";
import useSWR from "swr";
import Link from "next/link";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
ArrowLeft,
Plus,
Pencil,
Trash2,
Mail,
Phone,
MapPin,
User,
FileText,
Euro,
ExternalLink,
Package,
BarChart3,
} from "lucide-react";
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer,
Cell,
} from "recharts";
import { Progress } from "@/components/ui/progress";
import { useTableSort } from "@/hooks/use-table-sort";
import { SortableTableHead } from "@/components/sortable-table-head";
import { CustomerDialog } from "@/components/customer-dialog";
import { toast } from "sonner";
import { formatCurrency } from "@/lib/format";
import type { Customer, PurchaseOrder } from "@/lib/types";
const fetcher = (url: string) => fetch(url).then((r) => r.json());
const statusConfig: Record<string, { label: string; variant: "default" | "secondary" | "destructive" | "outline" }> = {
draft: { label: "Draft", variant: "secondary" },
confirmed: { label: "Confirmed", variant: "default" },
in_production: { label: "In Production", variant: "outline" },
shipped: { label: "Shipped", variant: "default" },
completed: { label: "Completed", variant: "default" },
cancelled: { label: "Cancelled", variant: "destructive" },
};
export default function CustomerDetailPage() {
const params = useParams();
const router = useRouter();
const customerId = params.id as string;
const [editOpen, setEditOpen] = useState(false);
const [deleteOrderTarget, setDeleteOrderTarget] = useState<PurchaseOrder | null>(null);
const [statsPeriod, setStatsPeriod] = useState<"week" | "month" | "year">("month");
const { data: customer, mutate: mutateCustomer } = useSWR<Customer>(
`/api/customers/${customerId}`,
fetcher
);
const { data: orders = [], mutate: mutateOrders } = useSWR<PurchaseOrder[]>(
`/api/orders?customerId=${customerId}`,
fetcher
);
const { sorted: sortedOrders, sort: orderSort, toggleSort: toggleOrderSort } = useTableSort(orders);
interface OnOrderItem {
product_id: number;
product_name: string;
sku: string;
total_ordered: number;
total_shipped: number;
on_order: number;
}
interface ProducedItem {
product_id: number;
product_name: string;
sku: string;
total_produced: number;
}
interface TimelineItem {
bucket: string;
product_name: string;
sku: string;
quantity: number;
}
interface StatsData {
onOrder: OnOrderItem[];
produced: ProducedItem[];
producedTimeline: TimelineItem[];
}
const { data: statsData } = useSWR<StatsData>(
`/api/customers/${customerId}/stats?period=${statsPeriod}`,
fetcher
);
async function handleDeleteOrder() {
if (!deleteOrderTarget) return;
try {
const res = await fetch(`/api/orders/${deleteOrderTarget.id}`, {
method: "DELETE",
});
if (!res.ok) throw new Error("Failed to delete");
toast.success("Purchase order deleted");
mutateOrders();
} catch {
toast.error("Failed to delete order");
} finally {
setDeleteOrderTarget(null);
}
}
if (!customer) {
return (
<div className="flex items-center justify-center p-12">
<p className="text-muted-foreground">Loading customer...</p>
</div>
);
}
const totalValue = orders.reduce(
(sum, o) => sum + (o.status !== "cancelled" ? Number(o.total_value || 0) : 0),
0
);
const activeOrders = orders.filter(
(o) => !["completed", "cancelled"].includes(o.status)
).length;
return (
<div className="flex flex-col gap-6 p-6">
{/* Header */}
<div className="flex items-start justify-between">
<div className="flex items-center gap-4">
<Button variant="ghost" size="icon" onClick={() => router.push("/customers")}>
<ArrowLeft className="h-4 w-4" />
</Button>
<div>
<div className="flex items-center gap-3">
<h1 className="text-2xl font-bold tracking-tight text-foreground">
{customer.name}
</h1>
<Badge variant="outline" className="font-mono text-xs">
{customer.code}
</Badge>
</div>
<p className="text-sm text-muted-foreground">
Customer since{" "}
{new Date(customer.created_at).toLocaleDateString()}
</p>
</div>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={() => setEditOpen(true)}>
<Pencil className="mr-2 h-3.5 w-3.5" />
Edit
</Button>
<Button size="sm" asChild>
<Link href={`/customers/${customerId}/orders/new`}>
<Plus className="mr-2 h-3.5 w-3.5" />
New Purchase Order
</Link>
</Button>
</div>
</div>
{/* Customer Info + Stats */}
<div className="grid grid-cols-1 gap-4 md:grid-cols-4">
<Card className="md:col-span-2">
<CardHeader>
<CardTitle className="text-sm font-medium text-muted-foreground">
Contact Information
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3">
{customer.contact_person && (
<div className="flex items-center gap-2 text-sm">
<User className="h-4 w-4 text-muted-foreground" />
<span>{customer.contact_person}</span>
</div>
)}
{customer.email && (
<div className="flex items-center gap-2 text-sm">
<Mail className="h-4 w-4 text-muted-foreground" />
<a
href={`mailto:${customer.email}`}
className="text-primary hover:underline"
>
{customer.email}
</a>
</div>
)}
{customer.phone && (
<div className="flex items-center gap-2 text-sm">
<Phone className="h-4 w-4 text-muted-foreground" />
<span>{customer.phone}</span>
</div>
)}
{customer.address && (
<div className="flex items-start gap-2 text-sm">
<MapPin className="mt-0.5 h-4 w-4 text-muted-foreground" />
<span className="whitespace-pre-wrap">{customer.address}</span>
</div>
)}
{customer.notes && (
<div className="mt-2 rounded-md bg-muted p-3 text-sm text-muted-foreground">
{customer.notes}
</div>
)}
{!customer.contact_person &&
!customer.email &&
!customer.phone &&
!customer.address && (
<p className="text-sm text-muted-foreground italic">
No contact information added yet.
</p>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
Active Orders
</CardTitle>
<FileText className="h-4 w-4 text-primary" />
</CardHeader>
<CardContent>
<p className="text-2xl font-bold">{activeOrders}</p>
<p className="text-xs text-muted-foreground">
of {orders.length} total
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
Total Revenue
</CardTitle>
<Euro className="h-4 w-4 text-accent" />
</CardHeader>
<CardContent>
<p className="text-2xl font-bold">
{formatCurrency(totalValue)}
</p>
<p className="text-xs text-muted-foreground">
excl. cancelled orders
</p>
</CardContent>
</Card>
</div>
{/* On Order + Production Stats */}
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
{/* On Order by Product */}
<Card>
<CardHeader className="flex flex-row items-center gap-2 pb-3">
<Package className="h-4 w-4 text-primary" />
<div>
<CardTitle className="text-sm font-medium">Units On Order</CardTitle>
<CardDescription className="text-xs">
Pending quantities by product across active orders
</CardDescription>
</div>
</CardHeader>
<CardContent className="p-0">
{statsData?.onOrder && statsData.onOrder.length > 0 ? (
<Table>
<TableHeader>
<TableRow>
<TableHead>Product</TableHead>
<TableHead className="text-right">Ordered</TableHead>
<TableHead className="text-right">Shipped</TableHead>
<TableHead className="text-right">Pending</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{statsData.onOrder.map((item) => (
<TableRow key={item.product_id}>
<TableCell>
<div className="flex flex-col">
<span className="text-sm font-medium">{item.product_name}</span>
<span className="font-mono text-xs text-muted-foreground">{item.sku}</span>
</div>
</TableCell>
<TableCell className="text-right font-mono text-sm">
{Number(item.total_ordered).toLocaleString()}
</TableCell>
<TableCell className="text-right font-mono text-sm text-muted-foreground">
{Number(item.total_shipped).toLocaleString()}
</TableCell>
<TableCell className="text-right">
<Badge variant="outline" className="font-mono text-xs font-bold text-primary border-primary/30">
{Number(item.on_order).toLocaleString()}
</Badge>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
) : (
<div className="flex items-center justify-center py-8 text-sm text-muted-foreground">
No pending orders
</div>
)}
</CardContent>
</Card>
{/* Produced / Shipped by Product */}
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-3">
<div className="flex items-center gap-2">
<BarChart3 className="h-4 w-4 text-accent" />
<div>
<CardTitle className="text-sm font-medium">Units Produced</CardTitle>
<CardDescription className="text-xs">
Shipped quantities by product
</CardDescription>
</div>
</div>
<Select
value={statsPeriod}
onValueChange={(val) => setStatsPeriod(val as "week" | "month" | "year")}
>
<SelectTrigger className="w-[110px] h-8 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="week">Last 7 days</SelectItem>
<SelectItem value="month">Last 30 days</SelectItem>
<SelectItem value="year">Last year</SelectItem>
</SelectContent>
</Select>
</CardHeader>
<CardContent>
{statsData?.produced && statsData.produced.length > 0 ? (
<div className="flex flex-col gap-4">
{/* Bar chart */}
<div className="h-[240px] w-full">
<ResponsiveContainer width="100%" height="100%">
{statsPeriod === "year" && statsData.producedTimeline && statsData.producedTimeline.length > 0 ? (() => {
const BAR_COLORS = [
"#6366f1", "#22c55e", "#3b82f6",
"#f59e0b", "#a855f7", "#ef4444",
];
// Pivot timeline into {month, product1: qty, product2: qty, ...}
const productSkus = [...new Set(statsData.producedTimeline.map((t) => t.sku))];
const productNames: Record<string, string> = {};
statsData.producedTimeline.forEach((t) => { productNames[t.sku] = t.product_name; });
const bucketMap = new Map<string, Record<string, number | string>>();
statsData.producedTimeline.forEach((t) => {
const d = new Date(t.bucket);
const label = d.toLocaleDateString("en-GB", { month: "short", year: "2-digit" });
if (!bucketMap.has(label)) {
const row: Record<string, number | string> = { month: label };
productSkus.forEach((s) => { row[s] = 0; });
bucketMap.set(label, row);
}
const row = bucketMap.get(label)!;
row[t.sku] = (Number(row[t.sku]) || 0) + Number(t.quantity);
});
const chartData = Array.from(bucketMap.values());
return (
<BarChart data={chartData} margin={{ top: 5, right: 5, left: 0, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
<XAxis
dataKey="month"
tick={{ fontSize: 10, fill: "hsl(var(--muted-foreground))" }}
/>
<YAxis
allowDecimals={false}
tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
/>
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
fontSize: "12px",
}}
formatter={(value: number, name: string) => [
`${value.toLocaleString()} units`,
productNames[name] || name,
]}
/>
<Legend
formatter={(value: string) => productNames[value] || value}
wrapperStyle={{ fontSize: "11px" }}
/>
{productSkus.map((sku, i) => (
<Bar
key={sku}
dataKey={sku}
fill={BAR_COLORS[i % BAR_COLORS.length]}
radius={[3, 3, 0, 0]}
/>
))}
</BarChart>
);
})() : (
<BarChart
data={statsData.produced.map((item) => ({
name: item.sku,
fullName: item.product_name,
units: Number(item.total_produced),
}))}
margin={{ top: 5, right: 5, left: 0, bottom: 5 }}
>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
<XAxis
dataKey="name"
tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
/>
<YAxis
allowDecimals={false}
tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
/>
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
fontSize: "12px",
}}
formatter={(value: number, _name: string, props: { payload?: { fullName?: string } }) => [
`${value.toLocaleString()} units`,
props.payload?.fullName || "Units",
]}
/>
<Bar dataKey="units" radius={[4, 4, 0, 0]}>
{statsData.produced.map((_entry, index) => {
const colors = [
"#6366f1", "#22c55e", "#3b82f6",
"#f59e0b", "#a855f7", "#ef4444",
];
return (
<Cell
key={`cell-${index}`}
fill={colors[index % colors.length]}
/>
);
})}
</Bar>
</BarChart>
)}
</ResponsiveContainer>
</div>
{/* Summary table below chart */}
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
{statsData.produced.map((item) => (
<div
key={item.product_id}
className="rounded-md border px-3 py-2 text-center"
>
<p className="font-mono text-xs text-muted-foreground">{item.sku}</p>
<p className="text-lg font-bold">{Number(item.total_produced).toLocaleString()}</p>
<p className="text-xs text-muted-foreground">units</p>
</div>
))}
</div>
</div>
) : (
<div className="flex items-center justify-center py-8 text-sm text-muted-foreground">
No production data for this period
</div>
)}
</CardContent>
</Card>
</div>
{/* Purchase Orders Table */}
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle className="text-base">Purchase Orders</CardTitle>
<Button size="sm" asChild>
<Link href={`/customers/${customerId}/orders/new`}>
<Plus className="mr-2 h-3.5 w-3.5" />
New Order
</Link>
</Button>
</CardHeader>
<CardContent className="p-0">
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<SortableTableHead column="po_number" label="PO Number" sort={orderSort} onToggle={toggleOrderSort} />
<SortableTableHead column="customer_ref" label="Customer Ref" sort={orderSort} onToggle={toggleOrderSort} />
<SortableTableHead column="status" label="Status" sort={orderSort} onToggle={toggleOrderSort} />
<SortableTableHead column="order_date" label="Order Date" sort={orderSort} onToggle={toggleOrderSort} />
<SortableTableHead column="due_date" label="Due Date" sort={orderSort} onToggle={toggleOrderSort} />
<SortableTableHead column="item_count" label="Items" sort={orderSort} onToggle={toggleOrderSort} className="text-right" />
<SortableTableHead column="total_value" label="Value" sort={orderSort} onToggle={toggleOrderSort} className="text-right" />
<TableHead className="w-[160px]">Fulfillment</TableHead>
<TableHead className="w-[120px]">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{sortedOrders.length === 0 ? (
<TableRow>
<TableCell
colSpan={9}
className="py-12 text-center text-muted-foreground"
>
No purchase orders yet. Click &quot;New Order&quot; to
create one.
</TableCell>
</TableRow>
) : (
sortedOrders.map((order) => {
const sc = statusConfig[order.status] || statusConfig.draft;
return (
<TableRow key={order.id}>
<TableCell className="font-mono text-sm font-medium">
<Link
href={`/customers/${customerId}/orders/${order.id}`}
className="flex items-center gap-1.5 text-primary hover:underline"
>
{order.po_number}
<ExternalLink className="h-3 w-3" />
</Link>
</TableCell>
<TableCell className="text-sm text-muted-foreground">
{order.customer_ref || "-"}
</TableCell>
<TableCell>
<Badge variant={sc.variant} className="text-xs">
{sc.label}
</Badge>
</TableCell>
<TableCell className="text-sm">
{new Date(order.order_date).toLocaleDateString()}
</TableCell>
<TableCell className="text-sm text-muted-foreground">
{order.due_date
? new Date(order.due_date).toLocaleDateString()
: "-"}
</TableCell>
<TableCell className="text-right font-mono text-sm">
{Number(order.item_count || 0)}
</TableCell>
<TableCell className="text-right font-mono text-sm font-medium">
{formatCurrency(Number(order.total_value || 0))}
</TableCell>
<TableCell>
{(() => {
const ordered = Number(order.total_ordered || 0);
const shipped = Number(order.total_shipped || 0);
const pct = ordered > 0 ? Math.round((shipped / ordered) * 100) : 0;
if (order.status === "cancelled") return <span className="text-xs text-muted-foreground">-</span>;
return (
<div className="flex flex-col gap-1">
<div className="flex items-center justify-between text-xs">
<span className="font-mono text-muted-foreground">{shipped}/{ordered}</span>
<span className={pct === 100 ? "font-semibold text-accent" : "text-muted-foreground"}>{pct}%</span>
</div>
<Progress value={pct} className="h-1.5" />
</div>
);
})()}
</TableCell>
<TableCell>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
asChild
>
<Link
href={`/customers/${customerId}/orders/${order.id}`}
>
<Pencil className="h-3.5 w-3.5" />
<span className="sr-only">Edit</span>
</Link>
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive hover:text-destructive"
onClick={() => setDeleteOrderTarget(order)}
>
<Trash2 className="h-3.5 w-3.5" />
<span className="sr-only">Delete</span>
</Button>
</div>
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
</div>
</CardContent>
</Card>
<CustomerDialog
open={editOpen}
onOpenChange={setEditOpen}
customer={customer}
onSaved={() => mutateCustomer()}
/>
<AlertDialog
open={!!deleteOrderTarget}
onOpenChange={() => setDeleteOrderTarget(null)}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Purchase Order</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete PO &quot;
{deleteOrderTarget?.po_number}&quot;? This will also remove all
associated line items.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleDeleteOrder}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}