style: 修正盤點與盤調畫面 Table Padding 並統一 UI 規範
All checks were successful
Koori-ERP-Deploy-System / deploy-demo (push) Successful in 1m4s
Koori-ERP-Deploy-System / deploy-production (push) Has been skipped

This commit is contained in:
2026-01-28 18:04:45 +08:00
parent 852370cfe0
commit e5edad4fd0
24 changed files with 3648 additions and 102 deletions

View File

@@ -0,0 +1,208 @@
<?php
namespace App\Modules\Inventory\Controllers;
use App\Http\Controllers\Controller;
use App\Modules\Inventory\Models\InventoryAdjustDoc;
use App\Modules\Inventory\Models\InventoryCountDoc;
use App\Modules\Inventory\Models\Warehouse;
use App\Modules\Inventory\Services\AdjustService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
class AdjustDocController extends Controller
{
protected $adjustService;
public function __construct(AdjustService $adjustService)
{
$this->adjustService = $adjustService;
}
public function index(Request $request)
{
$query = InventoryAdjustDoc::query()
->with(['createdBy', 'postedBy', 'warehouse']);
// 搜尋
if ($request->filled('search')) {
$search = $request->search;
$query->where(function($q) use ($search) {
$q->where('doc_no', 'like', "%{$search}%")
->orWhere('reason', 'like', "%{$search}%")
->orWhere('remarks', 'like', "%{$search}%");
});
}
if ($request->filled('warehouse_id')) {
$query->where('warehouse_id', $request->warehouse_id);
}
$perPage = $request->input('per_page', 15);
$docs = $query->orderByDesc('created_at')
->paginate($perPage)
->withQueryString()
->through(function ($doc) {
return [
'id' => (string) $doc->id,
'doc_no' => $doc->doc_no,
'status' => $doc->status,
'warehouse_name' => $doc->warehouse->name,
'reason' => $doc->reason,
'created_at' => $doc->created_at->format('Y-m-d H:i'),
'posted_at' => $doc->posted_at ? $doc->posted_at->format('Y-m-d H:i') : '-',
'created_by' => $doc->createdBy?->name,
'remarks' => $doc->remarks,
];
});
return Inertia::render('Inventory/Adjust/Index', [
'docs' => $docs,
'warehouses' => Warehouse::all()->map(fn($w) => ['id' => (string)$w->id, 'name' => $w->name]),
'filters' => $request->only(['warehouse_id', 'search', 'per_page']),
]);
}
public function store(Request $request)
{
// 模式 1: 從盤點單建立
if ($request->filled('count_doc_id')) {
$countDoc = InventoryCountDoc::findOrFail($request->count_doc_id);
// 檢查是否已存在對應的盤調單 (避免重複建立)
if (InventoryAdjustDoc::where('count_doc_id', $countDoc->id)->exists()) {
return redirect()->back()->with('error', '此盤點單已建立過盤調單');
}
$doc = $this->adjustService->createFromCountDoc($countDoc, auth()->id());
return redirect()->route('inventory.adjust.show', [$doc->id])
->with('success', '已從盤點單生成盤調單');
}
// 模式 2: 一般手動調整 (保留原始邏輯但更新訊息)
$validated = $request->validate([
'warehouse_id' => 'required',
'reason' => 'required|string',
'remarks' => 'nullable|string',
]);
$doc = $this->adjustService->createDoc(
$validated['warehouse_id'],
$validated['reason'],
$validated['remarks'],
auth()->id()
);
return redirect()->route('inventory.adjust.show', [$doc->id])
->with('success', '已建立盤調單');
}
/**
* API: 獲取可盤調的已完成盤點單 (支援掃描單號)
*/
public function getPendingCounts(Request $request)
{
$query = InventoryCountDoc::where('status', 'completed')
->whereNotExists(function ($query) {
$query->select(DB::raw(1))
->from('inventory_adjust_docs')
->whereColumn('inventory_adjust_docs.count_doc_id', 'inventory_count_docs.id');
});
if ($request->filled('search')) {
$search = $request->search;
$query->where('doc_no', 'like', "%{$search}%");
}
$counts = $query->limit(10)->get()->map(function($c) {
return [
'id' => (string)$c->id,
'doc_no' => $c->doc_no,
'warehouse_name' => $c->warehouse->name,
'completed_at' => $c->completed_at->format('Y-m-d H:i'),
];
});
return response()->json($counts);
}
public function show(InventoryAdjustDoc $doc)
{
$doc->load(['items.product.baseUnit', 'createdBy', 'postedBy', 'warehouse']);
$docData = [
'id' => (string) $doc->id,
'doc_no' => $doc->doc_no,
'warehouse_id' => (string) $doc->warehouse_id,
'warehouse_name' => $doc->warehouse->name,
'status' => $doc->status,
'reason' => $doc->reason,
'remarks' => $doc->remarks,
'created_at' => $doc->created_at->format('Y-m-d H:i'),
'created_by' => $doc->createdBy?->name,
'items' => $doc->items->map(function ($item) {
return [
'id' => (string) $item->id,
'product_id' => (string) $item->product_id,
'product_name' => $item->product->name,
'product_code' => $item->product->code,
'batch_number' => $item->batch_number,
'unit' => $item->product->baseUnit?->name,
'qty_before' => (float) $item->qty_before,
'adjust_qty' => (float) $item->adjust_qty,
'notes' => $item->notes,
];
}),
];
return Inertia::render('Inventory/Adjust/Show', [
'doc' => $docData,
]);
}
public function update(Request $request, InventoryAdjustDoc $doc)
{
if ($doc->status !== 'draft') {
return redirect()->back()->with('error', '只能修改草稿狀態的單據');
}
// 提交 (items 更新 或 過帳)
if ($request->input('action') === 'post') {
$this->adjustService->post($doc, auth()->id());
return redirect()->route('inventory.adjust.index')
->with('success', '調整單已過帳生效');
}
// 僅儲存資料
$validated = $request->validate([
'items' => 'array',
'items.*.product_id' => 'required|exists:products,id',
'items.*.adjust_qty' => 'required|numeric', // 可以是負數
'items.*.batch_number' => 'nullable|string',
'items.*.notes' => 'nullable|string',
]);
if ($request->has('items')) {
$this->adjustService->updateItems($doc, $validated['items']);
}
// 更新表頭
$doc->update($request->only(['reason', 'remarks']));
return redirect()->back()->with('success', '儲存成功');
}
public function destroy(InventoryAdjustDoc $doc)
{
if ($doc->status !== 'draft') {
return redirect()->back()->with('error', '只能刪除草稿狀態的單據');
}
$doc->items()->delete();
$doc->delete();
return redirect()->route('inventory.adjust.index')
->with('success', '調整單已刪除');
}
}

View File

@@ -0,0 +1,158 @@
<?php
namespace App\Modules\Inventory\Controllers;
use App\Http\Controllers\Controller;
use App\Modules\Inventory\Models\InventoryCountDoc;
use App\Modules\Inventory\Models\Warehouse;
use App\Modules\Inventory\Services\CountService;
use Illuminate\Http\Request;
use Inertia\Inertia;
class CountDocController extends Controller
{
protected $countService;
public function __construct(CountService $countService)
{
$this->countService = $countService;
}
public function index(Request $request)
{
$query = InventoryCountDoc::query()
->with(['createdBy', 'completedBy', 'warehouse']);
if ($request->filled('warehouse_id')) {
$query->where('warehouse_id', $request->warehouse_id);
}
if ($request->filled('search')) {
$search = $request->search;
$query->where(function ($q) use ($search) {
$q->where('doc_no', 'like', "%{$search}%")
->orWhere('remarks', 'like', "%{$search}%");
});
}
$perPage = $request->input('per_page', 10);
if (!in_array($perPage, [10, 20, 50, 100])) {
$perPage = 15;
}
$docs = $query->orderByDesc('created_at')
->paginate($perPage)
->withQueryString()
->through(function ($doc) {
return [
'id' => (string) $doc->id,
'doc_no' => $doc->doc_no,
'status' => $doc->status,
'warehouse_name' => $doc->warehouse->name,
'snapshot_date' => $doc->snapshot_date ? $doc->snapshot_date->format('Y-m-d H:i') : '-',
'completed_at' => $doc->completed_at ? $doc->completed_at->format('Y-m-d H:i') : '-',
'created_by' => $doc->createdBy?->name,
'remarks' => $doc->remarks,
];
});
return Inertia::render('Inventory/Count/Index', [
'docs' => $docs,
'warehouses' => Warehouse::all()->map(fn($w) => ['id' => (string)$w->id, 'name' => $w->name]),
'filters' => $request->only(['warehouse_id', 'search', 'per_page']),
]);
}
public function store(Request $request)
{
$validated = $request->validate([
'warehouse_id' => 'required|exists:warehouses,id',
'remarks' => 'nullable|string|max:255',
]);
$doc = $this->countService->createDoc(
$validated['warehouse_id'],
$validated['remarks'] ?? null,
auth()->id()
);
// 自動執行快照
$this->countService->snapshot($doc);
return redirect()->route('inventory.count.show', [$doc->id])
->with('success', '已建立盤點單並完成庫存快照');
}
public function show(InventoryCountDoc $doc)
{
$doc->load(['items.product.baseUnit', 'createdBy', 'completedBy', 'warehouse']);
$docData = [
'id' => (string) $doc->id,
'doc_no' => $doc->doc_no,
'warehouse_id' => (string) $doc->warehouse_id,
'warehouse_name' => $doc->warehouse->name,
'status' => $doc->status,
'remarks' => $doc->remarks,
'snapshot_date' => $doc->snapshot_date ? $doc->snapshot_date->format('Y-m-d H:i') : null,
'created_by' => $doc->createdBy?->name,
'items' => $doc->items->map(function ($item) {
return [
'id' => (string) $item->id,
'product_name' => $item->product->name,
'product_code' => $item->product->code,
'batch_number' => $item->batch_number,
'unit' => $item->product->baseUnit?->name,
'system_qty' => (float) $item->system_qty,
'counted_qty' => is_null($item->counted_qty) ? '' : (float) $item->counted_qty,
'diff_qty' => (float) $item->diff_qty,
'notes' => $item->notes,
];
}),
];
return Inertia::render('Inventory/Count/Show', [
'doc' => $docData,
]);
}
public function update(Request $request, InventoryCountDoc $doc)
{
if ($doc->status === 'completed') {
return redirect()->back()->with('error', '此盤點單已完成,無法修改');
}
$validated = $request->validate([
'items' => 'array',
'items.*.id' => 'required|exists:inventory_count_items,id',
'items.*.counted_qty' => 'nullable|numeric|min:0',
'items.*.notes' => 'nullable|string',
]);
if (isset($validated['items'])) {
$this->countService->updateCount($doc, $validated['items']);
}
// 如果是按了 "完成盤點"
if ($request->input('action') === 'complete') {
$this->countService->complete($doc, auth()->id());
return redirect()->route('inventory.count.index')
->with('success', '盤點已完成並過帳');
}
return redirect()->back()->with('success', '暫存成功');
}
public function destroy(InventoryCountDoc $doc)
{
if ($doc->status === 'completed') {
return redirect()->back()->with('error', '已完成的盤點單無法刪除');
}
$doc->items()->delete();
$doc->delete();
return redirect()->route('inventory.count.index')
->with('success', '盤點單已刪除');
}
}

View File

