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
+617
View File
@@ -0,0 +1,617 @@
"use client";
import { useState, useCallback } from "react";
import useSWR from "swr";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
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 {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Plus, Search, Pencil, Trash2, AlertTriangle, ExternalLink, PackagePlus, Printer, Box, ArrowRight } from "lucide-react";
import Link from "next/link";
import { useTableSort } from "@/hooks/use-table-sort";
import { SortableTableHead } from "@/components/sortable-table-head";
import { ComponentDialog } from "@/components/component-dialog";
import { AddStockDialog } from "@/components/add-stock-dialog";
import { generateLabelPdf } from "@/lib/generate-label-pdf";
import { toast } from "sonner";
import { formatUnitPrice } from "@/lib/format";
import type { Component, Category, ComponentSpecs } from "@/lib/types";
const fetcher = (url: string) => fetch(url).then((r) => r.json());
export default function ComponentsPage() {
const [search, setSearch] = useState("");
const [categoryFilter, setCategoryFilter] = useState("all");
const [lowStockFilter, setLowStockFilter] = useState(false);
const [dialogOpen, setDialogOpen] = useState(false);
const [editingComponent, setEditingComponent] = useState<Component | null>(null);
const [deleteTarget, setDeleteTarget] = useState<Component | null>(null);
const [stockTarget, setStockTarget] = useState<Component | null>(null);
const [stockDialogOpen, setStockDialogOpen] = useState(false);
// Component detail dialog state
const [detailDialogOpen, setDetailDialogOpen] = useState(false);
const [detailComponent, setDetailComponent] = useState<Component | null>(null);
interface ProductUsage {
id: number;
product_id: number;
product_name: string;
sku: string;
version: string;
status: string;
quantity: number;
reference_designator: string | null;
notes: string | null;
}
const { data: componentUsage = [], isLoading: usageLoading } = useSWR<ProductUsage[]>(
detailComponent ? `/api/components/${detailComponent.id}/usage` : null,
fetcher
);
function openDetail(comp: Component) {
setDetailComponent(comp);
setDetailDialogOpen(true);
}
// Label printing state
const [labelDialogOpen, setLabelDialogOpen] = useState(false);
const [labelPartNumber, setLabelPartNumber] = useState("");
const [labelQuantity, setLabelQuantity] = useState<number>(1);
const [printingLabel, setPrintingLabel] = useState(false);
function openLabelDialog(comp: Component) {
setLabelPartNumber(comp.part_number);
setLabelQuantity(comp.stock_quantity);
setLabelDialogOpen(true);
}
async function handlePrintLabel() {
if (!labelPartNumber) return;
setPrintingLabel(true);
try {
const doc = await generateLabelPdf({
partNumber: labelPartNumber,
quantity: labelQuantity,
});
doc.save(`label-${labelPartNumber}.pdf`);
toast.success("Label PDF generated");
setLabelDialogOpen(false);
} catch {
toast.error("Failed to generate label");
} finally {
setPrintingLabel(false);
}
}
const params = new URLSearchParams();
if (search) params.set("search", search);
if (categoryFilter && categoryFilter !== "all") params.set("category", categoryFilter);
if (lowStockFilter) params.set("lowStock", "true");
const { data: components = [], mutate } = useSWR<Component[]>(
`/api/components?${params.toString()}`,
fetcher
);
const { data: categories = [] } = useSWR<Category[]>(
"/api/categories",
fetcher
);
const { sorted: sortedComponents, sort, toggleSort } = useTableSort(components);
const handleSave = useCallback(
async (data: Partial<Component>) => {
const url = editingComponent
? `/api/components/${editingComponent.id}`
: "/api/components";
const method = editingComponent ? "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();
throw new Error(err.error || "Failed to save");
}
toast.success(
editingComponent ? "Component updated" : "Component created"
);
mutate();
},
[editingComponent, mutate]
);
const handleDelete = useCallback(async () => {
if (!deleteTarget) return;
await fetch(`/api/components/${deleteTarget.id}`, { method: "DELETE" });
toast.success("Component deleted");
setDeleteTarget(null);
mutate();
}, [deleteTarget, mutate]);
function openCreate() {
setEditingComponent(null);
setDialogOpen(true);
}
function openEdit(comp: Component) {
setEditingComponent(comp);
setDialogOpen(true);
}
function openAddStock(comp: Component) {
setStockTarget(comp);
setStockDialogOpen(true);
}
return (
<div className="flex flex-col gap-6 p-6 lg:p-8">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold tracking-tight text-foreground">
Components
</h1>
<p className="text-sm text-muted-foreground">
Manage your electronic component inventory
</p>
</div>
<Button onClick={openCreate}>
<Plus className="mr-2 h-4 w-4" />
Add Component
</Button>
</div>
{/* Filters */}
<div className="flex flex-wrap items-center gap-3">
<div className="relative flex-1 min-w-[240px] max-w-md">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search by name, part number, or manufacturer..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-9"
/>
</div>
<Select value={categoryFilter} onValueChange={setCategoryFilter}>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="All Categories" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Categories</SelectItem>
{categories.map((cat) => (
<SelectItem key={cat.id} value={String(cat.id)}>
{cat.name}
</SelectItem>
))}
</SelectContent>
</Select>
<Button
variant={lowStockFilter ? "destructive" : "outline"}
size="sm"
onClick={() => setLowStockFilter(!lowStockFilter)}
>
<AlertTriangle className="mr-1.5 h-3.5 w-3.5" />
Low Stock
</Button>
</div>
{/* Components Table */}
<div className="rounded-lg border bg-card">
<Table>
<TableHeader>
<TableRow>
<SortableTableHead column="part_number" label="Part Number" sort={sort} onToggle={toggleSort} className="w-[140px]" />
<SortableTableHead column="name" label="Name" sort={sort} onToggle={toggleSort} />
<SortableTableHead column="category_name" label="Category" sort={sort} onToggle={toggleSort} />
<SortableTableHead column="customer_supplied" label="Source" sort={sort} onToggle={toggleSort} />
<SortableTableHead column="shelf_location" label="Shelf Location" sort={sort} onToggle={toggleSort} />
<SortableTableHead column="unit_price" label="Unit Price" sort={sort} onToggle={toggleSort} className="text-right" />
<SortableTableHead column="stock_quantity" label="Stock" sort={sort} onToggle={toggleSort} className="text-right" />
<SortableTableHead column="on_order" label="On Order" sort={sort} onToggle={toggleSort} className="text-right" />
<SortableTableHead column="min_stock_level" label="Min Level" sort={sort} onToggle={toggleSort} className="text-right" />
<TableHead className="w-[140px]">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{sortedComponents.length === 0 ? (
<TableRow>
<TableCell
colSpan={10}
className="text-center py-12 text-muted-foreground"
>
{search || categoryFilter !== "all" || lowStockFilter
? "No components match your filters."
: "No components yet. Click \"Add Component\" to get started."}
</TableCell>
</TableRow>
) : (
sortedComponents.map((comp) => {
const isLowStock =
comp.stock_quantity <= comp.min_stock_level &&
comp.min_stock_level > 0;
return (
<TableRow key={comp.id} className="cursor-pointer" onClick={() => openDetail(comp)}>
<TableCell className="font-mono text-xs font-medium">
{comp.datasheet_url ? (
<a
href={comp.datasheet_url}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1 text-primary hover:underline"
onClick={(e) => e.stopPropagation()}
>
{comp.part_number}
<ExternalLink className="h-3 w-3" />
</a>
) : (
comp.part_number
)}
</TableCell>
<TableCell className="font-medium">{comp.name}</TableCell>
<TableCell>
{comp.category_name && (
<Badge variant="secondary" className="text-xs">
{comp.category_name}
</Badge>
)}
</TableCell>
<TableCell>
{comp.customer_supplied ? (
<Badge variant="outline" className="text-xs border-primary/30 text-primary">
{comp.customer_name || "Customer"}
</Badge>
) : (
<span className="text-xs text-muted-foreground">Standard</span>
)}
</TableCell>
<TableCell className="font-mono text-xs text-muted-foreground">
{comp.shelf_location || "-"}
</TableCell>
<TableCell className="text-right font-mono text-sm">
{formatUnitPrice(Number(comp.unit_price))}
</TableCell>
<TableCell className="text-right">
<span
className={
isLowStock
? "inline-flex items-center gap-1 font-semibold text-destructive"
: ""
}
>
{isLowStock && (
<AlertTriangle className="h-3.5 w-3.5" />
)}
{comp.stock_quantity}
</span>
</TableCell>
<TableCell className="text-right">
{Number((comp as Record<string, unknown>).on_order) > 0 ? (
<Badge variant="outline" className="font-mono text-xs text-primary border-primary/30">
{Number((comp as Record<string, unknown>).on_order)}
</Badge>
) : (
<span className="text-muted-foreground">-</span>
)}
</TableCell>
<TableCell className="text-right text-muted-foreground">
{comp.min_stock_level}
</TableCell>
<TableCell>
<div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-accent hover:text-accent"
onClick={() => openAddStock(comp)}
title="Add / Remove Stock"
>
<PackagePlus className="h-3.5 w-3.5" />
<span className="sr-only">Add Stock</span>
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => openLabelDialog(comp)}
title="Print Label"
>
<Printer className="h-3.5 w-3.5" />
<span className="sr-only">Print Label</span>
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => openEdit(comp)}
>
<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(comp)}
>
<Trash2 className="h-3.5 w-3.5" />
<span className="sr-only">Delete</span>
</Button>
</div>
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
</div>
<ComponentDialog
open={dialogOpen}
onOpenChange={setDialogOpen}
component={editingComponent}
categories={categories}
onSave={handleSave}
/>
<AddStockDialog
open={stockDialogOpen}
onOpenChange={setStockDialogOpen}
component={stockTarget}
onSaved={() => mutate()}
onPrintLabel={(partNumber, quantity) => {
setLabelPartNumber(partNumber);
setLabelQuantity(quantity);
setLabelDialogOpen(true);
}}
/>
<AlertDialog
open={!!deleteTarget}
onOpenChange={() => setDeleteTarget(null)}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Component</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete{" "}
<strong>{deleteTarget?.name}</strong> ({deleteTarget?.part_number}
)? This action cannot be undone and will remove it from all BOMs.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Component Detail Dialog */}
<Dialog open={detailDialogOpen} onOpenChange={setDetailDialogOpen}>
<DialogContent className="sm:max-w-[700px] max-h-[85vh] overflow-y-auto">
{detailComponent && (() => {
const rawSpecs = detailComponent.specs;
const specs: ComponentSpecs = typeof rawSpecs === "string" ? JSON.parse(rawSpecs) : rawSpecs || {};
const hasSpecs = Object.values(specs).some((v) => v && String(v).trim() !== "");
return (
<>
<DialogHeader>
<DialogTitle className="flex items-center gap-3">
<span>{detailComponent.name}</span>
<Badge variant="outline" className="font-mono text-xs">{detailComponent.part_number}</Badge>
</DialogTitle>
<div className="flex flex-wrap gap-x-4 gap-y-1 text-sm text-muted-foreground pt-1">
{detailComponent.category_name && (
<span>Category: <span className="text-foreground font-medium">{detailComponent.category_name}</span></span>
)}
{detailComponent.manufacturer && (
<span>Manufacturer: <span className="text-foreground font-medium">{detailComponent.manufacturer}</span></span>
)}
<span>Stock: <span className="text-foreground font-medium">{detailComponent.stock_quantity}</span></span>
{Number((detailComponent as Record<string, unknown>).on_order) > 0 && (
<span>On Order: <Badge variant="outline" className="font-mono text-xs text-primary border-primary/30 ml-0.5">{Number((detailComponent as Record<string, unknown>).on_order)}</Badge></span>
)}
{detailComponent.customer_supplied && (
<span>Customer Supplied: <Badge variant="outline" className="text-xs border-primary/30 text-primary ml-0.5">{detailComponent.customer_name || "Unknown"}</Badge></span>
)}
</div>
</DialogHeader>
{/* Specifications */}
{hasSpecs && (
<div className="rounded-lg border p-3 bg-muted/30">
<p className="text-xs font-medium text-muted-foreground mb-2">Specifications</p>
<div className="flex flex-wrap gap-x-6 gap-y-1 text-sm">
{specs.manufacturer_id && <span>Manufacturer ID: <span className="text-foreground font-mono text-xs">{specs.manufacturer_id}</span></span>}
{specs.value && <span>Value: <span className="text-foreground font-medium">{specs.value}</span></span>}
{specs.power && <span>Power: <span className="text-foreground font-medium">{specs.power}</span></span>}
{specs.voltage && <span>Voltage: <span className="text-foreground font-medium">{specs.voltage}</span></span>}
{specs.tolerance && <span>Tolerance: <span className="text-foreground font-medium">{specs.tolerance}</span></span>}
{specs.color && <span>Color: <span className="text-foreground font-medium">{specs.color}</span></span>}
{specs.no_of_pins && <span>Pins: <span className="text-foreground font-medium">{specs.no_of_pins}</span></span>}
{specs.no_of_rows && <span>Rows: <span className="text-foreground font-medium">{specs.no_of_rows}</span></span>}
{specs.connector_type && <span>Type: <span className="text-foreground font-medium">{specs.connector_type}</span></span>}
</div>
</div>
)}
{/* Supplier info */}
{(detailComponent.supplier || detailComponent.datasheet_url) && (
<div className="flex flex-wrap gap-x-4 gap-y-1 text-sm text-muted-foreground">
{detailComponent.supplier && (
<span>Supplier: <span className="text-foreground font-medium">{detailComponent.supplier}</span></span>
)}
{detailComponent.supplier_part_number && (
<span>Supplier Part No.: <span className="text-foreground font-mono text-xs">{detailComponent.supplier_part_number}</span></span>
)}
{detailComponent.datasheet_url && (
<a href={detailComponent.datasheet_url} target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">
Supplier URL
</a>
)}
</div>
)}
<div className="space-y-3">
<div className="flex items-center gap-2">
<Box className="h-4 w-4 text-muted-foreground" />
<h3 className="text-sm font-semibold">Used in Products</h3>
<Badge variant="secondary" className="text-xs">{componentUsage.length}</Badge>
</div>
{usageLoading ? (
<div className="flex items-center justify-center py-8 text-sm text-muted-foreground">
Loading...
</div>
) : componentUsage.length === 0 ? (
<div className="flex items-center justify-center py-8 text-sm text-muted-foreground">
Not used in any product BOM
</div>
) : (
<div className="rounded-lg border">
<Table>
<TableHeader>
<TableRow>
<TableHead>Product</TableHead>
<TableHead>SKU</TableHead>
<TableHead className="text-right">Qty per Unit</TableHead>
<TableHead>Ref. Designator</TableHead>
<TableHead className="w-[50px]" />
</TableRow>
</TableHeader>
<TableBody>
{componentUsage.map((usage) => (
<TableRow key={usage.id}>
<TableCell>
<div className="flex flex-col">
<span className="text-sm font-medium">{usage.product_name}</span>
{usage.version && (
<span className="text-xs text-muted-foreground">v{usage.version}</span>
)}
</div>
</TableCell>
<TableCell className="font-mono text-xs">{usage.sku}</TableCell>
<TableCell className="text-right font-mono text-sm font-semibold">
{Number(usage.quantity)}
</TableCell>
<TableCell className="font-mono text-xs text-muted-foreground">
{usage.reference_designator || "-"}
</TableCell>
<TableCell>
<Link
href={`/bom/${usage.product_id}`}
onClick={(e) => e.stopPropagation()}
className="inline-flex items-center text-primary hover:text-primary/80"
title="View BOM"
>
<ArrowRight className="h-3.5 w-3.5" />
</Link>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setDetailDialogOpen(false)}>Close</Button>
</DialogFooter>
</>
);
})()}
</DialogContent>
</Dialog>
{/* Print Label Dialog */}
<Dialog open={labelDialogOpen} onOpenChange={setLabelDialogOpen}>
<DialogContent className="sm:max-w-[400px]">
<DialogHeader>
<DialogTitle>Print Label</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-2">
<div className="rounded-md border bg-background p-3 flex items-center gap-3">
<div className="flex-1 min-w-0">
<p className="text-xs text-muted-foreground">Code:</p>
<p className="font-mono text-sm font-bold truncate">{labelPartNumber}</p>
</div>
<div className="text-right">
<p className="text-xs text-muted-foreground">Quantity:</p>
<p className="font-mono text-sm font-bold">{labelQuantity}</p>
</div>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="comp-label-qty">Quantity</Label>
<Input
id="comp-label-qty"
type="number"
min={1}
value={labelQuantity}
onChange={(e) => setLabelQuantity(Math.max(1, Number(e.target.value) || 1))}
className="font-mono"
/>
</div>
<p className="text-xs text-muted-foreground">
Label size: 49mm x 12mm. The QR code will contain: {labelPartNumber},{labelQuantity}
</p>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setLabelDialogOpen(false)}>
Cancel
</Button>
<Button onClick={handlePrintLabel} disabled={printingLabel}>
<Printer className="mr-2 h-4 w-4" />
{printingLabel ? "Generating..." : "Download Label PDF"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}