Add cart pricing module
This commit is contained in:
+25
@@ -0,0 +1,25 @@
|
|||||||
|
export interface CartItem {
|
||||||
|
sku: string
|
||||||
|
name: string
|
||||||
|
unitPriceCents: number
|
||||||
|
quantity: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Discount {
|
||||||
|
code: string
|
||||||
|
percentOff: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subtotalCents(items: CartItem[]): number {
|
||||||
|
return items.reduce((sum, item) => sum + item.unitPriceCents * item.quantity, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function applyDiscount(subtotal: number, discount?: Discount): number {
|
||||||
|
if (!discount) return subtotal
|
||||||
|
const factor = 1 - discount.percentOff / 100
|
||||||
|
return Math.round(subtotal * factor)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function totalCents(items: CartItem[], discount?: Discount): number {
|
||||||
|
return applyDiscount(subtotalCents(items), discount)
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
export function formatCents(cents: number, currency = 'USD'): string {
|
||||||
|
return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(cents / 100)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatLineItem(name: string, quantity: number, unitPriceCents: number): string {
|
||||||
|
return `${name} x${quantity} — ${formatCents(unitPriceCents * quantity)}`
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user