Compare commits

..

No commits in common. "24d2add4e3a6756d013e3b80214400eee7e9527c" and "12fb0db4c96061b510532352d4e8ce160b919105" have entirely different histories.

11 changed files with 14 additions and 171 deletions

View file

@ -840,7 +840,6 @@ known stale-test bug.
| UORD-45 | edge | usage-limit coupon | rejected | | UORD-45 | edge | usage-limit coupon | rejected |
| UORD-46 | edge | min-order not met | rejected/not applied | | UORD-46 | edge | min-order not met | rejected/not applied |
| UORD-47 | edge | targeted SKU coupon | discount only target | | UORD-47 | edge | targeted SKU coupon | discount only target |
| UORD-47B | edge | targeted SKU coupon, target below minOrder but whole cart above it | accepted; discount only on target |
| UORD-48 | edge | first-order-only | first works, second rejects | | UORD-48 | edge | first-order-only | first works, second rejects |
| UORD-49 | edge | exclusive coupon + another | reject or exclusive wins per contract | | UORD-49 | edge | exclusive coupon + another | reject or exclusive wins per contract |
| UORD-50 | edge | 100%+ percentage coupon | total never negative; delivery still correct | | UORD-50 | edge | 100%+ percentage coupon | total never negative; delivery still correct |
@ -907,7 +906,6 @@ known stale-test bug.
| UORD-106 | edge | cancel publishes cancellation | queue/publish called; failure logged | | UORD-106 | edge | cancel publishes cancellation | queue/publish called; failure logged |
| UORD-107 | edge | double cancel race | one success/one failure, no corrupt status | | UORD-107 | edge | double cancel race | one success/one failure, no corrupt status |
| UORD-108 | edge | order with orderGroup | cancellation updates group/status consistently | | UORD-108 | edge | order with orderGroup | cancellation updates group/status consistently |
| UORD-108B | edge | grouped order with a usage-capped coupon; cancel siblings one by one | coupon stays exhausted until the last sibling is cancelled, then becomes reusable |
### 6.12 User product API ### 6.12 User product API

View file

