feat(Inventory): 實作批號溯源完整功能與 UI 呈現,包含文字敘述卡片與更完整的關聯屬性

This commit is contained in:
2026-02-26 10:39:24 +08:00
parent 63e4f88a14
commit f960aaaeb2
16 changed files with 1085 additions and 694 deletions

View File

@@ -278,6 +278,13 @@ export default function AuthenticatedLayout({
route: "/inventory/analysis",
permission: "inventory_report.view",
},
{
id: "inventory-traceability",
label: "批號溯源",
icon: <TrendingUp className="h-4 w-4" />,
route: "/inventory/traceability",
permission: "inventory_traceability.view",
},
],
},
{

View File

@@ -0,0 +1,150 @@
import { Info } from "lucide-react";
import { TraceabilityNode } from "./TreeView";
interface TraceabilitySummaryProps {
data: TraceabilityNode;
direction: 'forward' | 'backward';
}
export function TraceabilitySummary({ data, direction }: TraceabilitySummaryProps) {
if (!data) return null;
// --- Helper to extract unqiue names/codes from children ---
const getUniqueLabels = (nodes: TraceabilityNode[], prefixToStrip: string = '') => {
const labels = nodes
.map(n => n.label.replace(prefixToStrip, '').trim())
.filter(Boolean);
return Array.from(new Set(labels));
};
// --- Logic for Backward Tracing ---
if (direction === 'backward') {
const poNodes = data.children?.filter(c => c.type === 'production_order') || [];
const poNames = getUniqueLabels(poNodes, '生產工單:');
let materialNodes: TraceabilityNode[] = [];
let grNodes: TraceabilityNode[] = [];
poNodes.forEach(po => {
const materials = po.children?.filter(c => c.type === 'material_batch') || [];
materialNodes = [...materialNodes, ...materials];
materials.forEach(mat => {
const grs = mat.children?.filter(c => c.type === 'goods_receipt') || [];
grNodes = [...grNodes, ...grs];
});
});
const materialNames = getUniqueLabels(materialNodes, '原料批號:');
const grNames = getUniqueLabels(grNodes, '進貨單:');
// Handle case where batch is directly from Goods Receipt (no PO)
const directGrNodes = data.children?.filter(c => c.type === 'goods_receipt') || [];
if (directGrNodes.length > 0) {
grNodes = [...grNodes, ...directGrNodes];
const directGrNames = getUniqueLabels(directGrNodes, '進貨單:');
return (
<div className="bg-blue-50/50 border border-blue-100 rounded-xl p-4 mb-6 flex gap-3 text-gray-700 leading-relaxed shadow-sm">
<Info className="w-5 h-5 text-blue-500 shrink-0 mt-0.5" />
<div>
<p>
<strong className="text-gray-900">{data.batch_number}</strong>
{data.product_name && <span> ({data.product_name})</span>}
{directGrNames.map(n => <strong key={n} className="text-gray-900 mx-1">{n}</strong>).reduce((prev, curr) => [prev, '、', curr] as any)}
</p>
</div>
</div>
);
}
return (
<div className="bg-blue-50/50 border border-blue-100 rounded-xl p-4 mb-6 flex gap-3 text-gray-700 leading-relaxed shadow-sm">
<Info className="w-5 h-5 text-blue-500 shrink-0 mt-0.5" />
<div className="space-y-1.5">
<p>
<strong className="text-gray-900">{data.batch_number}</strong>
{data.product_name && <span> ({data.product_name})</span>}
{poNames.length > 0 ? (
<>
{poNames.slice(0, 3).map(n => <strong key={n} className="text-gray-900 mx-1">{n}</strong>).reduce((prev, curr) => [prev, '、', curr] as any)}
{poNames.length > 3 && `${poNames.length} 張工單`}
</>
) : (
'未知的生產工單產出。'
)}
</p>
{materialNodes.length > 0 && (
<p>
使 <strong className="text-gray-900">{materialNodes.length}</strong>
{materialNames.slice(0, 3).map(n => <strong key={n} className="text-gray-900 mx-1">{n}</strong>).reduce((prev, curr) => [prev, '、', curr] as any)}
{materialNames.length > 3 && ' 等'}
</p>
)}
{grNodes.length > 0 && (
<p>
{grNames.slice(0, 3).map(n => <strong key={n} className="text-gray-900 mx-1">{n}</strong>).reduce((prev, curr) => [prev, '、', curr] as any)}
{grNames.length > 3 && `${grNames.length} 張單據`}
</p>
)}
</div>
</div>
);
}
// --- Logic for Forward Tracing ---
if (direction === 'forward') {
const poNodes = data.children?.filter(c => c.type === 'production_order') || [];
const poNames = getUniqueLabels(poNodes, '投入工單:');
let targetNodes: TraceabilityNode[] = [];
let outNodes: TraceabilityNode[] = [];
poNodes.forEach(po => {
const targets = po.children?.filter(c => c.type === 'target_batch') || [];
targetNodes = [...targetNodes, ...targets];
targets.forEach(tgt => {
const outs = tgt.children?.filter(c => c.type === 'outbound_transaction') || [];
outNodes = [...outNodes, ...outs];
});
});
const targetNames = getUniqueLabels(targetNodes, '產出成品:');
const outNames = getUniqueLabels(outNodes, '出庫單據:');
return (
<div className="bg-blue-50/50 border border-blue-100 rounded-xl p-4 mb-6 flex gap-3 text-gray-700 leading-relaxed shadow-sm">
<Info className="w-5 h-5 text-blue-500 shrink-0 mt-0.5" />
<div className="space-y-1.5">
<p>
<strong className="text-gray-900">{data.batch_number}</strong>
{data.product_name && <span> ({data.product_name})</span>}
{poNames.length > 0 ? (
<>
{poNames.slice(0, 3).map(n => <strong key={n} className="text-gray-900 mx-1">{n}</strong>).reduce((prev, curr) => [prev, '、', curr] as any)}
{poNames.length > 3 && `${poNames.length} 張工單`}
</>
) : (
' 未知的生產工單。'
)}
</p>
{targetNodes.length > 0 && (
<p>
{targetNames.slice(0, 3).map(n => <strong key={n} className="text-gray-900 mx-1">{n}</strong>).reduce((prev, curr) => [prev, '、', curr] as any)}
{targetNames.length > 3 && `${targetNodes.length} 批成品`}
</p>
)}
{outNodes.length > 0 && (
<p>
{outNames.slice(0, 3).map(n => <strong key={n} className="text-gray-900 mx-1">{n}</strong>).reduce((prev, curr) => [prev, '、', curr] as any)}
{outNames.length > 3 && `${outNodes.length} 張單據`}
</p>
)}
</div>
</div>
);
}
return null;
}

View File

@@ -0,0 +1,168 @@
import { cn } from '@/lib/utils';
import { Package, Truck, Factory, CornerDownRight, Box, ShoppingCart } from 'lucide-react';
import { formatDate } from '@/lib/date';
export interface TraceabilityNode {
id: string;
type: 'target_batch' | 'source_batch' | 'production_order' | 'material_batch' | 'goods_receipt' | 'outbound_transaction';
label: string;
batch_number?: string;
date?: string;
vendor_id?: number | string;
product_name?: string;
spec?: string;
quantity?: number | string;
unit?: string;
warehouse_name?: string;
children?: TraceabilityNode[];
}
interface TreeViewProps {
data: TraceabilityNode;
}
const getNodeIcon = (type: TraceabilityNode['type']) => {
switch (type) {
case 'target_batch':
case 'source_batch':
return <Package className="h-5 w-5 text-primary-main" />;
case 'production_order':
return <Factory className="h-5 w-5 text-other-warning" />;
case 'material_batch':
return <Box className="h-5 w-5 text-primary-main" />;
case 'goods_receipt':
return <Truck className="h-5 w-5 text-other-info" />;
case 'outbound_transaction':
return <ShoppingCart className="h-5 w-5 text-other-success" />;
default:
return <Box className="h-5 w-5 text-gray-400" />;
}
};
const getNodeColor = (type: TraceabilityNode['type']) => {
switch (type) {
case 'target_batch':
case 'source_batch':
return 'border-primary-light bg-primary-lightest';
case 'production_order':
return 'border-orange-200 bg-orange-50';
case 'material_batch':
return 'border-primary-light bg-primary-lightest';
case 'goods_receipt':
return 'border-blue-200 bg-blue-50';
case 'outbound_transaction':
return 'border-emerald-200 bg-emerald-50';
default:
return 'border-gray-200 bg-gray-50';
}
};
const TreeNode = ({ node, isLast, level = 0 }: { node: TraceabilityNode; isLast: boolean; level?: number }) => {
const hasChildren = node.children && node.children.length > 0;
return (
<div className="relative">
{/* 連接線 (上層到此節點) */}
{level > 0 && (
<div
className={cn(
"absolute border-l-2 border-gray-200",
isLast ? "h-6 top-0" : "h-full top-0"
)}
style={{ left: '-1.5rem' }}
/>
)}
{/* 橫向連接線 */}
{level > 0 && (
<div
className="absolute border-t-2 border-gray-200 w-6 top-6"
style={{ left: '-1.5rem' }}
/>
)}
<div className="flex items-start mb-6">
{level > 0 && (
<div className="w-6 h-12 shrink-0 flex items-center justify-end pr-2 text-gray-400">
<CornerDownRight className="h-4 w-4" />
</div>
)}
<div className={cn(
"relative flex flex-col p-4 rounded-xl border shadow-sm min-w-[320px] max-w-md",
getNodeColor(node.type)
)}>
<div className="flex items-center gap-3">
<div className="p-2 bg-white rounded-lg shadow-sm shrink-0">
{getNodeIcon(node.type)}
</div>
<div className="flex-1 min-w-0">
<h4 className="font-semibold text-gray-900 truncate">{node.label}</h4>
{node.date && (
<div className="mt-0.5">
<span className="text-xs text-gray-500">{formatDate(node.date)}</span>
</div>
)}
</div>
</div>
{(node.product_name || node.warehouse_name || (node.quantity !== undefined && node.quantity !== null)) && (
<div className="mt-3 pt-3 border-t border-gray-200/60 flex flex-wrap gap-4">
{node.product_name && (
<div className="flex-1 min-w-[120px]">
<span className="text-[11px] text-gray-500 font-medium block mb-0.5"> / </span>
<span className="text-sm font-medium text-gray-800 leading-tight block truncate" title={`${node.product_name} ${node.spec ? `(${node.spec})` : ''}`}>
{node.product_name}
{node.spec && <span className="text-gray-400 text-xs ml-1">({node.spec})</span>}
</span>
</div>
)}
{node.warehouse_name && (
<div className="shrink-0 min-w-[80px]">
<span className="text-[11px] text-gray-500 font-medium block mb-0.5"></span>
<span className="text-sm font-medium text-gray-800 leading-tight block truncate" title={node.warehouse_name}>
{node.warehouse_name}
</span>
</div>
)}
{node.quantity !== undefined && node.quantity !== null && (
<div className="shrink-0 text-right min-w-[60px]">
<span className="text-[11px] text-gray-500 font-medium block mb-0.5"></span>
<span className="text-sm font-bold text-gray-900 block truncate">
{Number(node.quantity).toLocaleString()}
<span className="text-[10px] ml-0.5 text-gray-500 font-normal">{node.unit || 'PCS'}</span>
</span>
</div>
)}
</div>
)}
</div>
</div>
{hasChildren && (
<div className="pl-12 relative">
{node.children!.map((child, index) => (
<TreeNode
key={`${child.id} -${index} `}
node={child}
isLast={index === node.children!.length - 1}
level={level + 1}
/>
))}
</div>
)}
</div>
);
};
export default function TreeView({ data }: TreeViewProps) {
if (!data) return null;
return (
<div className="p-4 md:p-8 bg-gray-50/50 rounded-2xl border border-gray-100 overflow-x-auto">
<TreeNode node={data} isLast={true} level={0} />
</div>
);
}

View File

@@ -0,0 +1,154 @@
import React, { useState } from 'react';
import { Head, router } from '@inertiajs/react';
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { PageProps } from '@/types/global';
import { Card, CardContent, CardHeader, CardTitle } from '@/Components/ui/card';
import { Button } from '@/Components/ui/button';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { TrendingUp, Search, RotateCcw } from 'lucide-react';
import { RadioGroup, RadioGroupItem } from '@/Components/ui/radio-group';
import { cn } from '@/lib/utils';
import TreeView, { TraceabilityNode } from './Components/TreeView';
import { TraceabilitySummary } from './Components/TraceabilitySummary';
import { Can } from '@/Components/Permission/Can';
interface Props extends PageProps {
search: {
batch_number: string | null;
direction: 'backward' | 'forward';
};
result: TraceabilityNode | null;
}
export default function TraceabilityIndex({ search, result }: Props) {
const [batchNumber, setBatchNumber] = useState(search.batch_number || '');
const [direction, setDirection] = useState<'backward' | 'forward'>(search.direction || 'backward');
const [isSearching, setIsSearching] = useState(false);
const handleSearch = (e: React.FormEvent) => {
e.preventDefault();
if (!batchNumber.trim()) return;
setIsSearching(true);
router.get(
route('inventory.traceability.index'),
{ batch_number: batchNumber.trim(), direction },
{
preserveState: true,
preserveScroll: true,
onFinish: () => setIsSearching(false)
}
);
};
return (
<AuthenticatedLayout
breadcrumbs={[
{ label: '報表管理', href: '#' },
{ label: '批號溯源', href: route('inventory.traceability.index'), isPage: true },
]}
>
<Head title="批號溯源 - Star ERP" />
<div className="container mx-auto p-6 max-w-7xl">
<div className="mb-6">
<div className="mb-4">
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<TrendingUp className="h-6 w-6 text-primary-main" />
</h1>
<p className="text-gray-500 mt-1">
</p>
</div>
</div>
<Can permission="inventory.traceability.view">
<Card className="mb-6 bg-white shadow-sm border-gray-200">
<CardHeader className="pb-3 border-b border-gray-100 bg-gray-50/50">
<CardTitle className="text-lg flex items-center gap-2 text-gray-800">
<Search className="h-5 w-5 text-primary-main" />
</CardTitle>
</CardHeader>
<CardContent className="pt-6">
<form onSubmit={handleSearch} className="flex flex-col md:flex-row gap-6 items-start md:items-end">
<div className="flex-1 w-full space-y-1.5">
<Label htmlFor="batchNumber" className="text-sm font-medium text-grey-1"></Label>
<Input
id="batchNumber"
type="text"
placeholder="請輸入欲查詢的批號 (例如PROD-TW-20240101-01)"
value={batchNumber}
onChange={(e) => setBatchNumber(e.target.value)}
className="max-w-md w-full"
/>
</div>
<div className="space-y-3">
<Label className="text-gray-700 font-medium"></Label>
<RadioGroup
value={direction}
onValueChange={(val: 'backward' | 'forward') => setDirection(val)}
className="flex space-x-6"
>
<div
className={cn(
"flex items-center space-x-2 px-4 py-2 rounded-lg border cursor-pointer transition-colors",
direction === 'backward' ? "bg-primary-lightest border-primary-light" : "bg-gray-50 border-gray-200 hover:bg-gray-100"
)}
>
<RadioGroupItem value="backward" id="backward" />
<Label htmlFor="backward" className="cursor-pointer flex items-center gap-1.5 font-medium">
<RotateCcw className="h-4 w-4 text-primary-main" />
( )
</Label>
</div>
<div
className={cn(
"flex items-center space-x-2 px-4 py-2 rounded-lg border cursor-pointer transition-colors",
direction === 'forward' ? "bg-primary-lightest border-primary-light" : "bg-gray-50 border-gray-200 hover:bg-gray-100"
)}
>
<RadioGroupItem value="forward" id="forward" />
<Label htmlFor="forward" className="cursor-pointer flex items-center gap-1.5 font-medium">
<TrendingUp className="h-4 w-4 text-primary-main" />
( )
</Label>
</div>
</RadioGroup>
</div>
<Button
type="submit"
disabled={isSearching || !batchNumber.trim()}
className="button-filled-primary min-w-[120px]"
>
{isSearching ? '查詢中...' : '開始查詢'}
</Button>
</form>
</CardContent>
</Card>
{search.batch_number && (
<div className="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden p-6 md:p-8">
{result ? (
<>
<TraceabilitySummary data={result} direction={search.direction || 'backward'} />
<TreeView data={result} />
</>
) : (
<div className="py-16 flex flex-col items-center justify-center text-gray-500">
<Search className="h-12 w-12 text-gray-300 mb-4" />
<h3 className="text-lg font-medium text-gray-900 mb-1"></h3>
<p>{search.batch_number}</p>
</div>
)}
</div>
)}
</Can>
</div>
</AuthenticatedLayout>
);
}

View File

@@ -13,14 +13,8 @@ import {
TableRow,
} from "@/Components/ui/table";
import { StatusBadge } from "@/Components/shared/StatusBadge";
import { Checkbox } from "@/Components/ui/checkbox";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/Components/ui/dialog";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import {
AlertDialog,
AlertDialogAction,
@@ -39,7 +33,7 @@ import {
SelectTrigger,
SelectValue,
} from "@/Components/ui/select";
import { Plus, Save, Trash2, ArrowLeft, CheckCircle, Package, ArrowLeftRight, Printer, Search, Truck, PackageCheck } from "lucide-react";
import { Plus, Save, Trash2, ArrowLeft, CheckCircle, Package, ArrowLeftRight, Printer, Truck, PackageCheck } from "lucide-react";
import { toast } from "sonner";
import axios from "axios";
import { Can } from '@/Components/Permission/Can';
@@ -115,20 +109,20 @@ export default function Show({ order, transitWarehouses = [] }: { order: any; tr
}
}, [order]);
const canEdit = can('inventory_transfer.edit');
const isReadOnly = (order.status !== 'draft' || !canEdit);
const isItemsReadOnly = isReadOnly || !!order.requisition;
const isVending = order.to_warehouse_type === 'vending';
// Product Selection
const [isProductDialogOpen, setIsProductDialogOpen] = useState(false);
const [availableInventory, setAvailableInventory] = useState<any[]>([]);
const [loadingInventory, setLoadingInventory] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const [selectedInventory, setSelectedInventory] = useState<string[]>([]); // product_id-batch
useEffect(() => {
if (isProductDialogOpen) {
if (!isItemsReadOnly && order.from_warehouse_id) {
loadInventory();
setSelectedInventory([]);
setSearchQuery('');
}
}, [isProductDialogOpen]);
}, [isItemsReadOnly, order.from_warehouse_id]);
const loadInventory = async () => {
setLoadingInventory(true);
@@ -143,57 +137,22 @@ export default function Show({ order, transitWarehouses = [] }: { order: any; tr
}
};
const toggleSelect = (key: string) => {
setSelectedInventory(prev =>
prev.includes(key) ? prev.filter(k => k !== key) : [...prev, key]
);
};
const toggleSelectAll = () => {
const filtered = availableInventory.filter(inv =>
inv.product_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
inv.product_code.toLowerCase().includes(searchQuery.toLowerCase()) ||
(inv.product_barcode && inv.product_barcode.toLowerCase().includes(searchQuery.toLowerCase()))
);
const filteredKeys = filtered.map(inv => `${inv.product_id}-${inv.batch_number}`);
if (filteredKeys.length > 0 && filteredKeys.every(k => selectedInventory.includes(k))) {
setSelectedInventory(prev => prev.filter(k => !filteredKeys.includes(k)));
} else {
setSelectedInventory(prev => Array.from(new Set([...prev, ...filteredKeys])));
}
};
const handleAddSelected = () => {
if (selectedInventory.length === 0) return;
const newItems = [...items];
let addedCount = 0;
availableInventory.forEach(inv => {
const key = `${inv.product_id}-${inv.batch_number}`;
if (selectedInventory.includes(key)) {
newItems.push({
product_id: inv.product_id,
product_name: inv.product_name,
product_code: inv.product_code,
batch_number: inv.batch_number,
expiry_date: inv.expiry_date,
unit: inv.unit_name,
quantity: 1,
max_quantity: inv.quantity,
notes: "",
});
addedCount++;
const handleAddItem = () => {
setItems([
...items,
{
product_id: "",
product_name: "",
product_code: "",
batch_number: "",
expiry_date: null,
unit: "",
quantity: "",
max_quantity: 0,
position: "",
notes: ""
}
});
setItems(newItems);
setIsProductDialogOpen(false);
if (addedCount > 0) {
toast.success(`已成功加入 ${addedCount} 個項目`);
}
]);
};
const handleUpdateItem = (index: number, field: string, value: any) => {
@@ -210,11 +169,16 @@ export default function Show({ order, transitWarehouses = [] }: { order: any; tr
const handleSave = async () => {
setIsSaving(true);
try {
await router.put(route('inventory.transfer.update', [order.id]), {
items: items,
const payload: any = {
remarks: remarks,
transit_warehouse_id: transitWarehouseId || '',
}, {
};
if (!order.requisition) {
payload.items = items;
}
await router.put(route('inventory.transfer.update', [order.id]), payload, {
onSuccess: () => { },
onError: () => toast.error("儲存失敗,請檢查輸入"),
});
@@ -223,15 +187,19 @@ export default function Show({ order, transitWarehouses = [] }: { order: any; tr
}
};
// 確認出貨 / 確認過帳(無在途倉)
// 確認出貨 / 確認過帳(無在途倉)
const handlePost = () => {
router.put(route('inventory.transfer.update', [order.id]), {
const payload: any = {
action: 'post',
transit_warehouse_id: transitWarehouseId || '',
items: items,
remarks: remarks,
}, {
};
if (!order.requisition) {
payload.items = items;
}
router.put(route('inventory.transfer.update', [order.id]), payload, {
onSuccess: () => {
setIsPostDialogOpen(false);
},
@@ -267,10 +235,7 @@ export default function Show({ order, transitWarehouses = [] }: { order: any; tr
});
};
const canEdit = can('inventory_transfer.edit');
const isReadOnly = (order.status !== 'draft' || !canEdit);
const isItemsReadOnly = isReadOnly || !!order.requisition;
const isVending = order.to_warehouse_type === 'vending';
// 狀態 Badge 渲染
const renderStatusBadge = () => {
@@ -579,146 +544,10 @@ export default function Show({ order, transitWarehouses = [] }: { order: any; tr
onOpenChange={setIsImportDialogOpen}
orderId={order.id}
/>
<Dialog open={isProductDialogOpen} onOpenChange={setIsProductDialogOpen}>
<DialogTrigger asChild>
<Button variant="outline" className="button-outlined-primary">
<Plus className="h-4 w-4 mr-2" />
</Button>
</DialogTrigger>
<DialogContent className="max-w-4xl max-h-[85vh] flex flex-col p-6">
<DialogHeader className="flex flex-row items-center justify-between space-y-0 pb-4">
<DialogTitle className="text-xl"> ({order.from_warehouse_name})</DialogTitle>
<div className="relative w-72">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-grey-3" />
<Input
placeholder="搜尋品名、代號或條碼..."
className="pl-9 h-9 border-2 border-grey-3 focus:ring-primary-main"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
</DialogHeader>
<div className="flex-1 overflow-auto pr-1">
{loadingInventory ? (
<div className="text-center py-12">
<Package className="h-10 w-10 animate-bounce mx-auto text-gray-300 mb-2" />
<p className="text-grey-2 text-sm">...</p>
</div>
) : (
<div className="border rounded-lg overflow-hidden">
<Table>
<TableHeader className="bg-gray-50/80 sticky top-0 z-10 shadow-sm">
<TableRow>
<TableHead className="w-[50px] text-center">
<Checkbox
checked={availableInventory.length > 0 && (() => {
const filtered = availableInventory.filter(inv =>
inv.product_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
inv.product_code.toLowerCase().includes(searchQuery.toLowerCase()) ||
(inv.product_barcode && inv.product_barcode.toLowerCase().includes(searchQuery.toLowerCase()))
);
const filteredKeys = filtered.map(inv => `${inv.product_id}-${inv.batch_number}`);
return filteredKeys.length > 0 && filteredKeys.every(k => selectedInventory.includes(k));
})()}
onCheckedChange={() => toggleSelectAll()}
/>
</TableHead>
<TableHead className="font-medium text-grey-600"> / </TableHead>
<TableHead className="font-medium text-grey-600"></TableHead>
<TableHead className="font-medium text-grey-600"></TableHead>
<TableHead className="text-right font-medium text-grey-600 pr-6"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{(() => {
const filtered = availableInventory.filter(inv =>
inv.product_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
inv.product_code.toLowerCase().includes(searchQuery.toLowerCase()) ||
(inv.product_barcode && inv.product_barcode.toLowerCase().includes(searchQuery.toLowerCase()))
);
if (filtered.length === 0) {
return (
<TableRow>
<TableCell colSpan={5} className="text-center py-12 text-grey-3 italic font-medium">
{searchQuery ? `找不到與 "${searchQuery}" 相關的商品` : '尚無庫存資料'}
</TableCell>
</TableRow>
);
}
return filtered.map((inv) => {
const key = `${inv.product_id}-${inv.batch_number}`;
const isSelected = selectedInventory.includes(key);
return (
<TableRow
key={key}
className={`hover:bg-primary-lightest/20 cursor-pointer transition-colors ${isSelected ? 'bg-primary-lightest/40' : ''}`}
onClick={() => toggleSelect(key)}
>
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
<Checkbox
checked={isSelected}
onCheckedChange={() => toggleSelect(key)}
/>
</TableCell>
<TableCell className="py-3">
<div className="flex flex-col">
<span className="font-semibold text-grey-0">{inv.product_name}</span>
<span className="text-xs text-grey-2 font-mono">{inv.product_code}</span>
</div>
</TableCell>
<TableCell className="text-sm font-mono text-grey-2">{inv.batch_number || '-'}</TableCell>
<TableCell className="text-sm font-mono text-grey-2">{inv.expiry_date || '-'}</TableCell>
<TableCell className="text-right font-bold text-primary-main pr-6">{inv.quantity} {inv.unit_name}</TableCell>
</TableRow>
);
});
})()}
</TableBody>
</Table>
</div>
)}
</div>
<div className="mt-6 flex items-center justify-between border-t pt-4">
<div className="flex items-center gap-3">
<div className="px-3 py-1 bg-primary-lightest/50 border border-primary-light/20 rounded-full text-sm font-medium text-primary-main animate-in zoom-in duration-200">
{selectedInventory.length}
</div>
{selectedInventory.length > 0 && (
<Button
variant="ghost"
size="sm"
className="text-grey-3 hover:text-red-500 hover:bg-red-50 text-xs px-2 h-7"
onClick={() => setSelectedInventory([])}
>
</Button>
)}
</div>
<div className="flex gap-2">
<Button
variant="outline"
className="button-outlined-primary w-24"
onClick={() => setIsProductDialogOpen(false)}
>
</Button>
<Button
className="button-filled-primary min-w-32"
disabled={selectedInventory.length === 0}
onClick={handleAddSelected}
>
</Button>
</div>
</div>
</DialogContent>
</Dialog>
<Button variant="outline" className="button-outlined-primary" onClick={handleAddItem}>
<Plus className="h-4 w-4 mr-2" />
</Button>
</div>
)}
</div>
@@ -752,10 +581,41 @@ export default function Show({ order, transitWarehouses = [] }: { order: any; tr
<TableRow key={index}>
<TableCell className="text-center text-gray-500 font-medium">{index + 1}</TableCell>
<TableCell className="py-3">
<div className="flex flex-col">
<span className="font-semibold text-gray-900">{item.product_name}</span>
<span className="text-xs text-gray-500 font-mono">{item.product_code}</span>
</div>
{isItemsReadOnly || item.product_id ? (
<div className="flex flex-col">
<span className="font-semibold text-gray-900">{item.product_name}</span>
<span className="text-xs text-gray-500 font-mono">{item.product_code}</span>
</div>
) : (
<SearchableSelect
value={item.product_id ? `${item.product_id}|${item.batch_number || ''}` : ""}
onValueChange={(val) => {
const [pid, batch] = val.split('|');
const inv = availableInventory.find(i => String(i.product_id) === pid && (i.batch_number || '') === batch);
if (inv) {
const newItems = [...items];
newItems[index] = {
...newItems[index],
product_id: inv.product_id,
product_name: inv.product_name,
product_code: inv.product_code,
batch_number: inv.batch_number,
expiry_date: inv.expiry_date,
unit: inv.unit_name,
max_quantity: inv.quantity,
quantity: newItems[index].quantity || 1
};
setItems(newItems);
}
}}
options={availableInventory.map(inv => ({
label: `${inv.product_code} - ${inv.product_name} ${inv.batch_number ? `(批號: ${inv.batch_number})` : ''} - 庫存: ${inv.quantity}`,
value: `${inv.product_id}|${inv.batch_number || ''}`
}))}
placeholder={loadingInventory ? "載入庫存中..." : "搜尋名稱或代號選擇庫存"}
className="w-full min-w-[200px]"
/>
)}
</TableCell>
<TableCell className="text-sm font-mono">
<div>{item.batch_number || '-'}</div>
@@ -766,7 +626,7 @@ export default function Show({ order, transitWarehouses = [] }: { order: any; tr
)}
</TableCell>
<TableCell className="text-right font-semibold text-primary-main">
{item.max_quantity} {item.unit || item.unit_name}
{item.product_id ? `${item.max_quantity} ${item.unit || item.unit_name || ''}` : '-'}
</TableCell>
<TableCell className="px-1 py-3">
{isItemsReadOnly ? (

View File

@@ -175,15 +175,33 @@ export default function Show({ requisition, warehouses }: Props) {
};
const handleApprove = () => {
// 確認每個核准數量
// 確認每個核准數量與庫存上限
for (const item of approvedItems) {
const originalItem = requisition.items.find(i => i.id === item.id);
if (!originalItem) continue;
for (const batch of item.batches) {
if (batch.qty !== "") {
const qty = parseFloat(batch.qty);
if (isNaN(qty) || qty < 0) {
toast.error("核准數量不能為負數");
toast.error("核准數量不能為負數或無效數字");
return;
}
// 檢查是否超過批號最大可用庫存
if (batch.inventory_id && originalItem.supply_batches) {
const originalBatch = originalItem.supply_batches.find(b => b.inventory_id === batch.inventory_id);
if (originalBatch && qty > originalBatch.available_qty) {
toast.error(`${originalItem.product_name}」批號 ${originalBatch.batch_number || '無批號'} 數量不可大於庫存上限 (${originalBatch.available_qty})`);
return;
}
} else if (batch.inventory_id === null) {
// 無批號情境:檢查總可用庫存
if (originalItem.supply_stock !== null && qty > originalItem.supply_stock) {
toast.error(`${originalItem.product_name}」數量不可大於供貨倉庫存上限 (${originalItem.supply_stock})`);
return;
}
}
}
}
}