優化: 門市叫貨模組 UI 調整、權限標籤中文化及調撥單動態導覽

This commit is contained in:
2026-02-13 10:39:10 +08:00
parent 882091ce5f
commit 097708aab7
17 changed files with 2359 additions and 6 deletions

View File

@@ -195,21 +195,28 @@ export default function Show({ order }: any) {
<AuthenticatedLayout
breadcrumbs={[
{ label: '商品與庫存管理', href: '#' },
{ label: '庫存調撥', href: route('inventory.transfer.index') },
{
label: order.requisition ? '門市叫貨申請' : '庫存調撥',
href: order.requisition ? route('store-requisitions.index') : route('inventory.transfer.index')
},
order.requisition && {
label: `叫貨單: ${order.requisition.doc_no}`,
href: route('store-requisitions.show', [order.requisition.id])
},
{ label: `調撥單: ${order.doc_no}`, href: route('inventory.transfer.show', [order.id]), isPage: true },
]}
].filter(Boolean) as any}
>
<Head title={`調撥單 ${order.doc_no}`} />
<div className="container mx-auto p-6 max-w-7xl animate-in fade-in duration-500 space-y-6">
<div>
<Link href={route('inventory.transfer.index')}>
<Link href={order.requisition ? route('store-requisitions.show', [order.requisition.id]) : route('inventory.transfer.index')}>
<Button
variant="outline"
className="gap-2 button-outlined-primary mb-6"
>
<ArrowLeft className="h-4 w-4" />
調
{order.requisition ? `返回叫貨單: ${order.requisition.doc_no}` : '返回調撥單列表'}
</Button>
</Link>

View File

