生產工單BOM以及批號完善
All checks were successful
Koori-ERP-Deploy-System / deploy-demo (push) Successful in 57s
Koori-ERP-Deploy-System / deploy-production (push) Has been skipped

This commit is contained in:
2026-01-22 15:39:35 +08:00
parent 1ae21febb5
commit 1d134c9ad8
31 changed files with 2684 additions and 694 deletions

View File

@@ -7,8 +7,10 @@ use App\Models\Vendor;
use App\Models\PurchaseOrder;
use App\Models\Warehouse;
use App\Models\Inventory;
use App\Models\WarehouseProductSafetyStock;
use Inertia\Inertia;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class DashboardController extends Controller
{
@@ -21,15 +23,25 @@ class DashboardController extends Controller
return redirect()->route('landlord.dashboard');
}
// 計算低庫存數量:各商品在各倉庫的總量 < 安全庫存
$lowStockCount = DB::table('warehouse_product_safety_stocks as ss')
->join(DB::raw('(SELECT warehouse_id, product_id, SUM(quantity) as total_qty FROM inventories WHERE deleted_at IS NULL GROUP BY warehouse_id, product_id) as inv'),
function ($join) {
$join->on('ss.warehouse_id', '=', 'inv.warehouse_id')
->on('ss.product_id', '=', 'inv.product_id');
})
->whereRaw('inv.total_qty <= ss.safety_stock')
->count();
$stats = [
'productsCount' => Product::count(),
'vendorsCount' => Vendor::count(),
'purchaseOrdersCount' => PurchaseOrder::count(),
'warehousesCount' => Warehouse::count(),
'totalInventoryValue' => Inventory::join('products', 'inventories.product_id', '=', 'products.id')
->sum('inventories.quantity'), // Simplified, maybe just sum quantities for now
->sum('inventories.quantity'),
'pendingOrdersCount' => PurchaseOrder::where('status', 'pending')->count(),
'lowStockCount' => Inventory::whereColumn('quantity', '<=', 'safety_stock')->count(),
'lowStockCount' => $lowStockCount,
];
return Inertia::render('Dashboard', [

View File

@@ -3,6 +3,7 @@
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\WarehouseProductSafetyStock;
class InventoryController extends Controller
{
@@ -19,16 +20,46 @@ class InventoryController extends Controller
// 1. 準備 availableProducts
$availableProducts = $allProducts->map(function ($product) {
return [
'id' => (string) $product->id, // Frontend expects string
'id' => (string) $product->id,
'name' => $product->name,
'type' => $product->category?->name ?? '其他', // 暫時用 Category Name 當 Type
'type' => $product->category?->name ?? '其他',
];
});
// 2. 準備 inventories (模擬批號)
// 2. 準備 inventories
// 資料庫結構為 (warehouse_id, product_id) 唯一,故為扁平列表
$inventories = $warehouse->inventories->map(function ($inv) {
// 2. 從新表格讀取安全庫存設定 (商品-倉庫層級)
$safetyStockMap = WarehouseProductSafetyStock::where('warehouse_id', $warehouse->id)
->pluck('safety_stock', 'product_id')
->mapWithKeys(fn($val, $key) => [(string)$key => (float)$val]);
// 3. 準備 inventories (批號分組)
$items = $warehouse->inventories()
->with(['product.baseUnit', 'lastIncomingTransaction', 'lastOutgoingTransaction'])
->get();
$inventories = $items->groupBy('product_id')->map(function ($batchItems) use ($safetyStockMap) {
$firstItem = $batchItems->first();
$product = $firstItem->product;
$totalQuantity = $batchItems->sum('quantity');
// 從獨立表格讀取安全庫存
$safetyStock = $safetyStockMap[(string)$firstItem->product_id] ?? null;
// 計算狀態
$status = '正常';
if (!is_null($safetyStock)) {
if ($totalQuantity < $safetyStock) {
$status = '低於';
}
}
return [
'productId' => (string) $firstItem->product_id,
'productName' => $product?->name ?? '未知商品',
'productCode' => $product?->code ?? 'N/A',
'baseUnit' => $product?->baseUnit?->name ?? '個',
'totalQuantity' => (float) $totalQuantity,
'safetyStock' => $safetyStock,
'status' => $status,
'batches' => $batchItems->map(function ($inv) {
return [
'id' => (string) $inv->id,
'warehouseId' => (string) $inv->warehouse_id,
@@ -37,31 +68,34 @@ class InventoryController extends Controller
'productCode' => $inv->product?->code ?? 'N/A',
'unit' => $inv->product?->baseUnit?->name ?? '個',
'quantity' => (float) $inv->quantity,
'safetyStock' => $inv->safety_stock !== null ? (float) $inv->safety_stock : null,
'status' => '正常', // 前端會根據 quantity 與 safetyStock 重算,但後端亦可提供基礎狀態
'batchNumber' => $inv->batch_number ?? 'BATCH-' . $inv->id, // 優先使用 DB 批號,若無則 fallback
'safetyStock' => null, // 批號層級不再有安全庫存
'status' => '正常',
'batchNumber' => $inv->batch_number ?? 'BATCH-' . $inv->id,
'expiryDate' => $inv->expiry_date ? $inv->expiry_date->format('Y-m-d') : null,
'lastInboundDate' => $inv->lastIncomingTransaction ? ($inv->lastIncomingTransaction->actual_time ? $inv->lastIncomingTransaction->actual_time->format('Y-m-d') : $inv->lastIncomingTransaction->created_at->format('Y-m-d')) : null,
'lastOutboundDate' => $inv->lastOutgoingTransaction ? ($inv->lastOutgoingTransaction->actual_time ? $inv->lastOutgoingTransaction->actual_time->format('Y-m-d') : $inv->lastOutgoingTransaction->created_at->format('Y-m-d')) : null,
];
});
// 3. 準備 safetyStockSettings
$safetyStockSettings = $warehouse->inventories->filter(function($inv) {
return !is_null($inv->safety_stock);
})->map(function ($inv) {
return [
'id' => 'ss-' . $inv->id,
'warehouseId' => (string) $inv->warehouse_id,
'productId' => (string) $inv->product_id,
'productName' => $inv->product?->name ?? '未知商品',
'productType' => $inv->product?->category?->name ?? '其他',
'safetyStock' => (float) $inv->safety_stock,
'createdAt' => $inv->created_at->toIso8601String(),
'updatedAt' => $inv->updated_at->toIso8601String(),
})->values(),
];
})->values();
// 4. 準備 safetyStockSettings (從新表格讀取)
$safetyStockSettings = WarehouseProductSafetyStock::where('warehouse_id', $warehouse->id)
->with(['product.category'])
->get()
->map(function ($setting) {
return [
'id' => (string) $setting->id,
'warehouseId' => (string) $setting->warehouse_id,
'productId' => (string) $setting->product_id,
'productName' => $setting->product?->name ?? '未知商品',
'productType' => $setting->product?->category?->name ?? '其他',
'safetyStock' => (float) $setting->safety_stock,
'createdAt' => $setting->created_at->toIso8601String(),
'updatedAt' => $setting->updated_at->toIso8601String(),
];
});
return \Inertia\Inertia::render('Warehouse/Inventory', [
'warehouse' => $warehouse,
'inventories' => $inventories,
@@ -73,10 +107,14 @@ class InventoryController extends Controller
public function create(\App\Models\Warehouse $warehouse)
{
// 取得所有商品供前端選單使用
$products = \App\Models\Product::with(['baseUnit', 'largeUnit'])->select('id', 'name', 'base_unit_id', 'large_unit_id', 'conversion_rate')->get()->map(function ($product) {
$products = \App\Models\Product::with(['baseUnit', 'largeUnit'])
->select('id', 'name', 'code', 'base_unit_id', 'large_unit_id', 'conversion_rate')
->get()
->map(function ($product) {
return [
'id' => (string) $product->id,
'name' => $product->name,
'code' => $product->code,
'baseUnit' => $product->baseUnit?->name ?? '個',
'largeUnit' => $product->largeUnit?->name, // 可能為 null
'conversionRate' => (float) $product->conversion_rate,
@@ -98,45 +136,55 @@ class InventoryController extends Controller
'items' => 'required|array|min:1',
'items.*.productId' => 'required|exists:products,id',
'items.*.quantity' => 'required|numeric|min:0.01',
'items.*.batchNumber' => 'nullable|string',
'items.*.batchMode' => 'required|in:existing,new',
'items.*.inventoryId' => 'required_if:items.*.batchMode,existing|nullable|exists:inventories,id',
'items.*.originCountry' => 'required_if:items.*.batchMode,new|nullable|string|max:2',
'items.*.expiryDate' => 'nullable|date',
]);
return \Illuminate\Support\Facades\DB::transaction(function () use ($validated, $warehouse) {
foreach ($validated['items'] as $item) {
$batchNumber = $item['batchNumber'] ?? null;
// 如果未提供批號,且系統設定需要批號,則自動產生 (這裡先保留彈性,若無則為 null 或預設)
if (empty($batchNumber)) {
// 嘗試自動產生:需要 product_code, country, date
$inventory = null;
if ($item['batchMode'] === 'existing') {
// 模式 A選擇現有批號 (包含已刪除的也要能找回來累加)
$inventory = \App\Models\Inventory::withTrashed()->findOrFail($item['inventoryId']);
if ($inventory->trashed()) {
$inventory->restore();
}
} else {
// 模式 B建立新批號
$originCountry = $item['originCountry'] ?? 'TW';
$product = \App\Models\Product::find($item['productId']);
if ($product) {
$batchNumber = \App\Models\Inventory::generateBatchNumber(
$product->code ?? 'UNK',
'TW', // 預設來源
$originCountry,
$validated['inboundDate']
);
}
}
// 取得或建立庫存紀錄 (加入批號判斷)
$inventory = $warehouse->inventories()->firstOrNew(
// 同樣要檢查此批號是否已經存在 (即使模式是 new, 但可能撞到同一天同產地手動建立的)
$inventory = $warehouse->inventories()->withTrashed()->firstOrNew(
[
'product_id' => $item['productId'],
'batch_number' => $batchNumber
],
[
'quantity' => 0,
'safety_stock' => null,
'arrival_date' => $validated['inboundDate'],
'expiry_date' => $item['expiryDate'] ?? null,
'origin_country' => 'TW', // 預設
'origin_country' => $originCountry,
]
);
if ($inventory->trashed()) {
$inventory->restore();
}
}
$currentQty = $inventory->quantity;
$newQty = $currentQty + $item['quantity'];
// 更新庫存並儲存 (新紀錄: Created, 舊紀錄: Updated)
$inventory->quantity = $newQty;
$inventory->save();
@@ -157,7 +205,46 @@ class InventoryController extends Controller
});
}
public function edit(\App\Models\Warehouse $warehouse, $inventoryId)
/**
* API: 取得商品在特定倉庫的所有批號,並回傳當前日期/產地下的一個流水號
*/
public function getBatches(\App\Models\Warehouse $warehouse, $productId, \Illuminate\Http\Request $request)
{
$originCountry = $request->query('originCountry', 'TW');
$arrivalDate = $request->query('arrivalDate', now()->format('Y-m-d'));
$batches = \App\Models\Inventory::where('warehouse_id', $warehouse->id)
->where('product_id', $productId)
->get()
->map(function ($inventory) {
return [
'inventoryId' => (string) $inventory->id,
'batchNumber' => $inventory->batch_number,
'originCountry' => $inventory->origin_country,
'expiryDate' => $inventory->expiry_date ? $inventory->expiry_date->format('Y-m-d') : null,
'quantity' => (float) $inventory->quantity,
];
});
// 計算下一個流水號
$product = \App\Models\Product::find($productId);
$nextSequence = '01';
if ($product) {
$batchNumber = \App\Models\Inventory::generateBatchNumber(
$product->code ?? 'UNK',
$originCountry,
$arrivalDate
);
$nextSequence = substr($batchNumber, -2);
}
return response()->json([
'batches' => $batches,
'nextSequence' => $nextSequence
]);
}
public function edit(\Illuminate\Http\Request $request, \App\Models\Warehouse $warehouse, $inventoryId)
{
// 取得庫存紀錄,包含商品資訊與異動紀錄 (含經手人)
// 這裡如果是 Mock 的 ID (mock-inv-1),需要特殊處理
@@ -176,8 +263,8 @@ class InventoryController extends Controller
'productId' => (string) $inventory->product_id,
'productName' => $inventory->product?->name ?? '未知商品',
'quantity' => (float) $inventory->quantity,
'batchNumber' => 'BATCH-' . $inventory->id, // Mock
'expiryDate' => '2099-12-31', // Mock
'batchNumber' => $inventory->batch_number ?? '-',
'expiryDate' => $inventory->expiry_date ?? null,
'lastInboundDate' => $inventory->updated_at->format('Y-m-d'),
'lastOutboundDate' => null,
];
@@ -234,19 +321,21 @@ class InventoryController extends Controller
]);
return \Illuminate\Support\Facades\DB::transaction(function () use ($validated, $inventory) {
$currentQty = $inventory->quantity;
$newQty = $validated['quantity'];
$currentQty = (float) $inventory->quantity;
$newQty = (float) $validated['quantity'];
// 判斷操作模式
if (isset($validated['operation'])) {
// 判斷是否來自調整彈窗 (包含 operation 參數)
$isAdjustment = isset($validated['operation']);
$changeQty = 0;
if ($isAdjustment) {
switch ($validated['operation']) {
case 'add':
$changeQty = $validated['quantity'];
$changeQty = (float) $validated['quantity'];
$newQty = $currentQty + $changeQty;
break;
case 'subtract':
$changeQty = -$validated['quantity'];
$changeQty = -(float) $validated['quantity'];
$newQty = $currentQty + $changeQty;
break;
case 'set':
@@ -262,8 +351,9 @@ class InventoryController extends Controller
$inventory->update(['quantity' => $newQty]);
// 異動類型映射
$type = $validated['type'] ?? 'adjustment';
$type = $validated['type'] ?? ($isAdjustment ? 'manual_adjustment' : 'adjustment');
$typeMapping = [
'manual_adjustment' => '手動調整庫存',
'adjustment' => '盤點調整',
'purchase_in' => '採購進貨',
'sales_out' => '銷售出庫',
@@ -274,22 +364,26 @@ class InventoryController extends Controller
];
$chineseType = $typeMapping[$type] ?? $type;
// 如果是編輯頁面來的,可能沒有 type設為 "盤點調整" 或 "手動編輯"
if (!isset($validated['type'])) {
// 如果是編輯頁面來的,且沒傳 type設為手動編輯
if (!$isAdjustment && !isset($validated['type'])) {
$chineseType = '手動編輯';
}
// 整理原因
$reason = $validated['reason'] ?? ($isAdjustment ? '手動庫存調整' : '編輯頁面更新');
if (isset($validated['notes'])) {
$reason .= ' - ' . $validated['notes'];
}
// 寫入異動紀錄
// 如果數量沒變,是否要寫紀錄?通常編輯頁面按儲存可能只改了其他欄位(如果有)
// 但因為我們目前只存 quantity如果 quantity 沒變,可以不寫異動,或者寫一筆 0 的異動代表更新屬性
if (abs($changeQty) > 0.0001) {
$inventory->transactions()->create([
'type' => $chineseType,
'quantity' => $changeQty,
'balance_before' => $currentQty,
'balance_after' => $newQty,
'reason' => ($validated['reason'] ?? '編輯頁面更新') . ($validated['notes'] ?? ''),
'actual_time' => now(), // 手動調整設定為當下
'reason' => $reason,
'actual_time' => now(),
'user_id' => auth()->id(),
]);
}
@@ -303,8 +397,13 @@ class InventoryController extends Controller
{
$inventory = \App\Models\Inventory::findOrFail($inventoryId);
// 歸零異動
// 庫存 > 0 不允許刪除 (哪怕是軟刪除)
if ($inventory->quantity > 0) {
return redirect()->back()->with('error', '庫存數量大於 0無法刪除。請先進行出庫或調整。');
}
// 歸零異動 (因為已經限制為 0 才能刪,這段邏輯可以簡化,但為了保險起見,若有微小殘值仍可記錄歸零)
if (abs($inventory->quantity) > 0.0001) {
$inventory->transactions()->create([
'type' => '手動編輯',
'quantity' => -$inventory->quantity,
@@ -322,8 +421,88 @@ class InventoryController extends Controller
->with('success', '庫存品項已刪除');
}
public function history(\App\Models\Warehouse $warehouse, $inventoryId)
public function history(Request $request, \App\Models\Warehouse $warehouse)
{
$inventoryId = $request->query('inventoryId');
$productId = $request->query('productId');
if ($productId) {
// 商品層級查詢
$inventories = \App\Models\Inventory::where('warehouse_id', $warehouse->id)
->where('product_id', $productId)
->with(['product', 'transactions' => function($query) {
$query->orderBy('actual_time', 'desc')->orderBy('id', 'desc');
}, 'transactions.user'])
->get();
if ($inventories->isEmpty()) {
return redirect()->back()->with('error', '找不到該商品的庫存紀錄');
}
$firstInventory = $inventories->first();
$productName = $firstInventory->product?->name ?? '未知商品';
$productCode = $firstInventory->product?->code ?? 'N/A';
$currentTotalQuantity = $inventories->sum('quantity');
// 合併所有批號的交易紀錄
$allTransactions = collect();
foreach ($inventories as $inv) {
foreach ($inv->transactions as $tx) {
$allTransactions->push([
'raw_tx' => $tx,
'batchNumber' => $inv->batch_number ?? '-',
'sort_time' => $tx->actual_time ?? $tx->created_at,
]);
}
}
// 依時間倒序排序 (最新的在前面)
$sortedTransactions = $allTransactions->sort(function ($a, $b) {
// 先比時間 (Desc)
if ($a['sort_time'] != $b['sort_time']) {
return $a['sort_time'] > $b['sort_time'] ? -1 : 1;
}
// 再比 ID (Desc)
return $a['raw_tx']->id > $b['raw_tx']->id ? -1 : 1;
});
// 回推計算結餘
$runningBalance = $currentTotalQuantity;
$transactions = $sortedTransactions->map(function ($item) use (&$runningBalance) {
$tx = $item['raw_tx'];
// 本次異動後的結餘 = 當前推算的結餘
$balanceAfter = $runningBalance;
// 推算前一次的結餘 (減去本次的異動量:如果是入庫+10前一次就是-10)
$runningBalance = $runningBalance - $tx->quantity;
return [
'id' => (string) $tx->id,
'type' => $tx->type,
'quantity' => (float) $tx->quantity,
'balanceAfter' => (float) $balanceAfter, // 使用即時計算的商品總結餘
'reason' => $tx->reason,
'userName' => $tx->user ? $tx->user->name : '系統',
'actualTime' => $tx->actual_time ? $tx->actual_time->format('Y-m-d H:i') : $tx->created_at->format('Y-m-d H:i'),
'batchNumber' => $item['batchNumber'],
];
})->values();
return \Inertia\Inertia::render('Warehouse/InventoryHistory', [
'warehouse' => $warehouse,
'inventory' => [
'id' => 'product-' . $productId,
'productName' => $productName,
'productCode' => $productCode,
'quantity' => (float) $currentTotalQuantity,
],
'transactions' => $transactions
]);
}
if ($inventoryId) {
// 單一批號查詢
$inventory = \App\Models\Inventory::with(['product', 'transactions' => function($query) {
$query->orderBy('actual_time', 'desc')->orderBy('id', 'desc');
}, 'transactions.user'])->findOrFail($inventoryId);
@@ -346,9 +525,13 @@ class InventoryController extends Controller
'id' => (string) $inventory->id,
'productName' => $inventory->product?->name ?? '未知商品',
'productCode' => $inventory->product?->code ?? 'N/A',
'batchNumber' => $inventory->batch_number ?? '-',
'quantity' => (float) $inventory->quantity,
],
'transactions' => $transactions
]);
}
return redirect()->back()->with('error', '未提供查詢參數');
}
}

View File

@@ -73,11 +73,19 @@ class ProductionOrderController extends Controller
*/
public function store(Request $request)
{
$validated = $request->validate([
$status = $request->input('status', 'draft'); // 預設為草稿
// 共用驗證規則
$baseRules = [
'product_id' => 'required|exists:products,id',
'output_batch_number' => 'required|string|max:50',
'status' => 'nullable|in:draft,completed',
];
// 完成模式需要完整驗證
$completedRules = [
'warehouse_id' => 'required|exists:warehouses,id',
'output_quantity' => 'required|numeric|min:0.01',
'output_batch_number' => 'required|string|max:50',
'output_box_count' => 'nullable|string|max:10',
'production_date' => 'required|date',
'expiry_date' => 'nullable|date|after_or_equal:production_date',
@@ -86,48 +94,75 @@ class ProductionOrderController extends Controller
'items.*.inventory_id' => 'required|exists:inventories,id',
'items.*.quantity_used' => 'required|numeric|min:0.0001',
'items.*.unit_id' => 'nullable|exists:units,id',
], [
];
// 草稿模式的寬鬆規則
$draftRules = [
'warehouse_id' => 'nullable|exists:warehouses,id',
'output_quantity' => 'nullable|numeric|min:0',
'output_box_count' => 'nullable|string|max:10',
'production_date' => 'nullable|date',
'expiry_date' => 'nullable|date',
'remark' => 'nullable|string',
'items' => 'nullable|array',
'items.*.inventory_id' => 'nullable|exists:inventories,id',
'items.*.quantity_used' => 'nullable|numeric|min:0',
'items.*.unit_id' => 'nullable|exists:units,id',
];
$rules = $status === 'completed'
? array_merge($baseRules, $completedRules)
: array_merge($baseRules, $draftRules);
$validated = $request->validate($rules, [
'product_id.required' => '請選擇成品商品',
'output_batch_number.required' => '請輸入成品批號',
'warehouse_id.required' => '請選擇入庫倉庫',
'output_quantity.required' => '請輸入生產數量',
'output_batch_number.required' => '請輸入成品批號',
'production_date.required' => '請選擇生產日期',
'items.required' => '請至少新增一項原物料',
'items.min' => '請至少新增一項原物料',
]);
DB::transaction(function () use ($validated, $request) {
DB::transaction(function () use ($validated, $request, $status) {
// 1. 建立生產工單
$productionOrder = ProductionOrder::create([
'code' => ProductionOrder::generateCode(),
'product_id' => $validated['product_id'],
'warehouse_id' => $validated['warehouse_id'],
'output_quantity' => $validated['output_quantity'],
'warehouse_id' => $validated['warehouse_id'] ?? null,
'output_quantity' => $validated['output_quantity'] ?? 0,
'output_batch_number' => $validated['output_batch_number'],
'output_box_count' => $validated['output_box_count'] ?? null,
'production_date' => $validated['production_date'],
'production_date' => $validated['production_date'] ?? now()->toDateString(),
'expiry_date' => $validated['expiry_date'] ?? null,
'user_id' => auth()->id(),
'status' => 'completed',
'status' => $status,
'remark' => $validated['remark'] ?? null,
]);
// 2. 建立明細並扣減原物料庫存
// 2. 建立明細 (草稿與完成模式皆需儲存)
if (!empty($validated['items'])) {
foreach ($validated['items'] as $item) {
if (empty($item['inventory_id'])) continue;
// 建立明細
ProductionOrderItem::create([
'production_order_id' => $productionOrder->id,
'inventory_id' => $item['inventory_id'],
'quantity_used' => $item['quantity_used'],
'quantity_used' => $item['quantity_used'] ?? 0,
'unit_id' => $item['unit_id'] ?? null,
]);
// 扣減原物料庫存
// 若為完成模式,則扣減原物料庫存
if ($status === 'completed') {
$inventory = Inventory::findOrFail($item['inventory_id']);
$inventory->decrement('quantity', $item['quantity_used']);
}
}
}
// 3. 成品入庫:在目標倉庫建立新的庫存紀錄
// 3. 若為完成模式,執行成品入庫
if ($status === 'completed') {
$product = Product::findOrFail($validated['product_id']);
Inventory::create([
'warehouse_id' => $validated['warehouse_id'],
@@ -140,10 +175,15 @@ class ProductionOrderController extends Controller
'expiry_date' => $validated['expiry_date'] ?? null,
'quality_status' => 'normal',
]);
}
});
$message = $status === 'completed'
? '生產單已建立,原物料已扣減,成品已入庫'
: '生產單草稿已儲存';
return redirect()->route('production-orders.index')
->with('success', '生產單已建立,原物料已扣減,成品已入庫');
->with('success', $message);
}
/**
@@ -170,7 +210,7 @@ class ProductionOrderController extends Controller
*/
public function getWarehouseInventories(Warehouse $warehouse)
{
$inventories = Inventory::with(['product.baseUnit'])
$inventories = Inventory::with(['product.baseUnit', 'product.largeUnit'])
->where('warehouse_id', $warehouse->id)
->where('quantity', '>', 0)
->where('quality_status', 'normal')
@@ -188,9 +228,158 @@ class ProductionOrderController extends Controller
'arrival_date' => $inv->arrival_date?->format('Y-m-d'),
'expiry_date' => $inv->expiry_date?->format('Y-m-d'),
'unit_name' => $inv->product->baseUnit?->name,
'base_unit_id' => $inv->product->base_unit_id,
'base_unit_name' => $inv->product->baseUnit?->name,
'large_unit_id' => $inv->product->large_unit_id,
'large_unit_name' => $inv->product->largeUnit?->name,
'conversion_rate' => $inv->product->conversion_rate,
];
});
return response()->json($inventories);
}
/**
* 編輯生產單(僅限草稿狀態)
*/
public function edit(ProductionOrder $productionOrder): Response
{
// 只有草稿可以編輯
if ($productionOrder->status !== 'draft') {
return redirect()->route('production-orders.show', $productionOrder->id)
->with('error', '只有草稿狀態的生產單可以編輯');
}
$productionOrder->load(['product', 'warehouse', 'items.inventory.product', 'items.unit']);
return Inertia::render('Production/Edit', [
'productionOrder' => $productionOrder,
'products' => Product::with(['baseUnit'])->get(),
'warehouses' => Warehouse::all(),
'units' => Unit::all(),
]);
}
/**
* 更新生產單
*/
public function update(Request $request, ProductionOrder $productionOrder)
{
// 只有草稿可以編輯
if ($productionOrder->status !== 'draft') {
return redirect()->route('production-orders.show', $productionOrder->id)
->with('error', '只有草稿狀態的生產單可以編輯');
}
$status = $request->input('status', 'draft');
// 共用驗證規則
$baseRules = [
'product_id' => 'required|exists:products,id',
'output_batch_number' => 'required|string|max:50',
'status' => 'nullable|in:draft,completed',
];
// 完成模式需要完整驗證
$completedRules = [
'warehouse_id' => 'required|exists:warehouses,id',
'output_quantity' => 'required|numeric|min:0.01',
'output_box_count' => 'nullable|string|max:10',
'production_date' => 'required|date',
'expiry_date' => 'nullable|date|after_or_equal:production_date',
'remark' => 'nullable|string',
'items' => 'required|array|min:1',
'items.*.inventory_id' => 'required|exists:inventories,id',
'items.*.quantity_used' => 'required|numeric|min:0.0001',
'items.*.unit_id' => 'nullable|exists:units,id',
];
// 草稿模式的寬鬆規則
$draftRules = [
'warehouse_id' => 'nullable|exists:warehouses,id',
'output_quantity' => 'nullable|numeric|min:0',
'output_box_count' => 'nullable|string|max:10',
'production_date' => 'nullable|date',
'expiry_date' => 'nullable|date',
'remark' => 'nullable|string',
'items' => 'nullable|array',
'items.*.inventory_id' => 'nullable|exists:inventories,id',
'items.*.quantity_used' => 'nullable|numeric|min:0',
'items.*.unit_id' => 'nullable|exists:units,id',
];
$rules = $status === 'completed'
? array_merge($baseRules, $completedRules)
: array_merge($baseRules, $draftRules);
$validated = $request->validate($rules, [
'product_id.required' => '請選擇成品商品',
'output_batch_number.required' => '請輸入成品批號',
'warehouse_id.required' => '請選擇入庫倉庫',
'output_quantity.required' => '請輸入生產數量',
'production_date.required' => '請選擇生產日期',
'items.required' => '請至少新增一項原物料',
'items.min' => '請至少新增一項原物料',
]);
DB::transaction(function () use ($validated, $status, $productionOrder) {
// 更新生產工單基本資料
$productionOrder->update([
'product_id' => $validated['product_id'],
'warehouse_id' => $validated['warehouse_id'] ?? null,
'output_quantity' => $validated['output_quantity'] ?? 0,
'output_batch_number' => $validated['output_batch_number'],
'output_box_count' => $validated['output_box_count'] ?? null,
'production_date' => $validated['production_date'] ?? now()->toDateString(),
'expiry_date' => $validated['expiry_date'] ?? null,
'status' => $status,
'remark' => $validated['remark'] ?? null,
]);
// 刪除舊的明細
$productionOrder->items()->delete();
// 重新建立明細 (草稿與完成模式皆需儲存)
if (!empty($validated['items'])) {
foreach ($validated['items'] as $item) {
if (empty($item['inventory_id'])) continue;
ProductionOrderItem::create([
'production_order_id' => $productionOrder->id,
'inventory_id' => $item['inventory_id'],
'quantity_used' => $item['quantity_used'] ?? 0,
'unit_id' => $item['unit_id'] ?? null,
]);
// 若為完成模式,則扣減原物料庫存
if ($status === 'completed') {
$inventory = Inventory::findOrFail($item['inventory_id']);
$inventory->decrement('quantity', $item['quantity_used']);
}
}
}
// 若為完成模式,執行成品入庫
if ($status === 'completed') {
Inventory::create([
'warehouse_id' => $validated['warehouse_id'],
'product_id' => $validated['product_id'],
'quantity' => $validated['output_quantity'],
'batch_number' => $validated['output_batch_number'],
'box_number' => $validated['output_box_count'],
'origin_country' => 'TW',
'arrival_date' => $validated['production_date'],
'expiry_date' => $validated['expiry_date'] ?? null,
'quality_status' => 'normal',
]);
}
});
$message = $status === 'completed'
? '生產單已完成,原物料已扣減,成品已入庫'
: '生產單草稿已更新';
return redirect()->route('production-orders.index')
->with('success', $message);
}
}

View File

@@ -3,8 +3,9 @@
namespace App\Http\Controllers;
use App\Models\Warehouse;
use App\Models\Inventory;
use App\Models\WarehouseProductSafetyStock;
use App\Models\Product;
use App\Models\Inventory;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\DB;
@@ -16,8 +17,6 @@ class SafetyStockController extends Controller
*/
public function index(Warehouse $warehouse)
{
$warehouse->load(['inventories.product.category']);
$allProducts = Product::with(['category', 'baseUnit'])->get();
// 準備可選商品列表
@@ -30,32 +29,34 @@ class SafetyStockController extends Controller
];
});
// 準備現有庫存列表 (用於狀態計算)
$inventories = $warehouse->inventories->map(function ($inv) {
// 準備現有庫存列表 (用於庫存量對比)
$inventories = Inventory::where('warehouse_id', $warehouse->id)
->select('product_id', DB::raw('SUM(quantity) as total_quantity'))
->groupBy('product_id')
->get()
->map(function ($inv) {
return [
'id' => (string) $inv->id,
'productId' => (string) $inv->product_id,
'quantity' => (float) $inv->quantity,
'safetyStock' => (float) $inv->safety_stock,
'quantity' => (float) $inv->total_quantity,
];
});
// 準備安全庫存設定列表
$safetyStockSettings = $warehouse->inventories->filter(function($inv) {
return !is_null($inv->safety_stock);
})->map(function ($inv) {
// 準備安全庫存設定列表 (從新表格讀取)
$safetyStockSettings = WarehouseProductSafetyStock::where('warehouse_id', $warehouse->id)
->with(['product.category', 'product.baseUnit'])
->get()
->map(function ($setting) {
return [
'id' => (string) $inv->id,
'warehouseId' => (string) $inv->warehouse_id,
'productId' => (string) $inv->product_id,
'productName' => $inv->product->name,
'productType' => $inv->product->category ? $inv->product->category->name : '其他',
'safetyStock' => (float) $inv->safety_stock,
'unit' => $inv->product->baseUnit?->name ?? '個',
'updatedAt' => $inv->updated_at->toIso8601String(),
'id' => (string) $setting->id,
'warehouseId' => (string) $setting->warehouse_id,
'productId' => (string) $setting->product_id,
'productName' => $setting->product->name,
'productType' => $setting->product->category ? $setting->product->category->name : '其他',
'safetyStock' => (float) $setting->safety_stock,
'unit' => $setting->product->baseUnit?->name ?? '個',
'updatedAt' => $setting->updated_at->toIso8601String(),
];
})->values();
});
return Inertia::render('Warehouse/SafetyStockSettings', [
'warehouse' => $warehouse,
@@ -78,7 +79,7 @@ class SafetyStockController extends Controller
DB::transaction(function () use ($validated, $warehouse) {
foreach ($validated['settings'] as $item) {
Inventory::updateOrCreate(
WarehouseProductSafetyStock::updateOrCreate(
[
'warehouse_id' => $warehouse->id,
'product_id' => $item['productId'],
@@ -96,13 +97,13 @@ class SafetyStockController extends Controller
/**
* 更新單筆安全庫存設定
*/
public function update(Request $request, Warehouse $warehouse, Inventory $inventory)
public function update(Request $request, Warehouse $warehouse, WarehouseProductSafetyStock $safetyStock)
{
$validated = $request->validate([
'safetyStock' => 'required|numeric|min:0',
]);
$inventory->update([
$safetyStock->update([
'safety_stock' => $validated['safetyStock'],
]);
@@ -110,13 +111,11 @@ class SafetyStockController extends Controller
}
/**
* 刪除 (歸零) 安全庫存設定
* 刪除安全庫存設定
*/
public function destroy(Warehouse $warehouse, Inventory $inventory)
public function destroy(Warehouse $warehouse, WarehouseProductSafetyStock $safetyStock)
{
$inventory->update([
'safety_stock' => null,
]);
$safetyStock->delete();
return redirect()->back()->with('success', '安全庫存設定已移除');
}

View File

@@ -46,7 +46,6 @@ class TransferOrderController extends Controller
],
[
'quantity' => 0,
'safety_stock' => null, // 預設為 null (未設定),而非 0
]
);

View File

@@ -23,9 +23,6 @@ class WarehouseController extends Controller
}
$warehouses = $query->withSum('inventories as total_quantity', 'quantity')
->withCount(['inventories as low_stock_count' => function ($query) {
$query->whereColumn('quantity', '<', 'safety_stock');
}])
->orderBy('created_at', 'desc')
->paginate(10)
->withQueryString();

View File

@@ -9,13 +9,13 @@ class Inventory extends Model
{
/** @use HasFactory<\Database\Factories\InventoryFactory> */
use HasFactory;
use \Illuminate\Database\Eloquent\SoftDeletes;
use \Spatie\Activitylog\Traits\LogsActivity;
protected $fillable = [
'warehouse_id',
'product_id',
'quantity',
'safety_stock',
'location',
// 批號追溯欄位
'batch_number',
@@ -121,7 +121,9 @@ class Inventory extends Model
$dateFormatted = date('Ymd', strtotime($arrivalDate));
$prefix = "{$productCode}-{$originCountry}-{$dateFormatted}-";
$lastBatch = static::where('batch_number', 'like', "{$prefix}%")
// 加入 withTrashed() 確保流水號不會撞到已刪除的紀錄
$lastBatch = static::withTrashed()
->where('batch_number', 'like', "{$prefix}%")
->orderByDesc('batch_number')
->first();

View File

@@ -0,0 +1,41 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* 倉庫-商品安全庫存設定
* 每個倉庫-商品組合只有一筆安全庫存設定
*/
class WarehouseProductSafetyStock extends Model
{
protected $table = 'warehouse_product_safety_stocks';
protected $fillable = [
'warehouse_id',
'product_id',
'safety_stock',
];
protected $casts = [
'safety_stock' => 'decimal:2',
];
/**
* 所屬倉庫
*/
public function warehouse(): BelongsTo
{
return $this->belongsTo(Warehouse::class);
}
/**
* 所屬商品
*/
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
}

View File

@@ -0,0 +1,36 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('inventories', function (Blueprint $table) {
// 先新增新的唯一約束 (倉庫 + 商品 + 批號)
// 這樣可以確保 warehouse_id 始終有索引可用,避免外鍵約束錯誤
$table->unique(['warehouse_id', 'product_id', 'batch_number'], 'warehouse_product_batch_unique');
// 然後移除舊的唯一約束 (倉庫 + 商品)
$table->dropUnique('warehouse_product_unique');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('inventories', function (Blueprint $table) {
// 恢復時也要注意順序,先加回舊的(如果資料允許),再刪除新的
// 但如果資料已經有多批號,加回舊的會失敗。這裡只盡力而為。
$table->unique(['warehouse_id', 'product_id'], 'warehouse_product_unique');
$table->dropUnique('warehouse_product_batch_unique');
});
}
};

View File

@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('inventory_transactions', function (Blueprint $table) {
$table->string('type', 50)->comment('異動類型: 採購進貨, 銷售出庫, 盤點調整, 撥補入庫, 撥補出庫, 手動入庫, 手動調整庫存')->change();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('inventory_transactions', function (Blueprint $table) {
$table->string('type', 20)->comment('異動類型: 採購進貨, 銷售出庫, 盤點調整, 撥補入庫, 撥補出庫, 手動入庫')->change();
});
}
};

View File

@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('inventories', function (Blueprint $table) {
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('inventories', function (Blueprint $table) {
$table->dropSoftDeletes();
});
}
};

View File

@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('warehouse_product_safety_stocks', function (Blueprint $table) {
$table->id();
$table->foreignId('warehouse_id')->constrained()->cascadeOnDelete();
$table->foreignId('product_id')->constrained()->cascadeOnDelete();
$table->decimal('safety_stock', 10, 2)->default(0);
$table->timestamps();
$table->unique(['warehouse_id', 'product_id'], 'wh_product_safety_stock_unique');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('warehouse_product_safety_stocks');
}
};

View File

@@ -0,0 +1,55 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
/**
* Run the migrations.
* inventories.safety_stock 資料遷移至 warehouse_product_safety_stocks 表格
*/
public function up(): void
{
// 1. 遷移現有資料:從 inventories 提取唯一的 warehouse_id + product_id 組合及其 safety_stock
DB::statement("
INSERT INTO warehouse_product_safety_stocks (warehouse_id, product_id, safety_stock, created_at, updated_at)
SELECT
warehouse_id,
product_id,
MAX(safety_stock) as safety_stock,
NOW(),
NOW()
FROM inventories
WHERE safety_stock IS NOT NULL AND safety_stock > 0
GROUP BY warehouse_id, product_id
ON DUPLICATE KEY UPDATE safety_stock = VALUES(safety_stock), updated_at = NOW()
");
// 2. 移除 inventories 表的 safety_stock 欄位
Schema::table('inventories', function (Blueprint $table) {
$table->dropColumn('safety_stock');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
// 1. 在 inventories 表重新加入 safety_stock 欄位
Schema::table('inventories', function (Blueprint $table) {
$table->decimal('safety_stock', 10, 2)->nullable()->after('quantity');
});
// 2. 將資料還原回 inventories (更新同商品所有批號)
DB::statement("
UPDATE inventories i
INNER JOIN warehouse_product_safety_stocks ss
ON i.warehouse_id = ss.warehouse_id AND i.product_id = ss.product_id
SET i.safety_stock = ss.safety_stock
");
}
};

View File

@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* warehouse_id 改為 nullable支援草稿模式。
*/
public function up(): void
{
Schema::table('production_orders', function (Blueprint $table) {
$table->foreignId('warehouse_id')->nullable()->change();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('production_orders', function (Blueprint $table) {
$table->foreignId('warehouse_id')->nullable(false)->change();
});
}
};

40
package-lock.json generated
View File

@@ -30,6 +30,7 @@
"lucide-react": "^0.562.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hot-toast": "^2.6.0",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0"
},
@@ -74,6 +75,7 @@
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.28.5.tgz",
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/code-frame": "^7.27.1",
"@babel/generator": "^7.28.5",
@@ -2537,6 +2539,7 @@
"integrity": "sha512-W609buLVRVmeW693xKfzHeIV6nJGGz98uCPfeXI1ELMLXVeKYZ9m15fAMSaUPBHYLGFsVRcMmSCksQOrZV9BYA==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"undici-types": "~7.16.0"
}
@@ -2547,6 +2550,7 @@
"integrity": "sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"csstype": "^3.2.2"
}
@@ -2557,6 +2561,7 @@
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
"devOptional": true,
"license": "MIT",
"peer": true,
"peerDependencies": {
"@types/react": "^19.2.0"
}
@@ -2664,6 +2669,7 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.9.0",
"caniuse-lite": "^1.0.30001759",
@@ -2876,8 +2882,8 @@
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"devOptional": true,
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/date-fns": {
"version": "4.1.0",
@@ -3208,6 +3214,15 @@
"node": ">= 0.4"
}
},
"node_modules/goober": {
"version": "2.1.18",
"resolved": "https://registry.npmjs.org/goober/-/goober-2.1.18.tgz",
"integrity": "sha512-2vFqsaDVIT9Gz7N6kAL++pLpp41l3PfDuusHcjnGLfR6+huZkl6ziX+zgVC3ZxpqWhzH6pyDdGrCeDhMIvwaxw==",
"license": "MIT",
"peerDependencies": {
"csstype": "^3.0.10"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
@@ -3747,6 +3762,7 @@
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -3808,6 +3824,7 @@
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"loose-envify": "^1.1.0"
},
@@ -3820,6 +3837,7 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
"license": "MIT",
"peer": true,
"dependencies": {
"loose-envify": "^1.1.0",
"scheduler": "^0.23.2"
@@ -3828,6 +3846,23 @@
"react": "^18.3.1"
}
},
"node_modules/react-hot-toast": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/react-hot-toast/-/react-hot-toast-2.6.0.tgz",
"integrity": "sha512-bH+2EBMZ4sdyou/DPrfgIouFpcRLCJ+HoCA32UoAYHn6T3Ur5yfcDCeSr5mwldl6pFOsiocmrXMuoCJ1vV8bWg==",
"license": "MIT",
"dependencies": {
"csstype": "^3.1.3",
"goober": "^2.1.16"
},
"engines": {
"node": ">=10"
},
"peerDependencies": {
"react": ">=16",
"react-dom": ">=16"
}
},
"node_modules/react-refresh": {
"version": "0.18.0",
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz",
@@ -4295,6 +4330,7 @@
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.0.tgz",
"integrity": "sha512-dZwN5L1VlUBewiP6H9s2+B3e3Jg96D0vzN+Ry73sOefebhYr9f94wwkMNN/9ouoU8pV1BqA1d1zGk8928cx0rg==",
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "^0.27.0",
"fdir": "^6.5.0",

View File

@@ -44,6 +44,7 @@
"lucide-react": "^0.562.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hot-toast": "^2.6.0",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0"
}

View File

@@ -86,6 +86,15 @@ const fieldLabels: Record<string, string> = {
quantity: '數量',
safety_stock: '安全庫存',
location: '儲位',
// Inventory fields
batch_number: '批號',
box_number: '箱號',
origin_country: '來源國家',
arrival_date: '入庫日期',
expiry_date: '有效期限',
source_purchase_order_id: '來源採購單',
quality_status: '品質狀態',
quality_remark: '品質備註',
// Purchase Order fields
po_number: '採購單號',
vendor_id: '廠商',
@@ -118,6 +127,13 @@ const statusMap: Record<string, string> = {
completed: '已完成',
};
// Inventory Quality Status Map
const qualityStatusMap: Record<string, string> = {
normal: '正常',
frozen: '凍結',
rejected: '瑕疵/拒收',
};
export default function ActivityDetailDialog({ open, onOpenChange, activity }: Props) {
if (!activity) return null;
@@ -193,8 +209,13 @@ export default function ActivityDetailDialog({ open, onOpenChange, activity }: P
return statusMap[value];
}
// Handle Inventory Quality Status
if (key === 'quality_status' && typeof value === 'string' && qualityStatusMap[value]) {
return qualityStatusMap[value];
}
// Handle Date Fields (YYYY-MM-DD)
if ((key === 'expected_delivery_date' || key === 'invoice_date') && typeof value === 'string') {
if ((key === 'expected_delivery_date' || key === 'invoice_date' || key === 'arrival_date' || key === 'expiry_date') && typeof value === 'string') {
// Take only the date part (YYYY-MM-DD)
return value.split('T')[0].split(' ')[0];
}

View File

@@ -0,0 +1,170 @@
import { useState, useEffect } from "react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "@/Components/ui/dialog";
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";
import { AlertCircle } from "lucide-react";
interface BatchAdjustmentModalProps {
isOpen: boolean;
onClose: () => void;
onConfirm: (data: {
operation: "add" | "subtract" | "set";
quantity: number;
reason: string;
}) => void;
batch?: {
id: string;
batchNumber: string;
currentQuantity: number;
productName: string;
};
processing?: boolean;
}
export default function BatchAdjustmentModal({
isOpen,
onClose,
onConfirm,
batch,
processing = false,
}: BatchAdjustmentModalProps) {
const [operation, setOperation] = useState<"add" | "subtract" | "set">("add");
const [quantity, setQuantity] = useState<string>("");
const [reason, setReason] = useState<string>("手動調整庫存");
// 當開啟時重置
useEffect(() => {
if (isOpen) {
setOperation("add");
setQuantity("");
setReason("手動調整庫存");
}
}, [isOpen]);
const handleConfirm = () => {
const numQty = parseFloat(quantity);
if (isNaN(numQty) || numQty <= 0 && operation !== "set") {
return;
}
onConfirm({
operation,
quantity: numQty,
reason,
});
};
const previewQuantity = () => {
if (!batch) return 0;
const numQty = parseFloat(quantity) || 0;
if (operation === "add") return batch.currentQuantity + numQty;
if (operation === "subtract") return Math.max(0, batch.currentQuantity - numQty);
if (operation === "set") return numQty;
return batch.currentQuantity;
};
if (!batch) return null;
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
調 - {batch.productName}
</DialogTitle>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="bg-gray-50 p-3 rounded-md border text-sm space-y-1">
<div className="flex justify-between">
<span className="text-gray-500"></span>
<span className="font-mono font-medium">{batch.batchNumber || "-"}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500"></span>
<span className="font-medium text-primary-main">{batch.currentQuantity}</span>
</div>
</div>
<div className="space-y-2">
<Label>調</Label>
<Select
value={operation}
onValueChange={(value: any) => setOperation(value)}
>
<SelectTrigger>
<SelectValue placeholder="選擇調整方式" />
</SelectTrigger>
<SelectContent>
<SelectItem value="add"> (+)</SelectItem>
<SelectItem value="subtract"> (-)</SelectItem>
<SelectItem value="set"> (=)</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="adj-qty"></Label>
<Input
id="adj-qty"
type="number"
step="0.01"
min="0"
value={quantity}
onChange={(e) => setQuantity(e.target.value)}
placeholder="請輸入數量"
/>
</div>
<div className="space-y-2">
<Label htmlFor="adj-reason">調</Label>
<Input
id="adj-reason"
value={reason}
onChange={(e) => setReason(e.target.value)}
placeholder="例:手動盤點修正"
/>
</div>
<div className="flex items-center gap-2 mt-2 p-3 bg-primary/5 rounded-md border border-primary/20 text-sm">
<AlertCircle className="h-4 w-4 text-primary-main" />
<span>
調
<span className="font-bold text-primary-main ml-1">
{previewQuantity()}
</span>
</span>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={onClose} disabled={processing}>
</Button>
<Button
onClick={handleConfirm}
disabled={processing || !quantity || parseFloat(quantity) < 0}
className="button-filled-primary"
>
調
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -1,19 +1,10 @@
/**
* 庫存表格元件 (扁平化列表版)
* 顯示庫存項目列表,不進行折疊分組
* 庫存表格元件 (Warehouse 版本)
* 顯示庫存項目列表(依商品分組並支援折疊)
*/
import { useState, useMemo } from "react";
import {
AlertTriangle,
Trash2,
Eye,
CheckCircle,
Package,
ArrowUpDown,
ArrowUp,
ArrowDown
} from "lucide-react";
import { useState } from "react";
import { AlertTriangle, Edit, Trash2, Eye, ChevronDown, ChevronRight, CheckCircle, Package } from "lucide-react";
import {
Table,
TableBody,
@@ -24,149 +15,87 @@ import {
} from "@/Components/ui/table";
import { Button } from "@/Components/ui/button";
import { Badge } from "@/Components/ui/badge";
import { WarehouseInventory } from "@/types/warehouse";
import { getSafetyStockStatus } from "@/utils/inventory";
import {
Collapsible,
CollapsibleContent,
} from "@/Components/ui/collapsible";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/Components/ui/tooltip";
import { GroupedInventory } from "@/types/warehouse";
import { formatDate } from "@/utils/format";
import { Can } from "@/Components/Permission/Can";
import BatchAdjustmentModal from "./BatchAdjustmentModal";
interface InventoryTableProps {
inventories: WarehouseInventory[];
inventories: GroupedInventory[];
onView: (id: string) => void;
onDelete: (id: string) => void;
onAdjust: (batchId: string, data: { operation: string; quantity: number; reason: string }) => void;
onViewProduct?: (productId: string) => void;
}
type SortField = "productName" | "quantity" | "lastInboundDate" | "lastOutboundDate" | "safetyStock" | "status";
type SortDirection = "asc" | "desc" | null;
export default function InventoryTable({
inventories,
onView,
onDelete,
onAdjust,
onViewProduct,
}: InventoryTableProps) {
const [sortField, setSortField] = useState<SortField | null>("status");
const [sortDirection, setSortDirection] = useState<SortDirection>("asc"); // "asc" for status means Priority High (Low Stock) first
// 每個商品的展開/折疊狀態
const [expandedProducts, setExpandedProducts] = useState<Set<string>>(new Set());
// 處理排序
const handleSort = (field: SortField) => {
if (sortField === field) {
if (sortDirection === "asc") {
setSortDirection("desc");
} else if (sortDirection === "desc") {
setSortDirection(null);
setSortField(null);
} else {
setSortDirection("asc");
}
} else {
setSortField(field);
setSortDirection("asc");
}
};
// 排序後的列表
const sortedInventories = useMemo(() => {
if (!sortField || !sortDirection) {
return inventories;
}
return [...inventories].sort((a, b) => {
let aValue: string | number;
let bValue: string | number;
// Status Priority map for sorting: Low > Near > Normal
const statusPriority: Record<string, number> = {
"低於": 1,
"接近": 2,
"正常": 3
};
switch (sortField) {
case "productName":
aValue = a.productName;
bValue = b.productName;
break;
case "quantity":
aValue = a.quantity;
bValue = b.quantity;
break;
case "lastInboundDate":
aValue = a.lastInboundDate || "";
bValue = b.lastInboundDate || "";
break;
case "lastOutboundDate":
aValue = a.lastOutboundDate || "";
bValue = b.lastOutboundDate || "";
break;
case "safetyStock":
aValue = a.safetyStock ?? -1; // null as -1 or Infinity depending on desired order
bValue = b.safetyStock ?? -1;
break;
case "status":
const aStatus = (a.safetyStock !== null && a.safetyStock !== undefined) ? getSafetyStockStatus(a.quantity, a.safetyStock) : "正常";
const bStatus = (b.safetyStock !== null && b.safetyStock !== undefined) ? getSafetyStockStatus(b.quantity, b.safetyStock) : "正常";
aValue = statusPriority[aStatus] || 3;
bValue = statusPriority[bStatus] || 3;
break;
default:
return 0;
}
if (typeof aValue === "string" && typeof bValue === "string") {
return sortDirection === "asc"
? aValue.localeCompare(bValue, "zh-TW")
: bValue.localeCompare(aValue, "zh-TW");
} else {
return sortDirection === "asc"
? (aValue as number) - (bValue as number)
: (bValue as number) - (aValue as number);
}
});
}, [inventories, sortField, sortDirection]);
const SortIcon = ({ field }: { field: SortField }) => {
if (sortField !== field) {
return <ArrowUpDown className="h-4 w-4 text-muted-foreground ml-1" />;
}
if (sortDirection === "asc") {
return <ArrowUp className="h-4 w-4 text-primary ml-1" />;
}
if (sortDirection === "desc") {
return <ArrowDown className="h-4 w-4 text-primary ml-1" />;
}
return <ArrowUpDown className="h-4 w-4 text-muted-foreground ml-1" />;
};
// 調整彈窗狀態
const [adjustmentTarget, setAdjustmentTarget] = useState<{
id: string;
batchNumber: string;
currentQuantity: number;
productName: string;
} | null>(null);
if (inventories.length === 0) {
return (
<div className="text-center py-12 text-gray-400">
<Package className="h-12 w-12 mx-auto mb-4 opacity-20" />
<p></p>
<p className="text-sm mt-1">調</p>
</div>
);
}
// 按商品名稱排序
const sortedInventories = [...inventories].sort((a, b) =>
a.productName.localeCompare(b.productName, "zh-TW")
);
const toggleProduct = (productId: string) => {
setExpandedProducts((prev) => {
const newSet = new Set(prev);
if (newSet.has(productId)) {
newSet.delete(productId);
} else {
newSet.add(productId);
}
return newSet;
});
};
// 獲取狀態徽章
const getStatusBadge = (quantity: number, safetyStock: number) => {
const status = getSafetyStockStatus(quantity, safetyStock);
const getStatusBadge = (status: string) => {
switch (status) {
case "正常":
return (
<Badge className="bg-green-100 text-green-700 border-green-300 hover:bg-green-100">
<Badge className="bg-green-100 text-green-700 border-green-300">
<CheckCircle className="mr-1 h-3 w-3" />
</Badge>
);
case "接近": // 數量 <= 安全庫存 * 1.2
case "低於":
return (
<Badge className="bg-yellow-100 text-yellow-700 border-yellow-300 hover:bg-yellow-100">
<AlertTriangle className="mr-1 h-3 w-3" />
</Badge>
);
case "低於": // 數量 < 安全庫存
return (
<Badge className="bg-orange-100 text-orange-700 border-orange-300 hover:bg-orange-100">
<Badge className="bg-red-100 text-red-700 border-red-300">
<AlertTriangle className="mr-1 h-3 w-3" />
</Badge>
@@ -177,127 +106,201 @@ export default function InventoryTable({
};
return (
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow className="bg-gray-50/50">
<TableHead className="w-[50px] text-center">#</TableHead>
<TableHead className="w-[25%]">
<button onClick={() => handleSort("productName")} className="flex items-center hover:text-gray-900">
<SortIcon field="productName" />
</button>
</TableHead>
<TableHead className="w-[10%] text-right">
<div className="flex justify-end">
<button onClick={() => handleSort("quantity")} className="flex items-center hover:text-gray-900">
<SortIcon field="quantity" />
</button>
</div>
</TableHead>
<TableHead className="w-[12%]">
<button onClick={() => handleSort("lastInboundDate")} className="flex items-center hover:text-gray-900">
<SortIcon field="lastInboundDate" />
</button>
</TableHead>
<TableHead className="w-[12%]">
<button onClick={() => handleSort("lastOutboundDate")} className="flex items-center hover:text-gray-900">
<SortIcon field="lastOutboundDate" />
</button>
</TableHead>
<TableHead className="w-[10%] text-right">
<div className="flex justify-end">
<button onClick={() => handleSort("safetyStock")} className="flex items-center hover:text-gray-900">
<SortIcon field="safetyStock" />
</button>
</div>
</TableHead>
<TableHead className="w-[10%] text-center">
<div className="flex justify-center">
<button onClick={() => handleSort("status")} className="flex items-center hover:text-gray-900">
<SortIcon field="status" />
</button>
</div>
</TableHead>
<TableHead className="w-[10%] text-center"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{sortedInventories.map((item, index) => (
<TableRow key={item.id}>
<TableCell className="text-gray-500 font-medium text-center">
{index + 1}
</TableCell>
{/* 商品資訊 */}
<TableCell>
<div className="flex flex-col">
<div className="font-medium text-gray-900">{item.productName}</div>
<div className="text-xs text-gray-500">{item.productCode}</div>
</div>
</TableCell>
<TooltipProvider>
<div className="space-y-4 p-4">
{sortedInventories.map((group) => {
const totalQuantity = group.totalQuantity;
{/* 庫存數量 */}
<TableCell className="text-right">
<span className="font-medium text-gray-900">{item.quantity}</span>
<span className="text-xs text-gray-500 ml-1">{item.unit}</span>
</TableCell>
// 使用後端提供的狀態
const status = group.status;
{/* 最新入庫 */}
<TableCell className="text-gray-600">
{item.lastInboundDate ? formatDate(item.lastInboundDate) : "-"}
</TableCell>
const isLowStock = status === "低於";
const isExpanded = expandedProducts.has(group.productId);
const hasInventory = group.batches.length > 0;
{/* 最新出庫 */}
<TableCell className="text-gray-600">
{item.lastOutboundDate ? formatDate(item.lastOutboundDate) : "-"}
</TableCell>
{/* 安全庫存 */}
<TableCell className="text-right">
{item.safetyStock !== null && item.safetyStock >= 0 ? (
<span className="font-medium text-gray-900">
{item.safetyStock} <span className="text-xs text-gray-500 font-normal">{item.unit}</span>
</span>
return (
<Collapsible
key={group.productId}
open={isExpanded}
onOpenChange={() => toggleProduct(group.productId)}
>
<div className="border rounded-lg overflow-hidden">
{/* 商品標題 - 可點擊折疊 */}
<div
onClick={() => toggleProduct(group.productId)}
className={`px-4 py-3 border-b cursor-pointer hover:bg-gray-100 transition-colors ${isLowStock ? "bg-red-50" : "bg-gray-50"
}`}
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
{/* 折疊圖示 */}
{isExpanded ? (
<ChevronDown className="h-5 w-5 text-gray-600" />
) : (
<span className="text-gray-400 text-xs"></span>
<ChevronRight className="h-5 w-5 text-gray-600" />
)}
</TableCell>
{/* 狀態 */}
<TableCell className="text-center">
{(item.safetyStock !== null && item.safetyStock !== undefined) ? getStatusBadge(item.quantity, item.safetyStock) : (
<Badge variant="outline" className="text-gray-400 border-dashed"></Badge>
<h3 className="font-semibold text-gray-900">{group.productName}</h3>
<span className="text-sm text-gray-500">
{hasInventory ? `${group.batches.length} 個批號` : '無庫存'}
</span>
</div>
<div className="flex items-center gap-4">
<div className="text-sm">
<span className="text-gray-600">
<span className={`font-medium ${isLowStock ? "text-red-600" : "text-gray-900"}`}>{totalQuantity} </span>
</span>
</div>
{group.safetyStock !== null ? (
<>
<div className="text-sm">
<span className="text-gray-600">
<span className="font-medium text-gray-900">{group.safetyStock} </span>
</span>
</div>
<div>
{status && getStatusBadge(status)}
</div>
</>
) : (
<Badge variant="outline" className="text-gray-500">
</Badge>
)}
</TableCell>
{/* 操作 */}
<TableCell className="text-center">
<div className="flex justify-center gap-2">
{onViewProduct && (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => onView(item.id)}
title="查看庫存流水帳"
onClick={(e) => {
e.stopPropagation();
onViewProduct(group.productId);
}}
className="button-outlined-primary"
>
<Eye className="h-4 w-4" />
</Button>
<Can permission="inventory.delete">
)}
</div>
</div>
</div>
{/* 商品表格 - 可折疊內容 */}
<CollapsibleContent>
{hasInventory ? (
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[5%]">#</TableHead>
<TableHead className="w-[12%]"></TableHead>
<TableHead className="w-[12%]"></TableHead>
<TableHead className="w-[15%]"></TableHead>
<TableHead className="w-[14%]"></TableHead>
<TableHead className="w-[14%]"></TableHead>
<TableHead className="w-[14%]"></TableHead>
<TableHead className="w-[8%] text-right"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{group.batches.map((batch, index) => {
return (
<TableRow key={batch.id}>
<TableCell className="text-grey-2">{index + 1}</TableCell>
<TableCell>{batch.batchNumber || "-"}</TableCell>
<TableCell>
<span>{batch.quantity}</span>
</TableCell>
<TableCell>{batch.batchNumber || "-"}</TableCell>
<TableCell>
{batch.expiryDate ? formatDate(batch.expiryDate) : "-"}
</TableCell>
<TableCell>
{batch.lastInboundDate ? formatDate(batch.lastInboundDate) : "-"}
</TableCell>
<TableCell>
{batch.lastOutboundDate ? formatDate(batch.lastOutboundDate) : "-"}
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => onDelete(item.id)}
title="刪除"
className="button-outlined-error"
onClick={() => onView(batch.id)}
className="button-outlined-primary"
>
<Eye className="h-4 w-4" />
</Button>
<Can permission="inventory.adjust">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setAdjustmentTarget({
id: batch.id,
batchNumber: batch.batchNumber,
currentQuantity: batch.quantity,
productName: group.productName
})}
className="button-outlined-primary"
>
<Edit className="h-4 w-4" />
</Button>
</Can>
<Can permission="inventory.delete">
<Tooltip>
<TooltipTrigger asChild>
<div className="inline-block">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => onDelete(batch.id)}
className={batch.quantity > 0 ? "opacity-50 cursor-not-allowed border-gray-200 text-gray-400 hover:bg-transparent" : "button-outlined-error"}
disabled={batch.quantity > 0}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</TooltipTrigger>
<TooltipContent>
<p className="text-xs">{batch.quantity > 0 ? "庫存須為 0 才可刪除" : "刪除"}</p>
</TooltipContent>
</Tooltip>
</Can>
</div>
</TableCell>
</TableRow>
))}
);
})}
</TableBody>
</Table>
</div>
) : (
<div className="px-4 py-8 text-center text-gray-400 bg-gray-50">
<Package className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm"></p>
<p className="text-xs mt-1"></p>
</div>
)}
</CollapsibleContent>
</div>
</Collapsible>
);
})}
<BatchAdjustmentModal
isOpen={!!adjustmentTarget}
onClose={() => setAdjustmentTarget(null)}
batch={adjustmentTarget || undefined}
onConfirm={(data) => {
if (adjustmentTarget) {
onAdjust(adjustmentTarget.id, data);
setAdjustmentTarget(null);
}
}}
/>
</div>
</TooltipProvider>
);
}

View File

@@ -8,13 +8,15 @@ export interface Transaction {
reason: string | null;
userName: string;
actualTime: string;
batchNumber?: string; // 商品層級查詢時顯示批號
}
interface TransactionTableProps {
transactions: Transaction[];
showBatchNumber?: boolean; // 是否顯示批號欄位
}
export default function TransactionTable({ transactions }: TransactionTableProps) {
export default function TransactionTable({ transactions, showBatchNumber = false }: TransactionTableProps) {
if (transactions.length === 0) {
return (
<div className="text-center py-8 text-gray-500">
@@ -23,6 +25,9 @@ export default function TransactionTable({ transactions }: TransactionTableProps
);
}
// 自動偵測是否需要顯示批號(如果任一筆記錄有 batchNumber
const shouldShowBatchNumber = showBatchNumber || transactions.some(tx => tx.batchNumber);
return (
<div className="overflow-x-auto">
<table className="w-full text-sm text-left">
@@ -30,6 +35,7 @@ export default function TransactionTable({ transactions }: TransactionTableProps
<tr>
<th className="px-4 py-3 w-[50px]">#</th>
<th className="px-4 py-3"></th>
{shouldShowBatchNumber && <th className="px-4 py-3"></th>}
<th className="px-4 py-3"></th>
<th className="px-4 py-3 text-right"></th>
<th className="px-4 py-3 text-right"></th>
@@ -42,6 +48,9 @@ export default function TransactionTable({ transactions }: TransactionTableProps
<tr key={tx.id} className="border-b hover:bg-gray-50">
<td className="px-4 py-3 text-center text-gray-500 font-medium">{index + 1}</td>
<td className="px-4 py-3 whitespace-nowrap">{tx.actualTime}</td>
{shouldShowBatchNumber && (
<td className="px-4 py-3 font-mono text-sm text-gray-600">{tx.batchNumber || '-'}</td>
)}
<td className="px-4 py-3">
<span className={`px-2 py-1 rounded-full text-xs ${tx.quantity > 0
? 'bg-green-100 text-green-800'

View File

@@ -4,15 +4,18 @@
*/
import { useState, useEffect } from "react";
import { Factory, Plus, Trash2, ArrowLeft, Save, AlertTriangle, Calendar } from 'lucide-react';
import { Factory, Plus, Trash2, ArrowLeft, Save, Calendar, AlertCircle } from 'lucide-react';
import { Button } from "@/Components/ui/button";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, router, useForm } from "@inertiajs/react";
import toast, { Toaster } from 'react-hot-toast';
import { getBreadcrumbs } from "@/utils/breadcrumb";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { Textarea } from "@/Components/ui/textarea";
import { Link } from "@inertiajs/react";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/Components/ui/table";
interface Product {
id: number;
@@ -42,16 +45,35 @@ interface InventoryOption {
arrival_date: string | null;
expiry_date: string | null;
unit_name: string | null;
base_unit_id?: number;
base_unit_name?: string;
large_unit_id?: number;
large_unit_name?: string;
conversion_rate?: number;
}
interface BomItem {
inventory_id: string;
quantity_used: string;
unit_id: string;
// 顯示用
product_name?: string;
batch_number?: string;
available_qty?: number;
// Backend required
inventory_id: string; // The selected inventory record ID (Specific Batch)
quantity_used: string; // The converted final quantity (Base Unit)
unit_id: string; // The unit ID (Base Unit ID usually)
// UI State
ui_warehouse_id: string; // Source Warehouse
ui_product_id: string; // Filter for batch list
ui_input_quantity: string; // User typed quantity
ui_selected_unit: 'base' | 'large'; // User selected unit
// UI Helpers / Cache
ui_product_name?: string;
ui_batch_number?: string;
ui_available_qty?: number;
ui_expiry_date?: string;
ui_conversion_rate?: number;
ui_base_unit_name?: string;
ui_large_unit_name?: string;
ui_base_unit_id?: number;
ui_large_unit_id?: number;
}
interface Props {
@@ -60,10 +82,12 @@ interface Props {
units: Unit[];
}
export default function ProductionCreate({ products, warehouses, units }: Props) {
const [selectedWarehouse, setSelectedWarehouse] = useState<string>("");
const [inventoryOptions, setInventoryOptions] = useState<InventoryOption[]>([]);
const [isLoadingInventory, setIsLoadingInventory] = useState(false);
export default function ProductionCreate({ products, warehouses }: Props) {
const [selectedWarehouse, setSelectedWarehouse] = useState<string>(""); // Output Warehouse
// Cache map: warehouse_id -> inventories
const [inventoryMap, setInventoryMap] = useState<Record<string, InventoryOption[]>>({});
const [loadingWarehouses, setLoadingWareStates] = useState<Record<string, boolean>>({});
const [bomItems, setBomItems] = useState<BomItem[]>([]);
const { data, setData, processing, errors } = useForm({
@@ -78,23 +102,23 @@ export default function ProductionCreate({ products, warehouses, units }: Props)
items: [] as { inventory_id: number; quantity_used: number; unit_id: number | null }[],
});
// 當選擇倉庫時,載入該倉庫的可用庫存
useEffect(() => {
if (selectedWarehouse) {
setIsLoadingInventory(true);
fetch(route('api.production.warehouses.inventories', selectedWarehouse))
.then(res => res.json())
.then((inventories: InventoryOption[]) => {
setInventoryOptions(inventories);
setIsLoadingInventory(false);
})
.catch(() => setIsLoadingInventory(false));
} else {
setInventoryOptions([]);
}
}, [selectedWarehouse]);
// Helper to fetch warehouse data
const fetchWarehouseInventory = async (warehouseId: string) => {
if (!warehouseId || inventoryMap[warehouseId] || loadingWarehouses[warehouseId]) return;
// 同步 warehouse_id 到 form data
setLoadingWareStates(prev => ({ ...prev, [warehouseId]: true }));
try {
const res = await fetch(route('api.production.warehouses.inventories', warehouseId));
const data = await res.json();
setInventoryMap(prev => ({ ...prev, [warehouseId]: data }));
} catch (e) {
console.error(e);
} finally {
setLoadingWareStates(prev => ({ ...prev, [warehouseId]: false }));
}
};
// 同步 warehouse_id 到 form data (Output)
useEffect(() => {
setData('warehouse_id', selectedWarehouse);
}, [selectedWarehouse]);
@@ -105,6 +129,10 @@ export default function ProductionCreate({ products, warehouses, units }: Props)
inventory_id: "",
quantity_used: "",
unit_id: "",
ui_warehouse_id: "",
ui_product_id: "",
ui_input_quantity: "",
ui_selected_unit: 'base',
}]);
};
@@ -113,45 +141,167 @@ export default function ProductionCreate({ products, warehouses, units }: Props)
setBomItems(bomItems.filter((_, i) => i !== index));
};
// 更新 BOM 項目
const updateBomItem = (index: number, field: keyof BomItem, value: string) => {
// 更新 BOM 項目邏輯
const updateBomItem = (index: number, field: keyof BomItem, value: any) => {
const updated = [...bomItems];
updated[index] = { ...updated[index], [field]: value };
const item = { ...updated[index], [field]: value };
// 如果選擇了庫存,自動填入顯示資訊
// 0. 當選擇來源倉庫變更時
if (field === 'ui_warehouse_id') {
// 重置後續欄位
item.ui_product_id = "";
item.inventory_id = "";
item.quantity_used = "";
item.unit_id = "";
item.ui_input_quantity = "";
item.ui_selected_unit = "base";
delete item.ui_product_name;
delete item.ui_batch_number;
delete item.ui_available_qty;
delete item.ui_expiry_date;
delete item.ui_conversion_rate;
delete item.ui_base_unit_name;
delete item.ui_large_unit_name;
delete item.ui_base_unit_id;
delete item.ui_large_unit_id;
// 觸發載入資料
if (value) {
fetchWarehouseInventory(value);
}
}
// 1. 當選擇商品變更時 -> 清空批號與相關資訊
if (field === 'ui_product_id') {
item.inventory_id = "";
item.quantity_used = "";
item.unit_id = "";
item.ui_input_quantity = "";
item.ui_selected_unit = "base";
// 清除 cache 資訊
delete item.ui_product_name;
delete item.ui_batch_number;
delete item.ui_available_qty;
delete item.ui_expiry_date;
delete item.ui_conversion_rate;
delete item.ui_base_unit_name;
delete item.ui_large_unit_name;
delete item.ui_base_unit_id;
delete item.ui_large_unit_id;
}
// 2. 當選擇批號 (Inventory ID) 變更時 -> 載入該批號資訊
if (field === 'inventory_id' && value) {
const inv = inventoryOptions.find(i => String(i.id) === value);
const currentOptions = inventoryMap[item.ui_warehouse_id] || [];
const inv = currentOptions.find(i => String(i.id) === value);
if (inv) {
updated[index].product_name = inv.product_name;
updated[index].batch_number = inv.batch_number;
updated[index].available_qty = inv.quantity;
item.ui_product_id = String(inv.product_id); // 確保商品也被選中 (雖通常是先選商品)
item.ui_product_name = inv.product_name;
item.ui_batch_number = inv.batch_number;
item.ui_available_qty = inv.quantity;
item.ui_expiry_date = inv.expiry_date || '';
// 單位與轉換率
item.ui_base_unit_name = inv.base_unit_name || inv.unit_name || '';
item.ui_large_unit_name = inv.large_unit_name || '';
item.ui_base_unit_id = inv.base_unit_id;
item.ui_large_unit_id = inv.large_unit_id;
item.ui_conversion_rate = inv.conversion_rate || 1;
// 預設單位
item.ui_selected_unit = 'base';
item.unit_id = String(inv.base_unit_id || '');
}
}
// 3. 計算最終數量 (Base Quantity)
// 當 輸入數量 或 選擇單位 變更時
if (field === 'ui_input_quantity' || field === 'ui_selected_unit' || field === 'inventory_id') {
const inputQty = parseFloat(item.ui_input_quantity || '0');
const rate = item.ui_conversion_rate || 1;
if (item.ui_selected_unit === 'large') {
item.quantity_used = String(inputQty * rate);
// 注意:後端需要的是 Base Unit ID? 這裡我們都送 Base Unit ID因為 quantity_used 是 Base Unit
// 但為了保留 User 的選擇,我們可能可以在 remark 註記? 目前先從簡
item.unit_id = String(item.ui_base_unit_id || '');
} else {
item.quantity_used = String(inputQty);
item.unit_id = String(item.ui_base_unit_id || '');
}
}
updated[index] = item;
setBomItems(updated);
};
// 產生成品批號建議
const generateBatchNumber = () => {
// 同步 BOM items 到表單 data
useEffect(() => {
setData('items', bomItems.map(item => ({
inventory_id: Number(item.inventory_id),
quantity_used: Number(item.quantity_used),
unit_id: item.unit_id ? Number(item.unit_id) : null
})));
}, [bomItems]);
// 自動產生成品批號(當選擇商品或日期變動時)
useEffect(() => {
if (!data.product_id) return;
const product = products.find(p => String(p.id) === data.product_id);
if (!product) return;
const date = data.production_date.replace(/-/g, '');
const suggested = `${product.code}-TW-${date}-01`;
const datePart = data.production_date; // YYYY-MM-DD
const dateFormatted = datePart.replace(/-/g, '');
const originCountry = 'TW';
// 呼叫 API 取得下一組流水號
// 複用庫存批號 API但這裡可能沒有選 warehouse所以用第一個預設
const warehouseId = selectedWarehouse || (warehouses.length > 0 ? String(warehouses[0].id) : '1');
fetch(`/api/warehouses/${warehouseId}/inventory/batches/${product.id}?originCountry=${originCountry}&arrivalDate=${datePart}`)
.then(res => res.json())
.then(result => {
const seq = result.nextSequence || '01';
const suggested = `${product.code}-${originCountry}-${dateFormatted}-${seq}`;
setData('output_batch_number', suggested);
};
})
.catch(() => {
// Fallback若 API 失敗,使用預設 01
const suggested = `${product.code}-${originCountry}-${dateFormatted}-01`;
setData('output_batch_number', suggested);
});
}, [data.product_id, data.production_date]);
// 提交表單
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const submit = (status: 'draft' | 'completed') => {
// 驗證(簡單前端驗證,完整驗證在後端)
if (status === 'completed') {
const missingFields = [];
if (!data.product_id) missingFields.push('成品商品');
if (!data.output_quantity) missingFields.push('生產數量');
if (!data.output_batch_number) missingFields.push('成品批號');
if (!data.production_date) missingFields.push('生產日期');
if (!selectedWarehouse) missingFields.push('入庫倉庫');
if (bomItems.length === 0) missingFields.push('原物料明細');
if (missingFields.length > 0) {
toast.error(
<div className="flex flex-col gap-1">
<span className="font-bold"></span>
<span className="text-sm">{missingFields.join('、')}</span>
</div>
);
return;
}
}
// 轉換 BOM items 格式
const formattedItems = bomItems
.filter(item => item.inventory_id && item.quantity_used)
.filter(item => status === 'draft' || (item.inventory_id && item.quantity_used))
.map(item => ({
inventory_id: parseInt(item.inventory_id),
quantity_used: parseFloat(item.quantity_used),
inventory_id: item.inventory_id ? parseInt(item.inventory_id) : null,
quantity_used: item.quantity_used ? parseFloat(item.quantity_used) : 0,
unit_id: item.unit_id ? parseInt(item.unit_id) : null,
}));
@@ -159,33 +309,74 @@ export default function ProductionCreate({ products, warehouses, units }: Props)
router.post(route('production-orders.store'), {
...data,
items: formattedItems,
status: status,
}, {
onError: (errors) => {
const errorCount = Object.keys(errors).length;
toast.error(
<div className="flex flex-col gap-1">
<span className="font-bold"></span>
<span className="text-sm"> {errorCount} </span>
</div>
);
}
});
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
submit('completed');
};
return (
<AuthenticatedLayout breadcrumbs={getBreadcrumbs("productionOrdersCreate")}>
<Head title="建立生產單" />
<div className="container mx-auto p-6 max-w-4xl">
<div className="flex items-center gap-4 mb-6">
<Toaster position="top-right" />
<div className="container mx-auto p-6 max-w-7xl">
<div className="mb-6">
<Link href={route('production-orders.index')}>
<Button
variant="ghost"
onClick={() => router.get(route('production-orders.index'))}
className="p-2"
variant="outline"
className="gap-2 button-outlined-primary mb-6"
>
<ArrowLeft className="h-5 w-5" />
<ArrowLeft className="h-4 w-4" />
</Button>
</Link>
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<Factory className="h-6 w-6 text-primary-main" />
</h1>
<p className="text-gray-500 mt-1">
使
</p>
</div>
<div className="flex gap-2">
<Button
onClick={() => submit('draft')}
disabled={processing}
variant="outline"
className="button-outlined-primary"
>
<Save className="mr-2 h-4 w-4" />
稿
</Button>
<Button
onClick={() => submit('completed')}
disabled={processing}
className="button-filled-primary"
>
<Factory className="mr-2 h-4 w-4" />
</Button>
</div>
</div>
</div>
<form onSubmit={handleSubmit}>
<form onSubmit={handleSubmit} className="space-y-6">
{/* 成品資訊 */}
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200 mb-6">
<h2 className="text-lg font-semibold mb-4"></h2>
@@ -220,23 +411,12 @@ export default function ProductionCreate({ products, warehouses, units }: Props)
<div className="space-y-1">
<Label className="text-xs font-medium text-grey-2"> *</Label>
<div className="flex gap-2">
<Input
value={data.output_batch_number}
onChange={(e) => setData('output_batch_number', e.target.value)}
placeholder="例如: AB-TW-20260121-01"
placeholder="選擇商品後自動產生"
className="h-9 font-mono"
/>
<Button
type="button"
variant="outline"
onClick={generateBatchNumber}
disabled={!data.product_id}
className="h-9 button-outlined-primary shrink-0"
>
</Button>
</div>
{errors.output_batch_number && <p className="text-red-500 text-xs mt-1">{errors.output_batch_number}</p>}
</div>
@@ -313,7 +493,6 @@ export default function ProductionCreate({ products, warehouses, units }: Props)
type="button"
variant="outline"
onClick={addBomItem}
disabled={!selectedWarehouse}
className="gap-2 button-filled-primary text-white"
>
<Plus className="h-4 w-4" />
@@ -321,20 +500,7 @@ export default function ProductionCreate({ products, warehouses, units }: Props)
</Button>
</div>
{!selectedWarehouse && (
<div className="text-center py-8 text-gray-500">
<AlertTriangle className="h-8 w-8 mx-auto mb-2 text-yellow-500" />
</div>
)}
{selectedWarehouse && isLoadingInventory && (
<div className="text-center py-8 text-gray-500">
...
</div>
)}
{selectedWarehouse && !isLoadingInventory && bomItems.length === 0 && (
{bomItems.length === 0 && (
<div className="text-center py-8 text-gray-500">
<Factory className="h-8 w-8 mx-auto mb-2 text-gray-300" />
BOM
@@ -342,99 +508,125 @@ export default function ProductionCreate({ products, warehouses, units }: Props)
)}
{bomItems.length > 0 && (
<div className="space-y-4">
{bomItems.map((item, index) => (
<div
key={index}
className="grid grid-cols-1 md:grid-cols-12 gap-3 items-end p-4 bg-gray-50/50 border border-gray-100 rounded-lg relative group"
>
<div className="md:col-span-5 space-y-1">
<Label className="text-xs font-medium text-grey-2"> ()</Label>
<div className="border rounded-lg overflow-hidden">
<Table>
<TableHeader>
<TableRow className="bg-gray-50/50">
<TableHead className="w-[20%]"> <span className="text-red-500">*</span></TableHead>
<TableHead className="w-[20%]"> <span className="text-red-500">*</span></TableHead>
<TableHead className="w-[25%]"> <span className="text-red-500">*</span></TableHead>
<TableHead className="w-[15%]"> <span className="text-red-500">*</span></TableHead>
<TableHead className="w-[15%]"></TableHead>
<TableHead className="w-[5%]"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{bomItems.map((item, index) => {
// 取得此列已載入的 Inventory Options
const currentOptions = inventoryMap[item.ui_warehouse_id] || [];
// 過濾商品
const uniqueProductOptions = Array.from(new Map(
currentOptions.map(inv => [inv.product_id, { label: inv.product_name, value: String(inv.product_id) }])
).values());
// 過濾批號
const batchOptions = currentOptions
.filter(inv => String(inv.product_id) === item.ui_product_id)
.map(inv => ({
label: `${inv.batch_number} / ${inv.expiry_date || '無效期'} / ${inv.quantity}`,
value: String(inv.id)
}));
return (
<TableRow key={index}>
{/* 0. 選擇來源倉庫 */}
<TableCell className="align-top">
<SearchableSelect
value={item.ui_warehouse_id}
onValueChange={(v) => updateBomItem(index, 'ui_warehouse_id', v)}
options={warehouses.map(w => ({ label: w.name, value: String(w.id) }))}
placeholder="選擇倉庫"
className="w-full"
/>
</TableCell>
{/* 1. 選擇商品 */}
<TableCell className="align-top">
<SearchableSelect
value={item.ui_product_id}
onValueChange={(v) => updateBomItem(index, 'ui_product_id', v)}
options={uniqueProductOptions}
placeholder="選擇商品"
className="w-full"
disabled={!item.ui_warehouse_id}
/>
</TableCell>
{/* 2. 選擇批號 */}
<TableCell className="align-top">
<SearchableSelect
value={item.inventory_id}
onValueChange={(v) => updateBomItem(index, 'inventory_id', v)}
options={inventoryOptions.map(inv => ({
label: `${inv.product_name} - ${inv.batch_number} (庫存: ${inv.quantity})`,
value: String(inv.id),
}))}
placeholder="選擇原物料與批號"
className="w-full h-9"
options={batchOptions}
placeholder={item.ui_product_id ? "選擇批號" : "請先選商品"}
className="w-full"
disabled={!item.ui_product_id}
/>
{item.inventory_id && (() => {
const selectedInv = currentOptions.find(i => String(i.id) === item.inventory_id);
if (selectedInv) return (
<div className="text-xs text-gray-500 mt-1">
: {selectedInv.expiry_date || '無'} | : {selectedInv.quantity}
</div>
);
return null;
})()}
</TableCell>
<div className="md:col-span-3 space-y-1">
<Label className="text-xs font-medium text-grey-2">使</Label>
<div className="relative">
{/* 3. 輸入數量 */}
<TableCell className="align-top">
<Input
type="number"
step="0.0001"
value={item.quantity_used}
onChange={(e) => updateBomItem(index, 'quantity_used', e.target.value)}
placeholder="0.00"
className="h-9 pr-12"
step="1"
value={item.ui_input_quantity}
onChange={(e) => updateBomItem(index, 'ui_input_quantity', e.target.value)}
placeholder="0"
className="h-9"
disabled={!item.inventory_id}
/>
<div className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-gray-400 pointer-events-none">
</div>
</div>
{item.available_qty && (
<p className="text-xs text-gray-400 mt-1">: {item.available_qty.toLocaleString()}</p>
)}
</div>
</TableCell>
<div className="md:col-span-3 space-y-1">
<Label className="text-xs font-medium text-grey-2">/</Label>
<SearchableSelect
value={item.unit_id}
onValueChange={(v) => updateBomItem(index, 'unit_id', v)}
options={units.map(u => ({
label: u.name,
value: String(u.id),
}))}
placeholder="選擇單位"
className="w-full h-9"
/>
</div>
{/* 4. 選擇單位 */}
<TableCell className="align-top pt-3">
<span className="text-sm">{item.ui_base_unit_name}</span>
</TableCell>
<div className="md:col-span-1">
<TableCell className="align-top">
<Button
type="button"
variant="outline"
variant="ghost"
size="sm"
onClick={() => removeBomItem(index)}
className="button-outlined-error h-9 w-full md:w-9 p-0"
title="移除此項目"
className="text-red-500 hover:text-red-700 hover:bg-red-50 p-2"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
))}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
)}
{errors.items && <p className="text-red-500 text-sm mt-2">{errors.items}</p>}
</div>
{/* 提交按鈕 */}
<div className="flex justify-end gap-3">
<Button
type="button"
variant="outline"
onClick={() => router.get(route('production-orders.index'))}
className="h-10 px-6"
>
</Button>
<Button
type="submit"
disabled={processing || bomItems.length === 0}
className="gap-2 button-filled-primary h-10 px-8"
>
<Save className="h-4 w-4" />
{processing ? '處理中...' : '建立生產單'}
</Button>
</div>
</form>
</div>
</AuthenticatedLayout>

View File

@@ -0,0 +1,710 @@
/**
* 編輯生產工單頁面
* 僅限草稿狀態可編輯
*/
import { useState, useEffect } from "react";
import { Factory, Plus, Trash2, ArrowLeft, Save, Calendar } from 'lucide-react';
import { Button } from "@/Components/ui/button";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, router, useForm, Link } from "@inertiajs/react";
import toast, { Toaster } from 'react-hot-toast';
import { getBreadcrumbs } from "@/utils/breadcrumb";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { Textarea } from "@/Components/ui/textarea";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/Components/ui/table";
interface Product {
id: number;
name: string;
code: string;
base_unit?: { id: number; name: string } | null;
}
interface Warehouse {
id: number;
name: string;
}
interface Unit {
id: number;
name: string;
}
interface InventoryOption {
id: number;
product_id: number;
product_name: string;
product_code: string;
batch_number: string;
box_number: string | null;
quantity: number;
arrival_date: string | null;
expiry_date: string | null;
unit_name: string | null;
base_unit_id?: number;
base_unit_name?: string;
large_unit_id?: number;
large_unit_name?: string;
conversion_rate?: number;
}
interface BomItem {
// Backend required
inventory_id: string;
quantity_used: string;
unit_id: string;
// UI State
ui_warehouse_id: string; // Source Warehouse
ui_product_id: string;
ui_input_quantity: string;
ui_selected_unit: 'base' | 'large';
// UI Helpers / Cache
ui_product_name?: string;
ui_batch_number?: string;
ui_available_qty?: number;
ui_expiry_date?: string;
ui_conversion_rate?: number;
ui_base_unit_name?: string;
ui_large_unit_name?: string;
ui_base_unit_id?: number;
ui_large_unit_id?: number;
}
interface ProductionOrderItem {
id: number;
production_order_id: number;
inventory_id: number;
quantity_used: number;
unit_id: number | null;
inventory?: {
product_id: number;
product?: {
name: string;
code: string;
base_unit?: { name: string };
};
batch_number: string;
quantity: number;
expiry_date?: string;
warehouse_id?: number;
};
unit?: {
name: string;
};
}
interface ProductionOrder {
id: number;
code: string;
product_id: number;
warehouse_id: number | null;
output_quantity: number;
output_batch_number: string;
output_box_count: string | null;
production_date: string;
expiry_date: string | null;
remark: string | null;
status: string;
items: ProductionOrderItem[];
product?: Product;
warehouse?: Warehouse;
}
interface Props {
productionOrder: ProductionOrder;
products: Product[];
warehouses: Warehouse[];
units: Unit[];
}
export default function ProductionEdit({ productionOrder, products, warehouses }: Props) {
// 日期格式轉換輔助函數
const formatDate = (dateValue: string | null | undefined): string => {
if (!dateValue) return '';
// 處理可能的 ISO 格式或 YYYY-MM-DD 格式
const date = new Date(dateValue);
if (isNaN(date.getTime())) return dateValue;
return date.toISOString().split('T')[0];
};
const [selectedWarehouse, setSelectedWarehouse] = useState<string>(
productionOrder.warehouse_id ? String(productionOrder.warehouse_id) : ""
); // Output Warehouse
// Cache map: warehouse_id -> inventories
const [inventoryMap, setInventoryMap] = useState<Record<string, InventoryOption[]>>({});
const [loadingWarehouses, setLoadingWareStates] = useState<Record<string, boolean>>({});
// Helper to fetch warehouse data
const fetchWarehouseInventory = async (warehouseId: string) => {
if (!warehouseId || inventoryMap[warehouseId] || loadingWarehouses[warehouseId]) return;
setLoadingWareStates(prev => ({ ...prev, [warehouseId]: true }));
try {
const res = await fetch(route('api.production.warehouses.inventories', warehouseId));
const data = await res.json();
setInventoryMap(prev => ({ ...prev, [warehouseId]: data }));
} catch (e) {
console.error(e);
} finally {
setLoadingWareStates(prev => ({ ...prev, [warehouseId]: false }));
}
};
// 初始化 BOM items
const initialBomItems: BomItem[] = productionOrder.items.map(item => ({
inventory_id: String(item.inventory_id),
quantity_used: String(item.quantity_used),
unit_id: item.unit_id ? String(item.unit_id) : "",
// UI Initial State (復原)
ui_warehouse_id: item.inventory?.warehouse_id ? String(item.inventory.warehouse_id) : "",
ui_product_id: item.inventory ? String(item.inventory.product_id) : "",
ui_input_quantity: String(item.quantity_used), // 假設已存的資料是基本單位
ui_selected_unit: 'base',
// UI Helpers
ui_product_name: item.inventory?.product?.name,
ui_batch_number: item.inventory?.batch_number,
ui_available_qty: item.inventory?.quantity,
ui_expiry_date: item.inventory?.expiry_date,
}));
const [bomItems, setBomItems] = useState<BomItem[]>(initialBomItems);
const { data, setData, processing, errors } = useForm({
product_id: String(productionOrder.product_id),
warehouse_id: productionOrder.warehouse_id ? String(productionOrder.warehouse_id) : "",
output_quantity: productionOrder.output_quantity ? String(productionOrder.output_quantity) : "",
output_batch_number: productionOrder.output_batch_number || "",
output_box_count: productionOrder.output_box_count || "",
production_date: formatDate(productionOrder.production_date) || new Date().toISOString().split('T')[0],
expiry_date: formatDate(productionOrder.expiry_date),
remark: productionOrder.remark || "",
items: [] as { inventory_id: number; quantity_used: number; unit_id: number | null }[],
});
// 初始化載入既有 BOM 的來源倉庫資料
useEffect(() => {
initialBomItems.forEach(item => {
if (item.ui_warehouse_id) {
fetchWarehouseInventory(item.ui_warehouse_id);
}
});
}, []);
// 當 inventoryOptions (Map) 載入後,更新現有 BOM items 的詳細資訊 (如單位、轉換率)
// 監聽 inventoryMap 變更
useEffect(() => {
setBomItems(prevItems => prevItems.map(item => {
if (item.ui_warehouse_id && inventoryMap[item.ui_warehouse_id] && item.inventory_id && !item.ui_conversion_rate) {
const inv = inventoryMap[item.ui_warehouse_id].find(i => String(i.id) === item.inventory_id);
if (inv) {
return {
...item,
ui_product_id: String(inv.product_id),
ui_product_name: inv.product_name,
ui_batch_number: inv.batch_number,
ui_available_qty: inv.quantity,
ui_expiry_date: inv.expiry_date || '',
ui_base_unit_name: inv.base_unit_name || inv.unit_name || '',
ui_large_unit_name: inv.large_unit_name || '',
ui_base_unit_id: inv.base_unit_id,
ui_large_unit_id: inv.large_unit_id,
ui_conversion_rate: inv.conversion_rate || 1,
};
}
}
return item;
}));
}, [inventoryMap]);
// 同步 warehouse_id 到 form data
useEffect(() => {
setData('warehouse_id', selectedWarehouse);
}, [selectedWarehouse]);
// 新增 BOM 項目
const addBomItem = () => {
setBomItems([...bomItems, {
inventory_id: "",
quantity_used: "",
unit_id: "",
ui_warehouse_id: "",
ui_product_id: "",
ui_input_quantity: "",
ui_selected_unit: 'base',
}]);
};
// 移除 BOM 項目
const removeBomItem = (index: number) => {
setBomItems(bomItems.filter((_, i) => i !== index));
};
// 更新 BOM 項目邏輯
const updateBomItem = (index: number, field: keyof BomItem, value: any) => {
const updated = [...bomItems];
const item = { ...updated[index], [field]: value };
// 0. 當選擇來源倉庫變更時
if (field === 'ui_warehouse_id') {
item.ui_product_id = "";
item.inventory_id = "";
item.quantity_used = "";
item.unit_id = "";
item.ui_input_quantity = "";
item.ui_selected_unit = "base";
delete item.ui_product_name;
delete item.ui_batch_number;
delete item.ui_available_qty;
delete item.ui_expiry_date;
delete item.ui_conversion_rate;
delete item.ui_base_unit_name;
delete item.ui_large_unit_name;
delete item.ui_base_unit_id;
delete item.ui_large_unit_id;
if (value) {
fetchWarehouseInventory(value);
}
}
// 1. 當選擇商品變更時 -> 清空批號與相關資訊
if (field === 'ui_product_id') {
item.inventory_id = "";
item.quantity_used = "";
item.unit_id = "";
item.ui_input_quantity = "";
item.ui_selected_unit = "base";
delete item.ui_product_name;
delete item.ui_batch_number;
delete item.ui_available_qty;
delete item.ui_expiry_date;
delete item.ui_conversion_rate;
delete item.ui_base_unit_name;
delete item.ui_large_unit_name;
delete item.ui_base_unit_id;
delete item.ui_large_unit_id;
}
// 2. 當選擇批號變更時
if (field === 'inventory_id' && value) {
const currentOptions = inventoryMap[item.ui_warehouse_id] || [];
const inv = currentOptions.find(i => String(i.id) === value);
if (inv) {
item.ui_product_id = String(inv.product_id);
item.ui_product_name = inv.product_name;
item.ui_batch_number = inv.batch_number;
item.ui_available_qty = inv.quantity;
item.ui_expiry_date = inv.expiry_date || '';
item.ui_base_unit_name = inv.base_unit_name || inv.unit_name || '';
item.ui_large_unit_name = inv.large_unit_name || '';
item.ui_base_unit_id = inv.base_unit_id;
item.ui_large_unit_id = inv.large_unit_id;
item.ui_conversion_rate = inv.conversion_rate || 1;
item.ui_selected_unit = 'base';
item.unit_id = String(inv.base_unit_id || '');
}
}
// 3. 計算最終數量
if (field === 'ui_input_quantity' || field === 'ui_selected_unit' || field === 'inventory_id') {
const inputQty = parseFloat(item.ui_input_quantity || '0');
const rate = item.ui_conversion_rate || 1;
if (item.ui_selected_unit === 'large') {
item.quantity_used = String(inputQty * rate);
item.unit_id = String(item.ui_base_unit_id || '');
} else {
item.quantity_used = String(inputQty);
item.unit_id = String(item.ui_base_unit_id || '');
}
}
updated[index] = item;
setBomItems(updated);
};
// 同步 BOM items 到表單 data
useEffect(() => {
setData('items', bomItems.map(item => ({
inventory_id: Number(item.inventory_id),
quantity_used: Number(item.quantity_used),
unit_id: item.unit_id ? Number(item.unit_id) : null
})));
}, [bomItems]);
// 提交表單(完成模式)
// 提交表單(完成模式)
// 提交表單(完成模式)
const submit = (status: 'draft' | 'completed') => {
// 驗證(簡單前端驗證)
if (status === 'completed') {
const missingFields = [];
if (!data.product_id) missingFields.push('成品商品');
if (!data.output_quantity) missingFields.push('生產數量');
if (!data.output_batch_number) missingFields.push('成品批號');
if (!data.production_date) missingFields.push('生產日期');
if (!selectedWarehouse) missingFields.push('入庫倉庫');
if (bomItems.length === 0) missingFields.push('原物料明細');
if (missingFields.length > 0) {
toast.error(
<div className="flex flex-col gap-1">
<span className="font-bold"></span>
<span className="text-sm">{missingFields.join('、')}</span>
</div>
);
return;
}
}
const formattedItems = bomItems
.filter(item => status === 'draft' || (item.inventory_id && item.quantity_used))
.map(item => ({
inventory_id: item.inventory_id ? parseInt(item.inventory_id) : null,
quantity_used: item.quantity_used ? parseFloat(item.quantity_used) : 0,
unit_id: item.unit_id ? parseInt(item.unit_id) : null,
}));
router.put(route('production-orders.update', productionOrder.id), {
...data,
items: formattedItems,
status: status,
}, {
onError: (errors) => {
const errorCount = Object.keys(errors).length;
toast.error(
<div className="flex flex-col gap-1">
<span className="font-bold"></span>
<span className="text-sm"> {errorCount} </span>
</div>
);
}
});
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
submit('completed');
};
return (
<AuthenticatedLayout breadcrumbs={getBreadcrumbs("productionOrdersCreate")}>
<Head title={`編輯生產單 - ${productionOrder.code}`} />
<Toaster position="top-right" />
<div className="container mx-auto p-6 max-w-7xl">
<div className="mb-6">
<Link href={route('production-orders.index')}>
<Button
variant="outline"
className="gap-2 button-outlined-primary mb-6"
>
<ArrowLeft className="h-4 w-4" />
</Button>
</Link>
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<Factory className="h-6 w-6 text-primary-main" />
</h1>
<p className="text-gray-500 mt-1">
</p>
</div>
<div className="flex gap-2">
<Button
onClick={() => submit('draft')}
disabled={processing}
variant="outline"
className="button-outlined-primary"
>
<Save className="mr-2 h-4 w-4" />
稿
</Button>
<Button
onClick={() => submit('completed')}
disabled={processing}
className="button-filled-primary"
>
<Factory className="mr-2 h-4 w-4" />
</Button>
</div>
</div>
</div>
<form onSubmit={handleSubmit} className="space-y-6">
{/* 成品資訊 */}
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200 mb-6">
<h2 className="text-lg font-semibold mb-4"></h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-1">
<Label className="text-xs font-medium text-grey-2"> *</Label>
<SearchableSelect
value={data.product_id}
onValueChange={(v) => setData('product_id', v)}
options={products.map(p => ({
label: `${p.name} (${p.code})`,
value: String(p.id),
}))}
placeholder="選擇成品"
className="w-full h-9"
/>
{errors.product_id && <p className="text-red-500 text-xs mt-1">{errors.product_id}</p>}
</div>
<div className="space-y-1">
<Label className="text-xs font-medium text-grey-2"> *</Label>
<Input
type="number"
step="0.01"
value={data.output_quantity}
onChange={(e) => setData('output_quantity', e.target.value)}
placeholder="例如: 50"
className="h-9"
/>
{errors.output_quantity && <p className="text-red-500 text-xs mt-1">{errors.output_quantity}</p>}
</div>
<div className="space-y-1">
<Label className="text-xs font-medium text-grey-2"> *</Label>
<Input
value={data.output_batch_number}
onChange={(e) => setData('output_batch_number', e.target.value)}
placeholder="例如: AB-TW-20260122-01"
className="h-9 font-mono"
/>
{errors.output_batch_number && <p className="text-red-500 text-xs mt-1">{errors.output_batch_number}</p>}
</div>
<div className="space-y-1">
<Label className="text-xs font-medium text-grey-2"></Label>
<Input
value={data.output_box_count}
onChange={(e) => setData('output_box_count', e.target.value)}
placeholder="例如: 10"
className="h-9"
/>
</div>
<div className="space-y-1">
<Label className="text-xs font-medium text-grey-2"> *</Label>
<div className="relative">
<Calendar className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
<Input
type="date"
value={data.production_date}
onChange={(e) => setData('production_date', e.target.value)}
className="h-9 pl-9"
/>
</div>
{errors.production_date && <p className="text-red-500 text-xs mt-1">{errors.production_date}</p>}
</div>
<div className="space-y-1">
<Label className="text-xs font-medium text-grey-2"></Label>
<div className="relative">
<Calendar className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
<Input
type="date"
value={data.expiry_date}
onChange={(e) => setData('expiry_date', e.target.value)}
className="h-9 pl-9"
/>
</div>
</div>
<div className="space-y-1">
<Label className="text-xs font-medium text-grey-2"> *</Label>
<SearchableSelect
value={selectedWarehouse}
onValueChange={setSelectedWarehouse}
options={warehouses.map(w => ({
label: w.name,
value: String(w.id),
}))}
placeholder="選擇倉庫"
className="w-full h-9"
/>
{errors.warehouse_id && <p className="text-red-500 text-xs mt-1">{errors.warehouse_id}</p>}
</div>
</div>
<div className="mt-4 space-y-1">
<Label className="text-xs font-medium text-grey-2"></Label>
<Textarea
value={data.remark}
onChange={(e) => setData('remark', e.target.value)}
placeholder="生產備註..."
rows={2}
className="resize-none"
/>
</div>
</div>
{/* BOM 原物料明細 */}
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200 mb-6">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold">使 (BOM)</h2>
<Button
type="button"
variant="outline"
onClick={addBomItem}
className="gap-2 button-filled-primary text-white"
>
<Plus className="h-4 w-4" />
</Button>
</div>
{bomItems.length === 0 && (
<div className="text-center py-8 text-gray-500">
<Factory className="h-8 w-8 mx-auto mb-2 text-gray-300" />
BOM
</div>
)}
{bomItems.length > 0 && (
<div className="border rounded-lg overflow-hidden">
<Table>
<TableHeader>
<TableRow className="bg-gray-50/50">
<TableHead className="w-[20%]"> <span className="text-red-500">*</span></TableHead>
<TableHead className="w-[20%]"> <span className="text-red-500">*</span></TableHead>
<TableHead className="w-[25%]"> <span className="text-red-500">*</span></TableHead>
<TableHead className="w-[15%]"> <span className="text-red-500">*</span></TableHead>
<TableHead className="w-[15%]"></TableHead>
<TableHead className="w-[5%]"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{bomItems.map((item, index) => {
// 取得此列已載入的 Inventory Options
const currentOptions = inventoryMap[item.ui_warehouse_id] || [];
const uniqueProductOptions = Array.from(new Map(
currentOptions.map(inv => [inv.product_id, { label: inv.product_name, value: String(inv.product_id) }])
).values());
// Fallback for initial state before fetch
const displayProductOptions = uniqueProductOptions.length > 0 ? uniqueProductOptions : (item.ui_product_name ? [{ label: item.ui_product_name, value: item.ui_product_id }] : []);
const batchOptions = currentOptions
.filter(inv => String(inv.product_id) === item.ui_product_id)
.map(inv => ({
label: `${inv.batch_number} / ${inv.expiry_date || '無效期'} / ${inv.quantity}`,
value: String(inv.id)
}));
// Fallback
const displayBatchOptions = batchOptions.length > 0 ? batchOptions : (item.inventory_id && item.ui_batch_number ? [{ label: item.ui_batch_number, value: item.inventory_id }] : []);
return (
<TableRow key={index}>
{/* 0. 選擇來源倉庫 */}
<TableCell className="align-top">
<SearchableSelect
value={item.ui_warehouse_id}
onValueChange={(v) => updateBomItem(index, 'ui_warehouse_id', v)}
options={warehouses.map(w => ({ label: w.name, value: String(w.id) }))}
placeholder="選擇倉庫"
className="w-full"
/>
</TableCell>
{/* 1. 選擇商品 */}
<TableCell className="align-top">
<SearchableSelect
value={item.ui_product_id}
onValueChange={(v) => updateBomItem(index, 'ui_product_id', v)}
options={displayProductOptions}
placeholder="選擇商品"
className="w-full"
disabled={!item.ui_warehouse_id}
/>
</TableCell>
{/* 2. 選擇批號 */}
<TableCell className="align-top">
<SearchableSelect
value={item.inventory_id}
onValueChange={(v) => updateBomItem(index, 'inventory_id', v)}
options={displayBatchOptions}
placeholder={item.ui_product_id ? "選擇批號" : "請先選商品"}
className="w-full"
disabled={!item.ui_product_id}
/>
{item.inventory_id && (() => {
const selectedInv = currentOptions.find(i => String(i.id) === item.inventory_id);
if (selectedInv) return (
<div className="text-xs text-gray-500 mt-1">
: {selectedInv.expiry_date || '無'} | : {selectedInv.quantity}
</div>
);
return null;
})()}
</TableCell>
{/* 3. 輸入數量 */}
<TableCell className="align-top">
<Input
type="number"
step="1"
value={item.ui_input_quantity}
onChange={(e) => updateBomItem(index, 'ui_input_quantity', e.target.value)}
placeholder="0"
className="h-9"
disabled={!item.inventory_id}
/>
</TableCell>
{/* 4. 選擇單位 */}
<TableCell className="align-top pt-3">
<span className="text-sm">{item.ui_base_unit_name}</span>
</TableCell>
<TableCell className="align-top">
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => removeBomItem(index)}
className="text-red-500 hover:text-red-700 hover:bg-red-50 p-2"
>
<Trash2 className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
)}
{errors.items && <p className="text-red-500 text-sm mt-2">{errors.items}</p>}
</div>
</form>
</div>
</AuthenticatedLayout>
);
}

View File

@@ -3,7 +3,7 @@
*/
import { useState, useEffect } from "react";
import { Plus, Factory, Search, RotateCcw, Eye } from 'lucide-react';
import { Plus, Factory, Search, RotateCcw, Eye, Pencil } from 'lucide-react';
import { Button } from "@/Components/ui/button";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, router, Link } from "@inertiajs/react";
@@ -239,15 +239,29 @@ export default function ProductionIndex({ productionOrders, filters }: Props) {
</Badge>
</TableCell>
<TableCell className="text-center">
<div className="flex items-center justify-center">
<div className="flex items-center justify-center gap-2">
{order.status === 'draft' && (
<Can permission="production_orders.edit">
<Link href={route('production-orders.edit', order.id)}>
<Button
variant="outline"
size="sm"
className="button-outlined-primary"
title="編輯"
>
<Pencil className="h-4 w-4" />
</Button>
</Link>
</Can>
)}
<Link href={route('production-orders.show', order.id)}>
<Button
variant="outline"
size="sm"
className="button-outlined-primary h-8"
className="button-outlined-primary"
title="檢視"
>
<Eye className="h-4 w-4 mr-1" />
<Eye className="h-4 w-4" />
</Button>
</Link>
</div>

View File

@@ -6,7 +6,7 @@
import { Factory, ArrowLeft, Package, Calendar, User, Warehouse, FileText, Link2 } from 'lucide-react';
import { Button } from "@/Components/ui/button";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, router, Link } from "@inertiajs/react";
import { Head, Link } from "@inertiajs/react";
import { getBreadcrumbs } from "@/utils/breadcrumb";
import { Badge } from "@/Components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/Components/ui/table";
@@ -61,16 +61,19 @@ export default function ProductionShow({ productionOrder }: Props) {
return (
<AuthenticatedLayout breadcrumbs={getBreadcrumbs("productionOrdersShow")}>
<Head title={`生產單 ${productionOrder.code}`} />
<div className="container mx-auto p-6 max-w-4xl">
<div className="flex items-center gap-4 mb-6">
<div className="container mx-auto p-6 max-w-7xl">
<div className="mb-6">
<Link href={route('production-orders.index')}>
<Button
variant="ghost"
onClick={() => router.get(route('production-orders.index'))}
className="p-2"
variant="outline"
className="gap-2 button-outlined-primary mb-6"
>
<ArrowLeft className="h-5 w-5" />
<ArrowLeft className="h-4 w-4" />
</Button>
<div className="flex-1">
</Link>
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<Factory className="h-6 w-6 text-primary-main" />
{productionOrder.code}
@@ -79,10 +82,11 @@ export default function ProductionShow({ productionOrder }: Props) {
</p>
</div>
<Badge variant={statusConfig[productionOrder.status]?.variant || "secondary"}>
<Badge variant={statusConfig[productionOrder.status]?.variant || "secondary"} className="text-sm">
{statusConfig[productionOrder.status]?.label || productionOrder.status}
</Badge>
</div>
</div>
{/* 成品資訊 */}
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200 mb-6">

View File

@@ -2,7 +2,7 @@
* 新增庫存頁面(手動入庫)
*/
import { useState } from "react";
import { useState, useEffect } from "react";
import { Plus, Trash2, Calendar, ArrowLeft, Save, Boxes } from "lucide-react";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
@@ -27,11 +27,21 @@ import { getInventoryBreadcrumbs } from "@/utils/breadcrumb";
interface Product {
id: string;
name: string;
code: string;
baseUnit: string;
largeUnit?: string;
conversionRate?: number;
}
interface Batch {
inventoryId: string;
batchNumber: string;
originCountry: string;
expiryDate: string | null;
quantity: number;
isDeleted?: boolean;
}
interface Props {
warehouse: Warehouse;
products: Product[];
@@ -51,10 +61,61 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
const [notes, setNotes] = useState("");
const [items, setItems] = useState<InboundItem[]>([]);
const [errors, setErrors] = useState<Record<string, string>>({});
const [batchesCache, setBatchesCache] = useState<Record<string, { batches: Batch[], nextSequences: Record<string, string> }>>({});
// 取得商品批號與流水號
const fetchProductBatches = async (productId: string, originCountry?: string, arrivalDate?: string) => {
if (!productId) return;
const country = originCountry || 'TW';
const date = arrivalDate || inboundDate.split('T')[0];
const cacheKey = `${country}_${date}`;
// 如果該商品的批號列表尚未載入,強制載入
const existingCache = batchesCache[productId];
const hasBatches = existingCache && existingCache.batches.length >= 0 && existingCache.batches !== undefined;
const hasThisSequence = existingCache?.nextSequences?.[cacheKey];
// 若 batches 尚未載入,或特定條件的 sequence 尚未載入,則呼叫 API
if (!hasBatches || !hasThisSequence) {
try {
const response = await fetch(`/api/warehouses/${warehouse.id}/inventory/batches/${productId}?originCountry=${country}&arrivalDate=${date}`);
const data = await response.json();
setBatchesCache(prev => {
const existingProductCache = prev[productId] || { batches: [], nextSequences: {} };
return {
...prev,
[productId]: {
batches: data.batches,
nextSequences: {
...existingProductCache.nextSequences,
[cacheKey]: data.nextSequence
}
}
};
});
} catch (error) {
console.error("Failed to fetch batches", error);
}
}
};
// 當 items 變動、日期變動時,確保資料同步
useEffect(() => {
items.forEach(item => {
if (item.productId) {
// 無論 batchMode 為何,都要載入批號列表
// 若使用者切換到 new 模式,則額外傳入 originCountry 以取得正確流水號
const country = item.batchMode === 'new' ? item.originCountry : undefined;
fetchProductBatches(item.productId, country, inboundDate.split('T')[0]);
}
});
}, [items, inboundDate]);
// 新增明細行
const handleAddItem = () => {
const defaultProduct = products.length > 0 ? products[0] : { id: "", name: "", baseUnit: "個" };
const defaultProduct = products.length > 0 ? products[0] : { id: "", name: "", code: "", baseUnit: "個" };
const newItem: InboundItem = {
tempId: `temp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
productId: defaultProduct.id,
@@ -65,6 +126,8 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
largeUnit: defaultProduct.largeUnit,
conversionRate: defaultProduct.conversionRate,
selectedUnit: 'base',
batchMode: 'existing', // 預設選擇現有批號
originCountry: 'TW',
};
setItems([...items, newItem]);
};
@@ -96,6 +159,9 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
largeUnit: product.largeUnit,
conversionRate: product.conversionRate,
selectedUnit: 'base',
batchMode: 'existing',
inventoryId: undefined, // 清除已選擇的批號
expiryDate: undefined,
});
}
};
@@ -123,6 +189,12 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
if (item.quantity <= 0) {
newErrors[`item-${index}-quantity`] = "數量必須大於 0";
}
if (item.batchMode === 'existing' && !item.inventoryId) {
newErrors[`item-${index}-batch`] = "請選擇批號";
}
if (item.batchMode === 'new' && !item.originCountry) {
newErrors[`item-${index}-country`] = "新批號必須輸入產地";
}
});
setErrors(newErrors);
@@ -149,7 +221,9 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
return {
productId: item.productId,
quantity: finalQuantity,
batchNumber: item.batchNumber,
batchMode: item.batchMode,
inventoryId: item.inventoryId,
originCountry: item.originCountry,
expiryDate: item.expiryDate
};
})
@@ -165,6 +239,24 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
});
};
// 生成批號預覽
const getBatchPreview = (productId: string | undefined, productCode: string | undefined, country: string, dateStr: string) => {
if (!productCode || !productId) return "--";
try {
// 直接字串處理,避免時區問題且確保與 fetchProductBatches 的 key 一致
const datePart = dateStr.includes('T') ? dateStr.split('T')[0] : dateStr;
const [yyyy, mm, dd] = datePart.split('-');
const dateFormatted = `${yyyy}${mm}${dd}`;
const cacheKey = `${country}_${datePart}`;
const seq = batchesCache[productId]?.nextSequences?.[cacheKey] || "XX";
return `${productCode}-${country}-${dateFormatted}-${seq}`;
} catch (e) {
return "--";
}
};
return (
<AuthenticatedLayout breadcrumbs={getInventoryBreadcrumbs(warehouse.id, warehouse.name, "手動入庫")}>
<Head title={`新增庫存 - ${warehouse.name}`} />
@@ -301,17 +393,19 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
<Table>
<TableHeader>
<TableRow className="bg-gray-50/50">
<TableHead className="w-[280px]">
<TableHead className="w-[180px]">
<span className="text-red-500">*</span>
</TableHead>
<TableHead className="w-[120px]">
<TableHead className="w-[220px]">
<span className="text-red-500">*</span>
</TableHead>
<TableHead className="w-[100px]">
<span className="text-red-500">*</span>
</TableHead>
<TableHead className="w-[100px]"></TableHead>
<TableHead className="w-[150px]"></TableHead>
<TableHead className="w-[180px]"></TableHead>
<TableHead className="w-[220px]"></TableHead>
<TableHead className="w-[60px]"></TableHead>
<TableHead className="w-[90px]"></TableHead>
<TableHead className="w-[100px]"></TableHead>
<TableHead className="w-[140px]"></TableHead>
<TableHead className="w-[50px]"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -321,6 +415,9 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
? item.quantity * item.conversionRate
: item.quantity;
// Find product code
const product = products.find(p => p.id === item.productId);
return (
<TableRow key={item.tempId}>
{/* 商品 */}
@@ -342,6 +439,73 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
)}
</TableCell>
{/* 批號與產地控制 */}
<TableCell>
<div className="space-y-2">
<SearchableSelect
value={item.batchMode === 'new' ? 'new_batch' : (item.inventoryId || "")}
onValueChange={(value) => {
if (value === 'new_batch') {
handleUpdateItem(item.tempId, {
batchMode: 'new',
inventoryId: undefined,
originCountry: 'TW',
expiryDate: undefined
});
} else {
const selectedBatch = (batchesCache[item.productId]?.batches || []).find(b => b.inventoryId === value);
handleUpdateItem(item.tempId, {
batchMode: 'existing',
inventoryId: value,
originCountry: selectedBatch?.originCountry,
expiryDate: selectedBatch?.expiryDate || undefined
});
}
}}
options={[
{ label: "+ 建立新批號", value: "new_batch" },
...(batchesCache[item.productId]?.batches || []).map(b => ({
label: `${b.batchNumber} - 庫存: ${b.quantity}`,
value: b.inventoryId
}))
]}
placeholder="選擇或新增批號"
className="border-gray-300"
/>
{errors[`item-${index}-batch`] && (
<p className="text-xs text-red-500">
{errors[`item-${index}-batch`]}
</p>
)}
{item.batchMode === 'new' && (
<div className="flex items-center gap-2 mt-2">
<div className="flex-1">
<Input
value={item.originCountry || ""}
onChange={(e) => {
const val = e.target.value.toUpperCase().slice(0, 2);
handleUpdateItem(item.tempId, { originCountry: val });
}}
maxLength={2}
placeholder="產地"
className="h-8 text-xs text-center border-gray-300"
/>
</div>
<div className="flex-[3] text-xs bg-primary-50/50 text-primary-main px-2 py-1 rounded border border-primary-200/50 font-mono overflow-hidden whitespace-nowrap">
{getBatchPreview(item.productId, product?.code, item.originCountry || 'TW', inboundDate)}
</div>
</div>
)}
{item.batchMode === 'existing' && item.inventoryId && (
<div className="text-xs text-gray-500 px-2 font-mono">
: {item.expiryDate || '未設定'}
</div>
)}
</div>
</TableCell>
{/* 數量 */}
<TableCell>
<Input
@@ -408,30 +572,12 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
expiryDate: e.target.value,
})
}
className="border-gray-300 pl-9"
disabled={item.batchMode === 'existing'}
className={`border-gray-300 pl-9 ${item.batchMode === 'existing' ? 'bg-gray-50' : ''}`}
/>
</div>
</TableCell>
{/* 批號 */}
<TableCell>
<Input
value={item.batchNumber || ""}
onChange={(e) =>
handleUpdateItem(item.tempId, {
batchNumber: e.target.value,
})
}
className="border-gray-300"
placeholder="系統自動生成"
/>
{errors[`item-${index}-batch`] && (
<p className="text-xs text-red-500 mt-1">
{errors[`item-${index}-batch`]}
</p>
)}
</TableCell>
{/* 刪除按鈕 */}
<TableCell>
<Button

View File

@@ -94,8 +94,11 @@ export default function EditInventory({ warehouse, inventory, transactions = []
<Boxes className="h-6 w-6 text-primary-main" />
</h1>
<p className="text-gray-500 mt-1">
<span className="font-medium text-gray-900">{warehouse.name}</span>
<p className="text-gray-500 mt-1 flex gap-4">
<span><span className="font-medium text-gray-900">{warehouse.name}</span></span>
{inventory.batchNumber && (
<span><span className="font-medium text-blue-600 bg-blue-50 px-2 py-0.5 rounded border border-blue-100">{inventory.batchNumber}</span></span>
)}
</p>
</div>
<div className="flex gap-3">

View File

@@ -3,7 +3,7 @@ import { ArrowLeft, PackagePlus, AlertTriangle, Shield, Boxes } from "lucide-rea
import { Button } from "@/Components/ui/button";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, Link, router } from "@inertiajs/react";
import { Warehouse, WarehouseInventory, SafetyStockSetting, Product } from "@/types/warehouse";
import { Warehouse, GroupedInventory, SafetyStockSetting, Product } from "@/types/warehouse";
import InventoryToolbar from "@/Components/Warehouse/Inventory/InventoryToolbar";
import InventoryTable from "@/Components/Warehouse/Inventory/InventoryTable";
import { calculateLowStockCount } from "@/utils/inventory";
@@ -24,7 +24,7 @@ import { Can } from "@/Components/Permission/Can";
// 庫存頁面 Props
interface Props {
warehouse: Warehouse;
inventories: WarehouseInventory[];
inventories: GroupedInventory[];
safetyStockSettings: SafetyStockSetting[];
availableProducts: Product[];
}
@@ -41,17 +41,17 @@ export default function WarehouseInventoryPage({
// 篩選庫存列表
const filteredInventories = useMemo(() => {
return inventories.filter((item) => {
// 搜尋條件:匹配商品名稱、編號批號
return inventories.filter((group) => {
// 搜尋條件:匹配商品名稱、編號 或 該商品下任一批號
const matchesSearch = !searchTerm ||
item.productName.toLowerCase().includes(searchTerm.toLowerCase()) ||
(item.productCode && item.productCode.toLowerCase().includes(searchTerm.toLowerCase())) ||
item.batchNumber.toLowerCase().includes(searchTerm.toLowerCase());
group.productName.toLowerCase().includes(searchTerm.toLowerCase()) ||
(group.productCode && group.productCode.toLowerCase().includes(searchTerm.toLowerCase())) ||
group.batches.some(b => b.batchNumber.toLowerCase().includes(searchTerm.toLowerCase()));
// 類型篩選 (需要比對 availableProducts 找到類型)
let matchesType = true;
if (typeFilter !== "all") {
const product = availableProducts.find((p) => p.id === item.productId);
const product = availableProducts.find((p) => p.id === group.productId);
matchesType = product?.type === typeFilter;
}
@@ -60,13 +60,24 @@ export default function WarehouseInventoryPage({
}, [inventories, searchTerm, typeFilter, availableProducts]);
// 計算統計資訊
const lowStockItems = calculateLowStockCount(inventories, warehouse.id, safetyStockSettings);
const lowStockItems = useMemo(() => {
const allBatches = inventories.flatMap(g => g.batches);
return calculateLowStockCount(allBatches, warehouse.id, safetyStockSettings);
}, [inventories, warehouse.id, safetyStockSettings]);
// 導航至流動紀錄頁
const handleView = (inventoryId: string) => {
router.visit(route('warehouses.inventory.history', { warehouse: warehouse.id, inventoryId: inventoryId }));
};
// 導航至商品層級流動紀錄頁(顯示該商品所有批號的流水帳)
const handleViewProduct = (productId: string) => {
router.visit(route('warehouses.inventory.history', {
warehouse: warehouse.id,
productId: productId
}));
};
const confirmDelete = (inventoryId: string) => {
setDeleteId(inventoryId);
@@ -90,6 +101,17 @@ export default function WarehouseInventoryPage({
});
};
const handleAdjust = (batchId: string, data: { operation: string; quantity: number; reason: string }) => {
router.put(route("warehouses.inventory.update", { warehouse: warehouse.id, inventoryId: batchId }), data, {
onSuccess: () => {
toast.success("庫存已更新");
},
onError: () => {
toast.error("庫存更新失敗");
}
});
};
return (
<AuthenticatedLayout breadcrumbs={getInventoryBreadcrumbs(warehouse.id, warehouse.name)}>
<Head title={`庫存管理 - ${warehouse.name}`} />
@@ -158,7 +180,7 @@ export default function WarehouseInventoryPage({
</div>
{/* 篩選工具列 */}
<div className="mb-6 bg-white rounded-lg shadow-sm border p-4">
<div className="mb-6">
<InventoryToolbar
searchTerm={searchTerm}
onSearchChange={setSearchTerm}
@@ -173,6 +195,8 @@ export default function WarehouseInventoryPage({
inventories={filteredInventories}
onView={handleView}
onDelete={confirmDelete}
onAdjust={handleAdjust}
onViewProduct={handleViewProduct}
/>
</div>
<AlertDialog open={!!deleteId} onOpenChange={(open) => !open && setDeleteId(null)}>

View File

@@ -12,6 +12,7 @@ interface Props {
id: string;
productName: string;
productCode: string;
batchNumber?: string;
quantity: number;
};
transactions: Transaction[];
@@ -40,9 +41,12 @@ export default function InventoryHistory({ warehouse, inventory, transactions }:
<History className="h-6 w-6 text-primary-main" />
</h1>
<p className="text-gray-500 mt-1">
<span className="font-medium text-gray-900">{inventory.productName}</span>
{inventory.productCode && <span className="text-gray-500 ml-2">({inventory.productCode})</span>}
<p className="text-gray-500 mt-1 flex gap-4 items-center">
<span><span className="font-medium text-gray-900">{inventory.productName}</span></span>
{inventory.productCode && <span className="text-gray-500">({inventory.productCode})</span>}
{inventory.batchNumber && (
<span><span className="font-medium text-primary-main bg-primary-main/10 px-2 py-0.5 rounded border border-primary-main/20">{inventory.batchNumber}</span></span>
)}
</p>
</div>
</div>

View File

@@ -39,13 +39,25 @@ export interface WarehouseInventory {
unit: string;
quantity: number;
safetyStock: number | null;
status?: '正常' | '接近' | '低於'; // 後端可能回傳的狀態
status?: '正常' | '低於'; // 後端可能回傳的狀態
batchNumber: string; // 批號 (Mock for now)
expiryDate: string;
lastInboundDate: string | null;
lastOutboundDate: string | null;
}
// 依照商品分組的庫存項目 (用於庫存列表)
export interface GroupedInventory {
productId: string;
productName: string;
productCode: string;
baseUnit: string;
totalQuantity: number;
safetyStock: number | null; // 以商品層級顯示的安全庫存
status: '正常' | '低於';
batches: WarehouseInventory[]; // 該商品下的所有批號庫存
}
export type TransferOrderStatus = "待處理" | "處理中" | "已完成" | "已取消";
export interface TransferOrder {
@@ -151,7 +163,10 @@ export interface InboundItem {
largeUnit?: string;
conversionRate?: number;
selectedUnit?: 'base' | 'large';
batchMode?: 'existing' | 'new'; // 批號模式
inventoryId?: string; // 選擇現有批號時的 ID
batchNumber?: string;
originCountry?: string; // 新增產地
expiryDate?: string;
}

View File

@@ -36,10 +36,8 @@ export const getSafetyStockStatus = (
safetyStock: number | null | undefined
): SafetyStockStatus => {
if (!safetyStock || safetyStock === 0) return "正常";
const ratio = currentStock / safetyStock;
if (ratio >= 1.2) return "正常";
if (ratio >= 1.0) return "接近";
return "低於";
if (currentStock < safetyStock) return "低於";
return "正常";
};
/**

View File

@@ -84,7 +84,7 @@ Route::middleware('auth')->group(function () {
// 倉庫庫存管理 - 需要庫存權限
Route::middleware('permission:inventory.view')->group(function () {
Route::get('/warehouses/{warehouse}/inventory', [InventoryController::class, 'index'])->name('warehouses.inventory.index');
Route::get('/warehouses/{warehouse}/inventory/{inventoryId}/history', [InventoryController::class, 'history'])->name('warehouses.inventory.history');
Route::get('/warehouses/{warehouse}/inventory-history', [InventoryController::class, 'history'])->name('warehouses.inventory.history');
Route::middleware('permission:inventory.adjust')->group(function () {
Route::get('/warehouses/{warehouse}/inventory/create', [InventoryController::class, 'create'])->name('warehouses.inventory.create');
@@ -93,6 +93,10 @@ Route::middleware('auth')->group(function () {
Route::put('/warehouses/{warehouse}/inventory/{inventoryId}', [InventoryController::class, 'update'])->name('warehouses.inventory.update');
Route::delete('/warehouses/{warehouse}/inventory/{inventoryId}', [InventoryController::class, 'destroy'])->name('warehouses.inventory.destroy');
});
// API: 取得商品在特定倉庫的所有批號
Route::get('/api/warehouses/{warehouse}/inventory/batches/{productId}', [InventoryController::class, 'getBatches'])
->name('api.warehouses.inventory.batches');
});
// 安全庫存設定
@@ -100,8 +104,8 @@ Route::middleware('auth')->group(function () {
Route::get('/warehouses/{warehouse}/safety-stock', [SafetyStockController::class, 'index'])->name('warehouses.safety-stock.index');
Route::middleware('permission:inventory.safety_stock')->group(function () {
Route::post('/warehouses/{warehouse}/safety-stock', [SafetyStockController::class, 'store'])->name('warehouses.safety-stock.store');
Route::put('/warehouses/{warehouse}/safety-stock/{inventory}', [SafetyStockController::class, 'update'])->name('warehouses.safety-stock.update');
Route::delete('/warehouses/{warehouse}/safety-stock/{inventory}', [SafetyStockController::class, 'destroy'])->name('warehouses.safety-stock.destroy');
Route::put('/warehouses/{warehouse}/safety-stock/{safetyStock}', [SafetyStockController::class, 'update'])->name('warehouses.safety-stock.update');
Route::delete('/warehouses/{warehouse}/safety-stock/{safetyStock}', [SafetyStockController::class, 'destroy'])->name('warehouses.safety-stock.destroy');
});
});
});
@@ -163,6 +167,11 @@ Route::middleware('auth')->group(function () {
});
Route::get('/production-orders/{productionOrder}', [ProductionOrderController::class, 'show'])->name('production-orders.show');
Route::middleware('permission:production_orders.edit')->group(function () {
Route::get('/production-orders/{productionOrder}/edit', [ProductionOrderController::class, 'edit'])->name('production-orders.edit');
Route::put('/production-orders/{productionOrder}', [ProductionOrderController::class, 'update'])->name('production-orders.update');
});
});
// 生產管理 API