新增 POS 庫存查詢 API:實作 InventorySyncController 與相關 Service 邏輯,並更新 API 整合手冊
All checks were successful
ERP-Deploy-Demo / deploy-demo (push) Successful in 1m24s

This commit is contained in:
2026-03-02 10:19:20 +08:00
parent 4bbbde685d
commit 5f8b2a1c2d
10 changed files with 255 additions and 27 deletions

View File

@@ -22,6 +22,7 @@ class ActivityLogController extends Controller
'App\Modules\Procurement\Models\PurchaseOrder' => '採購單',
'App\Modules\Inventory\Models\Warehouse' => '倉庫',
'App\Modules\Inventory\Models\Inventory' => '庫存',
'App\Modules\Inventory\Models\InventoryTransaction' => '庫存異動紀錄',
'App\Modules\Finance\Models\UtilityFee' => '公共事業費',
'App\Modules\Inventory\Models\GoodsReceipt' => '進貨單',
'App\Modules\Production\Models\ProductionOrder' => '生產工單',

View File

@@ -0,0 +1,51 @@
<?php
namespace App\Modules\Integration\Controllers;
use App\Http\Controllers\Controller;
use App\Modules\Inventory\Contracts\InventoryServiceInterface;
use Illuminate\Http\JsonResponse;
class InventorySyncController extends Controller
{
protected $inventoryService;
public function __construct(InventoryServiceInterface $inventoryService)
{
$this->inventoryService = $inventoryService;
}
/**
* 提供外部 POS 查詢指定倉庫的商品庫存餘額
*
* @param string $warehouseCode
* @return JsonResponse
*/
public function show(string $warehouseCode): JsonResponse
{
// 透過 Service 調用跨模組庫存查詢功能
$inventoryData = $this->inventoryService->getPosInventoryByWarehouseCode($warehouseCode);
// 若回傳 null表示尋無此倉庫代碼
if (is_null($inventoryData)) {
return response()->json([
'status' => 'error',
'message' => "Warehouse with code '{$warehouseCode}' not found.",
], 404);
}
// 以 JSON 格式回傳組合好的商品庫存列表
return response()->json([
'status' => 'success',
'warehouse_code' => $warehouseCode,
'data' => $inventoryData->map(function ($item) {
return [
'external_pos_id' => $item->external_pos_id,
'product_code' => $item->product_code,
'product_name' => $item->product_name,
'quantity' => (float) $item->total_quantity,
];
})
], 200);
}
}

View File

@@ -4,6 +4,7 @@ use Illuminate\Support\Facades\Route;
use App\Modules\Integration\Controllers\ProductSyncController;
use App\Modules\Integration\Controllers\OrderSyncController;
use App\Modules\Integration\Controllers\VendingOrderSyncController;
use App\Modules\Integration\Controllers\InventorySyncController;
Route::prefix('api/v1/integration')
->middleware(['api', 'throttle:integration', 'integration.tenant', 'auth:sanctum'])
@@ -11,4 +12,5 @@ Route::prefix('api/v1/integration')
Route::post('products/upsert', [ProductSyncController::class, 'upsert']);
Route::post('orders', [OrderSyncController::class, 'store']);
Route::post('vending/orders', [VendingOrderSyncController::class, 'store']);
Route::get('inventory/{warehouse_code}', [InventorySyncController::class, 'show']);
});

View File

@@ -157,4 +157,12 @@ interface InventoryServiceInterface
* Get items expiring soon for dashboard.
*/
public function getExpiringSoon(int $limit = 5): \Illuminate\Support\Collection;
/**
* Get inventory summary (group by product) for a specific warehouse code
*
* @param string $code
* @return \Illuminate\Support\Collection|null
*/
public function getPosInventoryByWarehouseCode(string $code);
}

View File

