feat: 優化採購單操作紀錄與統一刪除確認 UI

- 優化採購單更新與刪除的活動紀錄邏輯 (PurchaseOrderController)
  - 整合更新異動為單一紀錄,包含品項差異
  - 刪除時記錄當下品項快照
- 統一採購單刪除確認介面,使用 AlertDialog 取代原生 confirm (PurchaseOrderActions)
- Refactor: 將 ActivityDetailDialog 移至 Components/ActivityLog 並優化樣式與大數據顯示
- 調整 UI 文字:將「總金額」統一為「小計」
- 其他模型與 Controller 的活動紀錄支援更新
This commit is contained in:
2026-01-19 15:32:41 +08:00
parent 18edb3cb69
commit a8091276b8
20 changed files with 1114 additions and 482 deletions

View File

@@ -103,6 +103,7 @@ class PurchaseOrderController extends Controller
'items.*.quantity' => 'required|numeric|min:0.01', 'items.*.quantity' => 'required|numeric|min:0.01',
'items.*.subtotal' => 'required|numeric|min:0', // 總金額 'items.*.subtotal' => 'required|numeric|min:0', // 總金額
'items.*.unitId' => 'nullable|exists:units,id', 'items.*.unitId' => 'nullable|exists:units,id',
'tax_amount' => 'nullable|numeric|min:0',
]); ]);
try { try {
@@ -129,8 +130,8 @@ class PurchaseOrderController extends Controller
$totalAmount += $item['subtotal']; $totalAmount += $item['subtotal'];
} }
// Simple tax calculation (e.g., 5%) // Tax calculation
$taxAmount = round($totalAmount * 0.05, 2); $taxAmount = isset($validated['tax_amount']) ? $validated['tax_amount'] : round($totalAmount * 0.05, 2);
$grandTotal = $totalAmount + $taxAmount; $grandTotal = $totalAmount + $taxAmount;
// 確保有一個有效的使用者 ID // 確保有一個有效的使用者 ID
@@ -325,6 +326,9 @@ class PurchaseOrderController extends Controller
'items.*.quantity' => 'required|numeric|min:0.01', 'items.*.quantity' => 'required|numeric|min:0.01',
'items.*.subtotal' => 'required|numeric|min:0', // 總金額 'items.*.subtotal' => 'required|numeric|min:0', // 總金額
'items.*.unitId' => 'nullable|exists:units,id', 'items.*.unitId' => 'nullable|exists:units,id',
// Allow both tax_amount and taxAmount for compatibility
'tax_amount' => 'nullable|numeric|min:0',
'taxAmount' => 'nullable|numeric|min:0',
]); ]);
try { try {
@@ -335,11 +339,13 @@ class PurchaseOrderController extends Controller
$totalAmount += $item['subtotal']; $totalAmount += $item['subtotal'];
} }
// Simple tax calculation (e.g., 5%) // Tax calculation (handle both keys)
$taxAmount = round($totalAmount * 0.05, 2); $inputTax = $validated['tax_amount'] ?? $validated['taxAmount'] ?? null;
$taxAmount = !is_null($inputTax) ? $inputTax : round($totalAmount * 0.05, 2);
$grandTotal = $totalAmount + $taxAmount; $grandTotal = $totalAmount + $taxAmount;
$order->update([ // 1. Fill attributes but don't save yet to capture changes
$order->fill([
'vendor_id' => $validated['vendor_id'], 'vendor_id' => $validated['vendor_id'],
'warehouse_id' => $validated['warehouse_id'], 'warehouse_id' => $validated['warehouse_id'],
'expected_delivery_date' => $validated['expected_delivery_date'], 'expected_delivery_date' => $validated['expected_delivery_date'],
@@ -353,19 +359,124 @@ class PurchaseOrderController extends Controller
'invoice_amount' => $validated['invoice_amount'] ?? null, 'invoice_amount' => $validated['invoice_amount'] ?? null,
]); ]);
// Sync items // Capture attribute changes for manual logging
$dirty = $order->getDirty();
$oldAttributes = [];
$newAttributes = [];
foreach ($dirty as $key => $value) {
$oldAttributes[$key] = $order->getOriginal($key);
$newAttributes[$key] = $value;
}
// Save without triggering events (prevents duplicate log)
$order->saveQuietly();
// 2. Capture old items with product names for diffing
$oldItems = $order->items()->with('product', 'unit')->get()->map(function($item) {
return [
'id' => $item->id,
'product_id' => $item->product_id,
'product_name' => $item->product?->name,
'quantity' => (float) $item->quantity,
'unit_id' => $item->unit_id,
'unit_name' => $item->unit?->name,
'subtotal' => (float) $item->subtotal,
];
})->keyBy('product_id');
// Sync items (Original logic)
$order->items()->delete(); $order->items()->delete();
$newItemsData = [];
foreach ($validated['items'] as $item) { foreach ($validated['items'] as $item) {
// 反算單價 // 反算單價
$unitPrice = $item['quantity'] > 0 ? $item['subtotal'] / $item['quantity'] : 0; $unitPrice = $item['quantity'] > 0 ? $item['subtotal'] / $item['quantity'] : 0;
$order->items()->create([ $newItem = $order->items()->create([
'product_id' => $item['productId'], 'product_id' => $item['productId'],
'quantity' => $item['quantity'], 'quantity' => $item['quantity'],
'unit_id' => $item['unitId'] ?? null, 'unit_id' => $item['unitId'] ?? null,
'unit_price' => $unitPrice, 'unit_price' => $unitPrice,
'subtotal' => $item['subtotal'], 'subtotal' => $item['subtotal'],
]); ]);
$newItemsData[] = $newItem;
}
// 3. Calculate Item Diffs
$itemDiffs = [
'added' => [],
'removed' => [],
'updated' => [],
];
// Re-fetch new items to ensure we have fresh relations
$newItemsFormatted = $order->items()->with('product', 'unit')->get()->map(function($item) {
return [
'product_id' => $item->product_id,
'product_name' => $item->product?->name,
'quantity' => (float) $item->quantity,
'unit_id' => $item->unit_id,
'unit_name' => $item->unit?->name,
'subtotal' => (float) $item->subtotal,
];
})->keyBy('product_id');
// Find removed
foreach ($oldItems as $productId => $oldItem) {
if (!$newItemsFormatted->has($productId)) {
$itemDiffs['removed'][] = $oldItem;
}
}
// Find added and updated
foreach ($newItemsFormatted as $productId => $newItem) {
if (!$oldItems->has($productId)) {
$itemDiffs['added'][] = $newItem;
} else {
$oldItem = $oldItems[$productId];
// Compare fields
if (
$oldItem['quantity'] != $newItem['quantity'] ||
$oldItem['unit_id'] != $newItem['unit_id'] ||
$oldItem['subtotal'] != $newItem['subtotal']
) {
$itemDiffs['updated'][] = [
'product_name' => $newItem['product_name'],
'old' => [
'quantity' => $oldItem['quantity'],
'unit_name' => $oldItem['unit_name'],
'subtotal' => $oldItem['subtotal'],
],
'new' => [
'quantity' => $newItem['quantity'],
'unit_name' => $newItem['unit_name'],
'subtotal' => $newItem['subtotal'],
]
];
}
}
}
// 4. Manually Log activity (Single Consolidated Log)
// Log if there are attribute changes OR item changes
if (!empty($newAttributes) || !empty($itemDiffs['added']) || !empty($itemDiffs['removed']) || !empty($itemDiffs['updated'])) {
activity()
->performedOn($order)
->causedBy(auth()->user())
->event('updated')
->withProperties([
'attributes' => $newAttributes,
'old' => $oldAttributes,
'items_diff' => $itemDiffs,
'snapshot' => [
'po_number' => $order->code,
'vendor_name' => $order->vendor?->name,
'warehouse_name' => $order->warehouse?->name,
'user_name' => $order->user?->name,
]
])
->log('updated');
} }
DB::commit(); DB::commit();
@@ -383,9 +494,43 @@ class PurchaseOrderController extends Controller
try { try {
DB::beginTransaction(); DB::beginTransaction();
$order = PurchaseOrder::findOrFail($id); $order = PurchaseOrder::with(['items.product', 'items.unit'])->findOrFail($id);
// Delete associated items first (due to FK constraints if not cascade) // Capture items for logging
$items = $order->items->map(function ($item) {
return [
'product_name' => $item->product_name,
'quantity' => floatval($item->quantity),
'unit_name' => $item->unit_name,
'subtotal' => floatval($item->subtotal),
];
})->toArray();
// Manually log the deletion with items
activity()
->performedOn($order)
->causedBy(auth()->user())
->event('deleted')
->withProperties([
'attributes' => $order->getAttributes(),
'items_diff' => [
'added' => [],
'removed' => $items,
'updated' => [],
],
'snapshot' => [
'po_number' => $order->code,
'vendor_name' => $order->vendor?->name,
'warehouse_name' => $order->warehouse?->name,
'user_name' => $order->user?->name,
]
])
->log('deleted');
// Disable automatic logging for this operation
$order->disableLogging();
// Delete associated items first
$order->items()->delete(); $order->items()->delete();
$order->delete(); $order->delete();

View File

@@ -27,6 +27,25 @@ class VendorProductController extends Controller
'last_price' => $validated['last_price'] ?? null 'last_price' => $validated['last_price'] ?? null
]); ]);
// 記錄操作
$product = \App\Models\Product::find($validated['product_id']);
activity()
->performedOn($vendor)
->withProperties([
'attributes' => [
'product_name' => $product->name,
'last_price' => $validated['last_price'] ?? null,
],
'sub_subject' => '供貨商品',
'snapshot' => [
'name' => "{$vendor->name}-{$product->name}", // 顯示例如:台積電-紅糖
'vendor_name' => $vendor->name,
'product_name' => $product->name,
]
])
->event('created')
->log('新增供貨商品');
return redirect()->back()->with('success', '供貨商品已新增'); return redirect()->back()->with('success', '供貨商品已新增');
} }
@@ -39,10 +58,34 @@ class VendorProductController extends Controller
'last_price' => 'nullable|numeric|min:0', 'last_price' => 'nullable|numeric|min:0',
]); ]);
// 獲取舊價格
$old_price = $vendor->products()->where('product_id', $productId)->first()?->pivot?->last_price;
$vendor->products()->updateExistingPivot($productId, [ $vendor->products()->updateExistingPivot($productId, [
'last_price' => $validated['last_price'] ?? null 'last_price' => $validated['last_price'] ?? null
]); ]);
// 記錄操作
$product = \App\Models\Product::find($productId);
activity()
->performedOn($vendor)
->withProperties([
'old' => [
'last_price' => $old_price,
],
'attributes' => [
'last_price' => $validated['last_price'] ?? null,
],
'sub_subject' => '供貨商品',
'snapshot' => [
'name' => "{$vendor->name}-{$product->name}",
'vendor_name' => $vendor->name,
'product_name' => $product->name,
]
])
->event('updated')
->log('更新供貨商品價格');
return redirect()->back()->with('success', '供貨資訊已更新'); return redirect()->back()->with('success', '供貨資訊已更新');
} }
@@ -51,8 +94,31 @@ class VendorProductController extends Controller
*/ */
public function destroy(Vendor $vendor, $productId) public function destroy(Vendor $vendor, $productId)
{ {
// 記錄操作 (需在 detach 前獲取資訊)
$product = \App\Models\Product::find($productId);
$old_price = $vendor->products()->where('product_id', $productId)->first()?->pivot?->last_price;
$vendor->products()->detach($productId); $vendor->products()->detach($productId);
if ($product) {
activity()
->performedOn($vendor)
->withProperties([
'old' => [
'product_name' => $product->name,
'last_price' => $old_price,
],
'sub_subject' => '供貨商品',
'snapshot' => [
'name' => "{$vendor->name}-{$product->name}",
'vendor_name' => $vendor->name,
'product_name' => $product->name,
]
])
->event('deleted')
->log('移除供貨商品');
}
return redirect()->back()->with('success', '供貨商品已移除'); return redirect()->back()->with('success', '供貨商品已移除');
} }
} }

