diff --git a/resources/js/Pages/PurchaseOrder/Create.tsx b/resources/js/Pages/PurchaseOrder/Create.tsx
index 525e927..99c37ba 100644
--- a/resources/js/Pages/PurchaseOrder/Create.tsx
+++ b/resources/js/Pages/PurchaseOrder/Create.tsx
@@ -115,6 +115,7 @@ export default function CreatePurchaseOrder({
quantity: item.quantity,
unitPrice: item.unitPrice,
unitId: item.unitId,
+ subtotal: item.subtotal,
})),
};
diff --git a/resources/js/hooks/usePurchaseOrderForm.ts b/resources/js/hooks/usePurchaseOrderForm.ts
index 516dcb9..47e139a 100644
--- a/resources/js/hooks/usePurchaseOrderForm.ts
+++ b/resources/js/hooks/usePurchaseOrderForm.ts
@@ -87,7 +87,6 @@ export function usePurchaseOrderForm({ order, suppliers }: UsePurchaseOrderFormP
item.previousPrice = product.lastPrice;
// 決定預設單位
- // 若有採購單位且等於大單位,預設為大單位
const isPurchaseUnitLarge = product.purchase_unit_id && product.large_unit_id && product.purchase_unit_id === product.large_unit_id;
if (isPurchaseUnitLarge) {
@@ -97,6 +96,9 @@ export function usePurchaseOrderForm({ order, suppliers }: UsePurchaseOrderFormP
item.selectedUnit = 'base';
item.unitId = product.base_unit_id;
}
+
+ // 初始小計 = 數量 * 單價
+ item.subtotal = calculateSubtotal(Number(item.quantity), Number(item.unitPrice));
}
} else if (field === "selectedUnit") {
// @ts-ignore
@@ -106,17 +108,24 @@ export function usePurchaseOrderForm({ order, suppliers }: UsePurchaseOrderFormP
} else {
item.unitId = item.base_unit_id;
}
+ // Switch unit doesn't change Total Amount (Subtotal), but implies Unit Price changes?
+ // Actually if I switch unit, the Quantity is usually for that unit.
+ // If I have 1 Box ($100), and switch to Pc. Quantity is still 1.
+ // Total is $100. So Unit Price (per Pc) becomes $100.
+ // This seems safely consistent with "Total Amount" anchor.
} else {
// @ts-ignore
item[field] = value;
}
- // 計算小計
- if (field === "quantity" || field === "unitPrice" || field === "productId") {
- item.subtotal = calculateSubtotal(
- Number(item.quantity),
- Number(item.unitPrice)
- );
+ // 重新計算 (Always derive UnitPrice from Subtotal and Quantity)
+ // 除了剛剛已經算過 subtotal 的 productId case
+ if (field !== "productId") {
+ if (item.quantity > 0) {
+ item.unitPrice = Number(item.subtotal) / Number(item.quantity);
+ } else {
+ item.unitPrice = 0;
+ }
}
newItems[index] = item;