diff --git a/apps/user-ui/components/cart-page.tsx b/apps/user-ui/components/cart-page.tsx index 5e79026..95cb783 100644 --- a/apps/user-ui/components/cart-page.tsx +++ b/apps/user-ui/components/cart-page.tsx @@ -25,7 +25,7 @@ import TestingPhaseNote from "@/components/TestingPhaseNote"; import dayjs from "dayjs"; import { trpc } from "@/src/trpc-client"; -import { useCentralProductStore } from '@/src/store/centralProductStore'; +import { useCentralProductStore, type Product } from '@/src/store/centralProductStore'; import { useCentralSlotStore } from '@/src/store/centralSlotStore'; import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-query-hooks'; import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks'; @@ -51,6 +51,97 @@ const formatDeliverySlot = (deliveryTime: string): string => { return `${time.format('ddd, DD MMM ')}${range}`; }; +/** One row of the "products this coupon applies to" list. */ +type CouponTargetRow = + | { + key: string; + name: string; + unitNotation?: string; + image?: string; + } + | { + key: string; + /** Target SKU that is no longer in the region's catalog. */ + unavailableSkuId: number; + }; + +/** + * The products a coupon is restricted to, one row per DISTINCT product name — + * the coupon targets SKUs, but several SKUs of the same product are the same + * line to a customer. A target whose SKU is not in the catalog (suspended or + * deleted SKUs are filtered out of the product store) still gets a row, so the + * count shown next to the coupon never silently shrinks — which also matches + * the backend, where a stale target simply stops matching. + */ +const buildCouponTargetRows = ( + skuIds: number[], + productsById: Record +): CouponTargetRow[] => { + const rows: CouponTargetRow[] = []; + const seenNames = new Set(); + + skuIds.forEach((skuId) => { + const product = productsById[skuId]; + if (!product?.name) { + rows.push({ key: `sku-${skuId}`, unavailableSkuId: skuId }); + return; + } + if (seenNames.has(product.name)) return; + seenNames.add(product.name); + rows.push({ + key: `name-${product.name}`, + name: product.name, + unitNotation: product.unitNotation, + image: product.images?.[0], + }); + }); + + return rows; +}; + +/** Inline product list for one coupon — rendered inside the coupon dropdown's + * option (the dropdown provides the bounded, scrollable container). */ +function CouponTargetRows({ rows }: { rows: CouponTargetRow[] }) { + return ( + + {rows.map((row) => ( + + {'unavailableSkuId' in row ? ( + <> + + + + + Product unavailable · #{row.unavailableSkuId} + + + ) : ( + <> + + + + {row.name} + + {!!row.unitNotation && ( + + {row.unitNotation} + + )} + + + )} + + ))} + + ); +} + interface DeliverySlotGroupItem { id: number; name: string; @@ -437,6 +528,17 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps const selectedIds = new Set(selectedCoupons.map((c) => c.id)); return ( eligibleCoupons?.map((coupon) => { + // The products this coupon is restricted to (empty => whole cart). One row + // per distinct product name; the same array drives the label and the list, + // so the count always matches what is rendered. + const targetRows = buildCouponTargetRows(coupon.applicableSkuIds, productsById); + const detail = targetRows.length > 0 + ? { + label: `Applies to ${targetRows.length} product${targetRows.length === 1 ? '' : 's'}`, + render: () => , + } + : undefined; + // Disabled coupons can't be applied: row 1 shows just the code (with the // italic "Disabled" badge), row 2 the reason. No "Save" preview. if (!coupon.isEligible) { @@ -445,6 +547,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps value: coupon.id, disabled: true, note: coupon.ineligibilityReason, + detail, }; } @@ -459,10 +562,11 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps label: `${coupon.code} - ${coupon.description} (Save ₹${save})`, value: coupon.id, disabled: false, + detail, }; }) || [] ); - }, [eligibleCoupons, cartLines, selectedCoupons]); + }, [eligibleCoupons, cartLines, selectedCoupons, productsById]); // The coupon dropdown is a multi-select: it toggles an id and reports the whole // new list. An exclusive coupon still replaces every other selection (and @@ -1224,6 +1328,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps { if (unit?.toLowerCase() === 'kg' && quantity < 1) { @@ -231,7 +240,7 @@ const FloatingCartBar: React.FC = ({ )} setIsExpanded(false)} enableDismiss={true}> - + {/* Header */} @@ -269,8 +278,13 @@ const FloatingCartBar: React.FC = ({ )} - {/* Items List */} - + {/* Items List — the only scrolling region. flexBasis auto (not flex-1's + 0%) is what lets the sheet size to this list's content and shrink it + back once the sheet hits its max height. */} + {cartItems.map((item, index) => ( diff --git a/apps/user-ui/src/components/AddToCartDialog.tsx b/apps/user-ui/src/components/AddToCartDialog.tsx index 745dcec..013ab19 100644 --- a/apps/user-ui/src/components/AddToCartDialog.tsx +++ b/apps/user-ui/src/components/AddToCartDialog.tsx @@ -11,11 +11,19 @@ import { useGetEssentialConsts, useSlots } from '@/src/hooks/prominent-api-hooks import dayjs from 'dayjs'; import { SafeAreaView } from 'react-native-safe-area-context'; -// Height of the sheet's content box: the full 80% of the screen the dialog allows. -// Deliberate (not a max): the slot list is `flex-1`, so a definite height is what -// lets it take exactly the leftover space and scroll while the quantity row and the -// Cancel / Add to Cart row stay pinned at the bottom of the sheet. -const SHEET_HEIGHT = Dimensions.get('window').height * 0.8; +// How tall the sheet's content box may get before the slot list starts scrolling. +// Deliberately a MAX, not a height: a product with two slots gets a short sheet, a +// product with many slots stops here. 70px is reserved for BottomDialog's own chrome +// (its handle plus the paddingBottom it puts under our children, 40 on iOS / +// 20 on Android) so the dialog itself never scrolls and the quantity / action rows +// can't be dragged. +// +// The slot list is `shrink` (flexShrink 1, flexBasis auto), NOT `flex-1`: flex-1 is +// flexBasis 0%, which contributes nothing to an auto-height parent and collapses the +// list. With flexBasis auto the list contributes its content height, so the sheet +// sizes to the content and, once the max above is hit, the list — the only +// shrinkable child — takes the leftover space and scrolls. +const SHEET_MAX_HEIGHT = Math.round(Dimensions.get('window').height * 0.8) - 70; const formatTimeRange = (deliveryTime: string) => { const time = dayjs(deliveryTime); @@ -164,7 +172,7 @@ export default function AddToCartDialog() { {/* Bottom sheet: only the bottom inset matters here — a top inset would just add dead space between the handle and the header. */} - + @@ -179,10 +187,14 @@ export default function AddToCartDialog() { - {/* The only scrolling region: this shrinks to whatever space is left in - the capped box above, so the quantity row and the Cancel / Add to - Cart row underneath it never move. */} - + {/* The only scrolling region. flexBasis auto (not flex-1's 0%) is what lets + the sheet size to this list's content and shrink it back once the sheet + hits its max height, so the quantity row and the Cancel / Add to Cart row + underneath never move. */} + {availableSlots.map((slot: any) => ( - expect(screen.getByTestId(`undefined-option-${COUPON_ID}`)).toBeVisible() + expect(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}`)).toBeVisible() ) - fireEvent.press(screen.getByTestId(`undefined-option-${COUPON_ID}`)) + fireEvent.press(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}`)) } describe('Cart coupon application', () => { @@ -187,12 +187,64 @@ describe('Cart coupon application', () => { expect(screen.getAllByText(/Min order ₹1000/).length).toBeGreaterThan(0) ) - fireEvent.press(screen.getByTestId(`undefined-option-${COUPON_ID}`)) + fireEvent.press(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}`)) expect(screen.queryByText('Product Discount')).toBeNull() expect(screen.queryByText('Coupon Applied')).toBeNull() }) + it('expands a product-specific coupon to list the products it applies to', async () => { + // Product 2 = Chicken Breast 500 g, product 4 = Mutton (both in the fixture + // catalog, neither needs to be in the cart). + await mountCart([coupon({ discountPercent: '10', skuIds: [2, 4] })]) + + fireEvent.press(screen.getByText('Select a coupon')) + + await waitFor(() => + expect(screen.getByText('Applies to 2 products')).toBeVisible() + ) + // Collapsed by default. + expect(screen.queryByText('Mutton')).toBeNull() + + fireEvent.press(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}-detail`)) + + expect(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}-detail-list`)).toBeVisible() + expect(screen.getByText('Mutton')).toBeVisible() + // Product 2 is already rendered by the cart line above, so count the occurrences. + expect(screen.getAllByText('Chicken Breast 500 g').length).toBeGreaterThan(1) + + // Expanding must not select the coupon (the selected-coupon chip appears only + // when it is actually applied). + expect(screen.queryByTestId('coupon-chip-SAVE10')).toBeNull() + + // Pressing the trigger again collapses it. + fireEvent.press(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}-detail`)) + expect(screen.queryByText('Mutton')).toBeNull() + }) + + it('collapses the previously expanded coupon and keeps unresolved targets visible', async () => { + await mountCart([ + coupon({ id: COUPON_ID, discountPercent: '10', skuIds: [2] }), + // 999999 is not in the catalog (e.g. a suspended SKU): it still gets a row. + coupon({ id: 78, couponCode: 'MUTTON20', discountPercent: '20', skuIds: [999999] }), + ]) + + fireEvent.press(screen.getByText('Select a coupon')) + + // One product each, so both triggers read "1 product". + await waitFor(() => + expect(screen.getAllByText('Applies to 1 product').length).toBe(2) + ) + + fireEvent.press(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}-detail`)) + expect(screen.getAllByText('Chicken Breast 500 g').length).toBeGreaterThan(1) + + // Opening the second coupon's list closes the first one. + fireEvent.press(screen.getByTestId('coupon-dropdown-option-78-detail')) + expect(screen.getByText('Product unavailable · #999999')).toBeVisible() + expect(screen.queryByTestId(`coupon-dropdown-option-${COUPON_ID}-detail-list`)).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/change-log.txt b/change-log.txt index f0a58a4..90b5fff 100644 --- a/change-log.txt +++ b/change-log.txt @@ -5249,3 +5249,134 @@ user-ui * temp local D1 delta (outside repo): rebuild coupons + coupon_usage + coupon_applicable_users + order_status to drop the NOT NULL. No tests run; migrations not run. + +2026-10-17 09:58:20 user-ui: "Applies to N products" inline expansion in the cart's coupon dropdown. + + User: "I want a clickable 'applies to n products' for product specific coupons ... expand a + coupon's view and show the products list. I don't want to embed one dialog in another." + Decisions: show DISTINCT PRODUCT NAMES; the product list has its OWN inner scroll. + + packages/ui/src/components/bottom-dropdown.tsx + + DropdownOption.detail?: { label: string; render: () => React.ReactNode } - an optional + expander under an option row. The dropdown owns the trigger + open/closed state and wraps + render() in a bounded ScrollView (max-h-60, nestedScrollEnabled); the caller owns the content. + + useState expandedValue (one open at a time; toggling another collapses the previous). + + row is now wrapped in a View so text/trigger/list are siblings - the trigger is NOT nested + inside the option TouchableOpacity, so expanding can never toggle or close the selection. + + reset expandedValue in handleDone and the onClose handler, next to setSearchQuery(''). + + testIDs `${testID}-option-${value}-detail` / `-detail-list`, matching the existing convention. + No behaviour change for the ~15 existing BottomDropdown consumers (detail is optional). + + apps/user-ui/components/cart-page.tsx + + buildCouponTargetRows(skuIds, productsById) - dedupes by product NAME and emits one row per + distinct name; targets whose SKU is not in the catalog (suspended/deleted SKUs are filtered + out of productsById) each get an "unavailable" row so the count never silently shrinks. + + CouponTargetRows({ rows }) - presentational: 32px image, name, unit notation, or the muted + "Product unavailable - #" fallback. + ~ dropdownData: for every coupon with targets (eligible AND disabled), one rows array is built + once and used for BOTH the label ("Applies to N products", N = rows.length) and the content, + so the number always matches the rows rendered. + + testID="coupon-dropdown" on the coupon dropdown. + testID consequence: the dropdown had no testID, so options were reachable as + `undefined-option-`; they are now `coupon-dropdown-option-` - 3 references updated in + apps/user-ui/tests/screens/cart-coupons.test.tsx + a new expander test case. + + Not done (offered, not requested): the same expander in the cart's "Applied Coupons" dialog; an + "In cart" chip on the rows. + +2026-10-17 10:12:47 user-ui: "Applies to N products" expander - implementation notes + a pre-existing test staleness. + + Implemented as planned (see the 09:58:20 entry). Extra detail worth recording: + * cart-page.tsx: buildCouponTargetRows() returns the rows ONCE per coupon inside the dropdownData + memo; the same array drives both the trigger label and the rendered list, so the count can never + disagree with what is shown. Depends on productsById (added to the memo deps). + * The expander is attached to eligible AND disabled coupons (a disabled coupon is exactly where + "which products does it want" matters). Covered by the new second test case. + * Row styling: 32px image, name, unit notation, `last:border-b-0` (twrnc `last:` variants are + already used elsewhere in the repo). Inner scroll container is the dropdown's + `max-h-60` + `nestedScrollEnabled` ScrollView - same pattern as its own option list (max-h-80). + + Typecheck (not tests): apps/user-ui, apps/admin-ui, apps/web-ui, apps/fallback-ui all clean. + Tests deliberately NOT run (AGENTS: no suite runs unless asked). + + PRE-EXISTING FINDING (untouched by this change): apps/user-ui/tests/screens/cart-coupons.test.tsx + asserts the text 'Coupon Applied' at lines 123, 177, 193 and 268, but no cart-page code renders it - + `git grep 'Coupon Applied'` only matches the order-detail screens (user-ui/app/(drawer)/(tabs)/me/ + my-orders/[id].tsx, web-ui, admin-web). Line 123 is a getByText, so that test can only pass if the + string is rendered somewhere I have not found; the three queryByText lines pass vacuously. My own + new test therefore asserts the selected-coupon CHIP (coupon-chip-SAVE10) instead of that string. + +2026-10-17 10:31:02 common-ui: BottomDropdown's option list uses the available height (up to ~80% of the screen). + + Feedback: "the coupons bottom dialog is taking only upto 50% height and enabling scroll. I want it to + take as much as 80% if needed and then enable scroll". + + Cause: the option list inside the dropdown's BottomDialog was capped with `tw`max-h-80`` (320px). + BottomDialog is content-sized (auto height, BottomDialog keeps its 85% backstop), so that cap is + what set the dialog's height: 320 + the dialog chrome (handle, title, search field, Done row, its + own scroll-content paddingBottom ~260px) => the dialog stopped at roughly half the screen and the + 320px list started scrolling. + + packages/ui/src/components/bottom-dropdown.tsx + + SCREEN_HEIGHT (Dimensions.get('window').height) and + OPTION_LIST_MAX_HEIGHT = max(200, round(SCREEN_HEIGHT * 0.8) - 260) - i.e. "leave ~260px for the + chrome, hand the rest of the 80% budget to the list", floored so tiny screens still get a usable + window. On a 932pt screen: 486px list => dialog ~739px (79%); 667pt: 274px => ~527px (79%); + 568pt: 200px => ~453px (80%). + ~ the option list ScrollView: `tw`max-h-80`` -> style={{ maxHeight: OPTION_LIST_MAX_HEIGHT }} and + gained `nestedScrollEnabled` (it scrolls inside the dialog's own ScrollView on Android). + ~ short lists are unaffected: the dialog stays content-sized (a 2-coupon list is still a short + sheet), which is the "as much as 80% IF NEEDED" part. + Untouched: BottomDialog's 0.85*SCREEN_HEIGHT cap stays as the backstop, and no shared dialog + default changed (setting it to 0.8 globally would push the cart sheets - 0.8*S content + chrome - + ~65px past their ceiling and make their pinned footer draggable). The Done row stays pinned below + the list, matching the pinned-action-row preference from the cart sheets. + +2026-10-17 10:52:36 user-ui: the cart + Add-to-Cart sheets now grow with their content up to ~80% instead of always being 80%. + + Request: "I want the same behaviour for the expanded form of the floating cart bar and the add to + cart dialog too" - i.e. the dropdown change: as tall as the content needs, up to ~80%, and only then + scroll (footer/action row staying pinned). + + Both sheets had a DEFINITE height (screenHeight * 0.8), taken from the earlier "pinned footer" work: + the list was `flex-1` and that only works inside a definite height, because `flex-1` is + `flexBasis: 0%` - inside an auto-height parent it contributes 0 to the parent's size and collapses. + So the sheet was always 80% tall, mostly empty for a 1-2 item cart. + + The fix is flexBasis: the list becomes `shrink` (flexShrink: 1, flexBasis AUTO) instead of `flex-1`, + and the sheet becomes content-sized with a max: + * short cart -> the list's natural (content) height is what sizes the sheet -> short sheet + * long cart -> the sheet hits its maxHeight, the negative free space goes to the only + shrinkable child (the list; header/progress/footer keep RN's default flexShrink 0) + -> the list gets exactly maxHeight - header - footer and scrolls; footer pinned + Cap: screenHeight * 0.8 minus 70px reserved for BottomDialog's own chrome (handle 25 + its scroll + content paddingBottom 40 iOS / 20 Android, worst case 40 + margin) so the dialog itself never + scrolls and the pinned row cannot be dragged - the same chrome-reservation approach as the + dropdown list cap (10:31:02). + + apps/user-ui/components/floating-cart-bar.tsx + ~ CART_SHEET_HEIGHT = screenHeight * 0.8 -> CART_SHEET_MAX_HEIGHT = round(screenHeight * 0.8) - 70 + (comment rewritten: max, why not flex-1) + ~ sheet View: style={{ height: ... }} -> style={{ maxHeight: ... }} + ~ items list ScrollView: tw`flex-1` -> tw`shrink` + apps/user-ui/src/components/AddToCartDialog.tsx + ~ SHEET_HEIGHT = Dimensions.get('window').height * 0.8 -> SHEET_MAX_HEIGHT (same formula/comment) + ~ sheet View: [tw`p-6`, { height: SHEET_HEIGHT }] -> [tw`p-6`, { maxHeight: SHEET_MAX_HEIGHT }] + ~ slot list ScrollView: tw`flex-1` -> tw`shrink` + Untouched: BottomDialog's 0.85 cap (backstop), everything else in both sheets. + +2026-10-17 11:04:58 CORRECTION to 10:52:36: the lists use an explicit flex basis/shrink, not tw`shrink`. + + I first wrote `tw`shrink`` for the two lists. twrnc resolves a bare `shrink` through the theme's + flexShrink.DEFAULT (ClassParser -> flexGrowShrink('Shrink', '', theme.flexShrink)); if that theme + entry is missing, `Number(undefined ?? '')` is 0, i.e. the class would silently mean `shrink-0` + and the list would stop shrinking - the sheet would hit its max height and the list would overflow + instead of scrolling. Not worth the dependency, so both now say it outright: + + + + (flexBasis 'auto' is RN's default, written out because it is the whole point of the fix: flex-1's + `0%` basis is why the list used to collapse in an auto-height parent.) + 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. diff --git a/packages/ui/src/components/bottom-dropdown.tsx b/packages/ui/src/components/bottom-dropdown.tsx index ada36f3..80f027d 100644 --- a/packages/ui/src/components/bottom-dropdown.tsx +++ b/packages/ui/src/components/bottom-dropdown.tsx @@ -1,5 +1,5 @@ import React, { useState, useCallback, useRef, useEffect } from 'react'; -import { Text, View, TouchableOpacity, ScrollView, TextInput } from 'react-native'; +import { Text, View, TouchableOpacity, ScrollView, TextInput, Dimensions } from 'react-native'; import { Ionicons } from '@expo/vector-icons'; import { BottomDialog } from './dialog'; import MyText from './text'; @@ -14,6 +14,19 @@ export interface DropdownOption extends BaseDropdownOption { disabled?: boolean; /** Optional second line shown under the label (e.g. why it is disabled). */ note?: string; + /** + * Optional expander rendered under the option row — e.g. "Applies to 3 products" + * on a product-restricted coupon. The dropdown owns the trigger and the + * open/closed state (one option open at a time) and wraps `render()` in a bounded + * scroll container; the caller owns the content. Deliberately NOT a nested + * dialog: the expanded content lives inline, inside the option block. + */ + detail?: { + /** Trigger text, e.g. "Applies to 3 products". */ + label: string; + /** Content shown when expanded. */ + render: () => React.ReactNode; + }; } interface BottomDropdownProps extends DropdownBaseProps { @@ -30,6 +43,21 @@ interface BottomDropdownProps extends DropdownBaseProps { testID?: string; } +const SCREEN_HEIGHT = Dimensions.get('window').height; + +/** + * How tall the option list may grow before it starts scrolling. + * + * The dialog is content-sized (BottomDialog has an auto height with an 85% + * backstop), so the list cap is what actually decides how tall the dropdown + * dialog gets. This hands the list everything left of an 80%-of-screen budget + * after the dialog's own chrome — handle, title, bottom padding, and (when + * present) the search field and the Done row, ~260px on a phone — so a long + * list (coupons, products, …) fills the sheet up to about 80% and only then + * scrolls. Short lists are unaffected: the dialog stays content-sized. + */ +const OPTION_LIST_MAX_HEIGHT = Math.max(200, Math.round(SCREEN_HEIGHT * 0.8) - 260); + const BottomDropdown: React.FC = ({ label, topLabel, @@ -49,6 +77,8 @@ const BottomDropdown: React.FC = ({ const { theme } = useTheme(); const [isOpen, setIsOpen] = useState(false); const [searchQuery, setSearchQuery] = useState(''); + // Which option's `detail` is expanded (one at a time). + const [expandedValue, setExpandedValue] = useState(null); const debounceTimeoutRef = useRef(null); // Debounced search function @@ -107,6 +137,7 @@ const BottomDropdown: React.FC = ({ const handleDone = () => { setIsOpen(false); setSearchQuery(''); // Clear search when done + setExpandedValue(null); // Collapse any open detail if (debounceTimeoutRef.current) { clearTimeout(debounceTimeoutRef.current); debounceTimeoutRef.current = null; @@ -174,6 +205,7 @@ const BottomDropdown: React.FC = ({ { setIsOpen(false); setSearchQuery(''); // Clear search when closed + setExpandedValue(null); // Collapse any open detail if (debounceTimeoutRef.current) { clearTimeout(debounceTimeoutRef.current); debounceTimeoutRef.current = null; @@ -200,7 +232,10 @@ const BottomDropdown: React.FC = ({ )} - + {filteredOptions.length === 0 && searchQuery ? ( @@ -211,10 +246,11 @@ const BottomDropdown: React.FC = ({ filteredOptions.map((option) => { const selected = isSelected(option.value); const isDisabled = option.disabled || disabled; + const isDetailOpen = expandedValue === option.value; const [code, rest] = (option.label as string).split(' - ', 2); return ( + = ({ )} + + {/* Inline expander — a sibling of the row, so opening/closing it can + never toggle or dismiss the selection. */} + {!!option.detail && ( + <> + setExpandedValue(isDetailOpen ? null : option.value)} + activeOpacity={0.7} + > + + + {option.detail.label} + + + + {isDetailOpen && ( + + + {option.detail.render()} + + + )} + + )} + ); }) )}