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

@@ -15,7 +15,6 @@ import {
Dialog, Dialog,
DialogContent, DialogContent,
DialogDescription, DialogDescription,
DialogFooter,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from "@/Components/ui/dialog"; } from "@/Components/ui/dialog";
@@ -138,7 +137,7 @@ export default function Index({ docs, warehouses, filters }: { docs: DocsPaginat
const { data, setData, post, processing, reset } = useForm({ const { data, setData, post, processing, reset } = useForm({
count_doc_id: null as string | null, count_doc_id: null as string | null,
warehouse_id: '', warehouse_id: '',
reason: '', reason: '手動調整庫存',
remarks: '', remarks: '',
}); });
@@ -375,13 +374,16 @@ export default function Index({ docs, warehouses, filters }: { docs: DocsPaginat
<div className="py-4 space-y-6"> <div className="py-4 space-y-6">
{/* Option 1: Scan/Select from Count Docs */} {/* Option 1: Scan/Select from Count Docs */}
<div className="space-y-4"> <div className="space-y-4 p-4 rounded-xl bg-primary-lightest/50 border border-primary-light/20 shadow-sm">
<Label className="text-sm font-semibold text-grey-700"> ()</Label> <Label className="text-sm font-bold text-primary-main flex items-center gap-2">
<ClipboardCheck className="h-4 w-4" />
()
</Label>
<div className="relative"> <div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-grey-400" /> <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-grey-3" />
<Input <Input
placeholder="掃描盤點單號或搜尋..." placeholder="掃描盤點單號或搜尋..."
className="pl-9 h-11 border-primary-100 focus:ring-primary-main" className="pl-9 h-9"
value={scanSearch} value={scanSearch}
onChange={(e) => { onChange={(e) => {
setScanSearch(e.target.value); setScanSearch(e.target.value);
@@ -390,26 +392,26 @@ export default function Index({ docs, warehouses, filters }: { docs: DocsPaginat
/> />
</div> </div>
<div className="max-height-[300px] overflow-y-auto rounded-md border border-grey-100 bg-grey-50"> <div className="max-h-[200px] overflow-y-auto rounded-lg border-2 border-grey-3 bg-white">
{loadingPending ? ( {loadingPending ? (
<div className="p-8 text-center text-sm text-grey-400">...</div> <div className="p-8 text-center text-sm text-grey-3">...</div>
) : pendingCounts.length === 0 ? ( ) : pendingCounts.length === 0 ? (
<div className="p-8 text-center text-sm text-grey-400"> <div className="p-8 text-center text-sm text-grey-3">
調 () 調 ()
</div> </div>
) : ( ) : (
<div className="divide-y divide-grey-100"> <div className="divide-y divide-grey-4">
{pendingCounts.map((c: any) => ( {pendingCounts.map((c: any) => (
<div <div
key={c.id} key={c.id}
className="p-3 hover:bg-white flex items-center justify-between cursor-pointer group transition-colors" className="p-3 hover:bg-primary-lightest flex items-center justify-between cursor-pointer group transition-colors"
onClick={() => handleCreate(c.id)} onClick={() => handleCreate(c.id)}
> >
<div> <div>
<p className="font-bold text-grey-900 group-hover:text-primary-main">{c.doc_no}</p> <p className="font-bold text-grey-0 group-hover:text-primary-main">{c.doc_no}</p>
<p className="text-xs text-grey-500">{c.warehouse_name} | : {c.completed_at}</p> <p className="text-xs text-grey-2">{c.warehouse_name} | : {c.completed_at}</p>
</div> </div>
<Button size="sm" variant="outline" className="button-outlined-primary"> <Button size="sm" variant="outline" className="button-outlined-primary h-7 text-xs">
</Button> </Button>
</div> </div>
@@ -419,38 +421,37 @@ export default function Index({ docs, warehouses, filters }: { docs: DocsPaginat
</div> </div>
</div> </div>
<div className="relative"> <div className="relative flex items-center py-2">
<div className="absolute inset-0 flex items-center"><span className="w-full border-t border-grey-200" /></div> <div className="flex-grow border-t border-grey-4"></div>
<div className="relative flex justify-center text-xs uppercase"><span className="bg-white px-2 text-grey-400 font-medium"></span></div> <span className="flex-shrink mx-4 text-xs font-semibold text-grey-3 uppercase tracking-wider"></span>
<div className="flex-grow border-t border-grey-4"></div>
</div> </div>
{/* Option 2: Manual (Optional, though less common in this flow) */} {/* Option 2: Manual (Optional, though less common in this flow) */}
<div className="space-y-4"> <div className="space-y-4 px-1">
<Label className="text-sm font-semibold text-grey-700">調</Label> <Label className="text-sm font-bold text-grey-0">調</Label>
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<div className="space-y-2"> <div className="space-y-2">
<Label className="text-xs"></Label> <Label className="text-xs font-semibold text-grey-1"></Label>
<SearchableSelect <SearchableSelect
options={warehouses.map(w => ({ value: w.id, label: w.name }))} options={warehouses.map(w => ({ value: w.id, label: w.name }))}
value={data.warehouse_id} value={data.warehouse_id}
onValueChange={(val) => setData('warehouse_id', val)} onValueChange={(val) => setData('warehouse_id', val)}
placeholder="選擇倉庫" placeholder="選擇倉庫"
className="h-9"
/> />
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label className="text-xs">調</Label> <Label className="text-xs font-semibold text-grey-1">調</Label>
<Input <Input
placeholder="例如: 報廢, 破損..." placeholder="例如: 報廢, 破損..."
value={data.reason} value={data.reason}
onChange={(e) => setData('reason', e.target.value)} onChange={(e) => setData('reason', e.target.value)}
className="h-10" className="h-9"
/> />
</div> </div>
</div> </div>
</div> <div className="flex justify-end gap-2 pt-2">
</div>
<DialogFooter className="bg-gray-50 -mx-6 -mb-6 p-4 rounded-b-lg gap-2">
<Button variant="outline" className="button-outlined-primary" onClick={() => setIsDialogOpen(false)}></Button> <Button variant="outline" className="button-outlined-primary" onClick={() => setIsDialogOpen(false)}></Button>
<Button <Button
className="button-filled-primary" className="button-filled-primary"
@@ -459,7 +460,9 @@ export default function Index({ docs, warehouses, filters }: { docs: DocsPaginat
> >
</Button> </Button>
</DialogFooter> </div>
</div>
</div>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
</AuthenticatedLayout> </AuthenticatedLayout>

View File

@@ -11,6 +11,7 @@ import {
import { Button } from "@/Components/ui/button"; import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input"; import { Input } from "@/Components/ui/input";
import { Badge } from "@/Components/ui/badge"; import { Badge } from "@/Components/ui/badge";
import { Checkbox } from "@/Components/ui/checkbox";
import { import {
AlertDialog, AlertDialog,
AlertDialogAction, AlertDialogAction,
@@ -23,16 +24,18 @@ import {
AlertDialogTrigger, AlertDialogTrigger,
} from "@/Components/ui/alert-dialog"; } from "@/Components/ui/alert-dialog";
import { Label } from "@/Components/ui/label"; 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 { useState, useEffect } from 'react';
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
DialogTrigger,
} from "@/Components/ui/dialog"; } from "@/Components/ui/dialog";
import axios from 'axios'; import axios from 'axios';
import { Can } from '@/Components/Permission/Can'; import { Can } from '@/Components/Permission/Can';
import { toast } from 'sonner';
interface AdjItem { interface AdjItem {
id?: string; id?: string;
@@ -41,7 +44,7 @@ interface AdjItem {
product_code: string; product_code: string;
batch_number: string | null; batch_number: string | null;
unit: string; unit: string;
qty_before: number; qty_before: number | string;
adjust_qty: number | string; adjust_qty: number | string;
notes: string; notes: string;
} }
@@ -72,33 +75,96 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
action: 'save', 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 useEffect(() => {
const addItem = (product: any, batchNumber: string | null) => { if (isProductDialogOpen) {
// Check if exists loadInventory();
const exists = data.items.find(i => setSelectedInventory([]); // Reset selection when opening
i.product_id === String(product.id) && setSearchQuery(''); // Reset search when opening
i.batch_number === batchNumber }
}, [isProductDialogOpen]);
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) { if (!exists) {
alert('此商品與批號已在列表中'); newItems.push({
return; product_id: String(inv.product_id),
} product_name: inv.product_name,
product_code: inv.product_code,
setData('items', [ unit: inv.unit_name,
...data.items, batch_number: inv.batch_number,
{ qty_before: inv.quantity || 0,
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, adjust_qty: 0,
notes: '', notes: '',
});
addedCount++;
}
}
});
setData('items', newItems);
setIsProductDialogOpen(false);
if (addedCount > 0) {
toast.success(`已成功加入 ${addedCount} 個項目`);
} else {
toast.info("選取的商品已在清單中");
} }
]);
}; };
const removeItem = (index: number) => { const removeItem = (index: number) => {
@@ -117,23 +183,31 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
setData('action', 'save'); setData('action', 'save');
put(route('inventory.adjust.update', [doc.id]), { put(route('inventory.adjust.update', [doc.id]), {
preserveScroll: true, preserveScroll: true,
onSuccess: () => toast.success("草稿儲存成功"),
}); });
}; };
const handlePost = () => { const handlePost = () => {
if (data.items.length === 0) { if (data.items.length === 0) {
alert('請至少加入一個調整項目'); toast.error('請至少加入一個調整項目');
return; return;
} }
router.visit(route('inventory.adjust.update', [doc.id]), { router.put(route('inventory.adjust.update', [doc.id]), {
method: 'put', ...data,
data: { ...data, action: 'post' } as any, action: 'post'
} as any, {
onSuccess: () => {
setIsPostDialogOpen(false);
toast.success("盤調單過帳成功");
}
}); });
}; };
const handleDelete = () => { const handleDelete = () => {
destroy(route('inventory.adjust.destroy', [doc.id])); destroy(route('inventory.adjust.destroy', [doc.id]), {
onSuccess: () => toast.success("盤調單已刪除"),
});
}; };
return ( return (
@@ -166,9 +240,9 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
調: {doc.doc_no} 調: {doc.doc_no}
</h1> </h1>
{isDraft ? ( {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> </div>
<p className="text-sm text-gray-500 mt-1 font-medium flex items-center gap-2"> <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"> <div className="flex items-center gap-2">
{isDraft && ( {isDraft && (
<Can permission="inventory.adjust"> <Can permission="inventory.adjust">
<AlertDialog> <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
<AlertDialogTrigger asChild> <AlertDialogTrigger asChild>
<Button variant="outline" size="sm" disabled={processing} className="button-outlined-error"> <Button variant="outline" size="sm" disabled={processing} className="button-outlined-error">
<Trash2 className="w-4 h-4 mr-2" /> <Trash2 className="w-4 h-4 mr-2" />
@@ -223,15 +297,30 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
</Button> </Button>
<AlertDialog open={isPostDialogOpen} onOpenChange={setIsPostDialogOpen}>
<AlertDialogTrigger asChild>
<Button <Button
size="sm" size="sm"
className="button-filled-primary" className="button-filled-primary"
onClick={handlePost} disabled={processing || data.items.length === 0}
disabled={processing}
> >
<CheckCircle className="w-4 h-4 mr-2" /> <CheckCircle className="w-4 h-4 mr-2" />
</Button> </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> </Can>
)} )}
</div> </div>
@@ -242,7 +331,7 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
{/* Header Fields - Inline */} {/* Header Fields - Inline */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 pb-2"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pb-2">
<div className="space-y-1"> <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 ? ( {isDraft ? (
<Input <Input
value={data.reason} value={data.reason}
@@ -255,7 +344,7 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
)} )}
</div> </div>
<div className="space-y-1"> <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 ? ( {isDraft ? (
<Input <Input
value={data.remarks} 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="border-t pt-4"></div>
<div className="flex flex-row items-center justify-between mb-2"> <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 && ( {isDraft && !doc.count_doc_id && (
<ProductSearchDialog <Dialog open={isProductDialogOpen} onOpenChange={setIsProductDialogOpen}>
warehouseId={doc.warehouse_id} <DialogTrigger asChild>
onSelect={(product, batch) => addItem(product, batch)} <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> </div>
@@ -286,7 +499,7 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
<TableHeader className="bg-gray-50"> <TableHeader className="bg-gray-50">
<TableRow> <TableRow>
<TableHead className="w-[50px] text-center font-medium text-grey-600">#</TableHead> <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="font-medium text-grey-600"></TableHead>
<TableHead className="w-24 text-center 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> <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="text-center text-grey-400 font-medium">{index + 1}</TableCell>
<TableCell className="pl-4 py-3"> <TableCell className="pl-4 py-3">
<div className="font-bold text-grey-900">{item.product_name}</div> <div className="flex flex-col">
<div className="text-xs text-grey-500 font-mono">{item.product_code}</div> <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>
<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-center text-grey-500">{item.unit}</TableCell>
<TableCell className="text-right font-medium text-grey-400"> <TableCell className="text-right font-medium text-grey-400">
{item.qty_before} {item.qty_before}
</TableCell> </TableCell>
<TableCell className="text-right"> <TableCell className="text-right">
{isDraft ? ( {isDraft ? (
<div className="flex justify-end pr-2">
<Input <Input
type="number" type="number"
className="text-right h-9 border-grey-200 focus:ring-primary-main" className="text-right h-9 w-32 font-medium"
value={item.adjust_qty} value={item.adjust_qty}
onChange={e => updateItem(index, 'adjust_qty', e.target.value)} 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} {Number(item.adjust_qty) > 0 ? '+' : ''}{item.adjust_qty}
</span> </span>
)} )}
@@ -335,7 +552,7 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
<TableCell> <TableCell>
{isDraft ? ( {isDraft ? (
<Input <Input
className="h-9 border-grey-200 focus:ring-primary-main text-sm" className="h-9 text-sm"
value={item.notes || ''} value={item.notes || ''}
onChange={e => updateItem(index, 'notes', e.target.value)} onChange={e => updateItem(index, 'notes', e.target.value)}
placeholder="備註..." 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" className="h-8 w-8 text-red-400 hover:text-red-600 hover:bg-red-50 p-0"
onClick={() => removeItem(index)} onClick={() => removeItem(index)}
> >
<X className="h-4 w-4" /> <Trash2 className="h-4 w-4" />
</Button> </Button>
</TableCell> </TableCell>
)} )}
@@ -368,110 +585,3 @@ export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
</AuthenticatedLayout> </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>
)
}

View File

@@ -237,7 +237,6 @@ export default function Show({ doc }: any) {
<TableHead className="text-right font-medium text-grey-600"></TableHead> <TableHead className="text-right font-medium text-grey-600"></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="font-medium text-grey-600"></TableHead>
{!isCompleted && <TableHead className="w-[50px]"></TableHead>}
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
@@ -303,21 +302,6 @@ export default function Show({ doc }: any) {
/> />
)} )}
</TableCell> </TableCell>
{!isCompleted && (
<TableCell className="text-center">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 text-red-400 hover:text-red-600 hover:bg-red-50 p-0"
onClick={() => {
updateItem(index, 'counted_qty', '');
}}
>
<Trash2 className="h-4 w-4" />
</Button>
</TableCell>
)
}
</TableRow> </TableRow>
); );
})} })}

View File

@@ -1,7 +1,9 @@
import { useState, useEffect } from "react"; import { useState, useCallback, useEffect } from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout"; import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, Link, router } from "@inertiajs/react"; import { Head, Link, router } from "@inertiajs/react";
import { debounce } from "lodash";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import { import {
Table, Table,
TableBody, TableBody,
@@ -20,41 +22,94 @@ import {
DialogTitle, DialogTitle,
DialogTrigger, DialogTrigger,
DialogFooter, DialogFooter,
DialogDescription,
} from "@/Components/ui/dialog"; } from "@/Components/ui/dialog";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/Components/ui/select";
import { Label } from "@/Components/ui/label"; import { Label } from "@/Components/ui/label";
import { import {
Plus, Plus,
Search, Search,
FileText,
ArrowLeftRight, ArrowLeftRight,
Loader2, Loader2,
Eye,
Pencil,
Trash2,
X,
} from "lucide-react"; } from "lucide-react";
import { format } from "date-fns"; import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/Components/ui/alert-dialog";
import Pagination from "@/Components/shared/Pagination"; import Pagination from "@/Components/shared/Pagination";
import { toast } from "sonner"; import { toast } from "sonner";
import { Can } from '@/Components/Permission/Can';
export default function Index({ auth, orders, warehouses, filters }) { export default function Index({ warehouses, orders, filters }: any) {
const [searchQuery, setSearchQuery] = useState(""); const [searchTerm, setSearchTerm] = useState(filters.search || "");
const [warehouseFilter, setWarehouseFilter] = useState(filters.warehouse_id || "all");
const [perPage, setPerPage] = useState(filters.per_page || "10");
// Sync state with props
useEffect(() => {
setSearchTerm(filters.search || "");
setWarehouseFilter(filters.warehouse_id || "all");
setPerPage(filters.per_page || "10");
}, [filters]);
// Create Dialog State // Create Dialog State
const [isCreateOpen, setIsCreateOpen] = useState(false); const [isCreateOpen, setIsCreateOpen] = useState(false);
const [sourceWarehouseId, setSourceWarehouseId] = useState(""); const [sourceWarehouseId, setSourceWarehouseId] = useState("");
const [targetWarehouseId, setTargetWarehouseId] = useState(""); const [targetWarehouseId, setTargetWarehouseId] = useState("");
const [creating, setCreating] = useState(false); const [creating, setCreating] = useState(false);
const [deleteId, setDeleteId] = useState<string | null>(null);
// Handle warehouse filter change // Debounced Search Handler
const handleFilterChange = (value) => { const debouncedSearch = useCallback(
router.get(route('inventory.transfer.index'), { warehouse_id: value }, { debounce((term: string, warehouse: string) => {
preserveState: true, router.get(
replace: true, route('inventory.transfer.index'),
}); { ...filters, search: term, warehouse_id: warehouse === "all" ? "" : warehouse },
{ preserveState: true, replace: true, preserveScroll: true }
);
}, 500),
[filters]
);
const handleSearchChange = (term: string) => {
setSearchTerm(term);
debouncedSearch(term, warehouseFilter);
};
const handleFilterChange = (value: string) => {
setWarehouseFilter(value);
router.get(
route('inventory.transfer.index'),
{ ...filters, warehouse_id: value === "all" ? "" : value },
{ preserveState: false, replace: true, preserveScroll: true }
);
};
const handleClearSearch = () => {
setSearchTerm("");
router.get(
route('inventory.transfer.index'),
{ ...filters, search: "", warehouse_id: warehouseFilter === "all" ? "" : warehouseFilter },
{ preserveState: true, replace: true, preserveScroll: true }
);
};
const handlePerPageChange = (value: string) => {
setPerPage(value);
router.get(
route('inventory.transfer.index'),
{ ...filters, per_page: value },
{ preserveState: false, replace: true, preserveScroll: true }
);
}; };
const handleCreate = () => { const handleCreate = () => {
@@ -84,12 +139,28 @@ export default function Index({ auth, orders, warehouses, filters }) {
}); });
}; };
const getStatusBadge = (status) => { const confirmDelete = (id: string) => {
setDeleteId(id);
};
const handleDelete = () => {
if (deleteId) {
router.delete(route('inventory.transfer.destroy', [deleteId]), {
onSuccess: () => {
setDeleteId(null);
toast.success("已成功刪除");
},
onError: () => setDeleteId(null),
});
}
};
const getStatusBadge = (status: string) => {
switch (status) { switch (status) {
case 'draft': case 'draft':
return <Badge variant="secondary">稿</Badge>; return <Badge variant="secondary">稿</Badge>;
case 'completed': case 'completed':
return <Badge className="bg-green-600"></Badge>; return <Badge className="bg-green-500 hover:bg-green-600"></Badge>;
case 'voided': case 'voided':
return <Badge variant="destructive"></Badge>; return <Badge variant="destructive"></Badge>;
default: default:
@@ -99,92 +170,103 @@ export default function Index({ auth, orders, warehouses, filters }) {
return ( return (
<AuthenticatedLayout <AuthenticatedLayout
user={auth.user} breadcrumbs={[
header={ { label: '商品與庫存與管理', href: '#' },
<div className="flex justify-between items-center"> { label: '庫存調撥', href: route('inventory.transfer.index'), isPage: true },
<h2 className="font-semibold text-xl text-gray-800 leading-tight flex items-center gap-2"> ]}
<ArrowLeftRight className="h-5 w-5" />
調
</h2>
</div>
}
> >
<Head title="庫存調撥" /> <Head title="庫存調撥" />
<div className="py-12"> <div className="container mx-auto p-6 max-w-7xl">
<div className="max-w-7xl mx-auto sm:px-6 lg:px-8"> <div className="flex items-center justify-between mb-6">
<div className="bg-white overflow-hidden shadow-sm sm:rounded-lg"> <div>
<div className="p-6"> <h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<div className="flex justify-between items-center mb-6"> <ArrowLeftRight className="h-6 w-6 text-primary-main" />
<div className="flex items-center gap-4"> 調
<div className="w-[200px]"> </h1>
<Select <p className="text-gray-500 mt-1">
value={filters.warehouse_id || "all"} 調
onValueChange={(val) => handleFilterChange(val === "all" ? "" : val)} </p>
>
<SelectTrigger>
<SelectValue placeholder="篩選倉庫..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
{warehouses.map((w) => (
<SelectItem key={w.id} value={String(w.id)}>{w.name}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="relative flex-1 max-w-sm">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-500" />
<Input
placeholder="搜尋調撥單號..."
className="pl-9"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div> </div>
</div> </div>
{/* Toolbar */}
<div className="bg-white rounded-lg shadow-sm border p-4 mb-6">
<div className="flex flex-col md:flex-row gap-4">
{/* Search */}
<div className="flex-1 relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
<Input
placeholder="搜尋調撥單號、備註..."
value={searchTerm}
onChange={(e) => handleSearchChange(e.target.value)}
className="pl-10 pr-10 h-9"
/>
{searchTerm && (
<button
onClick={handleClearSearch}
className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
>
<X className="h-4 w-4" />
</button>
)}
</div>
{/* Warehouse Filter */}
<SearchableSelect
value={warehouseFilter}
onValueChange={handleFilterChange}
options={[
{ label: "所有倉庫", value: "all" },
...warehouses.map((w: any) => ({ label: w.name, value: w.id.toString() }))
]}
placeholder="選擇倉庫"
className="w-full md:w-[200px] h-9"
/>
{/* Action Buttons */}
<div className="flex gap-2 w-full md:w-auto">
<Can permission="inventory.view">
<Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}> <Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}>
<DialogTrigger asChild> <DialogTrigger asChild>
<Button> <Button className="flex-1 md:flex-none button-filled-primary">
<Plus className="h-4 w-4 mr-2" /> <Plus className="w-4 h-4 mr-2" />
調 調
</Button> </Button>
</DialogTrigger> </DialogTrigger>
<DialogContent> <DialogContent className="sm:max-w-[425px]">
<DialogHeader> <DialogHeader>
<DialogTitle>調</DialogTitle> <DialogTitle>調</DialogTitle>
<DialogDescription>
</DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-4 py-4"> <div className="grid gap-4 py-4">
<div className="space-y-2"> <div className="space-y-2">
<Label></Label> <Label></Label>
<Select onValueChange={setSourceWarehouseId} value={sourceWarehouseId}> <SearchableSelect
<SelectTrigger> value={sourceWarehouseId}
<SelectValue placeholder="選擇來源倉庫" /> onValueChange={setSourceWarehouseId}
</SelectTrigger> options={warehouses.map((w: any) => ({ label: w.name, value: w.id.toString() }))}
<SelectContent> placeholder="請選擇來源倉庫"
{warehouses.map(w => ( className="h-9"
<SelectItem key={w.id} value={String(w.id)}>{w.name}</SelectItem> />
))}
</SelectContent>
</Select>
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label></Label> <Label></Label>
<Select onValueChange={setTargetWarehouseId} value={targetWarehouseId}> <SearchableSelect
<SelectTrigger> value={targetWarehouseId}
<SelectValue placeholder="選擇目的倉庫" /> onValueChange={setTargetWarehouseId}
</SelectTrigger> options={warehouses.filter((w: any) => w.id.toString() !== sourceWarehouseId).map((w: any) => ({ label: w.name, value: w.id.toString() }))}
<SelectContent> placeholder="請選擇目的倉庫"
{warehouses.filter(w => String(w.id) !== sourceWarehouseId).map(w => ( className="h-9"
<SelectItem key={w.id} value={String(w.id)}>{w.name}</SelectItem> />
))}
</SelectContent>
</Select>
</div> </div>
</div> </div>
<DialogFooter> <DialogFooter>
<Button variant="outline" className="button-outlined-primary" onClick={() => setIsCreateOpen(false)}></Button> <Button type="button" variant="outline" className="button-outlined-primary" onClick={() => setIsCreateOpen(false)}>
</Button>
<Button onClick={handleCreate} className="button-filled-primary" disabled={creating || !sourceWarehouseId || !targetWarehouseId}> <Button onClick={handleCreate} className="button-filled-primary" disabled={creating || !sourceWarehouseId || !targetWarehouseId}>
{creating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />} {creating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
@@ -192,49 +274,80 @@ export default function Index({ auth, orders, warehouses, filters }) {
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
</Can>
</div>
</div>
</div> </div>
<div className="rounded-md border"> <div className="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">
<Table> <Table>
<TableHeader> <TableHeader className="bg-gray-50">
<TableRow> <TableRow>
<TableHead></TableHead> <TableHead className="w-[50px] text-center font-medium text-gray-600">#</TableHead>
<TableHead></TableHead> <TableHead className="font-medium text-gray-600"></TableHead>
<TableHead></TableHead> <TableHead className="text-center font-medium text-gray-600"></TableHead>
<TableHead></TableHead> <TableHead className="font-medium text-gray-600"></TableHead>
<TableHead></TableHead> <TableHead className="font-medium text-gray-600"></TableHead>
<TableHead></TableHead> <TableHead className="font-medium text-gray-600"></TableHead>
<TableHead></TableHead> <TableHead className="font-medium text-gray-600"></TableHead>
<TableHead className="text-right"></TableHead> <TableHead className="font-medium text-gray-600"></TableHead>
<TableHead className="text-center font-medium text-gray-600"></TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{orders.data.length === 0 ? ( {orders.data.length === 0 ? (
<TableRow> <TableRow>
<TableCell colSpan={8} className="text-center h-24 text-gray-500"> <TableCell colSpan={9} className="text-center h-24 text-gray-500">
調 調
</TableCell> </TableCell>
</TableRow> </TableRow>
) : ( ) : (
orders.data.map((order) => ( orders.data.map((order: any, index: number) => (
<TableRow key={order.id}> <TableRow
<TableCell className="font-medium">{order.doc_no}</TableCell> key={order.id}
<TableCell>{getStatusBadge(order.status)}</TableCell> className="hover:bg-gray-50/50 transition-colors cursor-pointer group"
<TableCell>{order.from_warehouse_name}</TableCell> onClick={() => router.visit(route('inventory.transfer.show', [order.id]))}
<TableCell>{order.to_warehouse_name}</TableCell>
<TableCell>{order.created_at}</TableCell>
<TableCell>{order.posted_at}</TableCell>
<TableCell>{order.created_by}</TableCell>
<TableCell className="text-right">
<Button
variant="ghost"
size="sm"
asChild
> >
<TableCell className="text-center text-gray-500 font-medium">
{(orders.current_page - 1) * orders.per_page + index + 1}
</TableCell>
<TableCell className="font-medium text-primary-main">{order.doc_no}</TableCell>
<TableCell className="text-center">{getStatusBadge(order.status)}</TableCell>
<TableCell className="text-gray-700">{order.from_warehouse_name}</TableCell>
<TableCell className="text-gray-700">{order.to_warehouse_name}</TableCell>
<TableCell className="text-gray-500 text-sm">{order.created_at}</TableCell>
<TableCell className="text-gray-500 text-sm">{order.posted_at || '-'}</TableCell>
<TableCell className="text-sm">{order.created_by}</TableCell>
<TableCell className="text-center">
<div className="flex items-center justify-center gap-2" onClick={(e) => e.stopPropagation()}>
<Can permission="inventory.view">
<Link href={route('inventory.transfer.show', [order.id])}> <Link href={route('inventory.transfer.show', [order.id])}>
<Button
</Link> variant="outline"
size="sm"
className="button-outlined-primary"
title={['completed', 'voided'].includes(order.status) ? '查閱' : '編輯'}
>
{['completed', 'voided'].includes(order.status) ? (
<Eye className="w-4 h-4 ml-0.5" />
) : (
<Pencil className="w-4 h-4 ml-0.5" />
)}
</Button> </Button>
</Link>
{order.status === 'draft' && (
<Button
variant="outline"
size="sm"
className="button-outlined-error"
title="刪除"
onClick={() => confirmDelete(order.id)}
>
<Trash2 className="w-4 h-4 ml-0.5" />
</Button>
)}
</Can>
</div>
</TableCell> </TableCell>
</TableRow> </TableRow>
)) ))
@@ -243,12 +356,43 @@ export default function Index({ auth, orders, warehouses, filters }) {
</Table> </Table>
</div> </div>
<div className="mt-4"> <div className="mt-4 flex flex-col sm:flex-row items-center justify-between gap-4">
<div className="flex items-center gap-4">
<div className="flex items-center gap-2 text-sm text-gray-500">
<span></span>
<SearchableSelect
value={perPage}
onValueChange={handlePerPageChange}
options={[
{ label: "10", value: "10" },
{ label: "20", value: "20" },
{ label: "50", value: "50" },
{ label: "100", value: "100" }
]}
className="w-[100px] h-8"
showSearch={false}
/>
<span></span>
</div>
<span className="text-sm text-gray-500"> {orders.total} </span>
</div>
<Pagination links={orders.links} /> <Pagination links={orders.links} />
</div> </div>
</div>
</div> <AlertDialog open={!!deleteId} onOpenChange={(open) => !open && setDeleteId(null)}>
</div> <AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>調</AlertDialogTitle>
<AlertDialogDescription>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={handleDelete} className="bg-red-600 hover:bg-red-700"></AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div> </div>
</AuthenticatedLayout> </AuthenticatedLayout>
); );

View File

@@ -1,11 +1,10 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout"; import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, router, usePage, Link } from "@inertiajs/react"; import { Head, router, Link } from "@inertiajs/react";
import { Button } from "@/Components/ui/button"; import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input"; import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label"; import { Label } from "@/Components/ui/label";
import { Textarea } from "@/Components/ui/textarea";
import { import {
Table, Table,
TableBody, TableBody,
@@ -15,38 +14,49 @@ import {
TableRow, TableRow,
} from "@/Components/ui/table"; } from "@/Components/ui/table";
import { Badge } from "@/Components/ui/badge"; import { Badge } from "@/Components/ui/badge";
import { Checkbox } from "@/Components/ui/checkbox";
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
DialogTrigger, DialogTrigger,
DialogFooter,
} from "@/Components/ui/dialog"; } from "@/Components/ui/dialog";
import { import {
Select, AlertDialog,
SelectContent, AlertDialogAction,
SelectItem, AlertDialogCancel,
SelectTrigger, AlertDialogContent,
SelectValue, AlertDialogDescription,
} from "@/Components/ui/select"; AlertDialogFooter,
import { Plus, Save, Trash2, ArrowLeft, CheckCircle, Ban, History, Package } from "lucide-react"; AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/Components/ui/alert-dialog";
import { Plus, Save, Trash2, ArrowLeft, CheckCircle, Package, ArrowLeftRight, Printer, Search } from "lucide-react";
import { toast } from "sonner"; import { toast } from "sonner";
import axios from "axios"; import axios from "axios";
import { Can } from '@/Components/Permission/Can';
export default function Show({ auth, order }) { export default function Show({ order }: any) {
const [items, setItems] = useState(order.items || []); const [items, setItems] = useState(order.items || []);
const [remarks, setRemarks] = useState(order.remarks || ""); const [remarks, setRemarks] = useState(order.remarks || "");
const [isSaving, setIsSaving] = useState(false); const [isSaving, setIsSaving] = useState(false);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [isPostDialogOpen, setIsPostDialogOpen] = useState(false);
// Product Selection // Product Selection
const [isProductDialogOpen, setIsProductDialogOpen] = useState(false); const [isProductDialogOpen, setIsProductDialogOpen] = useState(false);
const [availableInventory, setAvailableInventory] = useState([]); const [availableInventory, setAvailableInventory] = useState<any[]>([]);
const [loadingInventory, setLoadingInventory] = useState(false); const [loadingInventory, setLoadingInventory] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const [selectedInventory, setSelectedInventory] = useState<string[]>([]); // product_id-batch
useEffect(() => { useEffect(() => {
if (isProductDialogOpen) { if (isProductDialogOpen) {
loadInventory(); loadInventory();
setSelectedInventory([]);
setSearchQuery('');
} }
}, [isProductDialogOpen]); }, [isProductDialogOpen]);
@@ -64,39 +74,75 @@ export default function Show({ auth, order }) {
} }
}; };
const handleAddItem = (inventoryItem) => { const toggleSelect = (key: string) => {
// Check if already added setSelectedInventory(prev =>
const exists = items.find(i => prev.includes(key) ? prev.filter(k => k !== key) : [...prev, key]
i.product_id === inventoryItem.product_id &&
i.batch_number === inventoryItem.batch_number
); );
if (exists) {
toast.error("該商品與批號已在列表中");
return;
}
setItems([...items, {
product_id: inventoryItem.product_id,
product_name: inventoryItem.product_name,
product_code: inventoryItem.product_code,
batch_number: inventoryItem.batch_number,
unit: inventoryItem.unit_name,
quantity: 1, // Default 1
max_quantity: inventoryItem.quantity, // Max available
notes: "",
}]);
setIsProductDialogOpen(false);
}; };
const handleUpdateItem = (index, field, value) => { 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])));
}
};
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)) {
// Check if already added
const exists = newItems.find((i: any) =>
i.product_id === inv.product_id &&
i.batch_number === inv.batch_number
);
if (!exists) {
newItems.push({
product_id: inv.product_id,
product_name: inv.product_name,
product_code: inv.product_code,
batch_number: inv.batch_number,
unit: inv.unit_name,
quantity: 1, // Default 1
max_quantity: inv.quantity, // Max available
notes: "",
});
addedCount++;
}
}
});
setItems(newItems);
setIsProductDialogOpen(false);
if (addedCount > 0) {
toast.success(`已成功加入 ${addedCount} 個項目`);
} else {
toast.info("選取的商品已在清單中");
}
};
const handleUpdateItem = (index: number, field: string, value: any) => {
const newItems = [...items]; const newItems = [...items];
newItems[index][field] = value; newItems[index][field] = value;
setItems(newItems); setItems(newItems);
}; };
const handleRemoveItem = (index) => { const handleRemoveItem = (index: number) => {
const newItems = items.filter((_, i) => i !== index); const newItems = items.filter((_: any, i: number) => i !== index);
setItems(newItems); setItems(newItems);
}; };
@@ -116,32 +162,39 @@ export default function Show({ auth, order }) {
}; };
const handlePost = () => { const handlePost = () => {
if (!confirm("確定要過帳嗎?過帳後庫存將立即轉移且無法修改。")) return;
router.put(route('inventory.transfer.update', [order.id]), { router.put(route('inventory.transfer.update', [order.id]), {
action: 'post' action: 'post'
}, {
onSuccess: () => {
setIsPostDialogOpen(false);
toast.success("過帳成功");
}
}); });
}; };
const handleDelete = () => { const handleDelete = () => {
if (!confirm("確定要刪除此草稿嗎?")) return; router.delete(route('inventory.transfer.destroy', [order.id]), {
router.delete(route('inventory.transfer.destroy', [order.id])); onSuccess: () => {
setDeleteId(null);
toast.success("已成功刪除");
}
});
}; };
const isReadOnly = order.status !== 'draft'; const isReadOnly = order.status !== 'draft';
return ( return (
<AuthenticatedLayout <AuthenticatedLayout
user={auth.user}
breadcrumbs={[ breadcrumbs={[
{ label: '首頁', href: '/' }, { label: '商品與庫存管理', href: '#' },
{ label: '庫存調撥', href: route('inventory.transfer.index') }, { label: '庫存調撥', href: route('inventory.transfer.index') },
{ label: order.doc_no, href: route('inventory.transfer.show', [order.id]) }, { label: `調撥單: ${order.doc_no}`, href: route('inventory.transfer.show', [order.id]), isPage: true },
]} ]}
> >
<Head title={`調撥單 ${order.doc_no}`} /> <Head title={`調撥單 ${order.doc_no}`} />
<div className="container mx-auto p-6 max-w-7xl"> <div className="container mx-auto p-6 max-w-7xl animate-in fade-in duration-500 space-y-6">
<div className="mb-6"> <div>
<Link href={route('inventory.transfer.index')}> <Link href={route('inventory.transfer.index')}>
<Button <Button
variant="outline" variant="outline"
@@ -152,182 +205,327 @@ export default function Show({ auth, order }) {
</Button> </Button>
</Link> </Link>
<div className="flex justify-between items-center"> <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<h2 className="font-bold text-2xl text-gray-800 leading-tight flex items-center gap-2"> <div>
調 ({order.doc_no}) <div className="flex items-center gap-2">
</h2> <h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<div className="flex gap-2"> <ArrowLeftRight className="h-6 w-6 text-primary-main" />
調: {order.doc_no}
</h1>
{order.status === 'completed' && <Badge className="bg-green-500 hover:bg-green-600"></Badge>}
{order.status === 'draft' && <Badge className="bg-blue-500 hover:bg-blue-600">稿</Badge>}
{order.status === 'voided' && <Badge variant="destructive"></Badge>}
</div>
<p className="text-sm text-gray-500 mt-1 font-medium">
: {order.from_warehouse_name} <ArrowLeftRight className="inline-block h-3 w-3 mx-1" /> : {order.to_warehouse_name} <span className="mx-2">|</span> : {order.created_by}
</p>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
className="button-outlined-primary"
onClick={() => window.print()}
>
<Printer className="w-4 h-4 mr-2" />
</Button>
{!isReadOnly && ( {!isReadOnly && (
<> <div className="flex items-center gap-2">
<Button variant="destructive" onClick={handleDelete}> <Can permission="inventory.view">
<Trash2 className="h-4 w-4 mr-2" /> <AlertDialog open={!!deleteId} onOpenChange={(open) => !open && setDeleteId(null)}>
<AlertDialogTrigger asChild>
<Button variant="outline" size="sm" className="button-outlined-error" onClick={() => setDeleteId(order.id)}>
<Trash2 className="w-4 h-4 mr-2" />
</Button> </Button>
<Button variant="outline" onClick={handleSave} disabled={isSaving}> </AlertDialogTrigger>
<Save className="h-4 w-4 mr-2" /> <AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>調</AlertDialogTitle>
<AlertDialogDescription>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={handleDelete} className="bg-red-600 hover:bg-red-700"></AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<Button
variant="outline"
size="sm"
className="button-outlined-primary"
onClick={handleSave}
disabled={isSaving}
>
<Save className="w-4 h-4 mr-2" />
稿 稿
</Button> </Button>
<Button onClick={handlePost} disabled={items.length === 0}>
<CheckCircle className="h-4 w-4 mr-2" /> <AlertDialog open={isPostDialogOpen} onOpenChange={setIsPostDialogOpen}>
<AlertDialogTrigger asChild>
<Button
size="sm"
className="button-filled-primary"
disabled={items.length === 0 || isSaving}
>
<CheckCircle className="w-4 h-4 mr-2" />
</Button> </Button>
</> </AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle></AlertDialogTitle>
<AlertDialogDescription>
{order.from_warehouse_name}{order.to_warehouse_name}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={handlePost} className="bg-primary-600 hover:bg-primary-700"></AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</Can>
</div>
)} )}
</div> </div>
</div> </div>
</div> </div>
<div className="space-y-6"> <div className="bg-white rounded-lg shadow-sm border p-6 space-y-4">
{/* Header Info */} <div className="flex items-center justify-between">
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-100 grid grid-cols-1 md:grid-cols-4 gap-6"> <Label className="text-gray-500 font-semibold"></Label>
<div>
<Label className="text-gray-500"></Label>
<div className="font-medium text-lg">{order.from_warehouse_name}</div>
</div> </div>
<div>
<Label className="text-gray-500"></Label>
<div className="font-medium text-lg">{order.to_warehouse_name}</div>
</div>
<div>
<Label className="text-gray-500"></Label>
<div className="mt-1">
{order.status === 'draft' && <Badge variant="secondary">稿</Badge>}
{order.status === 'completed' && <Badge className="bg-green-600"></Badge>}
{order.status === 'voided' && <Badge variant="destructive"></Badge>}
</div>
</div>
<div>
<Label className="text-gray-500"></Label>
{isReadOnly ? ( {isReadOnly ? (
<div className="mt-1 text-gray-700">{order.remarks || '-'}</div> <div className="text-gray-700 p-2 bg-gray-50 rounded border text-sm min-h-[40px]">
{order.remarks || '無備註'}
</div>
) : ( ) : (
<Input <Input
value={remarks} value={remarks}
onChange={(e) => setRemarks(e.target.value)} onChange={(e) => setRemarks(e.target.value)}
className="mt-1" className="h-9 focus:ring-primary-main"
placeholder="填寫備註..." placeholder="填寫調撥單備註..."
/> />
)} )}
</div> </div>
</div>
{/* Items */} <div className="bg-white rounded-lg shadow-sm border p-6 space-y-4">
<div className="bg-white overflow-hidden shadow-sm sm:rounded-lg"> <div className="flex items-center justify-between">
<div className="p-6"> <div>
<div className="flex justify-between items-center mb-4"> <h3 className="font-semibold text-lg text-grey-900">調</h3>
<h3 className="text-lg font-semibold">調</h3> <p className="text-sm text-grey-500">
調{order.from_warehouse_name}
</p>
</div>
{!isReadOnly && ( {!isReadOnly && (
<Dialog open={isProductDialogOpen} onOpenChange={setIsProductDialogOpen}> <Dialog open={isProductDialogOpen} onOpenChange={setIsProductDialogOpen}>
<DialogTrigger asChild> <DialogTrigger asChild>
<Button variant="outline"> <Button variant="outline" className="button-outlined-primary">
<Plus className="h-4 w-4 mr-2" /> <Plus className="h-4 w-4 mr-2" />
</Button> </Button>
</DialogTrigger> </DialogTrigger>
<DialogContent className="max-w-3xl max-h-[80vh] overflow-y-auto"> <DialogContent className="max-w-4xl max-h-[85vh] flex flex-col p-6">
<DialogHeader> <DialogHeader className="flex flex-row items-center justify-between space-y-0 pb-4">
<DialogTitle> ({order.from_warehouse_name})</DialogTitle> <DialogTitle className="text-xl"> ({order.from_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> </DialogHeader>
<div className="mt-4"> <div className="flex-1 overflow-auto pr-1">
{loadingInventory ? ( {loadingInventory ? (
<div className="text-center py-4">...</div> <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> <Table>
<TableHeader> <TableHeader className="bg-gray-50/80 sticky top-0 z-10 shadow-sm">
<TableRow> <TableRow>
<TableHead></TableHead> <TableHead className="w-[50px] text-center">
<TableHead></TableHead> <Checkbox
<TableHead></TableHead> checked={availableInventory.length > 0 && (() => {
<TableHead className="text-right"></TableHead> const filtered = availableInventory.filter(inv =>
<TableHead></TableHead> 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}`);
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> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{availableInventory.map((inv) => ( {(() => {
<TableRow key={`${inv.product_id}-${inv.batch_number}`}> const filtered = availableInventory.filter(inv =>
<TableCell>{inv.product_code}</TableCell> inv.product_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
<TableCell>{inv.product_name}</TableCell> inv.product_code.toLowerCase().includes(searchQuery.toLowerCase())
<TableCell>{inv.batch_number || '-'}</TableCell> );
<TableCell className="text-right">{inv.quantity} {inv.unit_name}</TableCell>
<TableCell className="text-right"> if (filtered.length === 0) {
<Button size="sm" onClick={() => handleAddItem(inv)}> return (
<TableRow>
</Button> <TableCell colSpan={5} className="text-center py-12 text-grey-3 italic font-medium">
{searchQuery ? `找不到與 "${searchQuery}" 相關的商品` : '尚無庫存資料'}
</TableCell> </TableCell>
</TableRow> </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> </TableBody>
</Table> </Table>
</div>
)} )}
</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> </DialogContent>
</Dialog> </Dialog>
)} )}
</div> </div>
<div className="rounded-md border"> <div className="border rounded-lg overflow-hidden">
<Table> <Table>
<TableHeader> <TableHeader className="bg-gray-50">
<TableRow> <TableRow>
<TableHead className="w-[50px]">#</TableHead> <TableHead className="w-[50px] text-center font-medium text-grey-600">#</TableHead>
<TableHead></TableHead> <TableHead className="font-medium text-grey-600"> / </TableHead>
<TableHead></TableHead> <TableHead className="font-medium text-grey-600"></TableHead>
<TableHead className="w-[150px]">調</TableHead> <TableHead className="text-right w-32 font-medium text-grey-600"></TableHead>
<TableHead></TableHead> <TableHead className="text-right w-40 font-medium text-grey-600">調</TableHead>
<TableHead></TableHead> <TableHead className="font-medium text-grey-600"></TableHead>
<TableHead className="font-medium text-grey-600"></TableHead>
{!isReadOnly && <TableHead className="w-[50px]"></TableHead>} {!isReadOnly && <TableHead className="w-[50px]"></TableHead>}
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{items.length === 0 ? ( {items.length === 0 ? (
<TableRow> <TableRow>
<TableCell colSpan={7} className="text-center h-24 text-gray-500"> <TableCell colSpan={8} className="text-center h-24 text-gray-500">
</TableCell> </TableCell>
</TableRow> </TableRow>
) : ( ) : (
items.map((item, index) => ( items.map((item: any, index: number) => (
<TableRow key={index}> <TableRow key={index}>
<TableCell>{index + 1}</TableCell> <TableCell className="text-center text-gray-500 font-medium">{index + 1}</TableCell>
<TableCell> <TableCell className="py-3">
<div>{item.product_name}</div> <div className="flex flex-col">
<div className="text-xs text-gray-500">{item.product_code}</div> <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>
<TableCell>{item.batch_number || '-'}</TableCell> <TableCell className="text-sm font-mono">{item.batch_number || '-'}</TableCell>
<TableCell> <TableCell className="text-right font-semibold text-primary-main">
{item.max_quantity} {item.unit || item.unit_name}
</TableCell>
<TableCell className="px-1 py-3">
{isReadOnly ? ( {isReadOnly ? (
item.quantity <div className="text-right font-semibold mr-2">{item.quantity}</div>
) : ( ) : (
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-1 items-end pr-2">
<Input <Input
type="number" type="number"
min="0.01" min="0.01"
step="0.01" step="0.01"
value={item.quantity} value={item.quantity}
onChange={(e) => handleUpdateItem(index, 'quantity', e.target.value)} onChange={(e) => handleUpdateItem(index, 'quantity', e.target.value)}
className="h-9 w-32 text-right font-medium focus:ring-primary-main"
/> />
{item.max_quantity && (
<span className="text-xs text-gray-500">: {item.max_quantity}</span>
)}
</div> </div>
)} )}
</TableCell> </TableCell>
<TableCell>{item.unit}</TableCell> <TableCell className="text-sm text-gray-500">{item.unit || item.unit_name}</TableCell>
<TableCell> <TableCell className="px-1">
{isReadOnly ? ( {isReadOnly ? (
item.notes <span className="text-sm text-gray-600">{item.notes}</span>
) : ( ) : (
<Input <Input
value={item.notes} value={item.notes}
onChange={(e) => handleUpdateItem(index, 'notes', e.target.value)} onChange={(e) => handleUpdateItem(index, 'notes', e.target.value)}
placeholder="備註" placeholder="備註..."
className="h-9 text-sm"
/> />
)} )}
</TableCell> </TableCell>
{!isReadOnly && ( {!isReadOnly && (
<TableCell> <TableCell className="text-center">
<Button variant="ghost" size="icon" onClick={() => handleRemoveItem(index)}> <Button variant="ghost" size="sm" className="h-8 w-8 text-red-400 hover:text-red-600 hover:bg-red-50 p-0" onClick={() => handleRemoveItem(index)}>
<Trash2 className="h-4 w-4 text-red-500" /> <Trash2 className="h-4 w-4" />
</Button> </Button>
</TableCell> </TableCell>
)} )}
@@ -339,8 +537,6 @@ export default function Show({ auth, order }) {
</div> </div>
</div> </div>
</div> </div>
</div>
</div>
</AuthenticatedLayout> </AuthenticatedLayout>
); );
} }