View File

@@ -40,9 +40,11 @@ class Category extends Model
public function tapActivity(\Spatie\Activitylog\Contracts\Activity $activity, string $eventName) public function tapActivity(\Spatie\Activitylog\Contracts\Activity $activity, string $eventName)
{ {
$properties = $activity->properties; $properties = $activity->properties;
$attributes = $properties['attributes'] ?? [];
$attributes['name'] = $this->name; $snapshot = $properties['snapshot'] ?? [];
$properties['attributes'] = $attributes; $snapshot['name'] = $this->name;
$properties['snapshot'] = $snapshot;
$activity->properties = $properties; $activity->properties = $properties;
} }
} }

View File

@@ -38,11 +38,12 @@ class Inventory extends Model
{ {
$properties = $activity->properties; $properties = $activity->properties;
$attributes = $properties['attributes'] ?? []; $attributes = $properties['attributes'] ?? [];
$snapshot = $properties['snapshot'] ?? [];
// Always snapshot names for context, even if IDs didn't change // Always snapshot names for context, even if IDs didn't change
// $this refers to the Inventory model instance // $this refers to the Inventory model instance
$attributes['warehouse_name'] = $this->warehouse ? $this->warehouse->name : ($attributes['warehouse_name'] ?? null); $snapshot['warehouse_name'] = $this->warehouse ? $this->warehouse->name : ($snapshot['warehouse_name'] ?? null);
$attributes['product_name'] = $this->product ? $this->product->name : ($attributes['product_name'] ?? null); $snapshot['product_name'] = $this->product ? $this->product->name : ($snapshot['product_name'] ?? null);
// Capture the reason if set // Capture the reason if set
if ($this->activityLogReason) { if ($this->activityLogReason) {
@@ -50,6 +51,7 @@ class Inventory extends Model
} }
$properties['attributes'] = $attributes; $properties['attributes'] = $attributes;
$properties['snapshot'] = $snapshot;
$activity->properties = $properties; $activity->properties = $properties;
} }

View File

@@ -80,11 +80,12 @@ class Product extends Model
{ {
$properties = $activity->properties; $properties = $activity->properties;
$attributes = $properties['attributes'] ?? []; $attributes = $properties['attributes'] ?? [];
$snapshot = $properties['snapshot'] ?? [];
// Handle Category Name Snapshot // Handle Category Name Snapshot
if (isset($attributes['category_id'])) { if (isset($attributes['category_id'])) {
$category = Category::find($attributes['category_id']); $category = Category::find($attributes['category_id']);
$attributes['category_name'] = $category ? $category->name : null; $snapshot['category_name'] = $category ? $category->name : null;
} }
// Handle Unit Name Snapshots // Handle Unit Name Snapshots
@@ -93,14 +94,15 @@ class Product extends Model
if (isset($attributes[$field])) { if (isset($attributes[$field])) {
$unit = Unit::find($attributes[$field]); $unit = Unit::find($attributes[$field]);
$nameKey = str_replace('_id', '_name', $field); $nameKey = str_replace('_id', '_name', $field);
$attributes[$nameKey] = $unit ? $unit->name : null; $snapshot[$nameKey] = $unit ? $unit->name : null;
} }
} }
// Always snapshot self name for context (so logs always show "Cola") // Always snapshot self name for context (so logs always show "Cola")
$attributes['name'] = $this->name; $snapshot['name'] = $this->name;
$properties['attributes'] = $attributes; $properties['attributes'] = $attributes;
$properties['snapshot'] = $snapshot;
$activity->properties = $properties; $activity->properties = $properties;
} }

View File

@@ -44,6 +44,8 @@ class PurchaseOrder extends Model
'supplierName', 'supplierName',
'expectedDate', 'expectedDate',
'totalAmount', 'totalAmount',
'taxAmount', // Add this
'grandTotal', // Add this
'createdBy', 'createdBy',
'warehouse_name', 'warehouse_name',
'createdAt', 'createdAt',
@@ -82,6 +84,16 @@ class PurchaseOrder extends Model
return (float) ($this->attributes['total_amount'] ?? 0); return (float) ($this->attributes['total_amount'] ?? 0);
} }
public function getTaxAmountAttribute(): float
{
return (float) ($this->attributes['tax_amount'] ?? 0);
}
public function getGrandTotalAttribute(): float
{
return (float) ($this->attributes['grand_total'] ?? 0);
}
public function getCreatedByAttribute(): string public function getCreatedByAttribute(): string
{ {
return $this->user ? $this->user->name : '系統'; return $this->user ? $this->user->name : '系統';
@@ -135,4 +147,21 @@ class PurchaseOrder extends Model
->logOnlyDirty() ->logOnlyDirty()
->dontSubmitEmptyLogs(); ->dontSubmitEmptyLogs();
} }
public function tapActivity(\Spatie\Activitylog\Contracts\Activity $activity, string $eventName)
{
$properties = $activity->properties;
$attributes = $properties['attributes'] ?? [];
$snapshot = $properties['snapshot'] ?? [];
// Snapshot key names
$snapshot['po_number'] = $this->code;
$snapshot['vendor_name'] = $this->vendor ? $this->vendor->name : null;
$snapshot['warehouse_name'] = $this->warehouse ? $this->warehouse->name : null;
$snapshot['user_name'] = $this->user ? $this->user->name : null;
$properties['attributes'] = $attributes;
$properties['snapshot'] = $snapshot;
$activity->properties = $properties;
}
} }

View File

