Compare commits

..

6 Commits

Author SHA1 Message Date
7367577f6a feat: 統一採購單與操作紀錄 UI、增強各模組操作紀錄功能
All checks were successful
Koori-ERP-Deploy-System / deploy-demo (push) Successful in 59s
Koori-ERP-Deploy-System / deploy-production (push) Has been skipped
- 統一採購單篩選列與表單樣式 (移除舊元件、標準化 Input)
- 增強操作紀錄功能 (加入篩選、快照、詳細異動比對)
- 統一刪除確認視窗與按鈕樣式
- 修復庫存編輯頁面樣式
- 實作採購單品項異動紀錄
- 實作角色分配異動紀錄
- 擴充供應商與倉庫模組紀錄
2026-01-19 17:07:45 +08:00
5c4693577a fix(activity): 修正操作紀錄列表描述中未顯示使用者名稱的問題
- 在 User 模型中加入 tapActivity 自動記錄 snapshot (name, username)

- 在 UserController 手動紀錄的邏輯中補上 snapshot
2026-01-19 16:13:22 +08:00
632dee13a5 fix(activity): 修正使用者更新時產生雙重紀錄的問題
- 使用 saveQuietly 避免原生 update 事件觸發紀錄

- 手動合併屬性變更 (Attributes) 與角色變更 (Roles) 為單一操作紀錄
2026-01-19 16:10:59 +08:00
cdcc0f4ce3 feat(activity): 實作使用者角色分配操作紀錄
- 在使用者建立 (store) 時,將角色名稱寫入操作紀錄

- 在使用者更新 (update) 時,手動比對與紀錄角色名稱異動
2026-01-19 16:06:40 +08:00
f6167fdaec fix(ui): 隱藏操作紀錄中的密碼並中文化帳號欄位
- 在 ActivityDetailDialog 中將 password 欄位顯示為 ******

- 將 username 欄位名稱從 Username 翻譯為 登入帳號
2026-01-19 16:01:27 +08:00
b29278aa12 fix(i18n): 使用者密碼驗證訊息中文化
- 新增/編輯使用者時,密碼欄位的驗證錯誤訊息改為繁體中文顯示
2026-01-19 15:58:47 +08:00
17 changed files with 632 additions and 447 deletions

View File