@@ -3,135 +3,171 @@
namespace App\Modules\Inventory\Controllers; namespace App\Modules\Inventory\Controllers;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Modules\Inventory\Models\InventoryTransferOrder;
use App\Modules\Inventory\Models\Inventory;
use App\Modules\Inventory\Models\Warehouse; use App\Modules\Inventory\Models\Warehouse;
use App\Modules\Inventory\Services\TransferService;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; use Inertia\Inertia;
use Illuminate\Validation\ValidationException;
class TransferOrderController extends Controller class TransferOrderController extends Controller
{ {
/** protected $transferService;
* 儲存撥補單(建立調撥單並執行庫存轉移)
*/ public function __construct(TransferService $transferService)
{
$this->transferService = $transferService;
}
public function index(Request $request)
{
$query = InventoryTransferOrder::query()
->with(['fromWarehouse', 'toWarehouse', 'createdBy', 'postedBy']);
// 篩選:若有選定倉庫,則顯示該倉庫作為來源或目的地的調撥單
if ($request->filled('warehouse_id')) {
$query->where(function ($q) use ($request) {
$q->where('from_warehouse_id', $request->warehouse_id)
->orWhere('to_warehouse_id', $request->warehouse_id);
});
}
$orders = $query->orderByDesc('created_at')
->paginate(15)
->through(function ($order) {
return [
'id' => (string) $order->id,
'doc_no' => $order->doc_no,
'from_warehouse_name' => $order->fromWarehouse->name,
'to_warehouse_name' => $order->toWarehouse->name,
'status' => $order->status,
'created_at' => $order->created_at->format('Y-m-d H:i'),
'posted_at' => $order->posted_at ? $order->posted_at->format('Y-m-d H:i') : '-',
'created_by' => $order->createdBy?->name,
];
});
return Inertia::render('Inventory/Transfer/Index', [
'orders' => $orders,
'warehouses' => Warehouse::all()->map(fn($w) => ['id' => (string)$w->id, 'name' => $w->name]),
'filters' => $request->only(['warehouse_id']),
]);
}
public function store(Request $request) public function store(Request $request)
{ {
$validated = $request->validate([ $validated = $request->validate([
'sourceWarehouseId' => 'required|exists:warehouses,id', 'from_warehouse_id' => 'required|exists:warehouses,id',
'targetWarehouseId' => 'required|exists:warehouses,id|different:sourceWarehouseId', 'to_warehouse_id' => 'required|exists:warehouses,id|different:from_warehouse_id',
'productId' => 'required|exists:products,id', 'remarks' => 'nullable|string',
'quantity' => 'required|numeric|min:0.01',
'transferDate' => 'required|date',
'status' => 'required|in:待處理,處理中,已完成,已取消', // 目前僅支援立即完成或單純記錄
'notes' => 'nullable|string',
'batchNumber' => 'nullable|string', // 暫時接收,雖然 DB 可能沒存
]); ]);
return DB::transaction(function () use ($validated) { $order = $this->transferService->createOrder(
// 1. 檢查來源倉庫庫存 (精確匹配產品與批號) $validated['from_warehouse_id'],
$sourceInventory = Inventory::where('warehouse_id', $validated['sourceWarehouseId']) $validated['to_warehouse_id'],
->where('product_id', $validated['productId']) $validated['remarks'] ?? null,
->where('batch_number', $validated['batchNumber']) auth()->id()
->first(); );
if (!$sourceInventory || $sourceInventory->quantity < $validated['quantity']) { return redirect()->route('inventory.transfer.show', [$order->id])
throw ValidationException::withMessages([ ->with('success', '已建立調撥單');
'quantity' => ['來源倉庫指定批號庫存不足'], }
]);
public function show(InventoryTransferOrder $order)
{
$order->load(['items.product.baseUnit', 'fromWarehouse', 'toWarehouse', 'createdBy', 'postedBy']);
$orderData = [
'id' => (string) $order->id,
'doc_no' => $order->doc_no,
'from_warehouse_id' => (string) $order->from_warehouse_id,
'from_warehouse_name' => $order->fromWarehouse->name,
'to_warehouse_id' => (string) $order->to_warehouse_id,
'to_warehouse_name' => $order->toWarehouse->name,
'status' => $order->status,
'remarks' => $order->remarks,
'created_at' => $order->created_at->format('Y-m-d H:i'),
'created_by' => $order->createdBy?->name,
'items' => $order->items->map(function ($item) {
return [
'id' => (string) $item->id,
'product_id' => (string) $item->product_id,
'product_name' => $item->product->name,
'product_code' => $item->product->code,
'batch_number' => $item->batch_number,
'unit' => $item->product->baseUnit?->name,
'quantity' => (float) $item->quantity,
'notes' => $item->notes,
];
}),
];
return Inertia::render('Inventory/Transfer/Show', [
'order' => $orderData,
]);
}
public function update(Request $request, InventoryTransferOrder $order)
{
if ($order->status !== 'draft') {
return redirect()->back()->with('error', '只能修改草稿狀態的單據');
}
if ($request->input('action') === 'post') {
try {
$this->transferService->post($order, auth()->id());
return redirect()->route('inventory.transfer.index')
->with('success', '調撥單已過帳完成');
} catch (\Exception $e) {
return redirect()->back()->withErrors(['items' => $e->getMessage()]);
} }
}
// 2. 獲取或建立目標倉庫庫存 (精確匹配產品與批號,並繼承效期與品質狀態) $validated = $request->validate([
$targetInventory = Inventory::firstOrCreate( 'items' => 'array',
[ 'items.*.product_id' => 'required|exists:products,id',
'warehouse_id' => $validated['targetWarehouseId'], 'items.*.quantity' => 'required|numeric|min:0.01',
'product_id' => $validated['productId'], 'items.*.batch_number' => 'nullable|string',
'batch_number' => $validated['batchNumber'], 'items.*.notes' => 'nullable|string',
], ]);
[
'quantity' => 0,
'unit_cost' => $sourceInventory->unit_cost, // 繼承成本
'total_value' => 0,
'expiry_date' => $sourceInventory->expiry_date,
'quality_status' => $sourceInventory->quality_status,
'origin_country' => $sourceInventory->origin_country,
]
);
$sourceWarehouse = Warehouse::find($validated['sourceWarehouseId']); if ($request->has('items')) {
$targetWarehouse = Warehouse::find($validated['targetWarehouseId']); $this->transferService->updateItems($order, $validated['items']);
}
// 3. 執行庫存轉移 (扣除來源) $order->update($request->only(['remarks']));
$oldSourceQty = $sourceInventory->quantity;
$newSourceQty = $oldSourceQty - $validated['quantity'];
// 設定活動紀錄原因
$sourceInventory->activityLogReason = "撥補出庫 至 {$targetWarehouse->name}";
$sourceInventory->quantity = $newSourceQty;
$sourceInventory->total_value = $sourceInventory->quantity * $sourceInventory->unit_cost; // 更新總值
$sourceInventory->save();
// 記錄來源異動 return redirect()->back()->with('success', '儲存成功');
$sourceInventory->transactions()->create([ }
'type' => '撥補出庫',
'quantity' => -$validated['quantity'],
'unit_cost' => $sourceInventory->unit_cost, // 記錄
'balance_before' => $oldSourceQty,
'balance_after' => $newSourceQty,
'reason' => "撥補至 {$targetWarehouse->name}" . ($validated['notes'] ? " ({$validated['notes']})" : ""),
'actual_time' => $validated['transferDate'],
'user_id' => auth()->id(),
]);
// 4. 執行庫存轉移 (增加目標) public function destroy(InventoryTransferOrder $order)
$oldTargetQty = $targetInventory->quantity; {
$newTargetQty = $oldTargetQty + $validated['quantity']; if ($order->status !== 'draft') {
return redirect()->back()->with('error', '只能刪除草稿狀態的單據');
}
$order->items()->delete();
$order->delete();
// 設定活動紀錄原因 return redirect()->route('inventory.transfer.index')
$targetInventory->activityLogReason = "撥補入庫 來自 {$sourceWarehouse->name}"; ->with('success', '調撥單已刪除');
// 確保目標庫存也有成本 (如果是繼承來的)
if ($targetInventory->unit_cost == 0 && $sourceInventory->unit_cost > 0) {
$targetInventory->unit_cost = $sourceInventory->unit_cost;
}
$targetInventory->quantity = $newTargetQty;
$targetInventory->total_value = $targetInventory->quantity * $targetInventory->unit_cost; // 更新總值
$targetInventory->save();
// 記錄目標異動
$targetInventory->transactions()->create([
'type' => '撥補入庫',
'quantity' => $validated['quantity'],
'unit_cost' => $targetInventory->unit_cost, // 記錄
'balance_before' => $oldTargetQty,
'balance_after' => $newTargetQty,
'reason' => "來自 {$sourceWarehouse->name} 的撥補" . ($validated['notes'] ? " ({$validated['notes']})" : ""),
'actual_time' => $validated['transferDate'],
'user_id' => auth()->id(),
]);
// TODO: 未來若有獨立的 TransferOrder 模型,可在此建立紀錄
return redirect()->back()->with('success', '撥補單已建立且庫存已轉移');
});
} }
/** /**
* 獲取特定倉庫的庫存列表 (API) * 獲取特定倉庫的庫存列表 (API) - 保留給前端選擇商品用
*/ */
public function getWarehouseInventories(Warehouse $warehouse) public function getWarehouseInventories(Warehouse $warehouse)
{ {
$inventories = $warehouse->inventories() $inventories = $warehouse->inventories()
->with(['product.baseUnit', 'product.category']) ->with(['product.baseUnit', 'product.category'])
->where('quantity', '>', 0) // 只回傳有庫存的 ->where('quantity', '>', 0)
->get() ->get()
->map(function ($inv) { ->map(function ($inv) {
return [ return [
'product_id' => (string) $inv->product_id, 'product_id' => (string) $inv->product_id,
'product_name' => $inv->product->name, 'product_name' => $inv->product->name,
'product_code' => $inv->product->code, // Added code
'batch_number' => $inv->batch_number, 'batch_number' => $inv->batch_number,
'quantity' => (float) $inv->quantity, 'quantity' => (float) $inv->quantity,
'unit_cost' => (float) $inv->unit_cost, // 新增 'unit_cost' => (float) $inv->unit_cost,
'total_value' => (float) $inv->total_value, // 新增
'unit_name' => $inv->product->baseUnit?->name ?? '個', 'unit_name' => $inv->product->baseUnit?->name ?? '個',
'expiry_date' => $inv->expiry_date ? $inv->expiry_date->format('Y-m-d') : null, 'expiry_date' => $inv->expiry_date ? $inv->expiry_date->format('Y-m-d') : null,
]; ];

View File

@@ -0,0 +1,81 @@
<?php
namespace App\Modules\Inventory\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use App\Modules\Core\Models\User;
class InventoryAdjustDoc extends Model
{
use HasFactory;
protected $fillable = [
'doc_no',
'count_doc_id',
'warehouse_id',
'status',
'reason',
'remarks',
'posted_at',
'created_by',
'updated_by',
'posted_by',
];
protected $casts = [
'posted_at' => 'datetime',
];
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
if (empty($model->doc_no)) {
$today = date('Ymd');
$prefix = 'ADJ' . $today;
$lastDoc = static::where('doc_no', 'like', $prefix . '%')
->orderBy('doc_no', 'desc')
->first();
if ($lastDoc) {
$lastNumber = substr($lastDoc->doc_no, -2);
$nextNumber = str_pad((int)$lastNumber + 1, 2, '0', STR_PAD_LEFT);
} else {
$nextNumber = '01';
}
$model->doc_no = $prefix . $nextNumber;
}
});
}
public function warehouse(): BelongsTo
{
return $this->belongsTo(Warehouse::class);
}
public function countDoc(): BelongsTo
{
return $this->belongsTo(InventoryCountDoc::class, 'count_doc_id');
}
public function items(): HasMany
{
return $this->hasMany(InventoryAdjustItem::class, 'adjust_doc_id');
}
public function createdBy(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
public function postedBy(): BelongsTo
{
return $this->belongsTo(User::class, 'posted_by');
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace App\Modules\Inventory\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class InventoryAdjustItem extends Model
{
use HasFactory;
protected $fillable = [
'adjust_doc_id',
'product_id',
'batch_number',
'qty_before',
'adjust_qty', // 增減數量
'notes',
];
protected $casts = [
'qty_before' => 'decimal:2',
'adjust_qty' => 'decimal:2',
];
public function doc(): BelongsTo
{
return $this->belongsTo(InventoryAdjustDoc::class, 'adjust_doc_id');
}
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
}

View File

@@ -0,0 +1,78 @@
<?php
namespace App\Modules\Inventory\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use App\Modules\Core\Models\User;
class InventoryCountDoc extends Model
{
use HasFactory;
protected $fillable = [
'doc_no',
'warehouse_id',
'status',
'snapshot_date',
'completed_at',
'remarks',
'created_by',
'updated_by',
'completed_by',
];
protected $casts = [
'snapshot_date' => 'datetime',
'completed_at' => 'datetime',
];
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
if (empty($model->doc_no)) {
$today = date('Ymd');
$prefix = 'CNT' . $today;
// 查詢當天編號最大的單據
$lastDoc = static::where('doc_no', 'like', $prefix . '%')
->orderBy('doc_no', 'desc')
->first();
if ($lastDoc) {
// 取得最後兩位序號並遞增
$lastNumber = substr($lastDoc->doc_no, -2);
$nextNumber = str_pad((int)$lastNumber + 1, 2, '0', STR_PAD_LEFT);
} else {
$nextNumber = '01';
}
$model->doc_no = $prefix . $nextNumber;
}
});
}
public function warehouse(): BelongsTo
{
return $this->belongsTo(Warehouse::class);
}
public function items(): HasMany
{
return $this->hasMany(InventoryCountItem::class, 'count_doc_id');
}
public function createdBy(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
public function completedBy(): BelongsTo
{
return $this->belongsTo(User::class, 'completed_by');
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace App\Modules\Inventory\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class InventoryCountItem extends Model
{
use HasFactory;
protected $fillable = [
'count_doc_id',
'product_id',
'batch_number',
'system_qty',
'counted_qty',
'diff_qty',
'notes',
];
protected $casts = [
'system_qty' => 'decimal:2',
'counted_qty' => 'decimal:2',
'diff_qty' => 'decimal:2',
];
public function doc(): BelongsTo
{
return $this->belongsTo(InventoryCountDoc::class, 'count_doc_id');
}
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Modules\Inventory\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class InventoryTransferItem extends Model
{
use HasFactory;
protected $fillable = [
'transfer_order_id',
'product_id',
'batch_number',
'quantity',
'notes',
];
protected $casts = [
'quantity' => 'decimal:2',
];
public function order(): BelongsTo
{
return $this->belongsTo(InventoryTransferOrder::class, 'transfer_order_id');
}
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
}

View File

@@ -0,0 +1,66 @@
<?php
namespace App\Modules\Inventory\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use App\Modules\Core\Models\User;
class InventoryTransferOrder extends Model
{
use HasFactory;
protected $fillable = [
'doc_no',
'from_warehouse_id',
'to_warehouse_id',
'status',
'remarks',
'posted_at',
'created_by',
'updated_by',
'posted_by',
];
protected $casts = [
'posted_at' => 'datetime',
];
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
if (empty($model->doc_no)) {
$model->doc_no = 'TRF-' . date('YmdHis') . '-' . rand(100, 999);
}
});
}
public function fromWarehouse(): BelongsTo
{
return $this->belongsTo(Warehouse::class, 'from_warehouse_id');
}
public function toWarehouse(): BelongsTo
{
return $this->belongsTo(Warehouse::class, 'to_warehouse_id');
}
public function items(): HasMany
{
return $this->hasMany(InventoryTransferItem::class, 'transfer_order_id');
}
public function createdBy(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
public function postedBy(): BelongsTo
{
return $this->belongsTo(User::class, 'posted_by');
}
}

View File

@@ -8,6 +8,8 @@ use App\Modules\Inventory\Controllers\WarehouseController;
use App\Modules\Inventory\Controllers\InventoryController; use App\Modules\Inventory\Controllers\InventoryController;
use App\Modules\Inventory\Controllers\SafetyStockController; use App\Modules\Inventory\Controllers\SafetyStockController;
use App\Modules\Inventory\Controllers\TransferOrderController; use App\Modules\Inventory\Controllers\TransferOrderController;
use App\Modules\Inventory\Controllers\CountDocController;
use App\Modules\Inventory\Controllers\AdjustDocController;
Route::middleware('auth')->group(function () { Route::middleware('auth')->group(function () {
@@ -54,7 +56,7 @@ Route::middleware('auth')->group(function () {
Route::delete('/warehouses/{warehouse}/inventory/{inventoryId}', [InventoryController::class, 'destroy'])->name('warehouses.inventory.destroy'); Route::delete('/warehouses/{warehouse}/inventory/{inventoryId}', [InventoryController::class, 'destroy'])->name('warehouses.inventory.destroy');
}); });
// API: 取得商品在特定倉庫的所有批號 // API: 取得商品在特定倉庫的所有批號
Route::get('/api/warehouses/{warehouse}/inventory/batches/{productId}', [InventoryController::class, 'getBatches']) Route::get('/api/warehouses/{warehouse}/inventory/batches/{productId}', [InventoryController::class, 'getBatches'])
->name('api.warehouses.inventory.batches'); ->name('api.warehouses.inventory.batches');
}); });
@@ -70,9 +72,35 @@ Route::middleware('auth')->group(function () {
}); });
}); });
// 撥補單 (在庫存調撥時使用) // 庫存盤點 (Stock Counting) - Global
Route::middleware('permission:inventory.view')->group(function () {
Route::get('/inventory/count-docs', [CountDocController::class, 'index'])->name('inventory.count.index');
Route::get('/inventory/count-docs/{doc}', [CountDocController::class, 'show'])->name('inventory.count.show');
Route::middleware('permission:inventory.adjust')->group(function () {
Route::post('/inventory/count-docs', [CountDocController::class, 'store'])->name('inventory.count.store');
Route::put('/inventory/count-docs/{doc}', [CountDocController::class, 'update'])->name('inventory.count.update');
Route::delete('/inventory/count-docs/{doc}', [CountDocController::class, 'destroy'])->name('inventory.count.destroy');
});
});
// 庫存盤調 (Stock Adjustment) - Global
Route::middleware('permission:inventory.adjust')->group(function () {
Route::get('/inventory/adjust-docs', [AdjustDocController::class, 'index'])->name('inventory.adjust.index');
Route::get('/inventory/adjust-docs/get-pending-counts', [AdjustDocController::class, 'getPendingCounts'])->name('inventory.adjust.pending-counts');
Route::get('/inventory/adjust-docs/{doc}', [AdjustDocController::class, 'show'])->name('inventory.adjust.show');
Route::post('/inventory/adjust-docs', [AdjustDocController::class, 'store'])->name('inventory.adjust.store');
Route::put('/inventory/adjust-docs/{doc}', [AdjustDocController::class, 'update'])->name('inventory.adjust.update');
Route::delete('/inventory/adjust-docs/{doc}', [AdjustDocController::class, 'destroy'])->name('inventory.adjust.destroy');
});
// 撥補單/調撥單 (Transfer Order) - Global
Route::middleware('permission:inventory.transfer')->group(function () { Route::middleware('permission:inventory.transfer')->group(function () {
Route::post('/transfer-orders', [TransferOrderController::class, 'store'])->name('transfer-orders.store'); Route::get('/inventory/transfer-orders', [TransferOrderController::class, 'index'])->name('inventory.transfer.index');
Route::get('/inventory/transfer-orders/{order}', [TransferOrderController::class, 'show'])->name('inventory.transfer.show');
Route::post('/inventory/transfer-orders', [TransferOrderController::class, 'store'])->name('inventory.transfer.store');
Route::put('/inventory/transfer-orders/{order}', [TransferOrderController::class, 'update'])->name('inventory.transfer.update');
Route::delete('/inventory/transfer-orders/{order}', [TransferOrderController::class, 'destroy'])->name('inventory.transfer.destroy');
}); });
Route::get('/api/warehouses/{warehouse}/inventories', [TransferOrderController::class, 'getWarehouseInventories']) Route::get('/api/warehouses/{warehouse}/inventories', [TransferOrderController::class, 'getWarehouseInventories'])
->middleware('permission:inventory.view') ->middleware('permission:inventory.view')

