From 7ab2d715691687c4be4463bf208c10a787f10872 Mon Sep 17 00:00:00 2001 From: shafi54 <108669266+shafi-aviz@users.noreply.github.com> Date: Sat, 17 Oct 2026 10:32:15 +0530 Subject: [PATCH] enh --- apps/user-ui/components/cart-page.tsx | 116 +++++++----- apps/user-ui/components/checkout-page.tsx | 170 ++++++++++++----- .../src/components/CouponBreakdownDialog.tsx | 127 +++++++++++++ .../tests/screens/cart-coupons.test.tsx | 102 ++++++++-- .../tests/screens/checkout-coupons.test.tsx | 40 ++++ change-log.txt | 123 ++++++++++++ packages/shared/cart-pricing.ts | 176 ++++++++++++++++-- 7 files changed, 738 insertions(+), 116 deletions(-) create mode 100644 apps/user-ui/src/components/CouponBreakdownDialog.tsx diff --git a/apps/user-ui/components/cart-page.tsx b/apps/user-ui/components/cart-page.tsx index 95cb783..8f6b785 100644 --- a/apps/user-ui/components/cart-page.tsx +++ b/apps/user-ui/components/cart-page.tsx @@ -31,12 +31,13 @@ import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-q import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks'; import { useRegion } from '@/src/hooks/useRegion'; import CheckoutAddressSelector from '@/components/CheckoutAddressSelector'; +import CouponBreakdownDialog from '@/src/components/CouponBreakdownDialog'; import LoginWall from '@/components/LoginWall'; import CartAddressGate from '@/components/CartAddressGate'; import { useAddressStore } from '@/src/store/addressStore'; import { useCheckoutStore } from '@/src/store/checkoutStore'; import type { FlashDeliveryProps } from '@packages/shared'; -import { computeCouponStack, computeEligibleSubtotal, type CartLine } from '@packages/shared'; +import { computeCouponStack, computeCouponLineBreakdowns, evaluateCouponEligibility, type CartLine, type CouponLineBreakdown } from '@packages/shared'; const formatDeliverySlot = (deliveryTime: string): string => { const time = dayjs(deliveryTime); @@ -353,19 +354,6 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps ); }, [products, productSlotsMap]); - // Base total price without discounts for coupon eligibility check - const baseTotalPrice = useMemo( - () => - cartItems - .filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock) - .reduce((sum, item) => { - const product = productsById[item.skuId]; - const price = product?.price || 0; - return sum + price * (quantities[item.id] || item.quantity); - }, 0), - [cartItems, quantities, productsById] - ); - // Cart lines (in-stock only) with their effective unit price, in the shared // shape the coupon helpers expect. Declared before the coupon list so coupon // targeting can be evaluated against the cart. @@ -389,7 +377,10 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps // Every coupon we're allowed to surface (the API already drops expired, // invalidated, usage-limit-exceeded and other users' personal coupons). - // Ineligible ones are kept but flagged with the reason, and sorted to the end. + // Whether each one applies to THIS cart is decided locally — the shared + // resolver, the same rules the backend applies at placeOrder — so changing the + // cart never has to ask the server again. Ineligible ones are kept, flagged with + // the reason, and sorted to the end. const eligibleCoupons = useMemo(() => { if (!couponsRaw?.data) return []; const isFirstOrder = couponsRaw.isFirstOrder ?? true; @@ -398,20 +389,17 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps // Target SKUs live on the coupon row itself (empty => whole cart). const applicableSkuIds = Array.isArray(coupon.skuIds) ? (coupon.skuIds as number[]) : []; - let reason: string | undefined; - if (coupon.regionId != null && regionId != null && coupon.regionId !== regionId) { - reason = "Not valid in your region"; - } else if (coupon.isFirstOrderOnly && !isFirstOrder) { - reason = "Valid on your first order only"; - } else if (coupon.minOrder && parseFloat(coupon.minOrder) > baseTotalPrice) { - const shortfall = Math.ceil(parseFloat(coupon.minOrder) - baseTotalPrice); - reason = `Add ₹${shortfall} more to use this coupon`; - } else if ( - applicableSkuIds.length > 0 && - computeEligibleSubtotal(cartLines, { applicableSkuIds }) <= 0 - ) { - reason = "No applicable items in your cart"; - } + const { isEligible, reason: ineligibilityReason } = evaluateCouponEligibility( + { + regionId: coupon.regionId, + isFirstOrderOnly: coupon.isFirstOrderOnly, + minOrder: coupon.minOrder, + maxLimitForUser: coupon.maxLimitForUser, + usages: coupon.usages, + applicableSkuIds, + }, + { cartLines, regionId, isFirstOrder } + ); return { id: coupon.id, @@ -428,14 +416,14 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps discountPercent: coupon.discountPercent, flatDiscount: coupon.flatDiscount, applicableSkuIds, - isEligible: !reason, - ineligibilityReason: reason, + isEligible, + ineligibilityReason, }; }); // Applicable coupons first, disabled ones at the end (stable within groups). return mapped.sort((a, b) => Number(b.isEligible) - Number(a.isEligible)); - }, [couponsRaw, baseTotalPrice, cartLines, regionId]); + }, [couponsRaw, cartLines, regionId]); const updateCartItem = useUpdateCartItem({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true }, cartType); const removeFromCart = useRemoveFromCart({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true }, cartType); @@ -451,6 +439,9 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps const [selectedSlots, setSelectedSlots] = useState>({}); const [selectedCouponIds, setSelectedCouponIds] = useState([]); const [couponDialogOpen, setCouponDialogOpen] = useState(false); + // Coupon whose per-product discount split is open (only product-specific ones + // have an "i" in the bill). + const [breakdownCouponId, setBreakdownCouponId] = useState(null); const router = useRouter(); @@ -609,6 +600,24 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps [couponDiscounts] ); + // Where each applied coupon's discount landed, per cart line — the bill's "i" + // popup for product-specific coupons. Totals come from the same waterfall as the + // bill's own figures, so the popup's rows always add up to the coupon's line. + const couponBreakdowns = useMemo(() => { + const byId = new Map(); + computeCouponLineBreakdowns(cartLines, selectedCoupons).forEach((entry) => { + byId.set(entry.couponId, entry); + }); + return byId; + }, [cartLines, selectedCoupons]); + + // Cart lines by SKU, for the popup's quantity × price line. + // The coupon whose per-product split is open, if it is still applied. + const breakdownCoupon = + breakdownCouponId != null ? couponById.get(breakdownCouponId) : undefined; + const breakdown = + breakdownCouponId != null ? couponBreakdowns.get(breakdownCouponId) : undefined; + const finalTotal = totalPrice - discountAmount; const deliveryCharge = useMemo( @@ -1465,16 +1474,31 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps key={coupon.id} style={tw`flex-row justify-between items-center mb-3`} > - setCouponDialogOpen(true)} - activeOpacity={0.7} - > - - - {coupon.code} - - + + setCouponDialogOpen(true)} + activeOpacity={0.7} + > + + + {coupon.code} + + + {/* Product-specific coupon: how much came off each product. A + sibling of the row above, so it cannot open the applied- + coupons dialog by accident. */} + {coupon.applicableSkuIds.length > 0 && ( + setBreakdownCouponId(coupon.id)} + style={tw`p-1 ml-0.5`} + activeOpacity={0.7} + > + + + )} + -₹{Math.trunc(couponDiscounts[coupon.id] || 0)} @@ -1645,6 +1669,14 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps + {/* Per-product discount split of one applied coupon (the bill's "i") */} + setBreakdownCouponId(null)} + /> + {/* Coupon Details Dialog */} = ({ isFlashDelivery = false }) => { const params = useLocalSearchParams(); @@ -58,6 +59,8 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) const { selectedAddressId } = useAddressStore(); const [selectedCouponIds, setSelectedCouponIds] = useState([]); + // Coupon whose per-product discount split is open (product-specific coupons only). + const [breakdownCouponId, setBreakdownCouponId] = useState(null); @@ -170,36 +173,61 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) { enabled: isAuthenticated } ); - const eligibleCoupons = useMemo(() => { - if (!couponsRaw?.data) return []; - return couponsRaw.data.map(coupon => { - let isEligible = true; - let ineligibilityReason = ''; - if (coupon.maxLimitForUser && coupon.usages.length >= coupon.maxLimitForUser) { - isEligible = false; - ineligibilityReason = 'Usage limit exceeded'; - } - if (coupon.minOrder && parseFloat(coupon.minOrder) > totalPrice) { - isEligible = false; - ineligibilityReason = `Min order ₹${coupon.minOrder}`; - } - return { - id: coupon.id, - code: coupon.couponCode, - discountType: coupon.discountPercent ? 'percentage' : 'flat', - discountValue: parseFloat(coupon.discountPercent || coupon.flatDiscount || '0'), - maxValue: coupon.maxValue ? parseFloat(coupon.maxValue) : undefined, - minOrder: coupon.minOrder ? parseFloat(coupon.minOrder) : undefined, - description: '', - exclusiveApply: coupon.exclusiveApply, - discountPercent: coupon.discountPercent, - flatDiscount: coupon.flatDiscount, - applicableSkuIds: Array.isArray(coupon.skuIds) ? (coupon.skuIds as number[]) : [], - isEligible, - ineligibilityReason: isEligible ? undefined : ineligibilityReason, - }; - }).filter(coupon => coupon.ineligibilityReason !== 'Usage limit exceeded'); - }, [couponsRaw, totalPrice]); + // Lines being ordered, with their effective unit price, for the shared helpers. + // Declared before the coupon list so eligibility can be evaluated locally. + const cartLines = useMemo( + () => + selectedItems + .filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock) + .map((item) => { + const product = productsById[item.skuId]; + const unitPrice = isFlashDelivery + ? (product?.flashPrice ?? product?.price ?? 0) + : (product?.price || 0); + return { skuId: item.skuId, quantity: item.quantity, unitPrice: Number(unitPrice) }; + }), + [selectedItems, productSlotsMap, productsById, isFlashDelivery] + ); + + // Same local rules as the cart screen (and the backend's placeOrder checks), so + // a coupon that was applied in the cart can never be silently carried into the + // order: it is either still valid here, or it is listed below with its reason. + const eligibleCoupons = useMemo(() => { + if (!couponsRaw?.data) return []; + const isFirstOrder = couponsRaw.isFirstOrder ?? true; + + return couponsRaw.data.map(coupon => { + const applicableSkuIds = Array.isArray(coupon.skuIds) ? (coupon.skuIds as number[]) : []; + + const { isEligible, reason: ineligibilityReason } = evaluateCouponEligibility( + { + regionId: coupon.regionId, + isFirstOrderOnly: coupon.isFirstOrderOnly, + minOrder: coupon.minOrder, + maxLimitForUser: coupon.maxLimitForUser, + usages: coupon.usages, + applicableSkuIds, + }, + { cartLines, regionId, isFirstOrder } + ); + + return { + id: coupon.id, + code: coupon.couponCode, + discountType: coupon.discountPercent ? 'percentage' : 'flat', + discountValue: parseFloat(coupon.discountPercent || coupon.flatDiscount || '0'), + maxValue: coupon.maxValue ? parseFloat(coupon.maxValue) : undefined, + minOrder: coupon.minOrder ? parseFloat(coupon.minOrder) : undefined, + description: '', + exclusiveApply: coupon.exclusiveApply, + discountPercent: coupon.discountPercent, + flatDiscount: coupon.flatDiscount, + applicableSkuIds, + isEligible, + ineligibilityReason, + }; + }); + }, [couponsRaw, cartLines, regionId]); // Coupons applied, kept in the order the user selected them: coupons stack // sequentially, so the order changes the result. @@ -216,19 +244,14 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) [selectedCouponIds, couponById] ); - // Lines being ordered, with their effective unit price, for the shared helpers. - const cartLines = useMemo( + // Coupons the customer picked in the cart that no longer apply to this order — + // shown, not silently dropped. + const droppedCoupons = useMemo( () => - selectedItems - .filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock) - .map((item) => { - const product = productsById[item.skuId]; - const unitPrice = isFlashDelivery - ? (product?.flashPrice ?? product?.price ?? 0) - : (product?.price || 0); - return { skuId: item.skuId, quantity: item.quantity, unitPrice: Number(unitPrice) }; - }), - [selectedItems, productSlotsMap, productsById, isFlashDelivery] + selectedCouponIds + .map((id) => couponById.get(id)) + .filter((coupon): coupon is NonNullable => !!coupon && !coupon.isEligible), + [selectedCouponIds, couponById] ); const discountAmount = useMemo( @@ -236,6 +259,22 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) [selectedCoupons, cartLines] ); + // Where each applied coupon's discount landed, per cart line — the "i" next to a + // product-specific coupon. Same waterfall as the discount above, so the popup's + // rows always add up to what this page charges. + const couponBreakdowns = useMemo(() => { + const byId = new Map(); + computeCouponLineBreakdowns(cartLines, selectedCoupons).forEach((entry) => { + byId.set(entry.couponId, entry); + }); + return byId; + }, [cartLines, selectedCoupons]); + + const breakdownCoupon = + breakdownCouponId != null ? couponById.get(breakdownCouponId) : undefined; + const breakdown = + breakdownCouponId != null ? couponBreakdowns.get(breakdownCouponId) : undefined; + const finalTotal = totalPrice - discountAmount; const deliveryCharge = useMemo(() => { @@ -360,12 +399,25 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) {/* Coupon */} - {selectedCoupons.length > 0 && ( + {(selectedCoupons.length > 0 || droppedCoupons.length > 0) && ( Coupon {selectedCoupons.map((coupon) => ( - {coupon.code} + + {coupon.code} + {/* Product-specific coupon: the per-product split behind it. */} + {coupon.applicableSkuIds.length > 0 && ( + setBreakdownCouponId(coupon.id)} + style={tw`p-1 ml-0.5`} + activeOpacity={0.7} + > + + + )} + {coupon.discountType === 'percentage' ? `${coupon.discountValue}% off` @@ -373,15 +425,34 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) ))} + {/* Picked in the cart but no longer applicable to this order — shown with + the reason instead of vanishing (the cart has the full picker). */} + {droppedCoupons.map((coupon) => ( + + + + {coupon.code} + + Not applied + + {!!coupon.ineligibilityReason && ( + + {coupon.ineligibilityReason} + + )} + + ))} )} + {/* Only the coupons that survived the local check: the ids sent to + placeOrder are the ids the discount above is computed from. */} coupon.id)} cartItems={selectedItems} totalPrice={totalPrice} totalSavings={totalSavings} @@ -395,6 +466,13 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) /> + {/* Per-product discount split of one applied coupon (the coupon block's "i") */} + setBreakdownCouponId(null)} + /> ); }; diff --git a/apps/user-ui/src/components/CouponBreakdownDialog.tsx b/apps/user-ui/src/components/CouponBreakdownDialog.tsx new file mode 100644 index 0000000..7c387a3 --- /dev/null +++ b/apps/user-ui/src/components/CouponBreakdownDialog.tsx @@ -0,0 +1,127 @@ +import React, { useMemo } from 'react'; +import { Image, View } from 'react-native'; +import { tw, BottomDialog, MyText, MyTouchableOpacity } from 'common-ui'; +import MaterialIcons from '@expo/vector-icons/MaterialIcons'; +import { useCentralProductStore } from '@/src/store/centralProductStore'; +import type { CartLine, CouponLineBreakdown } from '@packages/shared'; + +interface CouponBreakdownDialogProps { + /** The applied coupon whose split is shown; null keeps the dialog closed. */ + coupon: { id: number; code: string } | null; + /** Its per-line discount split (from computeCouponLineBreakdowns). */ + breakdown: CouponLineBreakdown | null; + /** The cart lines the order is priced from, for the qty × price line. */ + cartLines: CartLine[]; + onClose: () => void; +} + +/** + * Where a product-specific coupon's discount landed, product by product — the + * dialog behind the "i" next to an applied coupon (cart bill and checkout coupon + * block). The rows come from `computeCouponLineBreakdowns`, the same waterfall the + * bill uses, and they are reconciled to whole rupees, so they always add up to the + * coupon's total shown here and on the bill. + * + * Note: this must be opened from an inline row, never from inside another dialog — + * a BottomDialog is a native Modal and must not be nested. + */ +const CouponBreakdownDialog: React.FC = ({ + coupon, + breakdown, + cartLines, + onClose, +}) => { + const productsById = useCentralProductStore((state) => state.productsById); + + const cartLineBySkuId = useMemo( + () => new Map(cartLines.map((line) => [line.skuId, line])), + [cartLines] + ); + + // Only the lines the money actually landed on, biggest first. + const rows = useMemo( + () => + (breakdown?.lines ?? []) + .filter((line) => line.discount > 0) + .sort((a, b) => b.discount - a.discount), + [breakdown] + ); + + return ( + + + + + + Product discount + + + {coupon?.code} · applied to specific products + + + + + + + + {rows.length === 0 ? ( + + No per-product split to show for this order. + + ) : ( + rows.map((row) => { + const product = productsById[row.skuId]; + const line = cartLineBySkuId.get(row.skuId); + return ( + + + + + {product?.name || `Product #${row.skuId}`} + + {!!line && ( + + {line.quantity} × ₹{Math.trunc(line.unitPrice)} + + )} + + + −₹{row.discount} + + + ); + }) + )} + + + + Total from this coupon + + + −₹{Math.trunc(breakdown?.discount ?? 0)} + + + + Applies to the listed products only — the rest of the cart is not + discounted by this coupon. + + + + Close + + + + ); +}; + +export default CouponBreakdownDialog; diff --git a/apps/user-ui/tests/screens/cart-coupons.test.tsx b/apps/user-ui/tests/screens/cart-coupons.test.tsx index 7bb749d..6e443d2 100644 --- a/apps/user-ui/tests/screens/cart-coupons.test.tsx +++ b/apps/user-ui/tests/screens/cart-coupons.test.tsx @@ -50,27 +50,40 @@ const coupon = (over: Record = {}) => ({ ...over, }) -/** Mount the cart with one line (2 x 215) and the given eligible coupons. */ -async function mountCart(coupons: unknown[]) { +const SECOND_SKU_ID = 4 // Mutton, price 839 + +/** Mount the cart with one line (2 x 215), optionally a second (1 x 839). */ +async function mountCart(coupons: unknown[], withSecondLine = false) { setupApiMocks({ procedures: { - 'user.cart.getCartSlots': { [PRODUCT_ID]: [futureSlot()] }, + 'user.cart.getCartSlots': { + [PRODUCT_ID]: [futureSlot()], + ...(withSecondLine ? { [SECOND_SKU_ID]: [futureSlot()] } : {}), + }, 'user.coupon.getEligible': { data: coupons }, }, }) - await StorageServiceCasual.setItem( - 'cart_items', - JSON.stringify([ - { - id: 1, - skuId: PRODUCT_ID, - quantity: 2, - slotId: SLOT_ID, - addedAt: new Date().toISOString(), - }, - ]) - ) + const lines = [ + { + id: 1, + skuId: PRODUCT_ID, + quantity: 2, + slotId: SLOT_ID, + addedAt: new Date().toISOString(), + }, + ] + if (withSecondLine) { + lines.push({ + id: 2, + skuId: SECOND_SKU_ID, + quantity: 1, + slotId: SLOT_ID, + addedAt: new Date().toISOString(), + }) + } + + await StorageServiceCasual.setItem('cart_items', JSON.stringify(lines)) renderWithProviders() await waitFor(() => expect(screen.getByText('Chicken Breast 500 g')).toBeVisible()) @@ -245,6 +258,65 @@ describe('Cart coupon application', () => { expect(screen.queryByTestId(`coupon-dropdown-option-${COUPON_ID}-detail-list`)).toBeNull() }) + it('measures minOrder on the coupon-targeted items, not the whole cart', async () => { + // Cart = 430 (2 x 215) + 839 (1 x Mutton) = 1269. The coupon only targets the + // 430 line and needs 500: measured against the whole cart it would look + // eligible, which is exactly what the backend refuses at placeOrder. + await mountCart([coupon({ discountPercent: '10', skuIds: [PRODUCT_ID], minOrder: '500' })], true) + + fireEvent.press(screen.getByText('Select a coupon')) + + await waitFor(() => + expect(screen.getAllByText(/Add ₹70 more to use this coupon/).length).toBeGreaterThan(0) + ) + }) + + it('reports missing targets ahead of minOrder', async () => { + // Target set matches nothing in the cart and minOrder is above the whole cart: + // "no applicable items" is the truthful reason, not "add ₹N more". + await mountCart([coupon({ discountPercent: '10', skuIds: [999999], minOrder: '2000' })], true) + + fireEvent.press(screen.getByText('Select a coupon')) + + await waitFor(() => + expect(screen.getAllByText(/No applicable items in your cart/).length).toBeGreaterThan(0) + ) + expect(screen.queryByText(/Add ₹/)).toBeNull() + }) + + it('shows a per-product breakdown for a product-specific coupon', async () => { + // 2 x 215 (targeted) + 1 x 839 (Mutton, not targeted): the coupon is 10% of the + // 430 targeted line only, so its whole discount lands on product 2. + await mountCart([coupon({ discountPercent: '10', skuIds: [PRODUCT_ID] })], true) + + await selectCoupon() + // The bill line for the coupon: 10% of 430. + expect(screen.getByText('-₹43')).toBeVisible() + + fireEvent.press(screen.getByTestId(`coupon-breakdown-${COUPON_ID}`)) + + expect(screen.getByTestId('coupon-breakdown-dialog')).toBeVisible() + expect(screen.getByText('Product discount')).toBeVisible() + // Only the targeted product gets a row… + expect(screen.getByTestId(`coupon-breakdown-row-${PRODUCT_ID}`)).toBeVisible() + expect(screen.queryByTestId(`coupon-breakdown-row-${SECOND_SKU_ID}`)).toBeNull() + // …and its share is the coupon's whole discount, shown twice: the row and the + // "total from this coupon" line below it. + expect(screen.getAllByText('−₹43').length).toBe(2) + + fireEvent.press(screen.getByText('Close')) + expect(screen.queryByTestId('coupon-breakdown-dialog')).toBeNull() + }) + + it('offers no breakdown for a coupon that applies to the whole cart', async () => { + await mountCart([coupon({ discountPercent: '10' })], true) + + await selectCoupon() + + expect(screen.getByTestId(`coupon-chip-SAVE10`)).toBeVisible() + expect(screen.queryByTestId(`coupon-breakdown-${COUPON_ID}`)).toBeNull() + }) + it('hides a coupon that has hit its per-user usage limit', async () => { await mountCart([ coupon({ discountPercent: '10', maxLimitForUser: 1, usages: [{ id: 1 }] }), diff --git a/apps/user-ui/tests/screens/checkout-coupons.test.tsx b/apps/user-ui/tests/screens/checkout-coupons.test.tsx index 2f4b1a9..8f6c476 100644 --- a/apps/user-ui/tests/screens/checkout-coupons.test.tsx +++ b/apps/user-ui/tests/screens/checkout-coupons.test.tsx @@ -187,6 +187,46 @@ describe('Checkout coupon discount calculation', () => { expect(screen.getByText('Free')).toBeVisible() }) + it('does not apply or send a coupon whose targets are gone from the order', async () => { + // Picked in the cart (?coupons=77) but its target SKU is not in this order: + // the old code showed it as applied and still sent the id, which placeOrder + // rejects. It is now shown as not applied, with the reason, and dropped. + const api = await mountCheckout([coupon({ discountPercent: '10', skuIds: [999999] })]) + + expect(screen.queryByText('Product Discount')).toBeNull() + expect(screen.getByText('Not applied')).toBeVisible() + expect(screen.getByText('No applicable items in your cart')).toBeVisible() + expect(screen.getAllByText(`₹${TOTAL}`).length).toBeGreaterThan(0) + + fireEvent.press(screen.getByTestId('place-order-button')) + + await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.order.placeOrder')) + expect(lastProcedureInput(api.fetchMock, 'user.order.placeOrder')).toMatchObject({ + couponIds: undefined, + }) + }) + + it('shows the per-product split for an applied product-specific coupon', async () => { + // 2 x 215, coupon targets product 2 only: the whole 10% (43) lands on it. + await mountCheckout([coupon({ discountPercent: '10', skuIds: [PRODUCT_ID] })]) + + expect(screen.getByText('-₹43')).toBeVisible() + // The "i" only exists for product-specific coupons. + fireEvent.press(screen.getByTestId(`coupon-breakdown-${COUPON_ID}`)) + + expect(screen.getByTestId('coupon-breakdown-dialog')).toBeVisible() + expect(screen.getByTestId(`coupon-breakdown-row-${PRODUCT_ID}`)).toBeVisible() + // Row plus the "Total from this coupon" line. + expect(screen.getAllByText('−₹43').length).toBe(2) + }) + + it('offers no per-product split for a whole-cart coupon', async () => { + await mountCheckout([coupon({ discountPercent: '10' })]) + + expect(screen.getByText('-₹43')).toBeVisible() + expect(screen.queryByTestId(`coupon-breakdown-${COUPON_ID}`)).toBeNull() + }) + it('sends the selected coupon id with the order', async () => { const api = await mountCheckout([coupon({ discountPercent: '10' })]) diff --git a/change-log.txt b/change-log.txt index 90b5fff..583ff3b 100644 --- a/change-log.txt +++ b/change-log.txt @@ -5380,3 +5380,126 @@ user-ui Verified statically in node_modules/twrnc/dist/esm/resolve/flex.js: `flex-1` -> {flexGrow: 1, flexBasis: '0%'} (no flexShrink), which is exactly the collapse the earlier sheet work hit. apps/user-ui typechecks clean. + +2026-10-17 12:20:41 shared + user-ui: one local coupon-eligibility rule set for cart and checkout. + + Context (user): "previously our api endpoint returned only eligible coupons. On every product change + we needed to call backend because eligibility changed. Now that we return all eligible ones. We don't + need to keep calling again. Just locally compute and enable/disable coupons." + + Verified before changing anything: the endpoint already returns every coupon the customer may see + (apps/backend/src/trpc/apis/user-apis/apis/coupon.ts:36-64 - its own comment says region / first-order + / usage / min-order ineligibility is deliberately NOT filtered, "the client shows those coupons + disabled with a reason"), both readers send only { regionId } (cart-page.tsx:334, + checkout-page.tsx:168), so no cart change ever refetches them; the only invalidation is after + redeeming a code (me/coupons/index.tsx:140). So no backend change is needed - the gap was that the + LOCAL rules were duplicated and incomplete on checkout. + + packages/shared/cart-pricing.ts + + CouponEligibilityFields / CouponEligibilityContext / CouponEligibility + + evaluateCouponEligibility(coupon, { cartLines, regionId, isFirstOrder }) + Rules in the server's order (validateAndGetCoupons): region -> first-order-only -> + targeted-with-no-eligible-line -> minOrder vs the ELIGIBLE subtotal. Targeting is checked BEFORE + minOrder on purpose: with no eligible line the subtotal is 0 and "Add Rs X more" would be a lie. + apps/user-ui/components/cart-page.tsx + ~ eligibleCoupons now calls the shared resolver (same strings as before); baseTotalPrice memo, + which existed only for the old whole-cart minOrder check, is deleted. + BEHAVIOUR CHANGE (agreed): minOrder is measured against the eligible (targeted) subtotal, not the + whole cart, so the cart now agrees with the backend for product-specific coupons. + apps/user-ui/components/checkout-page.tsx + + cartLines memo MOVED above the coupon block (the resolver needs it; same move cart-page made). + ~ eligibility mapped through the shared resolver: adds the region, first-order and product-target + checks the checkout page was missing, and drops its ad-hoc 'Usage limit exceeded' filter (the + server never returns used-up coupons). + + dropped coupons are no longer silent: they are listed under the applied ones with their reason. + ~ selectedCouponIds passed to PaymentAndOrderComponent is now the LOCALLY ELIGIBLE set + (selectedCoupons.map(c => c.id)) instead of the raw URL list, so the ids sent to placeOrder match + the discount shown on screen. + +2026-10-17 12:41:09 Correction/extension to 12:20:41 - the resolver also carries the usage limit. + + The checkout test "Usage-limit coupons are filtered out of the eligible list entirely" pins that a + coupon with maxLimitForUser reached is not applied. The endpoint already filters those out, but the + client check is worth keeping: a coupon used within the session can still sit in the CACHED list, and + without the local rule the customer would only find out at placeOrder ("Coupon usage limit exceeded"). + + packages/shared/cart-pricing.ts + + CouponEligibilityFields.maxLimitForUser / usages, and a 'Usage limit exceeded' rule placed FIRST + (the backend's order in validateAndGetCoupons is usage-limit -> region -> first-order -> targeting + -> minOrder). + apps/user-ui/components/{cart-page,checkout-page}.tsx: pass maxLimitForUser/usages through. + + Tests (written, NOT run - no suite runs unless asked): + apps/user-ui/tests/screens/cart-coupons.test.tsx + ~ mountCart(coupons, withSecondLine?) - can seed 2 x 215 + 1 x 839 now + + 'measures minOrder on the coupon-targeted items, not the whole cart': targets only the 430 + line, minOrder 500 => "Add Rs 70 more" (against the whole cart it would look eligible) + + 'reports missing targets ahead of minOrder': target 999999 + minOrder 2000 => "No applicable + items in your cart", not "Add Rs N more" + apps/user-ui/tests/screens/checkout-coupons.test.tsx + + 'does not apply or send a coupon whose targets are gone from the order': shown as "Not applied" + with the reason, discount untouched, and couponIds: undefined in the placeOrder input. + Typecheck: user-ui, admin-ui, web-ui, fallback-ui, db_helper_sqlite, backend - all clean. + +2026-10-17 13:02:58 user-ui + shared: per-product discount breakdown for product-specific coupons in the bill. + + Request: "in the billing section, if there is a product specific coupon applied, show an i symbol + beside it. On clicking it, open a bottom dialog and then show the per product discount applied there." + + The per-line split did not exist: runStack() computed a per-line `portion` but only kept it grouped + into shareByGroup (sub-orders), which is what computeCartPricing needs. So: + + packages/shared/cart-pricing.ts + + StackCouponResult.shareByLine (Map) - additive, the existing consumer + (computeCartPricing -> shareByGroup) is untouched. + + roundSharesOnto(rawShares, total) - extracted from computeCartPricing's inline + scale/round/fold-drift block; computeCartPricing now calls it, same behaviour. + + computeCouponLineBreakdowns(lines, coupons): CouponLineBreakdown[] = + { couponId, discount, lines: [{ skuId, discount }] } - same sequential waterfall as + computeCouponStack, and each coupon's per-line shares are reconciled onto its rounded discount, + so the popup's rows sum exactly to the figure on the bill. + apps/user-ui/components/cart-page.tsx + + state breakdownCouponId; memos couponBreakdowns (by coupon id), cartLineBySkuId, breakdownRows + (only non-zero lines, biggest first). + ~ bill row: the coupon code keeps opening "Applied Coupons", and a SIBLING info-outline button + (testID coupon-breakdown-) is rendered only when applicableSkuIds.length > 0. + + BottomDialog (no nesting — a sibling dialog, like the others on this screen) with + testID coupon-breakdown-dialog: one row per discounted product (image, name, qty x unit price, + its share), a "Total from this coupon" line and a note that the rest of the cart is not + discounted. Closes if the coupon stops being applied. + + Maths verified by running the shared module directly (npx tsx, not the test suite): + 10% whole cart on 430+839 -> coupon 127, rows 43 + 84 = 127 OK + 10% targeted at sku 2 -> coupon 43, rows 43 OK (one row) + 10% then flat 50 -> 127 (43+84) and 50 (17+33) OK (waterfall preserved) + 10% whole + 20% on sku 4 -> 127 (43+84) and 151 (single row) OK + maxValue 50 on 10% -> 50 (17+33) OK + 3 lines, 10% / 33% -> 30 / 99, rows sum OK (rounding drift folded into the largest share) + Tests added (written, NOT run): cart-coupons.test.tsx - per-product breakdown opens with only the + targeted product's row and a total matching the bill line; a whole-cart coupon shows no info button. + Typecheck: user-ui, admin-ui, web-ui, fallback-ui, db_helper_sqlite, backend - all clean. + +2026-10-17 13:21:33 user-ui: the per-product breakdown is now on checkout's coupon block too, and shared. + + Request: "show in the coupon block too, if applied". + + apps/user-ui/src/components/CouponBreakdownDialog.tsx (NEW) + + The dialog extracted from cart-page: props { coupon, breakdown, cartLines, onClose }, reads + productsById from the store itself, and keeps the same testIDs (coupon-breakdown-dialog, + coupon-breakdown-row-). One implementation -> both screens' numbers and wording cannot + drift. Its comment records that it must be opened from an inline row, never from inside another + dialog (a BottomDialog is a native Modal; nesting is what we avoid elsewhere). + apps/user-ui/components/cart-page.tsx + ~ the inline dialog (and its cartLineBySkuId / breakdownRows memos, now inside the component) is + replaced by ; keeps breakdownCoupon/breakdown + couponBreakdowns. + Deliberately NOT added inside the cart's "Applied Coupons" dialog: that is already a dialog, so an + "i" there would mean nesting one BottomDialog in another. + apps/user-ui/components/checkout-page.tsx + + couponBreakdowns memo (computeCouponLineBreakdowns over its own cartLines/selectedCoupons), + breakdownCouponId state, and breakdownCoupon/breakdown lookups. + + the "i" (testID coupon-breakdown-) beside each APPLIED coupon that has applicableSkuIds, in + the same row as the code; the dropped ones keep their "Not applied" + reason row and get no "i". + + next to the other dialogs. + Tests (written, NOT run): checkout-coupons.test.tsx - the split opens for a product-specific applied + coupon (row + total = the coupon's discount) and a whole-cart coupon shows no "i". + Typecheck: user-ui, admin-ui, web-ui, fallback-ui, db_helper_sqlite, backend - all clean. diff --git a/packages/shared/cart-pricing.ts b/packages/shared/cart-pricing.ts index af0cc26..5cb6c92 100644 --- a/packages/shared/cart-pricing.ts +++ b/packages/shared/cart-pricing.ts @@ -128,11 +128,102 @@ 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 — exactly what the coupon would discount */ + 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 has an eligible subtotal of 0 and "add ₹X more" would + * be the wrong reason (the server reports "does not apply to any items"). + * minOrder is compared against the ELIGIBLE subtotal, exactly as the server does. + */ +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 minOrder = toNum(coupon.minOrder) + if (minOrder > eligibleSubtotal) { + return fail(`Add ₹${Math.ceil(minOrder - eligibleSubtotal)} 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 + /** the same money, keyed by the index of the line it landed on */ + shareByLine: Map } /** @@ -157,6 +248,7 @@ function runStack( const eligible = idx.reduce((sum, i) => sum + remaining[i], 0) let discount = 0 const shareByGroup = new Map() + const shareByLine = new Map() if (eligible > 0) { const raw = computeCouponDiscount(eligible, coupon) @@ -167,16 +259,85 @@ function runStack( 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 }) + 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 +} + +/** 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 @@ -249,21 +410,10 @@ export function computeCartPricing(params: { 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 - } + const rounded = roundSharesOnto(rawShares, coupon.discount) groups.forEach((group, i) => { if (rounded[i] !== 0) {