24 lines
1.1 KiB
TypeScript
24 lines
1.1 KiB
TypeScript
import { ItemListItem } from "@/types/master-data"
|
|
|
|
/** Rounds a sales unit price to 2dp, half away from zero (matches the server's SalesPricingService).
|
|
* Shifts via the exponent string rather than `* 100` so binary-float cases like 1.005 round up. */
|
|
export function roundPrice(value: number): number {
|
|
const shifted = Number(`${Math.round(Number(`${Math.abs(value)}e2`))}e-2`)
|
|
// Values JS prints in exponent form (e.g. 1e-7) can't take the string shift — those are ~0 anyway.
|
|
const rounded = Number.isFinite(shifted) ? shifted : Math.round(Math.abs(value) * 100) / 100
|
|
return value < 0 ? -rounded : rounded
|
|
}
|
|
|
|
/** A unit price input's value as a 2dp price, or null when cleared. */
|
|
export function parsePriceInput(value: string): number | null {
|
|
if (value === "") return null
|
|
const n = Number(value)
|
|
return Number.isFinite(n) ? roundPrice(n) : null
|
|
}
|
|
|
|
export function getSuggestedUnitPrice(items: ItemListItem[], itemId: number | null | undefined): number | null {
|
|
if (!itemId) return null
|
|
const price = items.find((item) => item.itemId === itemId)?.sellingFlatPrice
|
|
return price === null || price === undefined ? null : roundPrice(price)
|
|
}
|