View File

@@ -0,0 +1,153 @@
<?php
namespace App\Modules\Inventory\Services;
use App\Modules\Inventory\Models\Inventory;
use App\Modules\Inventory\Models\InventoryCountDoc;
use App\Modules\Inventory\Models\InventoryAdjustDoc;
use App\Modules\Inventory\Models\InventoryAdjustItem;
use Illuminate\Support\Facades\DB;
class AdjustService
{
public function createDoc(string $warehouseId, string $reason, ?string $remarks = null, int $userId, ?int $countDocId = null): InventoryAdjustDoc
{
return InventoryAdjustDoc::create([
'warehouse_id' => $warehouseId,
'count_doc_id' => $countDocId,
'status' => 'draft',
'reason' => $reason,
'remarks' => $remarks,
'created_by' => $userId,
]);
}
/**
* 從盤點單建立盤調單
*/
public function createFromCountDoc(InventoryCountDoc $countDoc, int $userId): InventoryAdjustDoc
{
return DB::transaction(function () use ($countDoc, $userId) {
// 1. 建立盤調單頭
$adjDoc = $this->createDoc(
$countDoc->warehouse_id,
"盤點調整: " . $countDoc->doc_no,
"由盤點單 {$countDoc->doc_no} 自動生成",
$userId,
$countDoc->id
);
// 2. 抓取有差異的明細 (diff_qty != 0)
foreach ($countDoc->items as $item) {
if (abs($item->diff_qty) < 0.0001) continue;
$adjDoc->items()->create([
'product_id' => $item->product_id,
'batch_number' => $item->batch_number,
'qty_before' => $item->system_qty,
'adjust_qty' => $item->diff_qty,
'notes' => "盤點差異: " . $item->diff_qty,
]);
}
return $adjDoc;
});
}
/**
* 更新調整單內容 (Items)
* 此處採用 "全量更新" 方式處理 items (先刪後加),簡單可靠
*/
public function updateItems(InventoryAdjustDoc $doc, array $itemsData): void
{
DB::transaction(function () use ($doc, $itemsData) {
$doc->items()->delete();
foreach ($itemsData as $data) {
// 取得當前庫存作為 qty_before 參考 (僅參考,實際扣減以過帳當下為準)
$inventory = Inventory::where('warehouse_id', $doc->warehouse_id)
->where('product_id', $data['product_id'])
->where('batch_number', $data['batch_number'] ?? null)
->first();
$qtyBefore = $inventory ? $inventory->quantity : 0;
$doc->items()->create([
'product_id' => $data['product_id'],
'batch_number' => $data['batch_number'] ?? null,
'qty_before' => $qtyBefore,
'adjust_qty' => $data['adjust_qty'],
'notes' => $data['notes'] ?? null,
]);
}
});
}
/**
* 過帳 (Post) - 生效庫存異動
*/
public function post(InventoryAdjustDoc $doc, int $userId): void
{
DB::transaction(function () use ($doc, $userId) {
foreach ($doc->items as $item) {
if ($item->adjust_qty == 0) continue;
// 找尋或建立 Inventory
// 若是減少庫存,必須確保 Inventory 存在 (且理論上不能變負? 視策略而定,這裡假設允許變負或由 InventoryService 控管)
// 若是增加庫存,若不存在需建立
$inventory = Inventory::firstOrNew([
'warehouse_id' => $doc->warehouse_id,
'product_id' => $item->product_id,
'batch_number' => $item->batch_number,
]);
// 如果是新建立的 object (id 為空),需要初始化 default
if (!$inventory->exists) {
// 繼承 Product 成本或預設 0 (簡化處理)
$inventory->unit_cost = $item->product->cost ?? 0;
$inventory->quantity = 0;
}
$oldQty = $inventory->quantity;
$newQty = $oldQty + $item->adjust_qty;
$inventory->quantity = $newQty;
// 用最新的數量 * 單位成本 (簡化成本計算,不採用移動加權)
$inventory->total_value = $newQty * $inventory->unit_cost;
$inventory->save();
// 建立 Transaction
$inventory->transactions()->create([
'type' => '庫存調整',
'quantity' => $item->adjust_qty,
'unit_cost' => $inventory->unit_cost,
'balance_before' => $oldQty,
'balance_after' => $newQty,
'reason' => "調整單 {$doc->doc_no}: " . ($doc->reason ?? '手動調整'),
'actual_time' => now(),
'user_id' => $userId,
]);
}
$doc->update([
'status' => 'posted',
'posted_at' => now(),
'posted_by' => $userId,
]);
});
}
/**
* 作廢 (Void)
*/
public function void(InventoryAdjustDoc $doc, int $userId): void
{
if ($doc->status !== 'draft') {
throw new \Exception('只能作廢草稿狀態的單據');
}
$doc->update([
'status' => 'voided',
'updated_by' => $userId
]);
}
}

View File

@@ -0,0 +1,156 @@
<?php
namespace App\Modules\Inventory\Services;
use App\Modules\Inventory\Models\Inventory;
use App\Modules\Inventory\Models\InventoryCountDoc;
use App\Modules\Inventory\Models\InventoryCountItem;
use App\Modules\Inventory\Models\Warehouse;
use App\Modules\Inventory\Models\Product;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class CountService
{
/**
* 建立新的盤點單並執行快照
*/
public function createDoc(string $warehouseId, string $remarks = null, int $userId): InventoryCountDoc
{
return DB::transaction(function () use ($warehouseId, $remarks, $userId) {
$doc = InventoryCountDoc::create([
'warehouse_id' => $warehouseId,
'status' => 'draft',
'remarks' => $remarks,
'created_by' => $userId,
]);
return $doc;
});
}
/**
* 執行快照:鎖定當前庫存量
*/
public function snapshot(InventoryCountDoc $doc): void
{
DB::transaction(function () use ($doc) {
// 清除舊的 items (如果有)
$doc->items()->delete();
// 取得該倉庫所有庫存 (包含 quantity = 0 但未軟刪除的)
// 這裡可以根據需求決定是否要過濾掉 0 庫存,通常盤點單會希望能看到所有 "帳上有紀錄" 的東西
$inventories = Inventory::where('warehouse_id', $doc->warehouse_id)
->whereNull('deleted_at')
->get();
$items = [];
foreach ($inventories as $inv) {
$items[] = [
'count_doc_id' => $doc->id,
'product_id' => $inv->product_id,
'batch_number' => $inv->batch_number,
'system_qty' => $inv->quantity,
'counted_qty' => null, // 預設未盤點
'diff_qty' => 0,
'created_at' => now(),
'updated_at' => now(),
];
}
if (!empty($items)) {
InventoryCountItem::insert($items);
}
$doc->update([
'status' => 'counting',
'snapshot_date' => now(),
]);
});
}
/**
* 完成盤點:過帳差異
*/
public function complete(InventoryCountDoc $doc, int $userId): void
{
DB::transaction(function () use ($doc, $userId) {
foreach ($doc->items as $item) {
// 如果沒有輸入實盤數量,預設跳過或是視為 0?
// 安全起見:如果 counted_qty 是 null表示沒盤到跳過不處理 (或者依業務邏輯視為0)
// 這裡假設前端會確保有送出資料,若 null 則不做異動
if (is_null($item->counted_qty)) {
continue;
}
$diff = $item->counted_qty - $item->system_qty;
// 如果無差異,更新 item 狀態即可 (diff_qty 已經是 computed field 或在儲存時計算)
// 這裡 update 一下 diff_qty 以防萬一
$item->update(['diff_qty' => $diff]);
if (abs($diff) > 0.0001) {
// 找回原本的 Inventory
$inventory = Inventory::where('warehouse_id', $doc->warehouse_id)
->where('product_id', $item->product_id)
->where('batch_number', $item->batch_number)
->first();
if (!$inventory) {
// 如果原本沒庫存紀錄 (例如是新增的盤點項目),需要新建 Inventory
// 但目前 snapshot 邏輯只抓現有。若允許 "盤盈" (發現不在帳上的),需要額外邏輯
// 暫時略過 "新增 Inventory" 的複雜邏輯,假設只能針對 existing batch 調整
continue;
}
$oldQty = $inventory->quantity;
$newQty = $oldQty + $diff;
$inventory->quantity = $newQty;
$inventory->total_value = $inventory->unit_cost * $newQty;
$inventory->save();
// 寫入 Transaction
$inventory->transactions()->create([
'type' => '盤點調整',
'quantity' => $diff,
'unit_cost' => $inventory->unit_cost,
'balance_before' => $oldQty,
'balance_after' => $newQty,
'reason' => "盤點單 {$doc->doc_no} 過帳",
'actual_time' => now(),
'user_id' => $userId,
]);
}
}
$doc->update([
'status' => 'completed',
'completed_at' => now(),
'completed_by' => $userId,
]);
});
}
/**
* 更新盤點數量
*/
public function updateCount(InventoryCountDoc $doc, array $itemsData): void
{
DB::transaction(function () use ($doc, $itemsData) {
foreach ($itemsData as $data) {
$item = $doc->items()->find($data['id']);
if ($item) {
$countedQty = $data['counted_qty'];
$diff = is_numeric($countedQty) ? ($countedQty - $item->system_qty) : 0;
$item->update([
'counted_qty' => $countedQty,
'diff_qty' => $diff,
'notes' => $data['notes'] ?? $item->notes,
]);
}
}
});
}
}

