315 lines
10 KiB
TypeScript
315 lines
10 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 apply SEQUENTIALLY, in the order they are given (the user's
|
|
* selection order): the first coupon discounts the subtotal, the second discounts
|
|
* whatever is left, and so on. Each coupon's discount is rounded to the nearest
|
|
* rupee.
|
|
* - 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
|
|
}
|
|
|
|
export interface CouponStackEntry {
|
|
couponId: number
|
|
discount: 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
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Raw (unrounded) discount a single coupon contributes on a given subtotal:
|
|
* percent: min(subtotal * pct / 100, maxValue || Infinity)
|
|
* flat: min(flat, maxValue || subtotal)
|
|
* Clamped to [0, eligibleSubtotal]. Callers that need whole rupees round it.
|
|
*/
|
|
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
|
|
}
|
|
|
|
interface StackLine extends CartLine {
|
|
group: number
|
|
}
|
|
|
|
interface StackCouponResult {
|
|
couponId: number
|
|
discount: number
|
|
/** where this coupon's discount landed, keyed by the line's group (sub-order) */
|
|
shareByGroup: Map<number, number>
|
|
}
|
|
|
|
/**
|
|
* Apply coupons one after another over a shared set of line amounts. Each coupon
|
|
* discounts only what is still remaining on its eligible lines, so later coupons
|
|
* see the money the earlier ones left behind. Discounts are rounded to the nearest
|
|
* rupee and the eligible lines' remainders are reduced proportionally.
|
|
*/
|
|
function runStack(
|
|
lines: StackLine[],
|
|
coupons: TargetedCoupon[]
|
|
): { perCoupon: StackCouponResult[]; remaining: number[] } {
|
|
const remaining = lines.map((line) => line.unitPrice * line.quantity)
|
|
const perCoupon: StackCouponResult[] = []
|
|
|
|
for (const coupon of coupons) {
|
|
const idx: number[] = []
|
|
for (let i = 0; i < lines.length; i++) {
|
|
if (lineEligibleForCoupon(lines[i].skuId, coupon)) idx.push(i)
|
|
}
|
|
|
|
const eligible = idx.reduce((sum, i) => sum + remaining[i], 0)
|
|
let discount = 0
|
|
const shareByGroup = new Map<number, number>()
|
|
|
|
if (eligible > 0) {
|
|
const raw = computeCouponDiscount(eligible, coupon)
|
|
discount = Math.max(0, Math.min(Math.round(raw), Math.round(eligible)))
|
|
if (discount > 0) {
|
|
for (const i of idx) {
|
|
const portion = discount * (remaining[i] / eligible)
|
|
remaining[i] = Math.max(0, remaining[i] - portion)
|
|
const group = lines[i].group
|
|
shareByGroup.set(group, (shareByGroup.get(group) ?? 0) + portion)
|
|
}
|
|
}
|
|
}
|
|
|
|
perCoupon.push({ couponId: coupon.id, discount, shareByGroup })
|
|
}
|
|
|
|
return { perCoupon, remaining }
|
|
}
|
|
|
|
/**
|
|
* The per-coupon discount each coupon contributes when applied in the given order,
|
|
* rounded to whole rupees, plus the total. This is the single source of truth the
|
|
* cart/checkout screens use for their per-coupon ("Save ₹x") and total figures, so
|
|
* the app and the backend always agree.
|
|
*/
|
|
export function computeCouponStack(
|
|
lines: CartLine[],
|
|
coupons: TargetedCoupon[]
|
|
): { perCoupon: CouponStackEntry[]; discountTotal: number } {
|
|
const grouped: StackLine[] = lines.map((line) => ({ ...line, group: 0 }))
|
|
const { perCoupon } = runStack(grouped, coupons)
|
|
const entries = perCoupon.map((c) => ({
|
|
couponId: c.couponId,
|
|
discount: c.discount,
|
|
}))
|
|
return {
|
|
perCoupon: entries,
|
|
discountTotal: entries.reduce((sum, e) => sum + e.discount, 0),
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Price a (possibly split) cart with zero or more coupons.
|
|
*
|
|
* Coupons are applied in the order given: each discounts what is still remaining
|
|
* on its eligible lines (the cart-wide eligible subtotal minus what the earlier
|
|
* coupons already took), rounded to the nearest rupee. Each coupon's discount is
|
|
* then allocated to the sub-orders by that sub-order's share of the eligible
|
|
* remaining amount (targeted coupons therefore land only on the sub-orders that
|
|
* hold the items), reconciled so the per-sub-order shares sum exactly. 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
|
|
}
|
|
|
|
// Flatten every sub-order's lines so the waterfall runs across the whole cart
|
|
// while remembering which sub-order each line belongs to.
|
|
const flat: StackLine[] = []
|
|
subOrders.forEach((so, group) => {
|
|
so.items.forEach((item) => flat.push({ ...item, group }))
|
|
})
|
|
|
|
const { perCoupon } = runStack(flat, coupons)
|
|
|
|
const perSubOrderCoupon: CouponDiscountShare[][] = subOrders.map(() => [])
|
|
let discountTotal = 0
|
|
|
|
for (const coupon of perCoupon) {
|
|
discountTotal += coupon.discount
|
|
if (coupon.discount <= 0 || coupon.shareByGroup.size === 0) continue
|
|
|
|
const groups = [...coupon.shareByGroup.keys()].sort((a, b) => a - b)
|
|
const rawShares = groups.map((g) => coupon.shareByGroup.get(g) ?? 0)
|
|
const rawSum = rawShares.reduce((sum, v) => sum + v, 0)
|
|
|
|
// Scale the raw shares onto the rounded discount, round each sub-order share,
|
|
// and fold the 1-rupee drift into the largest share so they sum exactly.
|
|
const scaled =
|
|
rawSum > 0 ? rawShares.map((v) => (v * coupon.discount) / rawSum) : rawShares
|
|
const rounded = scaled.map((v) => Math.round(v))
|
|
const drift = coupon.discount - rounded.reduce((sum, v) => sum + v, 0)
|
|
if (drift !== 0 && rounded.length > 0) {
|
|
let maxI = 0
|
|
for (let i = 1; i < rounded.length; i++) {
|
|
if (scaled[i] > scaled[maxI]) maxI = i
|
|
}
|
|
rounded[maxI] += drift
|
|
}
|
|
|
|
groups.forEach((group, i) => {
|
|
if (rounded[i] !== 0) {
|
|
perSubOrderCoupon[group].push({
|
|
couponId: coupon.couponId,
|
|
discount: rounded[i],
|
|
})
|
|
}
|
|
})
|
|
}
|
|
|
|
// Defensive: 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: Math.round(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,
|
|
}
|
|
}
|