freshyo/packages/shared/cart-pricing.ts
2026-10-23 15:04:19 +05:30

520 lines
18 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.
* - `minOrder` is measured on the WHOLE cart's goods subtotal, even for a
* targeted coupon; targeting only narrows the discount base.
* - 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 every line's goods value — the whole cart, before delivery. */
export function computeCartSubtotal(items: CartLine[]): number {
return items.reduce((sum, item) => sum + item.unitPrice * item.quantity, 0)
}
/** 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
}
/* -------------------------------------------------------------------------- *
* Local coupon eligibility
*
* The coupon endpoint hands the customer every coupon they may SEE (it only
* drops expired / invalidated / used-up / other people's coupons); whether a
* coupon applies to the CURRENT cart is decided locally, so a cart change never
* costs a request. These rules are the local twin of the backend's
* `validateAndGetCoupons` cart checks — keep them, and their wording, in step
* with packages/db_helper_sqlite/src/user-apis/order.ts.
* -------------------------------------------------------------------------- */
/** The coupon fields that decide whether it may be applied to a cart. */
export interface CouponEligibilityFields {
regionId?: number | null
isFirstOrderOnly?: boolean | null
minOrder?: string | number | null
/** per-user spending limit, and how many times THIS user has already used it */
maxLimitForUser?: number | null
usages?: unknown[] | null
/** targeted SKU ids; empty/null => the whole cart */
applicableSkuIds?: number[] | null
}
export interface CouponEligibilityContext {
/**
* in-stock cart lines — the targeted ones form the discount base; all of them
* form the minOrder base
*/
cartLines: CartLine[]
/** the region the cart is being built in */
regionId: number | null
/** whether the customer is still eligible for first-order-only coupons */
isFirstOrder: boolean
}
export interface CouponEligibility {
isEligible: boolean
/** Why it cannot be applied — the string the UI shows. Absent when eligible. */
reason?: string
/** Goods subtotal the coupon discounts (whole cart, or just its targeted lines). */
eligibleSubtotal: number
}
/**
* Whether a coupon can be applied to this cart, and why not when it can't.
* Rule order matches the backend: region, then first-order-only, then product
* targeting, then minOrder — targeting BEFORE minOrder, because a coupon whose
* targets are all missing must report "no applicable items" instead of a
* misleading "add ₹X more". minOrder is compared against the WHOLE cart's goods
* subtotal (delivery excluded), exactly as the server does; `eligibleSubtotal`
* remains the targeted-line base the discount is calculated on.
*/
export function evaluateCouponEligibility(
coupon: CouponEligibilityFields,
context: CouponEligibilityContext
): CouponEligibility {
const applicableSkuIds = Array.isArray(coupon.applicableSkuIds) ? coupon.applicableSkuIds : []
const targets = applicableSkuIds.length > 0 ? applicableSkuIds : null
const eligibleSubtotal = computeEligibleSubtotal(context.cartLines, {
applicableSkuIds: targets,
})
const fail = (reason: string): CouponEligibility => ({
isEligible: false,
reason,
eligibleSubtotal,
})
if (coupon.maxLimitForUser && (coupon.usages?.length ?? 0) >= coupon.maxLimitForUser) {
return fail('Usage limit exceeded')
}
if (
coupon.regionId != null &&
context.regionId != null &&
coupon.regionId !== context.regionId
) {
return fail('Not valid in your region')
}
if (coupon.isFirstOrderOnly && !context.isFirstOrder) {
return fail('Valid on your first order only')
}
if (targets && eligibleSubtotal <= 0) {
return fail('No applicable items in your cart')
}
const cartSubtotal = computeCartSubtotal(context.cartLines)
const minOrder = toNum(coupon.minOrder)
if (minOrder > cartSubtotal) {
return fail(`Add ₹${Math.ceil(minOrder - cartSubtotal)} more to use this coupon`)
}
return { isEligible: true, eligibleSubtotal }
}
interface StackCouponResult {
couponId: number
discount: number
/** where this coupon's discount landed, keyed by the line's group (sub-order) */
shareByGroup: Map<number, number>
/** the same money, keyed by the index of the line it landed on */
shareByLine: 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>()
const shareByLine = 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)
shareByLine.set(i, (shareByLine.get(i) ?? 0) + portion)
}
}
}
perCoupon.push({ couponId: coupon.id, discount, shareByGroup, shareByLine })
}
return { perCoupon, remaining }
}
/**
* Scale raw proportional shares onto `total` whole rupees so they sum exactly:
* round each share, then fold the 1-rupee drift into the largest one.
*/
function roundSharesOnto(rawShares: number[], total: number): number[] {
const rawSum = rawShares.reduce((sum, v) => sum + v, 0)
if (rawSum <= 0 || rawShares.length === 0) return rawShares.map(() => 0)
const scaled = rawShares.map((v) => (v * total) / rawSum)
const rounded = scaled.map((v) => Math.round(v))
const drift = total - rounded.reduce((sum, v) => sum + v, 0)
if (drift !== 0) {
let maxI = 0
for (let i = 1; i < scaled.length; i++) {
if (scaled[i] > scaled[maxI]) maxI = i
}
rounded[maxI] += drift
}
return rounded
}
/**
* Allocate `total` whole rupees across `weights` proportionally, never exceeding
* `caps[i]`. The amounts sum to min(total, sum(caps)); the rounding shortfall is
* folded onto the largest weights that still have headroom.
*/
function allocateBounded(weights: number[], total: number, caps: number[]): number[] {
// Shares are whole rupees, so a sub-order can only absorb whole rupees.
const limits = caps.map((cap) => Math.max(0, Math.floor(cap)))
const capTotal = limits.reduce((sum, limit) => sum + limit, 0)
const target = Math.max(0, Math.min(total, capTotal))
if (target === 0) return weights.map(() => 0)
const allocated = roundSharesOnto(weights, target)
for (let i = 0; i < allocated.length; i++) {
allocated[i] = Math.max(0, Math.min(allocated[i], limits[i]))
}
// Proportional rounding can push a share past its sub-order's remaining
// balance (or the usable cap), and can round the split up or down overall.
// Reconcile one rupee at a time so the coupon still discounts exactly its
// rounded amount and nothing exceeds a sub-order's balance.
let diff = target - allocated.reduce((sum, value) => sum + value, 0)
while (diff > 0) {
let pick = -1
for (let i = 0; i < allocated.length; i++) {
if (allocated[i] >= limits[i]) continue
if (pick === -1 || (weights[i] ?? 0) > (weights[pick] ?? 0)) pick = i
}
if (pick === -1) break
allocated[pick] += 1
diff -= 1
}
while (diff < 0) {
let pick = -1
for (let i = 0; i < allocated.length; i++) {
if (allocated[i] <= 0) continue
if (pick === -1 || allocated[i] > allocated[pick]) pick = i
}
if (pick === -1) break
allocated[pick] -= 1
diff += 1
}
return allocated
}
/** One cart line's share of a coupon's discount. */
export interface CouponLineDiscount {
skuId: number
discount: number
}
/** A coupon's discount split over the cart lines it landed on. */
export interface CouponLineBreakdown {
couponId: number
/** the coupon's total discount — the figure the bill shows for it */
discount: number
/** per-line shares, reconciled so they sum exactly to `discount` */
lines: CouponLineDiscount[]
}
/**
* Where each applied coupon's discount went, per cart line — what the bill's
* "applies to specific products" popup shows. Uses the same sequential waterfall
* as `computeCouponStack`, so the total here always matches the coupon's line in
* the bill, and the per-line shares are reconciled onto that total (whole rupees)
* so the popup's rows add up exactly.
*/
export function computeCouponLineBreakdowns(
lines: CartLine[],
coupons: TargetedCoupon[]
): CouponLineBreakdown[] {
const grouped: StackLine[] = lines.map((line) => ({ ...line, group: 0 }))
const { perCoupon } = runStack(grouped, coupons)
return perCoupon.map((entry) => {
const indexes = [...entry.shareByLine.keys()].sort((a, b) => a - b)
const rawShares = indexes.map((i) => entry.shareByLine.get(i) ?? 0)
const rounded = roundSharesOnto(rawShares, entry.discount)
return {
couponId: entry.couponId,
discount: entry.discount,
lines: indexes.map((i, position) => ({
skuId: grouped[i].skuId,
discount: rounded[position],
})),
}
})
}
/**
* 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 and never
* exceed a sub-order's remaining balance. 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(() => [])
// What each sub-order has already absorbed, so later coupons can only take
// what is still left there.
const allocatedByGroup = subOrders.map(() => 0)
let discountTotal = 0
for (const coupon of perCoupon) {
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)
// Cap each share at the sub-order's remaining balance so no sub-order can be
// discounted below zero; the shortfall is re-allocated within those caps.
const caps = groups.map((g) => Math.max(0, subOrderGoods[g] - allocatedByGroup[g]))
const rounded = allocateBounded(rawShares, coupon.discount, caps)
const allocated = rounded.reduce((sum, value) => sum + value, 0)
if (allocated <= 0) continue
discountTotal += allocated
groups.forEach((group, i) => {
if (rounded[i] === 0) return
perSubOrderCoupon[group].push({
couponId: coupon.couponId,
discount: rounded[i],
})
allocatedByGroup[group] += rounded[i]
})
}
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,
// Shares are capped per sub-order, so this never goes negative; clamped
// defensively because the figure is persisted and shown as money.
total: Math.max(0, subOrderGoods[i] - discount + subDelivery),
couponDiscounts: perSubOrderCoupon[i],
}
})
return {
subOrders: priced,
primaryIndex,
primaryKey: subOrders[primaryIndex]?.key ?? null,
goodsSubtotal,
discountTotal,
deliveryTotal,
grandTotal: finalTotal + deliveryTotal,
}
}