@@ -0,0 +1,374 @@
import { useState } from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, Link, router } from "@inertiajs/react";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Textarea } from "@/Components/ui/textarea";
import { Label } from "@/Components/ui/label";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/Components/ui/table";
import { toast } from "sonner";
import {
Store,
Plus,
Trash2,
Loader2,
Save,
SendHorizontal,
ArrowLeft,
} from "lucide-react";
interface Product {
id: number;
name: string;
code: string;
unit_name: string;
}
interface Warehouse {
id: number;
name: string;
type: string;
}
interface RequisitionItem {
product_id: string;
requested_qty: string;
remark: string;
}
interface Props {
requisition?: {
id: number;
store_warehouse_id: number;
remark: string | null;
status: string;
items: {
id: number;
product_id: number;
requested_qty: number;
remark: string | null;
}[];
};
warehouses: Warehouse[];
products: Product[];
}
export default function Create({ requisition, warehouses, products }: Props) {
const isEditing = !!requisition;
const [storeWarehouseId, setStoreWarehouseId] = useState(
requisition?.store_warehouse_id?.toString() || ""
);
const [remark, setRemark] = useState(requisition?.remark || "");
const [items, setItems] = useState<RequisitionItem[]>(
requisition?.items?.map((item) => ({
product_id: item.product_id.toString(),
requested_qty: item.requested_qty.toString(),
remark: item.remark || "",
})) || [{ product_id: "", requested_qty: "", remark: "" }]
);
const [saving, setSaving] = useState(false);
const [submitting, setSubmitting] = useState(false);
const addItem = () => {
setItems([...items, { product_id: "", requested_qty: "", remark: "" }]);
};
const removeItem = (index: number) => {
if (items.length <= 1) {
toast.error("至少需要一項商品");
return;
}
setItems(items.filter((_, i) => i !== index));
};
const updateItem = (index: number, field: keyof RequisitionItem, value: string) => {
const newItems = [...items];
newItems[index] = { ...newItems[index], [field]: value };
setItems(newItems);
};
const validate = (): boolean => {
if (!storeWarehouseId) {
toast.error("請選擇申請倉庫");
return false;
}
if (items.length === 0) {
toast.error("至少需要一項商品");
return false;
}
for (let i = 0; i < items.length; i++) {
if (!items[i].product_id) {
toast.error(`${i + 1} 行請選擇商品`);
return false;
}
const qty = parseInt(items[i].requested_qty);
if (!qty || qty < 1) {
toast.error(`${i + 1} 行需求數量必須大於等於 1`);
return false;
}
}
// 檢查是否有重複商品
const productIds = items.map((item) => item.product_id);
if (new Set(productIds).size !== productIds.length) {
toast.error("不可重複選擇商品");
return false;
}
return true;
};
const handleSave = (submitImmediately: boolean = false) => {
if (!validate()) return;
const setter = submitImmediately ? setSubmitting : setSaving;
setter(true);
const payload = {
store_warehouse_id: storeWarehouseId,
remark: remark || null,
items: items.map((item) => ({
product_id: parseInt(item.product_id),
requested_qty: parseFloat(item.requested_qty),
remark: item.remark || null,
})),
submit_immediately: submitImmediately,
};
if (isEditing) {
router.put(route("store-requisitions.update", [requisition!.id]), payload, {
onFinish: () => setter(false),
});
} else {
router.post(route("store-requisitions.store"), payload, {
onFinish: () => setter(false),
});
}
};
// 已選商品列表(用於過濾下拉選項)
const selectedProductIds = items.map((item) => item.product_id).filter(Boolean);
return (
<AuthenticatedLayout
breadcrumbs={[
{ label: "商品與庫存管理", href: "#" },
{ label: "門市叫貨", href: route("store-requisitions.index") },
{
label: isEditing ? "編輯叫貨單" : "新增叫貨單",
href: "#",
isPage: true,
},
]}
>
<Head title={isEditing ? "編輯叫貨單" : "新增叫貨單"} />
<div className="container mx-auto p-6 max-w-7xl">
{/* 返回按鈕 */}
<div className="mb-6">
<Link href={route("store-requisitions.index")}>
<Button variant="outline" className="gap-2 button-outlined-primary">
<ArrowLeft className="h-4 w-4" />
</Button>
</Link>
</div>
{/* 頁面標題 */}
<div className="mb-6">
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<Store className="h-6 w-6 text-primary-main" />
{isEditing ? `編輯叫貨單 ${requisition?.status === "rejected" ? "(重新提交)" : ""}` : "新增叫貨單"}
</h1>
<p className="text-gray-500 mt-1">
</p>
</div>
{/* 基本資訊 */}
<div className="bg-white rounded-lg shadow-sm border p-6 mb-6">
<h2 className="text-lg font-semibold text-gray-800 mb-4"></h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-2">
<Label>
<span className="text-red-500">*</span>
</Label>
<SearchableSelect
value={storeWarehouseId}
onValueChange={setStoreWarehouseId}
options={warehouses.map((w) => ({
label: w.name,
value: w.id.toString(),
}))}
placeholder="請選擇倉庫"
className="h-9"
/>
<p className="text-xs text-gray-400"></p>
</div>
<div className="space-y-2">
<Label></Label>
<Textarea
value={remark}
onChange={(e) => setRemark(e.target.value)}
placeholder="補充說明(選填)"
rows={3}
/>
</div>
</div>
</div>
{/* 商品明細 */}
<div className="bg-white rounded-lg shadow-sm border p-6 mb-6">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold text-gray-800"></h2>
<Button
type="button"
variant="outline"
size="sm"
className="button-outlined-primary"
onClick={addItem}
>
<Plus className="w-4 h-4 mr-1" />
</Button>
</div>
<div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
<Table>
<TableHeader className="bg-gray-50">
<TableRow>
<TableHead className="w-[50px] text-center font-medium text-gray-600">
#
</TableHead>
<TableHead className="font-medium text-gray-600 min-w-[250px]">
<span className="text-red-500">*</span>
</TableHead>
<TableHead className="font-medium text-gray-600 w-[150px]">
<span className="text-red-500">*</span>
</TableHead>
<TableHead className="font-medium text-gray-600 w-[100px]"></TableHead>
<TableHead className="font-medium text-gray-600 min-w-[150px]"></TableHead>
<TableHead className="w-[60px] text-center font-medium text-gray-600">
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{items.map((item, index) => {
const selectedProduct = products.find(
(p) => String(p.id) === String(item.product_id)
);
return (
<TableRow key={index}>
<TableCell className="text-center text-gray-500 font-medium">
{index + 1}
</TableCell>
<TableCell>
<SearchableSelect
value={item.product_id}
onValueChange={(val) =>
updateItem(index, "product_id", val)
}
options={products
.filter(
(p) =>
!selectedProductIds.includes(
p.id.toString()
) ||
p.id.toString() === item.product_id
)
.map((p) => ({
label: `${p.code} - ${p.name}`,
value: p.id.toString(),
}))}
placeholder="選擇商品"
className="h-9"
/>
</TableCell>
<TableCell>
<Input
type="number"
step="1"
min="1"
value={item.requested_qty}
onChange={(e) =>
updateItem(index, "requested_qty", e.target.value)
}
placeholder="0"
className="h-9 text-right"
/>
</TableCell>
<TableCell className="text-gray-500">
{selectedProduct?.unit_name || "-"}
</TableCell>
<TableCell>
<Input
value={item.remark}
onChange={(e) =>
updateItem(index, "remark", e.target.value)
}
placeholder="備註"
className="h-9"
/>
</TableCell>
<TableCell className="text-center">
<Button
variant="outline"
size="sm"
onClick={() => removeItem(index)}
className="button-outlined-error"
>
<Trash2 className="w-4 h-4" />
</Button>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
</div>
{/* 操作按鈕列 */}
<div className="flex items-center justify-end gap-3">
<Button
type="button"
variant="outline"
className="button-outlined-primary"
onClick={() => router.visit(route("store-requisitions.index"))}
>
</Button>
<Button
type="button"
variant="outline"
className="button-outlined-primary"
disabled={saving || submitting}
onClick={() => handleSave(false)}
>
{saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
<Save className="w-4 h-4 mr-1" />
稿
</Button>
<Button
type="button"
className="button-filled-primary"
disabled={saving || submitting}
onClick={() => handleSave(true)}
>
{submitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
<SendHorizontal className="w-4 h-4 mr-1" />
</Button>
</div>
</div>
</AuthenticatedLayout>
);
}

View File

@@ -0,0 +1,407 @@
import { useState, useCallback, useEffect } from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, Link, router } from "@inertiajs/react";
import { debounce } from "lodash";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/Components/ui/table";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Badge } from "@/Components/ui/badge";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/Components/ui/alert-dialog";
import Pagination from "@/Components/shared/Pagination";
import { toast } from "sonner";
import { Can } from "@/Components/Permission/Can";
import { usePermission } from "@/hooks/usePermission";
import {
Plus,
Search,
Store,
Eye,
Pencil,
Trash2,
X,
} from "lucide-react";
import { formatDate } from "@/lib/date";
const statusMap: Record<string, { label: string; variant: string }> = {
draft: { label: "草稿", variant: "secondary" },
pending: { label: "待審核", variant: "warning" },
approved: { label: "已核准", variant: "success" },
rejected: { label: "已駁回", variant: "destructive" },
completed: { label: "已完成", variant: "default" },
cancelled: { label: "已取消", variant: "outline" },
};
function getStatusBadge(status: string) {
const config = statusMap[status];
if (!config) return <Badge variant="outline">{status}</Badge>;
const variantClass: Record<string, string> = {
secondary: "",
warning: "bg-amber-500 hover:bg-amber-600 text-white",
success: "bg-green-500 hover:bg-green-600 text-white",
destructive: "",
default: "bg-blue-500 hover:bg-blue-600 text-white",
outline: "",
};
const variant = ["secondary", "destructive", "outline"].includes(config.variant)
? (config.variant as "secondary" | "destructive" | "outline")
: "default";
return (
<Badge variant={variant} className={variantClass[config.variant] || ""}>
{config.label}
</Badge>
);
}
export default function Index({
requisitions,
filters,
warehouses,
}: {
requisitions: any;
filters: any;
warehouses: { id: number; name: string }[];
}) {
const { can } = usePermission();
const [searchTerm, setSearchTerm] = useState(filters.search || "");
const [statusFilter, setStatusFilter] = useState(filters.status || "all");
const [warehouseFilter, setWarehouseFilter] = useState(filters.warehouse_id || "all");
const [perPage, setPerPage] = useState(filters.per_page || "10");
const [deleteId, setDeleteId] = useState<string | null>(null);
useEffect(() => {
setSearchTerm(filters.search || "");
setStatusFilter(filters.status || "all");
setWarehouseFilter(filters.warehouse_id || "all");
setPerPage(filters.per_page || "10");
}, [filters]);
const applyFilters = useCallback(
(overrides: Record<string, string> = {}) => {
const params: Record<string, string> = {
search: searchTerm,
status: statusFilter === "all" ? "" : statusFilter,
warehouse_id: warehouseFilter === "all" ? "" : warehouseFilter,
per_page: perPage,
...overrides,
};
// 清理空值
Object.keys(params).forEach((key) => {
if (!params[key]) delete params[key];
});
router.get(route("store-requisitions.index"), params, {
preserveState: true,
replace: true,
preserveScroll: true,
});
},
[searchTerm, statusFilter, warehouseFilter, perPage]
);
const debouncedSearch = useCallback(
debounce((term: string) => {
applyFilters({ search: term });
}, 500),
[applyFilters]
);
const handleSearchChange = (term: string) => {
setSearchTerm(term);
debouncedSearch(term);
};
const handleClearSearch = () => {
setSearchTerm("");
applyFilters({ search: "" });
};
const handleStatusChange = (value: string) => {
setStatusFilter(value);
applyFilters({ status: value === "all" ? "" : value });
};
const handleWarehouseChange = (value: string) => {
setWarehouseFilter(value);
applyFilters({ warehouse_id: value === "all" ? "" : value });
};
const handlePerPageChange = (value: string) => {
setPerPage(value);
applyFilters({ per_page: value });
};
const handleDelete = () => {
if (deleteId) {
router.delete(route("store-requisitions.destroy", [deleteId]), {
onSuccess: () => {
setDeleteId(null);
toast.success("已成功刪除");
},
onError: () => setDeleteId(null),
});
}
};
return (
<AuthenticatedLayout
breadcrumbs={[
{ label: "商品與庫存管理", href: "#" },
{ label: "門市叫貨", href: route("store-requisitions.index"), isPage: true },
]}
>
<Head title="門市叫貨" />
<div className="container mx-auto p-6 max-w-7xl">
{/* 頁面標題 */}
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<Store className="h-6 w-6 text-primary-main" />
</h1>
<p className="text-gray-500 mt-1">
</p>
</div>
</div>
{/* 篩選工具列 */}
<div className="bg-white rounded-lg shadow-sm border p-4 mb-6">
<div className="flex flex-col md:flex-row gap-4">
{/* 搜尋 */}
<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>
{/* 狀態篩選 */}
<SearchableSelect
value={statusFilter}
onValueChange={handleStatusChange}
options={[
{ label: "所有狀態", value: "all" },
{ label: "草稿", value: "draft" },
{ label: "待審核", value: "pending" },
{ label: "已核准", value: "approved" },
{ label: "已駁回", value: "rejected" },
{ label: "已完成", value: "completed" },
{ label: "已取消", value: "cancelled" },
]}
placeholder="選擇狀態"
className="w-full md:w-[160px] h-9"
showSearch={false}
/>
{/* 倉庫篩選 */}
<SearchableSelect
value={warehouseFilter}
onValueChange={handleWarehouseChange}
options={[
{ label: "所有倉庫", value: "all" },
...warehouses.map((w) => ({
label: w.name,
value: w.id.toString(),
})),
]}
placeholder="選擇倉庫"
className="w-full md:w-[200px] h-9"
/>
{/* 操作按鈕 */}
<div className="flex gap-2 w-full md:w-auto">
<Can permission="store_requisitions.create">
<Link href={route("store-requisitions.create")}>
<Button className="flex-1 md:flex-none button-filled-primary">
<Plus className="w-4 h-4 mr-2" />
</Button>
</Link>
</Can>
</div>
</div>
</div>
{/* 資料表格 */}
<div className="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">
<Table>
<TableHeader className="bg-gray-50">
<TableRow>
<TableHead className="w-[50px] text-center font-medium text-gray-600">#</TableHead>
<TableHead className="font-medium text-gray-600"></TableHead>
<TableHead className="font-medium text-gray-600"></TableHead>
<TableHead className="font-medium text-gray-600"></TableHead>
<TableHead className="font-medium text-gray-600"></TableHead>
<TableHead className="font-medium text-gray-600"></TableHead>
<TableHead className="text-center font-medium text-gray-600"></TableHead>
<TableHead className="text-center font-medium text-gray-600"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{requisitions.data.length === 0 ? (
<TableRow>
<TableCell colSpan={8} className="text-center h-24 text-gray-500">
</TableCell>
</TableRow>
) : (
requisitions.data.map((req: any, index: number) => (
<TableRow
key={req.id}
className="hover:bg-gray-50/50 transition-colors cursor-pointer group"
onClick={() =>
router.visit(route("store-requisitions.show", [req.id]))
}
>
<TableCell className="text-center text-gray-500 font-medium">
{(requisitions.current_page - 1) * requisitions.per_page + index + 1}
</TableCell>
<TableCell className="font-medium text-primary-main">
{req.doc_no}
</TableCell>
<TableCell className="text-gray-700">
{req.store_warehouse_name}
</TableCell>
<TableCell className="text-gray-700">
{req.supply_warehouse_name}
</TableCell>
<TableCell className="text-sm">{req.creator_name}</TableCell>
<TableCell className="text-gray-500 text-sm">
{formatDate(req.created_at)}
</TableCell>
<TableCell className="text-center">
{getStatusBadge(req.status)}
</TableCell>
<TableCell className="text-center">
<div
className="flex items-center justify-center gap-2"
onClick={(e) => e.stopPropagation()}
>
{(() => {
const isEditable = ["draft", "rejected"].includes(req.status);
const canEdit = can("store_requisitions.edit");
if (isEditable && canEdit) {
return (
<Link href={route("store-requisitions.edit", [req.id])}>
<Button
variant="outline"
size="sm"
className="button-outlined-primary"
title="編輯"
>
<Pencil className="w-4 h-4 ml-0.5" />
</Button>
</Link>
);
}
return (
<Link href={route("store-requisitions.show", [req.id])}>
<Button
variant="outline"
size="sm"
className="button-outlined-primary"
title="查閱"
>
<Eye className="w-4 h-4 ml-0.5" />
</Button>
</Link>
);
})()}
{req.status === "draft" && (
<Can permission="store_requisitions.delete">
<Button
variant="outline"
size="sm"
className="button-outlined-error"
title="刪除"
onClick={() => setDeleteId(req.id)}
>
<Trash2 className="w-4 h-4 ml-0.5" />
</Button>
</Can>
)}
</div>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
{/* 分頁 */}
<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-[90px] h-8"
showSearch={false}
/>
<span></span>
</div>
<span className="text-sm text-gray-500"> {requisitions.total} </span>
</div>
<Pagination links={requisitions.links} />
</div>
{/* 刪除確認對話框 */}
<AlertDialog open={!!deleteId} onOpenChange={(open) => !open && setDeleteId(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle></AlertDialogTitle>
<AlertDialogDescription>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={handleDelete} className="button-filled-error">
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</AuthenticatedLayout>
);
}

View File

@@ -0,0 +1,601 @@
import { useState } from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, Link, router } from "@inertiajs/react";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Textarea } from "@/Components/ui/textarea";
import { Label } from "@/Components/ui/label";
import { Badge } from "@/Components/ui/badge";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/Components/ui/table";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
DialogDescription,
} from "@/Components/ui/dialog";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/Components/ui/alert-dialog";
import { toast } from "sonner";
import { Can } from "@/Components/Permission/Can";
import { usePermission } from "@/hooks/usePermission";
import {
Store,
SendHorizontal,
CheckCircle2,
XCircle,
Pencil,
Loader2,
ArrowLeft,
} from "lucide-react";
import { formatDate } from "@/lib/date";
const statusMap: Record<string, { label: string; variant: string }> = {
draft: { label: "草稿", variant: "secondary" },
pending: { label: "待審核", variant: "warning" },
approved: { label: "已核准", variant: "success" },
rejected: { label: "已駁回", variant: "destructive" },
completed: { label: "已完成", variant: "default" },
cancelled: { label: "已取消", variant: "outline" },
};
function getStatusBadge(status: string) {
const config = statusMap[status];
if (!config) return <Badge variant="outline">{status}</Badge>;
const variantClass: Record<string, string> = {
secondary: "",
warning: "bg-amber-500 hover:bg-amber-600 text-white",
success: "bg-green-500 hover:bg-green-600 text-white",
destructive: "",
default: "bg-blue-500 hover:bg-blue-600 text-white",
outline: "",
};
const variant = ["secondary", "destructive", "outline"].includes(config.variant)
? (config.variant as "secondary" | "destructive" | "outline")
: "default";
return (
<Badge variant={variant} className={variantClass[config.variant] || ""}>
{config.label}
</Badge>
);
}
interface RequisitionItem {
id: number;
product_id: number;
product_name: string;
product_code: string;
unit_name: string;
requested_qty: number;
approved_qty: number | null;
current_stock: number;
remark: string | null;
}
interface Requisition {
id: number;
doc_no: string;
status: string;
store_warehouse_id: number;
store_warehouse_name: string;
supply_warehouse_id: number | null;
supply_warehouse_name: string;
remark: string | null;
reject_reason: string | null;
creator_name: string;
approver_name: string;
submitted_at: string | null;
approved_at: string | null;
transfer_order_id: number | null;
created_at: string;
items: RequisitionItem[];
}
interface Props {
requisition: Requisition;
warehouses: { id: number; name: string }[];
activities: any[];
}
export default function Show({ requisition, warehouses }: Props) {
usePermission();
const [submitting, setSubmitting] = useState(false);
const [approving, setApproving] = useState(false);
const [rejecting, setRejecting] = useState(false);
// 核准狀態
const [showApproveDialog, setShowApproveDialog] = useState(false);
const [supplyWarehouseId, setSupplyWarehouseId] = useState("");
const [approvedItems, setApprovedItems] = useState<{ id: number; approved_qty: string }[]>(
requisition.items.map((item) => ({
id: item.id,
approved_qty: item.requested_qty.toString(),
}))
);
// 駁回狀態
const [showRejectDialog, setShowRejectDialog] = useState(false);
const [rejectReason, setRejectReason] = useState("");
// 提交確認
const [showSubmitDialog, setShowSubmitDialog] = useState(false);
const handleSubmit = () => {
setSubmitting(true);
router.post(route("store-requisitions.submit", [requisition.id]), {}, {
onFinish: () => {
setSubmitting(false);
setShowSubmitDialog(false);
},
});
};
const handleApprove = () => {
if (!supplyWarehouseId) {
toast.error("請選擇供貨倉庫");
return;
}
// 確認每個核准數量
for (const item of approvedItems) {
const qty = parseFloat(item.approved_qty);
if (isNaN(qty) || qty < 0) {
toast.error("核准數量不能為負數");
return;
}
}
setApproving(true);
router.post(
route("store-requisitions.approve", [requisition.id]),
{
supply_warehouse_id: supplyWarehouseId,
items: approvedItems.map((item) => ({
id: item.id,
approved_qty: parseFloat(item.approved_qty),
})),
},
{
onFinish: () => {
setApproving(false);
setShowApproveDialog(false);
},
}
);
};
const handleReject = () => {
if (!rejectReason.trim()) {
toast.error("請填寫駁回原因");
return;
}
setRejecting(true);
router.post(
route("store-requisitions.reject", [requisition.id]),
{ reject_reason: rejectReason },
{
onFinish: () => {
setRejecting(false);
setShowRejectDialog(false);
},
}
);
};
const updateApprovedQty = (itemId: number, qty: string) => {
setApprovedItems(
approvedItems.map((item) => (item.id === itemId ? { ...item, approved_qty: qty } : item))
);
};
const isEditable = ["draft", "rejected"].includes(requisition.status);
const isPending = requisition.status === "pending";
return (
<AuthenticatedLayout
breadcrumbs={[
{ label: "商品與庫存管理", href: "#" },
{ label: "門市叫貨", href: route("store-requisitions.index") },
{ label: requisition.doc_no, href: "#", isPage: true },
]}
>
<Head title={`叫貨單 ${requisition.doc_no}`} />
<div className="container mx-auto p-6 max-w-7xl">
{/* 返回按鈕 */}
<div className="mb-6">
<Link href={route("store-requisitions.index")}>
<Button variant="outline" className="gap-2 button-outlined-primary">
<ArrowLeft className="h-4 w-4" />
</Button>
</Link>
</div>
{/* 頁面標題與操作 */}
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<Store className="h-6 w-6 text-primary-main" />
{requisition.doc_no}
</h1>
<div className="flex items-center gap-2 mt-1">
{getStatusBadge(requisition.status)}
<span className="text-gray-500 text-sm">
{formatDate(requisition.created_at)}
</span>
</div>
</div>
{/* 操作按鈕 */}
<div className="flex gap-2">
{isEditable && (
<>
<Can permission="store_requisitions.edit">
<Link href={route("store-requisitions.edit", [requisition.id])}>
<Button variant="outline" className="button-outlined-primary">
<Pencil className="w-4 h-4 mr-1" />
</Button>
</Link>
</Can>
{requisition.status === "draft" && (
<Can permission="store_requisitions.view">
<Button
className="button-filled-primary"
onClick={() => setShowSubmitDialog(true)}
>
<SendHorizontal className="w-4 h-4 mr-1" />
</Button>
</Can>
)}
</>
)}
{isPending && (
<>
<Can permission="store_requisitions.approve">
<Button
variant="outline"
className="button-outlined-error"
onClick={() => setShowRejectDialog(true)}
>
<XCircle className="w-4 h-4 mr-1" />
</Button>
<Button
className="button-filled-success"
onClick={() => setShowApproveDialog(true)}
>
<CheckCircle2 className="w-4 h-4 mr-1" />
</Button>
</Can>
</>
)}
</div>
</div>
{/* 基本資訊 */}
<div className="bg-white rounded-lg shadow-sm border p-6 mb-6">
<h2 className="text-lg font-semibold text-gray-800 mb-4"></h2>
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<div>
<span className="text-sm text-gray-500"></span>
<p className="font-medium text-gray-800 mt-1">
{requisition.store_warehouse_name}
</p>
</div>
<div>
<span className="text-sm text-gray-500"></span>
<p className="font-medium text-gray-800 mt-1">
{requisition.supply_warehouse_name || "-"}
</p>
</div>
<div>
<span className="text-sm text-gray-500"></span>
<p className="font-medium text-gray-800 mt-1">
{requisition.creator_name}
</p>
</div>
{requisition.submitted_at && (
<div>
<span className="text-sm text-gray-500"></span>
<p className="font-medium text-gray-800 mt-1">
{formatDate(requisition.submitted_at)}
</p>
</div>
)}
{requisition.approved_at && (
<>
<div>
<span className="text-sm text-gray-500"></span>
<p className="font-medium text-gray-800 mt-1">
{requisition.approver_name}
</p>
</div>
<div>
<span className="text-sm text-gray-500"></span>
<p className="font-medium text-gray-800 mt-1">
{formatDate(requisition.approved_at)}
</p>
</div>
</>
)}
{requisition.remark && (
<div className="md:col-span-3">
<span className="text-sm text-gray-500"></span>
<p className="font-medium text-gray-800 mt-1">
{requisition.remark}
</p>
</div>
)}
{requisition.reject_reason && (
<div className="md:col-span-3">
<span className="text-sm text-red-500 font-medium"></span>
<p className="text-red-600 bg-red-50 rounded-md p-3 mt-1">
{requisition.reject_reason}
</p>
</div>
)}
{requisition.transfer_order_id && (
<div>
<span className="text-sm text-gray-500">調</span>
<p className="mt-1">
<Link
href={route("inventory.transfer.show", [requisition.transfer_order_id])}
className="text-primary-main hover:underline font-medium"
>
調
</Link>
</p>
</div>
)}
</div>
</div>
{/* 商品明細 */}
<div className="bg-white rounded-lg shadow-sm border p-6 mb-6">
<h2 className="text-lg font-semibold text-gray-800 mb-4"></h2>
<div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
<Table>
<TableHeader className="bg-gray-50">
<TableRow>
<TableHead className="w-[50px] text-center font-medium text-gray-600">
#
</TableHead>
<TableHead className="font-medium text-gray-600"></TableHead>
<TableHead className="font-medium text-gray-600"></TableHead>
<TableHead className="text-right font-medium text-gray-600">
</TableHead>
<TableHead className="text-right font-medium text-gray-600">
</TableHead>
<TableHead className="font-medium text-gray-600"></TableHead>
{["approved", "completed"].includes(requisition.status) && (
<TableHead className="text-right font-medium text-gray-600">
</TableHead>
)}
<TableHead className="font-medium text-gray-600"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{requisition.items.map((item, index) => (
<TableRow key={item.id}>
<TableCell className="text-center text-gray-500 font-medium">
{index + 1}
</TableCell>
<TableCell className="font-mono text-sm text-gray-600">
{item.product_code}
</TableCell>
<TableCell className="font-medium text-gray-800">
{item.product_name}
</TableCell>
<TableCell className="text-right text-gray-600">
{Number(item.current_stock).toLocaleString()}
</TableCell>
<TableCell className="text-right font-medium text-gray-800">
{Number(item.requested_qty).toLocaleString()}
</TableCell>
<TableCell className="text-gray-500">{item.unit_name}</TableCell>
{["approved", "completed"].includes(requisition.status) && (
<TableCell className="text-right font-medium text-green-600">
{item.approved_qty !== null
? Number(item.approved_qty).toLocaleString()
: "-"}
</TableCell>
)}
<TableCell className="text-gray-500 text-sm">
{item.remark || "-"}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</div>
</div>
{/* 提交確認 */}
<AlertDialog open={showSubmitDialog} onOpenChange={setShowSubmitDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle></AlertDialogTitle>
<AlertDialogDescription>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction
onClick={handleSubmit}
className="button-filled-primary"
disabled={submitting}
>
{submitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* 核准對話框 */}
<Dialog open={showApproveDialog} onOpenChange={setShowApproveDialog}>
<DialogContent className="sm:max-w-[700px]">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription></DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2">
<div className="space-y-2">
<Label>
<span className="text-red-500">*</span>
</Label>
<SearchableSelect
value={supplyWarehouseId}
onValueChange={setSupplyWarehouseId}
options={warehouses
.filter((w) => w.id !== requisition.store_warehouse_id)
.map((w) => ({
label: w.name,
value: w.id.toString(),
}))}
placeholder="請選擇供貨倉庫"
className="h-9"
/>
</div>
<div className="border rounded-lg overflow-hidden">
<Table>
<TableHeader className="bg-gray-50">
<TableRow>
<TableHead className="font-medium text-gray-600"></TableHead>
<TableHead className="text-right font-medium text-gray-600 w-[120px]">
</TableHead>
<TableHead className="font-medium text-gray-600 w-[80px]"></TableHead>
<TableHead className="font-medium text-gray-600 w-[150px]">
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{requisition.items.map((item) => (
<TableRow key={item.id}>
<TableCell>
<span className="font-mono text-xs text-gray-500">
{item.product_code}
</span>
<span className="ml-2 text-gray-800">{item.product_name}</span>
</TableCell>
<TableCell className="text-right text-gray-700">
{Number(item.requested_qty).toLocaleString()}
</TableCell>
<TableCell className="text-gray-500 text-sm">
{item.unit_name}
</TableCell>
<TableCell>
<Input
type="number"
step="1"
min="0"
value={
approvedItems.find((ai) => ai.id === item.id)
?.approved_qty || ""
}
onChange={(e) =>
updateApprovedQty(item.id, e.target.value)
}
className="h-8 text-right"
/>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</div>
<DialogFooter>
<Button
variant="outline"
className="button-outlined-primary"
onClick={() => setShowApproveDialog(false)}
>
</Button>
<Button
className="bg-green-600 hover:bg-green-700 text-white"
onClick={handleApprove}
disabled={approving || !supplyWarehouseId}
>
{approving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* 駁回對話框 */}
<Dialog open={showRejectDialog} onOpenChange={setShowRejectDialog}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
</DialogDescription>
</DialogHeader>
<div className="py-2">
<Label>
<span className="text-red-500">*</span>
</Label>
<Textarea
value={rejectReason}
onChange={(e) => setRejectReason(e.target.value)}
placeholder="請填寫駁回原因..."
rows={4}
className="mt-2"
/>
</div>
<DialogFooter>
<Button
variant="outline"
className="button-outlined-primary"
onClick={() => setShowRejectDialog(false)}
>
</Button>
<Button
variant="destructive"
onClick={handleReject}
disabled={rejecting || !rejectReason.trim()}
>
{rejecting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</AuthenticatedLayout>
);
}