@@ -9,14 +9,64 @@ use Spatie\Activitylog\Models\Activity;
class ActivityLogController extends Controller class ActivityLogController extends Controller
{ {
private function getSubjectMap()
{
return [
'App\Models\User' => '使用者',
'App\Models\Role' => '角色',
'App\Models\Product' => '商品',
'App\Models\Vendor' => '廠商',
'App\Models\Category' => '商品分類',
'App\Models\Unit' => '單位',
'App\Models\PurchaseOrder' => '採購單',
'App\Models\Warehouse' => '倉庫',
'App\Models\Inventory' => '庫存',
];
}
public function index(Request $request) public function index(Request $request)
{ {
$perPage = $request->input('per_page', 10); $perPage = $request->input('per_page', 10);
$sortBy = $request->input('sort_by', 'created_at'); $sortBy = $request->input('sort_by', 'created_at');
$sortOrder = $request->input('sort_order', 'desc'); $sortOrder = $request->input('sort_order', 'desc');
$search = $request->input('search');
$dateStart = $request->input('date_start');
$dateEnd = $request->input('date_end');
$event = $request->input('event');
$subjectType = $request->input('subject_type');
$causerId = $request->input('causer_id');
$query = Activity::with('causer'); $query = Activity::with('causer');
if ($search) {
$query->where(function ($q) use ($search) {
$q->where('description', 'like', "%{$search}%")
->orWhere('log_name', 'like', "%{$search}%")
->orWhere('properties', 'like', "%{$search}%");
});
}
if ($dateStart) {
$query->whereDate('created_at', '>=', $dateStart);
}
if ($dateEnd) {
$query->whereDate('created_at', '<=', $dateEnd);
}
if ($event) {
$query->where('event', $event);
}
if ($subjectType) {
$query->where('subject_type', $subjectType);
}
if ($causerId) {
$query->where('causer_id', $causerId);
}
if ($sortBy === 'created_at') { if ($sortBy === 'created_at') {
$query->orderBy($sortBy, $sortOrder); $query->orderBy($sortBy, $sortOrder);
} else { } else {
@@ -25,17 +75,7 @@ class ActivityLogController extends Controller
$activities = $query->paginate($perPage) $activities = $query->paginate($perPage)
->through(function ($activity) { ->through(function ($activity) {
$subjectMap = [ $subjectMap = $this->getSubjectMap();
'App\Models\User' => '使用者',
'App\Models\Role' => '角色',
'App\Models\Product' => '商品',
'App\Models\Vendor' => '廠商',
'App\Models\Category' => '商品分類',
'App\Models\Unit' => '單位',
'App\Models\PurchaseOrder' => '採購單',
'App\Models\Warehouse' => '倉庫',
'App\Models\Inventory' => '庫存',
];
$eventMap = [ $eventMap = [
'created' => '新增', 'created' => '新增',
@@ -54,13 +94,32 @@ class ActivityLogController extends Controller
]; ];
}); });
// Prepare subject types for frontend filter
$subjectTypes = collect($this->getSubjectMap())->map(function ($label, $value) {
return ['label' => $label, 'value' => $value];
})->values();
// Get users for causer filter
$users = \App\Models\User::select('id', 'name')->orderBy('name')->get()
->map(function ($user) {
return ['label' => $user->name, 'value' => (string) $user->id];
});
return Inertia::render('Admin/ActivityLog/Index', [ return Inertia::render('Admin/ActivityLog/Index', [
'activities' => $activities, 'activities' => $activities,
'filters' => [ 'filters' => [
'per_page' => $request->input('per_page', '10'), 'per_page' => $request->input('per_page', '10'),
'sort_by' => $request->input('sort_by'), 'sort_by' => $request->input('sort_by'),
'sort_order' => $request->input('sort_order'), 'sort_order' => $request->input('sort_order'),
'search' => $request->input('search'),
'date_start' => $request->input('date_start'),
'date_end' => $request->input('date_end'),
'event' => $request->input('event'),
'subject_type' => $request->input('subject_type'),
'causer_id' => $request->input('causer_id'),
], ],
'subject_types' => $subjectTypes,
'users' => $users,
]); ]);
} }
} }

View File

@@ -61,6 +61,10 @@ class UserController extends Controller
'username' => ['required', 'string', 'max:255', 'unique:users'], 'username' => ['required', 'string', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'], 'password' => ['required', 'string', 'min:8', 'confirmed'],
'roles' => ['array'], 'roles' => ['array'],
], [
'password.required' => '請輸入密碼',
'password.min' => '密碼長度至少需 :min 個字元',
'password.confirmed' => '密碼確認不符',
]); ]);
$user = User::create([ $user = User::create([
@@ -72,6 +76,21 @@ class UserController extends Controller
if (!empty($validated['roles'])) { if (!empty($validated['roles'])) {
$user->syncRoles($validated['roles']); $user->syncRoles($validated['roles']);
// Update the 'created' log to include roles
$activity = \Spatie\Activitylog\Models\Activity::where('subject_type', get_class($user))
->where('subject_id', $user->id)
->where('event', 'created')
->latest()
->first();
if ($activity) {
$roleNames = $user->roles()->pluck('display_name')->join(', ');
$properties = $activity->properties->toArray();
$properties['attributes']['role_id'] = $roleNames;
$activity->properties = $properties;
$activity->save();
}
} }
return redirect()->route('users.index')->with('success', '使用者建立成功'); return redirect()->route('users.index')->with('success', '使用者建立成功');
@@ -98,15 +117,19 @@ class UserController extends Controller
public function update(Request $request, string $id) public function update(Request $request, string $id)
{ {
$user = User::findOrFail($id); $user = User::findOrFail($id);
$validated = $request->validate([ $validated = $request->validate([
'name' => ['required', 'string', 'max:255'], 'name' => ['required', 'string', 'max:255'],
'email' => ['nullable', 'string', 'email', 'max:255', Rule::unique('users')->ignore($user->id)], 'email' => ['nullable', 'string', 'email', 'max:255', Rule::unique('users')->ignore($user->id)],
'username' => ['required', 'string', 'max:255', Rule::unique('users')->ignore($user->id)], 'username' => ['required', 'string', 'max:255', Rule::unique('users')->ignore($user->id)],
'password' => ['nullable', 'string', 'min:8', 'confirmed'], 'password' => ['nullable', 'string', 'min:8', 'confirmed'],
'roles' => ['array'], 'roles' => ['array'],
], [
'password.min' => '密碼長度至少需 :min 個字元',
'password.confirmed' => '密碼確認不符',
]); ]);
// 1. Prepare data and detect changes
$userData = [ $userData = [
'name' => $validated['name'], 'name' => $validated['name'],
'email' => $validated['email'], 'email' => $validated['email'],
@@ -117,10 +140,63 @@ class UserController extends Controller
$userData['password'] = Hash::make($validated['password']); $userData['password'] = Hash::make($validated['password']);
} }
$user->update($userData); $user->fill($userData);
// Capture dirty attributes for manual logging
$dirty = $user->getDirty();
$oldAttributes = [];
$newAttributes = [];
foreach ($dirty as $key => $value) {
$oldAttributes[$key] = $user->getOriginal($key);
$newAttributes[$key] = $value;
}
// Save without triggering events (prevents duplicate log)
$user->saveQuietly();
// 2. Handle Roles
$roleChanges = null;
if (isset($validated['roles'])) { if (isset($validated['roles'])) {
$oldRoles = $user->roles()->pluck('display_name')->join(', ');
$user->syncRoles($validated['roles']); $user->syncRoles($validated['roles']);
$newRoles = $user->roles()->pluck('display_name')->join(', ');
if ($oldRoles !== $newRoles) {
$roleChanges = [
'old' => $oldRoles,
'new' => $newRoles
];
}
}
// 3. Manually Log activity (Single Consolidated Log)
if (!empty($newAttributes) || $roleChanges) {
$properties = [
'attributes' => $newAttributes,
'old' => $oldAttributes,
];
if ($roleChanges) {
$properties['attributes']['role_id'] = $roleChanges['new'];
$properties['old']['role_id'] = $roleChanges['old'];
}
activity()
->performedOn($user)
->causedBy(auth()->user())
->event('updated')
->withProperties($properties)
->tap(function (\Spatie\Activitylog\Contracts\Activity $activity) use ($user) {
// Manually add snapshot since we aren't using the model's LogOptions due to saveQuietly
$activity->properties = $activity->properties->merge([
'snapshot' => [
'name' => $user->name,
'username' => $user->username,
]
]);
})
->log('updated');
} }
return redirect()->route('users.index')->with('success', '使用者更新成功'); return redirect()->route('users.index')->with('success', '使用者更新成功');

View File

@@ -34,6 +34,15 @@ class PurchaseOrderController extends Controller
$query->where('warehouse_id', $request->warehouse_id); $query->where('warehouse_id', $request->warehouse_id);
} }
// Date Range
if ($request->date_start) {
$query->whereDate('created_at', '>=', $request->date_start);
}
if ($request->date_end) {
$query->whereDate('created_at', '<=', $request->date_end);
}
// Sorting // Sorting
$sortField = $request->sort_field ?? 'id'; $sortField = $request->sort_field ?? 'id';
$sortDirection = $request->sort_direction ?? 'desc'; $sortDirection = $request->sort_direction ?? 'desc';
@@ -48,7 +57,7 @@ class PurchaseOrderController extends Controller
return Inertia::render('PurchaseOrder/Index', [ return Inertia::render('PurchaseOrder/Index', [
'orders' => $orders, 'orders' => $orders,
'filters' => $request->only(['search', 'status', 'warehouse_id', 'sort_field', 'sort_direction', 'per_page']), 'filters' => $request->only(['search', 'status', 'warehouse_id', 'date_start', 'date_end', 'sort_field', 'sort_direction', 'per_page']),
'warehouses' => Warehouse::all(['id', 'name']), 'warehouses' => Warehouse::all(['id', 'name']),
]); ]);
} }

View File

@@ -57,4 +57,14 @@ class User extends Authenticatable
->logOnlyDirty() ->logOnlyDirty()
->dontSubmitEmptyLogs(); ->dontSubmitEmptyLogs();
} }
public function tapActivity(\Spatie\Activitylog\Contracts\Activity $activity, string $eventName)
{
$activity->properties = $activity->properties->merge([
'snapshot' => [
'name' => $this->name,
'username' => $this->username,
]
]);
}
} }

View File

