feat: 實作 POS API 整合功能,包含商品與銷售訂單同步及韌性機制
This commit is contained in:
@@ -59,9 +59,9 @@ class InventoryService implements InventoryServiceInterface
|
||||
return $stock >= $quantity;
|
||||
}
|
||||
|
||||
public function decreaseStock(int $productId, int $warehouseId, float $quantity, ?string $reason = null): void
|
||||
public function decreaseStock(int $productId, int $warehouseId, float $quantity, ?string $reason = null, bool $force = false): void
|
||||
{
|
||||
DB::transaction(function () use ($productId, $warehouseId, $quantity, $reason) {
|
||||
DB::transaction(function () use ($productId, $warehouseId, $quantity, $reason, $force) {
|
||||
$inventories = Inventory::where('product_id', $productId)
|
||||
->where('warehouse_id', $warehouseId)
|
||||
->where('quantity', '>', 0)
|
||||
@@ -79,8 +79,30 @@ class InventoryService implements InventoryServiceInterface
|
||||
}
|
||||
|
||||
if ($remainingToDecrease > 0) {
|
||||
// 這裡可以選擇報錯或允許負庫存,目前為了嚴謹拋出異常
|
||||
throw new \Exception("庫存不足,無法扣除所有請求的數量。");
|
||||
if ($force) {
|
||||
// Find any existing inventory record in this warehouse to subtract from, or create one
|
||||
$inventory = Inventory::where('product_id', $productId)
|
||||
->where('warehouse_id', $warehouseId)
|
||||
->first();
|
||||
|
||||
if (!$inventory) {
|
||||
$inventory = Inventory::create([
|
||||
'warehouse_id' => $warehouseId,
|
||||
'product_id' => $productId,
|
||||
'quantity' => 0,
|
||||
'unit_cost' => 0,
|
||||
'total_value' => 0,
|
||||
'batch_number' => 'POS-AUTO-' . time(),
|
||||
'arrival_date' => now(),
|
||||
'origin_country' => 'TW',
|
||||
'quality_status' => 'normal',
|
||||
]);
|
||||
}
|
||||
|
||||
$this->decreaseInventoryQuantity($inventory->id, $remainingToDecrease, $reason);
|
||||
} else {
|
||||
throw new \Exception("庫存不足,無法扣除所有請求的數量。");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user