優化門市叫貨流程:實作庫存預扣機制、鎖定自動產生的調撥單明細、修復自動販賣機貨道數量連動 Bug 及狀態同步問題
All checks were successful
ERP-Deploy-Demo / deploy-demo (push) Successful in 56s
All checks were successful
ERP-Deploy-Demo / deploy-demo (push) Successful in 56s
This commit is contained in:
@@ -165,7 +165,10 @@ class StoreRequisitionController extends Controller
|
||||
*/
|
||||
public function show($id)
|
||||
{
|
||||
$requisition = StoreRequisition::with(['items.product.baseUnit'])->findOrFail($id);
|
||||
$requisition = StoreRequisition::with([
|
||||
'items.product.baseUnit',
|
||||
'transferOrder.items' // 載入產生的調撥單明細與批號
|
||||
])->findOrFail($id);
|
||||
|
||||
// 水和倉庫
|
||||
$warehouses = Warehouse::select('id', 'name', 'type')->get();
|
||||
@@ -198,8 +201,69 @@ class StoreRequisitionController extends Controller
|
||||
->get()
|
||||
->keyBy('product_id');
|
||||
|
||||
$requisition->items->transform(function ($item) use ($inventories) {
|
||||
// 取得供貨倉庫的可用庫存
|
||||
$supplyInventories = collect();
|
||||
$supplyBatchesMap = collect();
|
||||
if ($requisition->supply_warehouse_id) {
|
||||
$supplyInventories = Inventory::where('warehouse_id', $requisition->supply_warehouse_id)
|
||||
->whereIn('product_id', $productIds)
|
||||
->select('product_id')
|
||||
->selectRaw('SUM(quantity) as total_qty')
|
||||
->selectRaw('SUM(reserved_quantity) as total_reserved')
|
||||
->groupBy('product_id')
|
||||
->get()
|
||||
->keyBy('product_id');
|
||||
|
||||
// 取得各商品的批號庫存
|
||||
$batches = Inventory::where('warehouse_id', $requisition->supply_warehouse_id)
|
||||
->whereIn('product_id', $productIds)
|
||||
->whereRaw('(quantity - reserved_quantity) > 0') // 僅撈出還有可用庫存的批號
|
||||
->select('id', 'product_id', 'batch_number', 'expiry_date', 'location as position')
|
||||
->selectRaw('quantity - reserved_quantity as available_qty')
|
||||
->get();
|
||||
|
||||
$supplyBatchesMap = $batches->groupBy('product_id');
|
||||
}
|
||||
|
||||
// 把調撥單明細 (核准的批號與數量) 整理成 map, key 為 product_id
|
||||
$approvedBatchesMap = collect();
|
||||
if ($requisition->transferOrder) {
|
||||
$approvedBatchesMap = $requisition->transferOrder->items->groupBy('product_id');
|
||||
}
|
||||
|
||||
$requisition->items->transform(function ($item) use ($inventories, $supplyInventories, $supplyBatchesMap, $approvedBatchesMap) {
|
||||
$item->current_stock = $inventories->get($item->product_id)?->total_qty ?? 0;
|
||||
|
||||
if ($supplyInventories->has($item->product_id)) {
|
||||
$stock = $supplyInventories->get($item->product_id);
|
||||
$item->supply_stock = max(0, $stock->total_qty - $stock->total_reserved);
|
||||
|
||||
// 附加該商品的批號可用庫存
|
||||
$batches = $supplyBatchesMap->get($item->product_id) ?? collect();
|
||||
$item->supply_batches = $batches->map(function ($batch) {
|
||||
return [
|
||||
'inventory_id' => $batch->id,
|
||||
'batch_number' => $batch->batch_number,
|
||||
'position' => $batch->position,
|
||||
'available_qty' => $batch->available_qty,
|
||||
'expiry_date' => $batch->expiry_date ? $batch->expiry_date->format('Y-m-d') : null,
|
||||
];
|
||||
})->values()->toArray();
|
||||
} else {
|
||||
$item->supply_stock = null;
|
||||
$item->supply_batches = [];
|
||||
}
|
||||
|
||||
// 附加已核准的批號資訊
|
||||
$approvedBatches = $approvedBatchesMap->get($item->product_id) ?? collect();
|
||||
$item->approved_batches = $approvedBatches->map(function ($transferItem) {
|
||||
// 如果是沒有批號管控的商品,batch_number 可能為 null
|
||||
return [
|
||||
'batch_number' => $transferItem->batch_number,
|
||||
'qty' => $transferItem->quantity,
|
||||
];
|
||||
})->values()->toArray();
|
||||
|
||||
return $item;
|
||||
});
|
||||
|
||||
@@ -306,6 +370,10 @@ class StoreRequisitionController extends Controller
|
||||
'items' => 'required|array',
|
||||
'items.*.id' => 'required|exists:store_requisition_items,id',
|
||||
'items.*.approved_qty' => 'required|numeric|min:0',
|
||||
'items.*.batches' => 'nullable|array',
|
||||
'items.*.batches.*.inventory_id' => 'nullable|integer',
|
||||
'items.*.batches.*.batch_number' => 'nullable|string',
|
||||
'items.*.batches.*.qty' => 'required_with:items.*.batches|numeric|min:0.01',
|
||||
]);
|
||||
|
||||
if (empty($requisition->supply_warehouse_id)) {
|
||||
|
||||
@@ -215,6 +215,9 @@ class TransferOrderController extends Controller
|
||||
// 2. 先更新資料 (如果請求中包含 items,則先執行儲存)
|
||||
$itemsChanged = false;
|
||||
if ($request->has('items')) {
|
||||
if ($order->storeRequisition()->exists()) {
|
||||
return redirect()->back()->with('error', '由叫貨單自動產生的調撥單無法修改明細');
|
||||
}
|
||||
$validated = $request->validate([
|
||||
'items' => 'array',
|
||||
'items.*.product_id' => 'required|exists:products,id',
|
||||
@@ -263,6 +266,17 @@ class TransferOrderController extends Controller
|
||||
return redirect()->back()->with('error', '只能刪除草稿狀態的單據');
|
||||
}
|
||||
|
||||
// 刪除前必須先釋放預留庫存
|
||||
foreach ($order->items as $item) {
|
||||
$inv = Inventory::where('warehouse_id', $order->from_warehouse_id)
|
||||
->where('product_id', $item->product_id)
|
||||
->where('batch_number', $item->batch_number)
|
||||
->first();
|
||||
if ($inv) {
|
||||
$inv->releaseReservedQuantity($item->quantity);
|
||||
}
|
||||
}
|
||||
|
||||
$order->items()->delete();
|
||||
$order->delete();
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ class Inventory extends Model
|
||||
'warehouse_id',
|
||||
'product_id',
|
||||
'quantity',
|
||||
'reserved_quantity',
|
||||
'location',
|
||||
'unit_cost',
|
||||
'total_value',
|
||||
@@ -34,6 +35,8 @@ class Inventory extends Model
|
||||
protected $casts = [
|
||||
'arrival_date' => 'date:Y-m-d',
|
||||
'expiry_date' => 'date:Y-m-d',
|
||||
'quantity' => 'decimal:4',
|
||||
'reserved_quantity' => 'decimal:4',
|
||||
'unit_cost' => 'decimal:4',
|
||||
'total_value' => 'decimal:4',
|
||||
];
|
||||
@@ -109,7 +112,33 @@ class Inventory extends Model
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 可用庫存(實體庫存 - 預留庫存)
|
||||
*/
|
||||
public function getAvailableQuantityAttribute()
|
||||
{
|
||||
return max(0, $this->quantity - $this->reserved_quantity);
|
||||
}
|
||||
|
||||
/**
|
||||
* 增加預留庫存(鎖定)
|
||||
*/
|
||||
public function reserveQuantity(float|int $amount)
|
||||
{
|
||||
if ($amount <= 0) return;
|
||||
$this->reserved_quantity += $amount;
|
||||
$this->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* 釋放預留庫存(解鎖)
|
||||
*/
|
||||
public function releaseReservedQuantity(float|int $amount)
|
||||
{
|
||||
if ($amount <= 0) return;
|
||||
$this->reserved_quantity = max(0, $this->reserved_quantity - $amount);
|
||||
$this->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* 產生批號
|
||||
|
||||
@@ -118,17 +118,57 @@ class StoreRequisitionService
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($requisition, $data, $userId) {
|
||||
// 更新核准數量
|
||||
// 處理前端傳來的明細與批號資料
|
||||
$processedItems = []; // 暫存處理後的明細,用於轉入調撥單
|
||||
|
||||
if (isset($data['items'])) {
|
||||
foreach ($data['items'] as $itemData) {
|
||||
StoreRequisitionItem::where('id', $itemData['id'])
|
||||
$reqItemId = $itemData['id'];
|
||||
$totalApprovedQty = 0;
|
||||
$batches = $itemData['batches'] ?? [];
|
||||
|
||||
// 如果有批號,根據批號展開。若有多個無批號(null)的批次(例如來自不同貨道),則將其數量加總
|
||||
if (!empty($batches)) {
|
||||
$batchGroups = [];
|
||||
foreach ($batches as $batch) {
|
||||
$qty = (float)($batch['qty'] ?? 0);
|
||||
$bNum = $batch['batch_number'] ?? null;
|
||||
if ($qty > 0) {
|
||||
$totalApprovedQty += $qty;
|
||||
$batchKey = $bNum ?? '';
|
||||
$batchGroups[$batchKey] = ($batchGroups[$batchKey] ?? 0) + $qty;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($batchGroups as $bNumKey => $qty) {
|
||||
$processedItems[] = [
|
||||
'req_item_id' => $reqItemId,
|
||||
'batch_number' => $bNumKey === '' ? null : $bNumKey,
|
||||
'quantity' => $qty,
|
||||
];
|
||||
}
|
||||
} else {
|
||||
// 無批號,傳統輸入
|
||||
$qty = (float)($itemData['approved_qty'] ?? 0);
|
||||
if ($qty > 0) {
|
||||
$totalApprovedQty += $qty;
|
||||
$processedItems[] = [
|
||||
'req_item_id' => $reqItemId,
|
||||
'batch_number' => null,
|
||||
'quantity' => $qty,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// 更新叫貨單明細的核准數量總和
|
||||
StoreRequisitionItem::where('id', $reqItemId)
|
||||
->where('store_requisition_id', $requisition->id)
|
||||
->update(['approved_qty' => $itemData['approved_qty']]);
|
||||
->update(['approved_qty' => $totalApprovedQty]);
|
||||
}
|
||||
}
|
||||
|
||||
// 優先使用傳入的供貨倉庫,若無則從單據中取得
|
||||
$supplyWarehouseId = $data['supply_warehouse_id'] ?? $requisition->supply_warehouse_id;
|
||||
$supplyWarehouseId = $requisition->supply_warehouse_id;
|
||||
|
||||
if (!$supplyWarehouseId) {
|
||||
throw ValidationException::withMessages([
|
||||
@@ -152,12 +192,17 @@ class StoreRequisitionService
|
||||
// 將核准的明細寫入調撥單
|
||||
$requisition->load('items');
|
||||
$transferItems = [];
|
||||
foreach ($requisition->items as $item) {
|
||||
$qty = $item->approved_qty ?? $item->requested_qty;
|
||||
if ($qty > 0) {
|
||||
|
||||
// 建立 req_item_id 對應 product_id 的 lookup
|
||||
$reqItemMap = $requisition->items->keyBy('id');
|
||||
|
||||
foreach ($processedItems as $pItem) {
|
||||
$reqItem = $reqItemMap->get($pItem['req_item_id']);
|
||||
if ($reqItem) {
|
||||
$transferItems[] = [
|
||||
'product_id' => $item->product_id,
|
||||
'quantity' => $qty,
|
||||
'product_id' => $reqItem->product_id,
|
||||
'batch_number' => $pItem['batch_number'],
|
||||
'quantity' => $pItem['quantity'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,6 +45,17 @@ class TransferService
|
||||
return [$key => $item];
|
||||
});
|
||||
|
||||
// 釋放舊明細的預扣庫存
|
||||
foreach ($order->items as $item) {
|
||||
$inv = Inventory::where('warehouse_id', $order->from_warehouse_id)
|
||||
->where('product_id', $item->product_id)
|
||||
->where('batch_number', $item->batch_number)
|
||||
->first();
|
||||
if ($inv) {
|
||||
$inv->releaseReservedQuantity($item->quantity);
|
||||
}
|
||||
}
|
||||
|
||||
$diff = [
|
||||
'added' => [],
|
||||
'removed' => [],
|
||||
@@ -67,6 +78,21 @@ class TransferService
|
||||
]);
|
||||
$item->load('product');
|
||||
|
||||
// 增加新明細的預扣庫存
|
||||
$inv = Inventory::firstOrCreate(
|
||||
[
|
||||
'warehouse_id' => $order->from_warehouse_id,
|
||||
'product_id' => $item->product_id,
|
||||
'batch_number' => $item->batch_number,
|
||||
],
|
||||
[
|
||||
'quantity' => 0,
|
||||
'unit_cost' => 0,
|
||||
'total_value' => 0,
|
||||
]
|
||||
);
|
||||
$inv->reserveQuantity($item->quantity);
|
||||
|
||||
if ($oldItemsMap->has($key)) {
|
||||
$oldItem = $oldItemsMap->get($key);
|
||||
if ((float)$oldItem->quantity !== (float)$data['quantity'] ||
|
||||
@@ -163,6 +189,9 @@ class TransferService
|
||||
$oldSourceQty = $sourceInventory->quantity;
|
||||
$newSourceQty = $oldSourceQty - $item->quantity;
|
||||
|
||||
// 釋放草稿階段預扣的庫存
|
||||
$sourceInventory->reserved_quantity = max(0, $sourceInventory->reserved_quantity - $item->quantity);
|
||||
|
||||
$item->update(['snapshot_quantity' => $oldSourceQty]);
|
||||
|
||||
$sourceInventory->quantity = $newSourceQty;
|
||||
@@ -346,9 +375,22 @@ class TransferService
|
||||
if ($order->status !== 'draft') {
|
||||
throw new \Exception('只能作廢草稿狀態的單據');
|
||||
}
|
||||
$order->update([
|
||||
'status' => 'voided',
|
||||
'updated_by' => $userId
|
||||
]);
|
||||
|
||||
DB::transaction(function () use ($order, $userId) {
|
||||
foreach ($order->items as $item) {
|
||||
$inv = Inventory::where('warehouse_id', $order->from_warehouse_id)
|
||||
->where('product_id', $item->product_id)
|
||||
->where('batch_number', $item->batch_number)
|
||||
->first();
|
||||
if ($inv) {
|
||||
$inv->releaseReservedQuantity($item->quantity);
|
||||
}
|
||||
}
|
||||
|
||||
$order->update([
|
||||
'status' => 'voided',
|
||||
'updated_by' => $userId
|
||||
]);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('inventories', function (Blueprint $table) {
|
||||
$table->decimal('reserved_quantity', 12, 4)->default(0)->after('quantity')->comment('預留/鎖定庫存數量');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('inventories', function (Blueprint $table) {
|
||||
$table->dropColumn('reserved_quantity');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -269,6 +269,7 @@ export default function Show({ order, transitWarehouses = [] }: { order: any; tr
|
||||
|
||||
const canEdit = can('inventory_transfer.edit');
|
||||
const isReadOnly = (order.status !== 'draft' || !canEdit);
|
||||
const isItemsReadOnly = isReadOnly || !!order.requisition;
|
||||
const isVending = order.to_warehouse_type === 'vending';
|
||||
|
||||
// 狀態 Badge 渲染
|
||||
@@ -567,7 +568,7 @@ export default function Show({ order, transitWarehouses = [] }: { order: any; tr
|
||||
請選擇要調撥的商品並輸入數量。所有商品將從「{order.from_warehouse_name}」轉出。
|
||||
</p>
|
||||
</div>
|
||||
{!isReadOnly && (
|
||||
{!isItemsReadOnly && (
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" className="button-outlined-primary" onClick={() => setIsImportDialogOpen(true)}>
|
||||
<Package className="h-4 w-4 mr-2" />
|
||||
@@ -736,7 +737,7 @@ export default function Show({ order, transitWarehouses = [] }: { order: any; tr
|
||||
<TableHead className="font-medium text-grey-600">單位</TableHead>
|
||||
{isVending && <TableHead className="font-medium text-grey-600">貨道</TableHead>}
|
||||
<TableHead className="font-medium text-grey-600">備註</TableHead>
|
||||
{!isReadOnly && <TableHead className="w-[50px]"></TableHead>}
|
||||
{!isItemsReadOnly && <TableHead className="w-[50px]"></TableHead>}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
@@ -768,7 +769,7 @@ export default function Show({ order, transitWarehouses = [] }: { order: any; tr
|
||||
{item.max_quantity} {item.unit || item.unit_name}
|
||||
</TableCell>
|
||||
<TableCell className="px-1 py-3">
|
||||
{isReadOnly ? (
|
||||
{isItemsReadOnly ? (
|
||||
<div className="text-right font-semibold mr-2">{item.quantity}</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-1 items-end pr-2">
|
||||
@@ -786,7 +787,7 @@ export default function Show({ order, transitWarehouses = [] }: { order: any; tr
|
||||
<TableCell className="text-sm text-gray-500">{item.unit || item.unit_name}</TableCell>
|
||||
{isVending && (
|
||||
<TableCell className="px-1">
|
||||
{isReadOnly ? (
|
||||
{isItemsReadOnly ? (
|
||||
<span className="text-sm font-medium">{item.position}</span>
|
||||
) : (
|
||||
<Input
|
||||
@@ -799,7 +800,7 @@ export default function Show({ order, transitWarehouses = [] }: { order: any; tr
|
||||
</TableCell>
|
||||
)}
|
||||
<TableCell className="px-1">
|
||||
{isReadOnly ? (
|
||||
{isItemsReadOnly ? (
|
||||
<span className="text-sm text-gray-600">{item.notes}</span>
|
||||
) : (
|
||||
<Input
|
||||
@@ -810,7 +811,7 @@ export default function Show({ order, transitWarehouses = [] }: { order: any; tr
|
||||
/>
|
||||
)}
|
||||
</TableCell>
|
||||
{!isReadOnly && (
|
||||
{!isItemsReadOnly && (
|
||||
<TableCell className="text-center">
|
||||
<Button variant="outline" size="icon" className="button-outlined-error h-8 w-8" onClick={() => handleRemoveItem(index)}>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from "react";
|
||||
import React, { useState, useEffect } from "react";
|
||||
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
|
||||
import { Head, Link, router } from "@inertiajs/react";
|
||||
import { SearchableSelect } from "@/Components/ui/searchable-select";
|
||||
@@ -77,6 +77,9 @@ interface RequisitionItem {
|
||||
requested_qty: number;
|
||||
approved_qty: number | null;
|
||||
current_stock: number;
|
||||
supply_stock: number | null;
|
||||
supply_batches?: { inventory_id: number; batch_number: string | null; position: string | null; available_qty: number; expiry_date: string | null }[];
|
||||
approved_batches?: { batch_number: string | null; qty: number }[];
|
||||
remark: string | null;
|
||||
}
|
||||
|
||||
@@ -111,16 +114,49 @@ export default function Show({ requisition, warehouses }: Props) {
|
||||
const [approving, setApproving] = useState(false);
|
||||
const [rejecting, setRejecting] = useState(false);
|
||||
|
||||
// 核准狀態
|
||||
const [showApproveDialog, setShowApproveDialog] = useState(false);
|
||||
|
||||
const [approvedItems, setApprovedItems] = useState<{ id: number; approved_qty: string }[]>(
|
||||
requisition.items.map((item) => ({
|
||||
id: item.id,
|
||||
approved_qty: item.requested_qty.toString(),
|
||||
}))
|
||||
// 核准狀態 (支援批號分配)
|
||||
const [approvedItems, setApprovedItems] = useState<{
|
||||
id: number;
|
||||
batches: { inventory_id: number | null; batch_number: string | null; qty: string }[];
|
||||
}[]>(
|
||||
requisition.items.map((item) => {
|
||||
// 如果有批號,預設給空的陣列讓使用者自己填寫
|
||||
if (item.supply_batches && item.supply_batches.length > 0) {
|
||||
return {
|
||||
id: item.id,
|
||||
batches: item.supply_batches.map(b => ({ inventory_id: b.inventory_id, batch_number: b.batch_number, qty: "" }))
|
||||
};
|
||||
}
|
||||
// 無批號時,退回傳統單一輸入
|
||||
return {
|
||||
id: item.id,
|
||||
batches: [{ inventory_id: null, batch_number: null, qty: Number(item.requested_qty).toString() }],
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
// 當 requisition.items 變動時 (例如更換供貨倉庫導致 supply_batches 更新),同步更新核准狀態
|
||||
useEffect(() => {
|
||||
setApprovedItems(
|
||||
requisition.items.map((item) => {
|
||||
if (item.supply_batches && item.supply_batches.length > 0) {
|
||||
return {
|
||||
id: item.id,
|
||||
batches: item.supply_batches.map(b => ({
|
||||
inventory_id: b.inventory_id,
|
||||
batch_number: b.batch_number,
|
||||
qty: ""
|
||||
}))
|
||||
};
|
||||
}
|
||||
return {
|
||||
id: item.id,
|
||||
batches: [{ inventory_id: null, batch_number: null, qty: Number(item.requested_qty).toString() }],
|
||||
};
|
||||
})
|
||||
);
|
||||
}, [requisition.items]);
|
||||
|
||||
// 駁回狀態
|
||||
const [showRejectDialog, setShowRejectDialog] = useState(false);
|
||||
const [rejectReason, setRejectReason] = useState("");
|
||||
@@ -141,10 +177,14 @@ export default function Show({ requisition, warehouses }: Props) {
|
||||
const handleApprove = () => {
|
||||
// 確認每個核准數量
|
||||
for (const item of approvedItems) {
|
||||
const qty = parseFloat(item.approved_qty);
|
||||
if (isNaN(qty) || qty < 0) {
|
||||
toast.error("核准數量不能為負數");
|
||||
return;
|
||||
for (const batch of item.batches) {
|
||||
if (batch.qty !== "") {
|
||||
const qty = parseFloat(batch.qty);
|
||||
if (isNaN(qty) || qty < 0) {
|
||||
toast.error("核准數量不能為負數");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,15 +192,24 @@ export default function Show({ requisition, warehouses }: Props) {
|
||||
router.post(
|
||||
route("store-requisitions.approve", [requisition.id]),
|
||||
{
|
||||
items: approvedItems.map((item) => ({
|
||||
id: item.id,
|
||||
approved_qty: parseFloat(item.approved_qty),
|
||||
})),
|
||||
items: approvedItems.map((item) => {
|
||||
// 計算總數,提供給沒有批號情境的相容性,或作為總數參考
|
||||
const totalQty = item.batches.reduce((sum, b) => sum + (parseFloat(b.qty) || 0), 0);
|
||||
|
||||
return {
|
||||
id: item.id,
|
||||
approved_qty: totalQty,
|
||||
batches: item.batches.filter(b => b.qty !== "" && parseFloat(b.qty) > 0).map(b => ({
|
||||
inventory_id: b.inventory_id,
|
||||
batch_number: b.batch_number,
|
||||
qty: parseFloat(b.qty)
|
||||
}))
|
||||
};
|
||||
}),
|
||||
},
|
||||
{
|
||||
onFinish: () => {
|
||||
setApproving(false);
|
||||
setShowApproveDialog(false);
|
||||
},
|
||||
}
|
||||
);
|
||||
@@ -184,10 +233,16 @@ export default function Show({ requisition, warehouses }: Props) {
|
||||
);
|
||||
};
|
||||
|
||||
const updateApprovedQty = (itemId: number, qty: string) => {
|
||||
setApprovedItems(
|
||||
approvedItems.map((item) => (item.id === itemId ? { ...item, approved_qty: qty } : item))
|
||||
);
|
||||
const updateApprovedBatchQty = (itemId: number, inventoryId: number | null, qty: string) => {
|
||||
setApprovedItems(prev => prev.map(item => {
|
||||
if (item.id === itemId) {
|
||||
return {
|
||||
...item,
|
||||
batches: item.batches.map(b => b.inventory_id === inventoryId ? { ...b, qty } : b)
|
||||
};
|
||||
}
|
||||
return item;
|
||||
}));
|
||||
};
|
||||
|
||||
const isEditable = ["draft", "rejected"].includes(requisition.status);
|
||||
@@ -294,8 +349,10 @@ export default function Show({ requisition, warehouses }: Props) {
|
||||
</Button>
|
||||
<Button
|
||||
className="button-filled-success"
|
||||
onClick={() => setShowApproveDialog(true)}
|
||||
onClick={handleApprove}
|
||||
disabled={approving || !requisition.supply_warehouse_id}
|
||||
>
|
||||
{approving && <Loader2 className="w-4 h-4 mr-1 animate-spin" />}
|
||||
<CheckCircle2 className="w-4 h-4 mr-1" />
|
||||
核准
|
||||
</Button>
|
||||
@@ -402,8 +459,13 @@ export default function Show({ requisition, warehouses }: Props) {
|
||||
<TableHead className="font-medium text-gray-600">商品編號</TableHead>
|
||||
<TableHead className="font-medium text-gray-600">商品名稱</TableHead>
|
||||
<TableHead className="text-right font-medium text-gray-600">
|
||||
現有庫存
|
||||
申請倉現有
|
||||
</TableHead>
|
||||
{requisition.supply_warehouse_id && (
|
||||
<TableHead className="text-right font-medium text-gray-600">
|
||||
供貨倉可用
|
||||
</TableHead>
|
||||
)}
|
||||
<TableHead className="text-right font-medium text-gray-600">
|
||||
需求數量
|
||||
</TableHead>
|
||||
@@ -413,40 +475,145 @@ export default function Show({ requisition, warehouses }: Props) {
|
||||
核准數量
|
||||
</TableHead>
|
||||
)}
|
||||
{isPending && canApprove && (
|
||||
<TableHead className="font-medium text-gray-600">
|
||||
核准數量
|
||||
</TableHead>
|
||||
)}
|
||||
<TableHead className="font-medium text-gray-600">備註</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{requisition.items.map((item, index) => (
|
||||
<TableRow key={item.id}>
|
||||
<TableCell className="text-center text-gray-500 font-medium">
|
||||
{index + 1}
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-sm text-gray-600">
|
||||
{item.product_code}
|
||||
</TableCell>
|
||||
<TableCell className="font-medium text-gray-800">
|
||||
{item.product_name}
|
||||
</TableCell>
|
||||
<TableCell className="text-right text-gray-600">
|
||||
{Number(item.current_stock).toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-medium text-gray-800">
|
||||
{Number(item.requested_qty).toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell className="text-gray-500">{item.unit_name}</TableCell>
|
||||
{["approved", "completed"].includes(requisition.status) && (
|
||||
<TableCell className="text-right font-medium text-green-600">
|
||||
{item.approved_qty !== null
|
||||
? Number(item.approved_qty).toLocaleString()
|
||||
: "-"}
|
||||
</TableCell>
|
||||
)}
|
||||
<TableCell className="text-gray-500 text-sm">
|
||||
{item.remark || "-"}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
{requisition.items.map((item, index) => {
|
||||
const approvedItem = approvedItems.find((ai) => ai.id === item.id);
|
||||
|
||||
// 判斷是否為「多批號」情境 (審核時使用)
|
||||
const hasBatches = item.supply_batches && item.supply_batches.length > 0;
|
||||
|
||||
// 判斷是否含有效已核准批號 (檢視時使用)
|
||||
const hasApprovedBatches = item.approved_batches && item.approved_batches.some(b => b.batch_number !== null);
|
||||
|
||||
// 計算目前填寫的核准總量
|
||||
const totalApprovedQty = approvedItem
|
||||
? approvedItem.batches.reduce((sum, b) => sum + (parseFloat(b.qty) || 0), 0)
|
||||
: 0;
|
||||
|
||||
const isOverTotalStock = item.supply_stock !== null && totalApprovedQty > item.supply_stock;
|
||||
const rowClassName = (isPending && canApprove && isOverTotalStock) ? "bg-red-50/50" : "";
|
||||
|
||||
return (
|
||||
<React.Fragment key={item.id}>
|
||||
<TableRow className={rowClassName}>
|
||||
<TableCell className="text-center text-gray-500 font-medium pb-2">
|
||||
{index + 1}
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-sm text-gray-600 pb-2">
|
||||
{item.product_code}
|
||||
</TableCell>
|
||||
<TableCell className="font-medium text-gray-800 pb-2">
|
||||
{item.product_name}
|
||||
{hasBatches && isPending && canApprove && (
|
||||
<div className="text-xs text-blue-500 mt-1">需分配批號出庫 ↑</div>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right text-gray-600 pb-2">
|
||||
{Number(item.current_stock).toLocaleString()}
|
||||
</TableCell>
|
||||
{requisition.supply_warehouse_id && (
|
||||
<TableCell className="text-right text-gray-600 font-medium pb-2">
|
||||
{item.supply_stock !== null ? Number(item.supply_stock).toLocaleString() : "-"}
|
||||
</TableCell>
|
||||
)}
|
||||
<TableCell className="text-right font-medium text-gray-800 pb-2">
|
||||
{Number(item.requested_qty).toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell className="text-gray-500 pb-2">{item.unit_name}</TableCell>
|
||||
{["approved", "completed"].includes(requisition.status) && (
|
||||
<TableCell className="text-right font-medium text-green-600 pb-2">
|
||||
{item.approved_qty !== null
|
||||
? Number(item.approved_qty).toLocaleString()
|
||||
: "-"}
|
||||
</TableCell>
|
||||
)}
|
||||
{isPending && canApprove && (
|
||||
<TableCell className="pb-2">
|
||||
{!hasBatches ? (
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
min="0"
|
||||
value={approvedItem?.batches[0]?.qty || ""}
|
||||
onChange={(e) =>
|
||||
updateApprovedBatchQty(item.id, null, e.target.value)
|
||||
}
|
||||
className={`h-8 text-right w-[100px] ${isOverTotalStock ? "border-red-400 text-red-600 focus-visible:ring-red-400" : ""}`}
|
||||
/>
|
||||
) : (
|
||||
<div className="text-sm font-medium text-gray-700 text-right pr-6">
|
||||
總計: {totalApprovedQty > 0 ? totalApprovedQty : "-"}
|
||||
</div>
|
||||
)}
|
||||
</TableCell>
|
||||
)}
|
||||
<TableCell className="text-gray-500 text-sm pb-2">
|
||||
{item.remark || "-"}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
|
||||
{/* 展開批號/貨道輸入子行 */}
|
||||
{hasBatches && isPending && canApprove && item.supply_batches!.map((batch) => {
|
||||
const batchInput = approvedItem?.batches.find(b => b.inventory_id === batch.inventory_id);
|
||||
const inputQty = parseFloat(batchInput?.qty || "0");
|
||||
const isBatchOverStock = inputQty > batch.available_qty;
|
||||
|
||||
return (
|
||||
<TableRow key={`${item.id}-inv-${batch.inventory_id}`} className="bg-gray-50/50 border-0">
|
||||
<TableCell colSpan={4}></TableCell>
|
||||
<TableCell className="text-right text-xs text-gray-500 py-1">
|
||||
{batch.batch_number ? (
|
||||
<>批號: <span className="font-mono text-gray-700">{batch.batch_number}</span><br /></>
|
||||
) : (
|
||||
<>無批號<br /></>
|
||||
)}
|
||||
{batch.position && (
|
||||
<>貨道: <span className="font-medium text-gray-700">{batch.position}</span><br /></>
|
||||
)}
|
||||
(庫存: {Number(batch.available_qty)})<br />
|
||||
{batch.expiry_date && <span className="text-gray-400">效期: {batch.expiry_date}</span>}
|
||||
</TableCell>
|
||||
<TableCell colSpan={2}></TableCell>
|
||||
<TableCell className="py-1">
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
min="0"
|
||||
value={batchInput?.qty || ""}
|
||||
onChange={(e) => updateApprovedBatchQty(item.id, batch.inventory_id, e.target.value)}
|
||||
placeholder="輸入數量"
|
||||
className={`h-7 text-right w-[100px] text-xs ${isBatchOverStock ? "border-red-400 text-red-600 focus-visible:ring-red-400 bg-red-50" : ""}`}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell></TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* 展開已核准批號子行 (檢視用) */}
|
||||
{["approved", "completed"].includes(requisition.status) && hasApprovedBatches && item.approved_batches!.filter(b => b.batch_number).map((batch, bIndex) => (
|
||||
<TableRow key={`${item.id}-approved-batch-${batch.batch_number}-${bIndex}`} className="bg-green-50/40 border-0">
|
||||
<TableCell colSpan={5}></TableCell>
|
||||
<TableCell colSpan={2} className="text-right text-xs text-gray-500 py-1 pr-6">
|
||||
核准批號: <span className="font-mono text-gray-700">{batch.batch_number}</span>
|
||||
</TableCell>
|
||||
<TableCell className="text-right text-xs font-medium py-1 text-green-700 pr-4">
|
||||
{Number(batch.qty).toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell colSpan={2}></TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</React.Fragment>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
@@ -476,93 +643,7 @@ export default function Show({ requisition, warehouses }: Props) {
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* 核准對話框 */}
|
||||
<Dialog open={showApproveDialog} onOpenChange={setShowApproveDialog}>
|
||||
<DialogContent className="sm:max-w-[700px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>核准叫貨單</DialogTitle>
|
||||
<DialogDescription>選擇供貨倉庫,並確認各商品的核准數量。</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-2">
|
||||
<div className="flex items-center justify-between p-3 bg-blue-50 border border-blue-100 rounded-lg">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-blue-700 font-medium">供貨倉庫:</span>
|
||||
<span className="text-blue-900 font-bold">{requisition.supply_warehouse_name || "尚未選擇"}</span>
|
||||
</div>
|
||||
{!requisition.supply_warehouse_id && (
|
||||
<span className="text-xs text-red-500 font-medium">* 請先在基本資訊中選擇供貨倉庫</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="border rounded-lg overflow-hidden">
|
||||
<Table>
|
||||
<TableHeader className="bg-gray-50">
|
||||
<TableRow>
|
||||
<TableHead className="font-medium text-gray-600">商品</TableHead>
|
||||
<TableHead className="text-right font-medium text-gray-600 w-[120px]">
|
||||
需求數量
|
||||
</TableHead>
|
||||
<TableHead className="font-medium text-gray-600 w-[80px]">單位</TableHead>
|
||||
<TableHead className="font-medium text-gray-600 w-[150px]">
|
||||
核准數量
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{requisition.items.map((item) => (
|
||||
<TableRow key={item.id}>
|
||||
<TableCell>
|
||||
<span className="font-mono text-xs text-gray-500">
|
||||
{item.product_code}
|
||||
</span>
|
||||
<span className="ml-2 text-gray-800">{item.product_name}</span>
|
||||
</TableCell>
|
||||
<TableCell className="text-right text-gray-700">
|
||||
{Number(item.requested_qty).toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell className="text-gray-500 text-sm">
|
||||
{item.unit_name}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Input
|
||||
type="number"
|
||||
step="1"
|
||||
min="0"
|
||||
value={
|
||||
approvedItems.find((ai) => ai.id === item.id)
|
||||
?.approved_qty || ""
|
||||
}
|
||||
onChange={(e) =>
|
||||
updateApprovedQty(item.id, e.target.value)
|
||||
}
|
||||
className="h-8 text-right"
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="button-outlined-primary"
|
||||
onClick={() => setShowApproveDialog(false)}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
className="bg-green-600 hover:bg-green-700 text-white"
|
||||
onClick={handleApprove}
|
||||
disabled={approving || !requisition.supply_warehouse_id}
|
||||
>
|
||||
{approving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
確認核准
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* 駁回對話框 */}
|
||||
<Dialog open={showRejectDialog} onOpenChange={setShowRejectDialog}>
|
||||
|
||||
Reference in New Issue
Block a user