@@ -27,9 +27,11 @@ class Unit extends Model
public function tapActivity(\Spatie\Activitylog\Contracts\Activity $activity, string $eventName) public function tapActivity(\Spatie\Activitylog\Contracts\Activity $activity, string $eventName)
{ {
$properties = $activity->properties; $properties = $activity->properties;
$attributes = $properties['attributes'] ?? [];
$attributes['name'] = $this->name; $snapshot = $properties['snapshot'] ?? [];
$properties['attributes'] = $attributes; $snapshot['name'] = $this->name;
$properties['snapshot'] = $snapshot;
$activity->properties = $properties; $activity->properties = $properties;
} }
} }

View File

@@ -44,4 +44,19 @@ class Vendor extends Model
->logOnlyDirty() ->logOnlyDirty()
->dontSubmitEmptyLogs(); ->dontSubmitEmptyLogs();
} }
public function tapActivity(\Spatie\Activitylog\Contracts\Activity $activity, string $eventName)
{
$properties = $activity->properties;
// Store name in 'snapshot' for context, keeping 'attributes' clean
$snapshot = $properties['snapshot'] ?? [];
// Only set name if it's not already set (e.g. by controller for specific context like supply product)
if (!isset($snapshot['name'])) {
$snapshot['name'] = $this->name;
}
$properties['snapshot'] = $snapshot;
$activity->properties = $properties;
}
} }

View File

@@ -29,12 +29,11 @@ class Warehouse extends Model
public function tapActivity(\Spatie\Activitylog\Contracts\Activity $activity, string $eventName) public function tapActivity(\Spatie\Activitylog\Contracts\Activity $activity, string $eventName)
{ {
$properties = $activity->properties; $properties = $activity->properties;
$attributes = $properties['attributes'] ?? [];
$snapshot = $properties['snapshot'] ?? [];
$snapshot['name'] = $this->name;
$properties['snapshot'] = $snapshot;
// Always snapshot name
$attributes['name'] = $this->name;
$properties['attributes'] = $attributes;
$activity->properties = $properties; $activity->properties = $properties;
} }

View File