View File

@@ -0,0 +1,152 @@
<?php
namespace App\Modules\Inventory\Services;
use App\Modules\Inventory\Models\Inventory;
use App\Modules\Inventory\Models\InventoryTransferOrder;
use App\Modules\Inventory\Models\InventoryTransferItem;
use App\Modules\Inventory\Models\Warehouse;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class TransferService
{
/**
* 建立調撥單草稿
*/
public function createOrder(int $fromWarehouseId, int $toWarehouseId, ?string $remarks, int $userId): InventoryTransferOrder
{
return InventoryTransferOrder::create([
'from_warehouse_id' => $fromWarehouseId,
'to_warehouse_id' => $toWarehouseId,
'status' => 'draft',
'remarks' => $remarks,
'created_by' => $userId,
]);
}
/**
* 更新調撥單明細
*/
public function updateItems(InventoryTransferOrder $order, array $itemsData): void
{
DB::transaction(function () use ($order, $itemsData) {
$order->items()->delete();
foreach ($itemsData as $data) {
$order->items()->create([
'product_id' => $data['product_id'],
'batch_number' => $data['batch_number'] ?? null,
'quantity' => $data['quantity'],
'notes' => $data['notes'] ?? null,
]);
}
});
}
/**
* 過帳 (Post) - 執行調撥 (直接扣除來源,增加目的)
*/
public function post(InventoryTransferOrder $order, int $userId): void
{
DB::transaction(function () use ($order, $userId) {
$fromWarehouse = $order->fromWarehouse;
$toWarehouse = $order->toWarehouse;
foreach ($order->items as $item) {
if ($item->quantity <= 0) continue;
// 1. 處理來源倉 (扣除)
$sourceInventory = Inventory::where('warehouse_id', $order->from_warehouse_id)
->where('product_id', $item->product_id)
->where('batch_number', $item->batch_number)
->first();
if (!$sourceInventory || $sourceInventory->quantity < $item->quantity) {
throw ValidationException::withMessages([
'items' => ["商品 {$item->product->name} (批號: {$item->batch_number}) 在來源倉庫存不足"],
]);
}
$oldSourceQty = $sourceInventory->quantity;
$newSourceQty = $oldSourceQty - $item->quantity;
$sourceInventory->quantity = $newSourceQty;
// 更新總值 (假設成本不變)
$sourceInventory->total_value = $sourceInventory->quantity * $sourceInventory->unit_cost;
$sourceInventory->save();
// 記錄來源交易
$sourceInventory->transactions()->create([
'type' => '調撥出庫',
'quantity' => -$item->quantity,
'unit_cost' => $sourceInventory->unit_cost,
'balance_before' => $oldSourceQty,
'balance_after' => $newSourceQty,
'reason' => "調撥單 {$order->doc_no}{$toWarehouse->name}",
'actual_time' => now(),
'user_id' => $userId,
]);
// 2. 處理目的倉 (增加)
$targetInventory = Inventory::firstOrCreate(
[
'warehouse_id' => $order->to_warehouse_id,
'product_id' => $item->product_id,
'batch_number' => $item->batch_number,
],
[
'quantity' => 0,
'unit_cost' => $sourceInventory->unit_cost, // 繼承成本
'total_value' => 0,
// 繼承其他屬性
'expiry_date' => $sourceInventory->expiry_date,
'quality_status' => $sourceInventory->quality_status,
'origin_country' => $sourceInventory->origin_country,
]
);
// 若是新建立的且成本為0確保繼承成本
if ($targetInventory->wasRecentlyCreated && $targetInventory->unit_cost == 0) {
$targetInventory->unit_cost = $sourceInventory->unit_cost;
}
$oldTargetQty = $targetInventory->quantity;
$newTargetQty = $oldTargetQty + $item->quantity;
$targetInventory->quantity = $newTargetQty;
$targetInventory->total_value = $targetInventory->quantity * $targetInventory->unit_cost;
$targetInventory->save();
// 記錄目的交易
$targetInventory->transactions()->create([
'type' => '調撥入庫',
'quantity' => $item->quantity,
'unit_cost' => $targetInventory->unit_cost,
'balance_before' => $oldTargetQty,
'balance_after' => $newTargetQty,
'reason' => "調撥單 {$order->doc_no} 來自 {$fromWarehouse->name}",
'actual_time' => now(),
'user_id' => $userId,
]);
}
$order->update([
'status' => 'completed',
'posted_at' => now(),
'posted_by' => $userId,
]);
});
}
public function void(InventoryTransferOrder $order, int $userId): void
{
if ($order->status !== 'draft') {
throw new \Exception('只能作廢草稿狀態的單據');
}
$order->update([
'status' => 'voided',
'updated_by' => $userId
]);
}
}

View File

@@ -0,0 +1,54 @@
<?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('inventory_count_docs', function (Blueprint $table) {
$table->id();
$table->string('doc_no')->unique(); // 單號
$table->foreignId('warehouse_id')->constrained('warehouses')->cascadeOnDelete();
$table->string('status')->default('draft'); // draft, counting, completed, cancelled
$table->timestamp('snapshot_date')->nullable(); // 快照建立時間
$table->timestamp('completed_at')->nullable(); // 完成時間
$table->string('remarks')->nullable();
// 審核/建立資訊
$table->foreignId('created_by')->constrained('users');
$table->foreignId('updated_by')->nullable()->constrained('users');
$table->foreignId('completed_by')->nullable()->constrained('users');
$table->timestamps();
});
Schema::create('inventory_count_items', function (Blueprint $table) {
$table->id();
$table->foreignId('count_doc_id')->constrained('inventory_count_docs')->cascadeOnDelete();
$table->foreignId('product_id')->constrained('products');
$table->string('batch_number')->nullable(); // 針對特定批號盤點
$table->decimal('system_qty', 10, 2)->default(0); // 系統帳面數量 (快照當下)
$table->decimal('counted_qty', 10, 2)->nullable(); // 實盤數量
$table->decimal('diff_qty', 10, 2)->default(0); // 差異 (實盤 - 系統)
$table->string('notes')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('inventory_count_items');
Schema::dropIfExists('inventory_count_docs');
}
};

View File

@@ -0,0 +1,53 @@
<?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('inventory_adjust_docs', function (Blueprint $table) {
$table->id();
$table->string('doc_no')->unique(); // 單號
$table->foreignId('warehouse_id')->constrained('warehouses')->cascadeOnDelete();
$table->string('status')->default('draft'); // draft, posted, voided
$table->string('reason')->nullable(); // 調整原因 (e.g. 報廢, 盤盈虧, 其他)
$table->string('remarks')->nullable();
// 審核/建立資訊
$table->timestamp('posted_at')->nullable(); // 過帳時間
$table->foreignId('created_by')->constrained('users');
$table->foreignId('updated_by')->nullable()->constrained('users');
$table->foreignId('posted_by')->nullable()->constrained('users');
$table->timestamps();
});
Schema::create('inventory_adjust_items', function (Blueprint $table) {
$table->id();
$table->foreignId('adjust_doc_id')->constrained('inventory_adjust_docs')->cascadeOnDelete();
$table->foreignId('product_id')->constrained('products');
$table->string('batch_number')->nullable();
// 記錄當下 "調整前" 的庫存與成本 (參考用)
$table->decimal('qty_before', 10, 2)->default(0);
// 實際調整的數量 (可以正負, 正=增加, 負=減少)
$table->decimal('adjust_qty', 10, 2);
$table->string('notes')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('inventory_adjust_items');
Schema::dropIfExists('inventory_adjust_docs');
}
};

View File

@@ -0,0 +1,47 @@
<?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('inventory_transfer_orders', function (Blueprint $table) {
$table->id();
$table->string('doc_no')->unique();
$table->foreignId('from_warehouse_id')->constrained('warehouses')->cascadeOnDelete();
$table->foreignId('to_warehouse_id')->constrained('warehouses')->cascadeOnDelete();
$table->string('status')->default('draft'); // draft, completed, voided
$table->string('remarks')->nullable();
// 審核/建立資訊
$table->timestamp('posted_at')->nullable(); // 過帳時間
$table->foreignId('created_by')->constrained('users');
$table->foreignId('updated_by')->nullable()->constrained('users');
$table->foreignId('posted_by')->nullable()->constrained('users');
$table->timestamps();
});
Schema::create('inventory_transfer_items', function (Blueprint $table) {
$table->id();
$table->foreignId('transfer_order_id')->constrained('inventory_transfer_orders')->cascadeOnDelete();
$table->foreignId('product_id')->constrained('products');
$table->string('batch_number')->nullable();
$table->decimal('quantity', 10, 2);
$table->string('notes')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('inventory_transfer_items');
Schema::dropIfExists('inventory_transfer_orders');
}
};

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::table('inventory_adjust_docs', function (Blueprint $table) {
$table->foreignId('count_doc_id')
->after('doc_no')
->nullable()
->constrained('inventory_count_docs')
->nullOnDelete();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('inventory_adjust_docs', function (Blueprint $table) {
$table->dropConstrainedForeignId('count_doc_id');
});
}
};

View File

