[REFACTOR] 統一訂單同步 API 錯誤回應與修正 Linter 警告
This commit is contained in:
@@ -58,29 +58,35 @@ class SyncOrderAction
|
||||
];
|
||||
}
|
||||
|
||||
// --- 預檢 (Pre-flight check) N+1 優化 ---
|
||||
// --- 預檢 (Pre-flight check) 僅使用 product_id ---
|
||||
$items = $data['items'];
|
||||
$posProductIds = array_column($items, 'pos_product_id');
|
||||
$targetErpIds = array_column($items, 'product_id');
|
||||
|
||||
// 一次性查出所有相關的 Product
|
||||
$products = $this->productService->findByExternalPosIds($posProductIds)->keyBy('external_pos_id');
|
||||
$productsById = $this->productService->findByIds($targetErpIds)->keyBy('id');
|
||||
|
||||
$resolvedProducts = [];
|
||||
$missingIds = [];
|
||||
foreach ($posProductIds as $id) {
|
||||
if (!$products->has($id)) {
|
||||
$missingIds[] = $id;
|
||||
|
||||
foreach ($items as $index => $item) {
|
||||
$productId = $item['product_id'];
|
||||
$product = $productsById->get($productId);
|
||||
|
||||
if ($product) {
|
||||
$resolvedProducts[$index] = $product;
|
||||
} else {
|
||||
$missingIds[] = $productId;
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($missingIds)) {
|
||||
// 回報所有缺漏的 ID
|
||||
throw ValidationException::withMessages([
|
||||
'items' => ["The following products are not found: " . implode(', ', $missingIds) . ". Please sync products first."]
|
||||
'items' => ["The following product IDs are not found: " . implode(', ', array_unique($missingIds)) . ". Please ensure these products exist in the system."]
|
||||
]);
|
||||
}
|
||||
|
||||
// --- 執行寫入交易 ---
|
||||
$result = DB::transaction(function () use ($data, $items, $products) {
|
||||
$result = DB::transaction(function () use ($data, $items, $resolvedProducts) {
|
||||
// 1. 建立訂單
|
||||
$order = SalesOrder::create([
|
||||
'external_order_id' => $data['external_order_id'],
|
||||
@@ -108,11 +114,12 @@ class SyncOrderAction
|
||||
|
||||
// 3. 處理訂單明細
|
||||
$orderItemsData = [];
|
||||
foreach ($items as $itemData) {
|
||||
$product = $products->get($itemData['pos_product_id']);
|
||||
foreach ($items as $index => $itemData) {
|
||||
$product = $resolvedProducts[$index];
|
||||
|
||||
$qty = $itemData['qty'];
|
||||
$price = $itemData['price'];
|
||||
$batchNumber = $itemData['batch_number'] ?? null;
|
||||
$lineTotal = $qty * $price;
|
||||
$totalAmount += $lineTotal;
|
||||
|
||||
@@ -134,9 +141,10 @@ class SyncOrderAction
|
||||
$qty,
|
||||
"POS Order: " . $order->external_order_id,
|
||||
true,
|
||||
null,
|
||||
null, // Slot (location)
|
||||
\App\Modules\Integration\Models\SalesOrder::class,
|
||||
$order->id
|
||||
$order->id,
|
||||
$batchNumber
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user