feat(inventory): 統一庫存調整與調撥模組 UI,實作多選、搜尋與明細欄位重構
All checks were successful
Koori-ERP-Deploy-System / deploy-demo (push) Successful in 1m4s
Koori-ERP-Deploy-System / deploy-production (push) Has been skipped

This commit is contained in:
2026-01-29 14:37:21 +08:00
parent 2efaded77b
commit 7619dc24f7
5 changed files with 1013 additions and 576 deletions

View File

@@ -11,6 +11,7 @@ import {
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Badge } from "@/Components/ui/badge";
import { Checkbox } from "@/Components/ui/checkbox";
import {
AlertDialog,
AlertDialogAction,
@@ -23,16 +24,18 @@ import {
AlertDialogTrigger,
} from "@/Components/ui/alert-dialog";
import { Label } from "@/Components/ui/label";
import { Save, CheckCircle, Trash2, ArrowLeft, Plus, X, Search, ClipboardCheck } from "lucide-react";
import { Save, CheckCircle, Trash2, ArrowLeft, Plus, ClipboardCheck, Package, Search } from "lucide-react";
import { useState, useEffect } from 'react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/Components/ui/dialog";
import axios from 'axios';
import { Can } from '@/Components/Permission/Can';
import { toast } from 'sonner';
interface AdjItem {
id?: string;
@@ -41,7 +44,7 @@ interface AdjItem {
product_code: string;
batch_number: string | null;
unit: string;
qty_before: number;
qty_before: number | string;
adjust_qty: number | string;
notes: string;
}
@@ -72,33 +75,96 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
action: 'save',
});
// Product Selection State
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
const [isPostDialogOpen, setIsPostDialogOpen] = useState(false);
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
// Helper to add new item
const addItem = (product: any, batchNumber: string | null) => {
// Check if exists
const exists = data.items.find(i =>
i.product_id === String(product.id) &&
i.batch_number === batchNumber
);
if (exists) {
alert('此商品與批號已在列表中');
return;
useEffect(() => {
if (isProductDialogOpen) {
loadInventory();
setSelectedInventory([]); // Reset selection when opening
setSearchQuery(''); // Reset search when opening
}
}, [isProductDialogOpen]);
setData('items', [
...data.items,
{
product_id: String(product.id),
product_name: product.name,
product_code: product.code,
unit: product.unit,
batch_number: batchNumber,
qty_before: product.qty || 0, // Not fetched dynamically for now, or could fetch via API
adjust_qty: 0,
notes: '',
const loadInventory = async () => {
setLoadingInventory(true);
try {
const response = await axios.get(route('api.warehouses.inventories', doc.warehouse_id));
setAvailableInventory(response.data);
} catch (error) {
console.error("Failed to load inventory", error);
toast.error("無法載入庫存資料");
} finally {
setLoadingInventory(false);
}
};
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())
);
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])));
}
};
// Helper to add selected items to the main list
const handleAddSelected = () => {
if (selectedInventory.length === 0) return;
const newItems = [...data.items];
let addedCount = 0;
availableInventory.forEach(inv => {
const key = `${inv.product_id}-${inv.batch_number}`;
if (selectedInventory.includes(key)) {
// Check if already exists
const exists = newItems.find((i: any) =>
i.product_id === String(inv.product_id) &&
i.batch_number === inv.batch_number
);
if (!exists) {
newItems.push({
product_id: String(inv.product_id),
product_name: inv.product_name,
product_code: inv.product_code,
unit: inv.unit_name,
batch_number: inv.batch_number,
qty_before: inv.quantity || 0,
adjust_qty: 0,
notes: '',
});
addedCount++;
}
}
]);
});
setData('items', newItems);
setIsProductDialogOpen(false);
if (addedCount > 0) {
toast.success(`已成功加入 ${addedCount} 個項目`);
} else {
toast.info("選取的商品已在清單中");
}
};
const removeItem = (index: number) => {
@@ -117,23 +183,31 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
setData('action', 'save');
put(route('inventory.adjust.update', [doc.id]), {
preserveScroll: true,
onSuccess: () => toast.success("草稿儲存成功"),
});
};
const handlePost = () => {
if (data.items.length === 0) {
alert('請至少加入一個調整項目');
toast.error('請至少加入一個調整項目');
return;
}
router.visit(route('inventory.adjust.update', [doc.id]), {
method: 'put',
data: { ...data, action: 'post' } as any,
router.put(route('inventory.adjust.update', [doc.id]), {
...data,
action: 'post'
} as any, {
onSuccess: () => {
setIsPostDialogOpen(false);
toast.success("盤調單過帳成功");
}
});
};
const handleDelete = () => {
destroy(route('inventory.adjust.destroy', [doc.id]));
destroy(route('inventory.adjust.destroy', [doc.id]), {
onSuccess: () => toast.success("盤調單已刪除"),
});
};
return (
@@ -166,9 +240,9 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
調: {doc.doc_no}
</h1>
{isDraft ? (
<Badge variant="secondary" className="bg-gray-100 text-gray-600 border-none">稿</Badge>
<Badge variant="secondary" className="bg-blue-500 text-white border-none py-1 px-3">稿</Badge>
) : (
<Badge className="bg-green-100 text-green-700 border-none"></Badge>
<Badge className="bg-green-500 text-white border-none py-1 px-3"></Badge>
)}
</div>
<p className="text-sm text-gray-500 mt-1 font-medium flex items-center gap-2">
@@ -191,7 +265,7 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
<div className="flex items-center gap-2">
{isDraft && (
<Can permission="inventory.adjust">
<AlertDialog>
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
<AlertDialogTrigger asChild>
<Button variant="outline" size="sm" disabled={processing} className="button-outlined-error">
<Trash2 className="w-4 h-4 mr-2" />
@@ -223,15 +297,30 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
</Button>
<Button
size="sm"
className="button-filled-primary"
onClick={handlePost}
disabled={processing}
>
<CheckCircle className="w-4 h-4 mr-2" />
</Button>
<AlertDialog open={isPostDialogOpen} onOpenChange={setIsPostDialogOpen}>
<AlertDialogTrigger asChild>
<Button
size="sm"
className="button-filled-primary"
disabled={processing || data.items.length === 0}
>
<CheckCircle className="w-4 h-4 mr-2" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle></AlertDialogTitle>
<AlertDialogDescription>
調調
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={handlePost} className="bg-primary-600 hover:bg-primary-700"></AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</Can>
)}
</div>
@@ -242,7 +331,7 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
{/* Header Fields - Inline */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 pb-2">
<div className="space-y-1">
<Label className="text-xs font-bold text-grey-500 uppercase tracking-wider">調</Label>
<Label className="text-xs font-bold text-grey-500 uppercase tracking-wider font-semibold">調</Label>
{isDraft ? (
<Input
value={data.reason}
@@ -255,7 +344,7 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
)}
</div>
<div className="space-y-1">
<Label className="text-xs font-bold text-grey-500 uppercase tracking-wider"></Label>
<Label className="text-xs font-bold text-grey-500 uppercase tracking-wider font-semibold"></Label>
{isDraft ? (
<Input
value={data.remarks}
@@ -272,12 +361,136 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
<div className="border-t pt-4"></div>
<div className="flex flex-row items-center justify-between mb-2">
<h3 className="text-lg font-medium text-grey-900">調</h3>
<div>
<h3 className="text-lg font-semibold text-grey-900">調</h3>
<p className="text-sm text-gray-500">
</p>
</div>
{isDraft && !doc.count_doc_id && (
<ProductSearchDialog
warehouseId={doc.warehouse_id}
onSelect={(product, batch) => addItem(product, batch)}
/>
<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"> ({doc.warehouse_name})</DialogTitle>
<div className="relative w-64">
<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 && selectedInventory.length === availableInventory.length}
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())
);
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="font-mono text-sm text-grey-1">{inv.product_code}</TableCell>
<TableCell className="font-semibold text-grey-0">{inv.product_name}</TableCell>
<TableCell className="text-sm font-mono text-grey-2">{inv.batch_number || '-'}</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>
)}
</div>
@@ -286,7 +499,7 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
<TableHeader className="bg-gray-50">
<TableRow>
<TableHead className="w-[50px] text-center font-medium text-grey-600">#</TableHead>
<TableHead className="pl-4 font-medium text-grey-600"></TableHead>
<TableHead className="pl-4 font-medium text-grey-600"> / </TableHead>
<TableHead className="font-medium text-grey-600"></TableHead>
<TableHead className="w-24 text-center font-medium text-grey-600"></TableHead>
<TableHead className="w-32 text-right font-medium text-grey-600">調</TableHead>
@@ -310,24 +523,28 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
>
<TableCell className="text-center text-grey-400 font-medium">{index + 1}</TableCell>
<TableCell className="pl-4 py-3">
<div className="font-bold text-grey-900">{item.product_name}</div>
<div className="text-xs text-grey-500 font-mono">{item.product_code}</div>
<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>
</TableCell>
<TableCell className="text-grey-600">{item.batch_number || '-'}</TableCell>
<TableCell className="text-grey-600 font-mono text-sm">{item.batch_number || '-'}</TableCell>
<TableCell className="text-center text-grey-500">{item.unit}</TableCell>
<TableCell className="text-right font-medium text-grey-400">
{item.qty_before}
</TableCell>
<TableCell className="text-right">
{isDraft ? (
<Input
type="number"
className="text-right h-9 border-grey-200 focus:ring-primary-main"
value={item.adjust_qty}
onChange={e => updateItem(index, 'adjust_qty', e.target.value)}
/>
<div className="flex justify-end pr-2">
<Input
type="number"
className="text-right h-9 w-32 font-medium"
value={item.adjust_qty}
onChange={e => updateItem(index, 'adjust_qty', e.target.value)}
/>
</div>
) : (
<span className={`font-bold ${Number(item.adjust_qty) > 0 ? 'text-green-600' : 'text-red-600'}`}>
<span className={`font-bold mr-2 ${Number(item.adjust_qty) > 0 ? 'text-green-600' : Number(item.adjust_qty) < 0 ? 'text-red-600' : 'text-gray-600'}`}>
{Number(item.adjust_qty) > 0 ? '+' : ''}{item.adjust_qty}
</span>
)}
@@ -335,7 +552,7 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
<TableCell>
{isDraft ? (
<Input
className="h-9 border-grey-200 focus:ring-primary-main text-sm"
className="h-9 text-sm"
value={item.notes || ''}
onChange={e => updateItem(index, 'notes', e.target.value)}
placeholder="備註..."
@@ -352,7 +569,7 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
className="h-8 w-8 text-red-400 hover:text-red-600 hover:bg-red-50 p-0"
onClick={() => removeItem(index)}
>
<X className="h-4 w-4" />
<Trash2 className="h-4 w-4" />
</Button>
</TableCell>
)}
@@ -368,110 +585,3 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
</AuthenticatedLayout>
);
}
// Simple internal component for product search
function ProductSearchDialog({ onSelect }: { warehouseId: string, onSelect: (p: any, b: string | null) => void }) {
const [search, setSearch] = useState('');
const [results, setResults] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [open, setOpen] = useState(false);
// Debounce search
useEffect(() => {
if (!search) {
setResults([]);
return;
}
const timer = setTimeout(() => {
fetchProducts();
}, 500);
return () => clearTimeout(timer);
}, [search]);
const fetchProducts = async () => {
setLoading(true);
try {
// Using existing API logic from Goods Receipts or creating a flexible one
// Using count docs logic for now if specific endpoint not available,
// but `goods-receipts.search-products` is a good bet for general product search.
const res = await axios.get(route('goods-receipts.search-products'), { params: { query: search } });
setResults(res.data);
} catch (e) {
console.error(e);
} finally {
setLoading(false);
}
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<Button
variant="outline"
size="sm"
className="h-8 border-primary-100 text-primary-main hover:bg-primary-50 px-3 flex items-center gap-2"
onClick={() => setOpen(true)}
>
<Plus className="h-4 w-4" />
調
</Button>
<DialogContent className="sm:max-w-[500px] p-0 overflow-hidden border-none shadow-2xl">
<DialogHeader className="bg-primary-main p-6">
<DialogTitle className="text-white text-xl flex items-center gap-2">
<Search className="h-5 w-5" />
</DialogTitle>
</DialogHeader>
<div className="p-6 space-y-4">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-grey-400" />
<Input
placeholder="輸入商品名稱、代號或條碼..."
className="pl-11 h-12 border-grey-200 rounded-xl text-lg focus:ring-primary-main transition-all"
value={search}
onChange={e => setSearch(e.target.value)}
autoFocus
/>
</div>
<div className="h-[350px] overflow-y-auto rounded-xl border border-grey-100 bg-grey-50">
{loading ? (
<div className="flex flex-col items-center justify-center h-full text-grey-400 space-y-3">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-main"></div>
<span className="text-sm font-medium">...</span>
</div>
) : results.length === 0 ? (
<div className="flex flex-col items-center justify-center h-full text-grey-400 p-8 text-center space-y-2">
<Search className="h-10 w-10 opacity-20" />
<p className="text-sm"></p>
</div>
) : (
<div className="divide-y divide-grey-100">
{results.map(product => (
<div
key={product.id}
className="p-4 hover:bg-white cursor-pointer flex justify-between items-center group transition-colors"
onClick={() => {
onSelect(product, null);
setOpen(false);
setSearch('');
setResults([]);
}}
>
<div className="space-y-1">
<div className="font-bold text-grey-900 group-hover:text-primary-main transition-colors">{product.name}</div>
<div className="text-xs text-grey-500 font-mono tracking-tight">{product.code}</div>
</div>
<div className="flex flex-col items-end gap-2">
<Badge variant="outline" className="text-[10px] h-5 border-grey-200">{product.unit || '單位'}</Badge>
<span className="text-[10px] text-grey-400"></span>
</div>
</div>
))}
</div>
)}
</div>
</div>
</DialogContent>
</Dialog>
)
}