209 lines
6.5 KiB
TypeScript
209 lines
6.5 KiB
TypeScript
/**
|
|
* Cart/coupon money helpers shared by the backend (authoritative) and the RN
|
|
* cart/checkout + order-detail screens.
|
|
*
|
|
* Invariants:
|
|
* - The discount base is ALWAYS a goods subtotal — delivery (flash or scheduled)
|
|
* is never part of the base.
|
|
* - A coupon with no `applicableSkuIds` applies to the whole cart; otherwise it
|
|
* only discounts the line items whose skuId is in the target set.
|
|
* - Multiple coupons stack: percentage coupons first, then flat, each capped by
|
|
* its own `maxValue`; the combined discount never exceeds the goods subtotal.
|
|
*/
|
|
|
|
export interface CouponMoney {
|
|
discountPercent?: string | number | null
|
|
flatDiscount?: string | number | null
|
|
maxValue?: string | number | null
|
|
}
|
|
|
|
export interface TargetedCoupon extends CouponMoney {
|
|
id: number
|
|
exclusiveApply?: boolean
|
|
/** targeted SKU ids; empty/null => applies to the whole cart */
|
|
applicableSkuIds?: number[] | null
|
|
}
|
|
|
|
export interface CartLine {
|
|
skuId: number
|
|
quantity: number
|
|
unitPrice: number
|
|
}
|
|
|
|
export interface CartSubOrderInput {
|
|
key: number | string | null
|
|
items: CartLine[]
|
|
}
|
|
|
|
export interface CouponDiscountShare {
|
|
couponId: number
|
|
discount: number
|
|
}
|
|
|
|
export interface PricedSubOrder {
|
|
key: number | string | null
|
|
goodsSubtotal: number
|
|
discount: number
|
|
delivery: number
|
|
total: number
|
|
couponDiscounts: CouponDiscountShare[]
|
|
}
|
|
|
|
export interface CartPricingResult {
|
|
subOrders: PricedSubOrder[]
|
|
primaryIndex: number
|
|
primaryKey: number | string | null
|
|
goodsSubtotal: number
|
|
discountTotal: number
|
|
deliveryTotal: number
|
|
grandTotal: number
|
|
}
|
|
|
|
const toNum = (v: string | number | null | undefined): number => {
|
|
if (v == null) return 0
|
|
const n = typeof v === 'number' ? v : parseFloat(v)
|
|
return Number.isFinite(n) ? n : 0
|
|
}
|
|
|
|
const hasTargets = (coupon: TargetedCoupon): boolean =>
|
|
Array.isArray(coupon.applicableSkuIds) && coupon.applicableSkuIds.length > 0
|
|
|
|
/** Whether a line's sku participates in this coupon's discount base. */
|
|
export function lineEligibleForCoupon(
|
|
skuId: number,
|
|
coupon: Pick<TargetedCoupon, 'applicableSkuIds'>
|
|
): boolean {
|
|
if (!hasTargets(coupon as TargetedCoupon)) return true
|
|
return (coupon.applicableSkuIds as number[]).includes(skuId)
|
|
}
|
|
|
|
/** Sum of the line items this coupon discounts (whole cart when untargeted). */
|
|
export function computeEligibleSubtotal(
|
|
items: CartLine[],
|
|
coupon: Pick<TargetedCoupon, 'applicableSkuIds'>
|
|
): number {
|
|
return items.reduce(
|
|
(sum, item) =>
|
|
lineEligibleForCoupon(item.skuId, coupon)
|
|
? sum + item.unitPrice * item.quantity
|
|
: sum,
|
|
0
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Discount a single coupon contributes on its eligible subtotal:
|
|
* percent: min(subtotal * pct / 100, maxValue || Infinity)
|
|
* flat: min(flat, maxValue || subtotal)
|
|
* Clamped to [0, eligibleSubtotal].
|
|
*/
|
|
export function computeCouponDiscount(
|
|
eligibleSubtotal: number,
|
|
coupon: CouponMoney
|
|
): number {
|
|
if (eligibleSubtotal <= 0) return 0
|
|
const maxValue = toNum(coupon.maxValue)
|
|
const pct = toNum(coupon.discountPercent)
|
|
const flat = toNum(coupon.flatDiscount)
|
|
let discount = 0
|
|
if (pct) {
|
|
discount = Math.min((eligibleSubtotal * pct) / 100, maxValue || Infinity)
|
|
} else if (flat) {
|
|
discount = Math.min(flat, maxValue || eligibleSubtotal)
|
|
}
|
|
if (discount < 0) discount = 0
|
|
if (discount > eligibleSubtotal) discount = eligibleSubtotal
|
|
return discount
|
|
}
|
|
|
|
const couponRank = (coupon: CouponMoney): number =>
|
|
toNum(coupon.discountPercent) ? 0 : 1
|
|
|
|
/**
|
|
* Price a (possibly split) cart with zero or more coupons.
|
|
*
|
|
* Each coupon's discount is computed on its cart-wide eligible subtotal, then
|
|
* allocated to the sub-orders by that sub-order's share of the eligible subtotal
|
|
* (targeted coupons therefore land only on the sub-orders that hold the items).
|
|
* The combined discount is capped at the goods subtotal. The single cart-level
|
|
* delivery charge is attached to the primary sub-order (highest goods subtotal).
|
|
*/
|
|
export function computeCartPricing(params: {
|
|
subOrders: CartSubOrderInput[]
|
|
coupons?: TargetedCoupon[] | null
|
|
delivery: { threshold: number; charge: number }
|
|
}): CartPricingResult {
|
|
const subOrders = params.subOrders
|
|
const coupons = params.coupons ?? []
|
|
const { threshold, charge } = params.delivery
|
|
|
|
const subOrderGoods = subOrders.map((so) =>
|
|
so.items.reduce((sum, item) => sum + item.unitPrice * item.quantity, 0)
|
|
)
|
|
const goodsSubtotal = subOrderGoods.reduce((sum, v) => sum + v, 0)
|
|
|
|
// Primary sub-order = highest goods subtotal (tie -> first).
|
|
let primaryIndex = 0
|
|
for (let i = 1; i < subOrderGoods.length; i++) {
|
|
if (subOrderGoods[i] > subOrderGoods[primaryIndex]) primaryIndex = i
|
|
}
|
|
|
|
const orderedCoupons = [...coupons].sort(
|
|
(a, b) => couponRank(a) - couponRank(b)
|
|
)
|
|
|
|
const perSubOrderCoupon: CouponDiscountShare[][] = subOrders.map(() => [])
|
|
let discountTotal = 0
|
|
|
|
for (const coupon of orderedCoupons) {
|
|
const allItems = subOrders.flatMap((so) => so.items)
|
|
const eligibleTotal = computeEligibleSubtotal(allItems, coupon)
|
|
const discount = computeCouponDiscount(eligibleTotal, coupon)
|
|
if (discount <= 0) continue
|
|
|
|
for (let i = 0; i < subOrders.length; i++) {
|
|
const subEligible = computeEligibleSubtotal(subOrders[i].items, coupon)
|
|
const share = eligibleTotal > 0 ? discount * (subEligible / eligibleTotal) : 0
|
|
perSubOrderCoupon[i].push({ couponId: coupon.id, discount: share })
|
|
}
|
|
discountTotal += discount
|
|
}
|
|
|
|
// Never discount more than the goods subtotal.
|
|
if (discountTotal > goodsSubtotal && discountTotal > 0) {
|
|
const factor = goodsSubtotal / discountTotal
|
|
for (let i = 0; i < perSubOrderCoupon.length; i++) {
|
|
perSubOrderCoupon[i] = perSubOrderCoupon[i].map((entry) => ({
|
|
...entry,
|
|
discount: entry.discount * factor,
|
|
}))
|
|
}
|
|
discountTotal = goodsSubtotal
|
|
}
|
|
|
|
const finalTotal = goodsSubtotal - discountTotal
|
|
const deliveryTotal = finalTotal < threshold ? charge : 0
|
|
|
|
const priced: PricedSubOrder[] = subOrders.map((so, i) => {
|
|
const discount = perSubOrderCoupon[i].reduce((s, e) => s + e.discount, 0)
|
|
const subDelivery = i === primaryIndex ? deliveryTotal : 0
|
|
return {
|
|
key: so.key,
|
|
goodsSubtotal: subOrderGoods[i],
|
|
discount,
|
|
delivery: subDelivery,
|
|
total: subOrderGoods[i] - discount + subDelivery,
|
|
couponDiscounts: perSubOrderCoupon[i],
|
|
}
|
|
})
|
|
|
|
return {
|
|
subOrders: priced,
|
|
primaryIndex,
|
|
primaryKey: subOrders[primaryIndex]?.key ?? null,
|
|
goodsSubtotal,
|
|
discountTotal,
|
|
deliveryTotal,
|
|
grandTotal: finalTotal + deliveryTotal,
|
|
}
|
|
}
|