@@ -259,7 +259,7 @@ class InventoryController extends Controller
$inventory->quantity = $newQty;
// 更新總價值
$inventory->total_value = $inventory->quantity * $inventory->unit_cost;
$inventory->save();
$inventory->saveQuietly(); // 使用 saveQuietly() 避免產生冗餘的「單據已更新」日誌
// 寫入異動紀錄
$inventory->transactions()->create([
@@ -436,7 +436,7 @@ class InventoryController extends Controller
$inventory->quantity = $newQty;
// 更新總值
$inventory->total_value = $inventory->quantity * $inventory->unit_cost;
$inventory->save();
$inventory->saveQuietly(); // 使用 saveQuietly() 避免與下方的 transaction 紀錄重複
// 異動類型映射
$type = $validated['type'] ?? ($isAdjustment ? 'manual_adjustment' : 'adjustment');

View File

@@ -58,8 +58,11 @@ class Inventory extends Model
public function tapActivity(\Spatie\Activitylog\Contracts\Activity $activity, string $eventName)
{
$properties = $activity->properties;
$attributes = $properties['attributes'] ?? [];
// 核心:轉換為陣列以避免 Indirect modification error
$properties = $activity->properties instanceof \Illuminate\Support\Collection
? $activity->properties->toArray()
: $activity->properties;
$snapshot = $properties['snapshot'] ?? [];
// 始終對名稱進行快照以便於上下文顯示,即使 ID 未更改
@@ -69,11 +72,28 @@ class Inventory extends Model
// 如果已設定原因,則進行捕捉
if ($this->activityLogReason) {
$attributes['_reason'] = $this->activityLogReason;
$properties['attributes']['_reason'] = $this->activityLogReason;
}
$properties['attributes'] = $attributes;
$properties['snapshot'] = $snapshot;
// 全域 ID 轉名稱邏輯
$resolver = function (&$data) {
if (empty($data) || !is_array($data)) return;
// 倉庫 ID 轉換
if (isset($data['warehouse_id']) && is_numeric($data['warehouse_id'])) {
$data['warehouse_id'] = \App\Modules\Inventory\Models\Warehouse::find($data['warehouse_id'])?->name;
}
// 商品 ID 轉換
if (isset($data['product_id']) && is_numeric($data['product_id'])) {
$data['product_id'] = \App\Modules\Inventory\Models\Product::find($data['product_id'])?->name;
}
};
if (isset($properties['attributes'])) $resolver($properties['attributes']);
if (isset($properties['old'])) $resolver($properties['old']);
$activity->properties = $properties;
}

View File

@@ -10,6 +10,7 @@ class InventoryTransaction extends Model
{
/** @use HasFactory<\Database\Factories\InventoryTransactionFactory> */
use HasFactory;
use \Spatie\Activitylog\Traits\LogsActivity;
protected $fillable = [
'inventory_id',
@@ -41,4 +42,49 @@ class InventoryTransaction extends Model
{
return $this->morphTo();
}
public function getActivitylogOptions(): \Spatie\Activitylog\LogOptions
{
return \Spatie\Activitylog\LogOptions::defaults()
->logAll()
->dontLogIfAttributesChangedOnly(['updated_at'])
// 取消 logOnlyDirty代表新增時(created)也要留紀錄
->dontSubmitEmptyLogs();
}
public function tapActivity(\Spatie\Activitylog\Contracts\Activity $activity, string $eventName)
{
$properties = $activity->properties instanceof \Illuminate\Support\Collection
? $activity->properties->toArray()
: $activity->properties;
$snapshot = $properties['snapshot'] ?? [];
// 試著取得商品與倉庫名稱來作為主要顯示依據
$inventory = $this->inventory;
if ($inventory) {
$snapshot['warehouse_name'] = $inventory->warehouse ? $inventory->warehouse->name : null;
$snapshot['product_name'] = $inventory->product ? $inventory->product->name : null;
$snapshot['batch_number'] = $inventory->batch_number;
}
// 把異動類型與數量也拉到 snapshot
$snapshot['type'] = $this->type;
$snapshot['quantity'] = $this->quantity;
$snapshot['reason'] = $this->reason;
// 替換使用者名稱
$resolver = function (&$data) {
if (empty($data) || !is_array($data)) return;
if (isset($data['user_id']) && is_numeric($data['user_id'])) {
$data['user_id'] = \App\Modules\Core\Models\User::find($data['user_id'])?->name;
}
};
if (isset($properties['attributes'])) $resolver($properties['attributes']);
if (isset($properties['old'])) $resolver($properties['old']);
$properties['snapshot'] = $snapshot;
$activity->properties = $properties;
}
}

View File

@@ -85,30 +85,50 @@ class Product extends Model
public function tapActivity(\Spatie\Activitylog\Contracts\Activity $activity, string $eventName)
{
$properties = $activity->properties;
$attributes = $properties['attributes'] ?? [];
// 核心:轉換為陣列以避免 Indirect modification error
$properties = $activity->properties instanceof \Illuminate\Support\Collection
? $activity->properties->toArray()
: $activity->properties;
$snapshot = $properties['snapshot'] ?? [];
// 處理分類名稱快照
if (isset($attributes['category_id'])) {
$category = Category::find($attributes['category_id']);
$snapshot['category_name'] = $category ? $category->name : null;
}
// 處理單位名稱快照
$unitFields = ['base_unit_id', 'large_unit_id', 'purchase_unit_id'];
foreach ($unitFields as $field) {
if (isset($attributes[$field])) {
$unit = Unit::find($attributes[$field]);
$nameKey = str_replace('_id', '_name', $field);
$snapshot[$nameKey] = $unit ? $unit->name : null;
}
}
// 始終對自身名稱進行快照以便於上下文顯示(這樣日誌總是顯示 "可樂"
$snapshot['name'] = $this->name;
$properties['attributes'] = $attributes;
$properties['snapshot'] = $snapshot;
// 全域 ID 轉名稱邏輯
$resolver = function (&$data) use (&$snapshot) {
if (empty($data) || !is_array($data)) return;
// 處理分類名稱
if (isset($data['category_id']) && is_numeric($data['category_id'])) {
$categoryName = Category::find($data['category_id'])?->name;
$data['category_id'] = $categoryName;
if (!isset($snapshot['category_name']) && $categoryName) {
$snapshot['category_name'] = $categoryName;
}
}
// 處理單位名稱
$unitFields = ['base_unit_id', 'large_unit_id', 'purchase_unit_id'];
foreach ($unitFields as $field) {
if (isset($data[$field]) && is_numeric($data[$field])) {
$unitName = Unit::find($data[$field])?->name;
$data[$field] = $unitName;
$nameKey = str_replace('_id', '_name', $field);
if (!isset($snapshot[$nameKey]) && $unitName) {
$snapshot[$nameKey] = $unitName;
}
}
}
};
if (isset($properties['attributes'])) $resolver($properties['attributes']);
if (isset($properties['old'])) $resolver($properties['old']);
// 因為 resolver 內部可能更新了 snapshot所以再覆寫一次
$properties['snapshot'] = $snapshot;
$activity->properties = $properties;
}

View File

@@ -644,4 +644,34 @@ class InventoryService implements InventoryServiceInterface
]
);
}
/**
* 取得特定倉庫代碼的所屬商品總庫存 ( POS/外部系統同步使用)
*
* @param string $code
* @return \Illuminate\Support\Collection|null
*/
public function getPosInventoryByWarehouseCode(string $code)
{
$warehouse = Warehouse::where('code', $code)->first();
if (!$warehouse) {
return null;
}
// 整理該倉庫的庫存,以 product_id 進行 GROUP BY 並加總 quantity
return DB::table('inventories')
->join('products', 'inventories.product_id', '=', 'products.id')
->where('inventories.warehouse_id', $warehouse->id)
->whereNull('inventories.deleted_at')
->whereNull('products.deleted_at')
->select(
'products.external_pos_id',
'products.code as product_code',
'products.name as product_name',
DB::raw('SUM(inventories.quantity) as total_quantity')
)
->groupBy('inventories.product_id', 'products.external_pos_id', 'products.code', 'products.name')
->get();
}
}