生產工單BOM以及批號完善
All checks were successful
Koori-ERP-Deploy-System / deploy-demo (push) Successful in 57s
Koori-ERP-Deploy-System / deploy-production (push) Has been skipped

This commit is contained in:
2026-01-22 15:39:35 +08:00
parent 1ae21febb5
commit 1d134c9ad8
31 changed files with 2684 additions and 694 deletions

View File

@@ -86,6 +86,15 @@ const fieldLabels: Record<string, string> = {
quantity: '數量',
safety_stock: '安全庫存',
location: '儲位',
// Inventory fields
batch_number: '批號',
box_number: '箱號',
origin_country: '來源國家',
arrival_date: '入庫日期',
expiry_date: '有效期限',
source_purchase_order_id: '來源採購單',
quality_status: '品質狀態',
quality_remark: '品質備註',
// Purchase Order fields
po_number: '採購單號',
vendor_id: '廠商',
@@ -118,6 +127,13 @@ const statusMap: Record<string, string> = {
completed: '已完成',
};
// Inventory Quality Status Map
const qualityStatusMap: Record<string, string> = {
normal: '正常',
frozen: '凍結',
rejected: '瑕疵/拒收',
};
export default function ActivityDetailDialog({ open, onOpenChange, activity }: Props) {
if (!activity) return null;
@@ -193,8 +209,13 @@ export default function ActivityDetailDialog({ open, onOpenChange, activity }: P
return statusMap[value];
}
// Handle Inventory Quality Status
if (key === 'quality_status' && typeof value === 'string' && qualityStatusMap[value]) {
return qualityStatusMap[value];
}
// Handle Date Fields (YYYY-MM-DD)
if ((key === 'expected_delivery_date' || key === 'invoice_date') && typeof value === 'string') {
if ((key === 'expected_delivery_date' || key === 'invoice_date' || key === 'arrival_date' || key === 'expiry_date') && typeof value === 'string') {
// Take only the date part (YYYY-MM-DD)
return value.split('T')[0].split(' ')[0];
}

View File

@@ -0,0 +1,170 @@
import { useState, useEffect } from "react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/Components/ui/dialog";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/Components/ui/select";
import { AlertCircle } from "lucide-react";
interface BatchAdjustmentModalProps {
isOpen: boolean;
onClose: () => void;
onConfirm: (data: {
operation: "add" | "subtract" | "set";
quantity: number;
reason: string;
}) => void;
batch?: {
id: string;
batchNumber: string;
currentQuantity: number;
productName: string;
};
processing?: boolean;
}
export default function BatchAdjustmentModal({
isOpen,
onClose,
onConfirm,
batch,
processing = false,
}: BatchAdjustmentModalProps) {
const [operation, setOperation] = useState<"add" | "subtract" | "set">("add");
const [quantity, setQuantity] = useState<string>("");
const [reason, setReason] = useState<string>("手動調整庫存");
// 當開啟時重置
useEffect(() => {
if (isOpen) {
setOperation("add");
setQuantity("");
setReason("手動調整庫存");
}
}, [isOpen]);
const handleConfirm = () => {
const numQty = parseFloat(quantity);
if (isNaN(numQty) || numQty <= 0 && operation !== "set") {
return;
}
onConfirm({
operation,
quantity: numQty,
reason,
});
};
const previewQuantity = () => {
if (!batch) return 0;
const numQty = parseFloat(quantity) || 0;
if (operation === "add") return batch.currentQuantity + numQty;
if (operation === "subtract") return Math.max(0, batch.currentQuantity - numQty);
if (operation === "set") return numQty;
return batch.currentQuantity;
};
if (!batch) return null;
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
調 - {batch.productName}
</DialogTitle>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="bg-gray-50 p-3 rounded-md border text-sm space-y-1">
<div className="flex justify-between">
<span className="text-gray-500"></span>
<span className="font-mono font-medium">{batch.batchNumber || "-"}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500"></span>
<span className="font-medium text-primary-main">{batch.currentQuantity}</span>
</div>
</div>
<div className="space-y-2">
<Label>調</Label>
<Select
value={operation}
onValueChange={(value: any) => setOperation(value)}
>
<SelectTrigger>
<SelectValue placeholder="選擇調整方式" />
</SelectTrigger>
<SelectContent>
<SelectItem value="add"> (+)</SelectItem>
<SelectItem value="subtract"> (-)</SelectItem>
<SelectItem value="set"> (=)</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="adj-qty"></Label>
<Input
id="adj-qty"
type="number"
step="0.01"
min="0"
value={quantity}
onChange={(e) => setQuantity(e.target.value)}
placeholder="請輸入數量"
/>
</div>
<div className="space-y-2">
<Label htmlFor="adj-reason">調</Label>
<Input
id="adj-reason"
value={reason}
onChange={(e) => setReason(e.target.value)}
placeholder="例:手動盤點修正"
/>
</div>
<div className="flex items-center gap-2 mt-2 p-3 bg-primary/5 rounded-md border border-primary/20 text-sm">
<AlertCircle className="h-4 w-4 text-primary-main" />
<span>
調
<span className="font-bold text-primary-main ml-1">
{previewQuantity()}
</span>
</span>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={onClose} disabled={processing}>
</Button>
<Button
onClick={handleConfirm}
disabled={processing || !quantity || parseFloat(quantity) < 0}
className="button-filled-primary"
>
調
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -1,19 +1,10 @@
/**
* 庫存表格元件 (扁平化列表版)
* 顯示庫存項目列表,不進行折疊分組
* 庫存表格元件 (Warehouse 版本)
* 顯示庫存項目列表(依商品分組並支援折疊)
*/
import { useState, useMemo } from "react";
import {
AlertTriangle,
Trash2,
Eye,
CheckCircle,
Package,
ArrowUpDown,
ArrowUp,
ArrowDown
} from "lucide-react";
import { useState } from "react";
import { AlertTriangle, Edit, Trash2, Eye, ChevronDown, ChevronRight, CheckCircle, Package } from "lucide-react";
import {
Table,
TableBody,
@@ -24,149 +15,87 @@ import {
} from "@/Components/ui/table";
import { Button } from "@/Components/ui/button";
import { Badge } from "@/Components/ui/badge";
import { WarehouseInventory } from "@/types/warehouse";
import { getSafetyStockStatus } from "@/utils/inventory";
import {
Collapsible,
CollapsibleContent,
} from "@/Components/ui/collapsible";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/Components/ui/tooltip";
import { GroupedInventory } from "@/types/warehouse";
import { formatDate } from "@/utils/format";
import { Can } from "@/Components/Permission/Can";
import BatchAdjustmentModal from "./BatchAdjustmentModal";
interface InventoryTableProps {
inventories: WarehouseInventory[];
inventories: GroupedInventory[];
onView: (id: string) => void;
onDelete: (id: string) => void;
onAdjust: (batchId: string, data: { operation: string; quantity: number; reason: string }) => void;
onViewProduct?: (productId: string) => void;
}
type SortField = "productName" | "quantity" | "lastInboundDate" | "lastOutboundDate" | "safetyStock" | "status";
type SortDirection = "asc" | "desc" | null;
export default function InventoryTable({
inventories,
onView,
onDelete,
onAdjust,
onViewProduct,
}: InventoryTableProps) {
const [sortField, setSortField] = useState<SortField | null>("status");
const [sortDirection, setSortDirection] = useState<SortDirection>("asc"); // "asc" for status means Priority High (Low Stock) first
// 每個商品的展開/折疊狀態
const [expandedProducts, setExpandedProducts] = useState<Set<string>>(new Set());
// 處理排序
const handleSort = (field: SortField) => {
if (sortField === field) {
if (sortDirection === "asc") {
setSortDirection("desc");
} else if (sortDirection === "desc") {
setSortDirection(null);
setSortField(null);
} else {
setSortDirection("asc");
}
} else {
setSortField(field);
setSortDirection("asc");
}
};
// 排序後的列表
const sortedInventories = useMemo(() => {
if (!sortField || !sortDirection) {
return inventories;
}
return [...inventories].sort((a, b) => {
let aValue: string | number;
let bValue: string | number;
// Status Priority map for sorting: Low > Near > Normal
const statusPriority: Record<string, number> = {
"低於": 1,
"接近": 2,
"正常": 3
};
switch (sortField) {
case "productName":
aValue = a.productName;
bValue = b.productName;
break;
case "quantity":
aValue = a.quantity;
bValue = b.quantity;
break;
case "lastInboundDate":
aValue = a.lastInboundDate || "";
bValue = b.lastInboundDate || "";
break;
case "lastOutboundDate":
aValue = a.lastOutboundDate || "";
bValue = b.lastOutboundDate || "";
break;
case "safetyStock":
aValue = a.safetyStock ?? -1; // null as -1 or Infinity depending on desired order
bValue = b.safetyStock ?? -1;
break;
case "status":
const aStatus = (a.safetyStock !== null && a.safetyStock !== undefined) ? getSafetyStockStatus(a.quantity, a.safetyStock) : "正常";
const bStatus = (b.safetyStock !== null && b.safetyStock !== undefined) ? getSafetyStockStatus(b.quantity, b.safetyStock) : "正常";
aValue = statusPriority[aStatus] || 3;
bValue = statusPriority[bStatus] || 3;
break;
default:
return 0;
}
if (typeof aValue === "string" && typeof bValue === "string") {
return sortDirection === "asc"
? aValue.localeCompare(bValue, "zh-TW")
: bValue.localeCompare(aValue, "zh-TW");
} else {
return sortDirection === "asc"
? (aValue as number) - (bValue as number)
: (bValue as number) - (aValue as number);
}
});
}, [inventories, sortField, sortDirection]);
const SortIcon = ({ field }: { field: SortField }) => {
if (sortField !== field) {
return <ArrowUpDown className="h-4 w-4 text-muted-foreground ml-1" />;
}
if (sortDirection === "asc") {
return <ArrowUp className="h-4 w-4 text-primary ml-1" />;
}
if (sortDirection === "desc") {
return <ArrowDown className="h-4 w-4 text-primary ml-1" />;
}
return <ArrowUpDown className="h-4 w-4 text-muted-foreground ml-1" />;
};
// 調整彈窗狀態
const [adjustmentTarget, setAdjustmentTarget] = useState<{
id: string;
batchNumber: string;
currentQuantity: number;
productName: string;
} | null>(null);
if (inventories.length === 0) {
return (
<div className="text-center py-12 text-gray-400">
<Package className="h-12 w-12 mx-auto mb-4 opacity-20" />
<p></p>
<p className="text-sm mt-1">調</p>
</div>
);
}
// 按商品名稱排序
const sortedInventories = [...inventories].sort((a, b) =>
a.productName.localeCompare(b.productName, "zh-TW")
);
const toggleProduct = (productId: string) => {
setExpandedProducts((prev) => {
const newSet = new Set(prev);
if (newSet.has(productId)) {
newSet.delete(productId);
} else {
newSet.add(productId);
}
return newSet;
});
};
// 獲取狀態徽章
const getStatusBadge = (quantity: number, safetyStock: number) => {
const status = getSafetyStockStatus(quantity, safetyStock);
const getStatusBadge = (status: string) => {
switch (status) {
case "正常":
return (
<Badge className="bg-green-100 text-green-700 border-green-300 hover:bg-green-100">
<Badge className="bg-green-100 text-green-700 border-green-300">
<CheckCircle className="mr-1 h-3 w-3" />
</Badge>
);
case "接近": // 數量 <= 安全庫存 * 1.2
case "低於":
return (
<Badge className="bg-yellow-100 text-yellow-700 border-yellow-300 hover:bg-yellow-100">
<AlertTriangle className="mr-1 h-3 w-3" />
</Badge>
);
case "低於": // 數量 < 安全庫存
return (
<Badge className="bg-orange-100 text-orange-700 border-orange-300 hover:bg-orange-100">
<Badge className="bg-red-100 text-red-700 border-red-300">
<AlertTriangle className="mr-1 h-3 w-3" />
</Badge>
@@ -177,127 +106,201 @@ export default function InventoryTable({
};
return (
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow className="bg-gray-50/50">
<TableHead className="w-[50px] text-center">#</TableHead>
<TableHead className="w-[25%]">
<button onClick={() => handleSort("productName")} className="flex items-center hover:text-gray-900">
<SortIcon field="productName" />
</button>
</TableHead>
<TableHead className="w-[10%] text-right">
<div className="flex justify-end">
<button onClick={() => handleSort("quantity")} className="flex items-center hover:text-gray-900">
<SortIcon field="quantity" />
</button>
</div>
</TableHead>
<TableHead className="w-[12%]">
<button onClick={() => handleSort("lastInboundDate")} className="flex items-center hover:text-gray-900">
<SortIcon field="lastInboundDate" />
</button>
</TableHead>
<TableHead className="w-[12%]">
<button onClick={() => handleSort("lastOutboundDate")} className="flex items-center hover:text-gray-900">
<SortIcon field="lastOutboundDate" />
</button>
</TableHead>
<TableHead className="w-[10%] text-right">
<div className="flex justify-end">
<button onClick={() => handleSort("safetyStock")} className="flex items-center hover:text-gray-900">
<SortIcon field="safetyStock" />
</button>
</div>
</TableHead>
<TableHead className="w-[10%] text-center">
<div className="flex justify-center">
<button onClick={() => handleSort("status")} className="flex items-center hover:text-gray-900">
<SortIcon field="status" />
</button>
</div>
</TableHead>
<TableHead className="w-[10%] text-center"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{sortedInventories.map((item, index) => (
<TableRow key={item.id}>
<TableCell className="text-gray-500 font-medium text-center">
{index + 1}
</TableCell>
{/* 商品資訊 */}
<TableCell>
<div className="flex flex-col">
<div className="font-medium text-gray-900">{item.productName}</div>
<div className="text-xs text-gray-500">{item.productCode}</div>
<TooltipProvider>
<div className="space-y-4 p-4">
{sortedInventories.map((group) => {
const totalQuantity = group.totalQuantity;
// 使用後端提供的狀態
const status = group.status;
const isLowStock = status === "低於";
const isExpanded = expandedProducts.has(group.productId);
const hasInventory = group.batches.length > 0;
return (
<Collapsible
key={group.productId}
open={isExpanded}
onOpenChange={() => toggleProduct(group.productId)}
>
<div className="border rounded-lg overflow-hidden">
{/* 商品標題 - 可點擊折疊 */}
<div
onClick={() => toggleProduct(group.productId)}
className={`px-4 py-3 border-b cursor-pointer hover:bg-gray-100 transition-colors ${isLowStock ? "bg-red-50" : "bg-gray-50"
}`}
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
{/* 折疊圖示 */}
{isExpanded ? (
<ChevronDown className="h-5 w-5 text-gray-600" />
) : (
<ChevronRight className="h-5 w-5 text-gray-600" />
)}
<h3 className="font-semibold text-gray-900">{group.productName}</h3>
<span className="text-sm text-gray-500">
{hasInventory ? `${group.batches.length} 個批號` : '無庫存'}
</span>
</div>
<div className="flex items-center gap-4">
<div className="text-sm">
<span className="text-gray-600">
<span className={`font-medium ${isLowStock ? "text-red-600" : "text-gray-900"}`}>{totalQuantity} </span>
</span>
</div>
{group.safetyStock !== null ? (
<>
<div className="text-sm">
<span className="text-gray-600">
<span className="font-medium text-gray-900">{group.safetyStock} </span>
</span>
</div>
<div>
{status && getStatusBadge(status)}
</div>
</>
) : (
<Badge variant="outline" className="text-gray-500">
</Badge>
)}
{onViewProduct && (
<Button
type="button"
variant="outline"
size="sm"
onClick={(e) => {
e.stopPropagation();
onViewProduct(group.productId);
}}
className="button-outlined-primary"
>
<Eye className="h-4 w-4" />
</Button>
)}
</div>
</div>
</div>
</TableCell>
{/* 庫存數量 */}
<TableCell className="text-right">
<span className="font-medium text-gray-900">{item.quantity}</span>
<span className="text-xs text-gray-500 ml-1">{item.unit}</span>
</TableCell>
{/* 商品表格 - 可折疊內容 */}
<CollapsibleContent>
{hasInventory ? (
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[5%]">#</TableHead>
<TableHead className="w-[12%]"></TableHead>
<TableHead className="w-[12%]"></TableHead>
<TableHead className="w-[15%]"></TableHead>
<TableHead className="w-[14%]"></TableHead>
<TableHead className="w-[14%]"></TableHead>
<TableHead className="w-[14%]"></TableHead>
<TableHead className="w-[8%] text-right"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{group.batches.map((batch, index) => {
return (
<TableRow key={batch.id}>
<TableCell className="text-grey-2">{index + 1}</TableCell>
<TableCell>{batch.batchNumber || "-"}</TableCell>
<TableCell>
<span>{batch.quantity}</span>
</TableCell>
<TableCell>{batch.batchNumber || "-"}</TableCell>
<TableCell>
{batch.expiryDate ? formatDate(batch.expiryDate) : "-"}
</TableCell>
<TableCell>
{batch.lastInboundDate ? formatDate(batch.lastInboundDate) : "-"}
</TableCell>
<TableCell>
{batch.lastOutboundDate ? formatDate(batch.lastOutboundDate) : "-"}
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => onView(batch.id)}
className="button-outlined-primary"
>
<Eye className="h-4 w-4" />
</Button>
<Can permission="inventory.adjust">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setAdjustmentTarget({
id: batch.id,
batchNumber: batch.batchNumber,
currentQuantity: batch.quantity,
productName: group.productName
})}
className="button-outlined-primary"
>
<Edit className="h-4 w-4" />
</Button>
</Can>
<Can permission="inventory.delete">
<Tooltip>
<TooltipTrigger asChild>
<div className="inline-block">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => onDelete(batch.id)}
className={batch.quantity > 0 ? "opacity-50 cursor-not-allowed border-gray-200 text-gray-400 hover:bg-transparent" : "button-outlined-error"}
disabled={batch.quantity > 0}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</TooltipTrigger>
<TooltipContent>
<p className="text-xs">{batch.quantity > 0 ? "庫存須為 0 才可刪除" : "刪除"}</p>
</TooltipContent>
</Tooltip>
</Can>
</div>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
) : (
<div className="px-4 py-8 text-center text-gray-400 bg-gray-50">
<Package className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm"></p>
<p className="text-xs mt-1"></p>
</div>
)}
</CollapsibleContent>
</div>
</Collapsible>
);
})}
{/* 最新入庫 */}
<TableCell className="text-gray-600">
{item.lastInboundDate ? formatDate(item.lastInboundDate) : "-"}
</TableCell>
{/* 最新出庫 */}
<TableCell className="text-gray-600">
{item.lastOutboundDate ? formatDate(item.lastOutboundDate) : "-"}
</TableCell>
{/* 安全庫存 */}
<TableCell className="text-right">
{item.safetyStock !== null && item.safetyStock >= 0 ? (
<span className="font-medium text-gray-900">
{item.safetyStock} <span className="text-xs text-gray-500 font-normal">{item.unit}</span>
</span>
) : (
<span className="text-gray-400 text-xs"></span>
)}
</TableCell>
{/* 狀態 */}
<TableCell className="text-center">
{(item.safetyStock !== null && item.safetyStock !== undefined) ? getStatusBadge(item.quantity, item.safetyStock) : (
<Badge variant="outline" className="text-gray-400 border-dashed"></Badge>
)}
</TableCell>
{/* 操作 */}
<TableCell className="text-center">
<div className="flex justify-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => onView(item.id)}
title="查看庫存流水帳"
className="button-outlined-primary"
>
<Eye className="h-4 w-4" />
</Button>
<Can permission="inventory.delete">
<Button
variant="outline"
size="sm"
onClick={() => onDelete(item.id)}
title="刪除"
className="button-outlined-error"
>
<Trash2 className="h-4 w-4" />
</Button>
</Can>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
<BatchAdjustmentModal
isOpen={!!adjustmentTarget}
onClose={() => setAdjustmentTarget(null)}
batch={adjustmentTarget || undefined}
onConfirm={(data) => {
if (adjustmentTarget) {
onAdjust(adjustmentTarget.id, data);
setAdjustmentTarget(null);
}
}}
/>
</div>
</TooltipProvider>
);
}

View File

@@ -8,13 +8,15 @@ export interface Transaction {
reason: string | null;
userName: string;
actualTime: string;
batchNumber?: string; // 商品層級查詢時顯示批號
}
interface TransactionTableProps {
transactions: Transaction[];
showBatchNumber?: boolean; // 是否顯示批號欄位
}
export default function TransactionTable({ transactions }: TransactionTableProps) {
export default function TransactionTable({ transactions, showBatchNumber = false }: TransactionTableProps) {
if (transactions.length === 0) {
return (
<div className="text-center py-8 text-gray-500">
@@ -23,6 +25,9 @@ export default function TransactionTable({ transactions }: TransactionTableProps
);
}
// 自動偵測是否需要顯示批號(如果任一筆記錄有 batchNumber
const shouldShowBatchNumber = showBatchNumber || transactions.some(tx => tx.batchNumber);
return (
<div className="overflow-x-auto">
<table className="w-full text-sm text-left">
@@ -30,6 +35,7 @@ export default function TransactionTable({ transactions }: TransactionTableProps
<tr>
<th className="px-4 py-3 w-[50px]">#</th>
<th className="px-4 py-3"></th>
{shouldShowBatchNumber && <th className="px-4 py-3"></th>}
<th className="px-4 py-3"></th>
<th className="px-4 py-3 text-right"></th>
<th className="px-4 py-3 text-right"></th>
@@ -42,6 +48,9 @@ export default function TransactionTable({ transactions }: TransactionTableProps
<tr key={tx.id} className="border-b hover:bg-gray-50">
<td className="px-4 py-3 text-center text-gray-500 font-medium">{index + 1}</td>
<td className="px-4 py-3 whitespace-nowrap">{tx.actualTime}</td>
{shouldShowBatchNumber && (
<td className="px-4 py-3 font-mono text-sm text-gray-600">{tx.batchNumber || '-'}</td>
)}
<td className="px-4 py-3">
<span className={`px-2 py-1 rounded-full text-xs ${tx.quantity > 0
? 'bg-green-100 text-green-800'

View File

@@ -4,15 +4,18 @@
*/
import { useState, useEffect } from "react";
import { Factory, Plus, Trash2, ArrowLeft, Save, AlertTriangle, Calendar } from 'lucide-react';
import { Factory, Plus, Trash2, ArrowLeft, Save, Calendar, AlertCircle } from 'lucide-react';
import { Button } from "@/Components/ui/button";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, router, useForm } from "@inertiajs/react";
import toast, { Toaster } from 'react-hot-toast';
import { getBreadcrumbs } from "@/utils/breadcrumb";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { Textarea } from "@/Components/ui/textarea";
import { Link } from "@inertiajs/react";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/Components/ui/table";
interface Product {
id: number;
@@ -42,16 +45,35 @@ interface InventoryOption {
arrival_date: string | null;
expiry_date: string | null;
unit_name: string | null;
base_unit_id?: number;
base_unit_name?: string;
large_unit_id?: number;
large_unit_name?: string;
conversion_rate?: number;
}
interface BomItem {
inventory_id: string;
quantity_used: string;
unit_id: string;
// 顯示用
product_name?: string;
batch_number?: string;
available_qty?: number;
// Backend required
inventory_id: string; // The selected inventory record ID (Specific Batch)
quantity_used: string; // The converted final quantity (Base Unit)
unit_id: string; // The unit ID (Base Unit ID usually)
// UI State
ui_warehouse_id: string; // Source Warehouse
ui_product_id: string; // Filter for batch list
ui_input_quantity: string; // User typed quantity
ui_selected_unit: 'base' | 'large'; // User selected unit
// UI Helpers / Cache
ui_product_name?: string;
ui_batch_number?: string;
ui_available_qty?: number;
ui_expiry_date?: string;
ui_conversion_rate?: number;
ui_base_unit_name?: string;
ui_large_unit_name?: string;
ui_base_unit_id?: number;
ui_large_unit_id?: number;
}
interface Props {
@@ -60,10 +82,12 @@ interface Props {
units: Unit[];
}
export default function ProductionCreate({ products, warehouses, units }: Props) {
const [selectedWarehouse, setSelectedWarehouse] = useState<string>("");
const [inventoryOptions, setInventoryOptions] = useState<InventoryOption[]>([]);
const [isLoadingInventory, setIsLoadingInventory] = useState(false);
export default function ProductionCreate({ products, warehouses }: Props) {
const [selectedWarehouse, setSelectedWarehouse] = useState<string>(""); // Output Warehouse
// Cache map: warehouse_id -> inventories
const [inventoryMap, setInventoryMap] = useState<Record<string, InventoryOption[]>>({});
const [loadingWarehouses, setLoadingWareStates] = useState<Record<string, boolean>>({});
const [bomItems, setBomItems] = useState<BomItem[]>([]);
const { data, setData, processing, errors } = useForm({
@@ -78,23 +102,23 @@ export default function ProductionCreate({ products, warehouses, units }: Props)
items: [] as { inventory_id: number; quantity_used: number; unit_id: number | null }[],
});
// 當選擇倉庫時,載入該倉庫的可用庫存
useEffect(() => {
if (selectedWarehouse) {
setIsLoadingInventory(true);
fetch(route('api.production.warehouses.inventories', selectedWarehouse))
.then(res => res.json())
.then((inventories: InventoryOption[]) => {
setInventoryOptions(inventories);
setIsLoadingInventory(false);
})
.catch(() => setIsLoadingInventory(false));
} else {
setInventoryOptions([]);
}
}, [selectedWarehouse]);
// Helper to fetch warehouse data
const fetchWarehouseInventory = async (warehouseId: string) => {
if (!warehouseId || inventoryMap[warehouseId] || loadingWarehouses[warehouseId]) return;
// 同步 warehouse_id 到 form data
setLoadingWareStates(prev => ({ ...prev, [warehouseId]: true }));
try {
const res = await fetch(route('api.production.warehouses.inventories', warehouseId));
const data = await res.json();
setInventoryMap(prev => ({ ...prev, [warehouseId]: data }));
} catch (e) {
console.error(e);
} finally {
setLoadingWareStates(prev => ({ ...prev, [warehouseId]: false }));
}
};
// 同步 warehouse_id 到 form data (Output)
useEffect(() => {
setData('warehouse_id', selectedWarehouse);
}, [selectedWarehouse]);
@@ -105,6 +129,10 @@ export default function ProductionCreate({ products, warehouses, units }: Props)
inventory_id: "",
quantity_used: "",
unit_id: "",
ui_warehouse_id: "",
ui_product_id: "",
ui_input_quantity: "",
ui_selected_unit: 'base',
}]);
};
@@ -113,45 +141,167 @@ export default function ProductionCreate({ products, warehouses, units }: Props)
setBomItems(bomItems.filter((_, i) => i !== index));
};
// 更新 BOM 項目
const updateBomItem = (index: number, field: keyof BomItem, value: string) => {
// 更新 BOM 項目邏輯
const updateBomItem = (index: number, field: keyof BomItem, value: any) => {
const updated = [...bomItems];
updated[index] = { ...updated[index], [field]: value };
const item = { ...updated[index], [field]: value };
// 如果選擇了庫存,自動填入顯示資訊
if (field === 'inventory_id' && value) {
const inv = inventoryOptions.find(i => String(i.id) === value);
if (inv) {
updated[index].product_name = inv.product_name;
updated[index].batch_number = inv.batch_number;
updated[index].available_qty = inv.quantity;
// 0. 當選擇來源倉庫變更時
if (field === 'ui_warehouse_id') {
// 重置後續欄位
item.ui_product_id = "";
item.inventory_id = "";
item.quantity_used = "";
item.unit_id = "";
item.ui_input_quantity = "";
item.ui_selected_unit = "base";
delete item.ui_product_name;
delete item.ui_batch_number;
delete item.ui_available_qty;
delete item.ui_expiry_date;
delete item.ui_conversion_rate;
delete item.ui_base_unit_name;
delete item.ui_large_unit_name;
delete item.ui_base_unit_id;
delete item.ui_large_unit_id;
// 觸發載入資料
if (value) {
fetchWarehouseInventory(value);
}
}
// 1. 當選擇商品變更時 -> 清空批號與相關資訊
if (field === 'ui_product_id') {
item.inventory_id = "";
item.quantity_used = "";
item.unit_id = "";
item.ui_input_quantity = "";
item.ui_selected_unit = "base";
// 清除 cache 資訊
delete item.ui_product_name;
delete item.ui_batch_number;
delete item.ui_available_qty;
delete item.ui_expiry_date;
delete item.ui_conversion_rate;
delete item.ui_base_unit_name;
delete item.ui_large_unit_name;
delete item.ui_base_unit_id;
delete item.ui_large_unit_id;
}
// 2. 當選擇批號 (Inventory ID) 變更時 -> 載入該批號資訊
if (field === 'inventory_id' && value) {
const currentOptions = inventoryMap[item.ui_warehouse_id] || [];
const inv = currentOptions.find(i => String(i.id) === value);
if (inv) {
item.ui_product_id = String(inv.product_id); // 確保商品也被選中 (雖通常是先選商品)
item.ui_product_name = inv.product_name;
item.ui_batch_number = inv.batch_number;
item.ui_available_qty = inv.quantity;
item.ui_expiry_date = inv.expiry_date || '';
// 單位與轉換率
item.ui_base_unit_name = inv.base_unit_name || inv.unit_name || '';
item.ui_large_unit_name = inv.large_unit_name || '';
item.ui_base_unit_id = inv.base_unit_id;
item.ui_large_unit_id = inv.large_unit_id;
item.ui_conversion_rate = inv.conversion_rate || 1;
// 預設單位
item.ui_selected_unit = 'base';
item.unit_id = String(inv.base_unit_id || '');
}
}
// 3. 計算最終數量 (Base Quantity)
// 當 輸入數量 或 選擇單位 變更時
if (field === 'ui_input_quantity' || field === 'ui_selected_unit' || field === 'inventory_id') {
const inputQty = parseFloat(item.ui_input_quantity || '0');
const rate = item.ui_conversion_rate || 1;
if (item.ui_selected_unit === 'large') {
item.quantity_used = String(inputQty * rate);
// 注意:後端需要的是 Base Unit ID? 這裡我們都送 Base Unit ID因為 quantity_used 是 Base Unit
// 但為了保留 User 的選擇,我們可能可以在 remark 註記? 目前先從簡
item.unit_id = String(item.ui_base_unit_id || '');
} else {
item.quantity_used = String(inputQty);
item.unit_id = String(item.ui_base_unit_id || '');
}
}
updated[index] = item;
setBomItems(updated);
};
// 產生成品批號建議
const generateBatchNumber = () => {
// 同步 BOM items 到表單 data
useEffect(() => {
setData('items', bomItems.map(item => ({
inventory_id: Number(item.inventory_id),
quantity_used: Number(item.quantity_used),
unit_id: item.unit_id ? Number(item.unit_id) : null
})));
}, [bomItems]);
// 自動產生成品批號(當選擇商品或日期變動時)
useEffect(() => {
if (!data.product_id) return;
const product = products.find(p => String(p.id) === data.product_id);
if (!product) return;
const date = data.production_date.replace(/-/g, '');
const suggested = `${product.code}-TW-${date}-01`;
setData('output_batch_number', suggested);
};
const datePart = data.production_date; // YYYY-MM-DD
const dateFormatted = datePart.replace(/-/g, '');
const originCountry = 'TW';
// 呼叫 API 取得下一組流水號
// 複用庫存批號 API但這裡可能沒有選 warehouse所以用第一個預設
const warehouseId = selectedWarehouse || (warehouses.length > 0 ? String(warehouses[0].id) : '1');
fetch(`/api/warehouses/${warehouseId}/inventory/batches/${product.id}?originCountry=${originCountry}&arrivalDate=${datePart}`)
.then(res => res.json())
.then(result => {
const seq = result.nextSequence || '01';
const suggested = `${product.code}-${originCountry}-${dateFormatted}-${seq}`;
setData('output_batch_number', suggested);
})
.catch(() => {
// Fallback若 API 失敗,使用預設 01
const suggested = `${product.code}-${originCountry}-${dateFormatted}-01`;
setData('output_batch_number', suggested);
});
}, [data.product_id, data.production_date]);
// 提交表單
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const submit = (status: 'draft' | 'completed') => {
// 驗證(簡單前端驗證,完整驗證在後端)
if (status === 'completed') {
const missingFields = [];
if (!data.product_id) missingFields.push('成品商品');
if (!data.output_quantity) missingFields.push('生產數量');
if (!data.output_batch_number) missingFields.push('成品批號');
if (!data.production_date) missingFields.push('生產日期');
if (!selectedWarehouse) missingFields.push('入庫倉庫');
if (bomItems.length === 0) missingFields.push('原物料明細');
if (missingFields.length > 0) {
toast.error(
<div className="flex flex-col gap-1">
<span className="font-bold"></span>
<span className="text-sm">{missingFields.join('、')}</span>
</div>
);
return;
}
}
// 轉換 BOM items 格式
const formattedItems = bomItems
.filter(item => item.inventory_id && item.quantity_used)
.filter(item => status === 'draft' || (item.inventory_id && item.quantity_used))
.map(item => ({
inventory_id: parseInt(item.inventory_id),
quantity_used: parseFloat(item.quantity_used),
inventory_id: item.inventory_id ? parseInt(item.inventory_id) : null,
quantity_used: item.quantity_used ? parseFloat(item.quantity_used) : 0,
unit_id: item.unit_id ? parseInt(item.unit_id) : null,
}));
@@ -159,33 +309,74 @@ export default function ProductionCreate({ products, warehouses, units }: Props)
router.post(route('production-orders.store'), {
...data,
items: formattedItems,
status: status,
}, {
onError: (errors) => {
const errorCount = Object.keys(errors).length;
toast.error(
<div className="flex flex-col gap-1">
<span className="font-bold"></span>
<span className="text-sm"> {errorCount} </span>
</div>
);
}
});
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
submit('completed');
};
return (
<AuthenticatedLayout breadcrumbs={getBreadcrumbs("productionOrdersCreate")}>
<Head title="建立生產單" />
<div className="container mx-auto p-6 max-w-4xl">
<div className="flex items-center gap-4 mb-6">
<Button
variant="ghost"
onClick={() => router.get(route('production-orders.index'))}
className="p-2"
>
<ArrowLeft className="h-5 w-5" />
</Button>
<div>
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<Factory className="h-6 w-6 text-primary-main" />
</h1>
<p className="text-gray-500 mt-1">
使
</p>
<Toaster position="top-right" />
<div className="container mx-auto p-6 max-w-7xl">
<div className="mb-6">
<Link href={route('production-orders.index')}>
<Button
variant="outline"
className="gap-2 button-outlined-primary mb-6"
>
<ArrowLeft className="h-4 w-4" />
</Button>
</Link>
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<Factory className="h-6 w-6 text-primary-main" />
</h1>
<p className="text-gray-500 mt-1">
</p>
</div>
<div className="flex gap-2">
<Button
onClick={() => submit('draft')}
disabled={processing}
variant="outline"
className="button-outlined-primary"
>
<Save className="mr-2 h-4 w-4" />
稿
</Button>
<Button
onClick={() => submit('completed')}
disabled={processing}
className="button-filled-primary"
>
<Factory className="mr-2 h-4 w-4" />
</Button>
</div>
</div>
</div>
<form onSubmit={handleSubmit}>
<form onSubmit={handleSubmit} className="space-y-6">
{/* 成品資訊 */}
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200 mb-6">
<h2 className="text-lg font-semibold mb-4"></h2>
@@ -220,23 +411,12 @@ export default function ProductionCreate({ products, warehouses, units }: Props)
<div className="space-y-1">
<Label className="text-xs font-medium text-grey-2"> *</Label>
<div className="flex gap-2">
<Input
value={data.output_batch_number}
onChange={(e) => setData('output_batch_number', e.target.value)}
placeholder="例如: AB-TW-20260121-01"
className="h-9 font-mono"
/>
<Button
type="button"
variant="outline"
onClick={generateBatchNumber}
disabled={!data.product_id}
className="h-9 button-outlined-primary shrink-0"
>
</Button>
</div>
<Input
value={data.output_batch_number}
onChange={(e) => setData('output_batch_number', e.target.value)}
placeholder="選擇商品後自動產生"
className="h-9 font-mono"
/>
{errors.output_batch_number && <p className="text-red-500 text-xs mt-1">{errors.output_batch_number}</p>}
</div>
@@ -313,7 +493,6 @@ export default function ProductionCreate({ products, warehouses, units }: Props)
type="button"
variant="outline"
onClick={addBomItem}
disabled={!selectedWarehouse}
className="gap-2 button-filled-primary text-white"
>
<Plus className="h-4 w-4" />
@@ -321,20 +500,7 @@ export default function ProductionCreate({ products, warehouses, units }: Props)
</Button>
</div>
{!selectedWarehouse && (
<div className="text-center py-8 text-gray-500">
<AlertTriangle className="h-8 w-8 mx-auto mb-2 text-yellow-500" />
</div>
)}
{selectedWarehouse && isLoadingInventory && (
<div className="text-center py-8 text-gray-500">
...
</div>
)}
{selectedWarehouse && !isLoadingInventory && bomItems.length === 0 && (
{bomItems.length === 0 && (
<div className="text-center py-8 text-gray-500">
<Factory className="h-8 w-8 mx-auto mb-2 text-gray-300" />
BOM
@@ -342,99 +508,125 @@ export default function ProductionCreate({ products, warehouses, units }: Props)
)}
{bomItems.length > 0 && (
<div className="space-y-4">
{bomItems.map((item, index) => (
<div
key={index}
className="grid grid-cols-1 md:grid-cols-12 gap-3 items-end p-4 bg-gray-50/50 border border-gray-100 rounded-lg relative group"
>
<div className="md:col-span-5 space-y-1">
<Label className="text-xs font-medium text-grey-2"> ()</Label>
<SearchableSelect
value={item.inventory_id}
onValueChange={(v) => updateBomItem(index, 'inventory_id', v)}
options={inventoryOptions.map(inv => ({
label: `${inv.product_name} - ${inv.batch_number} (庫存: ${inv.quantity})`,
value: String(inv.id),
}))}
placeholder="選擇原物料與批號"
className="w-full h-9"
/>
</div>
<div className="border rounded-lg overflow-hidden">
<Table>
<TableHeader>
<TableRow className="bg-gray-50/50">
<TableHead className="w-[20%]"> <span className="text-red-500">*</span></TableHead>
<TableHead className="w-[20%]"> <span className="text-red-500">*</span></TableHead>
<TableHead className="w-[25%]"> <span className="text-red-500">*</span></TableHead>
<TableHead className="w-[15%]"> <span className="text-red-500">*</span></TableHead>
<TableHead className="w-[15%]"></TableHead>
<TableHead className="w-[5%]"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{bomItems.map((item, index) => {
// 取得此列已載入的 Inventory Options
const currentOptions = inventoryMap[item.ui_warehouse_id] || [];
<div className="md:col-span-3 space-y-1">
<Label className="text-xs font-medium text-grey-2">使</Label>
<div className="relative">
<Input
type="number"
step="0.0001"
value={item.quantity_used}
onChange={(e) => updateBomItem(index, 'quantity_used', e.target.value)}
placeholder="0.00"
className="h-9 pr-12"
/>
<div className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-gray-400 pointer-events-none">
</div>
</div>
{item.available_qty && (
<p className="text-xs text-gray-400 mt-1">: {item.available_qty.toLocaleString()}</p>
)}
</div>
// 過濾商品
const uniqueProductOptions = Array.from(new Map(
currentOptions.map(inv => [inv.product_id, { label: inv.product_name, value: String(inv.product_id) }])
).values());
<div className="md:col-span-3 space-y-1">
<Label className="text-xs font-medium text-grey-2">/</Label>
<SearchableSelect
value={item.unit_id}
onValueChange={(v) => updateBomItem(index, 'unit_id', v)}
options={units.map(u => ({
label: u.name,
value: String(u.id),
}))}
placeholder="選擇單位"
className="w-full h-9"
/>
</div>
// 過濾批號
const batchOptions = currentOptions
.filter(inv => String(inv.product_id) === item.ui_product_id)
.map(inv => ({
label: `${inv.batch_number} / ${inv.expiry_date || '無效期'} / ${inv.quantity}`,
value: String(inv.id)
}));
<div className="md:col-span-1">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => removeBomItem(index)}
className="button-outlined-error h-9 w-full md:w-9 p-0"
title="移除此項目"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
))}
return (
<TableRow key={index}>
{/* 0. 選擇來源倉庫 */}
<TableCell className="align-top">
<SearchableSelect
value={item.ui_warehouse_id}
onValueChange={(v) => updateBomItem(index, 'ui_warehouse_id', v)}
options={warehouses.map(w => ({ label: w.name, value: String(w.id) }))}
placeholder="選擇倉庫"
className="w-full"
/>
</TableCell>
{/* 1. 選擇商品 */}
<TableCell className="align-top">
<SearchableSelect
value={item.ui_product_id}
onValueChange={(v) => updateBomItem(index, 'ui_product_id', v)}
options={uniqueProductOptions}
placeholder="選擇商品"
className="w-full"
disabled={!item.ui_warehouse_id}
/>
</TableCell>
{/* 2. 選擇批號 */}
<TableCell className="align-top">
<SearchableSelect
value={item.inventory_id}
onValueChange={(v) => updateBomItem(index, 'inventory_id', v)}
options={batchOptions}
placeholder={item.ui_product_id ? "選擇批號" : "請先選商品"}
className="w-full"
disabled={!item.ui_product_id}
/>
{item.inventory_id && (() => {
const selectedInv = currentOptions.find(i => String(i.id) === item.inventory_id);
if (selectedInv) return (
<div className="text-xs text-gray-500 mt-1">
: {selectedInv.expiry_date || '無'} | : {selectedInv.quantity}
</div>
);
return null;
})()}
</TableCell>
{/* 3. 輸入數量 */}
<TableCell className="align-top">
<Input
type="number"
step="1"
value={item.ui_input_quantity}
onChange={(e) => updateBomItem(index, 'ui_input_quantity', e.target.value)}
placeholder="0"
className="h-9"
disabled={!item.inventory_id}
/>
</TableCell>
{/* 4. 選擇單位 */}
<TableCell className="align-top pt-3">
<span className="text-sm">{item.ui_base_unit_name}</span>
</TableCell>
<TableCell className="align-top">
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => removeBomItem(index)}
className="text-red-500 hover:text-red-700 hover:bg-red-50 p-2"
>
<Trash2 className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
)}
{errors.items && <p className="text-red-500 text-sm mt-2">{errors.items}</p>}
</div>
{/* 提交按鈕 */}
<div className="flex justify-end gap-3">
<Button
type="button"
variant="outline"
onClick={() => router.get(route('production-orders.index'))}
className="h-10 px-6"
>
</Button>
<Button
type="submit"
disabled={processing || bomItems.length === 0}
className="gap-2 button-filled-primary h-10 px-8"
>
<Save className="h-4 w-4" />
{processing ? '處理中...' : '建立生產單'}
</Button>
</div>
</form>
</div>
</AuthenticatedLayout>

View File

@@ -0,0 +1,710 @@
/**
* 編輯生產工單頁面
* 僅限草稿狀態可編輯
*/
import { useState, useEffect } from "react";
import { Factory, Plus, Trash2, ArrowLeft, Save, Calendar } from 'lucide-react';
import { Button } from "@/Components/ui/button";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, router, useForm, Link } from "@inertiajs/react";
import toast, { Toaster } from 'react-hot-toast';
import { getBreadcrumbs } from "@/utils/breadcrumb";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { Textarea } from "@/Components/ui/textarea";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/Components/ui/table";
interface Product {
id: number;
name: string;
code: string;
base_unit?: { id: number; name: string } | null;
}
interface Warehouse {
id: number;
name: string;
}
interface Unit {
id: number;
name: string;
}
interface InventoryOption {
id: number;
product_id: number;
product_name: string;
product_code: string;
batch_number: string;
box_number: string | null;
quantity: number;
arrival_date: string | null;
expiry_date: string | null;
unit_name: string | null;
base_unit_id?: number;
base_unit_name?: string;
large_unit_id?: number;
large_unit_name?: string;
conversion_rate?: number;
}
interface BomItem {
// Backend required
inventory_id: string;
quantity_used: string;
unit_id: string;
// UI State
ui_warehouse_id: string; // Source Warehouse
ui_product_id: string;
ui_input_quantity: string;
ui_selected_unit: 'base' | 'large';
// UI Helpers / Cache
ui_product_name?: string;
ui_batch_number?: string;
ui_available_qty?: number;
ui_expiry_date?: string;
ui_conversion_rate?: number;
ui_base_unit_name?: string;
ui_large_unit_name?: string;
ui_base_unit_id?: number;
ui_large_unit_id?: number;
}
interface ProductionOrderItem {
id: number;
production_order_id: number;
inventory_id: number;
quantity_used: number;
unit_id: number | null;
inventory?: {
product_id: number;
product?: {
name: string;
code: string;
base_unit?: { name: string };
};
batch_number: string;
quantity: number;
expiry_date?: string;
warehouse_id?: number;
};
unit?: {
name: string;
};
}
interface ProductionOrder {
id: number;
code: string;
product_id: number;
warehouse_id: number | null;
output_quantity: number;
output_batch_number: string;
output_box_count: string | null;
production_date: string;
expiry_date: string | null;
remark: string | null;
status: string;
items: ProductionOrderItem[];
product?: Product;
warehouse?: Warehouse;
}
interface Props {
productionOrder: ProductionOrder;
products: Product[];
warehouses: Warehouse[];
units: Unit[];
}
export default function ProductionEdit({ productionOrder, products, warehouses }: Props) {
// 日期格式轉換輔助函數
const formatDate = (dateValue: string | null | undefined): string => {
if (!dateValue) return '';
// 處理可能的 ISO 格式或 YYYY-MM-DD 格式
const date = new Date(dateValue);
if (isNaN(date.getTime())) return dateValue;
return date.toISOString().split('T')[0];
};
const [selectedWarehouse, setSelectedWarehouse] = useState<string>(
productionOrder.warehouse_id ? String(productionOrder.warehouse_id) : ""
); // Output Warehouse
// Cache map: warehouse_id -> inventories
const [inventoryMap, setInventoryMap] = useState<Record<string, InventoryOption[]>>({});
const [loadingWarehouses, setLoadingWareStates] = useState<Record<string, boolean>>({});
// Helper to fetch warehouse data
const fetchWarehouseInventory = async (warehouseId: string) => {
if (!warehouseId || inventoryMap[warehouseId] || loadingWarehouses[warehouseId]) return;
setLoadingWareStates(prev => ({ ...prev, [warehouseId]: true }));
try {
const res = await fetch(route('api.production.warehouses.inventories', warehouseId));
const data = await res.json();
setInventoryMap(prev => ({ ...prev, [warehouseId]: data }));
} catch (e) {
console.error(e);
} finally {
setLoadingWareStates(prev => ({ ...prev, [warehouseId]: false }));
}
};
// 初始化 BOM items
const initialBomItems: BomItem[] = productionOrder.items.map(item => ({
inventory_id: String(item.inventory_id),
quantity_used: String(item.quantity_used),
unit_id: item.unit_id ? String(item.unit_id) : "",
// UI Initial State (復原)
ui_warehouse_id: item.inventory?.warehouse_id ? String(item.inventory.warehouse_id) : "",
ui_product_id: item.inventory ? String(item.inventory.product_id) : "",
ui_input_quantity: String(item.quantity_used), // 假設已存的資料是基本單位
ui_selected_unit: 'base',
// UI Helpers
ui_product_name: item.inventory?.product?.name,
ui_batch_number: item.inventory?.batch_number,
ui_available_qty: item.inventory?.quantity,
ui_expiry_date: item.inventory?.expiry_date,
}));
const [bomItems, setBomItems] = useState<BomItem[]>(initialBomItems);
const { data, setData, processing, errors } = useForm({
product_id: String(productionOrder.product_id),
warehouse_id: productionOrder.warehouse_id ? String(productionOrder.warehouse_id) : "",
output_quantity: productionOrder.output_quantity ? String(productionOrder.output_quantity) : "",
output_batch_number: productionOrder.output_batch_number || "",
output_box_count: productionOrder.output_box_count || "",
production_date: formatDate(productionOrder.production_date) || new Date().toISOString().split('T')[0],
expiry_date: formatDate(productionOrder.expiry_date),
remark: productionOrder.remark || "",
items: [] as { inventory_id: number; quantity_used: number; unit_id: number | null }[],
});
// 初始化載入既有 BOM 的來源倉庫資料
useEffect(() => {
initialBomItems.forEach(item => {
if (item.ui_warehouse_id) {
fetchWarehouseInventory(item.ui_warehouse_id);
}
});
}, []);
// 當 inventoryOptions (Map) 載入後,更新現有 BOM items 的詳細資訊 (如單位、轉換率)
// 監聽 inventoryMap 變更
useEffect(() => {
setBomItems(prevItems => prevItems.map(item => {
if (item.ui_warehouse_id && inventoryMap[item.ui_warehouse_id] && item.inventory_id && !item.ui_conversion_rate) {
const inv = inventoryMap[item.ui_warehouse_id].find(i => String(i.id) === item.inventory_id);
if (inv) {
return {
...item,
ui_product_id: String(inv.product_id),
ui_product_name: inv.product_name,
ui_batch_number: inv.batch_number,
ui_available_qty: inv.quantity,
ui_expiry_date: inv.expiry_date || '',
ui_base_unit_name: inv.base_unit_name || inv.unit_name || '',
ui_large_unit_name: inv.large_unit_name || '',
ui_base_unit_id: inv.base_unit_id,
ui_large_unit_id: inv.large_unit_id,
ui_conversion_rate: inv.conversion_rate || 1,
};
}
}
return item;
}));
}, [inventoryMap]);
// 同步 warehouse_id 到 form data
useEffect(() => {
setData('warehouse_id', selectedWarehouse);
}, [selectedWarehouse]);
// 新增 BOM 項目
const addBomItem = () => {
setBomItems([...bomItems, {
inventory_id: "",
quantity_used: "",
unit_id: "",
ui_warehouse_id: "",
ui_product_id: "",
ui_input_quantity: "",
ui_selected_unit: 'base',
}]);
};
// 移除 BOM 項目
const removeBomItem = (index: number) => {
setBomItems(bomItems.filter((_, i) => i !== index));
};
// 更新 BOM 項目邏輯
const updateBomItem = (index: number, field: keyof BomItem, value: any) => {
const updated = [...bomItems];
const item = { ...updated[index], [field]: value };
// 0. 當選擇來源倉庫變更時
if (field === 'ui_warehouse_id') {
item.ui_product_id = "";
item.inventory_id = "";
item.quantity_used = "";
item.unit_id = "";
item.ui_input_quantity = "";
item.ui_selected_unit = "base";
delete item.ui_product_name;
delete item.ui_batch_number;
delete item.ui_available_qty;
delete item.ui_expiry_date;
delete item.ui_conversion_rate;
delete item.ui_base_unit_name;
delete item.ui_large_unit_name;
delete item.ui_base_unit_id;
delete item.ui_large_unit_id;
if (value) {
fetchWarehouseInventory(value);
}
}
// 1. 當選擇商品變更時 -> 清空批號與相關資訊
if (field === 'ui_product_id') {
item.inventory_id = "";
item.quantity_used = "";
item.unit_id = "";
item.ui_input_quantity = "";
item.ui_selected_unit = "base";
delete item.ui_product_name;
delete item.ui_batch_number;
delete item.ui_available_qty;
delete item.ui_expiry_date;
delete item.ui_conversion_rate;
delete item.ui_base_unit_name;
delete item.ui_large_unit_name;
delete item.ui_base_unit_id;
delete item.ui_large_unit_id;
}
// 2. 當選擇批號變更時
if (field === 'inventory_id' && value) {
const currentOptions = inventoryMap[item.ui_warehouse_id] || [];
const inv = currentOptions.find(i => String(i.id) === value);
if (inv) {
item.ui_product_id = String(inv.product_id);
item.ui_product_name = inv.product_name;
item.ui_batch_number = inv.batch_number;
item.ui_available_qty = inv.quantity;
item.ui_expiry_date = inv.expiry_date || '';
item.ui_base_unit_name = inv.base_unit_name || inv.unit_name || '';
item.ui_large_unit_name = inv.large_unit_name || '';
item.ui_base_unit_id = inv.base_unit_id;
item.ui_large_unit_id = inv.large_unit_id;
item.ui_conversion_rate = inv.conversion_rate || 1;
item.ui_selected_unit = 'base';
item.unit_id = String(inv.base_unit_id || '');
}
}
// 3. 計算最終數量
if (field === 'ui_input_quantity' || field === 'ui_selected_unit' || field === 'inventory_id') {
const inputQty = parseFloat(item.ui_input_quantity || '0');
const rate = item.ui_conversion_rate || 1;
if (item.ui_selected_unit === 'large') {
item.quantity_used = String(inputQty * rate);
item.unit_id = String(item.ui_base_unit_id || '');
} else {
item.quantity_used = String(inputQty);
item.unit_id = String(item.ui_base_unit_id || '');
}
}
updated[index] = item;
setBomItems(updated);
};
// 同步 BOM items 到表單 data
useEffect(() => {
setData('items', bomItems.map(item => ({
inventory_id: Number(item.inventory_id),
quantity_used: Number(item.quantity_used),
unit_id: item.unit_id ? Number(item.unit_id) : null
})));
}, [bomItems]);
// 提交表單(完成模式)
// 提交表單(完成模式)
// 提交表單(完成模式)
const submit = (status: 'draft' | 'completed') => {
// 驗證(簡單前端驗證)
if (status === 'completed') {
const missingFields = [];
if (!data.product_id) missingFields.push('成品商品');
if (!data.output_quantity) missingFields.push('生產數量');
if (!data.output_batch_number) missingFields.push('成品批號');
if (!data.production_date) missingFields.push('生產日期');
if (!selectedWarehouse) missingFields.push('入庫倉庫');
if (bomItems.length === 0) missingFields.push('原物料明細');
if (missingFields.length > 0) {
toast.error(
<div className="flex flex-col gap-1">
<span className="font-bold"></span>
<span className="text-sm">{missingFields.join('、')}</span>
</div>
);
return;
}
}
const formattedItems = bomItems
.filter(item => status === 'draft' || (item.inventory_id && item.quantity_used))
.map(item => ({
inventory_id: item.inventory_id ? parseInt(item.inventory_id) : null,
quantity_used: item.quantity_used ? parseFloat(item.quantity_used) : 0,
unit_id: item.unit_id ? parseInt(item.unit_id) : null,
}));
router.put(route('production-orders.update', productionOrder.id), {
...data,
items: formattedItems,
status: status,
}, {
onError: (errors) => {
const errorCount = Object.keys(errors).length;
toast.error(
<div className="flex flex-col gap-1">
<span className="font-bold"></span>
<span className="text-sm"> {errorCount} </span>
</div>
);
}
});
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
submit('completed');
};
return (
<AuthenticatedLayout breadcrumbs={getBreadcrumbs("productionOrdersCreate")}>
<Head title={`編輯生產單 - ${productionOrder.code}`} />
<Toaster position="top-right" />
<div className="container mx-auto p-6 max-w-7xl">
<div className="mb-6">
<Link href={route('production-orders.index')}>
<Button
variant="outline"
className="gap-2 button-outlined-primary mb-6"
>
<ArrowLeft className="h-4 w-4" />
</Button>
</Link>
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<Factory className="h-6 w-6 text-primary-main" />
</h1>
<p className="text-gray-500 mt-1">
</p>
</div>
<div className="flex gap-2">
<Button
onClick={() => submit('draft')}
disabled={processing}
variant="outline"
className="button-outlined-primary"
>
<Save className="mr-2 h-4 w-4" />
稿
</Button>
<Button
onClick={() => submit('completed')}
disabled={processing}
className="button-filled-primary"
>
<Factory className="mr-2 h-4 w-4" />
</Button>
</div>
</div>
</div>
<form onSubmit={handleSubmit} className="space-y-6">
{/* 成品資訊 */}
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200 mb-6">
<h2 className="text-lg font-semibold mb-4"></h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-1">
<Label className="text-xs font-medium text-grey-2"> *</Label>
<SearchableSelect
value={data.product_id}
onValueChange={(v) => setData('product_id', v)}
options={products.map(p => ({
label: `${p.name} (${p.code})`,
value: String(p.id),
}))}
placeholder="選擇成品"
className="w-full h-9"
/>
{errors.product_id && <p className="text-red-500 text-xs mt-1">{errors.product_id}</p>}
</div>
<div className="space-y-1">
<Label className="text-xs font-medium text-grey-2"> *</Label>
<Input
type="number"
step="0.01"
value={data.output_quantity}
onChange={(e) => setData('output_quantity', e.target.value)}
placeholder="例如: 50"
className="h-9"
/>
{errors.output_quantity && <p className="text-red-500 text-xs mt-1">{errors.output_quantity}</p>}
</div>
<div className="space-y-1">
<Label className="text-xs font-medium text-grey-2"> *</Label>
<Input
value={data.output_batch_number}
onChange={(e) => setData('output_batch_number', e.target.value)}
placeholder="例如: AB-TW-20260122-01"
className="h-9 font-mono"
/>
{errors.output_batch_number && <p className="text-red-500 text-xs mt-1">{errors.output_batch_number}</p>}
</div>
<div className="space-y-1">
<Label className="text-xs font-medium text-grey-2"></Label>
<Input
value={data.output_box_count}
onChange={(e) => setData('output_box_count', e.target.value)}
placeholder="例如: 10"
className="h-9"
/>
</div>
<div className="space-y-1">
<Label className="text-xs font-medium text-grey-2"> *</Label>
<div className="relative">
<Calendar className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
<Input
type="date"
value={data.production_date}
onChange={(e) => setData('production_date', e.target.value)}
className="h-9 pl-9"
/>
</div>
{errors.production_date && <p className="text-red-500 text-xs mt-1">{errors.production_date}</p>}
</div>
<div className="space-y-1">
<Label className="text-xs font-medium text-grey-2"></Label>
<div className="relative">
<Calendar className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
<Input
type="date"
value={data.expiry_date}
onChange={(e) => setData('expiry_date', e.target.value)}
className="h-9 pl-9"
/>
</div>
</div>
<div className="space-y-1">
<Label className="text-xs font-medium text-grey-2"> *</Label>
<SearchableSelect
value={selectedWarehouse}
onValueChange={setSelectedWarehouse}
options={warehouses.map(w => ({
label: w.name,
value: String(w.id),
}))}
placeholder="選擇倉庫"
className="w-full h-9"
/>
{errors.warehouse_id && <p className="text-red-500 text-xs mt-1">{errors.warehouse_id}</p>}
</div>
</div>
<div className="mt-4 space-y-1">
<Label className="text-xs font-medium text-grey-2"></Label>
<Textarea
value={data.remark}
onChange={(e) => setData('remark', e.target.value)}
placeholder="生產備註..."
rows={2}
className="resize-none"
/>
</div>
</div>
{/* BOM 原物料明細 */}
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200 mb-6">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold">使 (BOM)</h2>
<Button
type="button"
variant="outline"
onClick={addBomItem}
className="gap-2 button-filled-primary text-white"
>
<Plus className="h-4 w-4" />
</Button>
</div>
{bomItems.length === 0 && (
<div className="text-center py-8 text-gray-500">
<Factory className="h-8 w-8 mx-auto mb-2 text-gray-300" />
BOM
</div>
)}
{bomItems.length > 0 && (
<div className="border rounded-lg overflow-hidden">
<Table>
<TableHeader>
<TableRow className="bg-gray-50/50">
<TableHead className="w-[20%]"> <span className="text-red-500">*</span></TableHead>
<TableHead className="w-[20%]"> <span className="text-red-500">*</span></TableHead>
<TableHead className="w-[25%]"> <span className="text-red-500">*</span></TableHead>
<TableHead className="w-[15%]"> <span className="text-red-500">*</span></TableHead>
<TableHead className="w-[15%]"></TableHead>
<TableHead className="w-[5%]"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{bomItems.map((item, index) => {
// 取得此列已載入的 Inventory Options
const currentOptions = inventoryMap[item.ui_warehouse_id] || [];
const uniqueProductOptions = Array.from(new Map(
currentOptions.map(inv => [inv.product_id, { label: inv.product_name, value: String(inv.product_id) }])
).values());
// Fallback for initial state before fetch
const displayProductOptions = uniqueProductOptions.length > 0 ? uniqueProductOptions : (item.ui_product_name ? [{ label: item.ui_product_name, value: item.ui_product_id }] : []);
const batchOptions = currentOptions
.filter(inv => String(inv.product_id) === item.ui_product_id)
.map(inv => ({
label: `${inv.batch_number} / ${inv.expiry_date || '無效期'} / ${inv.quantity}`,
value: String(inv.id)
}));
// Fallback
const displayBatchOptions = batchOptions.length > 0 ? batchOptions : (item.inventory_id && item.ui_batch_number ? [{ label: item.ui_batch_number, value: item.inventory_id }] : []);
return (
<TableRow key={index}>
{/* 0. 選擇來源倉庫 */}
<TableCell className="align-top">
<SearchableSelect
value={item.ui_warehouse_id}
onValueChange={(v) => updateBomItem(index, 'ui_warehouse_id', v)}
options={warehouses.map(w => ({ label: w.name, value: String(w.id) }))}
placeholder="選擇倉庫"
className="w-full"
/>
</TableCell>
{/* 1. 選擇商品 */}
<TableCell className="align-top">
<SearchableSelect
value={item.ui_product_id}
onValueChange={(v) => updateBomItem(index, 'ui_product_id', v)}
options={displayProductOptions}
placeholder="選擇商品"
className="w-full"
disabled={!item.ui_warehouse_id}
/>
</TableCell>
{/* 2. 選擇批號 */}
<TableCell className="align-top">
<SearchableSelect
value={item.inventory_id}
onValueChange={(v) => updateBomItem(index, 'inventory_id', v)}
options={displayBatchOptions}
placeholder={item.ui_product_id ? "選擇批號" : "請先選商品"}
className="w-full"
disabled={!item.ui_product_id}
/>
{item.inventory_id && (() => {
const selectedInv = currentOptions.find(i => String(i.id) === item.inventory_id);
if (selectedInv) return (
<div className="text-xs text-gray-500 mt-1">
: {selectedInv.expiry_date || '無'} | : {selectedInv.quantity}
</div>
);
return null;
})()}
</TableCell>
{/* 3. 輸入數量 */}
<TableCell className="align-top">
<Input
type="number"
step="1"
value={item.ui_input_quantity}
onChange={(e) => updateBomItem(index, 'ui_input_quantity', e.target.value)}
placeholder="0"
className="h-9"
disabled={!item.inventory_id}
/>
</TableCell>
{/* 4. 選擇單位 */}
<TableCell className="align-top pt-3">
<span className="text-sm">{item.ui_base_unit_name}</span>
</TableCell>
<TableCell className="align-top">
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => removeBomItem(index)}
className="text-red-500 hover:text-red-700 hover:bg-red-50 p-2"
>
<Trash2 className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
)}
{errors.items && <p className="text-red-500 text-sm mt-2">{errors.items}</p>}
</div>
</form>
</div>
</AuthenticatedLayout>
);
}

View File

@@ -3,7 +3,7 @@
*/
import { useState, useEffect } from "react";
import { Plus, Factory, Search, RotateCcw, Eye } from 'lucide-react';
import { Plus, Factory, Search, RotateCcw, Eye, Pencil } from 'lucide-react';
import { Button } from "@/Components/ui/button";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, router, Link } from "@inertiajs/react";
@@ -239,15 +239,29 @@ export default function ProductionIndex({ productionOrders, filters }: Props) {
</Badge>
</TableCell>
<TableCell className="text-center">
<div className="flex items-center justify-center">
<div className="flex items-center justify-center gap-2">
{order.status === 'draft' && (
<Can permission="production_orders.edit">
<Link href={route('production-orders.edit', order.id)}>
<Button
variant="outline"
size="sm"
className="button-outlined-primary"
title="編輯"
>
<Pencil className="h-4 w-4" />
</Button>
</Link>
</Can>
)}
<Link href={route('production-orders.show', order.id)}>
<Button
variant="outline"
size="sm"
className="button-outlined-primary h-8"
className="button-outlined-primary"
title="檢視"
>
<Eye className="h-4 w-4 mr-1" />
<Eye className="h-4 w-4" />
</Button>
</Link>
</div>

View File

@@ -6,7 +6,7 @@
import { Factory, ArrowLeft, Package, Calendar, User, Warehouse, FileText, Link2 } from 'lucide-react';
import { Button } from "@/Components/ui/button";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, router, Link } from "@inertiajs/react";
import { Head, Link } from "@inertiajs/react";
import { getBreadcrumbs } from "@/utils/breadcrumb";
import { Badge } from "@/Components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/Components/ui/table";
@@ -61,27 +61,31 @@ export default function ProductionShow({ productionOrder }: Props) {
return (
<AuthenticatedLayout breadcrumbs={getBreadcrumbs("productionOrdersShow")}>
<Head title={`生產單 ${productionOrder.code}`} />
<div className="container mx-auto p-6 max-w-4xl">
<div className="flex items-center gap-4 mb-6">
<Button
variant="ghost"
onClick={() => router.get(route('production-orders.index'))}
className="p-2"
>
<ArrowLeft className="h-5 w-5" />
</Button>
<div className="flex-1">
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<Factory className="h-6 w-6 text-primary-main" />
{productionOrder.code}
</h1>
<p className="text-gray-500 mt-1">
</p>
<div className="container mx-auto p-6 max-w-7xl">
<div className="mb-6">
<Link href={route('production-orders.index')}>
<Button
variant="outline"
className="gap-2 button-outlined-primary mb-6"
>
<ArrowLeft className="h-4 w-4" />
</Button>
</Link>
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<Factory className="h-6 w-6 text-primary-main" />
{productionOrder.code}
</h1>
<p className="text-gray-500 mt-1">
</p>
</div>
<Badge variant={statusConfig[productionOrder.status]?.variant || "secondary"} className="text-sm">
{statusConfig[productionOrder.status]?.label || productionOrder.status}
</Badge>
</div>
<Badge variant={statusConfig[productionOrder.status]?.variant || "secondary"}>
{statusConfig[productionOrder.status]?.label || productionOrder.status}
</Badge>
</div>
{/* 成品資訊 */}

View File

@@ -2,7 +2,7 @@
* 新增庫存頁面(手動入庫)
*/
import { useState } from "react";
import { useState, useEffect } from "react";
import { Plus, Trash2, Calendar, ArrowLeft, Save, Boxes } from "lucide-react";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
@@ -27,11 +27,21 @@ import { getInventoryBreadcrumbs } from "@/utils/breadcrumb";
interface Product {
id: string;
name: string;
code: string;
baseUnit: string;
largeUnit?: string;
conversionRate?: number;
}
interface Batch {
inventoryId: string;
batchNumber: string;
originCountry: string;
expiryDate: string | null;
quantity: number;
isDeleted?: boolean;
}
interface Props {
warehouse: Warehouse;
products: Product[];
@@ -51,10 +61,61 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
const [notes, setNotes] = useState("");
const [items, setItems] = useState<InboundItem[]>([]);
const [errors, setErrors] = useState<Record<string, string>>({});
const [batchesCache, setBatchesCache] = useState<Record<string, { batches: Batch[], nextSequences: Record<string, string> }>>({});
// 取得商品批號與流水號
const fetchProductBatches = async (productId: string, originCountry?: string, arrivalDate?: string) => {
if (!productId) return;
const country = originCountry || 'TW';
const date = arrivalDate || inboundDate.split('T')[0];
const cacheKey = `${country}_${date}`;
// 如果該商品的批號列表尚未載入,強制載入
const existingCache = batchesCache[productId];
const hasBatches = existingCache && existingCache.batches.length >= 0 && existingCache.batches !== undefined;
const hasThisSequence = existingCache?.nextSequences?.[cacheKey];
// 若 batches 尚未載入,或特定條件的 sequence 尚未載入,則呼叫 API
if (!hasBatches || !hasThisSequence) {
try {
const response = await fetch(`/api/warehouses/${warehouse.id}/inventory/batches/${productId}?originCountry=${country}&arrivalDate=${date}`);
const data = await response.json();
setBatchesCache(prev => {
const existingProductCache = prev[productId] || { batches: [], nextSequences: {} };
return {
...prev,
[productId]: {
batches: data.batches,
nextSequences: {
...existingProductCache.nextSequences,
[cacheKey]: data.nextSequence
}
}
};
});
} catch (error) {
console.error("Failed to fetch batches", error);
}
}
};
// 當 items 變動、日期變動時,確保資料同步
useEffect(() => {
items.forEach(item => {
if (item.productId) {
// 無論 batchMode 為何,都要載入批號列表
// 若使用者切換到 new 模式,則額外傳入 originCountry 以取得正確流水號
const country = item.batchMode === 'new' ? item.originCountry : undefined;
fetchProductBatches(item.productId, country, inboundDate.split('T')[0]);
}
});
}, [items, inboundDate]);
// 新增明細行
const handleAddItem = () => {
const defaultProduct = products.length > 0 ? products[0] : { id: "", name: "", baseUnit: "個" };
const defaultProduct = products.length > 0 ? products[0] : { id: "", name: "", code: "", baseUnit: "個" };
const newItem: InboundItem = {
tempId: `temp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
productId: defaultProduct.id,
@@ -65,6 +126,8 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
largeUnit: defaultProduct.largeUnit,
conversionRate: defaultProduct.conversionRate,
selectedUnit: 'base',
batchMode: 'existing', // 預設選擇現有批號
originCountry: 'TW',
};
setItems([...items, newItem]);
};
@@ -96,6 +159,9 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
largeUnit: product.largeUnit,
conversionRate: product.conversionRate,
selectedUnit: 'base',
batchMode: 'existing',
inventoryId: undefined, // 清除已選擇的批號
expiryDate: undefined,
});
}
};
@@ -123,6 +189,12 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
if (item.quantity <= 0) {
newErrors[`item-${index}-quantity`] = "數量必須大於 0";
}
if (item.batchMode === 'existing' && !item.inventoryId) {
newErrors[`item-${index}-batch`] = "請選擇批號";
}
if (item.batchMode === 'new' && !item.originCountry) {
newErrors[`item-${index}-country`] = "新批號必須輸入產地";
}
});
setErrors(newErrors);
@@ -149,7 +221,9 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
return {
productId: item.productId,
quantity: finalQuantity,
batchNumber: item.batchNumber,
batchMode: item.batchMode,
inventoryId: item.inventoryId,
originCountry: item.originCountry,
expiryDate: item.expiryDate
};
})
@@ -165,6 +239,24 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
});
};
// 生成批號預覽
const getBatchPreview = (productId: string | undefined, productCode: string | undefined, country: string, dateStr: string) => {
if (!productCode || !productId) return "--";
try {
// 直接字串處理,避免時區問題且確保與 fetchProductBatches 的 key 一致
const datePart = dateStr.includes('T') ? dateStr.split('T')[0] : dateStr;
const [yyyy, mm, dd] = datePart.split('-');
const dateFormatted = `${yyyy}${mm}${dd}`;
const cacheKey = `${country}_${datePart}`;
const seq = batchesCache[productId]?.nextSequences?.[cacheKey] || "XX";
return `${productCode}-${country}-${dateFormatted}-${seq}`;
} catch (e) {
return "--";
}
};
return (
<AuthenticatedLayout breadcrumbs={getInventoryBreadcrumbs(warehouse.id, warehouse.name, "手動入庫")}>
<Head title={`新增庫存 - ${warehouse.name}`} />
@@ -301,17 +393,19 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
<Table>
<TableHeader>
<TableRow className="bg-gray-50/50">
<TableHead className="w-[280px]">
<TableHead className="w-[180px]">
<span className="text-red-500">*</span>
</TableHead>
<TableHead className="w-[120px]">
<TableHead className="w-[220px]">
<span className="text-red-500">*</span>
</TableHead>
<TableHead className="w-[100px]">
<span className="text-red-500">*</span>
</TableHead>
<TableHead className="w-[100px]"></TableHead>
<TableHead className="w-[150px]"></TableHead>
<TableHead className="w-[180px]"></TableHead>
<TableHead className="w-[220px]"></TableHead>
<TableHead className="w-[60px]"></TableHead>
<TableHead className="w-[90px]"></TableHead>
<TableHead className="w-[100px]"></TableHead>
<TableHead className="w-[140px]"></TableHead>
<TableHead className="w-[50px]"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -321,6 +415,9 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
? item.quantity * item.conversionRate
: item.quantity;
// Find product code
const product = products.find(p => p.id === item.productId);
return (
<TableRow key={item.tempId}>
{/* 商品 */}
@@ -342,6 +439,73 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
)}
</TableCell>
{/* 批號與產地控制 */}
<TableCell>
<div className="space-y-2">
<SearchableSelect
value={item.batchMode === 'new' ? 'new_batch' : (item.inventoryId || "")}
onValueChange={(value) => {
if (value === 'new_batch') {
handleUpdateItem(item.tempId, {
batchMode: 'new',
inventoryId: undefined,
originCountry: 'TW',
expiryDate: undefined
});
} else {
const selectedBatch = (batchesCache[item.productId]?.batches || []).find(b => b.inventoryId === value);
handleUpdateItem(item.tempId, {
batchMode: 'existing',
inventoryId: value,
originCountry: selectedBatch?.originCountry,
expiryDate: selectedBatch?.expiryDate || undefined
});
}
}}
options={[
{ label: "+ 建立新批號", value: "new_batch" },
...(batchesCache[item.productId]?.batches || []).map(b => ({
label: `${b.batchNumber} - 庫存: ${b.quantity}`,
value: b.inventoryId
}))
]}
placeholder="選擇或新增批號"
className="border-gray-300"
/>
{errors[`item-${index}-batch`] && (
<p className="text-xs text-red-500">
{errors[`item-${index}-batch`]}
</p>
)}
{item.batchMode === 'new' && (
<div className="flex items-center gap-2 mt-2">
<div className="flex-1">
<Input
value={item.originCountry || ""}
onChange={(e) => {
const val = e.target.value.toUpperCase().slice(0, 2);
handleUpdateItem(item.tempId, { originCountry: val });
}}
maxLength={2}
placeholder="產地"
className="h-8 text-xs text-center border-gray-300"
/>
</div>
<div className="flex-[3] text-xs bg-primary-50/50 text-primary-main px-2 py-1 rounded border border-primary-200/50 font-mono overflow-hidden whitespace-nowrap">
{getBatchPreview(item.productId, product?.code, item.originCountry || 'TW', inboundDate)}
</div>
</div>
)}
{item.batchMode === 'existing' && item.inventoryId && (
<div className="text-xs text-gray-500 px-2 font-mono">
: {item.expiryDate || '未設定'}
</div>
)}
</div>
</TableCell>
{/* 數量 */}
<TableCell>
<Input
@@ -408,30 +572,12 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
expiryDate: e.target.value,
})
}
className="border-gray-300 pl-9"
disabled={item.batchMode === 'existing'}
className={`border-gray-300 pl-9 ${item.batchMode === 'existing' ? 'bg-gray-50' : ''}`}
/>
</div>
</TableCell>
{/* 批號 */}
<TableCell>
<Input
value={item.batchNumber || ""}
onChange={(e) =>
handleUpdateItem(item.tempId, {
batchNumber: e.target.value,
})
}
className="border-gray-300"
placeholder="系統自動生成"
/>
{errors[`item-${index}-batch`] && (
<p className="text-xs text-red-500 mt-1">
{errors[`item-${index}-batch`]}
</p>
)}
</TableCell>
{/* 刪除按鈕 */}
<TableCell>
<Button

View File

@@ -94,8 +94,11 @@ export default function EditInventory({ warehouse, inventory, transactions = []
<Boxes className="h-6 w-6 text-primary-main" />
</h1>
<p className="text-gray-500 mt-1">
<span className="font-medium text-gray-900">{warehouse.name}</span>
<p className="text-gray-500 mt-1 flex gap-4">
<span><span className="font-medium text-gray-900">{warehouse.name}</span></span>
{inventory.batchNumber && (
<span><span className="font-medium text-blue-600 bg-blue-50 px-2 py-0.5 rounded border border-blue-100">{inventory.batchNumber}</span></span>
)}
</p>
</div>
<div className="flex gap-3">

View File

@@ -3,7 +3,7 @@ import { ArrowLeft, PackagePlus, AlertTriangle, Shield, Boxes } from "lucide-rea
import { Button } from "@/Components/ui/button";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, Link, router } from "@inertiajs/react";
import { Warehouse, WarehouseInventory, SafetyStockSetting, Product } from "@/types/warehouse";
import { Warehouse, GroupedInventory, SafetyStockSetting, Product } from "@/types/warehouse";
import InventoryToolbar from "@/Components/Warehouse/Inventory/InventoryToolbar";
import InventoryTable from "@/Components/Warehouse/Inventory/InventoryTable";
import { calculateLowStockCount } from "@/utils/inventory";
@@ -24,7 +24,7 @@ import { Can } from "@/Components/Permission/Can";
// 庫存頁面 Props
interface Props {
warehouse: Warehouse;
inventories: WarehouseInventory[];
inventories: GroupedInventory[];
safetyStockSettings: SafetyStockSetting[];
availableProducts: Product[];
}
@@ -41,17 +41,17 @@ export default function WarehouseInventoryPage({
// 篩選庫存列表
const filteredInventories = useMemo(() => {
return inventories.filter((item) => {
// 搜尋條件:匹配商品名稱、編號批號
return inventories.filter((group) => {
// 搜尋條件:匹配商品名稱、編號 或 該商品下任一批號
const matchesSearch = !searchTerm ||
item.productName.toLowerCase().includes(searchTerm.toLowerCase()) ||
(item.productCode && item.productCode.toLowerCase().includes(searchTerm.toLowerCase())) ||
item.batchNumber.toLowerCase().includes(searchTerm.toLowerCase());
group.productName.toLowerCase().includes(searchTerm.toLowerCase()) ||
(group.productCode && group.productCode.toLowerCase().includes(searchTerm.toLowerCase())) ||
group.batches.some(b => b.batchNumber.toLowerCase().includes(searchTerm.toLowerCase()));
// 類型篩選 (需要比對 availableProducts 找到類型)
let matchesType = true;
if (typeFilter !== "all") {
const product = availableProducts.find((p) => p.id === item.productId);
const product = availableProducts.find((p) => p.id === group.productId);
matchesType = product?.type === typeFilter;
}
@@ -60,13 +60,24 @@ export default function WarehouseInventoryPage({
}, [inventories, searchTerm, typeFilter, availableProducts]);
// 計算統計資訊
const lowStockItems = calculateLowStockCount(inventories, warehouse.id, safetyStockSettings);
const lowStockItems = useMemo(() => {
const allBatches = inventories.flatMap(g => g.batches);
return calculateLowStockCount(allBatches, warehouse.id, safetyStockSettings);
}, [inventories, warehouse.id, safetyStockSettings]);
// 導航至流動紀錄頁
const handleView = (inventoryId: string) => {
router.visit(route('warehouses.inventory.history', { warehouse: warehouse.id, inventoryId: inventoryId }));
};
// 導航至商品層級流動紀錄頁(顯示該商品所有批號的流水帳)
const handleViewProduct = (productId: string) => {
router.visit(route('warehouses.inventory.history', {
warehouse: warehouse.id,
productId: productId
}));
};
const confirmDelete = (inventoryId: string) => {
setDeleteId(inventoryId);
@@ -90,6 +101,17 @@ export default function WarehouseInventoryPage({
});
};
const handleAdjust = (batchId: string, data: { operation: string; quantity: number; reason: string }) => {
router.put(route("warehouses.inventory.update", { warehouse: warehouse.id, inventoryId: batchId }), data, {
onSuccess: () => {
toast.success("庫存已更新");
},
onError: () => {
toast.error("庫存更新失敗");
}
});
};
return (
<AuthenticatedLayout breadcrumbs={getInventoryBreadcrumbs(warehouse.id, warehouse.name)}>
<Head title={`庫存管理 - ${warehouse.name}`} />
@@ -158,7 +180,7 @@ export default function WarehouseInventoryPage({
</div>
{/* 篩選工具列 */}
<div className="mb-6 bg-white rounded-lg shadow-sm border p-4">
<div className="mb-6">
<InventoryToolbar
searchTerm={searchTerm}
onSearchChange={setSearchTerm}
@@ -173,6 +195,8 @@ export default function WarehouseInventoryPage({
inventories={filteredInventories}
onView={handleView}
onDelete={confirmDelete}
onAdjust={handleAdjust}
onViewProduct={handleViewProduct}
/>
</div>
<AlertDialog open={!!deleteId} onOpenChange={(open) => !open && setDeleteId(null)}>

View File

@@ -12,6 +12,7 @@ interface Props {
id: string;
productName: string;
productCode: string;
batchNumber?: string;
quantity: number;
};
transactions: Transaction[];
@@ -40,9 +41,12 @@ export default function InventoryHistory({ warehouse, inventory, transactions }:
<History className="h-6 w-6 text-primary-main" />
</h1>
<p className="text-gray-500 mt-1">
<span className="font-medium text-gray-900">{inventory.productName}</span>
{inventory.productCode && <span className="text-gray-500 ml-2">({inventory.productCode})</span>}
<p className="text-gray-500 mt-1 flex gap-4 items-center">
<span><span className="font-medium text-gray-900">{inventory.productName}</span></span>
{inventory.productCode && <span className="text-gray-500">({inventory.productCode})</span>}
{inventory.batchNumber && (
<span><span className="font-medium text-primary-main bg-primary-main/10 px-2 py-0.5 rounded border border-primary-main/20">{inventory.batchNumber}</span></span>
)}
</p>
</div>
</div>

View File

@@ -39,13 +39,25 @@ export interface WarehouseInventory {
unit: string;
quantity: number;
safetyStock: number | null;
status?: '正常' | '接近' | '低於'; // 後端可能回傳的狀態
status?: '正常' | '低於'; // 後端可能回傳的狀態
batchNumber: string; // 批號 (Mock for now)
expiryDate: string;
lastInboundDate: string | null;
lastOutboundDate: string | null;
}
// 依照商品分組的庫存項目 (用於庫存列表)
export interface GroupedInventory {
productId: string;
productName: string;
productCode: string;
baseUnit: string;
totalQuantity: number;
safetyStock: number | null; // 以商品層級顯示的安全庫存
status: '正常' | '低於';
batches: WarehouseInventory[]; // 該商品下的所有批號庫存
}
export type TransferOrderStatus = "待處理" | "處理中" | "已完成" | "已取消";
export interface TransferOrder {
@@ -151,7 +163,10 @@ export interface InboundItem {
largeUnit?: string;
conversionRate?: number;
selectedUnit?: 'base' | 'large';
batchMode?: 'existing' | 'new'; // 批號模式
inventoryId?: string; // 選擇現有批號時的 ID
batchNumber?: string;
originCountry?: string; // 新增產地
expiryDate?: string;
}

View File

@@ -36,10 +36,8 @@ export const getSafetyStockStatus = (
safetyStock: number | null | undefined
): SafetyStockStatus => {
if (!safetyStock || safetyStock === 0) return "正常";
const ratio = currentStock / safetyStock;
if (ratio >= 1.2) return "正常";
if (ratio >= 1.0) return "接近";
return "低於";
if (currentStock < safetyStock) return "低於";
return "正常";
};
/**