@@ -22,7 +22,8 @@ import {
BarChart3, BarChart3,
FileSpreadsheet, FileSpreadsheet,
BookOpen, BookOpen,
ClipboardCheck ClipboardCheck,
ArrowLeftRight
} from "lucide-react"; } from "lucide-react";
import { toast, Toaster } from "sonner"; import { toast, Toaster } from "sonner";
import { useState, useEffect, useMemo, useRef } from "react"; import { useState, useEffect, useMemo, useRef } from "react";
@@ -83,7 +84,7 @@ export default function AuthenticatedLayout({
id: "inventory-management", id: "inventory-management",
label: "商品與庫存管理", label: "商品與庫存管理",
icon: <Boxes className="h-5 w-5" />, icon: <Boxes className="h-5 w-5" />,
permission: ["products.view", "warehouses.view"], // 滿足任一即可看到此群組 permission: ["products.view", "warehouses.view", "inventory.view"], // 滿足任一即可看到此群組
children: [ children: [
{ {
id: "product-management", id: "product-management",
@@ -99,6 +100,27 @@ export default function AuthenticatedLayout({
route: "/warehouses", route: "/warehouses",
permission: "warehouses.view", permission: "warehouses.view",
}, },
{
id: "stock-counting",
label: "庫存盤點",
icon: <ClipboardCheck className="h-4 w-4" />,
route: "/inventory/count-docs",
permission: "inventory.view",
},
{
id: "stock-adjustment",
label: "庫存盤調",
icon: <FileText className="h-4 w-4" />,
route: "/inventory/adjust-docs",
permission: "inventory.adjust",
},
{
id: "stock-transfer",
label: "庫存調撥",
icon: <ArrowLeftRight className="h-4 w-4" />,
route: "/inventory/transfer-orders",
permission: "inventory.transfer",
},
], ],
}, },
{ {
@@ -260,7 +282,11 @@ export default function AuthenticatedLayout({
const activeItem = menuItems.find(item => const activeItem = menuItems.find(item =>
item.children?.some(child => child.route && url.startsWith(child.route)) item.children?.some(child => child.route && url.startsWith(child.route))
); );
return activeItem ? [activeItem.id] : ["inventory-management"]; const defaultExpanded = ["inventory-management"];
if (activeItem && !defaultExpanded.includes(activeItem.id)) {
defaultExpanded.push(activeItem.id);
}
return defaultExpanded;
}); });
// 監聽 URL 變化,確保「當前」頁面所屬群組是展開的 // 監聽 URL 變化,確保「當前」頁面所屬群組是展開的

View File

@@ -0,0 +1,409 @@
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, useForm, router } from '@inertiajs/react';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/Components/ui/table";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Badge } from "@/Components/ui/badge";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/Components/ui/dialog";
import { Label } from "@/Components/ui/label";
import { Plus, Search, X, Eye, Pencil, ClipboardCheck } from "lucide-react";
import { useState, useCallback, useEffect } from 'react';
import Pagination from '@/Components/shared/Pagination';
import { SearchableSelect } from '@/Components/ui/searchable-select';
import { Can } from '@/Components/Permission/Can';
import debounce from 'lodash/debounce';
import axios from 'axios';
interface Doc {
id: string;
doc_no: string;
warehouse_name: string;
reason: string;
status: string;
created_by: string;
created_at: string;
posted_at: string;
}
interface Warehouse {
id: string;
name: string;
}
interface Filters {
search?: string;
warehouse_id?: string;
per_page?: string;
}
interface DocsPagination {
data: Doc[];
current_page: number;
per_page: number;
total: number;
links: any[]; // Adjust type as needed for pagination links
}
export default function Index({ docs, warehouses, filters }: { docs: DocsPagination, warehouses: Warehouse[], filters: Filters }) {
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [searchQuery, setSearchQuery] = useState(filters.search || '');
const [warehouseId, setWarehouseId] = useState(filters.warehouse_id || '');
const [perPage, setPerPage] = useState(filters.per_page || '15');
// For Count Doc Selection
const [pendingCounts, setPendingCounts] = useState<any[]>([]);
const [loadingPending, setLoadingPending] = useState(false);
const [scanSearch, setScanSearch] = useState('');
const fetchPendingCounts = useCallback(
debounce((search = '') => {
setLoadingPending(true);
axios.get(route('inventory.adjust.pending-counts'), { params: { search } })
.then(res => setPendingCounts(res.data))
.finally(() => setLoadingPending(false));
}, 300),
[]
);
useEffect(() => {
if (isDialogOpen) {
fetchPendingCounts();
}
}, [isDialogOpen, fetchPendingCounts]);
const debouncedFilter = useCallback(
debounce((params: Filters) => {
router.get(route('inventory.adjust.index'), params as any, {
preserveState: true,
replace: true,
});
}, 300),
[]
);
const handleSearchChange = (val: string) => {
setSearchQuery(val);
debouncedFilter({ search: val, warehouse_id: warehouseId, per_page: perPage });
};
const handleWarehouseChange = (val: string) => {
setWarehouseId(val);
debouncedFilter({ search: searchQuery, warehouse_id: val, per_page: perPage });
};
const handlePerPageChange = (val: string) => {
setPerPage(val);
debouncedFilter({ search: searchQuery, warehouse_id: warehouseId, per_page: val });
};
const { data, setData, post, processing, reset } = useForm({
count_doc_id: null as string | null,
warehouse_id: '',
reason: '',
remarks: '',
});
const handleCreate = (countDocId?: string) => {
if (countDocId) {
setData('count_doc_id', countDocId);
router.post(route('inventory.adjust.store'), { count_doc_id: countDocId }, {
onSuccess: () => setIsDialogOpen(false),
});
return;
}
post(route('inventory.adjust.store'), {
onSuccess: () => {
setIsDialogOpen(false);
reset();
},
});
};
const getStatusBadge = (status: string) => {
switch (status) {
case 'draft':
return <Badge variant="secondary" className="bg-gray-100 text-gray-600 border-none">稿</Badge>;
case 'posted':
return <Badge className="bg-green-100 text-green-700 border-none"></Badge>;
case 'voided':
return <Badge variant="destructive" className="bg-red-100 text-red-700 border-none"></Badge>;
default:
return <Badge variant="outline">{status}</Badge>;
}
};
return (
<AuthenticatedLayout
breadcrumbs={[
{ label: '商品與庫存管理', href: '#' },
{ label: '庫存盤調', href: route('inventory.adjust.index'), isPage: true },
]}
>
<Head title="庫存盤調" />
<div className="container mx-auto p-6 max-w-7xl">
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<ClipboardCheck className="h-6 w-6 text-primary-main" />
調
</h1>
<p className="text-sm text-gray-500 mt-1">調 ()</p>
</div>
</div>
{/* Toolbar Context */}
<div className="bg-white rounded-lg shadow-sm border p-4 mb-6">
<div className="flex flex-col md:flex-row gap-4">
{/* Search */}
<div className="flex-1 relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
<Input
placeholder="搜尋單號、原因或備註..."
value={searchQuery}
onChange={(e) => handleSearchChange(e.target.value)}
className="pl-10 pr-10 h-9"
/>
{searchQuery && (
<button
onClick={() => handleSearchChange('')}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
>
<X className="h-4 w-4" />
</button>
)}
</div>
{/* Warehouse Filter */}
<SearchableSelect
options={[
{ value: '', label: '所有倉庫' },
...warehouses.map(w => ({ value: w.id, label: w.name }))
]}
value={warehouseId}
onValueChange={handleWarehouseChange}
placeholder="選擇倉庫"
className="w-full md:w-[200px] h-9"
/>
{/* Action Buttons */}
<div className="flex gap-2 w-full md:w-auto">
<Can permission="inventory.adjust">
<Button
className="flex-1 md:flex-none button-filled-primary h-9"
onClick={() => setIsDialogOpen(true)}
>
<Plus className="mr-2 h-4 w-4" />
調
</Button>
</Can>
</div>
</div>
</div>
{/* Table Container */}
<div className="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">
<Table>
<TableHeader className="bg-gray-50">
<TableRow>
<TableHead className="w-[60px] text-center font-medium text-grey-600">#</TableHead>
<TableHead className="w-[180px] font-medium text-grey-600"></TableHead>
<TableHead className="font-medium text-grey-600"></TableHead>
<TableHead className="font-medium text-grey-600">調</TableHead>
<TableHead className="font-medium text-grey-600 text-center"></TableHead>
<TableHead className="font-medium text-grey-600"></TableHead>
<TableHead className="font-medium text-grey-600"></TableHead>
<TableHead className="font-medium text-grey-600"></TableHead>
<TableHead className="text-right font-medium text-grey-600"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{docs.data.length === 0 ? (
<TableRow>
<TableCell colSpan={9} className="h-32 text-center text-grey-400">
調
</TableCell>
</TableRow>
) : (
docs.data.map((doc: Doc, index: number) => (
<TableRow
key={doc.id}
className="hover:bg-gray-50/50 transition-colors cursor-pointer group"
onClick={() => router.visit(route('inventory.adjust.show', [doc.id]))}
>
<TableCell className="text-center text-grey-400 font-medium">
{(docs.current_page - 1) * docs.per_page + index + 1}
</TableCell>
<TableCell className="font-semibold text-primary-main">
{doc.doc_no}
</TableCell>
<TableCell className="text-grey-700">{doc.warehouse_name}</TableCell>
<TableCell className="text-grey-600 max-w-[200px] truncate">{doc.reason}</TableCell>
<TableCell className="text-center">{getStatusBadge(doc.status)}</TableCell>
<TableCell className="text-grey-600 text-sm">{doc.created_by}</TableCell>
<TableCell className="text-grey-400 text-xs">{doc.created_at}</TableCell>
<TableCell className="text-grey-400 text-xs">{doc.posted_at}</TableCell>
<TableCell className="text-right">
<Button
variant="ghost"
size="sm"
className="text-primary-main hover:bg-primary-50 px-2"
>
{doc.status === 'posted' ? (
<><Eye className="h-4 w-4 mr-1" /> </>
) : (
<><Pencil className="h-4 w-4 mr-1" /> </>
)}
</Button>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
<div className="mt-4 flex flex-col sm:flex-row items-center justify-between gap-4">
<div className="flex items-center gap-4">
<div className="flex items-center gap-2 text-sm text-gray-500">
<span></span>
<SearchableSelect
value={perPage}
onValueChange={handlePerPageChange}
options={[
{ label: "15", value: "15" },
{ label: "30", value: "30" },
{ label: "50", value: "50" },
{ label: "100", value: "100" }
]}
className="w-[100px] h-8"
showSearch={false}
/>
<span></span>
</div>
<span className="text-sm text-gray-500"> {docs?.total || 0} </span>
</div>
<Pagination links={docs.links} />
</div>
</div>
{/* Create Dialog */}
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle className="text-xl font-bold flex items-center gap-2">
<Plus className="h-5 w-5 text-primary-main" />
調
</DialogTitle>
<DialogDescription>
調
</DialogDescription>
</DialogHeader>
<div className="py-4 space-y-6">
{/* Option 1: Scan/Select from Count Docs */}
<div className="space-y-4">
<Label className="text-sm font-semibold text-grey-700"> ()</Label>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-grey-400" />
<Input
placeholder="掃描盤點單號或搜尋..."
className="pl-9 h-11 border-primary-100 focus:ring-primary-main"
value={scanSearch}
onChange={(e) => {
setScanSearch(e.target.value);
fetchPendingCounts(e.target.value);
}}
/>
</div>
<div className="max-height-[300px] overflow-y-auto rounded-md border border-grey-100 bg-grey-50">
{loadingPending ? (
<div className="p-8 text-center text-sm text-grey-400">...</div>
) : pendingCounts.length === 0 ? (
<div className="p-8 text-center text-sm text-grey-400">
調 ()
</div>
) : (
<div className="divide-y divide-grey-100">
{pendingCounts.map((c: any) => (
<div
key={c.id}
className="p-3 hover:bg-white flex items-center justify-between cursor-pointer group transition-colors"
onClick={() => handleCreate(c.id)}
>
<div>
<p className="font-bold text-grey-900 group-hover:text-primary-main">{c.doc_no}</p>
<p className="text-xs text-grey-500">{c.warehouse_name} | : {c.completed_at}</p>
</div>
<Button size="sm" variant="outline" className="button-outlined-primary">
</Button>
</div>
))}
</div>
)}
</div>
</div>
<div className="relative">
<div className="absolute inset-0 flex items-center"><span className="w-full border-t border-grey-200" /></div>
<div className="relative flex justify-center text-xs uppercase"><span className="bg-white px-2 text-grey-400 font-medium"></span></div>
</div>
{/* Option 2: Manual (Optional, though less common in this flow) */}
<div className="space-y-4">
<Label className="text-sm font-semibold text-grey-700">調</Label>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label className="text-xs"></Label>
<SearchableSelect
options={warehouses.map(w => ({ value: w.id, label: w.name }))}
value={data.warehouse_id}
onValueChange={(val) => setData('warehouse_id', val)}
placeholder="選擇倉庫"
/>
</div>
<div className="space-y-2">
<Label className="text-xs">調</Label>
<Input
placeholder="例如: 報廢, 破損..."
value={data.reason}
onChange={(e) => setData('reason', e.target.value)}
className="h-10"
/>
</div>
</div>
</div>
</div>
<DialogFooter className="bg-gray-50 -mx-6 -mb-6 p-4 rounded-b-lg">
<Button variant="ghost" onClick={() => setIsDialogOpen(false)}></Button>
<Button
className="button-filled-primary"
disabled={processing || !data.warehouse_id || !data.reason}
onClick={() => handleCreate()}
>
調
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</AuthenticatedLayout>
);
}

View File

@@ -0,0 +1,511 @@
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, Link, useForm, router } from '@inertiajs/react';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/Components/ui/table";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Badge } from "@/Components/ui/badge";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "@/Components/ui/card";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/Components/ui/alert-dialog";
import { Label } from "@/Components/ui/label";
import { Textarea } from "@/Components/ui/textarea";
import { Save, CheckCircle, Trash2, ArrowLeft, Plus, X, Search, FileText } from "lucide-react";
import { useState, useEffect } from 'react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/Components/ui/dialog";
import axios from 'axios';
import { Can } from '@/Components/Permission/Can';
interface AdjItem {
id?: string;
product_id: string;
product_name: string;
product_code: string;
batch_number: string | null;
unit: string;
qty_before: number;
adjust_qty: number | string;
notes: string;
}
interface AdjDoc {
id: string;
doc_no: string;
warehouse_id: string;
warehouse_name: string;
status: string;
reason: string;
remarks: string;
created_at: string;
created_by: string;
count_doc_id?: string;
count_doc_no?: string;
items: AdjItem[];
}
export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
const isDraft = doc.status === 'draft';
// Main Form using Inertia useForm
const { data, setData, put, delete: destroy, processing } = useForm({
reason: doc.reason,
remarks: doc.remarks || '',
items: doc.items || [],
action: 'save',
});
const [newItemOpen, setNewItemOpen] = useState(false);
// Helper to add new item
const addItem = (product: any, batchNumber: string | null) => {
// Check if exists
const exists = data.items.find(i =>
i.product_id === String(product.id) &&
i.batch_number === batchNumber
);
if (exists) {
alert('此商品與批號已在列表中');
return;
}
setData('items', [
...data.items,
{
product_id: String(product.id),
product_name: product.name,
product_code: product.code,
unit: product.unit,
batch_number: batchNumber,
qty_before: product.qty || 0, // Not fetched dynamically for now, or could fetch via API
adjust_qty: 0,
notes: '',
}
]);
setNewItemOpen(false);
};
const removeItem = (index: number) => {
const newItems = [...data.items];
newItems.splice(index, 1);
setData('items', newItems);
};
const updateItem = (index: number, field: keyof AdjItem, value: any) => {
const newItems = [...data.items];
(newItems[index] as any)[field] = value;
setData('items', newItems);
};
const handleSave = () => {
setData('action', 'save');
put(route('inventory.adjust.update', [doc.id]), {
preserveScroll: true,
});
};
const handlePost = () => {
// Validate
if (data.items.length === 0) {
alert('請至少加入一個調整項目');
return;
}
const hasZero = data.items.some(i => Number(i.adjust_qty) === 0);
if (hasZero && !confirm('部分項目的調整數量為 0確定要繼續嗎')) {
return;
}
if (confirm('確定要過帳嗎?過帳後將無法修改,並直接影響庫存。')) {
router.visit(route('inventory.adjust.update', [doc.id]), {
method: 'put',
data: { ...data, action: 'post' } as any,
});
}
};
const handleDelete = () => {
destroy(route('inventory.adjust.destroy', [doc.id]));
};
return (
<AuthenticatedLayout
breadcrumbs={[
{ label: '商品與庫存管理', href: '#' },
{ label: '庫存盤調', href: route('inventory.adjust.index') },
{ label: doc.doc_no, href: route('inventory.adjust.show', [doc.id]), isPage: true },
]}
>
<Head title={`盤調單 ${doc.doc_no}`} />
<div className="container mx-auto p-6 max-w-7xl animate-in fade-in duration-500">
<div className="space-y-6">
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<div className="flex items-center gap-4">
<Button
variant="outline"
size="icon"
className="h-10 w-10 border-grey-200"
onClick={() => router.visit(route('inventory.adjust.index'))}
>
<ArrowLeft className="h-5 w-5 text-grey-600" />
</Button>
<div>
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-3">
{doc.doc_no}
{isDraft ? (
<Badge variant="secondary" className="bg-gray-100 text-gray-600 border-none">稿</Badge>
) : (
<Badge className="bg-green-100 text-green-700 border-none"></Badge>
)}
</h1>
<div className="flex items-center gap-3 mt-1 text-sm text-grey-500">
<span className="flex items-center gap-1"><CheckCircle className="h-3 w-3" /> : {doc.warehouse_name}</span>
<span>|</span>
<span>: {doc.created_by}</span>
<span>|</span>
<span>: {doc.created_at}</span>
</div>
</div>
</div>
<div className="flex items-center gap-3">
{isDraft && (
<Can permission="inventory.adjust">
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="ghost" className="text-red-500 hover:bg-red-50 hover:text-red-600">
<Trash2 className="mr-2 h-4 w-4" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>調</AlertDialogTitle>
<AlertDialogDescription>
稿
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={handleDelete} className="bg-red-500 hover:bg-red-600"></AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<Button variant="outline" className="border-primary-200 text-primary-main hover:bg-primary-50" onClick={handleSave} disabled={processing}>
<Save className="mr-2 h-4 w-4" />
稿
</Button>
<Button className="button-filled-primary" onClick={handlePost} disabled={processing}>
<CheckCircle className="mr-2 h-4 w-4" />
</Button>
</Can>
)}
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<Card className="lg:col-span-2 shadow-sm border-grey-100">
<CardHeader className="bg-grey-50/50 border-b border-grey-100 py-3">
<CardTitle className="text-sm font-semibold text-grey-600"></CardTitle>
</CardHeader>
<CardContent className="pt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-2">
<Label className="text-xs font-bold text-grey-500 uppercase tracking-wider">調</Label>
{isDraft ? (
<Input
value={data.reason}
onChange={e => setData('reason', e.target.value)}
className="focus:ring-primary-main"
/>
) : (
<div className="text-grey-900 font-medium">{data.reason}</div>
)}
</div>
<div className="space-y-2">
<Label className="text-xs font-bold text-grey-500 uppercase tracking-wider"></Label>
{isDraft ? (
<Textarea
value={data.remarks}
onChange={e => setData('remarks', e.target.value)}
rows={1}
className="focus:ring-primary-main"
/>
) : (
<div className="text-grey-600">{data.remarks || '-'}</div>
)}
</div>
</CardContent>
</Card>
<Card className="shadow-sm border-grey-100 bg-primary-50/30">
<CardHeader className="py-3">
<CardTitle className="text-sm font-semibold text-primary-main"></CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div>
<Label className="text-[10px] font-bold text-primary-main/60 uppercase"></Label>
{doc.count_doc_id ? (
<div className="mt-1">
<Link
href={route('inventory.count.show', [doc.count_doc_id])}
className="text-primary-main font-bold hover:underline flex items-center gap-2"
>
<FileText className="h-4 w-4" />
{doc.count_doc_no || '檢視盤點單'}
</Link>
</div>
) : (
<div className="text-grey-400 italic text-sm mt-1"></div>
)}
</div>
<div className="pt-2 border-t border-primary-100">
<Label className="text-[10px] font-bold text-primary-main/60 uppercase"></Label>
<p className="font-bold text-grey-900">{doc.warehouse_name}</p>
</div>
</CardContent>
</Card>
</div>
<Card className="border border-gray-200 shadow-sm overflow-hidden gap-0">
<CardHeader className="bg-white border-b flex flex-row items-center justify-between py-4 px-6">
<CardTitle className="text-lg font-medium text-grey-900">調</CardTitle>
{isDraft && (
<ProductSearchDialog
warehouseId={doc.warehouse_id}
onSelect={(product, batch) => addItem(product, batch)}
/>
)}
</CardHeader>
<Table>
<TableHeader className="bg-gray-50">
<TableRow>
<TableHead className="w-[60px] text-center font-medium text-grey-600">#</TableHead>
<TableHead className="pl-4 font-medium text-grey-600"></TableHead>
<TableHead className="font-medium text-grey-600"></TableHead>
<TableHead className="w-24 text-center font-medium text-grey-600"></TableHead>
<TableHead className="w-32 text-right font-medium text-grey-600 text-primary-main">調</TableHead>
<TableHead className="w-40 text-right font-medium text-grey-600">調 (+/-)</TableHead>
<TableHead className="font-medium text-grey-600"></TableHead>
{isDraft && <TableHead className="w-[80px]"></TableHead>}
</TableRow>
</TableHeader>
<TableBody>
{data.items.length === 0 ? (
<TableRow>
<TableCell colSpan={isDraft ? 8 : 7} className="h-32 text-center text-grey-400">
調
</TableCell>
</TableRow>
) : (
data.items.map((item, index) => (
<TableRow
key={`${item.product_id}-${item.batch_number}-${index}`}
className="group hover:bg-gray-50/50 transition-colors"
>
<TableCell className="text-center text-grey-400 font-medium">{index + 1}</TableCell>
<TableCell className="pl-4">
<div className="font-bold text-grey-900">{item.product_name}</div>
<div className="text-xs text-grey-500 font-mono">{item.product_code}</div>
</TableCell>
<TableCell className="text-grey-600">{item.batch_number || '-'}</TableCell>
<TableCell className="text-center text-grey-500">{item.unit}</TableCell>
<TableCell className="text-right font-medium text-grey-400">
{item.qty_before}
</TableCell>
<TableCell className="text-right">
{isDraft ? (
<Input
type="number"
className="text-right h-9 border-grey-200 focus:ring-primary-main"
value={item.adjust_qty}
onChange={e => updateItem(index, 'adjust_qty', e.target.value)}
/>
) : (
<span className={`font-bold ${Number(item.adjust_qty) > 0 ? 'text-green-600' : 'text-red-600'}`}>
{Number(item.adjust_qty) > 0 ? '+' : ''}{item.adjust_qty}
</span>
)}
</TableCell>
<TableCell>
{isDraft ? (
<Input
className="h-9 border-grey-200 focus:ring-primary-main"
value={item.notes || ''}
onChange={e => updateItem(index, 'notes', e.target.value)}
placeholder="輸入備註..."
/>
) : (
<span className="text-grey-600 text-sm">{item.notes || '-'}</span>
)}
</TableCell>
{isDraft && (
<TableCell className="text-center">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 text-red-400 hover:text-red-600 hover:bg-red-50 p-0"
onClick={() => removeItem(index)}
>
<X className="h-4 w-4" />
</Button>
</TableCell>
)}
</TableRow>
))
)}
</TableBody>
</Table>
</Card>
<div className="bg-gray-50/80 border border-dashed border-grey-200 rounded-lg p-4 flex items-start gap-3">
<CheckCircle className="h-5 w-5 text-primary-main mt-0.5 shrink-0" />
<div className="text-xs text-grey-500 leading-relaxed">
<p className="font-bold text-grey-700"></p>
<ul className="list-disc ml-4 space-y-1 mt-1">
<li><strong>調 (+/-)</strong> (+) () (-) ()</li>
<li><strong></strong>調</li>
<li><strong></strong></li>
</ul>
</div>
</div>
</div>
</div>
</AuthenticatedLayout>
);
}
// Simple internal component for product search
function ProductSearchDialog({ onSelect }: { warehouseId: string, onSelect: (p: any, b: string | null) => void }) {
const [search, setSearch] = useState('');
const [results, setResults] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [open, setOpen] = useState(false);
// Debounce search
useEffect(() => {
if (!search) {
setResults([]);
return;
}
const timer = setTimeout(() => {
fetchProducts();
}, 500);
return () => clearTimeout(timer);
}, [search]);
const fetchProducts = async () => {
setLoading(true);
try {
// Using existing API logic from Goods Receipts or creating a flexible one
// Using count docs logic for now if specific endpoint not available,
// but `goods-receipts.search-products` is a good bet for general product search.
const res = await axios.get(route('goods-receipts.search-products'), { params: { query: search } });
setResults(res.data);
} catch (e) {
console.error(e);
} finally {
setLoading(false);
}
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<Button
variant="outline"
size="sm"
className="h-8 border-primary-100 text-primary-main hover:bg-primary-50 px-3 flex items-center gap-2"
onClick={() => setOpen(true)}
>
<Plus className="h-4 w-4" />
調
</Button>
<DialogContent className="sm:max-w-[500px] p-0 overflow-hidden border-none shadow-2xl">
<DialogHeader className="bg-primary-main p-6">
<DialogTitle className="text-white text-xl flex items-center gap-2">
<Search className="h-5 w-5" />
</DialogTitle>
</DialogHeader>
<div className="p-6 space-y-4">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-grey-400" />
<Input
placeholder="輸入商品名稱、代號或條碼..."
className="pl-11 h-12 border-grey-200 rounded-xl text-lg focus:ring-primary-main transition-all"
value={search}
onChange={e => setSearch(e.target.value)}
autoFocus
/>
</div>
<div className="h-[350px] overflow-y-auto rounded-xl border border-grey-100 bg-grey-50">
{loading ? (
<div className="flex flex-col items-center justify-center h-full text-grey-400 space-y-3">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-main"></div>
<span className="text-sm font-medium">...</span>
</div>
) : results.length === 0 ? (
<div className="flex flex-col items-center justify-center h-full text-grey-400 p-8 text-center space-y-2">
<Search className="h-10 w-10 opacity-20" />
<p className="text-sm"></p>
</div>
) : (
<div className="divide-y divide-grey-100">
{results.map(product => (
<div
key={product.id}
className="p-4 hover:bg-white cursor-pointer flex justify-between items-center group transition-colors"
onClick={() => {
onSelect(product, null);
setOpen(false);
setSearch('');
setResults([]);
}}
>
<div className="space-y-1">
<div className="font-bold text-grey-900 group-hover:text-primary-main transition-colors">{product.name}</div>
<div className="text-xs text-grey-500 font-mono tracking-tight">{product.code}</div>
</div>
<div className="flex flex-col items-end gap-2">
<Badge variant="outline" className="text-[10px] h-5 border-grey-200">{product.unit || '單位'}</Badge>
<span className="text-[10px] text-grey-400"></span>
</div>
</div>
))}
</div>
)}
</div>
</div>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,324 @@
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, Link, useForm, router } from '@inertiajs/react';
import { useState, useCallback, useEffect } from 'react';
import { debounce } from "lodash";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/Components/ui/table';
import { Button } from '@/Components/ui/button';
import { Input } from '@/Components/ui/input';
import { Card, CardContent } from '@/Components/ui/card';
import { Badge } from '@/Components/ui/badge';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/Components/ui/dialog";
import { Label } from '@/Components/ui/label';
import {
Plus,
Search,
X,
ClipboardCheck,
Eye,
Pencil
} from 'lucide-react';
import Pagination from '@/Components/shared/Pagination';
import { Can } from '@/Components/Permission/Can';
export default function Index({ auth, docs, warehouses, filters }: any) {
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
const { data, setData, post, processing, reset, errors } = useForm({
warehouse_id: '',
remarks: '',
});
const [searchTerm, setSearchTerm] = useState(filters.search || "");
const [warehouseFilter, setWarehouseFilter] = useState(filters.warehouse_id || "all");
const [perPage, setPerPage] = useState(filters.per_page || "10");
// Sync state with props
useEffect(() => {
setSearchTerm(filters.search || "");
setWarehouseFilter(filters.warehouse_id || "all");
setPerPage(filters.per_page || "10");
}, [filters]);
// Debounced Search Handler
const debouncedSearch = useCallback(
debounce((term: string, warehouse: string) => {
router.get(
route('inventory.count.index'),
{ ...filters, search: term, warehouse_id: warehouse === "all" ? "" : warehouse },
{ preserveState: true, replace: true, preserveScroll: true }
);
}, 500),
[filters]
);
const handleSearchChange = (term: string) => {
setSearchTerm(term);
debouncedSearch(term, warehouseFilter);
};
const handleFilterChange = (value: string) => {
setWarehouseFilter(value);
router.get(
route('inventory.count.index'),
{ ...filters, warehouse_id: value === "all" ? "" : value },
{ preserveState: false, replace: true, preserveScroll: true }
);
};
const handleClearSearch = () => {
setSearchTerm("");
router.get(
route('inventory.count.index'),
{ ...filters, search: "", warehouse_id: warehouseFilter === "all" ? "" : warehouseFilter },
{ preserveState: true, replace: true, preserveScroll: true }
);
};
const handlePerPageChange = (value: string) => {
setPerPage(value);
router.get(
route('inventory.count.index'),
{ ...filters, per_page: value },
{ preserveState: false, replace: true, preserveScroll: true }
);
};
const handleCreate = (e) => {
e.preventDefault();
post(route('inventory.count.store'), {
onSuccess: () => {
setIsCreateDialogOpen(false);
reset();
},
});
};
const getStatusBadge = (status) => {
switch (status) {
case 'draft':
return <Badge variant="secondary">稿</Badge>;
case 'counting':
return <Badge className="bg-blue-500 hover:bg-blue-600"></Badge>;
case 'completed':
return <Badge className="bg-green-500 hover:bg-green-600"></Badge>;
case 'cancelled':
return <Badge variant="destructive"></Badge>;
default:
return <Badge variant="outline">{status}</Badge>;
}
};
return (
<AuthenticatedLayout
breadcrumbs={[
{ label: '商品與庫存與管理', href: '#' },
{ label: '庫存盤點', href: route('inventory.count.index'), isPage: true },
]}
>
<Head title="庫存盤點" />
<div className="container mx-auto p-6 max-w-7xl">
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<ClipboardCheck className="h-6 w-6 text-primary-main" />
</h1>
<p className="text-gray-500 mt-1">
</p>
</div>
</div>
{/* Toolbar */}
<div className="bg-white rounded-lg shadow-sm border p-4 mb-6">
<div className="flex flex-col md:flex-row gap-4">
{/* Search */}
<div className="flex-1 relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
<Input
placeholder="搜尋盤點單號、備註..."
value={searchTerm}
onChange={(e) => handleSearchChange(e.target.value)}
className="pl-10 pr-10 h-9"
/>
{searchTerm && (
<button
onClick={handleClearSearch}
className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
>
<X className="h-4 w-4" />
</button>
)}
</div>
{/* Warehouse Filter */}
<SearchableSelect
value={warehouseFilter}
onValueChange={handleFilterChange}
options={[
{ label: "所有倉庫", value: "all" },
...warehouses.map((w: any) => ({ label: w.name, value: w.id.toString() }))
]}
placeholder="選擇倉庫"
className="w-full md:w-[200px] h-9"
/>
{/* Action Buttons */}
<div className="flex gap-2 w-full md:w-auto">
<Can permission="inventory.view">
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogTrigger asChild>
<Button className="flex-1 md:flex-none button-filled-primary">
<Plus className="w-4 h-4 mr-2" />
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<form onSubmit={handleCreate}>
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="space-y-2">
<Label htmlFor="warehouse"></Label>
<SearchableSelect
value={data.warehouse_id}
onValueChange={(val) => setData('warehouse_id', val)}
options={warehouses.map((w: any) => ({ label: w.name, value: w.id.toString() }))}
placeholder="請選擇倉庫"
className="h-9"
/>
{errors.warehouse_id && <p className="text-red-500 text-sm">{errors.warehouse_id}</p>}
</div>
<div className="space-y-2">
<Label htmlFor="remarks"></Label>
<Input
id="remarks"
className="h-9"
value={data.remarks}
onChange={(e) => setData('remarks', e.target.value)}
/>
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setIsCreateDialogOpen(false)}>
</Button>
<Button type="submit" className="button-filled-primary" disabled={processing || !data.warehouse_id}>
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</Can>
</div>
</div>
</div>
<div className="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">
<Table>
<TableHeader className="bg-gray-50">
<TableRow>
<TableHead className="w-[50px] text-center">#</TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead className="text-center"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{docs.data.length === 0 ? (
<TableRow>
<TableCell colSpan={8} className="text-center h-24 text-gray-500">
</TableCell>
</TableRow>
) : (
docs.data.map((doc, index) => (
<TableRow key={doc.id}>
<TableCell className="text-gray-500 font-medium text-center">
{(docs.current_page - 1) * docs.per_page + index + 1}
</TableCell>
<TableCell className="font-medium text-primary-main">{doc.doc_no}</TableCell>
<TableCell>{doc.warehouse_name}</TableCell>
<TableCell>{getStatusBadge(doc.status)}</TableCell>
<TableCell className="text-gray-500 text-sm">{doc.snapshot_date}</TableCell>
<TableCell className="text-gray-500 text-sm">{doc.completed_at || '-'}</TableCell>
<TableCell className="text-sm">{doc.created_by}</TableCell>
<TableCell className="text-center">
<div className="flex items-center justify-center gap-2">
<Can permission="inventory.view">
<Link href={route('inventory.count.show', [doc.id])}>
<Button
variant="outline"
size="sm"
className="button-outlined-primary"
title={doc.status === 'completed' ? '查閱' : '盤點'}
>
{doc.status === 'completed' ? (
<Eye className="w-4 h-4 mr-1" />
) : (
<Pencil className="w-4 h-4 mr-1" />
)}
{doc.status === 'completed' ? '查閱' : '盤點'}
</Button>
</Link>
</Can>
</div>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
<div className="mt-4 flex flex-col sm:flex-row items-center justify-between gap-4">
<div className="flex items-center gap-4">
<div className="flex items-center gap-2 text-sm text-gray-500">
<span></span>
<SearchableSelect
value={perPage}
onValueChange={handlePerPageChange}
options={[
{ label: "10", value: "10" },
{ label: "20", value: "20" },
{ label: "50", value: "50" },
{ label: "100", value: "100" }
]}
className="w-[100px] h-8"
showSearch={false}
/>
<span></span>
</div>
<span className="text-sm text-gray-500"> {docs.total} </span>
</div>
<Pagination links={docs.links} />
</div>
</div>
</AuthenticatedLayout>
);
}

View File

@@ -0,0 +1,275 @@
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, useForm } from '@inertiajs/react';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/Components/ui/table';
import { Button } from '@/Components/ui/button';
import { Input } from '@/Components/ui/input';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/Components/ui/card';
import { Badge } from '@/Components/ui/badge';
import { Save, CheckCircle, Printer, Trash2, ClipboardCheck, Eye, Pencil } from 'lucide-react';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/Components/ui/alert-dialog"
import { Can } from '@/Components/Permission/Can';
import { Link } from '@inertiajs/react';
export default function Show({ doc }: any) {
// Transform items to form data structure
const { data, setData, put, delete: destroy, processing } = useForm({
items: doc.items.map((item: any) => ({
id: item.id,
counted_qty: item.counted_qty,
notes: item.notes || '',
})),
action: 'save', // 'save' or 'complete'
});
// Helper to update local form data
const updateItem = (index: number, field: string, value: any) => {
const newItems = [...data.items];
newItems[index][field] = value;
setData('items', newItems);
};
const handleSubmit = (action: string) => {
setData('action', action);
put(route('inventory.count.update', [doc.id]), {
onSuccess: () => {
// Handle success if needed
}
});
};
const handleDelete = () => {
destroy(route('inventory.count.destroy', [doc.id]));
};
const isCompleted = doc.status === 'completed';
// Calculate progress
const totalItems = doc.items.length;
const countedItems = data.items.filter((i: any) => i.counted_qty !== '' && i.counted_qty !== null).length;
const progress = Math.round((countedItems / totalItems) * 100) || 0;
return (
<AuthenticatedLayout
breadcrumbs={[
{ label: '商品與庫存管理', href: '#' },
{ label: '庫存盤點', href: route('inventory.count.index') },
{ label: `盤點單: ${doc.doc_no}`, href: route('inventory.count.show', [doc.id]), isPage: true },
]}
>
<Head title={`盤點單 ${doc.doc_no}`} />
<div className="container mx-auto p-6 max-w-7xl">
<div className="flex items-center justify-between mb-6">
<div className="flex items-center gap-4">
<div>
<div className="flex items-center gap-2">
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
<ClipboardCheck className="h-6 w-6 text-primary-main" />
: {doc.doc_no}
</h1>
{doc.status === 'completed' ? (
<Badge className="bg-green-500 hover:bg-green-600"></Badge>
) : (
<Badge className="bg-blue-500 hover:bg-blue-600"></Badge>
)}
</div>
<p className="text-sm text-gray-500 mt-1">
: {doc.warehouse_name} | : {doc.created_by} | : {doc.snapshot_date}
</p>
</div>
</div>
<div className="flex items-center gap-2">
{!isCompleted && (
<div className="flex items-center gap-2">
<Can permission="inventory.view">
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="outline" size="sm" disabled={processing} className="button-outlined-error">
<Trash2 className="w-4 h-4 mr-2" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle></AlertDialogTitle>
<AlertDialogDescription>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={handleDelete} className="bg-red-600 hover:bg-red-700"></AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<Button
variant="outline"
size="sm"
className="button-outlined-primary"
onClick={() => handleSubmit('save')}
disabled={processing}
>
<Save className="w-4 h-4 mr-2" />
</Button>
<Button
size="sm"
className="button-filled-primary"
onClick={() => handleSubmit('complete')}
disabled={processing}
>
<CheckCircle className="w-4 h-4 mr-2" />
</Button>
</Can>
</div>
)}
{isCompleted && (
<Button variant="outline" size="sm" onClick={() => window.print()}>
<Printer className="w-4 h-4 mr-2" />
</Button>
)}
</div>
</div>
<div className="max-w-7xl mx-auto space-y-6">
{!isCompleted && (
<Card className="border-none shadow-sm overflow-hidden">
<CardContent className="py-4">
<div className="flex items-center justify-between text-sm mb-2">
<span className="text-gray-500">: {countedItems} / {totalItems} </span>
<span className="font-semibold text-primary-main">{progress}%</span>
</div>
<div className="w-full bg-gray-200 rounded-full h-2">
<div className="bg-primary-main h-2 rounded-full transition-all duration-300" style={{ width: `${progress}%` }}></div>
</div>
</CardContent>
</Card>
)}
<Card className="border border-gray-200 shadow-sm overflow-hidden gap-0">
<CardHeader className="bg-white border-b px-6 py-4">
<CardTitle className="text-lg font-medium"></CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<Table>
<TableHeader className="bg-gray-50">
<TableRow>
<TableHead className="w-[50px] text-center">#</TableHead>
<TableHead> / </TableHead>
<TableHead></TableHead>
<TableHead className="text-right"></TableHead>
<TableHead className="text-right w-32"></TableHead>
<TableHead className="text-right"></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{doc.items.map((item: any, index: number) => {
const formItem = data.items[index];
const diff = formItem.counted_qty !== '' && formItem.counted_qty !== null
? (parseFloat(formItem.counted_qty) - item.system_qty)
: 0;
const hasDiff = Math.abs(diff) > 0.0001;
return (
<TableRow key={item.id} className={hasDiff && formItem.counted_qty !== '' ? "bg-red-50/30" : ""}>
<TableCell className="text-gray-500 font-medium text-center">
{index + 1}
</TableCell>
<TableCell>
<div className="flex flex-col">
<span className="font-medium text-gray-900">{item.product_code}</span>
<span className="text-xs text-gray-500">{item.product_name}</span>
</div>
</TableCell>
<TableCell className="text-sm font-mono">{item.batch_number || '-'}</TableCell>
<TableCell className="text-right font-medium">{item.system_qty.toFixed(2)}</TableCell>
<TableCell className="text-right px-1">
{isCompleted ? (
<span className="font-medium mr-2">{item.counted_qty}</span>
) : (
<Input
type="number"
step="0.01"
value={formItem.counted_qty ?? ''}
onChange={(e) => updateItem(index, 'counted_qty', e.target.value)}
onWheel={(e: any) => e.target.blur()}
disabled={processing}
className="h-9 text-right font-medium focus:ring-primary-main"
placeholder="盤點..."
/>
)}
</TableCell>
<TableCell className="text-right">
<span className={`font-bold ${!hasDiff
? 'text-gray-400'
: diff > 0
? 'text-green-600'
: 'text-red-600'
}`}>
{formItem.counted_qty !== '' && formItem.counted_qty !== null
? diff.toFixed(2)
: '-'}
</span>
</TableCell>
<TableCell className="text-sm text-gray-500">{item.unit || item.unit_name}</TableCell>
<TableCell className="px-1">
{isCompleted ? (
<span className="text-sm text-gray-600">{item.notes}</span>
) : (
<Input
value={formItem.notes}
onChange={(e) => updateItem(index, 'notes', e.target.value)}
disabled={processing}
className="h-9 text-sm"
placeholder="備註..."
/>
)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</Card>
<div className="bg-gray-50/80 border border-dashed border-grey-200 rounded-lg p-4 flex items-start gap-3">
<div className="bg-blue-100 p-2 rounded-lg">
<Save className="w-5 h-5 text-blue-600" />
</div>
<div>
<h4 className="font-semibold text-gray-900 mb-1 text-sm"></h4>
<p className="text-xs text-gray-500 leading-relaxed">
調
</p>
</div>
</div>
</div>
</div>
</AuthenticatedLayout>
);
}

View File

@@ -0,0 +1,255 @@
import { useState, useEffect } from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, Link, router } from "@inertiajs/react";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/Components/ui/table";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Badge } from "@/Components/ui/badge";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
DialogFooter,
} from "@/Components/ui/dialog";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/Components/ui/select";
import { Label } from "@/Components/ui/label";
import {
Plus,
Search,
FileText,
ArrowLeftRight,
Loader2,
} from "lucide-react";
import { format } from "date-fns";
import Pagination from "@/Components/shared/Pagination";
import { toast } from "sonner";
export default function Index({ auth, orders, warehouses, filters }) {
const [searchQuery, setSearchQuery] = useState("");
// Create Dialog State
const [isCreateOpen, setIsCreateOpen] = useState(false);
const [sourceWarehouseId, setSourceWarehouseId] = useState("");
const [targetWarehouseId, setTargetWarehouseId] = useState("");
const [creating, setCreating] = useState(false);
// Handle warehouse filter change
const handleFilterChange = (value) => {
router.get(route('inventory.transfer.index'), { warehouse_id: value }, {
preserveState: true,
replace: true,
});
};
const handleCreate = () => {
if (!sourceWarehouseId) {
toast.error("請選擇來源倉庫");
return;
}
if (!targetWarehouseId) {
toast.error("請選擇目的倉庫");
return;
}
if (sourceWarehouseId === targetWarehouseId) {
toast.error("來源與目的倉庫不能相同");
return;
}
setCreating(true);
router.post(route('inventory.transfer.store'), {
from_warehouse_id: sourceWarehouseId,
to_warehouse_id: targetWarehouseId
}, {
onFinish: () => setCreating(false),
onSuccess: () => {
setIsCreateOpen(false);
setSourceWarehouseId("");
setTargetWarehouseId("");
}
});
};
const getStatusBadge = (status) => {
switch (status) {
case 'draft':
return <Badge variant="secondary">稿</Badge>;
case 'completed':
return <Badge className="bg-green-600"></Badge>;
case 'voided':
return <Badge variant="destructive"></Badge>;
default:
return <Badge variant="outline">{status}</Badge>;
}
};
return (
<AuthenticatedLayout
user={auth.user}
header={
<div className="flex justify-between items-center">
<h2 className="font-semibold text-xl text-gray-800 leading-tight flex items-center gap-2">
<ArrowLeftRight className="h-5 w-5" />
調
</h2>
</div>
}
>
<Head title="庫存調撥" />
<div className="py-12">
<div className="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div className="bg-white overflow-hidden shadow-sm sm:rounded-lg">
<div className="p-6">
<div className="flex justify-between items-center mb-6">
<div className="flex items-center gap-4">
<div className="w-[200px]">
<Select
value={filters.warehouse_id || "all"}
onValueChange={(val) => handleFilterChange(val === "all" ? "" : val)}
>
<SelectTrigger>
<SelectValue placeholder="篩選倉庫..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
{warehouses.map((w) => (
<SelectItem key={w.id} value={String(w.id)}>{w.name}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="relative flex-1 max-w-sm">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-500" />
<Input
placeholder="搜尋調撥單號..."
className="pl-9"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
</div>
<Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="h-4 w-4 mr-2" />
調
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>調</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label></Label>
<Select onValueChange={setSourceWarehouseId} value={sourceWarehouseId}>
<SelectTrigger>
<SelectValue placeholder="選擇來源倉庫" />
</SelectTrigger>
<SelectContent>
{warehouses.map(w => (
<SelectItem key={w.id} value={String(w.id)}>{w.name}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label></Label>
<Select onValueChange={setTargetWarehouseId} value={targetWarehouseId}>
<SelectTrigger>
<SelectValue placeholder="選擇目的倉庫" />
</SelectTrigger>
<SelectContent>
{warehouses.filter(w => String(w.id) !== sourceWarehouseId).map(w => (
<SelectItem key={w.id} value={String(w.id)}>{w.name}</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsCreateOpen(false)}></Button>
<Button onClick={handleCreate} disabled={creating || !sourceWarehouseId || !targetWarehouseId}>
{creating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
稿
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead className="text-right"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{orders.data.length === 0 ? (
<TableRow>
<TableCell colSpan={8} className="text-center h-24 text-gray-500">
調
</TableCell>
</TableRow>
) : (
orders.data.map((order) => (
<TableRow key={order.id}>
<TableCell className="font-medium">{order.doc_no}</TableCell>
<TableCell>{getStatusBadge(order.status)}</TableCell>
<TableCell>{order.from_warehouse_name}</TableCell>
<TableCell>{order.to_warehouse_name}</TableCell>
<TableCell>{order.created_at}</TableCell>
<TableCell>{order.posted_at}</TableCell>
<TableCell>{order.created_by}</TableCell>
<TableCell className="text-right">
<Button
variant="ghost"
size="sm"
asChild
>
<Link href={route('inventory.transfer.show', [order.id])}>
</Link>
</Button>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
<div className="mt-4">
<Pagination links={orders.links} />
</div>
</div>
</div>
</div>
</div>
</AuthenticatedLayout>
);
}

View File

@@ -0,0 +1,336 @@
import { useState, useEffect } from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, router, usePage } from "@inertiajs/react";
import { Button } from "@/Components/ui/button";
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";
import { Badge } from "@/Components/ui/badge";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
DialogFooter,
} from "@/Components/ui/dialog";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/Components/ui/select";
import { Plus, Save, Trash2, ArrowLeft, CheckCircle, Ban, History, Package } from "lucide-react";
import { toast } from "sonner";
import axios from "axios";
export default function Show({ auth, order }) {
const [items, setItems] = useState(order.items || []);
const [remarks, setRemarks] = useState(order.remarks || "");
const [isSaving, setIsSaving] = useState(false);
// Product Selection
const [isProductDialogOpen, setIsProductDialogOpen] = useState(false);
const [availableInventory, setAvailableInventory] = useState([]);
const [loadingInventory, setLoadingInventory] = useState(false);
useEffect(() => {
if (isProductDialogOpen) {
loadInventory();
}
}, [isProductDialogOpen]);
const loadInventory = async () => {
setLoadingInventory(true);
try {
// Fetch inventory from SOURCE warehouse
const response = await axios.get(route('api.warehouses.inventories', order.from_warehouse_id));
setAvailableInventory(response.data);
} catch (error) {
console.error("Failed to load inventory", error);
toast.error("無法載入庫存資料");
} finally {
setLoadingInventory(false);
}
};
const handleAddItem = (inventoryItem) => {
// Check if already added
const exists = items.find(i =>
i.product_id === inventoryItem.product_id &&
i.batch_number === inventoryItem.batch_number
);
if (exists) {
toast.error("該商品與批號已在列表中");
return;
}
setItems([...items, {
product_id: inventoryItem.product_id,
product_name: inventoryItem.product_name,
product_code: inventoryItem.product_code,
batch_number: inventoryItem.batch_number,
unit: inventoryItem.unit_name,
quantity: 1, // Default 1
max_quantity: inventoryItem.quantity, // Max available
notes: "",
}]);
setIsProductDialogOpen(false);
};
const handleUpdateItem = (index, field, value) => {
const newItems = [...items];
newItems[index][field] = value;
setItems(newItems);
};
const handleRemoveItem = (index) => {
const newItems = items.filter((_, i) => i !== index);
setItems(newItems);
};
const handleSave = async () => {
setIsSaving(true);
try {
await router.put(route('inventory.transfer.update', [order.id]), {
items: items,
remarks: remarks,
}, {
onSuccess: () => toast.success("儲存成功"),
onError: () => toast.error("儲存失敗,請檢查輸入"),
});
} finally {
setIsSaving(false);
}
};
const handlePost = () => {
if (!confirm("確定要過帳嗎?過帳後庫存將立即轉移且無法修改。")) return;
router.put(route('inventory.transfer.update', [order.id]), {
action: 'post'
});
};
const handleDelete = () => {
if (!confirm("確定要刪除此草稿嗎?")) return;
router.delete(route('inventory.transfer.destroy', [order.id]));
};
const isReadOnly = order.status !== 'draft';
return (
<AuthenticatedLayout
user={auth.user}
header={
<div className="flex justify-between items-center">
<h2 className="font-semibold text-xl text-gray-800 leading-tight flex items-center gap-2">
<ArrowLeft className="h-5 w-5 cursor-pointer" onClick={() => router.visit(route('inventory.transfer.index'))} />
調 ({order.doc_no})
</h2>
<div className="flex gap-2">
{!isReadOnly && (
<>
<Button variant="destructive" onClick={handleDelete}>
<Trash2 className="h-4 w-4 mr-2" />
</Button>
<Button variant="outline" onClick={handleSave} disabled={isSaving}>
<Save className="h-4 w-4 mr-2" />
稿
</Button>
<Button onClick={handlePost} disabled={items.length === 0}>
<CheckCircle className="h-4 w-4 mr-2" />
</Button>
</>
)}
</div>
</div>
}
breadcrumbs={[
{ label: '首頁', href: '/' },
{ label: '庫存調撥', href: route('inventory.transfer.index') },
{ label: order.doc_no, href: route('inventory.transfer.show', [order.id]) },
]}
>
<Head title={`調撥單 ${order.doc_no}`} />
<div className="py-12">
<div className="max-w-7xl mx-auto sm:px-6 lg:px-8 space-y-6">
{/* Header Info */}
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-100 grid grid-cols-1 md:grid-cols-4 gap-6">
<div>
<Label className="text-gray-500"></Label>
<div className="font-medium text-lg">{order.from_warehouse_name}</div>
</div>
<div>
<Label className="text-gray-500"></Label>
<div className="font-medium text-lg">{order.to_warehouse_name}</div>
</div>
<div>
<Label className="text-gray-500"></Label>
<div className="mt-1">
{order.status === 'draft' && <Badge variant="secondary">稿</Badge>}
{order.status === 'completed' && <Badge className="bg-green-600"></Badge>}
{order.status === 'voided' && <Badge variant="destructive"></Badge>}
</div>
</div>
<div>
<Label className="text-gray-500"></Label>
{isReadOnly ? (
<div className="mt-1 text-gray-700">{order.remarks || '-'}</div>
) : (
<Input
value={remarks}
onChange={(e) => setRemarks(e.target.value)}
className="mt-1"
placeholder="填寫備註..."
/>
)}
</div>
</div>
{/* Items */}
<div className="bg-white overflow-hidden shadow-sm sm:rounded-lg">
<div className="p-6">
<div className="flex justify-between items-center mb-4">
<h3 className="text-lg font-semibold">調</h3>
{!isReadOnly && (
<Dialog open={isProductDialogOpen} onOpenChange={setIsProductDialogOpen}>
<DialogTrigger asChild>
<Button variant="outline">
<Plus className="h-4 w-4 mr-2" />
</Button>
</DialogTrigger>
<DialogContent className="max-w-3xl max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle> ({order.from_warehouse_name})</DialogTitle>
</DialogHeader>
<div className="mt-4">
{loadingInventory ? (
<div className="text-center py-4">...</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead className="text-right"></TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{availableInventory.map((inv) => (
<TableRow key={`${inv.product_id}-${inv.batch_number}`}>
<TableCell>{inv.product_code}</TableCell>
<TableCell>{inv.product_name}</TableCell>
<TableCell>{inv.batch_number || '-'}</TableCell>
<TableCell className="text-right">{inv.quantity} {inv.unit_name}</TableCell>
<TableCell className="text-right">
<Button size="sm" onClick={() => handleAddItem(inv)}>
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</div>
</DialogContent>
</Dialog>
)}
</div>
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[50px]">#</TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead className="w-[150px]">調</TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
{!isReadOnly && <TableHead className="w-[50px]"></TableHead>}
</TableRow>
</TableHeader>
<TableBody>
{items.length === 0 ? (
<TableRow>
<TableCell colSpan={7} className="text-center h-24 text-gray-500">
</TableCell>
</TableRow>
) : (
items.map((item, index) => (
<TableRow key={index}>
<TableCell>{index + 1}</TableCell>
<TableCell>
<div>{item.product_name}</div>
<div className="text-xs text-gray-500">{item.product_code}</div>
</TableCell>
<TableCell>{item.batch_number || '-'}</TableCell>
<TableCell>
{isReadOnly ? (
item.quantity
) : (
<div className="flex flex-col gap-1">
<Input
type="number"
min="0.01"
step="0.01"
value={item.quantity}
onChange={(e) => handleUpdateItem(index, 'quantity', e.target.value)}
/>
{item.max_quantity && (
<span className="text-xs text-gray-500">: {item.max_quantity}</span>
)}
</div>
)}
</TableCell>
<TableCell>{item.unit}</TableCell>
<TableCell>
{isReadOnly ? (
item.notes
) : (
<Input
value={item.notes}
onChange={(e) => handleUpdateItem(index, 'notes', e.target.value)}
placeholder="備註"
/>
)}
</TableCell>
{!isReadOnly && (
<TableCell>
<Button variant="ghost" size="icon" onClick={() => handleRemoveItem(index)}>
<Trash2 className="h-4 w-4 text-red-500" />
</Button>
</TableCell>
)}
</TableRow>
))
)}
</TableBody>
</Table>
</div>
</div>
</div>
</div>
</div>
</AuthenticatedLayout>
);
}