39 lines
1.2 KiB
TypeScript
39 lines
1.2 KiB
TypeScript
import type { StockCostHistoryEntry } from "@/lib/types";
|
|
|
|
/**
|
|
* Build the stock-item cost patch written when a purchase line is received.
|
|
* The purchase line remains the immutable source record; this keeps a compact
|
|
* operational current cost plus an append-only history on the stock item.
|
|
*/
|
|
export function buildStockReceiptCostPatch(
|
|
stockItem: { cost_history?: unknown },
|
|
input: {
|
|
costPrice: number;
|
|
quantity: number;
|
|
receivedAt?: string;
|
|
supplierId?: string;
|
|
purchaseId: string;
|
|
},
|
|
): { cost_price: number; cost_history: StockCostHistoryEntry[] } {
|
|
const history = Array.isArray(stockItem.cost_history)
|
|
? stockItem.cost_history.filter(
|
|
(entry): entry is StockCostHistoryEntry =>
|
|
Boolean(entry) &&
|
|
typeof entry === "object" &&
|
|
typeof (entry as { cost_price?: unknown }).cost_price === "number",
|
|
)
|
|
: [];
|
|
|
|
const entry: StockCostHistoryEntry = {
|
|
cost_price: input.costPrice,
|
|
quantity: input.quantity,
|
|
purchased_at: input.receivedAt ?? new Date().toISOString(),
|
|
purchase_id: input.purchaseId,
|
|
...(input.supplierId ? { supplier_id: input.supplierId } : {}),
|
|
};
|
|
|
|
return {
|
|
cost_price: input.costPrice,
|
|
cost_history: [...history, entry],
|
|
};
|
|
}
|