Add cart pricing module

This commit is contained in:
2026-07-25 14:51:30 -07:00
parent f713f6e409
commit a45586326b
2 changed files with 32 additions and 0 deletions
+25
View File
@@ -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)
}
+7
View File
@@ -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)}`
}