Files
website-secure/app/bom/[productId]/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

324 lines
11 KiB
TypeScript

"use client";
import { useState, useCallback, use } from "react";
import useSWR from "swr";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
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 {
Plus,
Pencil,
Trash2,
ArrowLeft,
AlertTriangle,
Euro,
Layers,
Hash,
} from "lucide-react";
import { useTableSort } from "@/hooks/use-table-sort";
import { SortableTableHead } from "@/components/sortable-table-head";
import { BomItemDialog } from "@/components/bom-item-dialog";
import { toast } from "sonner";
import { formatCurrency, formatUnitPrice } from "@/lib/format";
import type { Product, BomItem } from "@/lib/types";
const fetcher = (url: string) => fetch(url).then((r) => r.json());
export default function BomDetailPage({
params,
}: {
params: Promise<{ productId: string }>;
}) {
const { productId } = use(params);
const [dialogOpen, setDialogOpen] = useState(false);
const [editingItem, setEditingItem] = useState<BomItem | null>(null);
const [deleteTarget, setDeleteTarget] = useState<BomItem | null>(null);
const { data: products = [] } = useSWR<Product[]>("/api/products", fetcher);
const product = products.find((p) => p.id === Number(productId));
const { data: bomItems = [], mutate } = useSWR<BomItem[]>(
`/api/bom/${productId}`,
fetcher
);
const { sorted: sortedBomItems, sort, toggleSort } = useTableSort(bomItems);
const totalCost = bomItems.reduce(
(sum, item) => sum + Number(item.line_cost || 0),
0
);
const totalParts = bomItems.reduce((sum, item) => sum + item.quantity, 0);
const handleSave = useCallback(
async (data: Partial<BomItem>) => {
const url = editingItem
? `/api/bom/${productId}/${editingItem.id}`
: `/api/bom/${productId}`;
const method = editingItem ? "PUT" : "POST";
const res = await fetch(url, {
method,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
if (!res.ok) {
const err = await res.json();
toast.error(err.error || "Failed to save");
throw new Error(err.error || "Failed to save");
}
toast.success(editingItem ? "BOM item updated" : "Component added to BOM");
mutate();
},
[editingItem, productId, mutate]
);
const handleDelete = useCallback(async () => {
if (!deleteTarget) return;
await fetch(`/api/bom/${productId}/${deleteTarget.id}`, {
method: "DELETE",
});
toast.success("BOM item removed");
setDeleteTarget(null);
mutate();
}, [deleteTarget, productId, mutate]);
function openCreate() {
setEditingItem(null);
setDialogOpen(true);
}
function openEdit(item: BomItem) {
setEditingItem(item);
setDialogOpen(true);
}
return (
<div className="flex flex-col gap-6 p-6 lg:p-8">
{/* Header */}
<div className="flex items-start justify-between">
<div className="flex items-start gap-4">
<Button variant="outline" size="icon" asChild>
<Link href="/bom">
<ArrowLeft className="h-4 w-4" />
<span className="sr-only">Back</span>
</Link>
</Button>
<div>
<h1 className="text-2xl font-bold tracking-tight text-foreground">
{product?.name || "Loading..."}
</h1>
<p className="text-sm text-muted-foreground">
{product && (
<>
<span className="font-mono">{product.sku}</span>
{" "}
&middot; v{product.version} &middot; Bill of Materials
</>
)}
</p>
</div>
</div>
<Button onClick={openCreate}>
<Plus className="mr-2 h-4 w-4" />
Add Item
</Button>
</div>
{/* Summary Cards */}
<div className="grid gap-4 grid-cols-3">
<Card>
<CardContent className="flex items-center gap-3 py-4">
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
<Layers className="h-5 w-5 text-primary" />
</div>
<div>
<p className="text-sm text-muted-foreground">Unique Items</p>
<p className="text-2xl font-bold">{bomItems.length}</p>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="flex items-center gap-3 py-4">
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-accent/10">
<Hash className="h-5 w-5 text-accent" />
</div>
<div>
<p className="text-sm text-muted-foreground">Total Parts</p>
<p className="text-2xl font-bold">{totalParts}</p>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="flex items-center gap-3 py-4">
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-warning/10">
<Euro className="h-5 w-5 text-warning" />
</div>
<div>
<p className="text-sm text-muted-foreground">Total BOM Cost</p>
<p className="text-2xl font-bold font-mono">
{formatCurrency(totalCost)}
</p>
</div>
</CardContent>
</Card>
</div>
{/* BOM Table */}
<div className="rounded-lg border bg-card">
<Table>
<TableHeader>
<TableRow>
<SortableTableHead column="reference_designator" label="Ref Des" sort={sort} onToggle={toggleSort} />
<SortableTableHead column="part_number" label="Part Number" sort={sort} onToggle={toggleSort} className="w-[140px]" />
<SortableTableHead column="component_name" label="Component" sort={sort} onToggle={toggleSort} />
<SortableTableHead column="category_name" label="Category" sort={sort} onToggle={toggleSort} />
<SortableTableHead column="quantity" label="Qty" sort={sort} onToggle={toggleSort} className="text-right" />
<SortableTableHead column="unit_price" label="Unit Price" sort={sort} onToggle={toggleSort} className="text-right" />
<SortableTableHead column="line_cost" label="Line Cost" sort={sort} onToggle={toggleSort} className="text-right" />
<SortableTableHead column="stock_quantity" label="Stock" sort={sort} onToggle={toggleSort} className="text-right" />
<TableHead className="w-[90px]">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{sortedBomItems.length === 0 ? (
<TableRow>
<TableCell
colSpan={9}
className="text-center py-12 text-muted-foreground"
>
No items in this BOM yet. Click &quot;Add Item&quot; to add
components.
</TableCell>
</TableRow>
) : (
sortedBomItems.map((item) => {
const stockShort =
(item.stock_quantity || 0) < item.quantity;
return (
<TableRow key={item.id}>
<TableCell className="font-mono text-xs">
{item.reference_designator || "-"}
</TableCell>
<TableCell className="font-mono text-xs font-medium">
{item.part_number}
</TableCell>
<TableCell className="font-medium">
{item.component_name}
</TableCell>
<TableCell>
{item.category_name && (
<Badge variant="secondary" className="text-xs">
{item.category_name}
</Badge>
)}
</TableCell>
<TableCell className="text-right font-medium">
{item.quantity}
</TableCell>
<TableCell className="text-right font-mono text-sm">
{formatUnitPrice(Number(item.unit_price || 0))}
</TableCell>
<TableCell className="text-right font-mono text-sm font-medium">
{formatCurrency(Number(item.line_cost || 0))}
</TableCell>
<TableCell className="text-right">
<span
className={
stockShort
? "inline-flex items-center gap-1 font-semibold text-destructive"
: ""
}
>
{stockShort && (
<AlertTriangle className="h-3.5 w-3.5" />
)}
{item.stock_quantity ?? 0}
</span>
</TableCell>
<TableCell>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => openEdit(item)}
>
<Pencil className="h-3.5 w-3.5" />
<span className="sr-only">Edit</span>
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive hover:text-destructive"
onClick={() => setDeleteTarget(item)}
>
<Trash2 className="h-3.5 w-3.5" />
<span className="sr-only">Remove</span>
</Button>
</div>
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
</div>
<BomItemDialog
open={dialogOpen}
onOpenChange={setDialogOpen}
bomItem={editingItem}
productId={Number(productId)}
onSave={handleSave}
/>
<AlertDialog
open={!!deleteTarget}
onOpenChange={() => setDeleteTarget(null)}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Remove BOM Item</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to remove{" "}
<strong>{deleteTarget?.component_name}</strong> from this BOM?
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Remove
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}