@ -621,10 +621,10 @@ describe('user.order cancelOrder (UORD-98..103, 107)', () => {
}) })
/* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */
/* 5. Cancellation side-effects (UORD-104..106, 108, 108B) */ /* 5. Cancellation side-effects (UORD-104..106, 108) */
/* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */
describe('user.order cancellation side-effects (UORD-104..106, 108, 108B)', () => { describe('user.order cancellation side-effects (UORD-104..106, 108)', () => {
it('UORD-104: cancelling releases the coupon usage so it can be used again', async () => { it('UORD-104: cancelling releases the coupon usage so it can be used again', async () => {
const fx = await createCatalogOrderFixture({ price: 199 }) const fx = await createCatalogOrderFixture({ price: 199 })
const c = await makeCoupon({ flatDiscount: 20, minOrder: 1, maxLimitForUser: 1 }) const c = await makeCoupon({ flatDiscount: 20, minOrder: 1, maxLimitForUser: 1 })
@ -712,44 +712,4 @@ describe('user.order cancellation side-effects (UORD-104..106, 108, 108B)', () =
expect(e0.couponCode).toBeNull() expect(e0.couponCode).toBeNull()
expect(e1.couponCode).toBeNull() expect(e1.couponCode).toBeNull()
}) })
it('UORD-108B: a grouped coupon is restored only after every sibling is cancelled', async () => {
const fx = await createCatalogOrderFixture({ price: 199 })
const slot2 = await createFutureSlot([fx.product.skuId])
const c = await makeCoupon({ flatDiscount: 50, minOrder: 1, maxLimitForUser: 1 })
const res = await placeCall(fx.user.token, {
addressId: fx.address.id,
items: [
{ skuId: fx.product.skuId, quantity: 1, slotId: fx.slot.slotId },
{ skuId: fx.product.skuId, quantity: 1, slotId: slot2.slotId },
],
couponIds: [c.id],
})
const ids = res.data.map((o: any) => Number(o.id))
// Cancel one sibling: the group still has a live order, so the coupon stays used.
await apiClient(fx.user.token).user.order.cancelOrder.mutate({ id: ids[0], reason: 'first' })
await expectTrpcError(
() =>
placeCall(fx.user.token, {
addressId: fx.address.id,
skuId: fx.product.skuId,
slotId: fx.slot.slotId,
couponIds: [c.id],
}),
'INTERNAL_SERVER_ERROR',
'usage limit exceeded'
)
// Cancel the last sibling: the group is fully cancelled, so the usage is released.
await apiClient(fx.user.token).user.order.cancelOrder.mutate({ id: ids[1], reason: 'second' })
const after = await placeCall(fx.user.token, {
addressId: fx.address.id,
skuId: fx.product.skuId,
slotId: fx.slot.slotId,
couponIds: [c.id],
})
expect(after.success).toBe(true)
expect(Number(after.data[0].discountAmount)).toBe(50)
})
}) })

View file

@ -1050,30 +1050,6 @@ describe('user.order.placeOrder — coupons (UORD-39..56)', () => {
expect(Number(res.data[0].totalAmount)).toBe(100 + 300 * quantityOther - 50) expect(Number(res.data[0].totalAmount)).toBe(100 + 300 * quantityOther - 50)
}) })
it('UORD-47B: a targeted coupon measures minOrder on the whole cart, discounts only its SKU', async () => {
const store = await createStore()
const target = await createProduct({ storeId: store.storeId, price: 100 })
const other = await createProduct({ storeId: store.storeId, price: 300 })
const slot = await createFutureSlot([target.skuId, other.skuId])
const quantityOther = 10
// Target value is ₹100 (< ₹500), but the cart is ₹3,100.
const c = await makeCoupon({ flatDiscount: 50, skuIds: [target.skuId], minOrder: 500 })
const user = await registerThrowawayUser()
const address = await createAddress(user.token)
const res = await placeCall(user.token, {
addressId: address.id,
items: [
{ skuId: target.skuId, quantity: 1, slotId: slot.slotId },
{ skuId: other.skuId, quantity: quantityOther, slotId: slot.slotId },
],
couponIds: [c.id],
})
// The discount base stays the targeted ₹100, so the ₹50 flat fully applies.
expect(Number(res.data[0].discountAmount)).toBe(50)
expect(Number(res.data[0].totalAmount)).toBe(100 + 300 * quantityOther - 50)
})
it('UORD-48: a first-order-only coupon works once and is rejected afterwards', async () => { it('UORD-48: a first-order-only coupon works once and is rejected afterwards', async () => {
const fx = await createCatalogOrderFixture({ price: 199 }) const fx = await createCatalogOrderFixture({ price: 199 })
const c = await makeCoupon({ flatDiscount: 20, minOrder: 1, isFirstOrderOnly: true }) const c = await makeCoupon({ flatDiscount: 20, minOrder: 1, isFirstOrderOnly: true })

View file

@ -760,7 +760,6 @@ real.
| CART-63 | edge | flat capped at item total | never below zero | | CART-63 | edge | flat capped at item total | never below zero |
| CART-64 | edge | discount drops total below threshold | delivery fee re-added | | CART-64 | edge | discount drops total below threshold | delivery fee re-added |
| CART-65 | edge | minOrder not met | disabled option with reason; cannot select | | CART-65 | edge | minOrder not met | disabled option with reason; cannot select |
| CART-65B | edge | targeted coupon, target subtotal below minOrder but whole cart above it | option stays enabled; discount lands only on the targeted SKU |
| CART-66 | edge | usage limit reached | disabled option | | CART-66 | edge | usage limit reached | disabled option |
| CART-67 | edge | other-region coupon | disabled reason | | CART-67 | edge | other-region coupon | disabled reason |
| CART-68 | edge | first-order-only coupon and non-first order | disabled reason | | CART-68 | edge | first-order-only coupon and non-first order | disabled reason |

View file

@ -19,7 +19,7 @@ const UpdateChecker: React.FC<ReactParentComponent> = ({ children }) => {
useEffect(() => { useEffect(() => {
// Never nag in development; the dev build talks to a dev backend. // Never nag in development; the dev build talks to a dev backend.
// if (__DEV__) return; if (__DEV__) return;
if (prompted.current) return; if (prompted.current) return;
const remoteVersion = data?.internalAppVersion; const remoteVersion = data?.internalAppVersion;

View file

@ -876,33 +876,6 @@ describe('Cart (scheduled) — CART-01..110', () => {
expect(queryByTestId('coupon-chip-MIN1000')).toBeNull() expect(queryByTestId('coupon-chip-MIN1000')).toBeNull()
}) })
it('CART-65B: a targeted coupon allows minOrder on the whole cart but discounts only its SKU', async () => {
const targeted = {
...C3,
id: 65,
couponCode: 'TGT65',
minOrder: 500,
flatDiscount: 50,
skuIds: [2],
}
const { getByTestId, getByText } = await mount({
// Chicken (targeted) is ₹215, cucumber (other) is ₹300 -> cart ₹515.
lines: [line(1, 2, 1, 1849), line(2, 5, 20, 1849)],
setup: () =>
setProcedure('user.coupon.getEligible', {
data: { data: [targeted], isFirstOrder: true },
}),
})
fireEvent.press(getByTestId('coupon-dropdown'))
await flush(1)
// ₹215 of eligible product is below ₹500, but the cart is ₹515.
expect(getByTestId('coupon-dropdown-option-65')).not.toBeDisabled()
fireEvent.press(getByTestId('coupon-dropdown-option-65'))
await flush(2)
expect(getByTestId('coupon-bill-65')).toBeTruthy()
expect(getByText('-₹50')).toBeTruthy()
})
it('CART-66: a coupon at its usage limit is disabled', async () => { it('CART-66: a coupon at its usage limit is disabled', async () => {
const used = { ...C6, usages: [{ id: 1 }], maxLimitForUser: 1 } const used = { ...C6, usages: [{ id: 1 }], maxLimitForUser: 1 }
const { getByTestId, getByText } = await mount({ const { getByTestId, getByText } = await mount({

View file

@ -30,7 +30,6 @@
"devDependencies": { "devDependencies": {
"@babel/core": "^7.25.2", "@babel/core": "^7.25.2",
"@playwright/test": "^1.63.0", "@playwright/test": "^1.63.0",
"@types/bun": "^1.4.4",
"@types/canvas-confetti": "^1.9.0", "@types/canvas-confetti": "^1.9.0",
"@types/node": "^22.10.2", "@types/node": "^22.10.2",
"@types/react": "~19.0.10", "@types/react": "~19.0.10",
@ -1125,8 +1124,6 @@
"@types/better-sqlite3": ["@types/better-sqlite3@7.6.13", "", { "dependencies": { "@types/node": "*" } }, "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA=="], "@types/better-sqlite3": ["@types/better-sqlite3@7.6.13", "", { "dependencies": { "@types/node": "*" } }, "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA=="],
"@types/bun": ["@types/bun@1.4.4", "", { "dependencies": { "bun-types": "1.4.4" } }, "sha512-9wkRDXUXK124pEnAutE6n/l18j+i9GC5IAHK8TmX/2nlySETmky0OU6yL5U8pW1AoKh++AN9auDCr647BfurjQ=="],
"@types/canvas-confetti": ["@types/canvas-confetti@1.9.0", "", {}, "sha512-aBGj/dULrimR1XDZLtG9JwxX1b4HPRF6CX9Yfwh3NvstZEm1ZL7RBnel4keCPSqs1ANRu1u2Aoz9R+VmtjYuTg=="], "@types/canvas-confetti": ["@types/canvas-confetti@1.9.0", "", {}, "sha512-aBGj/dULrimR1XDZLtG9JwxX1b4HPRF6CX9Yfwh3NvstZEm1ZL7RBnel4keCPSqs1ANRu1u2Aoz9R+VmtjYuTg=="],
"@types/draco3d": ["@types/draco3d@1.4.10", "", {}, "sha512-AX22jp8Y7wwaBgAixaSvkoG4M/+PlAcm3Qs4OW8yT9DM4xUpWKeFhLueTAyZF39pviAdcDdeJoACapiAceqNcw=="], "@types/draco3d": ["@types/draco3d@1.4.10", "", {}, "sha512-AX22jp8Y7wwaBgAixaSvkoG4M/+PlAcm3Qs4OW8yT9DM4xUpWKeFhLueTAyZF39pviAdcDdeJoACapiAceqNcw=="],
@ -1423,8 +1420,6 @@
"buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="], "buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="],
"bun-types": ["bun-types@1.4.4", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-yjrJh5oGX7mMPKGd19YXyIjmEuj4G4zNC30bs7PM9Az7NQ3ndF3j6hbeRdvJTRQEhJ/FYQwW0a2moweEi2hMxQ=="],
"bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="], "bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
"call-bind": ["call-bind@1.0.8", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.0", "es-define-property": "^1.0.0", "get-intrinsic": "^1.2.4", "set-function-length": "^1.2.2" } }, "sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww=="], "call-bind": ["call-bind@1.0.8", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.0", "es-define-property": "^1.0.0", "get-intrinsic": "^1.2.4", "set-function-length": "^1.2.2" } }, "sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww=="],
@ -3413,10 +3408,6 @@
"body-parser/debug": ["debug@2.6.9", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="], "body-parser/debug": ["debug@2.6.9", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="],
"bun-types/@types/node": ["@types/node@24.12.0", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-GYDxsZi3ChgmckRT9HPU0WEhKLP08ev/Yfcq2AstjrDASOYCSXeyjDsHg4v5t4jOj7cyDX3vmprafKlWIG9MXQ=="],
"bun-types/undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
"caller-callsite/callsites": ["callsites@2.0.0", "", {}, "sha512-ksWePWBloaWPxJYQ8TL0JHvtci6G5QTKwQ95RcWAa/lzoAKuAOflGdAK92hpHXjkwb8zLxoLNUoNYZgVsaJzvQ=="], "caller-callsite/callsites": ["callsites@2.0.0", "", {}, "sha512-ksWePWBloaWPxJYQ8TL0JHvtci6G5QTKwQ95RcWAa/lzoAKuAOflGdAK92hpHXjkwb8zLxoLNUoNYZgVsaJzvQ=="],
"chokidar/glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="], "chokidar/glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],

View file

@ -8793,38 +8793,4 @@ typing error (unrelated to this change).
Cause: ProductCard.tsx sets an unused `updater` state every 5000ms; the state Cause: ProductCard.tsx sets an unused `updater` state every 5000ms; the state
value is never read, but it forces every card to re-render forever. value is never read, but it forces every card to re-render forever.
- Me was idle after HMR settled (~2 commits/minute). Home was idle after entry. - Me was idle after HMR settled (~2 commits/minute). Home was idle after entry.
A >15 commits/s during HMR was the only high-frequency window. A >15 commits/s burst during HMR was the only high-frequency window.
[2026-10-23 14:17:42 IST] Coupons: minimum order is the whole cart, discount stays on targeted SKUs.
Planned diffs:
- packages/shared/cart-pricing.ts: add `computeCartSubtotal`; compare
`minOrder` against the full in-stock goods subtotal in
`evaluateCouponEligibility`, while keeping `eligibleSubtotal` (targeted lines)
as the discount base; update the invariant/doc comments.
- packages/db_helper_sqlite/src/user-apis/order.ts: compare `minOrder` against
the full cart subtotal in `validateAndGetCoupons`; update comments.
- apps/user-ui/components/cart-page.tsx / checkout-page.tsx: no logic change —
they call `evaluateCouponEligibility`, so the new rule flows through.
- apps/user-ui/tests/pages/cart.test.tsx: add a regression test (CART-65B) where
the targeted SKU is below minOrder but the whole cart is above it.
- apps/backend/tests/api/user-order-place.test.ts: add UORD-47B covering the same
server-side rule.
- apps/user-ui/JEST-TEST-CASES.md: document CART-65B.
- apps/backend/API-TEST-CASES.md: document UORD-47B.
No migrations run. No test suite run (repo instruction).
Verified: `npx tsc --noEmit` clean in packages/db_helper_sqlite and apps/backend;
`apps/backend/tests/tsconfig.json` clean. `apps/user-ui` typecheck reports only
the two pre-existing `typeof fetch as Mock` errors in addresses/payment tests;
no cart/checkout errors from this change.
[2026-10-23 15:06:49 IST] Test grouped coupon restoration: only after the last sibling is cancelled.
The implementation already does this: `releaseCouponUsageIfGroupFullyCancelled`
deletes the group's `coupon_usage` rows only when every order in `order_group_id`
has `is_cancelled = true`. Existing UORD-108 checks couponCode disappears, but
uses no usage cap and never retries the coupon. Add a stronger regression test:
- apps/backend/tests/api/user-order-lifecycle.test.ts: UORD-108B places a
two-slot group with `maxLimitForUser: 1`; cancelling one sibling must leave the
coupon exhausted for a new order, and cancelling the last sibling must make the
same coupon usable again.
- apps/backend/API-TEST-CASES.md: document UORD-108B.
No production code change. No test suite run (repo instruction).

View file

@ -29,7 +29,6 @@
"devDependencies": { "devDependencies": {
"@babel/core": "^7.25.2", "@babel/core": "^7.25.2",
"@playwright/test": "^1.63.0", "@playwright/test": "^1.63.0",
"@types/bun": "^1.4.4",
"@types/canvas-confetti": "^1.9.0", "@types/canvas-confetti": "^1.9.0",
"@types/node": "^22.10.2", "@types/node": "^22.10.2",
"@types/react": "~19.0.10", "@types/react": "~19.0.10",

View file

@ -25,11 +25,7 @@ import { runBatched } from '../lib/run-batched'
import { attachOrderItems } from '../lib/order-items' import { attachOrderItems } from '../lib/order-items'
import { composeSkuName, composeUnitNotation } from '../lib/sku-features' import { composeSkuName, composeUnitNotation } from '../lib/sku-features'
import { marketStatsForRegion } from '../lib/market-stats' import { marketStatsForRegion } from '../lib/market-stats'
import { import { computeEligibleSubtotal, type CartLine } from '@packages/shared'
computeCartSubtotal,
computeEligibleSubtotal,
type CartLine,
} from '@packages/shared'
export interface OrderWithRelations { export interface OrderWithRelations {
id: number id: number
@ -114,9 +110,8 @@ export interface ValidatedCoupon extends CouponValidationResult {
* - user-based applicability, invalidated, expiry, per-user usage limit * - user-based applicability, invalidated, expiry, per-user usage limit
* - region: a regional coupon is only valid in its own region * - region: a regional coupon is only valid in its own region
* - first-order-only (via countEffectiveOrders) * - first-order-only (via countEffectiveOrders)
* - product targeting: the coupon must match at least one cart line * - product targeting: the coupon must match at least one cart line, and
* - minOrder: compared against the WHOLE cart's goods subtotal (delivery * minOrder is compared against the ELIGIBLE (targeted) subtotal
* excluded), even when the coupon only discounts targeted lines
*/ */
export async function validateAndGetCoupons(params: { export async function validateAndGetCoupons(params: {
couponIds: number[] couponIds: number[]
@ -190,15 +185,13 @@ export async function validateAndGetCoupons(params: {
const eligibleSubtotal = computeEligibleSubtotal(params.items, { const eligibleSubtotal = computeEligibleSubtotal(params.items, {
applicableSkuIds: targets, applicableSkuIds: targets,
}) })
// The minimum is cart-wide; targeting only limits what the discount lands on.
const cartSubtotal = computeCartSubtotal(params.items)
if (targets && eligibleSubtotal <= 0) { if (targets && eligibleSubtotal <= 0) {
throw new Error('Coupon does not apply to any items in your cart') throw new Error('Coupon does not apply to any items in your cart')
} }
if ( if (
coupon.minOrder && coupon.minOrder &&
parseFloat(coupon.minOrder.toString()) > cartSubtotal parseFloat(coupon.minOrder.toString()) > eligibleSubtotal
) { ) {
throw new Error('Order amount does not meet coupon minimum requirement') throw new Error('Order amount does not meet coupon minimum requirement')
} }

View file

@ -7,8 +7,6 @@
* is never part of the base. * is never part of the base.
* - A coupon with no `applicableSkuIds` applies to the whole cart; otherwise it * - A coupon with no `applicableSkuIds` applies to the whole cart; otherwise it
* only discounts the line items whose skuId is in the target set. * 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 * - Multiple coupons apply SEQUENTIALLY, in the order they are given (the user's
* selection order): the first coupon discounts the subtotal, the second discounts * 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 * whatever is left, and so on. Each coupon's discount is rounded to the nearest
@ -87,11 +85,6 @@ export function lineEligibleForCoupon(
return (coupon.applicableSkuIds as number[]).includes(skuId) 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). */ /** Sum of the line items this coupon discounts (whole cart when untargeted). */
export function computeEligibleSubtotal( export function computeEligibleSubtotal(
items: CartLine[], items: CartLine[],
@ -159,10 +152,7 @@ export interface CouponEligibilityFields {
} }
export interface CouponEligibilityContext { export interface CouponEligibilityContext {
/** /** in-stock cart lines — exactly what the coupon would discount */
* in-stock cart lines — the targeted ones form the discount base; all of them
* form the minOrder base
*/
cartLines: CartLine[] cartLines: CartLine[]
/** the region the cart is being built in */ /** the region the cart is being built in */
regionId: number | null regionId: number | null
@ -182,10 +172,9 @@ export interface CouponEligibility {
* Whether a coupon can be applied to this cart, and why not when it can't. * 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 * Rule order matches the backend: region, then first-order-only, then product
* targeting, then minOrder — targeting BEFORE minOrder, because a coupon whose * targeting, then minOrder — targeting BEFORE minOrder, because a coupon whose
* targets are all missing must report "no applicable items" instead of a * targets are all missing has an eligible subtotal of 0 and "add ₹X more" would
* misleading "add ₹X more". minOrder is compared against the WHOLE cart's goods * be the wrong reason (the server reports "does not apply to any items").
* subtotal (delivery excluded), exactly as the server does; `eligibleSubtotal` * minOrder is compared against the ELIGIBLE subtotal, exactly as the server does.
* remains the targeted-line base the discount is calculated on.
*/ */
export function evaluateCouponEligibility( export function evaluateCouponEligibility(
coupon: CouponEligibilityFields, coupon: CouponEligibilityFields,
@ -220,10 +209,9 @@ export function evaluateCouponEligibility(
return fail('No applicable items in your cart') return fail('No applicable items in your cart')
} }
const cartSubtotal = computeCartSubtotal(context.cartLines)
const minOrder = toNum(coupon.minOrder) const minOrder = toNum(coupon.minOrder)
if (minOrder > cartSubtotal) { if (minOrder > eligibleSubtotal) {
return fail(`Add ₹${Math.ceil(minOrder - cartSubtotal)} more to use this coupon`) return fail(`Add ₹${Math.ceil(minOrder - eligibleSubtotal)} more to use this coupon`)
} }
return { isEligible: true, eligibleSubtotal } return { isEligible: true, eligibleSubtotal }