@@ -45,6 +45,7 @@ interface Props {
const fieldLabels: Record<string, string> = { const fieldLabels: Record<string, string> = {
name: '名稱', name: '名稱',
code: '代碼', code: '代碼',
username: '登入帳號',
description: '描述', description: '描述',
price: '價格', price: '價格',
cost: '成本', cost: '成本',
@@ -63,6 +64,8 @@ const fieldLabels: Record<string, string> = {
phone: '電話', phone: '電話',
address: '地址', address: '地址',
role_id: '角色', role_id: '角色',
email_verified_at: '電子郵件驗證時間',
remember_token: '登入權杖',
// Snapshot fields // Snapshot fields
category_name: '分類名稱', category_name: '分類名稱',
base_unit_name: '基本單位名稱', base_unit_name: '基本單位名稱',
@@ -131,7 +134,7 @@ export default function ActivityDetailDialog({ open, onOpenChange, activity }: P
// Filter out internal keys often logged but not useful for users // Filter out internal keys often logged but not useful for users
const filteredKeys = allKeys const filteredKeys = allKeys
.filter(key => .filter(key =>
!['created_at', 'updated_at', 'deleted_at', 'id'].includes(key) !['created_at', 'updated_at', 'deleted_at', 'id', 'remember_token'].includes(key)
) )
.sort((a, b) => { .sort((a, b) => {
const indexA = sortOrder.indexOf(a); const indexA = sortOrder.indexOf(a);
@@ -146,8 +149,6 @@ export default function ActivityDetailDialog({ open, onOpenChange, activity }: P
return a.localeCompare(b); return a.localeCompare(b);
}); });
// Helper to check if a key is a snapshot name field
// Helper to check if a key is a snapshot name field // Helper to check if a key is a snapshot name field
const isSnapshotField = (key: string) => { const isSnapshotField = (key: string) => {
return [ return [
@@ -176,6 +177,9 @@ export default function ActivityDetailDialog({ open, onOpenChange, activity }: P
}; };
const formatValue = (key: string, value: any) => { const formatValue = (key: string, value: any) => {
// Mask password
if (key === 'password') return '******';
if (value === null || value === undefined) return '-'; if (value === null || value === undefined) return '-';
if (typeof value === 'boolean') return value ? '是' : '否'; if (typeof value === 'boolean') return value ? '是' : '否';
if (key === 'is_active') return value ? '啟用' : '停用'; if (key === 'is_active') return value ? '啟用' : '停用';

View File

@@ -156,7 +156,7 @@ export default function LogTable({
<TableHead className="w-[150px]"></TableHead> <TableHead className="w-[150px]"></TableHead>
<TableHead></TableHead> <TableHead></TableHead>
<TableHead className="w-[100px] text-center"></TableHead> <TableHead className="w-[100px] text-center"></TableHead>
<TableHead></TableHead> <TableHead></TableHead>
<TableHead className="w-[100px] text-center"></TableHead> <TableHead className="w-[100px] text-center"></TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>

View File

@@ -1,176 +0,0 @@
/**
* 日期篩選器元件
* 支援快捷日期範圍選項和自定義日期範圍
*/
import { Calendar } from "lucide-react";
import { Label } from "@/Components/ui/label";
import { Input } from "@/Components/ui/input";
import { Button } from "@/Components/ui/button";
export interface DateRange {
start: string; // YYYY-MM-DD 格式
end: string; // YYYY-MM-DD 格式
}
interface DateFilterProps {
dateRange: DateRange | null;
onDateRangeChange: (range: DateRange | null) => void;
}
// 格式化日期為 YYYY-MM-DD
function formatDate(date: Date): string {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
}
// 獲取從今天往前 N 天的日期範圍
function getDateRange(days: number): DateRange {
const end = new Date();
const start = new Date();
start.setDate(start.getDate() - days);
return {
start: formatDate(start),
end: formatDate(end),
};
}
// 獲取本月的日期範圍
function getCurrentMonth(): DateRange {
const now = new Date();
const start = new Date(now.getFullYear(), now.getMonth(), 1);
const end = new Date(now.getFullYear(), now.getMonth() + 1, 0);
return {
start: formatDate(start),
end: formatDate(end),
};
}
// 獲取上月的日期範圍
function getLastMonth(): DateRange {
const now = new Date();
const start = new Date(now.getFullYear(), now.getMonth() - 1, 1);
const end = new Date(now.getFullYear(), now.getMonth(), 0);
return {
start: formatDate(start),
end: formatDate(end),
};
}
// 快捷日期選項
const DATE_SHORTCUTS = [
{ label: "今天", getValue: () => getDateRange(0) },
{ label: "最近7天", getValue: () => getDateRange(7) },
{ label: "最近30天", getValue: () => getDateRange(30) },
{ label: "本月", getValue: () => getCurrentMonth() },
{ label: "上月", getValue: () => getLastMonth() },
];
export function DateFilter({ dateRange, onDateRangeChange }: DateFilterProps) {
const handleStartDateChange = (value: string) => {
if (!value) {
onDateRangeChange(null);
return;
}
onDateRangeChange({
start: value,
end: dateRange?.end || value,
});
};
const handleEndDateChange = (value: string) => {
if (!value) {
onDateRangeChange(null);
return;
}
onDateRangeChange({
start: dateRange?.start || value,
end: value,
});
};
const handleShortcutClick = (getValue: () => DateRange) => {
onDateRangeChange(getValue());
};
const handleClearClick = () => {
onDateRangeChange(null);
};
return (
<div className="space-y-4">
{/* 標題 */}
<div className="flex items-center gap-2">
<Calendar className="h-4 w-4 text-gray-500" />
<Label className="font-semibold text-gray-700"></Label>
</div>
{/* 快捷選項 */}
<div className="flex flex-wrap gap-2">
{DATE_SHORTCUTS.map((shortcut) => (
<Button
key={shortcut.label}
variant="outline"
size="sm"
onClick={() => handleShortcutClick(shortcut.getValue)}
className="button-outlined-primary border-gray-200"
>
{shortcut.label}
</Button>
))}
</div>
{/* 自定義日期範圍 */}
<div className="space-y-4 bg-gray-50/50 p-4 rounded-lg border border-dashed border-gray-200">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{/* 開始日期 */}
<div className="space-y-2">
<Label htmlFor="start-date" className="text-sm text-gray-500">
</Label>
<Input
id="start-date"
type="date"
value={dateRange?.start || ""}
onChange={(e) => handleStartDateChange(e.target.value)}
className="border-gray-200 focus:border-primary"
/>
</div>
{/* 結束日期 */}
<div className="space-y-2">
<Label htmlFor="end-date" className="text-sm text-gray-500">
</Label>
<Input
id="end-date"
type="date"
value={dateRange?.end || ""}
onChange={(e) => handleEndDateChange(e.target.value)}
className="border-gray-200 focus:border-primary"
/>
</div>
</div>
{/* 清除按鈕 */}
{dateRange && (
<Button
variant="outline"
size="sm"
onClick={handleClearClick}
className="w-full button-outlined-primary border-gray-200"
>
</Button>
)}
</div>
</div>
);
}

View File

@@ -1,135 +0,0 @@
/**
* 採購單篩選器元件
*/
import { useState } from "react";
import { Search, X, Filter, ChevronDown, ChevronUp } from "lucide-react";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/Components/ui/select";
import { DateFilter, type DateRange } from "./DateFilter";
interface PurchaseOrderFiltersProps {
searchQuery: string;
statusFilter: string;
requesterFilter: string;
warehouses: { id: string | number; name: string }[];
dateRange: DateRange | null;
onSearchChange: (value: string) => void;
onStatusChange: (value: string) => void;
onRequesterChange: (value: string) => void;
onDateRangeChange: (range: DateRange | null) => void;
onClearFilters: () => void;
hasActiveFilters: boolean;
}
export function PurchaseOrderFilters({
searchQuery,
statusFilter,
requesterFilter,
warehouses,
dateRange,
onSearchChange,
onStatusChange,
onRequesterChange,
onDateRangeChange,
onClearFilters,
hasActiveFilters,
}: PurchaseOrderFiltersProps) {
const [showAdvancedFilters, setShowAdvancedFilters] = useState(false);
return (
<div className="bg-white rounded-lg border shadow-sm p-4 space-y-4">
{/* 主要篩選列 */}
<div className="flex flex-col lg:flex-row gap-4">
{/* 搜尋框 */}
<div className="flex-1 relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
<Input
placeholder="搜尋採購單編號"
value={searchQuery}
onChange={(e) => onSearchChange(e.target.value)}
className="h-10 pl-10 border-gray-200 focus:border-primary"
/>
</div>
{/* 快速篩選區 */}
<div className="flex flex-wrap gap-3 items-center">
{/* 狀態篩選 */}
<div className="flex items-center gap-2">
<Filter className="h-4 w-4 text-gray-400 hidden sm:block" />
<Select value={statusFilter} onValueChange={onStatusChange}>
<SelectTrigger className="w-[160px] h-10 border-gray-200">
<SelectValue placeholder="全部狀態" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="draft">稿</SelectItem>
<SelectItem value="pending"></SelectItem>
<SelectItem value="processing"></SelectItem>
<SelectItem value="shipping"></SelectItem>
<SelectItem value="confirming"></SelectItem>
<SelectItem value="completed"></SelectItem>
<SelectItem value="cancelled"></SelectItem>
</SelectContent>
</Select>
</div>
{/* 倉庫篩選 */}
<Select value={requesterFilter} onValueChange={onRequesterChange}>
<SelectTrigger className="w-[180px] h-10 border-gray-200">
<SelectValue placeholder="全部倉庫" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
{warehouses.map((warehouse) => (
<SelectItem key={warehouse.id} value={String(warehouse.id)}>
{warehouse.name}
</SelectItem>
))}
</SelectContent>
</Select>
{/* 進階篩選按鈕 */}
<Button
variant="outline"
onClick={() => setShowAdvancedFilters(!showAdvancedFilters)}
className="gap-2 button-outlined-primary h-10 border-gray-200"
>
{showAdvancedFilters ? (
<ChevronUp className="h-4 w-4" />
) : (
<ChevronDown className="h-4 w-4" />
)}
<span className="hidden sm:inline"></span>
</Button>
{/* 清除篩選按鈕 */}
{hasActiveFilters && (
<Button
variant="outline"
onClick={onClearFilters}
className="gap-2 button-outlined-primary h-10 border-gray-200"
>
<X className="h-4 w-4" />
<span className="hidden sm:inline"></span>
</Button>
)}
</div>
</div>
{/* 進階篩選區 */}
{showAdvancedFilters && (
<div className="pt-4 border-t border-gray-100">
<DateFilter dateRange={dateRange} onDateRangeChange={onDateRangeChange} />
</div>
)}
</div>
);
}

View File

@@ -105,7 +105,7 @@ export function PurchaseOrderItemsTable({
onItemChange?.(index, "quantity", Math.floor(Number(e.target.value))) onItemChange?.(index, "quantity", Math.floor(Number(e.target.value)))
} }
disabled={isDisabled} disabled={isDisabled}
className="h-10 text-left border-gray-200 w-24" className="text-left w-24"
/> />
)} )}
</TableCell> </TableCell>
@@ -161,11 +161,11 @@ export function PurchaseOrderItemsTable({
onItemChange?.(index, "subtotal", Number(e.target.value)) onItemChange?.(index, "subtotal", Number(e.target.value))
} }
disabled={isDisabled} disabled={isDisabled}
className={`h-10 text-left w-32 ${ className={`text-left w-32 ${
// 如果有數量但沒有金額,顯示錯誤樣式 // 如果有數量但沒有金額,顯示錯誤樣式
item.quantity > 0 && (!item.subtotal || item.subtotal <= 0) item.quantity > 0 && (!item.subtotal || item.subtotal <= 0)
? "border-red-400 bg-red-50 focus-visible:ring-red-500" ? "border-red-400 bg-red-50 focus-visible:ring-red-500"
: "border-gray-200" : ""
}`} }`}
/> />
{/* 錯誤提示 */} {/* 錯誤提示 */}

View File

@@ -4,9 +4,13 @@ import { Head, router } from '@inertiajs/react';
import { PageProps } from '@/types/global'; import { PageProps } from '@/types/global';
import Pagination from '@/Components/shared/Pagination'; import Pagination from '@/Components/shared/Pagination';
import { SearchableSelect } from "@/Components/ui/searchable-select"; import { SearchableSelect } from "@/Components/ui/searchable-select";
import { FileText } from 'lucide-react'; import { FileText, Search, RotateCcw, Calendar } from 'lucide-react';
import LogTable, { Activity } from '@/Components/ActivityLog/LogTable'; import LogTable, { Activity } from '@/Components/ActivityLog/LogTable';
import ActivityDetailDialog from '@/Components/ActivityLog/ActivityDetailDialog'; import ActivityDetailDialog from '@/Components/ActivityLog/ActivityDetailDialog';
import { Button } from '@/Components/ui/button';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/ui/select";
interface PaginationLinks { interface PaginationLinks {
url: string | null; url: string | null;
@@ -27,14 +31,62 @@ interface Props extends PageProps {
per_page?: string; per_page?: string;
sort_by?: string; sort_by?: string;
sort_order?: 'asc' | 'desc'; sort_order?: 'asc' | 'desc';
search?: string;
date_start?: string;
date_end?: string;
event?: string;
subject_type?: string;
causer_id?: string;
}; };
subject_types: { label: string; value: string }[];
users: { label: string; value: string }[];
} }
export default function ActivityLogIndex({ activities, filters }: Props) { export default function ActivityLogIndex({ activities, filters, subject_types, users }: Props) {
const [perPage, setPerPage] = useState<string>(filters.per_page || "10"); const [perPage, setPerPage] = useState<string>(filters.per_page || "10");
const [selectedActivity, setSelectedActivity] = useState<Activity | null>(null); const [selectedActivity, setSelectedActivity] = useState<Activity | null>(null);
const [detailOpen, setDetailOpen] = useState(false); const [detailOpen, setDetailOpen] = useState(false);
// Filter States
const [search, setSearch] = useState(filters.search || '');
const [dateStart, setDateStart] = useState(filters.date_start || '');
const [dateEnd, setDateEnd] = useState(filters.date_end || '');
const [event, setEvent] = useState(filters.event || 'all');
const [subjectType, setSubjectType] = useState(filters.subject_type || 'all');
const [causer, setCauser] = useState(filters.causer_id || 'all');
const handleFilter = () => {
router.get(
route('activity-logs.index'),
{
...filters,
search: search,
date_start: dateStart,
date_end: dateEnd,
event: event === 'all' ? undefined : event,
subject_type: subjectType === 'all' ? undefined : subjectType,
causer_id: causer === 'all' ? undefined : causer,
page: 1 // Reset to first page on filter
},
{ preserveState: true, replace: true }
);
};
const handleReset = () => {
setSearch('');
setDateStart('');
setDateEnd('');
setEvent('all');
setSubjectType('all');
setCauser('all');
router.get(
route('activity-logs.index'),
{ per_page: perPage, sort_by: filters.sort_by, sort_order: filters.sort_order },
{ preserveState: true, replace: true }
);
};
const handleViewDetail = (activity: Activity) => { const handleViewDetail = (activity: Activity) => {
setSelectedActivity(activity); setSelectedActivity(activity);
setDetailOpen(true); setDetailOpen(true);
@@ -91,6 +143,118 @@ export default function ActivityLogIndex({ activities, filters }: Props) {
</div> </div>
</div> </div>
{/* 篩選區塊 */}
<div className="bg-white p-5 rounded-lg shadow-sm border border-gray-200 mb-6">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-4">
{/* 關鍵字搜尋 */}
<div className="space-y-1">
<Label className="text-xs text-gray-500"></Label>
<div className="relative">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
<Input
placeholder="搜尋描述、內容..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-9"
onKeyDown={(e) => e.key === 'Enter' && handleFilter()}
/>
</div>
</div>
{/* 操作人員 */}
<div className="space-y-1">
<Label className="text-xs text-gray-500"></Label>
<SearchableSelect
value={causer}
onValueChange={setCauser}
options={[
{ label: "所有人員", value: "all" },
...users
]}
placeholder="選擇操作人員"
className="w-full"
/>
</div>
{/* 事件類型 */}
<div className="space-y-1">
<Label className="text-xs text-gray-500"></Label>
<Select value={event} onValueChange={setEvent}>
<SelectTrigger>
<SelectValue placeholder="選擇事件類型" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="created"> (Created)</SelectItem>
<SelectItem value="updated"> (Updated)</SelectItem>
<SelectItem value="deleted"> (Deleted)</SelectItem>
</SelectContent>
</Select>
</div>
{/* 操作對象 */}
<div className="space-y-1">
<Label className="text-xs text-gray-500"></Label>
<SearchableSelect
value={subjectType}
onValueChange={setSubjectType}
options={[
{ label: "所有對象", value: "all" },
...subject_types
]}
placeholder="選擇操作對象"
className="w-full"
/>
</div>
{/* 日期範圍 - 開始 */}
<div className="space-y-1">
<Label className="text-xs text-gray-500"></Label>
<div className="relative">
<Calendar className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
<Input
type="date"
value={dateStart}
onChange={(e) => setDateStart(e.target.value)}
className="pl-9 block w-full"
/>
</div>
</div>
{/* 日期範圍 - 結束 */}
<div className="space-y-1">
<Label className="text-xs text-gray-500"></Label>
<div className="relative">
<Calendar className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
<Input
type="date"
value={dateEnd}
onChange={(e) => setDateEnd(e.target.value)}
className="pl-9 block w-full text-left"
/>
</div>
</div>
</div>
<div className="flex items-center justify-end gap-3 pt-2 border-t border-gray-100">
<Button
variant="outline"
onClick={handleReset}
className="flex items-center gap-2 button-outlined-primary"
>
<RotateCcw className="h-4 w-4" />
</Button>
<Button
onClick={handleFilter}
className="flex items-center gap-2 button-filled-primary"
>
<Search className="h-4 w-4" />
</Button>
</div>
</div>
<LogTable <LogTable
activities={activities.data} activities={activities.data}
sortField={filters.sort_by} sortField={filters.sort_by}
@@ -100,7 +264,7 @@ export default function ActivityLogIndex({ activities, filters }: Props) {
from={activities.from} from={activities.from}
/> />
<div className="mt-4 flex flex-col sm:flex-row items-center justify-between gap-4"> <div className="mt-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
<div className="flex items-center gap-2 text-sm text-gray-500"> <div className="flex items-center gap-2 text-sm text-gray-500">
<span></span> <span></span>
<SearchableSelect <SearchableSelect
@@ -112,12 +276,14 @@ export default function ActivityLogIndex({ activities, filters }: Props) {
{ label: "50", value: "50" }, { label: "50", value: "50" },
{ label: "100", value: "100" } { label: "100", value: "100" }
]} ]}
className="w-[80px] h-8" className="w-[100px] h-8"
showSearch={false} showSearch={false}
/> />
<span></span> <span></span>
</div> </div>
<Pagination links={activities.links} /> <div className="w-full sm:w-auto flex justify-center sm:justify-end">
<Pagination links={activities.links} />
</div>
</div> </div>
</div> </div>

View File

@@ -13,7 +13,6 @@ import {
TableRow, TableRow,
} from "@/Components/ui/table"; } from "@/Components/ui/table";
import { format } from 'date-fns'; import { format } from 'date-fns';
import { toast } from 'sonner';
import { Can } from '@/Components/Permission/Can'; import { Can } from '@/Components/Permission/Can';
import { useState } from 'react'; import { useState } from 'react';
import { import {
@@ -23,6 +22,16 @@ import {
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from "@/Components/ui/dialog"; } from "@/Components/ui/dialog";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/Components/ui/alert-dialog";
interface User { interface User {
id: number; id: number;
@@ -50,11 +59,23 @@ interface Props {
export default function RoleIndex({ roles, filters = {} }: Props) { export default function RoleIndex({ roles, filters = {} }: Props) {
const [selectedRole, setSelectedRole] = useState<Role | null>(null); const [selectedRole, setSelectedRole] = useState<Role | null>(null);
const [deleteId, setDeleteId] = useState<number | null>(null);
const [deleteName, setDeleteName] = useState<string>('');
const [modelOpen, setModelOpen] = useState(false);
const handleDelete = (id: number, name: string) => { const confirmDelete = (id: number, name: string) => {
if (confirm(`確定要刪除角色「${name}」嗎?此操作無法復原。`)) { setDeleteId(id);
router.delete(route('roles.destroy', id), { setDeleteName(name);
onSuccess: () => toast.success('角色已刪除'), setModelOpen(true);
};
const handleDelete = () => {
if (deleteId) {
router.delete(route('roles.destroy', deleteId), {
onSuccess: () => {
setModelOpen(false);
},
onFinish: () => setModelOpen(false),
}); });
} }
}; };
@@ -212,7 +233,7 @@ export default function RoleIndex({ roles, filters = {} }: Props) {
className="button-outlined-error" className="button-outlined-error"
title="刪除" title="刪除"
disabled={role.users_count > 0} disabled={role.users_count > 0}
onClick={() => handleDelete(role.id, role.display_name)} onClick={() => confirmDelete(role.id, role.display_name)}
> >
<Trash2 className="h-4 w-4" /> <Trash2 className="h-4 w-4" />
</Button> </Button>
@@ -274,6 +295,23 @@ export default function RoleIndex({ roles, filters = {} }: Props) {
</div> </div>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
<AlertDialog open={modelOpen} onOpenChange={setModelOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle></AlertDialogTitle>
<AlertDialogDescription>
{deleteName}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={handleDelete} className="button-filled-error">
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</AuthenticatedLayout> </AuthenticatedLayout>
); );
} }

View File

@@ -12,11 +12,20 @@ import {
TableRow, TableRow,
} from "@/Components/ui/table"; } from "@/Components/ui/table";
import { format } from 'date-fns'; import { format } from 'date-fns';
import { toast } from 'sonner';
import { Can } from '@/Components/Permission/Can'; import { Can } from '@/Components/Permission/Can';
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import Pagination from "@/Components/shared/Pagination"; import Pagination from "@/Components/shared/Pagination";
import { SearchableSelect } from "@/Components/ui/searchable-select"; import { SearchableSelect } from "@/Components/ui/searchable-select";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/Components/ui/alert-dialog";
interface Role { interface Role {
id: number; id: number;
@@ -54,12 +63,23 @@ interface Props {
export default function UserIndex({ users, filters }: Props) { export default function UserIndex({ users, filters }: Props) {
const [perPage, setPerPage] = useState<string>(filters.per_page || "10"); const [perPage, setPerPage] = useState<string>(filters.per_page || "10");
const [deleteId, setDeleteId] = useState<number | null>(null);
const [deleteName, setDeleteName] = useState<string>('');
const [modelOpen, setModelOpen] = useState(false);
const handleDelete = (id: number, name: string) => { const confirmDelete = (id: number, name: string) => {
if (confirm(`確定要刪除使用者「${name}」嗎?此操作無法復原。`)) { setDeleteId(id);
router.delete(route('users.destroy', id), { setDeleteName(name);
onSuccess: () => toast.success('使用者已刪除'), setModelOpen(true);
onError: () => toast.error('刪除失敗,請檢查權限'), };
const handleDelete = () => {
if (deleteId) {
router.delete(route('users.destroy', deleteId), {
onSuccess: () => {
setModelOpen(false);
},
onFinish: () => setModelOpen(false),
}); });
} }
}; };
@@ -229,7 +249,7 @@ export default function UserIndex({ users, filters }: Props) {
size="sm" size="sm"
className="button-outlined-error" className="button-outlined-error"
title="刪除" title="刪除"
onClick={() => handleDelete(user.id, user.name)} onClick={() => confirmDelete(user.id, user.name)}
> >
<Trash2 className="h-4 w-4" /> <Trash2 className="h-4 w-4" />
</Button> </Button>
@@ -243,7 +263,7 @@ export default function UserIndex({ users, filters }: Props) {
</div> </div>
{/* 分頁元件 - 統一樣式 */} {/* 分頁元件 - 統一樣式 */}
<div className="mt-4 flex flex-col sm:flex-row items-center justify-between gap-4"> <div className="mt-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
<div className="flex items-center gap-2 text-sm text-gray-500"> <div className="flex items-center gap-2 text-sm text-gray-500">
<span></span> <span></span>
<SearchableSelect <SearchableSelect
@@ -255,14 +275,33 @@ export default function UserIndex({ users, filters }: Props) {
{ label: "50", value: "50" }, { label: "50", value: "50" },
{ label: "100", value: "100" } { label: "100", value: "100" }
]} ]}
className="w-[80px] h-8" className="w-[100px] h-8"
showSearch={false} showSearch={false}
/> />
<span></span> <span></span>
</div> </div>
<Pagination links={users.links} /> <div className="w-full sm:w-auto flex justify-center sm:justify-end">
<Pagination links={users.links} />
</div>
</div> </div>
</div> </div>
</AuthenticatedLayout>
<AlertDialog open={modelOpen} onOpenChange={setModelOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>使</AlertDialogTitle>
<AlertDialogDescription>
使{deleteName}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={handleDelete} className="button-filled-error">
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</AuthenticatedLayout >
); );
} }

View File

@@ -260,7 +260,7 @@ export default function ProductManagement({ products, categories, units, filters
/> />
{/* 分頁元件 */} {/* 分頁元件 */}
<div className="mt-4 flex flex-col sm:flex-row items-center justify-between gap-4"> <div className="mt-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
<div className="flex items-center gap-2 text-sm text-gray-500"> <div className="flex items-center gap-2 text-sm text-gray-500">
<span></span> <span></span>
<SearchableSelect <SearchableSelect
@@ -272,12 +272,14 @@ export default function ProductManagement({ products, categories, units, filters
{ label: "50", value: "50" }, { label: "50", value: "50" },
{ label: "100", value: "100" } { label: "100", value: "100" }
]} ]}
className="w-[80px] h-8" className="w-[100px] h-8"
showSearch={false} showSearch={false}
/> />
<span></span> <span></span>
</div> </div>
<Pagination links={products.links} /> <div className="w-full sm:w-auto flex justify-center sm:justify-end">
<Pagination links={products.links} />
</div>
</div> </div>
<ProductDialog <ProductDialog

View File

@@ -244,7 +244,7 @@ export default function CreatePurchaseOrder({
value={expectedDate || ""} value={expectedDate || ""}
onChange={(e) => setExpectedDate(e.target.value)} onChange={(e) => setExpectedDate(e.target.value)}
min={getTodayDate()} min={getTodayDate()}
className="h-12 border-gray-200" className="block w-full"
/> />
</div> </div>
@@ -267,7 +267,7 @@ export default function CreatePurchaseOrder({
value={notes || ""} value={notes || ""}
onChange={(e) => setNotes(e.target.value)} onChange={(e) => setNotes(e.target.value)}
placeholder="備註這筆採購單的特殊需求..." placeholder="備註這筆採購單的特殊需求..."
className="min-h-[100px] border-gray-200" className="min-h-[100px]"
/> />
</div> </div>
</div> </div>
@@ -293,7 +293,7 @@ export default function CreatePurchaseOrder({
onChange={(e) => setInvoiceNumber(e.target.value)} onChange={(e) => setInvoiceNumber(e.target.value)}
placeholder="AB-12345678" placeholder="AB-12345678"
maxLength={11} maxLength={11}
className="h-12 border-gray-200" className="block w-full"
/> />
<p className="text-xs text-gray-500">2 + + 8 </p> <p className="text-xs text-gray-500">2 + + 8 </p>
</div> </div>
@@ -306,7 +306,7 @@ export default function CreatePurchaseOrder({
type="date" type="date"
value={invoiceDate} value={invoiceDate}
onChange={(e) => setInvoiceDate(e.target.value)} onChange={(e) => setInvoiceDate(e.target.value)}
className="h-12 border-gray-200" className="block w-full"
/> />
</div> </div>
@@ -321,7 +321,7 @@ export default function CreatePurchaseOrder({
placeholder="0" placeholder="0"
min="0" min="0"
step="0.01" step="0.01"
className="h-12 border-gray-200" className="block w-full"
/> />
{invoiceAmount && totalAmount > 0 && parseFloat(invoiceAmount) !== totalAmount && ( {invoiceAmount && totalAmount > 0 && parseFloat(invoiceAmount) !== totalAmount && (
<p className="text-xs text-amber-600"> <p className="text-xs text-amber-600">

View File

@@ -2,20 +2,26 @@
* 採購單管理主頁面 * 採購單管理主頁面
*/ */
import { useState, useCallback } from "react"; import { useState, useEffect } from "react";
import { Plus, ShoppingCart } from 'lucide-react'; import { Plus, ShoppingCart, Search, RotateCcw, Calendar } from 'lucide-react';
import { Button } from "@/Components/ui/button"; import { Button } from "@/Components/ui/button";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout"; import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, router } from "@inertiajs/react"; import { Head, router } from "@inertiajs/react";
import PurchaseOrderTable from "@/Components/PurchaseOrder/PurchaseOrderTable"; import PurchaseOrderTable from "@/Components/PurchaseOrder/PurchaseOrderTable";
import { PurchaseOrderFilters } from "@/Components/PurchaseOrder/PurchaseOrderFilters";
import { type DateRange } from "@/Components/PurchaseOrder/DateFilter";
import type { PurchaseOrder } from "@/types/purchase-order"; import type { PurchaseOrder } from "@/types/purchase-order";
import { debounce } from "lodash";
import Pagination from "@/Components/shared/Pagination"; import Pagination from "@/Components/shared/Pagination";
import { getBreadcrumbs } from "@/utils/breadcrumb"; import { getBreadcrumbs } from "@/utils/breadcrumb";
import { Can } from "@/Components/Permission/Can"; import { Can } from "@/Components/Permission/Can";
import { SearchableSelect } from "@/Components/ui/searchable-select"; import { SearchableSelect } from "@/Components/ui/searchable-select";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/Components/ui/select";
interface Props { interface Props {
orders: { orders: {
@@ -29,6 +35,8 @@ interface Props {
search?: string; search?: string;
status?: string; status?: string;
warehouse_id?: string; warehouse_id?: string;
date_start?: string;
date_end?: string;
sort_field?: string; sort_field?: string;
sort_direction?: string; sort_direction?: string;
per_page?: string; per_page?: string;
@@ -37,74 +45,70 @@ interface Props {
} }
export default function PurchaseOrderIndex({ orders, filters, warehouses }: Props) { export default function PurchaseOrderIndex({ orders, filters, warehouses }: Props) {
const [searchQuery, setSearchQuery] = useState(filters.search || ""); // 篩選狀態
const [statusFilter, setStatusFilter] = useState<string>(filters.status || "all"); const [search, setSearch] = useState(filters.search || "");
const [requesterFilter, setRequesterFilter] = useState<string>(filters.warehouse_id || "all"); const [status, setStatus] = useState<string>(filters.status || "all");
const [warehouseId, setWarehouseId] = useState<string>(filters.warehouse_id || "all");
const [dateStart, setDateStart] = useState(filters.date_start || "");
const [dateEnd, setDateEnd] = useState(filters.date_end || "");
const [perPage, setPerPage] = useState<string>(filters.per_page || "10"); const [perPage, setPerPage] = useState<string>(filters.per_page || "10");
const [dateRange, setDateRange] = useState<DateRange | null>(null);
const handleFilterChange = (newFilters: any) => { // 同步 URL 參數到 State (雖有初始值,但若由外部連結進入可確保同步)
router.get("/purchase-orders", { useEffect(() => {
...filters, setSearch(filters.search || "");
...newFilters, setStatus(filters.status || "all");
page: 1, setWarehouseId(filters.warehouse_id || "all");
}, { setDateStart(filters.date_start || "");
preserveState: true, setDateEnd(filters.date_end || "");
replace: true, setPerPage(filters.per_page || "10");
}); }, [filters]);
const handleFilter = () => {
router.get(
route('purchase-orders.index'),
{
search,
status: status === 'all' ? undefined : status,
warehouse_id: warehouseId === 'all' ? undefined : warehouseId,
date_start: dateStart,
date_end: dateEnd,
per_page: perPage,
sort_field: filters.sort_field,
sort_direction: filters.sort_direction,
},
{ preserveState: true, replace: true }
);
}; };
const handleSearch = useCallback( const handleReset = () => {
debounce((value: string) => { setSearch("");
handleFilterChange({ search: value }); setStatus("all");
}, 500), setWarehouseId("all");
[filters] setDateStart("");
); setDateEnd("");
const onSearchChange = (value: string) => { router.get(route('purchase-orders.index'));
setSearchQuery(value);
handleSearch(value);
};
const onStatusChange = (value: string) => {
setStatusFilter(value);
handleFilterChange({ status: value });
};
const onWarehouseChange = (value: string) => {
setRequesterFilter(value);
handleFilterChange({ warehouse_id: value });
};
const handleClearFilters = () => {
setSearchQuery("");
setStatusFilter("all");
setRequesterFilter("all");
setDateRange(null);
router.get("/purchase-orders");
};
const hasActiveFilters = searchQuery !== "" || statusFilter !== "all" || requesterFilter !== "all" || dateRange !== null;
const handleNavigateToCreateOrder = () => {
router.get("/purchase-orders/create");
}; };
const handlePerPageChange = (value: string) => { const handlePerPageChange = (value: string) => {
setPerPage(value); setPerPage(value);
router.get("/purchase-orders", { router.get(
...filters, route("purchase-orders.index"),
per_page: value, {
page: 1, ...filters,
}, { per_page: value,
preserveState: false, },
replace: true, { preserveState: false, replace: true, preserveScroll: true }
}); );
};
const handleNavigateToCreateOrder = () => {
router.get(route('purchase-orders.create'));
}; };
return ( return (
<AuthenticatedLayout breadcrumbs={getBreadcrumbs("purchaseOrders")}> <AuthenticatedLayout breadcrumbs={getBreadcrumbs("purchaseOrders")}>
<Head title="採購管理 - 管理採購單" /> <Head title="採購管理" />
<div className="container mx-auto p-6 max-w-7xl"> <div className="container mx-auto p-6 max-w-7xl">
<div className="flex items-center justify-between mb-6"> <div className="flex items-center justify-between mb-6">
<div> <div>
@@ -129,20 +133,105 @@ export default function PurchaseOrderIndex({ orders, filters, warehouses }: Prop
</div> </div>
</div> </div>
<div className="mb-6"> {/* 篩選區塊 */}
<PurchaseOrderFilters <div className="bg-white p-5 rounded-lg shadow-sm border border-gray-200 mb-6">
searchQuery={searchQuery} <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-4">
statusFilter={statusFilter} {/* 關鍵字搜尋 */}
requesterFilter={requesterFilter} <div className="space-y-1">
warehouses={warehouses} <Label className="text-xs text-gray-500"></Label>
onSearchChange={onSearchChange} <div className="relative">
onStatusChange={onStatusChange} <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
onRequesterChange={onWarehouseChange} <Input
onClearFilters={handleClearFilters} placeholder="搜尋採購單號、廠商..."
hasActiveFilters={hasActiveFilters} value={search}
dateRange={dateRange} onChange={(e) => setSearch(e.target.value)}
onDateRangeChange={setDateRange} className="pl-9"
/> onKeyDown={(e) => e.key === 'Enter' && handleFilter()}
/>
</div>
</div>
{/* 狀態篩選 */}
<div className="space-y-1">
<Label className="text-xs text-gray-500"></Label>
<Select value={status} onValueChange={setStatus}>
<SelectTrigger>
<SelectValue placeholder="選擇狀態" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="draft">稿</SelectItem>
<SelectItem value="pending"></SelectItem>
<SelectItem value="processing"></SelectItem>
<SelectItem value="shipping"></SelectItem>
<SelectItem value="confirming"></SelectItem>
<SelectItem value="completed"></SelectItem>
<SelectItem value="cancelled"></SelectItem>
</SelectContent>
</Select>
</div>
{/* 倉庫篩選 */}
<div className="space-y-1">
<Label className="text-xs text-gray-500"></Label>
<SearchableSelect
value={warehouseId}
onValueChange={setWarehouseId}
options={[
{ label: "全部倉庫", value: "all" },
...warehouses.map(w => ({ label: w.name, value: String(w.id) }))
]}
placeholder="選擇倉庫"
className="w-full"
/>
</div>
{/* 日期範圍 - 開始 */}
<div className="space-y-1">
<Label className="text-xs text-gray-500"></Label>
<div className="relative">
<Calendar className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
<Input
type="date"
value={dateStart}
onChange={(e) => setDateStart(e.target.value)}
className="pl-9 block w-full"
/>
</div>
</div>
{/* 日期範圍 - 結束 */}
<div className="space-y-1">
<Label className="text-xs text-gray-500"></Label>
<div className="relative">
<Calendar className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
<Input
type="date"
value={dateEnd}
onChange={(e) => setDateEnd(e.target.value)}
className="pl-9 block w-full text-left"
/>
</div>
</div>
</div>
<div className="flex items-center justify-end gap-3 pt-2 border-t border-gray-100">
<Button
variant="outline"
onClick={handleReset}
className="flex items-center gap-2 button-outlined-primary"
>
<RotateCcw className="h-4 w-4" />
</Button>
<Button
onClick={handleFilter}
className="flex items-center gap-2 button-filled-primary"
>
<Search className="h-4 w-4" />
</Button>
</div>
</div> </div>
<PurchaseOrderTable <PurchaseOrderTable
@@ -150,7 +239,7 @@ export default function PurchaseOrderIndex({ orders, filters, warehouses }: Prop
/> />
{/* 分頁元件 - 統一樣式 */} {/* 分頁元件 - 統一樣式 */}
<div className="mt-4 flex flex-col sm:flex-row items-center justify-between gap-4"> <div className="mt-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
<div className="flex items-center gap-2 text-sm text-gray-500"> <div className="flex items-center gap-2 text-sm text-gray-500">
<span></span> <span></span>
<SearchableSelect <SearchableSelect
@@ -162,12 +251,14 @@ export default function PurchaseOrderIndex({ orders, filters, warehouses }: Prop
{ label: "50", value: "50" }, { label: "50", value: "50" },
{ label: "100", value: "100" } { label: "100", value: "100" }
]} ]}
className="w-[80px] h-8" className="w-[100px] h-8"
showSearch={false} showSearch={false}
/> />
<span></span> <span></span>
</div> </div>
<Pagination links={orders.links} /> <div className="w-full sm:w-auto flex justify-center sm:justify-end">
<Pagination links={orders.links} />
</div>
</div> </div>
</div> </div>
</AuthenticatedLayout> </AuthenticatedLayout>

View File

@@ -202,7 +202,7 @@ export default function VendorManagement({ vendors, filters }: PageProps) {
/> />
{/* 分頁元件 - 統一樣式 */} {/* 分頁元件 - 統一樣式 */}
<div className="mt-4 flex flex-col sm:flex-row items-center justify-between gap-4"> <div className="mt-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
<div className="flex items-center gap-2 text-sm text-gray-500"> <div className="flex items-center gap-2 text-sm text-gray-500">
<span></span> <span></span>
<SearchableSelect <SearchableSelect
@@ -214,12 +214,14 @@ export default function VendorManagement({ vendors, filters }: PageProps) {
{ label: "50", value: "50" }, { label: "50", value: "50" },
{ label: "100", value: "100" } { label: "100", value: "100" }
]} ]}
className="w-[80px] h-8" className="w-[100px] h-8"
showSearch={false} showSearch={false}
/> />
<span></span> <span></span>
</div> </div>
<Pagination links={vendors.links} /> <div className="w-full sm:w-auto flex justify-center sm:justify-end">
<Pagination links={vendors.links} />
</div>
</div> </div>
</div> </div>
</AuthenticatedLayout> </AuthenticatedLayout>

View File

@@ -146,7 +146,7 @@ export default function EditInventory({ warehouse, inventory, transactions = []
value={data.batchNumber} value={data.batchNumber}
onChange={(e) => setData("batchNumber", e.target.value)} onChange={(e) => setData("batchNumber", e.target.value)}
placeholder="例FL20251101" placeholder="例FL20251101"
className="button-outlined-primary" className="border-gray-300"
// 目前後端可能尚未支援儲存,但依需求顯示 // 目前後端可能尚未支援儲存,但依需求顯示
/> />
</div> </div>
@@ -172,7 +172,7 @@ export default function EditInventory({ warehouse, inventory, transactions = []
setData("quantity", parseFloat(e.target.value) || 0) setData("quantity", parseFloat(e.target.value) || 0)
} }
placeholder="0" placeholder="0"
className={`button-outlined-primary ${errors.quantity ? "border-red-500" : ""}`} className={`border-gray-300 ${errors.quantity ? "border-red-500" : ""}`}
/> />
{errors.quantity && <p className="text-xs text-red-500">{errors.quantity}</p>} {errors.quantity && <p className="text-xs text-red-500">{errors.quantity}</p>}
<p className="text-sm text-gray-500"> <p className="text-sm text-gray-500">
@@ -194,7 +194,7 @@ export default function EditInventory({ warehouse, inventory, transactions = []
type="date" type="date"
value={data.expiryDate} value={data.expiryDate}
onChange={(e) => setData("expiryDate", e.target.value)} onChange={(e) => setData("expiryDate", e.target.value)}
className="button-outlined-primary" className="border-gray-300"
/> />
</div> </div>
@@ -207,7 +207,7 @@ export default function EditInventory({ warehouse, inventory, transactions = []
onChange={(e) => onChange={(e) =>
setData("lastInboundDate", e.target.value) setData("lastInboundDate", e.target.value)
} }
className="button-outlined-primary" className="border-gray-300"
/> />
</div> </div>
@@ -220,7 +220,7 @@ export default function EditInventory({ warehouse, inventory, transactions = []
onChange={(e) => onChange={(e) =>
setData("lastOutboundDate", e.target.value) setData("lastOutboundDate", e.target.value)
} }
className="button-outlined-primary" className="border-gray-300"
/> />
</div> </div>
</div> </div>