feat: 實作即時庫存查詢功能、儀表板庫存導盤,及優化手動入庫批號與儲位連動與選單顯示
This commit is contained in:
@@ -32,20 +32,16 @@ class DashboardController extends Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
$invStats = $this->inventoryService->getDashboardStats();
|
$invStats = $this->inventoryService->getDashboardStats();
|
||||||
$procStats = $this->procurementService->getDashboardStats();
|
|
||||||
|
|
||||||
$stats = [
|
|
||||||
'productsCount' => $invStats['productsCount'],
|
|
||||||
'vendorsCount' => $procStats['vendorsCount'],
|
|
||||||
'purchaseOrdersCount' => $procStats['purchaseOrdersCount'],
|
|
||||||
'warehousesCount' => $invStats['warehousesCount'],
|
|
||||||
'totalInventoryValue' => $invStats['totalInventoryQuantity'], // 原本前端命名是 totalInventoryValue 但實作是 Quantity,暫且保留欄位名以不破壞前端
|
|
||||||
'pendingOrdersCount' => $procStats['pendingOrdersCount'],
|
|
||||||
'lowStockCount' => $invStats['lowStockCount'],
|
|
||||||
];
|
|
||||||
|
|
||||||
return Inertia::render('Dashboard', [
|
return Inertia::render('Dashboard', [
|
||||||
'stats' => $stats,
|
'stats' => [
|
||||||
|
'totalItems' => $invStats['productsCount'],
|
||||||
|
'lowStockCount' => $invStats['lowStockCount'],
|
||||||
|
'negativeCount' => $invStats['negativeCount'] ?? 0,
|
||||||
|
'expiringCount' => $invStats['expiringCount'] ?? 0,
|
||||||
|
],
|
||||||
|
'abnormalItems' => $invStats['abnormalItems'] ?? [],
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -116,6 +116,15 @@ interface InventoryServiceInterface
|
|||||||
*/
|
*/
|
||||||
public function findInventoryByBatch(int $warehouseId, int $productId, ?string $batchNumber);
|
public function findInventoryByBatch(int $warehouseId, int $productId, ?string $batchNumber);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取得即時庫存查詢資料(含統計卡片 + 分頁明細)。
|
||||||
|
*
|
||||||
|
* @param array $filters 篩選條件
|
||||||
|
* @param int $perPage 每頁筆數
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function getStockQueryData(array $filters = [], int $perPage = 10): array;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get statistics for the dashboard.
|
* Get statistics for the dashboard.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -295,7 +295,8 @@ class InventoryController extends Controller
|
|||||||
'originCountry' => $inventory->origin_country,
|
'originCountry' => $inventory->origin_country,
|
||||||
'expiryDate' => $inventory->expiry_date ? $inventory->expiry_date->format('Y-m-d') : null,
|
'expiryDate' => $inventory->expiry_date ? $inventory->expiry_date->format('Y-m-d') : null,
|
||||||
'quantity' => (float) $inventory->quantity,
|
'quantity' => (float) $inventory->quantity,
|
||||||
'unitCost' => (float) $inventory->unit_cost, // 新增
|
'unitCost' => (float) $inventory->unit_cost,
|
||||||
|
'location' => $inventory->location,
|
||||||
];
|
];
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
59
app/Modules/Inventory/Controllers/StockQueryController.php
Normal file
59
app/Modules/Inventory/Controllers/StockQueryController.php
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Modules\Inventory\Controllers;
|
||||||
|
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use App\Modules\Inventory\Contracts\InventoryServiceInterface;
|
||||||
|
use App\Modules\Inventory\Models\Category;
|
||||||
|
use App\Modules\Inventory\Models\Warehouse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
|
||||||
|
class StockQueryController extends Controller
|
||||||
|
{
|
||||||
|
protected InventoryServiceInterface $inventoryService;
|
||||||
|
|
||||||
|
public function __construct(InventoryServiceInterface $inventoryService)
|
||||||
|
{
|
||||||
|
$this->inventoryService = $inventoryService;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 即時庫存查詢頁面
|
||||||
|
*/
|
||||||
|
public function index(Request $request)
|
||||||
|
{
|
||||||
|
$filters = $request->only(['warehouse_id', 'category_id', 'search', 'status', 'sort_by', 'sort_order', 'per_page']);
|
||||||
|
$perPage = (int) ($filters['per_page'] ?? 10);
|
||||||
|
|
||||||
|
$result = $this->inventoryService->getStockQueryData($filters, $perPage);
|
||||||
|
|
||||||
|
return Inertia::render('Inventory/StockQuery/Index', [
|
||||||
|
'filters' => $filters,
|
||||||
|
'summary' => $result['summary'],
|
||||||
|
'inventories' => [
|
||||||
|
'data' => $result['data'],
|
||||||
|
'total' => $result['pagination']['total'],
|
||||||
|
'per_page' => $result['pagination']['per_page'],
|
||||||
|
'current_page' => $result['pagination']['current_page'],
|
||||||
|
'last_page' => $result['pagination']['last_page'],
|
||||||
|
'links' => $result['pagination']['links'],
|
||||||
|
],
|
||||||
|
'warehouses' => Warehouse::select('id', 'name')->orderBy('name')->get(),
|
||||||
|
'categories' => Category::select('id', 'name')->orderBy('name')->get(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Excel 匯出
|
||||||
|
*/
|
||||||
|
public function export(Request $request)
|
||||||
|
{
|
||||||
|
$filters = $request->only(['warehouse_id', 'category_id', 'search', 'status']);
|
||||||
|
|
||||||
|
return \Maatwebsite\Excel\Facades\Excel::download(
|
||||||
|
new \App\Modules\Inventory\Exports\StockQueryExport($filters),
|
||||||
|
'即時庫存查詢_' . now()->format('Ymd_His') . '.xlsx'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
167
app/Modules/Inventory/Exports/StockQueryExport.php
Normal file
167
app/Modules/Inventory/Exports/StockQueryExport.php
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Modules\Inventory\Exports;
|
||||||
|
|
||||||
|
use App\Modules\Inventory\Models\Inventory;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Maatwebsite\Excel\Concerns\FromCollection;
|
||||||
|
use Maatwebsite\Excel\Concerns\WithHeadings;
|
||||||
|
use Maatwebsite\Excel\Concerns\WithMapping;
|
||||||
|
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
|
||||||
|
use Maatwebsite\Excel\Concerns\WithStyles;
|
||||||
|
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
|
||||||
|
|
||||||
|
class StockQueryExport implements FromCollection, WithHeadings, WithMapping, ShouldAutoSize, WithStyles
|
||||||
|
{
|
||||||
|
protected array $filters;
|
||||||
|
|
||||||
|
public function __construct(array $filters = [])
|
||||||
|
{
|
||||||
|
$this->filters = $filters;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function collection()
|
||||||
|
{
|
||||||
|
$today = now()->toDateString();
|
||||||
|
$expiryThreshold = now()->addDays(30)->toDateString();
|
||||||
|
|
||||||
|
$query = Inventory::query()
|
||||||
|
->join('products', 'inventories.product_id', '=', 'products.id')
|
||||||
|
->join('warehouses', 'inventories.warehouse_id', '=', 'warehouses.id')
|
||||||
|
->leftJoin('categories', 'products.category_id', '=', 'categories.id')
|
||||||
|
->leftJoin('warehouse_product_safety_stocks as ss', function ($join) {
|
||||||
|
$join->on('inventories.warehouse_id', '=', 'ss.warehouse_id')
|
||||||
|
->on('inventories.product_id', '=', 'ss.product_id');
|
||||||
|
})
|
||||||
|
->whereNull('inventories.deleted_at')
|
||||||
|
->select([
|
||||||
|
'inventories.id',
|
||||||
|
'inventories.quantity',
|
||||||
|
'inventories.batch_number',
|
||||||
|
'inventories.expiry_date',
|
||||||
|
'inventories.quality_status',
|
||||||
|
'products.code as product_code',
|
||||||
|
'products.name as product_name',
|
||||||
|
'categories.name as category_name',
|
||||||
|
'warehouses.name as warehouse_name',
|
||||||
|
'ss.safety_stock',
|
||||||
|
]);
|
||||||
|
|
||||||
|
// 篩選
|
||||||
|
if (!empty($this->filters['warehouse_id'])) {
|
||||||
|
$query->where('inventories.warehouse_id', $this->filters['warehouse_id']);
|
||||||
|
}
|
||||||
|
if (!empty($this->filters['category_id'])) {
|
||||||
|
$query->where('products.category_id', $this->filters['category_id']);
|
||||||
|
}
|
||||||
|
if (!empty($this->filters['search'])) {
|
||||||
|
$search = $this->filters['search'];
|
||||||
|
$query->where(function ($q) use ($search) {
|
||||||
|
$q->where('products.code', 'like', "%{$search}%")
|
||||||
|
->orWhere('products.name', 'like', "%{$search}%");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!empty($this->filters['status'])) {
|
||||||
|
switch ($this->filters['status']) {
|
||||||
|
case 'low_stock':
|
||||||
|
$query->whereNotNull('ss.safety_stock')
|
||||||
|
->whereRaw('inventories.quantity <= ss.safety_stock')
|
||||||
|
->where('inventories.quantity', '>=', 0);
|
||||||
|
break;
|
||||||
|
case 'negative':
|
||||||
|
$query->where('inventories.quantity', '<', 0);
|
||||||
|
break;
|
||||||
|
case 'expiring':
|
||||||
|
$query->whereNotNull('inventories.expiry_date')
|
||||||
|
->where('inventories.expiry_date', '>', $today)
|
||||||
|
->where('inventories.expiry_date', '<=', $expiryThreshold);
|
||||||
|
break;
|
||||||
|
case 'expired':
|
||||||
|
$query->whereNotNull('inventories.expiry_date')
|
||||||
|
->where('inventories.expiry_date', '<=', $today);
|
||||||
|
break;
|
||||||
|
case 'abnormal':
|
||||||
|
$query->where(function ($q) use ($today, $expiryThreshold) {
|
||||||
|
$q->where('inventories.quantity', '<', 0)
|
||||||
|
->orWhere(function ($q2) {
|
||||||
|
$q2->whereNotNull('ss.safety_stock')
|
||||||
|
->whereRaw('inventories.quantity <= ss.safety_stock');
|
||||||
|
})
|
||||||
|
->orWhere(function ($q2) use ($expiryThreshold) {
|
||||||
|
$q2->whereNotNull('inventories.expiry_date')
|
||||||
|
->where('inventories.expiry_date', '<=', $expiryThreshold);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $query->orderBy('products.code', 'asc')->get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function headings(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'商品代碼',
|
||||||
|
'商品名稱',
|
||||||
|
'分類',
|
||||||
|
'倉庫',
|
||||||
|
'批號',
|
||||||
|
'數量',
|
||||||
|
'安全庫存',
|
||||||
|
'到期日',
|
||||||
|
'品質狀態',
|
||||||
|
'狀態',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function map($row): array
|
||||||
|
{
|
||||||
|
$today = now()->toDateString();
|
||||||
|
$expiryThreshold = now()->addDays(30)->toDateString();
|
||||||
|
|
||||||
|
$statuses = [];
|
||||||
|
if ($row->quantity < 0) {
|
||||||
|
$statuses[] = '負庫存';
|
||||||
|
}
|
||||||
|
if ($row->safety_stock !== null && $row->quantity <= $row->safety_stock && $row->quantity >= 0) {
|
||||||
|
$statuses[] = '低庫存';
|
||||||
|
}
|
||||||
|
if ($row->expiry_date) {
|
||||||
|
if ($row->expiry_date <= $today) {
|
||||||
|
$statuses[] = '已過期';
|
||||||
|
} elseif ($row->expiry_date <= $expiryThreshold) {
|
||||||
|
$statuses[] = '即將過期';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (empty($statuses)) {
|
||||||
|
$statuses[] = '正常';
|
||||||
|
}
|
||||||
|
|
||||||
|
$qualityLabels = [
|
||||||
|
'normal' => '正常',
|
||||||
|
'inspecting' => '檢驗中',
|
||||||
|
'rejected' => '不合格',
|
||||||
|
];
|
||||||
|
|
||||||
|
return [
|
||||||
|
$row->product_code,
|
||||||
|
$row->product_name,
|
||||||
|
$row->category_name ?? '-',
|
||||||
|
$row->warehouse_name,
|
||||||
|
$row->batch_number ?? '-',
|
||||||
|
$row->quantity,
|
||||||
|
$row->safety_stock ?? '-',
|
||||||
|
$row->expiry_date ?? '-',
|
||||||
|
$qualityLabels[$row->quality_status] ?? $row->quality_status ?? '-',
|
||||||
|
implode('、', $statuses),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function styles(Worksheet $sheet): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
1 => ['font' => ['bold' => true]],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,8 +11,15 @@ use App\Modules\Inventory\Controllers\TransferOrderController;
|
|||||||
use App\Modules\Inventory\Controllers\CountDocController;
|
use App\Modules\Inventory\Controllers\CountDocController;
|
||||||
use App\Modules\Inventory\Controllers\AdjustDocController;
|
use App\Modules\Inventory\Controllers\AdjustDocController;
|
||||||
|
|
||||||
|
use App\Modules\Inventory\Controllers\StockQueryController;
|
||||||
|
|
||||||
Route::middleware('auth')->group(function () {
|
Route::middleware('auth')->group(function () {
|
||||||
|
|
||||||
|
// 即時庫存查詢
|
||||||
|
Route::middleware('permission:inventory.view')->group(function () {
|
||||||
|
Route::get('/inventory/stock-query', [StockQueryController::class, 'index'])->name('inventory.stock-query.index');
|
||||||
|
Route::get('/inventory/stock-query/export', [StockQueryController::class, 'export'])->name('inventory.stock-query.export');
|
||||||
|
});
|
||||||
// 類別管理 (用於商品對話框) - 需要商品權限
|
// 類別管理 (用於商品對話框) - 需要商品權限
|
||||||
Route::middleware('permission:products.view')->group(function () {
|
Route::middleware('permission:products.view')->group(function () {
|
||||||
Route::get('/categories', [CategoryController::class, 'index'])->name('categories.index');
|
Route::get('/categories', [CategoryController::class, 'index'])->name('categories.index');
|
||||||
|
|||||||
@@ -229,9 +229,137 @@ class InventoryService implements InventoryServiceInterface
|
|||||||
->first();
|
->first();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getDashboardStats(): array
|
/**
|
||||||
|
* 即時庫存查詢:統計卡片 + 分頁明細
|
||||||
|
*/
|
||||||
|
public function getStockQueryData(array $filters = [], int $perPage = 10): array
|
||||||
{
|
{
|
||||||
// 庫存總表 join 安全庫存表,計算低庫存
|
$today = now()->toDateString();
|
||||||
|
$expiryThreshold = now()->addDays(30)->toDateString();
|
||||||
|
|
||||||
|
// 基礎查詢
|
||||||
|
$query = Inventory::query()
|
||||||
|
->join('products', 'inventories.product_id', '=', 'products.id')
|
||||||
|
->join('warehouses', 'inventories.warehouse_id', '=', 'warehouses.id')
|
||||||
|
->leftJoin('categories', 'products.category_id', '=', 'categories.id')
|
||||||
|
->leftJoin('warehouse_product_safety_stocks as ss', function ($join) {
|
||||||
|
$join->on('inventories.warehouse_id', '=', 'ss.warehouse_id')
|
||||||
|
->on('inventories.product_id', '=', 'ss.product_id');
|
||||||
|
})
|
||||||
|
->whereNull('inventories.deleted_at')
|
||||||
|
->select([
|
||||||
|
'inventories.id',
|
||||||
|
'inventories.warehouse_id',
|
||||||
|
'inventories.product_id',
|
||||||
|
'inventories.quantity',
|
||||||
|
'inventories.batch_number',
|
||||||
|
'inventories.expiry_date',
|
||||||
|
'inventories.location',
|
||||||
|
'inventories.quality_status',
|
||||||
|
'inventories.arrival_date',
|
||||||
|
'products.code as product_code',
|
||||||
|
'products.name as product_name',
|
||||||
|
'categories.name as category_name',
|
||||||
|
'warehouses.name as warehouse_name',
|
||||||
|
'ss.safety_stock',
|
||||||
|
]);
|
||||||
|
|
||||||
|
// 篩選:倉庫
|
||||||
|
if (!empty($filters['warehouse_id'])) {
|
||||||
|
$query->where('inventories.warehouse_id', $filters['warehouse_id']);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 篩選:分類
|
||||||
|
if (!empty($filters['category_id'])) {
|
||||||
|
$query->where('products.category_id', $filters['category_id']);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 篩選:關鍵字(商品代碼或名稱)
|
||||||
|
if (!empty($filters['search'])) {
|
||||||
|
$search = $filters['search'];
|
||||||
|
$query->where(function ($q) use ($search) {
|
||||||
|
$q->where('products.code', 'like', "%{$search}%")
|
||||||
|
->orWhere('products.name', 'like', "%{$search}%");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 篩選:狀態 (改為對齊聚合統計的判斷標準)
|
||||||
|
if (!empty($filters['status'])) {
|
||||||
|
switch ($filters['status']) {
|
||||||
|
case 'low_stock':
|
||||||
|
$query->whereIn(DB::raw('(inventories.warehouse_id, inventories.product_id)'), function ($sub) {
|
||||||
|
$sub->select('i2.warehouse_id', 'i2.product_id')
|
||||||
|
->from('inventories as i2')
|
||||||
|
->join('warehouse_product_safety_stocks as ss2', function ($join) {
|
||||||
|
$join->on('i2.warehouse_id', '=', 'ss2.warehouse_id')
|
||||||
|
->on('i2.product_id', '=', 'ss2.product_id');
|
||||||
|
})
|
||||||
|
->whereNull('i2.deleted_at')
|
||||||
|
->groupBy('i2.warehouse_id', 'i2.product_id', 'ss2.safety_stock')
|
||||||
|
->havingRaw('SUM(i2.quantity) <= ss2.safety_stock');
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case 'negative':
|
||||||
|
$query->whereIn(DB::raw('(inventories.warehouse_id, inventories.product_id)'), function ($sub) {
|
||||||
|
$sub->select('i2.warehouse_id', 'i2.product_id')
|
||||||
|
->from('inventories as i2')
|
||||||
|
->whereNull('i2.deleted_at')
|
||||||
|
->groupBy('i2.warehouse_id', 'i2.product_id')
|
||||||
|
->havingRaw('SUM(i2.quantity) < 0');
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case 'expiring':
|
||||||
|
$query->whereNotNull('inventories.expiry_date')
|
||||||
|
->where('inventories.expiry_date', '>', $today)
|
||||||
|
->where('inventories.expiry_date', '<=', $expiryThreshold);
|
||||||
|
break;
|
||||||
|
case 'expired':
|
||||||
|
$query->whereNotNull('inventories.expiry_date')
|
||||||
|
->where('inventories.expiry_date', '<=', $today);
|
||||||
|
break;
|
||||||
|
case 'abnormal':
|
||||||
|
// 只要該「倉庫-品項」對應的總庫存有低庫存、負庫存,或該批次已過期/即將過期
|
||||||
|
$query->where(function ($q) use ($today, $expiryThreshold) {
|
||||||
|
// 1. 低庫存或負庫存 (依聚合判斷)
|
||||||
|
$q->whereIn(DB::raw('(inventories.warehouse_id, inventories.product_id)'), function ($sub) {
|
||||||
|
$sub->select('i3.warehouse_id', 'i3.product_id')
|
||||||
|
->from('inventories as i3')
|
||||||
|
->leftJoin('warehouse_product_safety_stocks as ss3', function ($join) {
|
||||||
|
$join->on('i3.warehouse_id', '=', 'ss3.warehouse_id')
|
||||||
|
->on('i3.product_id', '=', 'ss3.product_id');
|
||||||
|
})
|
||||||
|
->whereNull('i3.deleted_at')
|
||||||
|
->groupBy('i3.warehouse_id', 'i3.product_id', 'ss3.safety_stock')
|
||||||
|
->havingRaw('SUM(i3.quantity) < 0 OR (ss3.safety_stock IS NOT NULL AND SUM(i3.quantity) <= ss3.safety_stock)');
|
||||||
|
})
|
||||||
|
// 2. 或該批次效期異常
|
||||||
|
->orWhere(function ($q_batch) use ($expiryThreshold) {
|
||||||
|
$q_batch->whereNotNull('inventories.expiry_date')
|
||||||
|
->where('inventories.expiry_date', '<=', $expiryThreshold);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 排序
|
||||||
|
$sortBy = $filters['sort_by'] ?? 'products.code';
|
||||||
|
$sortOrder = $filters['sort_order'] ?? 'asc';
|
||||||
|
$allowedSorts = ['products.code', 'products.name', 'warehouses.name', 'inventories.quantity', 'inventories.expiry_date'];
|
||||||
|
if (in_array($sortBy, $allowedSorts)) {
|
||||||
|
$query->orderBy($sortBy, $sortOrder);
|
||||||
|
} else {
|
||||||
|
$query->orderBy('products.code', 'asc');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 統計卡片(無篩選條件下的全域統計)
|
||||||
|
// 1. 庫存品項數:在庫的「倉庫-商品」對總數
|
||||||
|
$totalItems = DB::table('inventories')
|
||||||
|
->whereNull('deleted_at')
|
||||||
|
->distinct()
|
||||||
|
->count(DB::raw('CONCAT(warehouse_id, "-", product_id)'));
|
||||||
|
|
||||||
|
// 2. 低庫存:以「倉庫-商品」聚合後的總量與安全庫存比較 (品項計數)
|
||||||
$lowStockCount = DB::table('warehouse_product_safety_stocks as ss')
|
$lowStockCount = DB::table('warehouse_product_safety_stocks as ss')
|
||||||
->join(DB::raw('(SELECT warehouse_id, product_id, SUM(quantity) as total_qty FROM inventories WHERE deleted_at IS NULL GROUP BY warehouse_id, product_id) as inv'),
|
->join(DB::raw('(SELECT warehouse_id, product_id, SUM(quantity) as total_qty FROM inventories WHERE deleted_at IS NULL GROUP BY warehouse_id, product_id) as inv'),
|
||||||
function ($join) {
|
function ($join) {
|
||||||
@@ -241,11 +369,200 @@ class InventoryService implements InventoryServiceInterface
|
|||||||
->whereRaw('inv.total_qty <= ss.safety_stock')
|
->whereRaw('inv.total_qty <= ss.safety_stock')
|
||||||
->count();
|
->count();
|
||||||
|
|
||||||
|
// 3. 負庫存:只要該「倉庫-商品」的總庫存為負數 (品項計數)
|
||||||
|
$negativeCount = DB::table(DB::raw('(SELECT warehouse_id, product_id, SUM(quantity) as total_qty FROM inventories WHERE deleted_at IS NULL GROUP BY warehouse_id, product_id) as inv'))
|
||||||
|
->where('total_qty', '<', 0)
|
||||||
|
->count();
|
||||||
|
|
||||||
|
// 4. 即將過期:有任一批次效期符合的「品項」總數
|
||||||
|
$expiringCount = DB::table('inventories')
|
||||||
|
->whereNull('deleted_at')
|
||||||
|
->whereNotNull('expiry_date')
|
||||||
|
->where('expiry_date', '<=', $expiryThreshold)
|
||||||
|
->distinct()
|
||||||
|
->count(DB::raw('CONCAT(warehouse_id, "-", product_id)'));
|
||||||
|
|
||||||
|
// 分頁
|
||||||
|
$paginated = $query->paginate($perPage)->withQueryString();
|
||||||
|
|
||||||
|
// 為每筆紀錄附加最後入庫/出庫時間 + 狀態
|
||||||
|
$items = collect($paginated->items())->map(function ($item) use ($today, $expiryThreshold) {
|
||||||
|
$lastIn = \App\Modules\Inventory\Models\InventoryTransaction::where('inventory_id', $item->id)
|
||||||
|
->where('type', '入庫')
|
||||||
|
->orderByDesc('actual_time')
|
||||||
|
->value('actual_time');
|
||||||
|
|
||||||
|
$lastOut = \App\Modules\Inventory\Models\InventoryTransaction::where('inventory_id', $item->id)
|
||||||
|
->where('type', '出庫')
|
||||||
|
->orderByDesc('actual_time')
|
||||||
|
->value('actual_time');
|
||||||
|
|
||||||
|
// 計算狀態 (明細表格依然呈現該批次的狀態)
|
||||||
|
$statuses = [];
|
||||||
|
if ($item->quantity < 0) {
|
||||||
|
$statuses[] = 'negative';
|
||||||
|
}
|
||||||
|
if ($item->safety_stock !== null && $item->quantity <= $item->safety_stock && $item->quantity >= 0) {
|
||||||
|
$statuses[] = 'low_stock';
|
||||||
|
}
|
||||||
|
if ($item->expiry_date) {
|
||||||
|
if ($item->expiry_date <= $today) {
|
||||||
|
$statuses[] = 'expired';
|
||||||
|
} elseif ($item->expiry_date <= $expiryThreshold) {
|
||||||
|
$statuses[] = 'expiring';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (empty($statuses)) {
|
||||||
|
$statuses[] = 'normal';
|
||||||
|
}
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'productsCount' => Product::count(),
|
'id' => $item->id,
|
||||||
|
'product_code' => $item->product_code,
|
||||||
|
'product_name' => $item->product_name,
|
||||||
|
'category_name' => $item->category_name,
|
||||||
|
'warehouse_name' => $item->warehouse_name,
|
||||||
|
'batch_number' => $item->batch_number,
|
||||||
|
'quantity' => $item->quantity,
|
||||||
|
'safety_stock' => $item->safety_stock,
|
||||||
|
'expiry_date' => $item->expiry_date ? \Carbon\Carbon::parse($item->expiry_date)->toDateString() : null,
|
||||||
|
'location' => $item->location,
|
||||||
|
'quality_status' => $item->quality_status,
|
||||||
|
'last_inbound' => $lastIn ? \Carbon\Carbon::parse($lastIn)->toDateString() : null,
|
||||||
|
'last_outbound' => $lastOut ? \Carbon\Carbon::parse($lastOut)->toDateString() : null,
|
||||||
|
'statuses' => $statuses,
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
return [
|
||||||
|
'summary' => [
|
||||||
|
'totalItems' => $totalItems,
|
||||||
|
'lowStockCount' => $lowStockCount,
|
||||||
|
'negativeCount' => $negativeCount,
|
||||||
|
'expiringCount' => $expiringCount,
|
||||||
|
],
|
||||||
|
'data' => $items->toArray(),
|
||||||
|
'pagination' => [
|
||||||
|
'total' => $paginated->total(),
|
||||||
|
'per_page' => $paginated->perPage(),
|
||||||
|
'current_page' => $paginated->currentPage(),
|
||||||
|
'last_page' => $paginated->lastPage(),
|
||||||
|
'links' => $paginated->linkCollection()->toArray(),
|
||||||
|
],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getDashboardStats(): array
|
||||||
|
{
|
||||||
|
$today = now()->toDateString();
|
||||||
|
$expiryThreshold = now()->addDays(30)->toDateString();
|
||||||
|
|
||||||
|
// 1. 庫存品項數 (Unique Product-Warehouse)
|
||||||
|
$totalItems = DB::table('inventories')
|
||||||
|
->whereNull('deleted_at')
|
||||||
|
->distinct()
|
||||||
|
->count(DB::raw('CONCAT(warehouse_id, "-", product_id)'));
|
||||||
|
|
||||||
|
// 2. 低庫存 (品項計數)
|
||||||
|
$lowStockCount = DB::table('warehouse_product_safety_stocks as ss')
|
||||||
|
->join(DB::raw('(SELECT warehouse_id, product_id, SUM(quantity) as total_qty FROM inventories WHERE deleted_at IS NULL GROUP BY warehouse_id, product_id) as inv'),
|
||||||
|
function ($join) {
|
||||||
|
$join->on('ss.warehouse_id', '=', 'inv.warehouse_id')
|
||||||
|
->on('ss.product_id', '=', 'inv.product_id');
|
||||||
|
})
|
||||||
|
->whereRaw('inv.total_qty <= ss.safety_stock')
|
||||||
|
->count();
|
||||||
|
|
||||||
|
// 3. 負庫存 (品項計數)
|
||||||
|
$negativeCount = DB::table(DB::raw('(SELECT warehouse_id, product_id, SUM(quantity) as total_qty FROM inventories WHERE deleted_at IS NULL GROUP BY warehouse_id, product_id) as inv'))
|
||||||
|
->where('total_qty', '<', 0)
|
||||||
|
->count();
|
||||||
|
|
||||||
|
// 4. 即將過期 (品項計數)
|
||||||
|
$expiringCount = DB::table('inventories')
|
||||||
|
->whereNull('deleted_at')
|
||||||
|
->whereNotNull('expiry_date')
|
||||||
|
->where('expiry_date', '<=', $expiryThreshold)
|
||||||
|
->distinct()
|
||||||
|
->count(DB::raw('CONCAT(warehouse_id, "-", product_id)'));
|
||||||
|
|
||||||
|
// 異常庫存前 10 筆 (明細面依然以個別批次為主,供快速跳轉)
|
||||||
|
$abnormalItems = Inventory::query()
|
||||||
|
->join('products', 'inventories.product_id', '=', 'products.id')
|
||||||
|
->join('warehouses', 'inventories.warehouse_id', '=', 'warehouses.id')
|
||||||
|
->leftJoin('warehouse_product_safety_stocks as ss', function ($join) {
|
||||||
|
$join->on('inventories.warehouse_id', '=', 'ss.warehouse_id')
|
||||||
|
->on('inventories.product_id', '=', 'ss.product_id');
|
||||||
|
})
|
||||||
|
->whereNull('inventories.deleted_at')
|
||||||
|
->where(function ($q) use ($today, $expiryThreshold) {
|
||||||
|
// 1. 屬於低庫存或負庫存品項的批次
|
||||||
|
$q->whereIn(DB::raw('(inventories.warehouse_id, inventories.product_id)'), function ($sub) {
|
||||||
|
$sub->select('i3.warehouse_id', 'i3.product_id')
|
||||||
|
->from('inventories as i3')
|
||||||
|
->leftJoin('warehouse_product_safety_stocks as ss3', function ($join) {
|
||||||
|
$join->on('i3.warehouse_id', '=', 'ss3.warehouse_id')
|
||||||
|
->on('i3.product_id', '=', 'ss3.product_id');
|
||||||
|
})
|
||||||
|
->whereNull('i3.deleted_at')
|
||||||
|
->groupBy('i3.warehouse_id', 'i3.product_id', 'ss3.safety_stock')
|
||||||
|
->havingRaw('SUM(i3.quantity) < 0 OR (ss3.safety_stock IS NOT NULL AND SUM(i3.quantity) <= ss3.safety_stock)');
|
||||||
|
})
|
||||||
|
// 2. 或單一批次效期異常
|
||||||
|
->orWhere(function ($q2) use ($expiryThreshold) {
|
||||||
|
$q2->whereNotNull('inventories.expiry_date')
|
||||||
|
->where('inventories.expiry_date', '<=', $expiryThreshold);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
->select([
|
||||||
|
'inventories.id',
|
||||||
|
'inventories.quantity',
|
||||||
|
'inventories.expiry_date',
|
||||||
|
'products.code as product_code',
|
||||||
|
'products.name as product_name',
|
||||||
|
'warehouses.name as warehouse_name',
|
||||||
|
'ss.safety_stock',
|
||||||
|
])
|
||||||
|
->orderBy('inventories.id', 'desc')
|
||||||
|
->limit(10)
|
||||||
|
->get()
|
||||||
|
->map(function ($item) use ($today, $expiryThreshold) {
|
||||||
|
$statuses = [];
|
||||||
|
if ($item->quantity < 0) {
|
||||||
|
$statuses[] = 'negative';
|
||||||
|
}
|
||||||
|
if ($item->safety_stock !== null && $item->quantity <= $item->safety_stock && $item->quantity >= 0) {
|
||||||
|
$statuses[] = 'low_stock';
|
||||||
|
}
|
||||||
|
if ($item->expiry_date) {
|
||||||
|
if ($item->expiry_date <= $today) {
|
||||||
|
$statuses[] = 'expired';
|
||||||
|
} elseif ($item->expiry_date <= $expiryThreshold) {
|
||||||
|
$statuses[] = 'expiring';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [
|
||||||
|
'id' => $item->id,
|
||||||
|
'product_code' => $item->product_code,
|
||||||
|
'product_name' => $item->product_name,
|
||||||
|
'warehouse_name' => $item->warehouse_name,
|
||||||
|
'quantity' => $item->quantity,
|
||||||
|
'safety_stock' => $item->safety_stock,
|
||||||
|
'expiry_date' => $item->expiry_date,
|
||||||
|
'statuses' => $statuses,
|
||||||
|
];
|
||||||
|
})
|
||||||
|
->toArray();
|
||||||
|
|
||||||
|
return [
|
||||||
|
'productsCount' => $totalItems,
|
||||||
'warehousesCount' => Warehouse::count(),
|
'warehousesCount' => Warehouse::count(),
|
||||||
'lowStockCount' => $lowStockCount,
|
'lowStockCount' => $lowStockCount,
|
||||||
|
'negativeCount' => $negativeCount,
|
||||||
|
'expiringCount' => $expiringCount,
|
||||||
'totalInventoryQuantity' => Inventory::sum('quantity'),
|
'totalInventoryQuantity' => Inventory::sum('quantity'),
|
||||||
|
'abnormalItems' => $abnormalItems,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -104,7 +104,7 @@ export function SearchableSelect({
|
|||||||
{options.map((option) => (
|
{options.map((option) => (
|
||||||
<CommandItem
|
<CommandItem
|
||||||
key={option.value}
|
key={option.value}
|
||||||
value={option.label}
|
value={`${option.label} ${option.value}`}
|
||||||
onSelect={() => {
|
onSelect={() => {
|
||||||
onValueChange(option.value);
|
onValueChange(option.value);
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
|
|||||||
@@ -88,6 +88,13 @@ export default function AuthenticatedLayout({
|
|||||||
icon: <Boxes className="h-5 w-5" />,
|
icon: <Boxes className="h-5 w-5" />,
|
||||||
permission: ["products.view", "warehouses.view", "inventory.view"], // 滿足任一即可看到此群組
|
permission: ["products.view", "warehouses.view", "inventory.view"], // 滿足任一即可看到此群組
|
||||||
children: [
|
children: [
|
||||||
|
{
|
||||||
|
id: "stock-query",
|
||||||
|
label: "即時庫存查詢",
|
||||||
|
icon: <BarChart3 className="h-4 w-4" />,
|
||||||
|
route: "/inventory/stock-query",
|
||||||
|
permission: "inventory.view",
|
||||||
|
},
|
||||||
{
|
{
|
||||||
id: "product-management",
|
id: "product-management",
|
||||||
label: "商品資料管理",
|
label: "商品資料管理",
|
||||||
|
|||||||
@@ -1,211 +1,259 @@
|
|||||||
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
|
import { Head, Link } from "@inertiajs/react";
|
||||||
import { Link, Head, usePage } from '@inertiajs/react';
|
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
|
||||||
import { PageProps } from '@/types/global';
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
import {
|
import {
|
||||||
Package,
|
Package,
|
||||||
Users,
|
|
||||||
ShoppingCart,
|
|
||||||
Warehouse as WarehouseIcon,
|
|
||||||
AlertTriangle,
|
AlertTriangle,
|
||||||
|
MinusCircle,
|
||||||
Clock,
|
Clock,
|
||||||
TrendingUp,
|
ArrowRight,
|
||||||
ChevronRight
|
LayoutDashboard,
|
||||||
} from 'lucide-react';
|
} from "lucide-react";
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from "@/Components/ui/table";
|
||||||
|
import { Badge } from "@/Components/ui/badge";
|
||||||
|
import { Button } from "@/Components/ui/button";
|
||||||
|
|
||||||
interface Stats {
|
interface AbnormalItem {
|
||||||
productsCount: number;
|
id: number;
|
||||||
vendorsCount: number;
|
product_code: string;
|
||||||
purchaseOrdersCount: number;
|
product_name: string;
|
||||||
warehousesCount: number;
|
warehouse_name: string;
|
||||||
totalInventoryValue: number;
|
quantity: number;
|
||||||
pendingOrdersCount: number;
|
safety_stock: number | null;
|
||||||
lowStockCount: number;
|
expiry_date: string | null;
|
||||||
|
statuses: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
stats: Stats;
|
stats: {
|
||||||
|
totalItems: number;
|
||||||
|
lowStockCount: number;
|
||||||
|
negativeCount: number;
|
||||||
|
expiringCount: number;
|
||||||
|
};
|
||||||
|
abnormalItems: AbnormalItem[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Dashboard({ stats }: Props) {
|
// 狀態 Badge 映射
|
||||||
const { branding } = usePage<PageProps>().props;
|
const statusConfig: Record<string, { label: string; className: string }> = {
|
||||||
const cardData = [
|
negative: {
|
||||||
{
|
label: "負庫存",
|
||||||
label: '商品總數',
|
className: "bg-red-100 text-red-800 border-red-200",
|
||||||
value: stats.productsCount,
|
|
||||||
icon: <Package className="h-6 w-6 text-primary-main" />,
|
|
||||||
description: '目前系統中的商品種類',
|
|
||||||
color: 'bg-primary-main/10',
|
|
||||||
},
|
},
|
||||||
{
|
low_stock: {
|
||||||
label: '合作廠商',
|
label: "低庫存",
|
||||||
value: stats.vendorsCount,
|
className: "bg-amber-100 text-amber-800 border-amber-200",
|
||||||
icon: <Users className="h-6 w-6 text-blue-600" />,
|
|
||||||
description: '已建立資料的供應商',
|
|
||||||
color: 'bg-blue-50',
|
|
||||||
},
|
},
|
||||||
{
|
expiring: {
|
||||||
label: '採購單據',
|
label: "即將過期",
|
||||||
value: stats.purchaseOrdersCount,
|
className: "bg-yellow-100 text-yellow-800 border-yellow-200",
|
||||||
icon: <ShoppingCart className="h-6 w-6 text-purple-600" />,
|
|
||||||
description: '歷年累計採購單數量',
|
|
||||||
color: 'bg-purple-50',
|
|
||||||
},
|
},
|
||||||
{
|
expired: {
|
||||||
label: '倉庫站點',
|
label: "已過期",
|
||||||
value: stats.warehousesCount,
|
className: "bg-red-100 text-red-800 border-red-200",
|
||||||
icon: <WarehouseIcon className="h-6 w-6 text-orange-600" />,
|
|
||||||
description: '目前營運中的倉庫環境',
|
|
||||||
color: 'bg-orange-50',
|
|
||||||
},
|
},
|
||||||
];
|
};
|
||||||
|
|
||||||
const alertData = [
|
export default function Dashboard({ stats, abnormalItems }: Props) {
|
||||||
|
const cards = [
|
||||||
{
|
{
|
||||||
label: '待處理採購單',
|
label: "庫存品項數",
|
||||||
value: stats.pendingOrdersCount,
|
value: stats.totalItems,
|
||||||
icon: <Clock className="h-5 w-5" />,
|
icon: <Package className="h-6 w-6" />,
|
||||||
status: stats.pendingOrdersCount > 0 ? 'warning' : 'normal',
|
color: "text-primary-main",
|
||||||
|
bgColor: "bg-primary-lightest",
|
||||||
|
borderColor: "border-primary-light",
|
||||||
|
href: "/inventory/stock-query",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: '低庫存警示',
|
label: "低庫存",
|
||||||
value: stats.lowStockCount,
|
value: stats.lowStockCount,
|
||||||
icon: <AlertTriangle className="h-5 w-5" />,
|
icon: <AlertTriangle className="h-6 w-6" />,
|
||||||
status: stats.lowStockCount > 0 ? 'error' : 'normal',
|
color: "text-amber-600",
|
||||||
|
bgColor: "bg-amber-50",
|
||||||
|
borderColor: "border-amber-200",
|
||||||
|
href: "/inventory/stock-query?status=low_stock",
|
||||||
|
alert: stats.lowStockCount > 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "負庫存",
|
||||||
|
value: stats.negativeCount,
|
||||||
|
icon: <MinusCircle className="h-6 w-6" />,
|
||||||
|
color: "text-red-600",
|
||||||
|
bgColor: "bg-red-50",
|
||||||
|
borderColor: "border-red-200",
|
||||||
|
href: "/inventory/stock-query?status=negative",
|
||||||
|
alert: stats.negativeCount > 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "即將過期",
|
||||||
|
value: stats.expiringCount,
|
||||||
|
icon: <Clock className="h-6 w-6" />,
|
||||||
|
color: "text-yellow-600",
|
||||||
|
bgColor: "bg-yellow-50",
|
||||||
|
borderColor: "border-yellow-200",
|
||||||
|
href: "/inventory/stock-query?status=expiring",
|
||||||
|
alert: stats.expiringCount > 0,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthenticatedLayout>
|
<AuthenticatedLayout
|
||||||
<Head title={`控制台 - ${branding?.short_name || 'Star'} ERP`} />
|
breadcrumbs={[
|
||||||
|
{
|
||||||
|
label: "儀表板",
|
||||||
|
href: "/",
|
||||||
|
isPage: true,
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Head title="儀表板" />
|
||||||
|
|
||||||
<div className="p-8 max-w-7xl mx-auto">
|
<div className="container mx-auto p-6 max-w-7xl">
|
||||||
<div className="mb-8">
|
{/* 頁面標題 */}
|
||||||
|
<div className="mb-6">
|
||||||
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
|
<h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
|
||||||
<TrendingUp className="h-6 w-6 text-primary-main" />
|
<LayoutDashboard className="h-6 w-6 text-primary-main" />
|
||||||
系統總覽
|
庫存總覽
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-gray-500 mt-1">歡迎回來,這是您的 {branding?.short_name || 'Star'} ERP 營運數據概況。</p>
|
<p className="text-gray-500 mt-1">
|
||||||
</div>
|
即時掌握庫存狀態,異常情況一目了然
|
||||||
|
|
||||||
{/* 主要數據卡片 */}
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-10">
|
|
||||||
{cardData.map((card, index) => (
|
|
||||||
<div key={index} className="bg-white p-6 rounded-2xl border border-grey-4 shadow-sm hover:shadow-md transition-shadow">
|
|
||||||
<div className="flex items-start justify-between mb-4">
|
|
||||||
<div className={`p-3 rounded-xl ${card.color}`}>
|
|
||||||
{card.icon}
|
|
||||||
</div>
|
|
||||||
<span className="text-xs font-medium text-grey-3 bg-grey-5 px-2 py-1 rounded-full border border-grey-4">
|
|
||||||
統計中
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<h3 className="text-grey-2 text-sm font-medium mb-1">{card.label}</h3>
|
|
||||||
<div className="flex items-baseline gap-2">
|
|
||||||
<span className="text-2xl font-bold text-grey-0">{card.value}</span>
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-grey-3 mt-2">{card.description}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
|
|
||||||
{/* 警示與通知 */}
|
|
||||||
<div className="lg:col-span-1 space-y-6">
|
|
||||||
<h2 className="text-xl font-bold text-grey-0 flex items-center gap-2">
|
|
||||||
<TrendingUp className="h-5 w-5 text-primary-main" />
|
|
||||||
即時動態
|
|
||||||
</h2>
|
|
||||||
<div className="bg-white rounded-2xl border border-grey-4 shadow-sm divide-y divide-grey-4">
|
|
||||||
{alertData.map((alert, index) => (
|
|
||||||
<div key={index} className="p-6 flex items-center justify-between group cursor-pointer hover:bg-background-light transition-colors">
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<div className={cn(
|
|
||||||
"p-2 rounded-lg",
|
|
||||||
alert.status === 'error' ? "bg-red-50 text-red-600" :
|
|
||||||
alert.status === 'warning' ? "bg-amber-50 text-amber-600" : "bg-grey-5 text-grey-2"
|
|
||||||
)}>
|
|
||||||
{alert.icon}
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="text-sm font-medium text-grey-1">{alert.label}</p>
|
|
||||||
<p className="text-xs text-grey-3">需立即查看</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className={cn(
|
|
||||||
"text-lg font-bold",
|
|
||||||
alert.status === 'error' ? "text-red-600" :
|
|
||||||
alert.status === 'warning' ? "text-amber-600" : "text-grey-1"
|
|
||||||
)}>
|
|
||||||
{alert.value}
|
|
||||||
</span>
|
|
||||||
<ChevronRight className="h-4 w-4 text-grey-4 group-hover:translate-x-1 transition-transform" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="bg-primary/5 rounded-2xl p-6 border border-primary/10">
|
|
||||||
<h4 className="text-sm font-bold text-primary mb-2">系統提示</h4>
|
|
||||||
<p className="text-xs text-grey-1 leading-relaxed">
|
|
||||||
目前系統運行正常。如有任何問題,請聯絡開發團隊獲取支援。
|
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* 統計卡片 */}
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
|
||||||
|
{cards.map((card) => (
|
||||||
|
<Link key={card.label} href={card.href}>
|
||||||
|
<div
|
||||||
|
className={`relative rounded-xl border ${card.borderColor} ${card.bgColor} p-5 transition-all hover:shadow-md hover:-translate-y-0.5 cursor-pointer`}
|
||||||
|
>
|
||||||
|
{card.alert && (
|
||||||
|
<span className="absolute top-3 right-3 h-2.5 w-2.5 rounded-full bg-red-500 animate-pulse" />
|
||||||
|
)}
|
||||||
|
<div className="flex items-center gap-3 mb-3">
|
||||||
|
<div className={card.color}>
|
||||||
|
{card.icon}
|
||||||
|
</div>
|
||||||
|
<span className="text-sm font-medium text-grey-1">
|
||||||
|
{card.label}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className={`text-3xl font-bold ${card.color}`}
|
||||||
|
>
|
||||||
|
{card.value.toLocaleString()}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 快速捷徑 */}
|
{/* 異常庫存清單 */}
|
||||||
<div className="lg:col-span-2 space-y-6">
|
<div className="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">
|
||||||
<h2 className="text-xl font-bold text-grey-0">快速操作</h2>
|
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
<h2 className="text-lg font-semibold text-grey-0 flex items-center gap-2">
|
||||||
<Link href="/products" className="group h-full">
|
<AlertTriangle className="h-5 w-5 text-amber-500" />
|
||||||
<div className="bg-white p-6 rounded-2xl border border-grey-4 shadow-sm hover:border-primary-main transition-all h-full flex flex-col justify-between">
|
異常庫存清單
|
||||||
<div>
|
</h2>
|
||||||
<h3 className="font-bold text-grey-0 mb-1 group-hover:text-primary-main">商品管理</h3>
|
<Link href="/inventory/stock-query?status=abnormal">
|
||||||
<p className="text-sm text-grey-2">查看並編輯所有商品資料與單位換算。</p>
|
<Button
|
||||||
</div>
|
variant="outline"
|
||||||
<div className="mt-4 flex items-center text-xs font-bold text-primary-main group-hover:gap-2 transition-all">
|
size="sm"
|
||||||
即刻前往 <ChevronRight className="h-3 w-3" />
|
className="button-outlined-primary gap-1"
|
||||||
</div>
|
>
|
||||||
</div>
|
查看完整庫存
|
||||||
</Link>
|
<ArrowRight className="h-4 w-4" />
|
||||||
<Link href="/purchase-orders" className="group h-full">
|
</Button>
|
||||||
<div className="bg-white p-6 rounded-2xl border border-grey-4 shadow-sm hover:border-purple-500 transition-all h-full flex flex-col justify-between">
|
|
||||||
<div>
|
|
||||||
<h3 className="font-bold text-grey-0 mb-1 group-hover:text-purple-600">採購單管理</h3>
|
|
||||||
<p className="text-sm text-grey-2">處理進貨、追蹤採購進度與管理單據。</p>
|
|
||||||
</div>
|
|
||||||
<div className="mt-4 flex items-center text-xs font-bold text-purple-600 group-hover:gap-2 transition-all">
|
|
||||||
即刻前往 <ChevronRight className="h-3 w-3" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Link>
|
|
||||||
<Link href="/vendors" className="group h-full">
|
|
||||||
<div className="bg-white p-6 rounded-2xl border border-grey-4 shadow-sm hover:border-blue-500 transition-all h-full flex flex-col justify-between">
|
|
||||||
<div>
|
|
||||||
<h3 className="font-bold text-grey-0 mb-1 group-hover:text-blue-600">廠商管理</h3>
|
|
||||||
<p className="text-sm text-grey-2">管理供應商聯絡資訊與供貨清單。</p>
|
|
||||||
</div>
|
|
||||||
<div className="mt-4 flex items-center text-xs font-bold text-blue-600 group-hover:gap-2 transition-all">
|
|
||||||
即刻前往 <ChevronRight className="h-3 w-3" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Link>
|
|
||||||
<Link href="/warehouses" className="group h-full">
|
|
||||||
<div className="bg-white p-6 rounded-2xl border border-grey-4 shadow-sm hover:border-orange-500 transition-all h-full flex flex-col justify-between">
|
|
||||||
<div>
|
|
||||||
<h3 className="font-bold text-grey-0 mb-1 group-hover:text-orange-600">倉庫與庫存</h3>
|
|
||||||
<p className="text-sm text-grey-2">管理入庫、庫存水位與基礎設施。</p>
|
|
||||||
</div>
|
|
||||||
<div className="mt-4 flex items-center text-xs font-bold text-orange-600 group-hover:gap-2 transition-all">
|
|
||||||
即刻前往 <ChevronRight className="h-3 w-3" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<Table>
|
||||||
|
<TableHeader className="bg-gray-50">
|
||||||
|
<TableRow>
|
||||||
|
<TableHead className="w-[50px] text-center">
|
||||||
|
#
|
||||||
|
</TableHead>
|
||||||
|
<TableHead>商品代碼</TableHead>
|
||||||
|
<TableHead>商品名稱</TableHead>
|
||||||
|
<TableHead>倉庫</TableHead>
|
||||||
|
<TableHead className="text-right">
|
||||||
|
數量
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="text-center">
|
||||||
|
狀態
|
||||||
|
</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{abnormalItems.length === 0 ? (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell
|
||||||
|
colSpan={6}
|
||||||
|
className="text-center py-8 text-gray-500"
|
||||||
|
>
|
||||||
|
🎉 目前沒有異常庫存,一切正常!
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
) : (
|
||||||
|
abnormalItems.map((item, index) => (
|
||||||
|
<TableRow key={item.id}>
|
||||||
|
<TableCell className="text-gray-500 font-medium text-center">
|
||||||
|
{index + 1}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-sm">
|
||||||
|
{item.product_code}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-medium">
|
||||||
|
{item.product_name}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{item.warehouse_name}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell
|
||||||
|
className={`text-right font-medium ${item.quantity < 0
|
||||||
|
? "text-red-600"
|
||||||
|
: ""
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{item.quantity}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-center">
|
||||||
|
<div className="flex flex-wrap items-center justify-center gap-1">
|
||||||
|
{item.statuses.map(
|
||||||
|
(status) => {
|
||||||
|
const config =
|
||||||
|
statusConfig[
|
||||||
|
status
|
||||||
|
];
|
||||||
|
if (!config)
|
||||||
|
return null;
|
||||||
|
return (
|
||||||
|
<Badge
|
||||||
|
key={status}
|
||||||
|
variant="outline"
|
||||||
|
className={
|
||||||
|
config.className
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{config.label}
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</AuthenticatedLayout>
|
</AuthenticatedLayout>
|
||||||
|
|||||||
582
resources/js/Pages/Inventory/StockQuery/Index.tsx
Normal file
582
resources/js/Pages/Inventory/StockQuery/Index.tsx
Normal file
@@ -0,0 +1,582 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { Head, router } from "@inertiajs/react";
|
||||||
|
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
|
||||||
|
import {
|
||||||
|
Search,
|
||||||
|
Package,
|
||||||
|
AlertTriangle,
|
||||||
|
MinusCircle,
|
||||||
|
Clock,
|
||||||
|
Download,
|
||||||
|
ArrowUpDown,
|
||||||
|
ArrowUp,
|
||||||
|
ArrowDown,
|
||||||
|
} from "lucide-react";
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from "@/Components/ui/table";
|
||||||
|
import { Badge } from "@/Components/ui/badge";
|
||||||
|
import { Button } from "@/Components/ui/button";
|
||||||
|
import { Input } from "@/Components/ui/input";
|
||||||
|
import { SearchableSelect } from "@/Components/ui/searchable-select";
|
||||||
|
import Pagination from "@/Components/shared/Pagination";
|
||||||
|
|
||||||
|
interface InventoryItem {
|
||||||
|
id: number;
|
||||||
|
product_code: string;
|
||||||
|
product_name: string;
|
||||||
|
category_name: string | null;
|
||||||
|
warehouse_name: string;
|
||||||
|
batch_number: string | null;
|
||||||
|
quantity: number;
|
||||||
|
safety_stock: number | null;
|
||||||
|
expiry_date: string | null;
|
||||||
|
quality_status: string | null;
|
||||||
|
last_inbound: string | null;
|
||||||
|
last_outbound: string | null;
|
||||||
|
statuses: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PaginationLink {
|
||||||
|
url: string | null;
|
||||||
|
label: string;
|
||||||
|
active: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
filters: {
|
||||||
|
warehouse_id?: string;
|
||||||
|
category_id?: string;
|
||||||
|
search?: string;
|
||||||
|
status?: string;
|
||||||
|
sort_by?: string;
|
||||||
|
sort_order?: string;
|
||||||
|
per_page?: string;
|
||||||
|
};
|
||||||
|
summary: {
|
||||||
|
totalItems: number;
|
||||||
|
lowStockCount: number;
|
||||||
|
negativeCount: number;
|
||||||
|
expiringCount: number;
|
||||||
|
};
|
||||||
|
inventories: {
|
||||||
|
data: InventoryItem[];
|
||||||
|
total: number;
|
||||||
|
per_page: number;
|
||||||
|
current_page: number;
|
||||||
|
last_page: number;
|
||||||
|
links: PaginationLink[];
|
||||||
|
};
|
||||||
|
warehouses: { id: number; name: string }[];
|
||||||
|
categories: { id: number; name: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 狀態 Badge
|
||||||
|
const statusConfig: Record<
|
||||||
|
string,
|
||||||
|
{ label: string; className: string }
|
||||||
|
> = {
|
||||||
|
normal: {
|
||||||
|
label: "正常",
|
||||||
|
className: "bg-green-100 text-green-800 border-green-200",
|
||||||
|
},
|
||||||
|
negative: {
|
||||||
|
label: "負庫存",
|
||||||
|
className: "bg-red-100 text-red-800 border-red-200",
|
||||||
|
},
|
||||||
|
low_stock: {
|
||||||
|
label: "低庫存",
|
||||||
|
className: "bg-amber-100 text-amber-800 border-amber-200",
|
||||||
|
},
|
||||||
|
expiring: {
|
||||||
|
label: "即將過期",
|
||||||
|
className: "bg-yellow-100 text-yellow-800 border-yellow-200",
|
||||||
|
},
|
||||||
|
expired: {
|
||||||
|
label: "已過期",
|
||||||
|
className: "bg-red-100 text-red-800 border-red-200",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// 狀態篩選選項
|
||||||
|
const statusOptions = [
|
||||||
|
{ label: "全部狀態", value: "" },
|
||||||
|
{ label: "低庫存", value: "low_stock" },
|
||||||
|
{ label: "負庫存", value: "negative" },
|
||||||
|
{ label: "即將過期", value: "expiring" },
|
||||||
|
{ label: "已過期", value: "expired" },
|
||||||
|
{ label: "所有異常", value: "abnormal" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function StockQueryIndex({
|
||||||
|
filters,
|
||||||
|
summary,
|
||||||
|
inventories,
|
||||||
|
warehouses,
|
||||||
|
categories,
|
||||||
|
}: Props) {
|
||||||
|
const [search, setSearch] = useState(filters.search || "");
|
||||||
|
const [perPage, setPerPage] = useState<string>(
|
||||||
|
filters.per_page || "10"
|
||||||
|
);
|
||||||
|
|
||||||
|
// 執行篩選
|
||||||
|
const applyFilters = (newFilters: Record<string, string | undefined>) => {
|
||||||
|
const merged = { ...filters, ...newFilters, page: undefined };
|
||||||
|
// 移除空值
|
||||||
|
const cleaned: Record<string, string> = {};
|
||||||
|
Object.entries(merged).forEach(([key, value]) => {
|
||||||
|
if (value !== undefined && value !== "" && value !== null) {
|
||||||
|
cleaned[key] = String(value);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
router.get(route("inventory.stock-query.index"), cleaned, {
|
||||||
|
preserveState: true,
|
||||||
|
replace: true,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 搜尋
|
||||||
|
const handleSearch = () => {
|
||||||
|
applyFilters({ search: search || undefined });
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSearchKeyDown = (e: React.KeyboardEvent) => {
|
||||||
|
if (e.key === "Enter") {
|
||||||
|
handleSearch();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 排序
|
||||||
|
const handleSort = (field: string) => {
|
||||||
|
let newSortBy: string | undefined = field;
|
||||||
|
let newSortOrder: string | undefined = "asc";
|
||||||
|
|
||||||
|
if (filters.sort_by === field) {
|
||||||
|
if (filters.sort_order === "asc") {
|
||||||
|
newSortOrder = "desc";
|
||||||
|
} else {
|
||||||
|
newSortBy = undefined;
|
||||||
|
newSortOrder = undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
applyFilters({ sort_by: newSortBy, sort_order: newSortOrder });
|
||||||
|
};
|
||||||
|
|
||||||
|
// 排序圖標
|
||||||
|
const SortIcon = ({ field }: { field: string }) => {
|
||||||
|
if (filters.sort_by !== field) {
|
||||||
|
return (
|
||||||
|
<ArrowUpDown className="h-4 w-4 text-muted-foreground ml-1" />
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (filters.sort_order === "asc") {
|
||||||
|
return <ArrowUp className="h-4 w-4 text-primary ml-1" />;
|
||||||
|
}
|
||||||
|
return <ArrowDown className="h-4 w-4 text-primary ml-1" />;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 每頁筆數變更
|
||||||
|
const handlePerPageChange = (value: string) => {
|
||||||
|
setPerPage(value);
|
||||||
|
router.get(
|
||||||
|
route("inventory.stock-query.index"),
|
||||||
|
{ ...filters, per_page: value, page: undefined },
|
||||||
|
{ preserveState: false, replace: true, preserveScroll: true }
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 匯出
|
||||||
|
const handleExport = () => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (filters.warehouse_id)
|
||||||
|
params.append("warehouse_id", filters.warehouse_id);
|
||||||
|
if (filters.category_id)
|
||||||
|
params.append("category_id", filters.category_id);
|
||||||
|
if (filters.search) params.append("search", filters.search);
|
||||||
|
if (filters.status) params.append("status", filters.status);
|
||||||
|
window.location.href =
|
||||||
|
route("inventory.stock-query.export") + "?" + params.toString();
|
||||||
|
};
|
||||||
|
|
||||||
|
// 計算序號起始值
|
||||||
|
const startIndex =
|
||||||
|
(inventories.current_page - 1) * inventories.per_page + 1;
|
||||||
|
|
||||||
|
// 統計卡片
|
||||||
|
const cards = [
|
||||||
|
{
|
||||||
|
label: "庫存品項",
|
||||||
|
value: summary.totalItems,
|
||||||
|
icon: <Package className="h-5 w-5" />,
|
||||||
|
color: "text-primary-main",
|
||||||
|
bgColor: "bg-primary-lightest",
|
||||||
|
borderColor: "border-primary-light",
|
||||||
|
status: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "低庫存",
|
||||||
|
value: summary.lowStockCount,
|
||||||
|
icon: <AlertTriangle className="h-5 w-5" />,
|
||||||
|
color: "text-amber-600",
|
||||||
|
bgColor: "bg-amber-50",
|
||||||
|
borderColor: "border-amber-200",
|
||||||
|
status: "low_stock",
|
||||||
|
alert: summary.lowStockCount > 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "負庫存",
|
||||||
|
value: summary.negativeCount,
|
||||||
|
icon: <MinusCircle className="h-5 w-5" />,
|
||||||
|
color: "text-red-600",
|
||||||
|
bgColor: "bg-red-50",
|
||||||
|
borderColor: "border-red-200",
|
||||||
|
status: "negative",
|
||||||
|
alert: summary.negativeCount > 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "即將過期",
|
||||||
|
value: summary.expiringCount,
|
||||||
|
icon: <Clock className="h-5 w-5" />,
|
||||||
|
color: "text-yellow-600",
|
||||||
|
bgColor: "bg-yellow-50",
|
||||||
|
borderColor: "border-yellow-200",
|
||||||
|
status: "expiring",
|
||||||
|
alert: summary.expiringCount > 0,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AuthenticatedLayout
|
||||||
|
breadcrumbs={[
|
||||||
|
{ label: "商品與庫存管理", href: "#" },
|
||||||
|
{
|
||||||
|
label: "即時庫存查詢",
|
||||||
|
href: route("inventory.stock-query.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">
|
||||||
|
<Search className="h-6 w-6 text-primary-main" />
|
||||||
|
即時庫存查詢
|
||||||
|
</h1>
|
||||||
|
<p className="text-gray-500 mt-1">
|
||||||
|
跨倉庫即時庫存查詢,含批號追蹤與到期管理
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
className="button-filled-primary gap-2"
|
||||||
|
onClick={handleExport}
|
||||||
|
>
|
||||||
|
<Download className="h-4 w-4" />
|
||||||
|
匯出 Excel
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 統計卡片 */}
|
||||||
|
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-6">
|
||||||
|
{cards.map((card) => (
|
||||||
|
<div
|
||||||
|
key={card.label}
|
||||||
|
onClick={() =>
|
||||||
|
applyFilters({
|
||||||
|
status: card.status || undefined,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className={`relative rounded-xl border ${card.borderColor} ${card.bgColor} p-4 transition-all hover:shadow-md hover:-translate-y-0.5 cursor-pointer ${filters.status === card.status
|
||||||
|
? "ring-2 ring-primary-main ring-offset-1"
|
||||||
|
: ""
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{card.alert && (
|
||||||
|
<span className="absolute top-2.5 right-2.5 h-2 w-2 rounded-full bg-red-500 animate-pulse" />
|
||||||
|
)}
|
||||||
|
<div className="flex items-center gap-2 mb-2">
|
||||||
|
<div className={card.color}>{card.icon}</div>
|
||||||
|
<span className="text-xs font-medium text-grey-2">
|
||||||
|
{card.label}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className={`text-2xl font-bold ${card.color}`}
|
||||||
|
>
|
||||||
|
{card.value.toLocaleString()}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 篩選列 */}
|
||||||
|
<div className="bg-white rounded-xl border border-gray-200 p-4 mb-4">
|
||||||
|
<div className="flex flex-wrap items-center gap-3">
|
||||||
|
<SearchableSelect
|
||||||
|
value={filters.warehouse_id || ""}
|
||||||
|
onValueChange={(v) =>
|
||||||
|
applyFilters({
|
||||||
|
warehouse_id: v || undefined,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
options={[
|
||||||
|
{ label: "全部倉庫", value: "" },
|
||||||
|
...warehouses.map((w) => ({
|
||||||
|
label: w.name,
|
||||||
|
value: String(w.id),
|
||||||
|
})),
|
||||||
|
]}
|
||||||
|
className="w-[160px] h-9"
|
||||||
|
placeholder="選擇倉庫"
|
||||||
|
/>
|
||||||
|
<SearchableSelect
|
||||||
|
value={filters.category_id || ""}
|
||||||
|
onValueChange={(v) =>
|
||||||
|
applyFilters({
|
||||||
|
category_id: v || undefined,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
options={[
|
||||||
|
{ label: "全部分類", value: "" },
|
||||||
|
...categories.map((c) => ({
|
||||||
|
label: c.name,
|
||||||
|
value: String(c.id),
|
||||||
|
})),
|
||||||
|
]}
|
||||||
|
className="w-[160px] h-9"
|
||||||
|
placeholder="選擇分類"
|
||||||
|
/>
|
||||||
|
<SearchableSelect
|
||||||
|
value={filters.status || ""}
|
||||||
|
onValueChange={(v) =>
|
||||||
|
applyFilters({ status: v || undefined })
|
||||||
|
}
|
||||||
|
options={statusOptions}
|
||||||
|
className="w-[140px] h-9"
|
||||||
|
showSearch={false}
|
||||||
|
placeholder="篩選狀態"
|
||||||
|
/>
|
||||||
|
<div className="flex items-center gap-2 flex-1 min-w-[200px]">
|
||||||
|
<Input
|
||||||
|
type="text"
|
||||||
|
value={search}
|
||||||
|
onChange={(e) => setSearch(e.target.value)}
|
||||||
|
onKeyDown={handleSearchKeyDown}
|
||||||
|
placeholder="搜尋商品代碼或名稱..."
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
className="button-outlined-primary h-9"
|
||||||
|
onClick={handleSearch}
|
||||||
|
>
|
||||||
|
<Search className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</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>
|
||||||
|
<button
|
||||||
|
onClick={() =>
|
||||||
|
handleSort("products.code")
|
||||||
|
}
|
||||||
|
className="flex items-center hover:text-gray-900"
|
||||||
|
>
|
||||||
|
商品代碼
|
||||||
|
<SortIcon field="products.code" />
|
||||||
|
</button>
|
||||||
|
</TableHead>
|
||||||
|
<TableHead>
|
||||||
|
<button
|
||||||
|
onClick={() =>
|
||||||
|
handleSort("products.name")
|
||||||
|
}
|
||||||
|
className="flex items-center hover:text-gray-900"
|
||||||
|
>
|
||||||
|
商品名稱
|
||||||
|
<SortIcon field="products.name" />
|
||||||
|
</button>
|
||||||
|
</TableHead>
|
||||||
|
<TableHead>分類</TableHead>
|
||||||
|
<TableHead>
|
||||||
|
<button
|
||||||
|
onClick={() =>
|
||||||
|
handleSort("warehouses.name")
|
||||||
|
}
|
||||||
|
className="flex items-center hover:text-gray-900"
|
||||||
|
>
|
||||||
|
倉庫
|
||||||
|
<SortIcon field="warehouses.name" />
|
||||||
|
</button>
|
||||||
|
</TableHead>
|
||||||
|
<TableHead>批號</TableHead>
|
||||||
|
<TableHead>儲位/貨道</TableHead>
|
||||||
|
<TableHead>
|
||||||
|
<button
|
||||||
|
onClick={() =>
|
||||||
|
handleSort("inventories.quantity")
|
||||||
|
}
|
||||||
|
className="flex items-center hover:text-gray-900"
|
||||||
|
>
|
||||||
|
數量
|
||||||
|
<SortIcon field="inventories.quantity" />
|
||||||
|
</button>
|
||||||
|
</TableHead>
|
||||||
|
<TableHead>安全庫存</TableHead>
|
||||||
|
<TableHead>
|
||||||
|
<button
|
||||||
|
onClick={() =>
|
||||||
|
handleSort(
|
||||||
|
"inventories.expiry_date"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
className="flex items-center hover:text-gray-900"
|
||||||
|
>
|
||||||
|
保存期限
|
||||||
|
<SortIcon field="inventories.expiry_date" />
|
||||||
|
</button>
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="text-center">
|
||||||
|
狀態
|
||||||
|
</TableHead>
|
||||||
|
<TableHead>最後入庫</TableHead>
|
||||||
|
<TableHead>最後出庫</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{inventories.data.length === 0 ? (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell
|
||||||
|
colSpan={13}
|
||||||
|
className="text-center py-8 text-gray-500"
|
||||||
|
>
|
||||||
|
無符合條件的資料
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
) : (
|
||||||
|
inventories.data.map((item: InventoryItem, index) => (
|
||||||
|
<TableRow key={item.id}>
|
||||||
|
<TableCell className="text-gray-500 font-medium text-center">
|
||||||
|
{startIndex + index}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-mono text-sm">
|
||||||
|
{item.product_code}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-medium">
|
||||||
|
{item.product_name}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-gray-500">
|
||||||
|
{item.category_name || "—"}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{item.warehouse_name}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-gray-500 text-sm">
|
||||||
|
{item.batch_number || "—"}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-sm text-gray-500">
|
||||||
|
{item.location || "—"}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell
|
||||||
|
className={`text-right font-medium ${item.quantity < 0
|
||||||
|
? "text-red-600"
|
||||||
|
: ""
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{item.quantity}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-right text-gray-500">
|
||||||
|
{item.safety_stock !== null
|
||||||
|
? item.safety_stock
|
||||||
|
: "—"}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-sm">
|
||||||
|
{item.expiry_date || "—"}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-center">
|
||||||
|
<div className="flex flex-wrap items-center justify-center gap-1">
|
||||||
|
{item.statuses.map(
|
||||||
|
(status) => {
|
||||||
|
const config =
|
||||||
|
statusConfig[
|
||||||
|
status
|
||||||
|
];
|
||||||
|
if (!config)
|
||||||
|
return null;
|
||||||
|
return (
|
||||||
|
<Badge
|
||||||
|
key={status}
|
||||||
|
variant="outline"
|
||||||
|
className={
|
||||||
|
config.className
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{config.label}
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-sm text-gray-500">
|
||||||
|
{item.last_inbound || "—"}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-sm text-gray-500">
|
||||||
|
{item.last_outbound || "—"}
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 分頁 */}
|
||||||
|
<div className="mt-4 flex flex-col sm:flex-row items-center justify-between gap-4">
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<div className="flex items-center gap-2 text-sm text-gray-500">
|
||||||
|
<span>每頁顯示</span>
|
||||||
|
<SearchableSelect
|
||||||
|
value={perPage}
|
||||||
|
onValueChange={handlePerPageChange}
|
||||||
|
options={[
|
||||||
|
{ label: "10", value: "10" },
|
||||||
|
{ label: "20", value: "20" },
|
||||||
|
{ label: "50", value: "50" },
|
||||||
|
{ label: "100", value: "100" },
|
||||||
|
]}
|
||||||
|
className="w-[90px] h-8"
|
||||||
|
showSearch={false}
|
||||||
|
/>
|
||||||
|
<span>筆</span>
|
||||||
|
</div>
|
||||||
|
<span className="text-sm text-gray-500">
|
||||||
|
共 {inventories.total} 筆紀錄
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<Pagination links={inventories.links} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</AuthenticatedLayout>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -43,6 +43,7 @@ interface Batch {
|
|||||||
expiryDate: string | null;
|
expiryDate: string | null;
|
||||||
quantity: number;
|
quantity: number;
|
||||||
isDeleted?: boolean;
|
isDeleted?: boolean;
|
||||||
|
location?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -322,7 +323,8 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
|
|||||||
inventoryId: item.inventoryId,
|
inventoryId: item.inventoryId,
|
||||||
originCountry: item.originCountry,
|
originCountry: item.originCountry,
|
||||||
expiryDate: item.expiryDate,
|
expiryDate: item.expiryDate,
|
||||||
unit_cost: item.unit_cost
|
unit_cost: item.unit_cost,
|
||||||
|
location: item.location,
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
}, {
|
}, {
|
||||||
@@ -575,17 +577,25 @@ export default function AddInventoryPage({ warehouse, products }: Props) {
|
|||||||
batchMode: 'existing',
|
batchMode: 'existing',
|
||||||
inventoryId: value,
|
inventoryId: value,
|
||||||
originCountry: selectedBatch?.originCountry,
|
originCountry: selectedBatch?.originCountry,
|
||||||
expiryDate: selectedBatch?.expiryDate || undefined
|
expiryDate: selectedBatch?.expiryDate || undefined,
|
||||||
|
location: selectedBatch?.location || item.location,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
options={[
|
options={[
|
||||||
{ label: "📦 不使用批號 (自動累加)", value: "no_batch" },
|
{ label: "📦 不使用批號 (自動累加)", value: "no_batch" },
|
||||||
{ label: "+ 建立新批號", value: "new_batch" },
|
{ label: "+ 建立新批號", value: "new_batch" },
|
||||||
...(batchesCache[item.productId]?.batches || []).map(b => ({
|
...(batchesCache[item.productId]?.batches || []).map(b => {
|
||||||
label: `${b.batchNumber === 'NO-BATCH' ? '(無批號紀錄)' : b.batchNumber} - 庫存: ${b.quantity}`,
|
const isNoBatch = b.batchNumber === 'NO-BATCH';
|
||||||
|
const showLocation = isNoBatch || warehouse.type === 'vending';
|
||||||
|
const locationInfo = (showLocation && b.location) ? ` [${b.location}]` : '';
|
||||||
|
const batchLabel = isNoBatch ? '(無批號紀錄)' : b.batchNumber;
|
||||||
|
|
||||||
|
return {
|
||||||
|
label: `${batchLabel}${locationInfo} - 庫存: ${b.quantity}`,
|
||||||
value: b.inventoryId
|
value: b.inventoryId
|
||||||
}))
|
};
|
||||||
|
})
|
||||||
]}
|
]}
|
||||||
placeholder="選擇或新增批號"
|
placeholder="選擇或新增批號"
|
||||||
className="border-gray-300"
|
className="border-gray-300"
|
||||||
|
|||||||
Reference in New Issue
Block a user