@@ -0,0 +1,440 @@
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/Components/ui/dialog";
import { Badge } from "@/Components/ui/badge";
import { ScrollArea } from "@/Components/ui/scroll-area";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/Components/ui/table";
import { User, Clock, Package, Activity as ActivityIcon } from "lucide-react";
interface Activity {
id: number;
description: string;
subject_type: string;
event: string;
causer: string;
created_at: string;
properties: {
attributes?: Record<string, any>;
old?: Record<string, any>;
snapshot?: Record<string, any>;
sub_subject?: string;
items_diff?: {
added: any[];
removed: any[];
updated: any[];
};
};
}
interface Props {
open: boolean;
onOpenChange: (open: boolean) => void;
activity: Activity | null;
}
// Field translation map
const fieldLabels: Record<string, string> = {
name: '名稱',
code: '代碼',
description: '描述',
price: '價格',
cost: '成本',
stock: '庫存',
category_id: '分類',
unit_id: '單位',
is_active: '啟用狀態',
conversion_rate: '換算率',
specification: '規格',
brand: '品牌',
base_unit_id: '基本單位',
large_unit_id: '大單位',
purchase_unit_id: '採購單位',
email: 'Email',
password: '密碼',
phone: '電話',
address: '地址',
role_id: '角色',
// Snapshot fields
category_name: '分類名稱',
base_unit_name: '基本單位名稱',
large_unit_name: '大單位名稱',
purchase_unit_name: '採購單位名稱',
// Vendor fields
short_name: '簡稱',
tax_id: '統編',
owner: '負責人',
contact_name: '聯絡人',
tel: '電話',
remark: '備註',
// Warehouse & Inventory fields
warehouse_name: '倉庫名稱',
product_name: '商品名稱',
warehouse_id: '倉庫',
product_id: '商品',
quantity: '數量',
safety_stock: '安全庫存',
location: '儲位',
// Purchase Order fields
po_number: '採購單號',
vendor_id: '廠商',
vendor_name: '廠商名稱',
user_name: '建單人員',
user_id: '建單人員',
total_amount: '小計',
expected_delivery_date: '預計到貨日',
status: '狀態',
tax_amount: '稅額',
grand_total: '總計',
invoice_number: '發票號碼',
invoice_date: '發票日期',
invoice_amount: '發票金額',
last_price: '供貨價格',
};
// Purchase Order Status Map
const statusMap: Record<string, string> = {
draft: '草稿',
pending: '待審核',
approved: '已核准',
ordered: '已下單',
received: '已收貨',
cancelled: '已取消',
completed: '已完成',
};
export default function ActivityDetailDialog({ open, onOpenChange, activity }: Props) {
if (!activity) return null;
const attributes = activity.properties?.attributes || {};
const old = activity.properties?.old || {};
const snapshot = activity.properties?.snapshot || {};
// Get all keys from both attributes and old to ensure we show all changes
const allKeys = Array.from(new Set([...Object.keys(attributes), ...Object.keys(old)]));
// Custom sort order for fields
const sortOrder = [
'po_number', 'vendor_name', 'warehouse_name', 'expected_delivery_date', 'status', 'remark',
'invoice_number', 'invoice_date', 'invoice_amount',
'total_amount', 'tax_amount', 'grand_total' // Ensure specific order for amounts
];
// Filter out internal keys often logged but not useful for users
const filteredKeys = allKeys
.filter(key =>
!['created_at', 'updated_at', 'deleted_at', 'id'].includes(key)
)
.sort((a, b) => {
const indexA = sortOrder.indexOf(a);
const indexB = sortOrder.indexOf(b);
// If both are in sortOrder, compare indices
if (indexA !== -1 && indexB !== -1) return indexA - indexB;
// If only A is in sortOrder, it comes first (or wherever logic dictates, usually put known fields first)
if (indexA !== -1) return -1;
if (indexB !== -1) return 1;
// Otherwise alphabetical or default
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
const isSnapshotField = (key: string) => {
return [
'category_name', 'base_unit_name', 'large_unit_name', 'purchase_unit_name',
'warehouse_name', 'user_name'
].includes(key);
};
const getEventBadgeClass = (event: string) => {
switch (event) {
case 'created': return 'bg-green-50 text-green-700 border-green-200';
case 'updated': return 'bg-blue-50 text-blue-700 border-blue-200';
case 'deleted': return 'bg-red-50 text-red-700 border-red-200';
default: return 'bg-gray-50 text-gray-700 border-gray-200';
}
};
const getEventLabel = (event: string) => {
switch (event) {
case 'created': return '新增';
case 'updated': return '更新';
case 'deleted': return '刪除';
case 'updated_items': return '異動品項';
default: return event;
}
};
const formatValue = (key: string, value: any) => {
if (value === null || value === undefined) return '-';
if (typeof value === 'boolean') return value ? '是' : '否';
if (key === 'is_active') return value ? '啟用' : '停用';
// Handle Purchase Order Status
if (key === 'status' && typeof value === 'string' && statusMap[value]) {
return statusMap[value];
}
// Handle Date Fields (YYYY-MM-DD)
if ((key === 'expected_delivery_date' || key === 'invoice_date') && typeof value === 'string') {
// Take only the date part (YYYY-MM-DD)
return value.split('T')[0].split(' ')[0];
}
return String(value);
};
const getFormattedValue = (key: string, value: any) => {
// If it's an ID field, try to find a corresponding name in snapshot or attributes
if (key.endsWith('_id')) {
const nameKey = key.replace('_id', '_name');
// Check snapshot first, then attributes
const nameValue = snapshot[nameKey] || attributes[nameKey];
if (nameValue) {
return `${nameValue}`;
}
}
return formatValue(key, value);
};
// Helper to get translated field label
const getFieldLabel = (key: string) => {
return fieldLabels[key] || key;
};
// Get subject name for header
const getSubjectName = () => {
// Special handling for Inventory: show "Warehouse - Product"
if ((snapshot.warehouse_name || attributes.warehouse_name) && (snapshot.product_name || attributes.product_name)) {
const wName = snapshot.warehouse_name || attributes.warehouse_name;
const pName = snapshot.product_name || attributes.product_name;
return `${wName} - ${pName}`;
}
const nameParams = ['po_number', 'name', 'code', 'product_name', 'warehouse_name', 'category_name', 'base_unit_name', 'title'];
for (const param of nameParams) {
if (snapshot[param]) return snapshot[param];
if (attributes[param]) return attributes[param];
if (old[param]) return old[param];
}
if (attributes.id || old.id) return `#${attributes.id || old.id}`;
return '';
};
const subjectName = getSubjectName();
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-3xl max-h-[90vh] flex flex-col p-0 gap-0 overflow-hidden">
<DialogHeader className="p-6 pb-4 border-b pr-12">
<div className="flex items-center gap-3 mb-2">
<DialogTitle className="text-xl font-bold text-gray-900">
</DialogTitle>
<Badge variant="outline" className={getEventBadgeClass(activity.event)}>
{getEventLabel(activity.event)}
</Badge>
</div>
{/* Modern Metadata Strip */}
<div className="flex flex-wrap items-center gap-6 pt-2 text-sm text-gray-500">
<div className="flex items-center gap-2">
<User className="w-4 h-4 text-gray-400" />
<span className="font-medium text-gray-700">{activity.causer}</span>
</div>
<div className="flex items-center gap-2">
<Clock className="w-4 h-4 text-gray-400" />
<span>{activity.created_at}</span>
</div>
<div className="flex items-center gap-2">
<Package className="w-4 h-4 text-gray-400" />
<span className="font-medium text-gray-700">
{subjectName ? `${subjectName} ` : ''}
{activity.properties?.sub_subject || activity.subject_type}
</span>
</div>
{/* Only show 'description' if it differs from event name (unlikely but safe) */}
{activity.description !== getEventLabel(activity.event) &&
activity.description !== 'created' && activity.description !== 'updated' && (
<div className="flex items-center gap-2">
<ActivityIcon className="w-4 h-4 text-gray-400" />
<span>{activity.description}</span>
</div>
)}
</div>
</DialogHeader>
<div className="flex-1 overflow-hidden bg-gray-50/50">
<ScrollArea className="h-full max-h-[calc(90vh-140px)] p-6">
{activity.event === 'created' ? (
<div className="border rounded-md overflow-hidden bg-white shadow-sm">
<Table>
<TableHeader>
<TableRow className="bg-gray-50/50 hover:bg-gray-50/50">
<TableHead className="w-[150px]"></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredKeys
.filter(key => attributes[key] !== null && attributes[key] !== '' && !isSnapshotField(key))
.map((key) => (
<TableRow key={key}>
<TableCell className="font-medium text-gray-700 w-[150px]">{getFieldLabel(key)}</TableCell>
<TableCell className="text-gray-500 break-words max-w-[200px]">-</TableCell>
<TableCell className="text-gray-900 font-medium break-words max-w-[200px]">
{getFormattedValue(key, attributes[key])}
</TableCell>
</TableRow>
))}
{filteredKeys.filter(key => attributes[key] !== null && attributes[key] !== '' && !isSnapshotField(key)).length === 0 && (
<TableRow>
<TableCell colSpan={3} className="h-24 text-center text-gray-500">
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
) : (
<div className="border rounded-md overflow-hidden bg-white shadow-sm">
<Table>
<TableHeader>
<TableRow className="bg-gray-50 hover:bg-gray-50">
<TableHead className="w-[150px]"></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredKeys.some(key => !isSnapshotField(key)) ? (
filteredKeys
.filter(key => !isSnapshotField(key))
.map((key) => {
const oldValue = old[key];
const newValue = attributes[key];
const isChanged = JSON.stringify(oldValue) !== JSON.stringify(newValue);
// For deleted events, we want to show the current attributes in the "Before" column
const displayBefore = activity.event === 'deleted'
? getFormattedValue(key, newValue || oldValue)
: getFormattedValue(key, oldValue);
const displayAfter = activity.event === 'deleted'
? '-'
: getFormattedValue(key, newValue);
return (
<TableRow key={key} className={isChanged ? 'bg-amber-50/30 hover:bg-amber-50/50' : 'hover:bg-gray-50/50'}>
<TableCell className="font-medium text-gray-700 w-[150px]">{getFieldLabel(key)}</TableCell>
<TableCell className="text-gray-500 break-words max-w-[200px]">
{displayBefore}
</TableCell>
<TableCell className="text-gray-900 font-medium break-words max-w-[200px]">
{displayAfter}
</TableCell>
</TableRow>
);
})
) : (
<TableRow>
<TableCell colSpan={3} className="h-24 text-center text-gray-500">
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
)}
{/* Items Diff Section (Special for Purchase Orders) */}
{activity.properties?.items_diff && (
<div className="mt-6 space-y-4">
<h3 className="text-sm font-bold text-gray-900 flex items-center gap-2 px-1">
<Package className="w-4 h-4 text-primary-main" />
</h3>
<div className="border rounded-md overflow-hidden bg-white shadow-sm">
<Table>
<TableHeader className="bg-gray-50/50">
<TableRow>
<TableHead></TableHead>
<TableHead className="text-center"></TableHead>
<TableHead> ( )</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{/* Updated Items */}
{activity.properties.items_diff.updated.map((item: any, idx: number) => (
<TableRow key={`upd-${idx}`} className="bg-blue-50/10 hover:bg-blue-50/20">
<TableCell className="font-medium">{item.product_name}</TableCell>
<TableCell className="text-center">
<Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200"></Badge>
</TableCell>
<TableCell className="text-sm">
<div className="space-y-1">
{item.old.quantity !== item.new.quantity && (
<div>: <span className="text-gray-500 line-through">{item.old.quantity}</span> <span className="text-blue-700 font-bold">{item.new.quantity}</span></div>
)}
{item.old.unit_name !== item.new.unit_name && (
<div>: <span className="text-gray-500 line-through">{item.old.unit_name || '-'}</span> <span className="text-blue-700 font-bold">{item.new.unit_name || '-'}</span></div>
)}
{item.old.subtotal !== item.new.subtotal && (
<div>: <span className="text-gray-500 line-through">${item.old.subtotal}</span> <span className="text-blue-700 font-bold">${item.new.subtotal}</span></div>
)}
</div>
</TableCell>
</TableRow>
))}
{/* Added Items */}
{activity.properties.items_diff.added.map((item: any, idx: number) => (
<TableRow key={`add-${idx}`} className="bg-green-50/10 hover:bg-green-50/20">
<TableCell className="font-medium">{item.product_name}</TableCell>
<TableCell className="text-center">
<Badge variant="outline" className="bg-green-50 text-green-700 border-green-200"></Badge>
</TableCell>
<TableCell className="text-sm">
: {item.quantity} {item.unit_name} / 小計: ${item.subtotal}
</TableCell>
</TableRow>
))}
{/* Removed Items */}
{activity.properties.items_diff.removed.map((item: any, idx: number) => (
<TableRow key={`rem-${idx}`} className="bg-red-50/10 hover:bg-red-50/20">
<TableCell className="font-medium text-gray-400 line-through">{item.product_name}</TableCell>
<TableCell className="text-center">
<Badge variant="outline" className="bg-red-50 text-red-700 border-red-200"></Badge>
</TableCell>
<TableCell className="text-sm text-gray-400">
: {item.quantity} {item.unit_name}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</div>
)}
</ScrollArea>
</div>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,213 @@
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/Components/ui/table";
import { Badge } from "@/Components/ui/badge";
import { Eye, ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-react';
import { Button } from '@/Components/ui/button';
export interface Activity {
id: number;
description: string;
subject_type: string;
event: string;
causer: string;
created_at: string;
properties: any;
}
interface LogTableProps {
activities: Activity[];
sortField?: string;
sortOrder?: 'asc' | 'desc';
onSort?: (field: string) => void;
onViewDetail: (activity: Activity) => void;
from?: number; // Starting index number (paginator.from)
}
export default function LogTable({
activities,
sortField,
sortOrder,
onSort,
onViewDetail,
from = 1
}: LogTableProps) {
const getEventBadgeClass = (event: string) => {
switch (event) {
case 'created': return 'bg-green-50 text-green-700 border-green-200 hover:bg-green-100';
case 'updated': return 'bg-blue-50 text-blue-700 border-blue-200 hover:bg-blue-100';
case 'deleted': return 'bg-red-50 text-red-700 border-red-200 hover:bg-red-100';
default: return 'bg-gray-50 text-gray-700 border-gray-200 hover:bg-gray-100';
}
};
const getEventLabel = (event: string) => {
switch (event) {
case 'created': return '新增';
case 'updated': return '更新';
case 'deleted': return '刪除';
default: return event;
}
};
const getDescription = (activity: Activity) => {
const props = activity.properties || {};
const attrs = props.attributes || {};
const old = props.old || {};
const snapshot = props.snapshot || {};
// Try to find a name in snapshot, attributes or old values
// Priority: snapshot > specific name fields > generic name > code > ID
const nameParams = ['po_number', 'name', 'code', 'product_name', 'warehouse_name', 'category_name', 'base_unit_name', 'title'];
let subjectName = '';
// Special handling for Inventory: show "Warehouse - Product"
if ((snapshot.warehouse_name || attrs.warehouse_name) && (snapshot.product_name || attrs.product_name)) {
const wName = snapshot.warehouse_name || attrs.warehouse_name;
const pName = snapshot.product_name || attrs.product_name;
subjectName = `${wName} - ${pName}`;
} else if (old.warehouse_name && old.product_name) {
subjectName = `${old.warehouse_name} - ${old.product_name}`;
} else {
// Default fallback
for (const param of nameParams) {
if (snapshot[param]) {
subjectName = snapshot[param];
break;
}
if (attrs[param]) {
subjectName = attrs[param];
break;
}
if (old[param]) {
subjectName = old[param];
break;
}
}
}
// If no name found, try ID but format it nicely if possible, or just don't show it if it's redundant with subject_type
if (!subjectName && (attrs.id || old.id)) {
subjectName = `#${attrs.id || old.id}`;
}
// Combine parts: [Causer] [Action] [Name] [Subject]
// Example: Admin 新增 可樂 商品
// Example: Admin 更新 台北倉 - 可樂 庫存
return (
<span className="flex items-center gap-1.5 flex-wrap">
<span className="font-medium text-gray-900">{activity.causer}</span>
<span className="text-gray-500">{getEventLabel(activity.event)}</span>
{subjectName && (
<span className="font-medium text-primary-600 bg-primary-50 px-1.5 py-0.5 rounded text-xs">
{subjectName}
</span>
)}
{props.sub_subject ? (
<span className="text-gray-700">{props.sub_subject}</span>
) : (
<span className="text-gray-700">{activity.subject_type}</span>
)}
{/* Display reason/source if available (e.g., from Replenishment) */}
{(attrs._reason || old._reason) && (
<span className="text-gray-500 text-xs">
( {attrs._reason || old._reason})
</span>
)}
</span>
);
};
const SortIcon = ({ field }: { field: string }) => {
if (!onSort) return null;
if (sortField !== field) {
return <ArrowUpDown className="h-4 w-4 text-muted-foreground ml-1" />;
}
if (sortOrder === "asc") {
return <ArrowUp className="h-4 w-4 text-primary-main ml-1" />;
}
return <ArrowDown className="h-4 w-4 text-primary-main ml-1" />;
};
return (
<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">#</TableHead>
<TableHead className="w-[180px]">
{onSort ? (
<button
onClick={() => onSort('created_at')}
className="flex items-center gap-1 hover:text-gray-900 transition-colors"
>
<SortIcon field="created_at" />
</button>
) : (
"時間"
)}
</TableHead>
<TableHead className="w-[150px]"></TableHead>
<TableHead></TableHead>
<TableHead className="w-[100px] text-center"></TableHead>
<TableHead></TableHead>
<TableHead className="w-[100px] text-center"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{activities.length > 0 ? (
activities.map((activity, index) => (
<TableRow key={activity.id}>
<TableCell className="text-gray-500 font-medium text-center">
{from + index}
</TableCell>
<TableCell className="text-gray-500 font-medium whitespace-nowrap">
{activity.created_at}
</TableCell>
<TableCell>
<span className="font-medium text-gray-900">{activity.causer}</span>
</TableCell>
<TableCell>
{getDescription(activity)}
</TableCell>
<TableCell className="text-center">
<Badge variant="outline" className={getEventBadgeClass(activity.event)}>
{getEventLabel(activity.event)}
</Badge>
</TableCell>
<TableCell>
<Badge variant="outline" className="bg-slate-50 text-slate-600 border-slate-200">
{activity.subject_type}
</Badge>
</TableCell>
<TableCell className="text-center">
<Button
variant="outline"
size="sm"
onClick={() => onViewDetail(activity)}
className="button-outlined-primary"
title="檢視詳情"
>
<Eye className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={7} className="text-center py-8 text-gray-500">
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
);
}

View File

@@ -1,23 +1,36 @@
import { useState } from "react";
import { Pencil, Eye, Trash2 } from "lucide-react"; import { Pencil, Eye, Trash2 } from "lucide-react";
import { Button } from "@/Components/ui/button"; import { Button } from "@/Components/ui/button";
import { Link, useForm } from "@inertiajs/react"; import { Link, useForm } from "@inertiajs/react";
import type { PurchaseOrder } from "@/types/purchase-order"; import type { PurchaseOrder } from "@/types/purchase-order";
import { toast } from "sonner"; import { toast } from "sonner";
import { Can } from "@/Components/Permission/Can"; import { Can } from "@/Components/Permission/Can";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/Components/ui/alert-dialog";
export function PurchaseOrderActions({ export function PurchaseOrderActions({
order, order,
}: { order: PurchaseOrder }) { }: { order: PurchaseOrder }) {
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const { delete: destroy, processing } = useForm({}); const { delete: destroy, processing } = useForm({});
const handleDelete = () => { const handleConfirmDelete = () => {
if (confirm(`確定要刪除採購單 ${order.poNumber} 嗎?`)) { // @ts-ignore
// @ts-ignore destroy(route('purchase-orders.destroy', order.id), {
destroy(route('purchase-orders.destroy', order.id), { onSuccess: () => {
onSuccess: () => toast.success("採購單已成功刪除"), toast.success("採購單已成功刪除");
onError: (errors: any) => toast.error(errors.error || "刪除過程中發生錯誤"), setShowDeleteDialog(false);
}); },
} onError: (errors: any) => toast.error(errors.error || "刪除過程中發生錯誤"),
});
}; };
return ( return (
@@ -50,11 +63,31 @@ export function PurchaseOrderActions({
size="sm" size="sm"
className="button-outlined-error" className="button-outlined-error"
title="刪除" title="刪除"
onClick={handleDelete} onClick={() => setShowDeleteDialog(true)}
disabled={processing} disabled={processing}
> >
<Trash2 className="h-4 w-4" /> <Trash2 className="h-4 w-4" />
</Button> </Button>
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle></AlertDialogTitle>
<AlertDialogDescription>
{order.poNumber}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel className="button-outlined-primary"></AlertDialogCancel>
<AlertDialogAction
onClick={handleConfirmDelete}
className="button-filled-error"
>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</Can> </Can>
</div> </div>
); );

View File

@@ -44,7 +44,7 @@ export function PurchaseOrderItemsTable({
<TableHead className="w-[10%] text-left"></TableHead> <TableHead className="w-[10%] text-left"></TableHead>
<TableHead className="w-[12%] text-left"></TableHead> <TableHead className="w-[12%] text-left"></TableHead>
<TableHead className="w-[12%] text-left"></TableHead> <TableHead className="w-[12%] text-left"></TableHead>
<TableHead className="w-[15%] text-left"></TableHead> <TableHead className="w-[15%] text-left"></TableHead>
<TableHead className="w-[15%] text-left"> / </TableHead> <TableHead className="w-[15%] text-left"> / </TableHead>
{!isReadOnly && <TableHead className="w-[5%]"></TableHead>} {!isReadOnly && <TableHead className="w-[5%]"></TableHead>}
</TableRow> </TableRow>

View File

@@ -161,7 +161,7 @@ export default function PurchaseOrderTable({
onClick={() => handleSort("totalAmount")} onClick={() => handleSort("totalAmount")}
className="flex items-center gap-2 ml-auto hover:text-foreground transition-colors" className="flex items-center gap-2 ml-auto hover:text-foreground transition-colors"
> >
<SortIcon field="totalAmount" /> <SortIcon field="totalAmount" />
</button> </button>
</TableHead> </TableHead>

View File

@@ -1,239 +0,0 @@
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/Components/ui/dialog";
import { Badge } from "@/Components/ui/badge";
import { ScrollArea } from "@/Components/ui/scroll-area";
import { User, Clock, Package, Activity as ActivityIcon } from "lucide-react";
interface Activity {
id: number;
description: string;
subject_type: string;
event: string;
causer: string;
created_at: string;
properties: {
attributes?: Record<string, any>;
old?: Record<string, any>;
};
}
interface Props {
open: boolean;
onOpenChange: (open: boolean) => void;
activity: Activity | null;
}
// Field translation map
const fieldLabels: Record<string, string> = {
name: '名稱',
code: '代碼',
description: '描述',
price: '價格',
cost: '成本',
stock: '庫存',
category_id: '分類',
unit_id: '單位',
is_active: '啟用狀態',
conversion_rate: '換算率',
specification: '規格',
brand: '品牌',
base_unit_id: '基本單位',
large_unit_id: '大單位',
purchase_unit_id: '採購單位',
email: 'Email',
password: '密碼',
phone: '電話',
address: '地址',
role_id: '角色',
// Snapshot fields
category_name: '分類名稱',
base_unit_name: '基本單位名稱',
large_unit_name: '大單位名稱',
purchase_unit_name: '採購單位名稱',
// Warehouse & Inventory fields
warehouse_name: '倉庫名稱',
product_name: '商品名稱',
warehouse_id: '倉庫',
product_id: '商品',
quantity: '數量',
safety_stock: '安全庫存',
location: '儲位',
};
export default function ActivityDetailDialog({ open, onOpenChange, activity }: Props) {
if (!activity) return null;
const attributes = activity.properties?.attributes || {};
const old = activity.properties?.old || {};
// Get all keys from both attributes and old to ensure we show all changes
const allKeys = Array.from(new Set([...Object.keys(attributes), ...Object.keys(old)]));
// Filter out internal keys often logged but not useful for users
const filteredKeys = allKeys.filter(key =>
!['created_at', 'updated_at', 'deleted_at', 'id'].includes(key)
);
const getEventBadgeClass = (event: string) => {
switch (event) {
case 'created': return 'bg-green-100 text-green-700 hover:bg-green-200 border-green-200';
case 'updated': return 'bg-blue-100 text-blue-700 hover:bg-blue-200 border-blue-200';
case 'deleted': return 'bg-red-100 text-red-700 hover:bg-red-200 border-red-200';
default: return 'bg-gray-100 text-gray-700 hover:bg-gray-200 border-gray-200';
}
};
const getEventLabel = (event: string) => {
switch (event) {
case 'created': return '新增';
case 'updated': return '更新';
case 'deleted': return '刪除';
default: return event;
}
};
const formatValue = (key: string, value: any) => {
if (value === null || value === undefined) return <span className="text-gray-400">-</span>;
// Special handling for boolean values based on key
if (typeof value === 'boolean') {
if (key === 'is_active') return value ? '啟用' : '停用';
return value ? '是' : '否';
}
if (typeof value === 'object') return JSON.stringify(value);
return String(value);
};
const getFieldName = (key: string) => {
return fieldLabels[key] || key.charAt(0).toUpperCase() + key.slice(1).replace(/_/g, ' ');
};
// Helper to check if a key is a snapshot name field
const isSnapshotField = (key: string) => {
return ['category_name', 'base_unit_name', 'large_unit_name', 'purchase_unit_name', 'warehouse_name', 'product_name'].includes(key);
};
// Helper to get formatted value (merging ID and Name if available)
const getFormattedValue = (key: string, value: any, allData: Record<string, any>) => {
// If it's an ID field, check if we have a corresponding name snapshot
if (key.endsWith('_id')) {
const nameKey = key.replace('_id', '_name');
const nameValue = allData[nameKey];
if (nameValue) {
return `${nameValue}`;
}
}
return formatValue(key, value);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl">
<DialogHeader className="border-b pb-4">
<DialogTitle className="flex items-center gap-3">
<span className="text-xl font-bold text-gray-900"></span>
<Badge variant="outline" className={`text-sm px-3 py-1 ${getEventBadgeClass(activity.event)}`}>
{getEventLabel(activity.event)}
</Badge>
</DialogTitle>
{/* Modern Metadata Strip */}
<div className="flex flex-wrap items-center gap-6 pt-4 text-sm text-gray-500">
<div className="flex items-center gap-2">
<User className="w-4 h-4 text-gray-400" />
<span className="font-medium text-gray-700">{activity.causer}</span>
</div>
<div className="flex items-center gap-2">
<Clock className="w-4 h-4 text-gray-400" />
<span>{activity.created_at}</span>
</div>
<div className="flex items-center gap-2">
<Package className="w-4 h-4 text-gray-400" />
<span>{activity.subject_type}</span>
</div>
{/* Only show 'description' if it differs from event name (unlikely but safe) */}
{activity.description !== getEventLabel(activity.event) &&
activity.description !== 'created' && activity.description !== 'updated' && (
<div className="flex items-center gap-2">
<ActivityIcon className="w-4 h-4 text-gray-400" />
<span>{activity.description}</span>
</div>
)}
</div>
</DialogHeader>
<div className="py-4">
{activity.event === 'created' ? (
<div className="border rounded-md overflow-hidden bg-white">
<div className="grid grid-cols-2 bg-gray-50/80 px-4 py-2 text-xs font-semibold text-gray-500 uppercase tracking-wider border-b">
<div></div>
<div></div>
</div>
<ScrollArea className="h-[300px]">
<div className="divide-y divide-gray-100">
{filteredKeys
.filter(key => attributes[key] !== null && attributes[key] !== '' && !isSnapshotField(key))
.map((key) => (
<div key={key} className="grid grid-cols-2 px-4 py-3 text-sm hover:bg-gray-50/50 transition-colors">
<div className="font-medium text-gray-700">{getFieldName(key)}</div>
<div className="text-gray-900 font-medium">
{getFormattedValue(key, attributes[key], attributes)}
</div>
</div>
))}
{filteredKeys.filter(key => attributes[key] !== null && attributes[key] !== '' && !isSnapshotField(key)).length === 0 && (
<div className="p-8 text-center text-gray-500 text-sm">
</div>
)}
</div>
</ScrollArea>
</div>
) : (
<div className="border rounded-md overflow-hidden bg-white">
<div className="grid grid-cols-3 bg-gray-50/80 px-4 py-2 text-xs font-semibold text-gray-500 uppercase tracking-wider border-b">
<div></div>
<div></div>
<div></div>
</div>
<ScrollArea className="h-[300px]">
{filteredKeys.some(key => !isSnapshotField(key)) ? (
<div className="divide-y divide-gray-100">
{filteredKeys
.filter(key => !isSnapshotField(key))
.map((key) => {
const oldValue = old[key];
const newValue = attributes[key];
const isChanged = JSON.stringify(oldValue) !== JSON.stringify(newValue);
return (
<div key={key} className={`grid grid-cols-3 px-4 py-3 text-sm transition-colors ${isChanged ? 'bg-amber-50/50' : 'hover:bg-gray-50/50'}`}>
<div className="font-medium text-gray-700 flex items-center">{getFieldName(key)}</div>
<div className="text-gray-500 break-words pr-4">
{getFormattedValue(key, oldValue, old)}
</div>
<div className="text-gray-900 font-medium break-words">
{activity.event === 'deleted' ? '-' : getFormattedValue(key, newValue, attributes)}
</div>
</div>
);
})}
</div>
) : (
<div className="p-8 text-center text-gray-500 text-sm">
</div>
)}
</ScrollArea>
</div>
)}
</div>
</DialogContent>
</Dialog>
);
}

View File

@@ -2,30 +2,11 @@ import { useState } from 'react';
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout'; import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, router } from '@inertiajs/react'; import { Head, router } from '@inertiajs/react';
import { PageProps } from '@/types/global'; import { PageProps } from '@/types/global';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/Components/ui/table";
import { Badge } from "@/Components/ui/badge";
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, Eye, ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-react'; import { FileText } from 'lucide-react';
import { Button } from '@/Components/ui/button'; import LogTable, { Activity } from '@/Components/ActivityLog/LogTable';
import ActivityDetailDialog from './ActivityDetailDialog'; import ActivityDetailDialog from '@/Components/ActivityLog/ActivityDetailDialog';
interface Activity {
id: number;
description: string;
subject_type: string;
event: string;
causer: string;
created_at: string;
properties: any;
}
interface PaginationLinks { interface PaginationLinks {
url: string | null; url: string | null;
@@ -54,82 +35,6 @@ export default function ActivityLogIndex({ activities, filters }: Props) {
const [selectedActivity, setSelectedActivity] = useState<Activity | null>(null); const [selectedActivity, setSelectedActivity] = useState<Activity | null>(null);
const [detailOpen, setDetailOpen] = useState(false); const [detailOpen, setDetailOpen] = useState(false);
const getEventBadgeClass = (event: string) => {
switch (event) {
case 'created': return 'bg-green-50 text-green-700 border-green-200 hover:bg-green-100';
case 'updated': return 'bg-blue-50 text-blue-700 border-blue-200 hover:bg-blue-100';
case 'deleted': return 'bg-red-50 text-red-700 border-red-200 hover:bg-red-100';
default: return 'bg-gray-50 text-gray-700 border-gray-200 hover:bg-gray-100';
}
};
const getEventLabel = (event: string) => {
switch (event) {
case 'created': return '新增';
case 'updated': return '更新';
case 'deleted': return '刪除';
default: return event;
}
};
const getDescription = (activity: Activity) => {
const props = activity.properties || {};
const attrs = props.attributes || {};
const old = props.old || {};
// Try to find a name in attributes or old values
// Priority: specific name fields > generic name > code > ID
const nameParams = ['product_name', 'warehouse_name', 'category_name', 'base_unit_name', 'name', 'code', 'title'];
let subjectName = '';
// Special handling for Inventory: show "Warehouse - Product"
if (attrs.warehouse_name && attrs.product_name) {
subjectName = `${attrs.warehouse_name} - ${attrs.product_name}`;
} else if (old.warehouse_name && old.product_name) {
subjectName = `${old.warehouse_name} - ${old.product_name}`;
} else {
// Default fallback
for (const param of nameParams) {
if (attrs[param]) {
subjectName = attrs[param];
break;
}
if (old[param]) {
subjectName = old[param];
break;
}
}
}
// If no name found, try ID but format it nicely if possible, or just don't show it if it's redundant with subject_type
if (!subjectName && (attrs.id || old.id)) {
subjectName = `#${attrs.id || old.id}`;
}
// Combine parts: [Causer] [Action] [Name] [Subject]
// Example: Admin 新增 可樂 商品
// Example: Admin 更新 台北倉 - 可樂 庫存
return (
<span className="flex items-center gap-1.5 flex-wrap">
<span className="font-medium text-gray-900">{activity.causer}</span>
<span className="text-gray-500">{getEventLabel(activity.event)}</span>
{subjectName && (
<span className="font-medium text-primary-600 bg-primary-50 px-1.5 py-0.5 rounded text-xs">
{subjectName}
</span>
)}
<span className="text-gray-700">{activity.subject_type}</span>
{/* Display reason/source if available (e.g., from Replenishment) */}
{(attrs._reason || old._reason) && (
<span className="text-gray-500 text-xs">
( {attrs._reason || old._reason})
</span>
)}
</span>
);
};
const handleViewDetail = (activity: Activity) => { const handleViewDetail = (activity: Activity) => {
setSelectedActivity(activity); setSelectedActivity(activity);
setDetailOpen(true); setDetailOpen(true);
@@ -164,16 +69,6 @@ export default function ActivityLogIndex({ activities, filters }: Props) {
); );
}; };
const SortIcon = ({ field }: { field: string }) => {
if (filters.sort_by !== field) {
return <ArrowUpDown className="h-4 w-4 text-muted-foreground ml-1" />;
}
if (filters.sort_order === "asc") {
return <ArrowUp className="h-4 w-4 text-primary-main ml-1" />;
}
return <ArrowDown className="h-4 w-4 text-primary-main ml-1" />;
};
return ( return (
<AuthenticatedLayout <AuthenticatedLayout
breadcrumbs={[ breadcrumbs={[
@@ -196,75 +91,14 @@ export default function ActivityLogIndex({ activities, filters }: Props) {
</div> </div>
</div> </div>
<div className="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden"> <LogTable
<Table> activities={activities.data}
<TableHeader className="bg-gray-50"> sortField={filters.sort_by}
<TableRow> sortOrder={filters.sort_order}
<TableHead className="w-[50px] text-center">#</TableHead> onSort={handleSort}
<TableHead className="w-[180px]"> onViewDetail={handleViewDetail}
<button from={activities.from}
onClick={() => handleSort('created_at')} />
className="flex items-center gap-1 hover:text-gray-900 transition-colors"
>
<SortIcon field="created_at" />
</button>
</TableHead>
<TableHead className="w-[150px]"></TableHead>
<TableHead></TableHead>
<TableHead className="w-[100px] text-center"></TableHead>
<TableHead></TableHead>
<TableHead className="w-[100px] text-center"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{activities.data.length > 0 ? (
activities.data.map((activity, index) => (
<TableRow key={activity.id}>
<TableCell className="text-gray-500 font-medium text-center">
{activities.from + index}
</TableCell>
<TableCell className="text-gray-500 font-medium whitespace-nowrap">
{activity.created_at}
</TableCell>
<TableCell>
<span className="font-medium text-gray-900">{activity.causer}</span>
</TableCell>
<TableCell>
{getDescription(activity)}
</TableCell>
<TableCell className="text-center">
<Badge variant="outline" className={getEventBadgeClass(activity.event)}>
{getEventLabel(activity.event)}
</Badge>
</TableCell>
<TableCell>
<Badge variant="outline" className="bg-slate-50 text-slate-600 border-slate-200">
{activity.subject_type}
</Badge>
</TableCell>
<TableCell className="text-center">
<Button
variant="outline"
size="sm"
onClick={() => handleViewDetail(activity)}
className="button-outlined-primary"
title="檢視詳情"
>
<Eye className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={6} className="text-center py-8 text-gray-500">
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</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-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">

View File

@@ -3,6 +3,7 @@
*/ */
import { ArrowLeft, Plus, Info, ShoppingCart } from "lucide-react"; import { ArrowLeft, Plus, Info, ShoppingCart } from "lucide-react";
import { useEffect } from "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 { Textarea } from "@/Components/ui/textarea"; import { Textarea } from "@/Components/ui/textarea";
@@ -58,11 +59,23 @@ export default function CreatePurchaseOrder({
setInvoiceNumber, setInvoiceNumber,
setInvoiceDate, setInvoiceDate,
setInvoiceAmount, setInvoiceAmount,
taxAmount,
setTaxAmount,
isTaxManual,
setIsTaxManual,
} = usePurchaseOrderForm({ order, suppliers }); } = usePurchaseOrderForm({ order, suppliers });
const totalAmount = calculateTotalAmount(items); const totalAmount = calculateTotalAmount(items);
// Auto-calculate tax if not manual
useEffect(() => {
if (!isTaxManual) {
const calculatedTax = Math.round(totalAmount * 0.05);
setTaxAmount(calculatedTax);
}
}, [totalAmount, isTaxManual]);
const handleSave = () => { const handleSave = () => {
if (!warehouseId) { if (!warehouseId) {
toast.error("請選擇入庫倉庫"); toast.error("請選擇入庫倉庫");
@@ -113,6 +126,7 @@ export default function CreatePurchaseOrder({
invoice_number: invoiceNumber || null, invoice_number: invoiceNumber || null,
invoice_date: invoiceDate || null, invoice_date: invoiceDate || null,
invoice_amount: invoiceAmount ? parseFloat(invoiceAmount) : null, invoice_amount: invoiceAmount ? parseFloat(invoiceAmount) : null,
tax_amount: Number(taxAmount) || 0,
items: validItems.map(item => ({ items: validItems.map(item => ({
productId: item.productId, productId: item.productId,
quantity: item.quantity, quantity: item.quantity,
@@ -159,20 +173,20 @@ export default function CreatePurchaseOrder({
return ( return (
<AuthenticatedLayout breadcrumbs={order ? getEditBreadcrumbs("purchaseOrders") : getCreateBreadcrumbs("purchaseOrders")}> <AuthenticatedLayout breadcrumbs={order ? getEditBreadcrumbs("purchaseOrders") : getCreateBreadcrumbs("purchaseOrders")}>
<Head title={order ? "編輯採購單" : "建立採購單"} /> <Head title={order ? "編輯採購單" : "建立採購單"} />
<div className="container mx-auto p-6 max-w-5xl"> <div className="container mx-auto p-6 max-w-7xl">
{/* Header */} {/* Header */}
<div className="mb-8"> <div className="mb-6">
<Link href="/purchase-orders"> <Link href="/purchase-orders">
<Button <Button
variant="outline" variant="outline"
className="gap-2 button-outlined-primary mb-6" className="gap-2 button-outlined-primary mb-4"
> >
<ArrowLeft className="h-4 w-4" /> <ArrowLeft className="h-4 w-4" />
</Button> </Button>
</Link> </Link>
<div className="mb-6"> <div className="mb-4">
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2"> <h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<ShoppingCart className="h-6 w-6 text-primary-main" /> <ShoppingCart className="h-6 w-6 text-primary-main" />
{order ? "編輯採購單" : "建立採購單"} {order ? "編輯採購單" : "建立採購單"}
@@ -183,7 +197,7 @@ export default function CreatePurchaseOrder({
</div> </div>
</div> </div>
<div className="space-y-8"> <div className="space-y-6">
{/* 步驟一:基本資訊 */} {/* 步驟一:基本資訊 */}
<div className="bg-white rounded-lg border shadow-sm overflow-hidden"> <div className="bg-white rounded-lg border shadow-sm overflow-hidden">
<div className="p-6 bg-gray-50/50 border-b flex items-center gap-3"> <div className="p-6 bg-gray-50/50 border-b flex items-center gap-3">
@@ -191,7 +205,7 @@ export default function CreatePurchaseOrder({
<h2 className="text-lg font-bold"></h2> <h2 className="text-lg font-bold"></h2>
</div> </div>
<div className="p-8 space-y-8"> <div className="p-6 space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-8"> <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
<div className="space-y-3"> <div className="space-y-3">
<label className="text-sm font-bold text-gray-700"> <label className="text-sm font-bold text-gray-700">
@@ -267,7 +281,7 @@ export default function CreatePurchaseOrder({
<span className="text-sm text-gray-500"></span> <span className="text-sm text-gray-500"></span>
</div> </div>
<div className="p-8 space-y-8"> <div className="p-6 space-y-6">
<div className="grid grid-cols-1 md:grid-cols-3 gap-8"> <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
<div className="space-y-3"> <div className="space-y-3">
<label className="text-sm font-bold text-gray-700"> <label className="text-sm font-bold text-gray-700">
@@ -335,7 +349,7 @@ export default function CreatePurchaseOrder({
</Button> </Button>
</div> </div>
<div className="p-8"> <div className="p-6">
{!hasSupplier && ( {!hasSupplier && (
<Alert className="mb-6 bg-amber-50 border-amber-200 text-amber-800"> <Alert className="mb-6 bg-amber-50 border-amber-200 text-amber-800">
<Info className="h-4 w-4 text-amber-600" /> <Info className="h-4 w-4 text-amber-600" />
@@ -355,10 +369,53 @@ export default function CreatePurchaseOrder({
/> />
{hasSupplier && items.length > 0 && ( {hasSupplier && items.length > 0 && (
<div className="mt-8 flex justify-end"> <div className="mt-6 flex justify-end">
<div className="bg-primary/5 px-8 py-5 rounded-xl border border-primary/10 inline-flex flex-col items-end min-w-[240px]"> <div className="w-full max-w-sm bg-primary/5 px-6 py-4 rounded-xl border border-primary/10 flex flex-col gap-3">
<span className="text-sm text-gray-500 font-medium mb-1"></span> <div className="flex justify-between items-center w-full">
<span className="text-3xl font-black text-primary">{formatCurrency(totalAmount)}</span> <span className="text-sm text-gray-500 font-medium"></span>
<span className="text-lg font-bold text-gray-700">{formatCurrency(totalAmount)}</span>
</div>
<div className="flex justify-between items-center w-full gap-4">
<div className="flex items-center gap-2">
<span className="text-sm text-gray-500 font-medium"> (5%)</span>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 text-gray-400 hover:text-primary"
title="重設為自動計算 (5%)"
onClick={() => {
const autoTax = Math.round(totalAmount * 0.05);
setTaxAmount(autoTax);
setIsTaxManual(false);
toast.success("已重設為自動計算 (5%)");
}}
>
</Button>
</div>
<div className="relative w-32">
<Input
type="number"
value={taxAmount}
onChange={(e) => {
setTaxAmount(e.target.value);
setIsTaxManual(true);
}}
className="text-right h-9 bg-white"
placeholder="0"
/>
</div>
</div>
<div className="h-px bg-primary/10 w-full my-1"></div>
<div className="flex justify-between items-end w-full">
<span className="text-sm text-gray-500 font-medium mb-1"> ()</span>
<span className="text-2xl font-black text-primary">
{formatCurrency(totalAmount + (Number(taxAmount) || 0))}
</span>
</div>
</div> </div>
</div> </div>
)} )}
@@ -367,9 +424,9 @@ export default function CreatePurchaseOrder({
</div> </div>
{/* 底部按鈕 */} {/* 底部按鈕 */}
<div className="flex items-center justify-end gap-4 py-8 border-t border-gray-100 mt-8"> <div className="flex items-center justify-end gap-4 py-6 border-t border-gray-100 mt-6">
<Link href="/purchase-orders"> <Link href="/purchase-orders">
<Button variant="ghost" className="h-12 px-8 text-gray-500 hover:text-gray-700"> <Button variant="ghost" className="h-11 px-6 text-gray-500 hover:text-gray-700">
</Button> </Button>
</Link> </Link>

View File

@@ -143,11 +143,21 @@ export default function ViewPurchaseOrderPage({ order }: Props) {
items={order.items} items={order.items}
isReadOnly={true} isReadOnly={true}
/> />
<div className="mt-4 flex justify-end items-center gap-4 border-t pt-4"> <div className="mt-4 flex flex-col items-end gap-2 border-t pt-4">
<span className="text-gray-600 font-medium"></span> <div className="flex items-center gap-8 text-gray-600">
<span className="text-xl font-bold text-primary"> <span className="font-medium"></span>
{formatCurrency(order.totalAmount)} <span>{formatCurrency(order.totalAmount)}</span>
</span> </div>
<div className="flex items-center gap-8 text-gray-600">
<span className="font-medium"></span>
<span>{formatCurrency(order.tax_amount || 0)}</span>
</div>
<div className="flex items-center gap-8 pt-2 mt-2 border-t border-gray-100">
<span className="font-bold text-lg"></span>
<span className="text-xl font-bold text-primary">
{formatCurrency(order.grand_total || (order.totalAmount + (order.tax_amount || 0)))}
</span>
</div>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -12,28 +12,40 @@ interface UsePurchaseOrderFormProps {
} }
export function usePurchaseOrderForm({ order, suppliers }: UsePurchaseOrderFormProps) { export function usePurchaseOrderForm({ order, suppliers }: UsePurchaseOrderFormProps) {
const [supplierId, setSupplierId] = useState(""); const [supplierId, setSupplierId] = useState(order?.supplierId || "");
const [expectedDate, setExpectedDate] = useState(""); const [expectedDate, setExpectedDate] = useState(order?.expectedDate || "");
const [items, setItems] = useState<PurchaseOrderItem[]>([]); const [items, setItems] = useState<PurchaseOrderItem[]>(order?.items || []);
const [notes, setNotes] = useState(""); const [notes, setNotes] = useState(order?.remark || "");
const [status, setStatus] = useState<PurchaseOrderStatus>("draft"); const [status, setStatus] = useState<PurchaseOrderStatus>(order?.status || "draft");
const [warehouseId, setWarehouseId] = useState<string | number>(""); const [warehouseId, setWarehouseId] = useState<string | number>(order?.warehouse_id || "");
const [invoiceNumber, setInvoiceNumber] = useState(""); const [invoiceNumber, setInvoiceNumber] = useState(order?.invoiceNumber || "");
const [invoiceDate, setInvoiceDate] = useState(""); const [invoiceDate, setInvoiceDate] = useState(order?.invoiceDate || "");
const [invoiceAmount, setInvoiceAmount] = useState(""); const [invoiceAmount, setInvoiceAmount] = useState(order?.invoiceAmount ? String(order.invoiceAmount) : "");
const [taxAmount, setTaxAmount] = useState<string | number>(
order?.taxAmount !== undefined && order.taxAmount !== null ? order.taxAmount :
(order?.tax_amount !== undefined && order.tax_amount !== null ? order.tax_amount : "")
);
const [isTaxManual, setIsTaxManual] = useState(!!(order?.taxAmount !== undefined || order?.tax_amount !== undefined));
// 載入編輯訂單資料 // 同步外部傳入的 order 更新 (例如重新執行 edit 路由)
useEffect(() => { useEffect(() => {
if (order) { if (order) {
setSupplierId(order.supplierId); setSupplierId(order.supplierId);
setExpectedDate(order.expectedDate); setExpectedDate(order.expectedDate);
setItems(order.items); setItems(order.items || []);
setNotes(order.remark || ""); setNotes(order.remark || "");
setStatus(order.status); setStatus(order.status);
setWarehouseId(order.warehouse_id || ""); setWarehouseId(order.warehouse_id || "");
setInvoiceNumber(order.invoiceNumber || ""); setInvoiceNumber(order.invoiceNumber || "");
setInvoiceDate(order.invoiceDate || ""); setInvoiceDate(order.invoiceDate || "");
setInvoiceAmount(order.invoiceAmount ? String(order.invoiceAmount) : ""); setInvoiceAmount(order.invoiceAmount ? String(order.invoiceAmount) : "");
const val = order.taxAmount !== undefined && order.taxAmount !== null ? order.taxAmount :
(order.tax_amount !== undefined && order.tax_amount !== null ? order.tax_amount : "");
setTaxAmount(val);
if (val !== "") {
setIsTaxManual(true);
}
} }
}, [order]); }, [order]);
@@ -47,6 +59,8 @@ export function usePurchaseOrderForm({ order, suppliers }: UsePurchaseOrderFormP
setInvoiceNumber(""); setInvoiceNumber("");
setInvoiceDate(""); setInvoiceDate("");
setInvoiceAmount(""); setInvoiceAmount("");
setTaxAmount("");
setIsTaxManual(false);
}; };
const selectedSupplier = suppliers.find((s) => String(s.id) === String(supplierId)); const selectedSupplier = suppliers.find((s) => String(s.id) === String(supplierId));
@@ -154,6 +168,8 @@ export function usePurchaseOrderForm({ order, suppliers }: UsePurchaseOrderFormP
invoiceNumber, invoiceNumber,
invoiceDate, invoiceDate,
invoiceAmount, invoiceAmount,
taxAmount,
isTaxManual,
// Setters // Setters
setSupplierId, setSupplierId,
@@ -164,6 +180,8 @@ export function usePurchaseOrderForm({ order, suppliers }: UsePurchaseOrderFormP
setInvoiceNumber, setInvoiceNumber,
setInvoiceDate, setInvoiceDate,
setInvoiceAmount, setInvoiceAmount,
setTaxAmount,
setIsTaxManual,
// Methods // Methods
addItem, addItem,

View File

@@ -81,6 +81,10 @@ export interface PurchaseOrder {
invoiceNumber?: string; // 發票號碼 invoiceNumber?: string; // 發票號碼
invoiceDate?: string; // 發票日期 invoiceDate?: string; // 發票日期
invoiceAmount?: number; // 發票金額 invoiceAmount?: number; // 發票金額
tax_amount?: number; // 稅額 (DB column)
taxAmount?: number; // 稅額 (Accessor)
grand_total?: number; // 總計 (含稅) (DB column)
grandTotal?: number; // 總計 (含稅) (Accessor)
} }
export interface CommonProduct { export interface CommonProduct {