freshyo/change-log.txt
2026-11-16 01:28:18 +05:30

1495 lines
76 KiB
Text

[2026-10-29 22:54:34 IST] Admin app: open the order from an order-placed push, including cold start.
--- apps/admin-ui/services/notif-service/pending-order.ts (new)
+ Module-level pending order id: setPendingOrderId / takePendingOrderId / clearPendingOrderId.
--- apps/admin-ui/services/notif-service/notif-context.tsx
~ Extract openFromNotification(response): numeric-validates data.orderId, dedupes by
request.identifier, pushes order details when signed in, stashes the id when signed out.
~ Call it from the response listener AND from Notifications.getLastNotificationResponseAsync()
(terminated-app tap), then clearLastNotificationResponseAsync().
~ Wait for StaffAuthProvider hydration (isLoading === false) before handling the launch response.
--- apps/admin-ui/components/context/staff-auth-context.tsx
~ On login success, route to a pending order notification target instead of always the dashboard.
--- apps/admin-ui/tests/mocks/expo-notifications-mock.ts
+ clearLastNotificationResponseAsync mock; __setLastResponse() to seed the cold-start response.
--- apps/admin-ui/tests/app/root-layout.test.tsx
+ AROOT-06 cold-start tap, AROOT-07 duplicate response opened once, AROOT-08 signed-out deferral.
--- apps/admin-ui/tests/pages/login.test.tsx
+ ALOGIN-15 pending order target wins over the dashboard after login.
--- apps/admin-ui/JEST-TEST-CASES.md
+ Catalogue rows for AROOT-06..08 and ALOGIN-15.
[2026-10-29 22:57:48 IST] Admin push notifications for order cancellation and new complaints.
--- apps/backend/src/lib/admin-notif.ts
~ notifyAllAdmins payload gains optional complaintId; forwarded in jobData.
--- apps/backend/src/lib/notif-job.ts
~ sendAdminNotification accepts complaintId and includes it in the push data.
--- apps/backend/src/lib/queue-consumer.ts
~ forwards jobData.complaintId (null fallback) to sendAdminNotification.
--- apps/backend/src/lib/post-order-handler.ts
~ handleOrderCancelled pushes "Order Cancelled" to every admin device with data.orderId.
--- packages/db_helper_sqlite/src/user-apis/complaint.ts
~ createComplaint returns the inserted complaint id (was void).
--- apps/backend/src/trpc/apis/user-apis/apis/complaint.ts
~ complaint.raise pushes "New Complaint" to admin devices with data.complaintId;
notification failures are logged and never fail the complaint.
--- apps/admin-ui/services/notif-service/pending-navigation.ts (renames pending-order.ts)
~ Holds a pending href instead of an order id, so a signed-out tap on either
notification type resumes after login.
--- apps/admin-ui/services/notif-service/notif-context.tsx
~ Routes data.complaintId to the complaints list (orderId still wins).
--- apps/admin-ui/components/context/staff-auth-context.tsx
~ login consumes the pending href.
--- tests
~ queue-consumer expectation gains complaintId; admin-ui root-layout/login tests
updated for the href-based pending target; AROOT-09 complaint tap added.
[2026-10-29 23:02:23 IST] Scope admin order/complaint push notifications to the event's region.
--- packages/db_helper_sqlite/src/admin-apis/staff-user.ts
+ getStaffNotifTokensForRegion(regionId): staff_notif_creds inner-joined to
staff_users where staff_users.region_id = regionId.
--- packages/db_helper_sqlite/index.ts
+ export the new helper.
--- packages/db_helper_sqlite/src/user-apis/order.ts
~ OrderWithFullData gains regionId (already selected at runtime).
--- packages/db_helper_sqlite/src/user-apis/complaint.ts
~ createComplaint returns { id, regionId } instead of a bare id.
--- apps/backend/src/lib/admin-notif.ts
+ notifyRegionAdmins(regionId, payload) — refuses null region, otherwise batches
the region's tokens. notifyAllAdmins kept for manual broadcasts only.
--- apps/backend/src/lib/post-order-handler.ts
~ Order placed and order cancelled use notifyRegionAdmins(order.regionId, ...).
--- apps/backend/src/trpc/apis/user-apis/apis/complaint.ts
~ complaint.raise uses notifyRegionAdmins(complaint.regionId, ...).
--- apps/backend/tests/unit/admin-notif.test.ts
~ Rewritten for region scoping + manual broadcast; asserts null region is a no-op.
[2026-11-01 12:32:24 IST] user-ui home: match the All Available Products grid spacing to the tag grid.
--- apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
~ staticStyles.columnWrapper.paddingHorizontal 16 -> 28. Cards keep
heroItemWidth, so the horizontal gap becomes 8px, identical to the tag grid
(mx-4 + px-3 = 28px inset, same 8px gaps).
~ All Available Products heading row px-1 -> px-3 so the title sits on the same
28px gutter as the rows.
No data, paging, or card changes.
[2026-11-01 12:34:02 IST] user-ui home: give the catalog grid the extra space as card width.
--- apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
~ Reverts the 28px row gutter: columnWrapper.paddingHorizontal back to 16 so the
grid keeps the page's 16px margin (and the heading returns to px-1).
+ catalogItemWidth = (screenWidth - 48) / 3; ProductItem (catalog rows only)
uses it instead of heroItemWidth, so three cards fill the row with 8px gaps.
Tag grid keeps heroItemWidth inside its 28px inset card.
[2026-11-01 12:37:54 IST] user-ui Offers/Combos: same compact 3-up grid as the home catalog.
--- apps/user-ui/app/(drawer)/(tabs)/order-again/index.tsx
~ heroItemWidth -> catalogItemWidth = (screenWidth - 48) / 3.
~ Grid gap-5 (20px) -> gap-2 (8px); px-4 page margin unchanged.
Three cards now fill the row, matching the All Available Products grid.
Web offers page already uses a 12px grid gap (gap-3), so no web change.
[2026-11-01 12:51:23 IST] Flash delivery: tag tabs instead of the store drawer, 3-up hero grid.
--- apps/user-ui/components/ProductCard.tsx
+ cartType?: 'regular' | 'flash' (default regular). Flash reads/writes the flash
cart, prices flashPrice ?? price, adds with slotId 0 and the 1hr alert, and
skips scheduled-slot out-of-stock/delivery badges. Regular call sites unchanged.
--- apps/user-ui/components/SlotSpecificView.tsx
+ FlashTagStrip: horizontal, fixed strip copied from home's TagTabStrip mechanics.
~ SlotLayout: isForFlashDelivery renders selector + strip + <Slot/>; the
scheduled view keeps its Drawer untouched.
~ FlashDeliveryProducts: tags from useAllProducts (first tag default), filter by
tag.productIds then search, numColumns 3, width (sw-48)/3, columnGap 8,
rowGap 12, ProductCard hero cards. Store filtering/loading gates removed.
--- apps/user-ui/app/(drawer)/(tabs)/flash-delivery/(products)/index.tsx
--- apps/user-ui/app/(drawer)/(tabs)/flash-delivery/(products)/_layout.tsx
~ storeId param no longer read or written; route shape unchanged.
--- apps/web-ui/src/routes/flash.tsx
~ Store tabs -> tag tabs (same order, first default); store filtering removed;
cart storeId still taken from the product.
--- tests
~ flash-products store cases rewritten for tags; slot-view flash asserts no
drawer; JEST-TEST-CASES rows updated.
[2026-11-01 12:56:02 IST] Flash delivery: page the tag feed 9 at a time with Show More.
--- apps/user-ui/components/SlotSpecificView.tsx
+ FLASH_PAGE_SIZE = 9; visibleCount state, reset on tag/search change; grid renders
the first 9, footer Show More adds 9 (home's pattern). testID flash-products-show-more.
--- apps/web-ui/src/routes/flash.tsx
~ Same 9-at-a-time paging with a Show More button; reset on tag change.
--- apps/user-ui/tests/pages/flash-products.test.tsx
+ FLASH-19: nine products render, Show More reveals the rest.
--- apps/user-ui/JEST-TEST-CASES.md
+ FLASH-19 row.
[2026-11-01 12:59:05 IST] Flash delivery: scroll-away tabs + a "Shop by Store" tab section.
--- apps/user-ui/components/SlotSpecificView.tsx
~ FlashTagStrip generalised to FlashTabStrip (items + testID prefix); reused for
tags and stores.
~ FlashDeliveryProducts becomes a ScrollView: search, tag strip, tag grid (9 +
Show More), then "Shop by Store" heading, store strip, store grid (9 + Show
More). Both strips scroll with the page; paging resets per section on
tab/search change. Search filters both grids. Every store gets a tab.
--- apps/web-ui/src/routes/flash.tsx
~ Same two sections, store tabs below the tag grid, independent 9-item paging.
--- tests
~ Product assertions scoped to the tag grid; new store-section cases.
[2026-11-01 14:06:51 IST] Flash delivery: the pull-to-refresh spinner no longer reports background fetches.
Diagnosed with a throwaway cache-subscription test (25s, real timers): the flash
screen itself starts no background fetches (only the 7 initial ones), and the
catalogue URL is built from assetsDomain/apiCacheKey/region/version — stable, so
the products query key does not churn. There is no 10s timer anywhere in
user-ui. What is wrong is the wiring: `refreshing` was bound to
`productsQuery.isFetching`, so *any* fetch (mount-after-stale, invalidation,
version bump, pull) drove the pull-to-refresh control, and the control element
was rebuilt on every render (re-attaching the platform control).
--- apps/user-ui/components/SlotSpecificView.tsx
~ FlashDeliveryProducts: `isRefreshing` local state + handleRefresh
(refetch products + stores, clear in finally), RefreshControl element
memoised. Mirrors home's handleRefresh. Background fetches are invisible.
--- apps/user-ui/src/hooks/useHideTabNav.ts
~ Focus callback memoised (was recreated every render, so useFocusEffect
unsubscribed/resubscribed per render and wrote false->true into the store,
flickering the tab bar on every render of every screen using it).
--- apps/user-ui/src/store/appStore.ts
~ setHideTabsNavKey no longer allocates when the key already has that value,
so it cannot notify subscribers spuriously.
--- tests
+ FLASH-24: a background refetch leaves the spinner idle.
+ FLASH-25: a pull keeps the spinner up until the refresh settles.
+ HIDE-04: re-render does not rewrite the store.
+ STORE-20: same-value write keeps the map identity.
[2026-11-01 14:24:07 IST] user-ui: arm64-only Android profile for personal device builds.
--- apps/user-ui/eas.json
+ "shafi-dev-arm64": internal distribution, channel shafi-dev, buildType apk,
gradleCommand ":app:assembleRelease -PreactNativeArchitectures=arm64-v8a".
Same JS/OTA channel as shafi-dev; the APK simply carries only arm64-v8a native
libs instead of all four ABIs (that is most of the 80 MB universal APK).
~ shafi-dev left untouched (universal APK for emulators / 32-bit testers).
[2026-11-01 14:31:37 IST] user-ui: shafi-dev now builds arm64-only + R8 (was universal APK).
Measured on the device (Play install, v1.2.0): base.apk 38.4 MB (dex 29.6 MB,
assets 3.9, res 2.7) + split arm64 libs 19.0 MB + density/langs 0.4 => 57.8 MB
installed. The local universal APK carries the same bytes plus three unused ABI
sets (x86, x86_64, armeabi-v7a), which is the 80 MB.
--- apps/user-ui/eas.json
~ shafi-dev: explicit buildType apk; gradleCommand
":app:assembleRelease -PreactNativeArchitectures=arm64-v8a
-Pandroid.enableProguardInReleaseBuilds=true".
-PreactNativeArchitectures drops the three unused ABIs, and the ProGuard
property turns on R8 + resource shrinking for this profile only (the template
reads it via findProperty, so production is untouched).
- shafi-dev-arm64 removed: redundant now that shafi-dev is arm64-only.
[2026-11-01 14:53:35 IST] Home: catalogue memo is the single source for products, tags and products-by-tag.
--- apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
~ Removed `products = productsData?.products || []`, `dashboardTags =
productsData?.tags || []` and the separate `productsByTagId` memo. One memo
now returns { dashboardTags, products, productsByTagId } and all three are
read from it.
~ productById Map hoisted out of the per-tag loop (it was rebuilt once per tag).
~ Duplicate ids in tag.productIds are skipped (first occurrence wins), so a
repeated id renders one card instead of two.
~ displayedProducts effect deps use the memo's `products`.
--- apps/user-ui/hooks/useProductSlotIdentifier.ts
~ getQuickestSlot wrapped in useCallback with [slots, productSlotsMap]. It was
a new function every render, which made the catalogue memo recompute on every
render (and defeated its useMemo).
--- apps/web-ui/src/routes/home.index.tsx
~ Same restructure: one memo returns { dashboardTags, allProducts,
productsByTagId }, dedupe + hoisted productById, and the dead `extra` branch
removed (its filter can never match: orderedIds is built from productIds).
--- apps/user-ui/tests/pages/home.test.tsx
~ HOME-16 rewritten: duplicate ids in a tag now render once (was pinning the
bug).
--- apps/user-ui/JEST-TEST-CASES.md
~ HOME-16 catalogue row updated.
[2026-11-01 15:10:50 IST] Home tag selection/expansion moved to a zustand store so a tap stops re-rendering the whole page.
Selecting a tag used to set Dashboard state, which re-rendered Dashboard, rebuilt
ListHeader and rebuilt the SectionList `sections` literal, re-rendering every
visible main-list ProductCard as well. The selection now lives outside React
state; only the tab strip and the active tag scene subscribe.
--- apps/user-ui/src/store/homeTagStore.ts (new)
+ selectedTagId + expandedByTagId + selectTag/expandTag/resetHomeTags.
+ Writes are no-ops when unchanged (same guard as appStore.setHideTabsNavKey)
so re-selecting the active tag does not wake subscribers.
--- apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
~ Removed Dashboard's selectedTagId/expandedByTagId state, activeTagId,
handleToggleExpand and the dead pageTint (both styles hardcoded #FFFFFF, so
getTagColor/TAG_COLORS had no visible effect).
~ TagTabStrip and TagScene subscribe to useHomeTagStore directly; their
activeTagId/onSelectTag/expandedByTagId/onToggleExpand props are gone.
~ ListHeader no longer receives or forwards selection props.
~ listHeader memo deps drop activeTagId/expandedByTagId/handleToggleExpand, so
Dashboard no longer produces a new header element on a tag tap.
--- apps/user-ui/src/lib/region-switch.ts
+ resetHomeTags() on region switch: tag ids are region-scoped.
--- apps/user-ui/tests/helpers/reset.ts
+ reset the home tag store between cases.
--- apps/user-ui/tests/lib/stores.test.ts
+ STORE-21: selecting the active tag again keeps store identity.
+ STORE-22: resetHomeTags clears selection and expansion.
--- apps/user-ui/JEST-TEST-CASES.md
~ rows for STORE-21/22.
--- apps/web-ui/src/lib/stores/home-tag-store.ts (new)
+ Same store, mirrored.
--- apps/web-ui/src/routes/home.index.tsx
~ selection/expansion read from the store (the web page is one component, so it
still subscribes; behaviour matches user-ui).
--- apps/web-ui/src/lib/region-switch.ts
+ resetHomeTags() on region switch.
[2026-11-01 17:53:16 IST] user-ui: ProductCard images move from RN Image (Fresco) to expo-image.
Diagnosed from the device onError payload:
"Pool hard cap violation? Hard cap = 301989888 Used size = 301156264 Free
size = 0 Request size = 4259840" — Fresco's bitmap pool (288 MiB) was full, so
valid images failed to decode. Live catalogue check: 148/149 image URLs return
200 image/*; the one 404 is product 84's ref missing the product-images/ prefix.
Source images are 1024-1600px, i.e. 4-10 MB decoded at source vs ~0.35 MB at
card size.
--- apps/user-ui/components/ProductCard.tsx
~ <RnImage> replaced with expo-image <Image> (already imported, used by every
other image surface in the app): contentFit="cover", cachePolicy="memory-disk",
recyclingKey=item.id, transition={0}. Glide downsamples to the view size and
bounds its caches instead of holding full-size bitmaps in Fresco's pool.
~ resizeMode moved out of the style object into contentFit (style resizeMode is
not a valid RN style).
~ onError now surfaces event.error (was discarded, always "Image failed to
load"). Remove the now-unused `Image as RnImage` import.
--- apps/user-ui/tests/pages/home.test.tsx
~ HOME-38 fires the error on the expo-image mock (testID "expo-image") instead
of an RN Image instance.
[2026-11-01 18:07:16 IST] product-images: generated 1000px copies of the 147 oversized catalogue images (nothing uploaded).
--- product-images/resized/ (new, untracked)
+ one resized copy per row of needs-edit.csv; max side 1000, aspect preserved,
JPEG re-encoded at quality 70, PNG kept as PNG. Originals untouched.
--- product-images/resized-report.csv (new, untracked)
+ per file: old/new dimensions, old/new bytes, old/new decoded MB, delta.
- R2 bucket, products.json and DB were not modified.
[2026-11-01 18:26:30 IST] product-images: 800px pass generated and uploaded over the live keys (prod bucket).
--- product-images/resized-800/ (new, untracked)
+ every referenced catalogue image with max side > 800 resized to 800px
(JPEG q70, PNG kept as PNG). Originals left untouched in product-images/.
--- product-images/resized-800-report.csv (new, untracked)
+ per file: old/new dimensions, bytes and decoded MB.
--- R2 (bucket meatfarmer, prefix product-images/)
~ the same keys were overwritten with the 800px files; Content-Type preserved
per output format. Cloudflare cache purged for every replaced URL.
- No DB rows, products.json or version numbers changed.
[2026-11-01 18:37:42 IST] products.json: append a static cache-busting query to image URLs.
Client image caches are keyed by URL and the R2 object keys never change, so
replaced files were invisible to phones that had cached the old bytes. The
generated catalogue now appends ?random=1 to every product image URL and tag
imageUrl. Static by design: a per-request value would defeat caching.
--- apps/backend/src/lib/product-image-cache.ts (new)
+ PRODUCT_IMAGE_CACHE_BUST = 'random=1', withImageCacheBust(url) (handles a URL
that already has a query) and applyImageCacheBust(catalogue), which rewrites
product images and tag imageUrl only.
--- apps/backend/src/lib/cloud_cache.ts
~ createProductsFileInternal applies applyImageCacheBust before serialising, so
only the published products.json carries the query; the admin summary endpoint
and the test snapshot controller keep raw URLs.
--- apps/backend/tests/unit/product-image-cache.test.ts (new)
+ unit coverage for plain URLs, URLs with a query, empty values, the
product/tag mapping and input immutability.
--- docs/jobs-to-be-added.txt
+ job to roll the same asset version out to the remaining image surfaces.
[2026-11-01 19:03:33 IST] user-ui: enforce a 3-day TTL on the expo-image disk cache.
expo-image has no per-entry TTL (cachePolicy is only none/disk/memory/memory-disk;
the underlying Glide/SDWebImage caches are LRU, no expiry). It does expose
Image.clearDiskCache(), so the cache is cleared when the stored timestamp is
older than 3 days, checked on mount and whenever the app returns to the
foreground. Results in a maximum age of 3 days for any cached image.
--- apps/user-ui/src/lib/image-cache-ttl.ts (new)
+ IMAGE_CACHE_TTL_MS (3 days), IMAGE_CACHE_CLEARED_AT_KEY and
shouldClearImageCache(lastClearedAt, now) (null/invalid/future timestamps
clear).
--- apps/user-ui/src/lib/image-cache-meta.ts (new)
+ timestamp persisted in a plain file under expo-file-system's documentDirectory
(expo-file-system is a dependency of expo). No SecureStore / StorageService.
--- apps/user-ui/src/components/ImageCacheTtl.tsx (new)
+ one-shot guard, reads the file timestamp, calls Image.clearDiskCache() only
when expired, writes the new timestamp when the clear reports success. Errors
never block startup.
--- apps/user-ui/app/_layout.tsx
+ mount <ImageCacheTtl /> inside CentralStoreInitializer.
--- apps/user-ui/tests/mocks/native/common.tsx + tests/jest.config.js
+ expo-image mock gains clearDiskCache/clearMemoryCache/prefetch jest.fn
statics; expo-file-system is mapped to the same shim.
--- apps/user-ui/tests/lib/image-cache-ttl.test.tsx (new)
+ IMGCACHE-01..07: helper boundaries, component clear/skip and failed-clear.
--- apps/user-ui/tests/lib/image-cache-meta.test.ts (new)
+ IMGCACHE-08..10: missing/corrupt file and the write path.
--- apps/user-ui/JEST-TEST-CASES.md
+ rows for IMGCACHE-01..10.
[2026-11-01 19:19:30 IST] home: split the monolithic list header into separate virtualized items and tighten the render window.
The whole top block (glimpse + tag strip + tag grid + stores + slots + "All
Available Products" title) was a single SectionList item, and the first
`initialNumToRender` items are pinned by VirtualizedList. With
initialNumToRender=10 and windowSize=5, the header plus ~27 cards stayed mounted
forever, growing worse as Show More appended rows.
--- apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
~ Removed the ListHeader component/wrapper. The list data is now a list of
typed items: glimpse, tagStrip, tagScene, stores, slots, allProductsTitle,
empty and row (3 products). Each renders independently, so the top sections
unmount as they scroll out of the window.
~ Per-item white/px-4 wrappers replace the old rounded-t-3xl wrapper (page
background is white, so the rounded edge was not visible).
~ Extracted HomeGlimpse, TagSceneBlock, StoresSection, SlotsSection and
AllProductsTitle (all memoized); SlotsSection keeps its own renderSlotItem.
~ sections, keyExtractor, renderItem, renderSectionHeader and the footer are
memoized/callback-stable so unrelated Dashboard renders no longer rebuild
the list props.
--- apps/user-ui/src/lib/home-list-tuning.ts (new)
+ HOME_INITIAL_RENDER_COUNT=2, HOME_WINDOW_SIZE=3, HOME_MAX_RENDER_BATCH=6.
VirtualizedList pins the first initialNumToRender cells forever, so it must
stay small for the split top sections to unmount.
~ Virtualization props now read those constants (was windowSize 5,
initialNumToRender 10, maxToRenderPerBatch 10). removeClippedSubviews stays
off (nested horizontal scrollers).
- ProductCard's 5s interval left untouched, as requested.
--- apps/user-ui/tests/pages/home.test.tsx
~ mainListIds reads the row items from sections[0].data (kind === 'row').
~ Mocks home-list-tuning with initialNumToRender 20 so interaction assertions
have product rows mounted (jsdom never scrolls a virtualized list).
[2026-11-01 19:57:06 IST] admin-ui manage-orders: virtualize the order lists and stop re-rendering every mounted row.
--- apps/admin-ui/app/(drawer)/dashboard/manage-orders/orders/index.tsx
~ OrderItem wrapped in React.memo; orders pages flattened in a useMemo;
keyExtractor/renderItem/onEndReached/onRefresh are stable callbacks and the
footer is memoized. With the inline props, every filter-dialog state change
re-rendered every mounted row (each with six dialog elements).
~ FlatList window: initialNumToRender 6, maxToRenderPerBatch 6, windowSize 5,
updateCellsBatchingPeriod 50, removeClippedSubviews false (rows carry
modals/shadows; windowing already unmounts them).
--- apps/admin-ui/app/(drawer)/dashboard/manage-orders/delivery-sequences/index.tsx
~ OrderItem wrapped in React.memo; stable renderItem/keyExtractor and a stable
onToggleOrder (the inline callback previously defeated memoization);
ListHeaderComponent memoized.
~ DraggableFlatList window: initialNumToRender 6, maxToRenderPerBatch 6,
windowSize 3 (rows are shorter), updateCellsBatchingPeriod 50,
removeClippedSubviews false (drag/measure needs the cells attached).
- Hub (2 items) and order-details (ScrollView, no FlatList) left untouched.
- admin-web uses its own non-virtualized MyFlatList (plain map); the RN
virtualization props do not exist there.
[2026-11-01 19:59:28 IST] admin-ui: apply the shared FlatList virtualization preset to every list page.
Every MyFlatList / FlatList / DraggableFlatList in apps/admin-ui now spreads
ADMIN_LIST_VIRTUALIZATION: initialNumToRender 10 (RN default, so initial test
fixtures stay mounted), maxToRenderPerBatch 6, windowSize 3, updateCellsBatching
Period 50, removeClippedSubviews false. RN's default windowSize is 21, so each
list keeps roughly a seventh of the off-screen rows it used to.
--- apps/admin-ui/src/lib/list-virtualization.ts (new)
+ one shared preset object.
~ app/(drawer)/dashboard/manage-orders/orders/index.tsx
~ app/(drawer)/dashboard/manage-orders/delivery-sequences/index.tsx
~ app/(drawer)/dashboard/manage-orders/index.tsx
~ app/(drawer)/dashboard/complaints/index.tsx
~ app/(drawer)/dashboard/coupons/index.tsx (two lists)
~ app/(drawer)/dashboard/product-tags/index.tsx
~ app/(drawer)/dashboard/products/index.tsx
~ app/(drawer)/dashboard/rebalance-orders/index.tsx (two lists)
~ app/(drawer)/dashboard/slots/index.tsx (two lists)
~ app/(drawer)/dashboard/stores/index.tsx
~ app/(drawer)/dashboard/user-management/index.tsx
~ app/(drawer)/dashboard/prices-overview/index.tsx
~ app/(drawer)/dashboard/customize-app/all-items-order.tsx
~ app/(drawer)/dashboard/customize-app/popular-items.tsx
~ app/(drawer)/dashboard/product-tags/order.tsx
~ src/components/CouponForm.tsx
~ src/components/TagForm.tsx
- admin-web uses the non-virtualized web MyFlatList; unchanged.
[2026-11-02 08:01:30 IST] flash-delivery: move tab/search selection out of the page component so a tab tap stops re-rendering the whole screen.
The page held selectedTagId, selectedStoreId, searchQuery and both visible
counts in FlashDeliveryProducts. A tap re-rendered the page, both strips, both
grids and every ProductCard (ProductCard is not memoized and renderProduct
built a new onPress per render). Tabs also rendered twice per tap: the
visible-count reset lived in a useEffect that ran after paint.
--- apps/user-ui/src/store/flashTabStore.ts (new)
+ selectedTagId / selectedStoreId / searchQuery plus selectTag, selectStore,
setSearchQuery, resetFlashTabs. select* are same-value no-ops (same guard as
homeTagStore) so re-tapping the active tab does not wake subscribers.
--- apps/web-ui/src/lib/stores/flash-tab-store.ts (new)
+ mirror of the native store (same shape, same reset).
--- apps/user-ui/components/SlotSpecificView.tsx
~ FlashDeliveryProducts now only derives the catalog: one memo builds
tagTabs, storeTabs, per-tag rows (productsByTagId) and per-store rows
(productsByStoreId), plus the stable tab item arrays.
~ New FlashSearchBar subscribes to the store, so typing no longer re-renders
the page, the strips or the other grid.
~ New FlashTagStrip / FlashStoreStrip wrappers subscribe to the store and
derive activeId themselves; FlashTabStrip keeps its memo and now receives
stable items/onSelect, so it no longer rebuilds on every keystroke.
~ New FlashTagSection / FlashStoreSection (memo) subscribe to the store, so a
tag tap re-renders only the tag grid and a store tap only the store section.
~ New FlashProductGrid owns visibleCount; the grid is keyed by active id so a
tab switch resets the page size in one render (no effect, no double paint).
A search change resets it during render with the same pattern.
~ New FlashProductItem (memo) derives its onPress from item.id; the page's
onProductPress handler is a useCallback.
--- apps/user-ui/components/ProductCard.tsx
~ default export wrapped in React.memo; parents pass stable item/onPress.
--- apps/user-ui/app/(drawer)/(tabs)/flash-delivery/(products)/index.tsx
~ handleProductPress wrapped in useCallback (it was recreated every render,
which defeated memoisation on every card).
--- apps/user-ui/src/lib/region-switch.ts, apps/web-ui/src/lib/region-switch.ts
~ resetFlashTabs() on region switch: tag/store ids are region-scoped.
--- apps/user-ui/tests/helpers/reset.ts
~ reset the flash tab store between cases.
--- apps/web-ui/src/routes/flash.tsx
~ same restructure: store-backed selection/search, memoized
FlashTagStrip / FlashStoreStrip / FlashProductGrid / FlashProductItem,
CompactProductCard wrapped in memo with a stable handleAddToCart.
- Flash grids are still plain maps inside the page ScrollView (no FlatList);
virtualization left for a follow-up since the page stacks two sections.
--- apps/user-ui/tests/lib/stores.test.ts
+ STORE-23: re-selecting the active flash tag/store keeps the store identity.
+ STORE-24: resetFlashTabs drops both selections and the search box.
+ STORE-25: an unchanged flash search query keeps the store identity.
--- apps/user-ui/JEST-TEST-CASES.md
~ catalogue rows STORE-23..25 added.
[2026-11-02 20:03:22 IST] home: fix the true-positive React Doctor findings (report in apps/user-ui/REACT-DOCTOR-HOME.md).
--- apps/user-ui/hooks/useHomeCatalog.ts (new)
+ One hook owns the catalogue derivation that used to sit inside Dashboard:
useAllProducts + slot helpers, the products/productsByTagId memo, the
out-of-stock sort (still an effect so the reset keeps its old timing), the
displayed count and the Show More page size (21).
+ The sort effect now lists getQuickestSlot and isSlotsLoaded in its deps
(react-doctor/exhaustive-deps, index.tsx:587). Safe: getQuickestSlot is
useCallback-memoized on [slots, productSlotsMap] and the effect writes only
displayed count state, so it cannot self-trigger.
+ hasMore is derived (visibleCount < displayedProducts.length) instead of state,
and showMore is a pure updater, removing the nested setHasMore() call inside
setVisibleCount (react-doctor/no-impure-state-updater,
no-side-effect-in-state-updater-function).
--- apps/user-ui/app/(drawer)/(tabs)/home/index.tsx
~ Dashboard calls useHomeCatalog(); the catalogue memo, sort effect, both
catalogue states and handleShowMore moved out (~75 lines). Behaviour, testIDs
and the HOME_* virtualization props unchanged.
~ New SectionHeading component shared by SlotsSection and AllProductsTitle,
which repeated the same 9-line heading (duplicate-jsx-subtree).
--- apps/user-ui/app/(drawer)/(tabs)/home/search-results/index.tsx
~ New memoized SearchResultItem owns its onPress (derived from item.id) and the
screen passes a stable handleProductPress, so the inline handler no longer
defeats ProductCard's memo (rn-list-callback-per-row).
- Left as-is, with reasons in the report: the tag strip is a ScrollView on
purpose (rn-no-scrollview-mapped-list), totalAmount is a string from
useLocalSearchParams (rn-no-falsy-and-render), root lock files need a
package-manager decision (expo-lockfile).
~ ShowMoreFooter is now a memo component rendered as ListFooterComponent,
instead of a useMemo built before the loading/error early returns
(rerender-memo-before-early-return).
~ search-results: allProducts is memoised on productsData so the Fuse memo has a
stable dependency (react-hooks/exhaustive-deps).
- Re-scan after the fixes: 11 -> 3 findings. The 3 left are the documented false
positives (tag-strip ScrollView, string totalAmount) and the root lockfile
decision.
[2026-11-02 20:32:28 IST] user-ui tests: stop jest-expo's expo-file-system mock from replacing the shared native shim.
Running the suite gave 943 failures: every rendered screen died with
"Font.isLoaded is not a function" / "type is invalid ... got undefined".
Cause: jest-expo's preset (setupFiles) calls jest.mock('expo-file-system',
factory). jest.mock is keyed by the *resolved path*, and jest.config.js maps
^expo-file-system$ at mocks/native/common.tsx — the same file used for expo-font,
expo-image, expo-linear-gradient, react-native-safe-area-context and friends.
The preset's factory therefore replaced that whole module, so every import of
those packages received expo-file-system's exports. Unrelated to any app code.
--- apps/user-ui/tests/mocks/native/file-system.ts (new)
+ dedicated expo-file-system shim (documentDirectory, getInfoAsync,
readAsStringAsync, writeAsStringAsync, deleteAsync + the preset's extra names).
--- apps/user-ui/tests/jest.config.js
~ ^expo-file-system$ now maps to the dedicated shim instead of common.tsx.
--- apps/user-ui/tests/setup.ts
~ jest.mock('expo-file-system', () => require('./mocks/native/file-system'))
after the preset's registration, so the factory is ours.
--- apps/user-ui/tests/mocks/native/common.tsx
- expo-file-system exports removed (single source of truth; nothing else used them).
~ Correction: the dedicated shim is NOT added to moduleNameMapper. Mapping
^expo-file-system$ at it would make setup.ts's jest.mock factory require the
mocked path itself (infinite recursion → "Maximum call stack size exceeded").
Instead the mapper line is removed and setup.ts overrides the preset's
factory with require('./mocks/native/file-system'), which resolves to an
unmocked file.
- Full suite after the harness fix: 5 failed / 1211 passed (54 suites, 50 pass).
The 5 are the known pre-existing ones: REGION-31, AUTH-04, AUTH-19, CART-09,
HOME-119. Flash (index/products/checkout) and the new STORE-23..25 pass.
[2026-11-02 21:34:40 IST] remove the vendor-snippets feature end to end.
Vendor snippets (the "ils" / vendor_snippets table: a snippet code that grants a
vendor a slot-scoped order list and package marking) are being retired. All
screens, APIs, types and the table go with it. db_helper_postgres is left alone
(abandoned per AGENTS.md).
--- packages/db_helper_sqlite/src/db/schema.ts
- vendorSnippets table, vendorSnippetsRelations, and the deliverySlotInfo
vendorSnippets relation.
--- packages/db_helper_sqlite/src/admin-apis/vendor-snippets.ts (deleted)
--- packages/db_helper_sqlite/index.ts
- Vendor Snippets export block.
--- packages/db_helper_sqlite/src/admin-apis/slots.ts
- snippet imports, mapVendorSnippet, the vendorSnippets relation on slot detail,
the snippet create/update loop and createdSnippets in the result.
--- packages/db_helper_sqlite/src/admin-apis/product.ts
- unused vendorSnippets schema import.
--- packages/shared/types/admin.ts
- every AdminVendorSnippet* type, SlotSnippetInput, and the snippet fields on the
slot result types.
--- apps/backend/src/trpc/apis/admin-apis/apis/vendor-snippets.ts (deleted)
--- apps/backend/src/trpc/apis/admin-apis/apis/admin-trpc-index.ts
- vendorSnippets router registration.
--- apps/backend/src/trpc/apis/admin-apis/apis/slots.ts
- vendorSnippets from both slot input schemas and the create/update/detail
mapping, including the vendor accessUrl.
--- apps/backend/src/dbService.ts, apps/backend/src/sqliteImporter.ts
- vendor-snippet type/function re-exports.
--- apps/admin-ui
- vendor-snippets screen, VendorSnippetForm, SnippetMenu, SnippetOrdersView,
types/vendor-snippets.ts, ProductListDialog (only the snippet screen used it),
the drawer/stack entries, the SlotForm snippet editor and the slot-details
snippet section.
--- apps/admin-web
- mirror of the above: route, components, types, SlotForm/SlotForm detail,
dashboard nav, routeTree.gen.ts entries.
--- apps/fallback-ui
- vendor-order-list route, its router registration and the sidebar entry, plus
the order-details link that opened it.
--- apps/backend/scripts/remove-test-data.ts, scripts/clear-db*.sql,
tests/e2e/basic-sanity-setup.sh
- vendor_snippets / vendorSnippets cleanup statements.
--- docs/test-cases/vendor-snippets.md (deleted), docs/test-cases/README.md,
apps/admin-ui/JEST-TEST-CASES.md
- catalogue rows for the removed screens/tests.
--- packages/db_helper_sqlite/drizzle/0007_drop_vendor_snippets.sql (new)
+ drops vendor_snippets and the legacy ils table. Not executed here.
- Historical test reports under docs/test reports/ are left as written records.
--- apps/admin-ui/tests
- deleted the four vendor-snippet suites and product-list-dialog.test.tsx;
slot-details/slot-form/slot-edit/slot-add/drawer/fixtures/mocks trimmed to the
remaining behaviour.
--- apps/backend/tests
- deleted admin-vendor.test.ts; removed snippet setup and ISO-08 from isolation,
the snippet branch of CACHE-76, the vendor rows in the auth matrix, the
snippet assertions in admin-slots, and createdSnippets from the unit mock.
--- docs (active)
- removed docs/test-cases/vendor-snippets.md and its references (README,
fallback-legacy-pages, scheduled-slots, authorization, staff-authentication);
cleaned admin-ui/backend case catalogues, the validation plan + manual guide,
admin-ui-vs-admin-web parity and the e2e sanity plan. Historical reports
under docs/test reports/ are untouched.
- `packages/db_helper_sqlite/drizzle/meta/_journal.json` gained the 0007 entry.
[2026-11-05 22:24:32 IST] flash delivery now switches off at 8:30 PM IST instead of 9:30 PM IST.
15:00 UTC is 20:30 IST; the on-time (0 1 * * *, 06:30 IST) and the archive
cron (30 20 * * *) are unchanged. The Cloudflare trigger in wrangler.prod.toml
is the source of truth for the schedule, so it moves with the constant in the
job itself.
--- apps/backend/src/lib/flash-delivery-cron.ts
-const CRON_TURN_OFF_FLASH_DELIVERY = '0 16 * * *' // 9:30 PM IST
+const CRON_TURN_OFF_FLASH_DELIVERY = '0 15 * * *' // 8:30 PM IST
--- apps/backend/wrangler.prod.toml
-crons = ["0 16 * * *", "0 1 * * *", "30 20 * * *"]
+crons = ["0 15 * * *", "0 1 * * *", "30 20 * * *"]
[2026-11-05 22:40:37 IST] add a backend kill switch for the in-app update dialog.
The force-update dialog (apps/user-ui/components/UpdateChecker.tsx) is now gated
by `isUpdatePromptEnabled`, returned per request by `common.essentialConsts`.
It is a hardcoded literal in the router, deliberately NOT in the constants
tables or the per-bound KV cache, so flipping it is a one-line change plus a
deploy. Currently `false`: no prompt even when the build is behind
`internalAppVersion`. The client only prompts when the flag is explicitly
`true`, so an older payload or a persisted snapshot cannot flash the dialog.
--- apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
return {
...response,
webviewHtml: shouldShowNotice ? updateNotice : null,
isWebviewClosable: shouldShowNotice ? false : true,
+ // Kill switch for the in-app "Update available" dialog (UpdateChecker in
+ // apps/user-ui). Hardcoded on purpose and computed per request, so it can
+ // be flipped and deployed without touching the constants tables or waiting
+ // for the per-bound KV cache to rebuild: `false` means users are never
+ // asked to restart, even when their build is behind `internalAppVersion`.
+ isUpdatePromptEnabled: false,
};
--- apps/user-ui/components/UpdateChecker.tsx
const remoteVersion = data?.internalAppVersion;
if (typeof remoteVersion !== 'number') return;
+ // Backend kill switch: only prompt when the backend explicitly enables it.
+ // A missing field (older payload, or a persisted snapshot from before the
+ // flag existed) also suppresses the prompt, so a stale cache cannot flash
+ // the dialog before the fresh payload arrives.
+ if (data?.isUpdatePromptEnabled !== true) return;
if (constants.INTERNAL_APP_VERSION >= remoteVersion) return;
--- apps/user-ui/tests/fixtures/index.ts
internalAppVersion: 2,
+ isUpdatePromptEnabled: true,
--- apps/user-ui/tests/app/root-layout.test.tsx
+ it('ROOT-30: a disabled backend flag suppresses the update prompt', ...)
--- apps/backend/tests/helpers/cache.ts
webviewHtml?: string | null
isWebviewClosable?: boolean
+ isUpdatePromptEnabled?: boolean
--- apps/backend/tests/api/cache-consts.test.ts
+ it('CACHE-117: isUpdatePromptEnabled is a boolean', ...)
--- apps/user-ui/JEST-TEST-CASES.md, apps/backend/API-TEST-CASES.md
- CONSTS fixture row + ROOT-30 row; CACHE-117 row.
[2026-11-05 22:45:31 IST] the update-dialog flag becomes an object: enabled + closable.
`common.essentialConsts` now returns `updatePrompt: { isEnabled, isClosable }`
instead of the scalar `isUpdatePromptEnabled`. `isEnabled: false` still means the
dialog is never shown (the current state). When it is enabled, `isClosable: true`
renders a "Later" button and lets Android back/outside-tap dismiss the alert;
`isClosable: false` keeps the single-button hard gate. Still a hardcoded literal
computed per request (not in the per-bound KV cache), so flipping it is one line
plus a deploy.
--- apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
- // Kill switch for the in-app "Update available" dialog (UpdateChecker in
- // apps/user-ui). Hardcoded on purpose and computed per request, so it can
- // be flipped and deployed without touching the constants tables or waiting
- // for the per-bound KV cache to rebuild: `false` means users are never
- // asked to restart, even when their build is behind `internalAppVersion`.
- isUpdatePromptEnabled: false,
+ // Kill switch + close behaviour for the in-app "Update available" dialog
+ // (UpdateChecker in apps/user-ui). Hardcoded on purpose and computed per
+ // request, so it can be flipped and deployed without touching the
+ // constants tables or waiting for the per-bound KV cache to rebuild.
+ updatePrompt: {
+ isEnabled: false,
+ isClosable: true,
+ },
--- apps/user-ui/components/UpdateChecker.tsx
- if (data?.isUpdatePromptEnabled !== true) return;
+ const prompt = data?.updatePrompt;
+ if (prompt?.isEnabled !== true) return;
...
- Alert.alert('Update available', '...Please restart to continue.', [one button], { cancelable: false })
+ const isClosable = prompt?.isClosable === true;
+ Alert.alert(
+ 'Update available',
+ isClosable ? '... Update now, or continue and restart later.' : '... Please restart to continue.',
+ isClosable
+ ? [{ text: 'Later', style: 'cancel' }, { text: 'Update & Restart', onPress: applyUpdate }]
+ : [{ text: 'Update & Restart', onPress: applyUpdate }],
+ { cancelable: isClosable }
+ );
--- apps/user-ui/tests/fixtures/index.ts
- isUpdatePromptEnabled: true,
+ updatePrompt: { isEnabled: true, isClosable: false },
--- apps/user-ui/tests/app/root-layout.test.tsx
- ROOT-30 uses updatePrompt: { isEnabled: false, isClosable: false }
+ ROOT-31 (new): isClosable:true shows "Later", cancelable alert, no fetch on Later
--- apps/backend/tests/helpers/cache.ts
- isUpdatePromptEnabled?: boolean
+ updatePrompt?: { isEnabled: boolean; isClosable: boolean }
--- apps/backend/tests/api/cache-consts.test.ts
- CACHE-117 asserts typeof === 'boolean'
+ CACHE-117 asserts the updatePrompt object shape
--- apps/user-ui/JEST-TEST-CASES.md, apps/backend/API-TEST-CASES.md
- CONSTS fixture row, ROOT-30/ROOT-31 rows, CACHE-117 row.
[2026-11-05 23:14:54 IST] fix `bun run pull_db`: split the dump into schema + data before replaying.
`wrangler d1 export` writes tables in sqlite_master rowid (historical creation)
order, so a child table is created and populated before its parent exists
(`notif_creds`/`unlogged_user_tokens` -> `regions`, `product_skus` ->
`product_info`). Local D1 pins foreign_keys=ON and runs the file as one
transaction, so neither `PRAGMA foreign_keys=OFF` (a no-op, verified: the pragma
still reads 1) nor the dump's own `defer_foreign_keys` prevents
`no such table: main.regions`. `CREATE TABLE` may reference a missing parent, so
replaying every CREATE first and every INSERT second makes the import
order-independent.
`populate_localdb.sh` now splits dumps/latest.sql into .wrangler/pull/schema.sql
and .wrangler/pull/data.sql (gitignored by the existing `**/.wrangler/*` rule)
and executes them in that order. `package.json` is unchanged, so `bun run pull_db`
is still the one command (and `pull_dev_db` benefits from the same fix).
--- apps/backend/scripts/populate_localdb.sh
-wrangler d1 execute "$DB_NAME" --local --file "$DUMP_FILE" --config "$WRANGLER_CONFIG"
+mkdir -p "$SPLIT_DIR"
+# ... awk splitter: CREATE/PRAGMA -> schema.sql, everything else -> data.sql
+wrangler d1 execute "$DB_NAME" --local --file "$SCHEMA_FILE" --config "$WRANGLER_CONFIG"
+wrangler d1 execute "$DB_NAME" --local --file "$DATA_FILE" --config "$WRANGLER_CONFIG"
--- apps/backend/wrangler-commands.md
- "How to hand-fix" (cut/paste the parent block above the child) is now automated
+ by populate_localdb.sh; kept the way to verify a dump by hand.
Follow-up on the same change: the data pass also needs deferred FK checks.
The dump's row order is not FK-safe (child rows can precede their parent rows),
and D1 enforces FKs per statement, which surfaced as
`FOREIGN KEY constraint failed: SQLITE_CONSTRAINT` only after the schema split
was in place. populate_localdb.sh now writes `PRAGMA defer_foreign_keys=TRUE;`
at the top of .wrangler/pull/data.sql as well; enforcement then happens once at
COMMIT and `PRAGMA foreign_key_check` is clean on the imported DB.
[2026-11-05 23:22:25 IST] never fire the update prompt from the persisted snapshot.
useGetEssentialConsts rehydrates the last cached payload as React Query
`placeholderData` before the network call resolves, so on launch the effect can
see an older `updatePrompt.isEnabled: true` while the fresh (correct) `false`
arrives a moment later. The alert had already been raised by then and cannot be
dismissed programmatically. UpdateChecker now ignores placeholder data entirely
and only decides from the resolved response. Also removed a leftover debug
`console.log({ consts: data })`.
--- apps/user-ui/components/UpdateChecker.tsx
- const { data } = useGetEssentialConsts();
+ const { data, isPlaceholderData } = useGetEssentialConsts();
- console.log({consts: data})
useEffect(() => {
if (prompted.current) return;
+ // The hook rehydrates the last persisted payload as placeholder data before
+ // the network call resolves; that snapshot can predate an `isEnabled: false`
+ // flip, so never decide from it.
+ if (isPlaceholderData) return;
const remoteVersion = data?.internalAppVersion;
- }, [data]);
+ }, [data, isPlaceholderData]);
--- apps/user-ui/tests/app/root-layout.test.tsx
+ ROOT-32: a seeded stale snapshot (isEnabled:true) with a pending query shows no alert.
--- apps/user-ui/JEST-TEST-CASES.md
+ ROOT-32 row.
[2026-11-05 23:25:16 IST] the update prompt uses the app's BottomDialog at 40% height.
Replaced the native `Alert.alert` with `BottomDialog` (common-ui) sized to 40%
of the window height, so it matches the rest of the app (handle, slide-up,
scrollable body) and can carry real buttons. `enableDismiss` follows
`updatePrompt.isClosable` (backdrop tap + Android back only when closable);
the closable variant renders a "Later" button, the hard gate renders only
"Update & Restart". "Updating…" disables the button while fetch/reload runs.
--- apps/user-ui/components/UpdateChecker.tsx
-import { Alert } from 'react-native';
+import { useWindowDimensions, View } from 'react-native';
+import { BottomDialog, MyButton, MyText, tw } from 'common-ui';
- const prompted = useRef(false);
+ const [prompt, setPrompt] = useState<{ isClosable: boolean } | null>(null);
+ const [isUpdating, setIsUpdating] = useState(false);
- Alert.alert('Update available', message, [buttons], { cancelable: isClosable });
+ setPrompt({ isClosable: updatePrompt.isClosable === true });
+ ...
+ <BottomDialog open={prompt !== null} onClose={handleClose} enableDismiss={isClosable}>
+ <View testID="update-dialog" style={{ height: Math.round(height * 0.4) }}> ... </View>
+ </BottomDialog>
--- apps/user-ui/tests/app/root-layout.test.tsx
- ROOT-16/17/30/31/32 now assert the rendered dialog (testIDs update-dialog,
update-later, update-restart) instead of spying on Alert.alert.
--- apps/user-ui/JEST-TEST-CASES.md
- ROOT-16/17/31 wording updated from "alert" to "bottom dialog".
[2026-11-05 23:30:12 IST] every update prompt now honours `updatePrompt.isEnabled`.
The dialog still shown with `isEnabled: false` was not UpdateChecker: it was
HealthTestWrapper's store-version gate (`versionNum` vs `Constants.expoConfig
.version`, rendered `enableDismiss={false}` so it cannot be closed). That gate
never read the new switch. WebViewWrapper was a third surface (host-gated
`webviewHtml`) that also ignored it.
--- apps/user-ui/components/HealthTestWrapper.tsx
- const { data: backendConsts } = useGetEssentialConsts();
+ const { data: backendConsts, isPlaceholderData } = useGetEssentialConsts();
+ const updatePrompt = backendConsts?.updatePrompt;
+ const isUpdatePromptEnabled = updatePrompt?.isEnabled === true;
+ const isUpdatePromptClosable = updatePrompt?.isClosable === true;
useEffect(() => {
+ // Same switch as UpdateChecker, and never from the persisted placeholder.
+ if (isPlaceholderData) return;
+ if (!isUpdatePromptEnabled) return;
...
- }, [versionFromBackend]);
+ }, [versionFromBackend, isPlaceholderData, isUpdatePromptEnabled]);
- <BottomDialog open={showUpdateDialog} onClose={...} enableDismiss={false}>
+ <BottomDialog open={showUpdateDialog} onClose={...} enableDismiss={isUpdatePromptClosable}>
+ {isUpdatePromptClosable && <Later button that closes the dialog>}
--- apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
const updatePrompt = { isEnabled: false, isClosable: true }
- const shouldShowNotice = host.includes('raw') || host.includes('mf')
+ const shouldShowNotice = updatePrompt.isEnabled && (host.includes('raw') || host.includes('mf'))
return {
webviewHtml: shouldShowNotice ? updateNotice : null,
- isWebviewClosable: shouldShowNotice ? false : true,
+ isWebviewClosable: shouldShowNotice ? updatePrompt.isClosable : true,
updatePrompt,
}
--- apps/user-ui/tests/app/root-layout.test.tsx
+ ROOT-33: versionNum ahead but updatePrompt.isEnabled:false -> no store dialog.
+ ROOT-34: closable store dialog renders Later and dismisses.
--- apps/user-ui/JEST-TEST-CASES.md
+ ROOT-33/ROOT-34 rows; ROOT-05/06 note the switch.
[2026-11-08 15:47:34 IST] cart add-address: fix the invisible touch-blocking layer after a successful save (ported from neo-region).
On iOS, a Modal dismissed while another Modal is presenting/dismissing can leave
an empty native layer that swallows every touch (react-native#50152). The cart's
add-address form is already inside RawBottomDialog/CartAddressGate's Modal, and
AddressForm rendered its submit loader as a second Modal (LoadingDialog), then
closed that loader and the host sheet in quick succession. After saving, the
cart looked frozen.
--- apps/user-ui/src/components/AddressForm.tsx
- submit <LoadingDialog> (nested Modal)
+ inline absolute-fill overlay with the same spinner + message inside the form's
KeyboardAvoidingView; no second native modal to leave behind
[2026-11-10 17:22:58 IST] admin orders: record packaging time and delivery time.
Both columns already exist on the SQLite schema (order_items.packaged_at from
migration 0004/0005, orders.delivered_at from 0005) and were never written. No
new migration is needed; this wires the writes and surfaces the values in the
admin order-details screens (RN admin-ui + web admin-web).
--- packages/db_helper_sqlite/src/lib/date.ts
+ export function nullableDate(value: Date | null | undefined): Date | null
(timestampText's fromDriver maps NULL to new Date(0); treat epoch as null)
--- packages/db_helper_sqlite/src/admin-apis/order.ts
updateOrderPackaged:
- .set({ is_packaged: isPackaged })
+ isPackaged true -> { is_packaged: true, packagedAt: COALESCE(packaged_at, now) }
+ isPackaged false -> { is_packaged: false, packagedAt: null }
+ !isPackaged also clears orders.deliveredAt (it already reset isDelivered)
updateOrderDelivered:
+ stamps orders.deliveredAt = now on the first delivered=true, keeps it on repeat
+ calls, and clears it on delivered=false
updateOrderItemPackaging:
+ isPackaged true -> packaged_at = existing ?? now
+ isPackaged false -> packaged_at = null
getOrderDetails:
+ deliveredAt (order) and packagedAt (per item), epoch-as-null
--- packages/db_helper_sqlite/src/lib/order-items-archive.ts
- packagedAt: row.packagedAt ? row.packagedAt.toISOString() : null
+ packagedAt: nullableDate(row.packagedAt)?.toISOString() ?? null
(an unset timestamp was archived as 1970-01-01T00:00:00.000Z)
--- packages/shared/types/admin.ts
+ AdminOrderDetails.deliveredAt: Date | null
+ AdminOrderDetailsItem.packagedAt: Date | null
--- apps/admin-ui/app/(drawer)/dashboard/manage-orders/order-details/[id].tsx
+ testID "order-delivered-at" row in the header when order.deliveredAt
+ testID `order-item-packaged-at-<id>` under each item when item.packagedAt
--- apps/admin-web/src/routes/dashboard.orders.$id.tsx
+ same two blocks (web counterpart)
--- apps/backend/tests/api/admin-order.test.ts
+ AORD-13: asserts packagedAt is stamped then cleared on un-pack
+ AORD-16: asserts deliveredAt is stamped then cleared on un-deliver
+ AORD-18: asserts the per-item packagedAt follows the Packaged toggle
--- apps/admin-ui/tests/fixtures/index.ts
+ deliveredAt / packagedAt on ORDER_DETAILS and its items
--- apps/admin-ui/tests/pages/order-details.test.tsx
+ AOD-26: delivered timestamp renders when order.deliveredAt is set
+ AOD-27: no delivered timestamp before delivery
+ AOD-28: per-item packed timestamp renders only when packagedAt is set
[2026-11-14 11:21:51 IST] intrv.java: print numbers 1 to 10 using Java streams.
--- intrv.java (new)
+ class intrv with static printOneToTen() using IntStream.rangeClosed(1, 10).forEach(System.out::println)
+ main() invoking printOneToTen()
[2026-11-14 11:27:23 IST] intrv.java: extract company name before the first hyphen.
--- intrv.java
+ import java.util.Arrays
+ static String extractCompany(String input): null/blank guard, input.split("-", 2)[0].trim()
+ static String extractCompanyStream(String input): Arrays.stream(input.split("-", 2)).findFirst().orElse("")
~ main() now also demos both on "Infosys-Interview 2028"
[2026-11-14 11:27:53 IST] intrv.java: company extraction now stream-only.
--- intrv.java
- remove non-stream extractCompany
~ extractCompanyStream renamed to extractCompany; body is a single Arrays.stream(...).findFirst().orElse("") pipeline
~ main() calls extractCompany only
[2026-11-14 11:58:07 IST] intrv.java: extractCompany rewritten with an enhanced for loop.
--- intrv.java
~ extractCompany: drop Arrays.stream/split pipeline; split once and walk the
segments with a `for (String part : parts)` loop, returning the first non-blank
trimmed segment ("" when none)
- drop now-unused `import java.util.Arrays` (IntStream import stays for printOneToTen)
[2026-11-14 21:20:45 IST] perf: Promise.all for verified-independent sequential awaits.
Read-only waterfalls and independent storage/refetch pairs that the audit
found. No ordering-dependent pair was changed (validate->write, write->read,
mutate->refetch, fetch->reload stay sequential).
--- apps/backend/src/stores/product-store.ts
initializeProducts: 5 cache reads -> one Promise.all
- const productsData = await getAllProductsForCache(regionId)
- const allStores = await getAllStoresForCache(regionId)
- const allDeliverySlots = await getAllDeliverySlotsForCache(regionId)
- const allSpecialDeals = await getAllSpecialDealsForCache(regionId)
- const allProductTags = await getAllProductTagsForCache(regionId)
+ const [productsData, allStores, allDeliverySlots, allSpecialDeals, allProductTags] =
+ await Promise.all([...same five calls...])
getAllProducts: 6 cache reads -> one Promise.all (adds getAllProductCombosForCache)
--- apps/backend/src/stores/product-tag-store.ts
- const tagsData = await getAllTagsForCache(regionId)
- const productTagsData = await getAllTagProductMappings(regionId)
+ const [tagsData, productTagsData] = await Promise.all([
+ getAllTagsForCache(regionId),
+ getAllTagProductMappings(regionId),
+ ])
--- apps/backend/src/stores/user-negativity-store.ts
loop of per-user awaits -> Promise.all over userIds, then fill the record.
--- apps/backend/src/trpc/apis/admin-apis/apis/user.ts
getAllUsers: order counts / last orders / suspension -> Promise.all
getUserDetails: suspension + orders -> Promise.all; statuses + item counts -> Promise.all
getUsersForNotification: searchUsers + getAllNotifCreds -> Promise.all
sendNotification: logged-in + unlogged tokens -> Promise.all
--- apps/backend/src/trpc/apis/user-apis/apis/order.ts
- const totalCount = await getUserOrderCount(userId);
- const userOrders = await getUserOrdersWithRelations(userId, offset, pageSize);
+ const [totalCount, userOrders] = await Promise.all([...])
--- apps/backend/src/trpc/apis/admin-apis/apis/product.ts
claimUploadUrls + scheduleStoreInitialization -> Promise.all at 4 sites
(create product, update product, create tag, update tag). create/update and
replaceTagProducts stay before the batch because the cache rebuild reads them.
--- apps/user-ui/src/contexts/AuthContext.tsx
saveAuthToken + saveUserId -> Promise.all (3 sites: loginWithToken/login/register)
--- apps/admin-ui/components/context/staff-auth-context.tsx
saveJWT + saveStaff, deleteJWT + deleteStaff -> Promise.all
--- apps/admin-ui/app/(drawer)/dashboard/products/edit.tsx
--- apps/admin-web/src/routes/dashboard.products.edit.tsx
refetch() + refetchProducts() -> Promise.all (2 sites each; web counterpart)
--- apps/user-ui/components/ProductDetail.tsx
onRefresh: refetch() + loadReviews(true) -> Promise.all
--- apps/user-ui/src/components/PendingAddressSync.tsx
clearPendingAddress + getUserAddresses/getDefaultAddress invalidations -> Promise.all
(the createAddress mutation still completes first)
Skipped on purpose:
- write -> scheduleStoreInitialization pairs (store/banner/global-store CRUD):
single enqueue after commit, negligible gain.
- cloud_cache version bumpers: independent but D1 serializes writes anyway.
- per-region loops (createAllCacheFiles, initializeAllStores, gen-store,
flash cron): deliberate batching, not a missed parallel await.
- getAuthToken + getCurrentUserId (AuthContext:70): getCurrentUserId re-reads
the token; needs a refactor, not Promise.all.
[2026-11-16 00:36:38 IST] refactor catalogue: the central product store is the single
source of product data (native + web).
Catalogue screens used to call useAllProducts() themselves — 6 hook instances in
user-ui, 10 in web-ui — each rebuilding the merged products array, while cart,
checkout and billing already read useCentralProductStore. The store now owns the
whole catalogue snapshot (products, tags, loading, error, refetch) and every
catalogue screen reads it.
--- packages/shared/types/app-common.types.ts
CentralProductState<Product> -> CentralProductState<Product, Tag = unknown>
+ tags: Tag[]
+ isLoading: boolean
+ error: unknown | null
+ setTags(tags)
+ setCatalogMeta({ isLoading?, error? })
(second generic defaulted to unknown, so existing CentralProductState<Product>
references still compile)
--- apps/user-ui/src/store/centralProductStore.ts
initial state: tags [], isLoading true (cold start must not flash the empty
catalogue), error null
+ useInitializeCentralProductStore publishes products + tags in one effect and
mirrors the query's isLoading / error into the store; products are never
cleared when data is undefined (a version bump or a failed refresh keeps the
last good catalogue, matching keepPreviousData)
--- apps/user-ui/src/lib/region-switch.ts
+ clears tags alongside products when the region switches
--- apps/user-ui/hooks/useHomeCatalog.ts
- const { data: productsData, isLoading, error } = useAllProducts()
+ products / tags / isLoading / error from useCentralProductStore
(return shape unchanged, so home/index.tsx needs no edit)
--- apps/user-ui/app/(drawer)/(tabs)/home/search-results/index.tsx
products / isLoading / error from the store; manual refresh and the focus
refetcher call the store's refetchProducts
--- apps/user-ui/app/(drawer)/(tabs)/order-again/index.tsx
same swap (Offers tab: combos and isOffer rows)
--- apps/user-ui/app/(drawer)/(tabs)/stores/store-detail/[id].tsx
- const { data: productsData, isLoading: isProductsLoading } = useAllProducts()
- const productById = useMemo(...) // a second copy of the store's map
+ productsById / isLoading from useCentralProductStore
--- apps/user-ui/components/SlotSpecificView.tsx
FlashDeliveryProducts: products, tags, isLoading, error and refetchProducts
from the store. SlotProducts in the same file already did.
--- apps/user-ui/tests/helpers/test-utils.tsx
+ renderWithProviders({ withProductStore }) mounts the real producer
(useInitializeCentralProductStore) so page tests keep driving the catalogue
through the mocked products JSON instead of seeding the store by hand
+ seedCentralStores seeds tags (TAGS fixture) and a refetchProducts stub
--- apps/user-ui/tests/helpers/reset.ts
+ resets tags / isLoading / error
--- apps/user-ui/tests/pages/{home,flash-products,offers,search-results,store-detail}.test.tsx
render helpers opt into withProductStore
--- apps/web-ui
central-product-store + usePopulateCentralProductStore carry the same state;
home.index / home.search / offers / stores.$storeId / flash read it
(home.index, stores.$storeId and flash now also mount the product populator)
+ tests/lib/use-region.test.tsx: the five Home renders opt into
withProductStore so the region's products document is still fetched and the
"only this region's catalogue is requested" assertions stay meaningful
+ home.test.tsx: HOME-02/03 seed an empty catalogue (cold start); HOME-58..61
assert the products document refetch instead of a store spy (the producer
owns refetchProducts now); HOME-96/97 patch productsById after mount, since
the producer seeds the store on its first effect
+ flash-products FLASH-02 / search-results SEARCH-14 seed an empty catalogue
for the first-load failure copy
[2026-11-16 00:52:09 IST] catalogue: show the coupon price on product cards and the
product detail screen.
Product-specific coupons (coupons.sku_ids non-empty) already reach the client via
user.coupon.getEligible, which cart/checkout use. The catalogue store now carries
them too, so a card can say "₹194 with coupon" without a second request and
without any screen owning the math.
Nothing waits on it: the coupon query runs in parallel with the products document
inside the store's initializer; products render first, coupon prices fill in when
the call lands. Cart-wide coupons (no sku_ids) are ignored here — they are not a
product offer. minOrder is ignored too: it is a cart-level rule and the cart
screen already explains eligibility.
--- packages/shared/types/app-common.types.ts
+ interface ProductCouponOffer { couponId; couponCode; discountPercent; flatDiscount; maxValue }
+ CentralProductState.couponOffers: Record<skuId, ProductCouponOffer>
+ CentralProductState.setCouponOffers(offers)
(price-independent params: the catalogue card prices a regular product and the
flash card prices flashPrice, and both must use the same coupon)
--- apps/user-ui/src/lib/product-coupons.ts (new)
+ buildCouponOffers(coupons, { regionId, isFirstOrder }) -> Record<skuId, offer>
best single coupon per sku; skips region mismatch, first-order-only when the
customer already ordered, and non-targeted coupons
+ couponPriceFor(offer, unitPrice) -> number | null
round(unitPrice - computeCouponDiscount(unitPrice, offer)); null when there is
no discount (reuses the shared cart-pricing helper, so card and cart agree)
--- apps/user-ui/src/store/centralProductStore.ts
+ couponOffers state; setCouponOffers decorates products/productsById with
+ isProductCouponApply: true, couponDiscountedPrice: N
+ setProducts re-applies the offers it holds (products.json refetches every
+ minute and would otherwise drop the fields); clearing the offers strips them
+ useInitializeCentralProductStore runs user.coupon.getEligible alongside the
+ catalogue (enabled only when signed in; same query key as cart/checkout, so
+ an open cart dedupes it) and rebuilds the offers on region / first-order
+ changes and on logout
--- apps/user-ui/src/lib/region-switch.ts
+ clears couponOffers with the catalogue
--- apps/user-ui/components/ProductCard.tsx
with an offer: the price row drops to the struck price's size (text-base ->
text-xs, hero text-sm -> text-[10px]) at opacity 0.85, and a new row shows
₹discountedPrice in the brand colour with a muted "With Coupon" label.
Flash cards price the flash price; out-of-stock cards show no coupon row.
--- apps/user-ui/components/ProductDetail.tsx
+ the same coupon line under the price block (price block itself unchanged:
it carries the unit suffix, the % OFF badge and the flash price row)
--- apps/web-ui/src/lib/stores/central-product-store.ts
implements the new members with an always-empty map: web-ui has no coupon
support in its cart/checkout, so it shows no coupon price at all.
--- apps/user-ui/tests
+ tests/lib/product-coupons.test.ts (COUPON-01..15): targeting, cart-wide
exclusion, region, first-order-only, invalidated, minOrder ignored, best of
several, rounding, flash base, price guards
+ tests/lib/stores.test.ts (STORE-13..15): offers before/after the catalogue,
catalogue refresh keeps the fields, clearing the offers strips them
+ tests/components/product-card-coupon.test.tsx (PCARD-01..08): coupon row,
"With Coupon", price size == struck size, opacity 0.85, per-sku isolation,
flash base, out-of-stock
+ tests/pages/product-detail.test.tsx (PD-52..55): coupon line, no line, flash
base, out-of-stock
+ tests/fixtures: C_SKU2_FLAT / C_SKU2_MIN / C_SKU8_FLASH / C_SKU2_FIRST kept out
of `COUPONS` so the cart/checkout payloads are untouched
+ tests/helpers/reset.ts resets couponOffers
JEST-TEST-CASES.md: rows for all of the above + a seeding rule
[2026-11-16 01:04:37] debug: log the tRPC bearer token presence per request (token value not printed)
apps/admin-ui/src/trpc-client.ts
--- a/apps/admin-ui/src/trpc-client.ts
+++ b/apps/admin-ui/src/trpc-client.ts
@@ headers
headers: async () => {
const token = await getJWT();
+ console.log(
+ `[admin-ui][trpc] getJWT: ${token ? `present (${token.length} chars)` : 'MISSING'}`
+ );
return token ? { Authorization: `Bearer ${token}` } : {};
},
@@ fetch
fetch: async (url, options) => {
+ const rawHeaders: any = options?.headers;
+ const authHeader =
+ typeof rawHeaders?.get === 'function'
+ ? rawHeaders.get('authorization')
+ : rawHeaders?.Authorization ?? rawHeaders?.authorization;
+ console.log(
+ `[admin-ui][trpc] request ${String(url)} | auth: ${authHeader ? 'PRESENT' : 'MISSING'}`
+ );
const response = await fetch(url, options);
if (response.status === 401) {
+ console.log(
+ `[admin-ui][trpc] 401 ${String(url)} | auth was: ${authHeader ? 'PRESENT' : 'MISSING'}`
+ );
const data = await response.clone().json().catch(() => ({}));
apps/admin-web/src/lib/trpc-client.ts
--- a/apps/admin-web/src/lib/trpc-client.ts
+++ b/apps/admin-web/src/lib/trpc-client.ts
@@ headers
headers: async () => {
const token = await getJWT()
+ console.log(
+ `[admin-web][trpc] getJWT: ${token ? `present (${token.length} chars)` : 'MISSING'}`
+ )
return token ? { Authorization: `Bearer ${token}` } : {}
},
@@ fetch
fetch: async (url, options) => {
+ const rawHeaders: any = options?.headers
+ const authHeader =
+ typeof rawHeaders?.get === 'function'
+ ? rawHeaders.get('authorization')
+ : rawHeaders?.Authorization ?? rawHeaders?.authorization
+ console.log(
+ `[admin-web][trpc] request ${String(url)} | auth: ${authHeader ? 'PRESENT' : 'MISSING'}`
+ )
const response = await fetch(url, options)
if (response.status === 401) {
+ console.log(
+ `[admin-web][trpc] 401 ${String(url)} | auth was: ${authHeader ? 'PRESENT' : 'MISSING'}`
+ )
const data = await response.clone().json().catch(() => ({}))
[2026-11-16 01:08:09] debug: after a 401, re-probe staffUser.me with the same headers; include header length in the request log
apps/admin-ui/src/trpc-client.ts
--- a/apps/admin-ui/src/trpc-client.ts
+++ b/apps/admin-ui/src/trpc-client.ts
@@ request log
console.log(
- `[admin-ui][trpc] request ${String(url)} | auth: ${authHeader ? 'PRESENT' : 'MISSING'}`
+ `[admin-ui][trpc] request ${String(url)} | auth: ${
+ authHeader ? `PRESENT (${String(authHeader).length} chars)` : 'MISSING'
+ }`
);
@@ 401 branch
console.log(
`[admin-ui][trpc] 401 ${String(url)} | auth was: ${authHeader ? 'PRESENT' : 'MISSING'}`
);
+ try {
+ const probe = await fetch(
+ `${BASE_API_URL}/api/trpc/admin.staffUser.me?batch=1&input=%7B%7D`,
+ { method: 'GET', headers: options?.headers }
+ );
+ console.log(`[admin-ui][trpc] 401 probe (staffUser.me) -> ${probe.status}`);
+ } catch (probeError: any) {
+ console.log(
+ `[admin-ui][trpc] 401 probe failed: ${probeError?.message ?? probeError}`
+ );
+ }
const data = await response.clone().json().catch(() => ({}));
apps/admin-web/src/lib/trpc-client.ts
--- a/apps/admin-web/src/lib/trpc-client.ts
+++ b/apps/admin-web/src/lib/trpc-client.ts
@@ request log
console.log(
- `[admin-web][trpc] request ${String(url)} | auth: ${authHeader ? 'PRESENT' : 'MISSING'}`
+ `[admin-web][trpc] request ${String(url)} | auth: ${
+ authHeader ? `PRESENT (${String(authHeader).length} chars)` : 'MISSING'
+ }`
)
@@ 401 branch
console.log(
`[admin-web][trpc] 401 ${String(url)} | auth was: ${authHeader ? 'PRESENT' : 'MISSING'}`
)
+ try {
+ const probe = await fetch(
+ `${BASE_API_URL}/api/trpc/admin.staffUser.me?batch=1&input=%7B%7D`,
+ { method: 'GET', headers: options?.headers }
+ )
+ console.log(`[admin-web][trpc] 401 probe (staffUser.me) -> ${probe.status}`)
+ } catch (probeError: any) {
+ console.log(
+ `[admin-web][trpc] 401 probe failed: ${probeError?.message ?? probeError}`
+ )
+ }
const data = await response.clone().json().catch(() => ({}))
[2026-11-16 01:11:30] debug: decode the stored JWT claims (staffId/userId/exp only, not the signature) in the tRPC header log
apps/admin-ui/src/trpc-client.ts
--- a/apps/admin-ui/src/trpc-client.ts
+++ b/apps/admin-ui/src/trpc-client.ts
@@ add helper
+// TEMP DIAGNOSTIC: decode (not verify) so we can see expiry/identity.
+function decodeJwtClaims(token: string): Record<string, any> | null {
+ try {
+ const part = token.split('.')[1];
+ if (!part) return null;
+ const b64 = part.replace(/-/g, '+').replace(/_/g, '/');
+ const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4);
+ const atobFn = (globalThis as any).atob as ((value: string) => string) | undefined;
+ if (!atobFn) return null;
+ const json = decodeURIComponent(
+ atobFn(padded)
+ .split('')
+ .map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
+ .join('')
+ );
+ return JSON.parse(json);
+ } catch {
+ return null;
+ }
+}
@@ headers
const token = await getJWT();
+ const claims = token ? decodeJwtClaims(token) : null;
console.log(
`[admin-ui][trpc] getJWT: ${token ? `present (${token.length} chars)` : 'MISSING'}`
);
+ console.log(
+ `[admin-ui][trpc] token claims: ${
+ claims
+ ? `staffId=${claims.staffId ?? '-'} userId=${claims.userId ?? '-'} exp=${
+ claims.exp ? new Date(claims.exp * 1000).toISOString() : '-'
+ } expired=${claims.exp ? claims.exp * 1000 <= Date.now() : '?'}`
+ : 'unreadable'
+ }`
+ );
apps/admin-web/src/lib/trpc-client.ts
--- a/apps/admin-web/src/lib/trpc-client.ts
+++ b/apps/admin-web/src/lib/trpc-client.ts
@@ add helper
+// TEMP DIAGNOSTIC: decode (not verify) so we can see expiry/identity.
+function decodeJwtClaims(token: string): Record<string, any> | null {
+ try {
+ const part = token.split('.')[1]
+ if (!part) return null
+ const b64 = part.replace(/-/g, '+').replace(/_/g, '/')
+ const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4)
+ const json = decodeURIComponent(
+ atob(padded)
+ .split('')
+ .map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
+ .join('')
+ )
+ return JSON.parse(json)
+ } catch {
+ return null
+ }
+}
@@ headers
const token = await getJWT()
+ const claims = token ? decodeJwtClaims(token) : null
console.log(
`[admin-web][trpc] getJWT: ${token ? `present (${token.length} chars)` : 'MISSING'}`
)
+ console.log(
+ `[admin-web][trpc] token claims: ${
+ claims
+ ? `staffId=${claims.staffId ?? '-'} userId=${claims.userId ?? '-'} exp=${
+ claims.exp ? new Date(claims.exp * 1000).toISOString() : '-'
+ } expired=${claims.exp ? claims.exp * 1000 <= Date.now() : '?'}`
+ : 'unreadable'
+ }`
+ )
[2026-11-16 01:14:47] fix(admin): debounce the coupon user search (350ms) so keystrokes cannot fire overlapping queries
apps/admin-ui/src/components/CouponForm.tsx
apps/admin-web/src/components/CouponForm.tsx
apps/admin-ui/tests/components/coupon-form.test.tsx
--- a/apps/admin-ui/src/components/CouponForm.tsx
+++ b/apps/admin-ui/src/components/CouponForm.tsx
@@ constant
const USERS_PAGE_SIZE = 10;
+// The user search fires on every keystroke; debounce it so a 10-digit mobile
+// number does not issue 10 overlapping queries (which saturated D1 in prod and
+// surfaced as a 401 / forced logout).
+const USER_SEARCH_DEBOUNCE_MS = 350;
@@ state
const [userSearchQuery, setUserSearchQuery] = useState('');
+ const [debouncedUserSearch, setDebouncedUserSearch] = useState('');
const [userOffset, setUserOffset] = useState(0);
@@ effect before the query
+ useEffect(() => {
+ const timer = setTimeout(
+ () => setDebouncedUserSearch(userSearchQuery),
+ USER_SEARCH_DEBOUNCE_MS
+ );
+ return () => clearTimeout(timer);
+ }, [userSearchQuery]);
+
@@ query input
- { search: userSearchQuery, limit: USERS_PAGE_SIZE, offset: userOffset },
+ { search: debouncedUserSearch, limit: USERS_PAGE_SIZE, offset: userOffset },
@@ opening the dialog resets both values
setHasMoreUsers(true);
setUserSearchQuery('');
+ setDebouncedUserSearch('');
}
--- a/apps/admin-web/src/components/CouponForm.tsx
+++ b/apps/admin-web/src/components/CouponForm.tsx
(same debounce constant, state, effect, query input and open-reset as the RN form)
--- a/apps/admin-ui/tests/components/coupon-form.test.tsx
+++ b/apps/admin-ui/tests/components/coupon-form.test.tsx
+const USER_SEARCH_DEBOUNCE_MS = 350
+
+async function waitForUserSearchDebounce() {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, USER_SEARCH_DEBOUNCE_MS + 50))
+ })
+ await flush(2)
+}
@@ ACOUPF-15
fireEvent.changeText(view.getByPlaceholderText('Search users by name or mobile...'), 'Test')
- await flush(2)
setProcedure('admin.coupon.getUsersMiniInfo', { ... })
- await flush(2)
+ await waitForUserSearchDebounce()
@@ new ACOUPF-18
+ it('ACOUPF-18: rapid typing is debounced into a single user-search request', ...)
+ - open the dialog (1 request)
+ - type 9 / 96 / 967 / 9676 quickly
+ - before the debounce: still 1 request
+ - after the debounce: exactly 2 requests, last input search '9676'
[2026-11-16 01:15:38] test: keep the temporary 401 probe out of the test environment (it adds a fetch; ATRPC-01 asserts exactly one)
apps/admin-ui/src/trpc-client.ts
apps/admin-web/src/lib/trpc-client.ts
--- a/apps/admin-ui/src/trpc-client.ts
+++ b/apps/admin-ui/src/trpc-client.ts
@@ 401 branch
- try {
- const probe = await fetch(...)
- console.log(...)
- } catch (probeError: any) {
- console.log(...)
- }
+ if (process.env.NODE_ENV !== 'test') {
+ try {
+ const probe = await fetch(...)
+ console.log(...)
+ } catch (probeError: any) {
+ console.log(...)
+ }
+ }
(same guard in the admin-web client)
[2026-11-16 01:21:49 IST] floating cart bar: show the coupon price per line and point at
the checkout coupon step.
The catalogue store already holds the product-specific coupons, so the expanded
sheet prices each line with the same helper the cards use (line total as the base,
flash items on flashPrice). The footer, under the subtotal, tells the customer
coupons exist at checkout — the cart screens have no coupon picker of their own.
--- apps/user-ui/components/floating-cart-bar.tsx
+ couponOffers read from useCentralProductStore
+ each expanded line: under its total, ₹couponLineTotal + "With Coupon"
+ footer: "Apply Coupons at checkout" under the Subtotal row
[2026-11-16 01:24:27 IST] catalogue coupons: the listed price keeps its weight, the
coupon price sits at the struck price's size.
The demotion (halved size + 85% opacity on the listed price) made the coupon number
the loudest thing on the card. Reverting it: the listed price keeps its original
class and full opacity, the struck price is untouched, and the coupon price moves
down to the struck price's size in the brand colour, with the same muted
"With Coupon" label. The product detail coupon line drops from text-xl to
text-base for the same reason.
--- apps/user-ui/components/ProductCard.tsx
- price row: back to the original class, no opacity wrapper, testID dropped
- coupon row: ₹couponPrice at text-xs (default) / text-[10px] (hero), brand colour
+ “With Coupon” in text-gray-400
--- apps/user-ui/components/ProductDetail.tsx
- coupon line: text-xl -> text-base, brand colour + text-gray-400 label
--- apps/user-ui/tests/components/product-card-coupon.test.tsx
PCARD-03/04 now assert sizes + colours instead of the demotion
--- apps/user-ui/tests/pages/product-detail.test.tsx
PD-52 also pins the coupon size against the 3xl listed price