chore: upload parte 1 - logica
DevSecOps Enterprise Pipeline / security-gate-and-deploy (push) Failing after 41s

This commit is contained in:
2026-06-01 15:35:53 +01:00
parent a63625d228
commit 9c14a19a87
127 changed files with 22255 additions and 0 deletions
@@ -0,0 +1,679 @@
"use client";
import { useState, useEffect } from "react";
import { useParams, useRouter } from "next/navigation";
import useSWR from "swr";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Textarea } from "@/components/ui/textarea";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Progress } from "@/components/ui/progress";
import { ArrowLeft, Plus, Trash2, Package, Save, Euro, Layers, Truck, FileDown } from "lucide-react";
import { toast } from "sonner";
import { formatCurrency } from "@/lib/format";
import type { Product, PurchaseOrder, PurchaseOrderItem } from "@/lib/types";
const fetcher = (url: string) => fetch(url).then((r) => r.json());
interface OrderLineItem {
product_id: string;
quantity: string;
unit_price: string;
notes: string;
}
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 OrderDetailPage() {
const params = useParams();
const router = useRouter();
const customerId = params.id as string;
const orderId = params.orderId as string;
const [loading, setLoading] = useState(false);
const [editing, setEditing] = useState(false);
const [form, setForm] = useState({
po_number: "",
customer_ref: "",
status: "draft",
order_date: "",
due_date: "",
notes: "",
});
const [items, setItems] = useState<OrderLineItem[]>([]);
const { data: orderData, mutate } = useSWR<
PurchaseOrder & { items: PurchaseOrderItem[] }
>(`/api/orders/${orderId}`, fetcher);
const { data: products = [] } = useSWR<Product[]>("/api/products", fetcher);
useEffect(() => {
if (orderData) {
setForm({
po_number: orderData.po_number || "",
customer_ref: orderData.customer_ref || "",
status: orderData.status || "draft",
order_date: orderData.order_date
? new Date(orderData.order_date).toISOString().slice(0, 10)
: "",
due_date: orderData.due_date
? new Date(orderData.due_date).toISOString().slice(0, 10)
: "",
notes: orderData.notes || "",
});
setItems(
(orderData.items || []).map((item) => ({
product_id: String(item.product_id),
quantity: String(item.quantity),
unit_price: String(item.unit_price),
notes: item.notes || "",
}))
);
}
}, [orderData]);
function addLine() {
setItems([
...items,
{ product_id: "", quantity: "1", unit_price: "", notes: "" },
]);
}
function removeLine(index: number) {
if (items.length <= 1) return;
setItems(items.filter((_, i) => i !== index));
}
function updateLine(index: number, field: keyof OrderLineItem, value: string) {
const updated = [...items];
updated[index] = { ...updated[index], [field]: value };
setItems(updated);
}
function getLineTotal(item: OrderLineItem) {
return (Number(item.quantity) || 0) * (Number(item.unit_price) || 0);
}
const orderTotal = items.reduce((sum, item) => sum + getLineTotal(item), 0);
async function handleDownloadPO() {
if (!orderData) return;
const { generatePoPdf } = await import("@/lib/generate-po-pdf");
const doc = generatePoPdf({
po_number: orderData.po_number,
order_date: orderData.order_date,
due_date: orderData.due_date,
customer_ref: orderData.customer_ref,
status: orderData.status,
customer_name: orderData.customer_name || "",
customer_code: orderData.customer_code || "",
customer_email: (orderData as Record<string, unknown>).customer_email as string | null,
customer_phone: (orderData as Record<string, unknown>).customer_phone as string | null,
customer_address: (orderData as Record<string, unknown>).customer_address as string | null,
customer_contact: (orderData as Record<string, unknown>).customer_contact as string | null,
notes: orderData.notes,
items: (orderData.items || []).map((item) => ({
product_name: item.product_name || "",
product_sku: item.product_sku || "",
quantity: Number(item.quantity),
unit_price: Number(item.unit_price),
line_total: Number(item.line_total || 0),
notes: item.notes,
})),
});
doc.save(`${orderData.po_number}.pdf`);
}
async function handleSave() {
setLoading(true);
try {
const validItems = items.filter((item) => item.product_id);
const res = await fetch(`/api/orders/${orderId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
customer_id: Number(customerId),
...form,
due_date: form.due_date || null,
items: validItems.map((item) => ({
product_id: Number(item.product_id),
quantity: Number(item.quantity) || 1,
unit_price: Number(item.unit_price) || 0,
notes: item.notes || null,
})),
}),
});
if (!res.ok) throw new Error("Failed to update");
toast.success("Purchase order updated");
mutate();
setEditing(false);
} catch {
toast.error("Failed to update order");
} finally {
setLoading(false);
}
}
if (!orderData) {
return (
<div className="flex items-center justify-center p-12">
<p className="text-muted-foreground">Loading order...</p>
</div>
);
}
const sc = statusConfig[orderData.status] || statusConfig.draft;
// VIEW MODE
if (!editing) {
return (
<div className="flex flex-col gap-6 p-6">
<div className="flex items-start justify-between">
<div className="flex items-center gap-4">
<Button
variant="ghost"
size="icon"
onClick={() => router.push(`/customers/${customerId}`)}
>
<ArrowLeft className="h-4 w-4" />
</Button>
<div>
<div className="flex items-center gap-3">
<h1 className="text-2xl font-bold tracking-tight font-mono text-foreground">
{orderData.po_number}
</h1>
<Badge variant={sc.variant}>{sc.label}</Badge>
</div>
<p className="text-sm text-muted-foreground">
Order for {orderData.customer_name} ({orderData.customer_code})
</p>
</div>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={handleDownloadPO}>
<FileDown className="mr-2 h-3.5 w-3.5" />
Download PO
</Button>
<Button variant="outline" size="sm" onClick={() => setEditing(true)}>
Edit Order
</Button>
</div>
</div>
{/* Summary Cards */}
{(() => {
const itemsList = orderData.items || [];
const totalOrdered = itemsList.reduce((s, i) => s + Number(i.quantity), 0);
const totalShipped = itemsList.reduce((s, i) => s + Number(i.shipped_quantity || 0), 0);
const totalRemaining = totalOrdered - totalShipped;
const fulfillmentPct = totalOrdered > 0 ? Math.round((totalShipped / totalOrdered) * 100) : 0;
const isOverdue = orderData.due_date && new Date(orderData.due_date) < new Date() && fulfillmentPct < 100;
return (
<div className="grid grid-cols-1 gap-4 md:grid-cols-5">
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
Order Date
</CardTitle>
</CardHeader>
<CardContent>
<p className="text-lg font-semibold">
{new Date(orderData.order_date).toLocaleDateString()}
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
Due Date
</CardTitle>
</CardHeader>
<CardContent>
<p className={`text-lg font-semibold ${isOverdue ? "text-destructive" : ""}`}>
{orderData.due_date
? new Date(orderData.due_date).toLocaleDateString()
: "Not set"}
{isOverdue && (
<span className="ml-1 text-xs font-normal">(overdue)</span>
)}
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
Order Total
</CardTitle>
<Euro className="h-4 w-4 text-accent" />
</CardHeader>
<CardContent>
<p className="text-2xl font-bold">
{formatCurrency(
itemsList.reduce((s, i) => s + Number(i.line_total || 0), 0)
)}
</p>
<p className="text-xs text-muted-foreground">
{itemsList.length} line item{itemsList.length !== 1 ? "s" : ""}
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
Units Remaining
</CardTitle>
<Package className="h-4 w-4 text-primary" />
</CardHeader>
<CardContent>
<p className="text-2xl font-bold font-mono">
<span className={totalRemaining > 0 ? "text-foreground" : "text-accent"}>
{totalRemaining}
</span>
<span className="text-sm font-normal text-muted-foreground ml-1">
/ {totalOrdered}
</span>
</p>
<p className="text-xs text-muted-foreground">
{totalShipped} shipped
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
Fulfillment
</CardTitle>
<Truck className="h-4 w-4 text-primary" />
</CardHeader>
<CardContent>
<p className={`text-2xl font-bold font-mono ${fulfillmentPct === 100 ? "text-accent" : ""}`}>
{fulfillmentPct}%
</p>
<Progress value={fulfillmentPct} className="mt-2 h-2" />
</CardContent>
</Card>
</div>
);
})()}
{orderData.customer_ref && (
<div className="text-sm text-muted-foreground">
Customer Reference:{" "}
<span className="font-mono font-medium text-foreground">
{orderData.customer_ref}
</span>
</div>
)}
{orderData.notes && (
<Card>
<CardContent className="p-4 text-sm text-muted-foreground">
{orderData.notes}
</CardContent>
</Card>
)}
{/* Line Items Table */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<Package className="h-4 w-4 text-primary" />
Order Items
</CardTitle>
</CardHeader>
<CardContent className="p-0">
<Table>
<TableHeader>
<TableRow>
<TableHead>#</TableHead>
<TableHead>Product</TableHead>
<TableHead>SKU</TableHead>
<TableHead className="text-right">Ordered</TableHead>
<TableHead className="text-right">Shipped</TableHead>
<TableHead className="text-right">Remaining</TableHead>
<TableHead className="w-[120px]">Fulfillment</TableHead>
<TableHead className="text-right">Unit Price</TableHead>
<TableHead className="text-right">Line Total</TableHead>
<TableHead>Notes</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{(orderData.items || []).map(
(item: PurchaseOrderItem, idx: number) => {
const ordered = Number(item.quantity);
const shipped = Number(item.shipped_quantity || 0);
const remaining = ordered - shipped;
const pct = ordered > 0 ? Math.round((shipped / ordered) * 100) : 0;
return (
<TableRow key={item.id}>
<TableCell className="text-xs text-muted-foreground">
{idx + 1}
</TableCell>
<TableCell className="font-medium">
{item.product_name}
</TableCell>
<TableCell className="font-mono text-xs text-muted-foreground">
{item.product_sku}
</TableCell>
<TableCell className="text-right font-mono">
{ordered.toLocaleString()}
</TableCell>
<TableCell className="text-right font-mono">
{shipped.toLocaleString()}
</TableCell>
<TableCell className="text-right font-mono font-semibold">
<span className={remaining > 0 ? "text-foreground" : "text-accent"}>
{remaining.toLocaleString()}
</span>
</TableCell>
<TableCell>
<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 className="text-right font-mono">
{formatCurrency(Number(item.unit_price))}
</TableCell>
<TableCell className="text-right font-mono font-semibold">
{formatCurrency(Number(item.line_total || 0))}
</TableCell>
<TableCell className="text-xs text-muted-foreground">
{item.notes || "-"}
</TableCell>
</TableRow>
);
}
)}
</TableBody>
</Table>
</CardContent>
</Card>
</div>
);
}
// EDIT MODE
return (
<div className="flex flex-col gap-6 p-6">
<div className="flex items-center gap-4">
<Button
variant="ghost"
size="icon"
onClick={() => setEditing(false)}
>
<ArrowLeft className="h-4 w-4" />
</Button>
<div>
<h1 className="text-2xl font-bold tracking-tight text-foreground">
Edit Purchase Order
</h1>
<p className="text-sm text-muted-foreground">
{orderData.po_number} - {orderData.customer_name}
</p>
</div>
</div>
<Card>
<CardHeader>
<CardTitle className="text-base">Order Details</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
<div className="flex flex-col gap-2">
<Label htmlFor="po_number">PO Number</Label>
<Input
id="po_number"
value={form.po_number}
onChange={(e) =>
setForm({ ...form, po_number: e.target.value })
}
className="font-mono"
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="customer_ref">Customer Reference</Label>
<Input
id="customer_ref"
value={form.customer_ref}
onChange={(e) =>
setForm({ ...form, customer_ref: e.target.value })
}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="status">Status</Label>
<Select
value={form.status}
onValueChange={(v) => setForm({ ...form, status: v })}
>
<SelectTrigger id="status">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="draft">Draft</SelectItem>
<SelectItem value="confirmed">Confirmed</SelectItem>
<SelectItem value="in_production">In Production</SelectItem>
<SelectItem value="shipped">Shipped</SelectItem>
<SelectItem value="completed">Completed</SelectItem>
<SelectItem value="cancelled">Cancelled</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
<div className="flex flex-col gap-2">
<Label htmlFor="order_date">Order Date</Label>
<Input
id="order_date"
type="date"
value={form.order_date}
onChange={(e) =>
setForm({ ...form, order_date: e.target.value })
}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="due_date">Due Date</Label>
<Input
id="due_date"
type="date"
value={form.due_date}
onChange={(e) =>
setForm({ ...form, due_date: e.target.value })
}
/>
</div>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="notes">Notes</Label>
<Textarea
id="notes"
value={form.notes}
onChange={(e) => setForm({ ...form, notes: e.target.value })}
rows={2}
/>
</div>
</CardContent>
</Card>
{/* Line Items */}
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle className="flex items-center gap-2 text-base">
<Package className="h-4 w-4 text-primary" />
Line Items
</CardTitle>
<Button type="button" variant="outline" size="sm" onClick={addLine}>
<Plus className="mr-2 h-3.5 w-3.5" />
Add Line
</Button>
</CardHeader>
<CardContent className="p-0">
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[40px]">#</TableHead>
<TableHead>Product</TableHead>
<TableHead className="w-[120px]">Quantity</TableHead>
<TableHead className="w-[140px]">Unit Price</TableHead>
<TableHead className="w-[140px] text-right">
Line Total
</TableHead>
<TableHead>Notes</TableHead>
<TableHead className="w-[50px]" />
</TableRow>
</TableHeader>
<TableBody>
{items.map((item, index) => (
<TableRow key={index}>
<TableCell className="text-center text-xs text-muted-foreground">
{index + 1}
</TableCell>
<TableCell>
<Select
value={item.product_id}
onValueChange={(v) =>
updateLine(index, "product_id", v)
}
>
<SelectTrigger className="h-9">
<SelectValue placeholder="Select product..." />
</SelectTrigger>
<SelectContent>
{products.map((p) => (
<SelectItem key={p.id} value={String(p.id)}>
<span className="font-mono text-xs text-muted-foreground mr-2">
{p.sku}
</span>
{p.name}
</SelectItem>
))}
</SelectContent>
</Select>
</TableCell>
<TableCell>
<Input
type="number"
min="1"
value={item.quantity}
onChange={(e) =>
updateLine(index, "quantity", e.target.value)
}
className="h-9 font-mono"
/>
</TableCell>
<TableCell>
<div className="relative">
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">
{'€'}
</span>
<Input
type="number"
step="0.01"
min="0"
value={item.unit_price}
onChange={(e) =>
updateLine(index, "unit_price", e.target.value)
}
className="h-9 pl-7 font-mono"
/>
</div>
</TableCell>
<TableCell className="text-right font-mono text-sm font-semibold">
{formatCurrency(getLineTotal(item))}
</TableCell>
<TableCell>
<Input
value={item.notes}
onChange={(e) =>
updateLine(index, "notes", e.target.value)
}
placeholder="Optional"
className="h-9 text-xs"
/>
</TableCell>
<TableCell>
<Button
type="button"
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive hover:text-destructive"
onClick={() => removeLine(index)}
disabled={items.length <= 1}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</TableCell>
</TableRow>
))}
<TableRow className="bg-muted/50">
<TableCell colSpan={4} className="text-right font-semibold">
Order Total
</TableCell>
<TableCell className="text-right font-mono text-base font-bold text-primary">
{formatCurrency(orderTotal)}
</TableCell>
<TableCell colSpan={2} />
</TableRow>
</TableBody>
</Table>
</div>
</CardContent>
</Card>
<div className="flex justify-end gap-3">
<Button variant="outline" onClick={() => setEditing(false)}>
Cancel
</Button>
<Button onClick={handleSave} disabled={loading}>
<Save className="mr-2 h-4 w-4" />
{loading ? "Saving..." : "Save Changes"}
</Button>
</div>
</div>
);
}
+401
View File
@@ -0,0 +1,401 @@
"use client";
import { useState } from "react";
import { useParams, useRouter } from "next/navigation";
import useSWR from "swr";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} 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";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { ArrowLeft, Plus, Trash2, Package, Save } from "lucide-react";
import { toast } from "sonner";
import { formatCurrency } from "@/lib/format";
import type { Customer, Product } from "@/lib/types";
const fetcher = (url: string) => fetch(url).then((r) => r.json());
interface OrderLineItem {
product_id: string;
quantity: string;
unit_price: string;
notes: string;
}
export default function NewOrderPage() {
const params = useParams();
const router = useRouter();
const customerId = params.id as string;
const [loading, setLoading] = useState(false);
const [form, setForm] = useState({
po_number: "",
customer_ref: "",
status: "draft",
order_date: new Date().toISOString().slice(0, 10),
due_date: "",
notes: "",
});
const [items, setItems] = useState<OrderLineItem[]>([
{ product_id: "", quantity: "1", unit_price: "", notes: "" },
]);
const { data: customer } = useSWR<Customer>(
`/api/customers/${customerId}`,
fetcher
);
const { data: products = [] } = useSWR<Product[]>("/api/products", fetcher);
function addLine() {
setItems([
...items,
{ product_id: "", quantity: "1", unit_price: "", notes: "" },
]);
}
function removeLine(index: number) {
if (items.length <= 1) return;
setItems(items.filter((_, i) => i !== index));
}
function updateLine(index: number, field: keyof OrderLineItem, value: string) {
const updated = [...items];
updated[index] = { ...updated[index], [field]: value };
setItems(updated);
}
function getLineTotal(item: OrderLineItem) {
const qty = Number(item.quantity) || 0;
const price = Number(item.unit_price) || 0;
return qty * price;
}
const orderTotal = items.reduce((sum, item) => sum + getLineTotal(item), 0);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!form.po_number) {
toast.error("PO Number is required");
return;
}
const validItems = items.filter((item) => item.product_id);
if (validItems.length === 0) {
toast.error("Add at least one product line item");
return;
}
setLoading(true);
try {
const res = await fetch("/api/orders", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
customer_id: Number(customerId),
...form,
due_date: form.due_date || null,
items: validItems.map((item) => ({
product_id: Number(item.product_id),
quantity: Number(item.quantity) || 1,
unit_price: Number(item.unit_price) || 0,
notes: item.notes || null,
})),
}),
});
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || "Failed to create order");
}
toast.success("Purchase order created");
router.push(`/customers/${customerId}`);
} catch (err) {
toast.error(
err instanceof Error ? err.message : "Failed to create order"
);
} finally {
setLoading(false);
}
}
return (
<div className="flex flex-col gap-6 p-6">
{/* Header */}
<div className="flex items-center gap-4">
<Button
variant="ghost"
size="icon"
onClick={() => router.push(`/customers/${customerId}`)}
>
<ArrowLeft className="h-4 w-4" />
</Button>
<div>
<h1 className="text-2xl font-bold tracking-tight text-foreground">
New Purchase Order
</h1>
<p className="text-sm text-muted-foreground">
{customer
? `Creating order for ${customer.name} (${customer.code})`
: "Loading..."}
</p>
</div>
</div>
<form onSubmit={handleSubmit} className="flex flex-col gap-6">
{/* Order Details */}
<Card>
<CardHeader>
<CardTitle className="text-base">Order Details</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
<div className="flex flex-col gap-2">
<Label htmlFor="po_number">
PO Number <span className="text-destructive">*</span>
</Label>
<Input
id="po_number"
value={form.po_number}
onChange={(e) =>
setForm({ ...form, po_number: e.target.value })
}
placeholder="PO-2026-001"
className="font-mono"
required
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="customer_ref">Customer Reference</Label>
<Input
id="customer_ref"
value={form.customer_ref}
onChange={(e) =>
setForm({ ...form, customer_ref: e.target.value })
}
placeholder="Their internal ref"
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="status">Status</Label>
<Select
value={form.status}
onValueChange={(v) => setForm({ ...form, status: v })}
>
<SelectTrigger id="status">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="draft">Draft</SelectItem>
<SelectItem value="confirmed">Confirmed</SelectItem>
<SelectItem value="in_production">In Production</SelectItem>
<SelectItem value="shipped">Shipped</SelectItem>
<SelectItem value="completed">Completed</SelectItem>
<SelectItem value="cancelled">Cancelled</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
<div className="flex flex-col gap-2">
<Label htmlFor="order_date">Order Date</Label>
<Input
id="order_date"
type="date"
value={form.order_date}
onChange={(e) =>
setForm({ ...form, order_date: e.target.value })
}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="due_date">Due Date</Label>
<Input
id="due_date"
type="date"
value={form.due_date}
onChange={(e) =>
setForm({ ...form, due_date: e.target.value })
}
/>
</div>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="notes">Notes</Label>
<Textarea
id="notes"
value={form.notes}
onChange={(e) => setForm({ ...form, notes: e.target.value })}
placeholder="Internal notes about this order..."
rows={2}
/>
</div>
</CardContent>
</Card>
{/* Line Items */}
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle className="flex items-center gap-2 text-base">
<Package className="h-4 w-4 text-primary" />
Line Items
</CardTitle>
<Button type="button" variant="outline" size="sm" onClick={addLine}>
<Plus className="mr-2 h-3.5 w-3.5" />
Add Line
</Button>
</CardHeader>
<CardContent className="p-0">
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[40px]">#</TableHead>
<TableHead>Product</TableHead>
<TableHead className="w-[120px]">Quantity</TableHead>
<TableHead className="w-[140px]">Unit Price</TableHead>
<TableHead className="w-[140px] text-right">
Line Total
</TableHead>
<TableHead>Notes</TableHead>
<TableHead className="w-[50px]" />
</TableRow>
</TableHeader>
<TableBody>
{items.map((item, index) => (
<TableRow key={index}>
<TableCell className="text-center text-xs text-muted-foreground">
{index + 1}
</TableCell>
<TableCell>
<Select
value={item.product_id}
onValueChange={(v) =>
updateLine(index, "product_id", v)
}
>
<SelectTrigger className="h-9">
<SelectValue placeholder="Select product..." />
</SelectTrigger>
<SelectContent>
{products.map((p) => (
<SelectItem key={p.id} value={String(p.id)}>
<span className="font-mono text-xs text-muted-foreground mr-2">
{p.sku}
</span>
{p.name}
</SelectItem>
))}
</SelectContent>
</Select>
</TableCell>
<TableCell>
<Input
type="number"
min="1"
value={item.quantity}
onChange={(e) =>
updateLine(index, "quantity", e.target.value)
}
className="h-9 font-mono"
/>
</TableCell>
<TableCell>
<div className="relative">
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">
{'€'}
</span>
<Input
type="number"
step="0.01"
min="0"
value={item.unit_price}
onChange={(e) =>
updateLine(index, "unit_price", e.target.value)
}
className="h-9 pl-7 font-mono"
/>
</div>
</TableCell>
<TableCell className="text-right font-mono text-sm font-semibold">
{formatCurrency(getLineTotal(item))}
</TableCell>
<TableCell>
<Input
value={item.notes}
onChange={(e) =>
updateLine(index, "notes", e.target.value)
}
placeholder="Optional"
className="h-9 text-xs"
/>
</TableCell>
<TableCell>
<Button
type="button"
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive hover:text-destructive"
onClick={() => removeLine(index)}
disabled={items.length <= 1}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</TableCell>
</TableRow>
))}
<TableRow className="bg-muted/50">
<TableCell colSpan={4} className="text-right font-semibold">
Order Total
</TableCell>
<TableCell className="text-right font-mono text-base font-bold text-primary">
{formatCurrency(orderTotal)}
</TableCell>
<TableCell colSpan={2} />
</TableRow>
</TableBody>
</Table>
</div>
</CardContent>
</Card>
{/* Actions */}
<div className="flex justify-end gap-3">
<Button
type="button"
variant="outline"
onClick={() => router.push(`/customers/${customerId}`)}
>
Cancel
</Button>
<Button type="submit" disabled={loading}>
<Save className="mr-2 h-4 w-4" />
{loading ? "Creating..." : "Create Purchase Order"}
</Button>
</div>
</form>
</div>
);
}
+677
View File
@@ -0,0 +1,677 @@
"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>
);
}