This commit is contained in:
shafi54 2026-10-22 19:39:12 +05:30
parent 7e2cca0e34
commit 12fb0db4c9
45 changed files with 1787 additions and 581 deletions

View file

@ -1,57 +0,0 @@
# MULTI_REGION_I2 Code Review
Comparison: `main...MULTI_REGION_I2`
## Findings
1. **[P1] Name searches bypass regional customer isolation** — `packages/db_helper_sqlite/src/admin-apis/user.ts:224`
The predicate becomes `(inRegion AND mobile LIKE … OR name LIKE …)`. A regional admin searching by name receives matching customers from other regions, including their mobile numbers. Group the search predicates with Drizzle’s `or()`.
2. **[P1] Web discovery sends the wrong required parameter** — `apps/web-ui/src/hooks/prominent-api-hooks.ts:25–27`
The hook sends `{ regionId }`, but `essentialConsts` now requires `{ boundId }`. Every discovery request fails validation after selecting a region, leaving catalog and slot requests disabled. Pass the selected bound and remove the masking `as any`.
3. **[P1] Global-product updates discard existing SKU IDs** — `apps/backend/src/trpc/apis/superadmin-apis/apis/global-products.ts:95–107`
`skuInput` does not declare `id`, so Zod strips the IDs before the resolver reads them. Saving existing variants therefore inserts duplicates instead of updating them. Suspending an existing variant creates a suspended duplicate while the original remains purchasable. Preserve optional SKU IDs in the update schema.
4. **[P1] Rejected regional edits can delete a global store’s image** — `apps/backend/src/trpc/apis/admin-apis/apis/store.ts:93–110`
The visibility check now accepts global stores, and the resolver deletes their old image before the database helper rejects regional writes. A regional staff member can consequently remove an image shared across all regions despite the mutation failing. Check edit ownership before deleting assets.
5. **[P1] Regional cache requests suppress pending global regeneration** — `apps/backend/src/jobs/cache-creator.ts:25–33`
A global request leaves `pendingRegions` unchanged. If a regional request occurs in the same debounce window, the alarm regenerates only that region. For example, a global-product edit followed by a region-A banner edit leaves every other region’s catalog stale. Persist an explicit “all regions pending” flag that regional requests cannot narrow.
6. **[P1] Scheduled web checkout always submits rejected slot IDs** — `apps/backend/src/trpc/apis/user-apis/apis/order.ts:190–194`
The new validation rejects null scheduled slots, but `apps/web-ui/src/routes/home.checkout.tsx:93–101` still submits `slotId: null` for every item. Every nonempty scheduled web checkout fails. Forward each cart line’s selected slot ID.
7. **[P1] New-region cache generation is detached from the Worker lifetime** — `apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts:88–93`
Cache generation starts without being awaited, registered with `waitUntil`, or scheduled through the Durable Object. In production, Cloudflare can cancel it after the response, leaving a successfully created region without usable catalog/discovery files. Schedule durable generation or attach the work to the execution context.
8. **[P2] Global-product Edit retains the create form’s draft** — `apps/superadmin-ui/src/routes/global-products.tsx:274–282`
Both branches render the same unkeyed component, whose fields initialize only on mount. Clicking Edit therefore retains the empty create draft—or another product’s draft—while submission targets the selected product. Key the form by product ID or explicitly reset its state when the product changes.
9. **[P2] Global ID windows hide orders from quieter regions** — `packages/db_helper_sqlite/src/admin-apis/order.ts:415–427`
The new regional filter is combined with a pagination threshold derived from the globally newest order ID. Once another region creates more than `limit + 5` newer orders, a quiet region’s list becomes empty and returns no next cursor, even when it has pending orders. Paginate matching regional rows rather than bounded global ID ranges.
10. **[P2] Startup address selection deletes or rolls back persisted carts** — `apps/user-ui/src/lib/region-switch.ts:34–41`
The region store starts null on every launch, but carts remain persisted. Selecting the same address through the startup chooser skips stashing the live carts, clears them, and restores an absent or older snapshot. Persist cart ownership independently of the transient browsing region before performing this reset.
11. **[P2] Unrelated market edits undo regional suspension** — `packages/db_helper_sqlite/src/admin-apis/product.ts:539–545`
Regional forms initialize suspension from `sku.isSuspended`, but the response mapper returns the global structural flag instead of `marketStats.isSuspendedInRegion`. Suspend a global SKU regionally, reopen it, and save a price change: this writes false and re-enables it. Return and edit the regional suspension separately.
12. **[P2] Coupon allocation can persist negative sub-order totals** — `packages/shared/cart-pricing.ts:411–423`
Each coupon’s shares are rounded independently without respecting each sub-order’s remaining balance. With two ₹101 sub-orders and two stackable ₹101 coupons, the resulting discounts are ₹100 and ₹102, producing totals of ₹1 and **−₹1**. Allocate against remaining per-order balances and reconcile without exceeding them.
13. **[P2] Migration erases historical discount amounts** — `packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql:488–489`
Every existing order receives `discount_amount = '0'`, including orders whose stored total already includes a coupon discount. Both new order-detail APIs exclusively read this column, so historical invoices incorrectly report no discount. Backfill the charged discount from historical item totals, delivery charge, and order total.
14. **[P2] Changing a global coupon to flat discount retains its percentage** — `apps/backend/src/trpc/apis/superadmin-apis/apis/global-coupons.ts:137–138`
Switching a 20% coupon to ₹50 sends only `flatDiscount`; the update preserves the existing percentage. Both values are stored, and pricing continues prioritizing 20%, despite the successful save. Explicitly clear the opposite discount field and validate the merged coupon.
15. **[P2] Browser reload disables vendor-snippet slot selection** — `apps/admin-web/src/components/VendorSnippetForm.tsx:25–28`
Session restoration loads only the JWT, leaving `staff` and `regionId` null. The new query condition then permanently disables slot loading after a reload, making nonpermanent snippet creation impossible until another login. Restore the staff identity or obtain the region from the authenticated staff endpoint.
16. **[P2] Dedicated superadmin login breaks Admin Notifs** — `apps/superadmin-ui/src/lib/auth-context.tsx:37`
The new login produces a superadmin-only principal, but the retained notification page calls `admin.staffUser.sendAdminNotification`, whose guard accepts only users or staff. Every send now fails with `UNAUTHORIZED`. Expose an appropriately guarded superadmin notification endpoint and update the caller.
## Verification Notes
No files were changed during the review. The test suite and migrations were not run.

File diff suppressed because one or more lines are too long

View file

@ -1474,6 +1474,7 @@ Covered by HOME-81..98, plus:
| REGION-24 | edge | address list response held | startup waits for it | | REGION-24 | edge | address list response held | startup waits for it |
| REGION-25 | edge | cached regions + address, live pending | starts from cache; live requests still run | | REGION-25 | edge | cached regions + address, live pending | starts from cache; live requests still run |
| REGION-26 | edge | live data differs from cache | region/bound/address reconcile to live | | REGION-26 | edge | live data differs from cache | region/bound/address reconcile to live |
| REGION-27 | edge | consumer above AuthProvider | does not settle launch decision; authenticated instance anchors on default |
| LOCSTORE-01 | happy | start once | one permission/fix; second start no-op | | LOCSTORE-01 | happy | start once | one permission/fix; second start no-op |
| LOCSTORE-02 | error | denied | status denied, coords null | | LOCSTORE-02 | error | denied | status denied, coords null |
| LOCSTORE-03 | edge | services off | status services-off | | LOCSTORE-03 | edge | services off | status services-off |

View file

@ -16,7 +16,7 @@ export default function FlashDeliveryBaseLayout() {
if (!isFlashDeliveryEnabled) { if (!isFlashDeliveryEnabled) {
return ( return (
<AppContainer> <AppContainer>
<View style={tw`flex-1 justify-center items-center p-6`}> <View testID="flash-unavailable" style={tw`flex-1 justify-center items-center p-6`}>
<View style={tw`bg-gray-100 rounded-full p-6 mb-6`}> <View style={tw`bg-gray-100 rounded-full p-6 mb-6`}>
<MaterialIcons name="flash-off" size={64} color="#9ca3af" /> <MaterialIcons name="flash-off" size={64} color="#9ca3af" />
</View> </View>
@ -27,6 +27,7 @@ export default function FlashDeliveryBaseLayout() {
1 Hr Delivery is not available at the moment. Please opt for a scheduled delivery. 1 Hr Delivery is not available at the moment. Please opt for a scheduled delivery.
</MyText> </MyText>
<MyTouchableOpacity <MyTouchableOpacity
testID="flash-unavailable-home"
onPress={() => router.replace('/(drawer)/(tabs)/home')} onPress={() => router.replace('/(drawer)/(tabs)/home')}
style={tw`bg-green-500 px-8 py-4 rounded-lg`} style={tw`bg-green-500 px-8 py-4 rounded-lg`}
> >

View file

@ -222,6 +222,7 @@ const TagTabStrip = memo(({
<ScrollView <ScrollView
ref={scrollRef} ref={scrollRef}
horizontal horizontal
testID="home-tag-strip"
showsHorizontalScrollIndicator={false} showsHorizontalScrollIndicator={false}
// horizontal ScrollViews default to flexGrow: 1 — pin it to content height // horizontal ScrollViews default to flexGrow: 1 — pin it to content height
// so it doesn't eat the page space below the tabs // so it doesn't eat the page space below the tabs

View file

@ -111,7 +111,7 @@ export default function SearchResults() {
<MyText style={tw`text-gray-500 font-medium`}>Loading products...</MyText> <MyText style={tw`text-gray-500 font-medium`}>Loading products...</MyText>
</View> </View>
) : ( ) : (
<View style={tw`flex-1 justify-center items-center py-12 px-4`}> <View testID="search-empty" style={tw`flex-1 justify-center items-center py-12 px-4`}>
<MaterialIcons name="search-off" size={64} color="#e5e7eb" /> <MaterialIcons name="search-off" size={64} color="#e5e7eb" />
<MyText style={tw`text-gray-500 mt-4 text-center text-lg font-medium`}> <MyText style={tw`text-gray-500 mt-4 text-center text-lg font-medium`}>
No products found No products found

View file

@ -36,7 +36,7 @@ const OffersSection = ({
const hasMore = products.length > SHOW_MORE_STEP && !expanded; const hasMore = products.length > SHOW_MORE_STEP && !expanded;
return ( return (
<View style={tw`pt-4`}> <View testID={title === 'Offers' ? 'offers-section' : 'combos-section'} style={tw`pt-4`}>
<View style={tw`mb-2 px-4`}> <View style={tw`mb-2 px-4`}>
<MyText style={tw`text-2xl font-extrabold text-gray-900 tracking-tight`}> <MyText style={tw`text-2xl font-extrabold text-gray-900 tracking-tight`}>
{title} {title}
@ -76,7 +76,12 @@ const OffersSection = ({
activeOpacity={0.85} activeOpacity={0.85}
onPress={onExpand} onPress={onExpand}
> >
<MyText style={tw`text-white text-sm font-semibold`}>Show More</MyText> <MyText
testID={title === 'Offers' ? 'offers-show-more' : 'combos-show-more'}
style={tw`text-white text-sm font-semibold`}
>
Show More
</MyText>
</MyTouchableOpacity> </MyTouchableOpacity>
)} )}
</> </>

View file

@ -14,8 +14,10 @@ import StoresIcon from "@/components/icons/StoresIcon";
import OffersIcon from "@/components/icons/OffersIcon"; import OffersIcon from "@/components/icons/OffersIcon";
import MeIcon from "@/components/icons/MeIcon"; import MeIcon from "@/components/icons/MeIcon";
import { useAppStore } from "@/src/store/appStore"; import { useAppStore } from "@/src/store/appStore";
import { useRenderProbe } from "@/src/lib/render-probe";
export default function Layout() { export default function Layout() {
useRenderProbe('layout:tabs')
const { isAuthenticated, isLoading } = useAuth(); const { isAuthenticated, isLoading } = useAuth();
const hideTabsNav = useAppStore((state) => state.hideTabsNav); const hideTabsNav = useAppStore((state) => state.hideTabsNav);
const shouldHideTabs = Object.values(hideTabsNav).some(Boolean); const shouldHideTabs = Object.values(hideTabsNav).some(Boolean);
@ -54,6 +56,7 @@ export default function Layout() {
name="(tabs)/home" name="(tabs)/home"
options={{ options={{
tabBarLabel: 'Home', tabBarLabel: 'Home',
tabBarButtonTestID: 'tab-home',
tabBarIcon: ({ color, size, focused }) => ( tabBarIcon: ({ color, size, focused }) => (
<HomeIcon focused={focused} size={size} color={color} /> <HomeIcon focused={focused} size={size} color={color} />
), ),
@ -63,6 +66,7 @@ export default function Layout() {
name="(tabs)/order-again" name="(tabs)/order-again"
options={{ options={{
tabBarLabel: 'Offers', tabBarLabel: 'Offers',
tabBarButtonTestID: 'tab-offers',
tabBarIcon: ({ color, size, focused }) => ( tabBarIcon: ({ color, size, focused }) => (
<OffersIcon focused={focused} size={size} color={color} /> <OffersIcon focused={focused} size={size} color={color} />
), ),
@ -76,6 +80,7 @@ export default function Layout() {
tabBarButton: (props) => ( tabBarButton: (props) => (
<MyTouchableOpacity <MyTouchableOpacity
{...(props as any)} {...(props as any)}
testID="tab-flash"
style={[ style={[
props.style, props.style,
tw`items-center justify-center -top-2`, // Adjusted elevation tw`items-center justify-center -top-2`, // Adjusted elevation
@ -98,6 +103,7 @@ export default function Layout() {
name="(tabs)/stores" name="(tabs)/stores"
options={{ options={{
tabBarLabel: 'Stores', tabBarLabel: 'Stores',
tabBarButtonTestID: 'tab-stores',
tabBarIcon: ({ color, size, focused }) => ( tabBarIcon: ({ color, size, focused }) => (
<StoresIcon focused={focused} size={size} color={color} /> <StoresIcon focused={focused} size={size} color={color} />
), ),
@ -107,6 +113,7 @@ export default function Layout() {
name="(tabs)/me" name="(tabs)/me"
options={{ options={{
tabBarLabel: 'Me', tabBarLabel: 'Me',
tabBarButtonTestID: 'tab-me',
tabBarIcon: ({ color, size, focused }) => ( tabBarIcon: ({ color, size, focused }) => (
<MeIcon focused={focused} size={size} color={color} /> <MeIcon focused={focused} size={size} color={color} />
), ),

View file

@ -32,6 +32,7 @@ import LocationTestWrapper from "@/components/LocationTestWrapper";
import React from "react"; import React from "react";
import { GestureHandlerRootView } from "react-native-gesture-handler"; import { GestureHandlerRootView } from "react-native-gesture-handler";
import NotifChecker from "@/services/notif-service/notif-checker"; import NotifChecker from "@/services/notif-service/notif-checker";
import RenderCommitProbe from "@/src/lib/render-probe";
// Silence dev warnings/errors in LogBox. The "Open debugger to view warnings" // Silence dev warnings/errors in LogBox. The "Open debugger to view warnings"
// toast overlays the bottom of the UI and intercepts taps (e.g. tab bar / // toast overlays the bottom of the UI and intercepts taps (e.g. tab bar /
@ -82,7 +83,9 @@ export default function RootLayout() {
<RefreshProvider queryClient={queryClient}> <RefreshProvider queryClient={queryClient}>
<CentralStoreInitializer> <CentralStoreInitializer>
<BackHandlerWrapper /> <BackHandlerWrapper />
<Stack screenOptions={{ headerShown: false }} /> <RenderCommitProbe>
<Stack screenOptions={{ headerShown: false }} />
</RenderCommitProbe>
<AddToCartDialog /> <AddToCartDialog />
</CentralStoreInitializer> </CentralStoreInitializer>
</RefreshProvider> </RefreshProvider>

View file

@ -6,6 +6,7 @@ import { trpc } from '../src/trpc-client'
import { useRegion } from '@/src/hooks/useRegion' import { useRegion } from '@/src/hooks/useRegion'
import { useLocationStore } from '@/src/store/locationStore' import { useLocationStore } from '@/src/store/locationStore'
import LocationFallbackFlow from '@/src/components/location/LocationFallbackFlow' import LocationFallbackFlow from '@/src/components/location/LocationFallbackFlow'
import { useRenderProbe } from '@/src/lib/render-probe'
// How often the gate re-checks the device location while it is up. // How often the gate re-checks the device location while it is up.
const LOCATION_POLL_MS = 3000 const LOCATION_POLL_MS = 3000
@ -28,6 +29,7 @@ const LoadingScreen: React.FC<{ label?: string }> = ({ label }) => (
* asked to choose an address. * asked to choose an address.
*/ */
const LocationTestWrapper: React.FC<ReactParentComponent> = ({ children }) => { const LocationTestWrapper: React.FC<ReactParentComponent> = ({ children }) => {
useRenderProbe('provider:LocationTestWrapper')
const { const {
regionId, regionId,
clearRegion, clearRegion,

View file

@ -13,6 +13,7 @@ import OrderStatusTracker from './OrderStatusTracker';
import { useGetEssentialConsts } from '@/src/hooks/prominent-api-hooks'; import { useGetEssentialConsts } from '@/src/hooks/prominent-api-hooks';
import { useUserDetails } from '@/src/contexts/AuthContext'; import { useUserDetails } from '@/src/contexts/AuthContext';
import type { Order, OrderItem } from '@/src/types/orders'; import type { Order, OrderItem } from '@/src/types/orders';
import { useRenderProbe } from '@/src/lib/render-probe';
const { width: screenWidth } = Dimensions.get('window'); const { width: screenWidth } = Dimensions.get('window');
const CARD_WIDTH = (screenWidth - 48) * 0.95; // card width (24px padding each side), reduced 5% const CARD_WIDTH = (screenWidth - 48) * 0.95; // card width (24px padding each side), reduced 5%
@ -118,6 +119,7 @@ function OrderCard({ order, onPress, supportMobile }: OrderCardProps) {
} }
export default function NextOrderGlimpse() { export default function NextOrderGlimpse() {
useRenderProbe('component:NextOrderGlimpse')
const router = useRouter(); const router = useRouter();
const { setNavigationTarget } = useNavigationTarget(); const { setNavigationTarget } = useNavigationTarget();
const userDetails = useUserDetails(); const userDetails = useUserDetails();

View file

@ -16,6 +16,7 @@ import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier';
import { useCartStore } from '@/src/store/cartStore'; import { useCartStore } from '@/src/store/cartStore';
import { useCentralSlotStore } from '@/src/store/centralSlotStore'; import { useCentralSlotStore } from '@/src/store/centralSlotStore';
import { Image as RnImage } from 'react-native' import { Image as RnImage } from 'react-native'
import { useRenderProbe } from '@/src/lib/render-probe'
interface ProductCardProps { interface ProductCardProps {
@ -48,6 +49,7 @@ const ProductCard: React.FC<ProductCardProps> = ({
containerComp: ContainerComp = React.Fragment, containerComp: ContainerComp = React.Fragment,
useAddToCartDialog = false, useAddToCartDialog = false,
}) => { }) => {
useRenderProbe('component:ProductCard')
const isHero = variant === 'hero'; const isHero = variant === 'hero';
const imageUri = item.images?.[0] const imageUri = item.images?.[0]
const [imageStatus, setImageStatus] = React.useState<'loading' | 'loaded' | 'error'>('loading') const [imageStatus, setImageStatus] = React.useState<'loading' | 'loaded' | 'error'>('loading')
@ -155,6 +157,7 @@ const ProductCard: React.FC<ProductCardProps> = ({
// console.log('rendering the product cart for id', item.id) // console.log('rendering the product cart for id', item.id)
return ( return (
<ContainerComp> <ContainerComp>
<View testID={`product-card-${item.id}`}>
<MyTouchableOpacity <MyTouchableOpacity
testID="product-card" testID="product-card"
style={[ style={[
@ -195,13 +198,13 @@ const ProductCard: React.FC<ProductCardProps> = ({
)} )}
{displayIsOutOfStock && ( {displayIsOutOfStock && (
<View testID="out-of-stock-badge" style={tw`absolute inset-0 bg-black/40 items-center justify-center`}> <View testID="out-of-stock-badge" style={tw`absolute inset-0 bg-black/40 items-center justify-center`}>
<View style={tw`bg-red-500 px-3 py-1 rounded-full`}> <View testID={`out-of-stock-${item.id}`} style={tw`bg-red-500 px-3 py-1 rounded-full`}>
<MyText style={tw`text-white text-xs font-bold`}>Out of Stock</MyText> <MyText style={tw`text-white text-xs font-bold`}>Out of Stock</MyText>
</View> </View>
</View> </View>
)} )}
{miniView && ( {miniView && (
<View style={isHero ? tw`absolute bottom-1.5 right-1.5` : tw`absolute bottom-2 right-2`}> <View testID={`add-to-cart-${item.id}`} style={isHero ? tw`absolute bottom-1.5 right-1.5` : tw`absolute bottom-2 right-2`}>
{quantity > 0 ? ( {quantity > 0 ? (
<MiniQuantifier value={quantity} onChange={handleQuantityChange} step={item.incrementStep} /> <MiniQuantifier value={quantity} onChange={handleQuantityChange} step={item.incrementStep} />
) : ( ) : (
@ -272,6 +275,7 @@ const ProductCard: React.FC<ProductCardProps> = ({
)} )}
</View> </View>
</MyTouchableOpacity> </MyTouchableOpacity>
</View>
</ContainerComp> </ContainerComp>
); );
}; };

View file

@ -269,6 +269,7 @@ const CompactProductCard = ({
}; };
return ( return (
<View testID={`${cartType === "flash" ? "flash-product" : "slot-product"}-${item.id}`}>
<MyTouchableOpacity <MyTouchableOpacity
testID="compact-product-card" testID="compact-product-card"
style={[ style={[
@ -288,7 +289,7 @@ const CompactProductCard = ({
<MyText style={tw`text-white text-xs font-bold`}>Out of Stock</MyText> <MyText style={tw`text-white text-xs font-bold`}>Out of Stock</MyText>
</View> </View>
)} )}
<View style={tw`absolute bottom-2 right-2`}> <View testID={`${cartType === "flash" ? "flash-add" : "slot-add"}-${item.id}`} style={tw`absolute bottom-2 right-2`}>
{quantity > 0 ? ( {quantity > 0 ? (
<MiniQuantifier <MiniQuantifier
value={quantity} value={quantity}
@ -329,6 +330,7 @@ const CompactProductCard = ({
</View> </View>
</MyTouchableOpacity> </MyTouchableOpacity>
</View>
); );
}; };

View file

@ -2,6 +2,7 @@ import React from 'react';
import type { StyleProp, ViewStyle } from 'react-native'; import type { StyleProp, ViewStyle } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context'; import { SafeAreaView } from 'react-native-safe-area-context';
import { tw } from 'common-ui'; import { tw } from 'common-ui';
import { useRenderProbe } from '@/src/lib/render-probe';
interface TabLayoutWrapperProps { interface TabLayoutWrapperProps {
children: React.ReactNode; children: React.ReactNode;
@ -9,6 +10,7 @@ interface TabLayoutWrapperProps {
} }
export default function TabLayoutWrapper({ children, style }: TabLayoutWrapperProps) { export default function TabLayoutWrapper({ children, style }: TabLayoutWrapperProps) {
useRenderProbe('component:TabLayoutWrapper')
return ( return (
<SafeAreaView testID="tab-layout-wrapper" edges={['top']} style={[tw`flex-1 bg-white`, style]}> <SafeAreaView testID="tab-layout-wrapper" edges={['top']} style={[tw`flex-1 bg-white`, style]}>
{children} {children}

View file

@ -982,7 +982,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
const itemPrice = (Number(price)) * quantity; const itemPrice = (Number(price)) * quantity;
return ( return (
<View key={item.id}> <View key={item.id} testID={`cart-sku-${item.skuId}`}>
<View style={tw`p-4`}> <View style={tw`p-4`}>
<View style={tw`flex-row items-center mb-2`}> <View style={tw`flex-row items-center mb-2`}>
<MyTouchableOpacity <MyTouchableOpacity
@ -1551,7 +1551,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
{/* Grand Total */} {/* Grand Total */}
<View style={tw`flex-row justify-between items-center mt-2`}> <View style={tw`flex-row justify-between items-center mt-2`}>
<MyText style={tw`text-lg font-bold text-gray-900`}>To Pay</MyText> <MyText style={tw`text-lg font-bold text-gray-900`}>To Pay</MyText>
<MyText style={tw`text-xl font-bold text-gray-900`}>₹{Math.trunc(finalTotalWithDelivery)}</MyText> <MyText testID="cart-to-pay" style={tw`text-xl font-bold text-gray-900`}>₹{Math.trunc(finalTotalWithDelivery)}</MyText>
</View> </View>
{/* Savings Banner */} {/* Savings Banner */}

View file

@ -22,6 +22,7 @@ import {
type CartType, type CartType,
} from "@/hooks/cart-query-hooks"; } from "@/hooks/cart-query-hooks";
import { useRegionalConsts, useSlots } from "@/src/hooks/prominent-api-hooks" import { useRegionalConsts, useSlots } from "@/src/hooks/prominent-api-hooks"
import { useRenderProbe } from "@/src/lib/render-probe"
import { useProductSlotIdentifier } from "@/hooks/useProductSlotIdentifier"; import { useProductSlotIdentifier } from "@/hooks/useProductSlotIdentifier";
import { useCentralProductStore } from "@/src/store/centralProductStore"; import { useCentralProductStore } from "@/src/store/centralProductStore";
import dayjs from "dayjs"; import dayjs from "dayjs";
@ -92,6 +93,7 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
isExpanded: controlledIsExpanded, isExpanded: controlledIsExpanded,
setIsExpanded: controlledSetIsExpanded, setIsExpanded: controlledSetIsExpanded,
}) => { }) => {
useRenderProbe('component:FloatingCartBar')
const cartBarColor = isFlashDelivery ? '#f81260' : theme.colors.brand600; const cartBarColor = isFlashDelivery ? '#f81260' : theme.colors.brand600;
const cartBarBorderColor = isFlashDelivery ? '#e11d48' : theme.colors.brand500; const cartBarBorderColor = isFlashDelivery ? '#e11d48' : theme.colors.brand500;
const router = useRouter(); const router = useRouter();

View file

@ -198,7 +198,7 @@ export default function AddToCartDialog() {
{availableSlots.map((slot: any) => ( {availableSlots.map((slot: any) => (
<MyTouchableOpacity <MyTouchableOpacity
key={slot.id} key={slot.id}
testID={`slot-${dayjs(slot.deliveryTime).format('YYYY-MM-DD-HH-mm')}`} testID={`slot-option-${slot.id}`}
style={tw`flex-row items-start mb-4 bg-gray-50 p-4 rounded-xl border border-gray-100 ${selectedSlotId === slot.id ? 'border-brand500' : 'border-gray-100' style={tw`flex-row items-start mb-4 bg-gray-50 p-4 rounded-xl border border-gray-100 ${selectedSlotId === slot.id ? 'border-brand500' : 'border-gray-100'
}`} }`}
onPress={() => { onPress={() => {

View file

@ -7,6 +7,7 @@ import { useAddressStore } from '@/src/store/addressStore'
import { useAuthOptional } from '@/src/contexts/AuthContext' import { useAuthOptional } from '@/src/contexts/AuthContext'
import { trpc } from '@/src/trpc-client' import { trpc } from '@/src/trpc-client'
import AddressSwitcherSheet from '@/src/components/location/AddressSwitcherSheet' import AddressSwitcherSheet from '@/src/components/location/AddressSwitcherSheet'
import { useRenderProbe } from '@/src/lib/render-probe'
const formatAddress = (address: { const formatAddress = (address: {
addressLine1: string addressLine1: string
@ -25,6 +26,7 @@ const formatAddress = (address: {
* address beneath it. * address beneath it.
*/ */
const LocationBar: React.FC = () => { const LocationBar: React.FC = () => {
useRenderProbe('component:LocationBar')
const [sheetOpen, setSheetOpen] = useState(false) const [sheetOpen, setSheetOpen] = useState(false)
const { region } = useRegion() const { region } = useRegion()

View file

@ -229,7 +229,7 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({
style={tw`px-5 pt-12 pb-2 flex-row items-center`} style={tw`px-5 pt-12 pb-2 flex-row items-center`}
> >
<MaterialIcons name="arrow-back" size={22} color="#4B5563" /> <MaterialIcons name="arrow-back" size={22} color="#4B5563" />
<MyText style={tw`text-gray-600 ml-1`}>Back</MyText> <MyText testID="location-add-back-label" style={tw`text-gray-600 ml-1`}>Back</MyText>
</MyTouchableOpacity> </MyTouchableOpacity>
<AddressForm <AddressForm
draftMode={!isAuthenticated} draftMode={!isAuthenticated}
@ -252,7 +252,7 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({
</MyText> </MyText>
</View> </View>
{onClose && ( {onClose && (
<MyTouchableOpacity onPress={onClose} style={tw`p-1`}> <MyTouchableOpacity testID="location-close" onPress={onClose} style={tw`p-1`}>
<MaterialIcons name="close" size={24} color="#9CA3AF" /> <MaterialIcons name="close" size={24} color="#9CA3AF" />
</MyTouchableOpacity> </MyTouchableOpacity>
)} )}
@ -304,7 +304,7 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({
> >
<MyTouchableOpacity testID={`location-address-${address.id}`} disabled={busy} onPress={() => handleSelect(address)}> <MyTouchableOpacity testID={`location-address-${address.id}`} disabled={busy} onPress={() => handleSelect(address)}>
<View style={tw`flex-row items-center mb-1`}> <View style={tw`flex-row items-center mb-1`}>
<MyText style={tw`text-base font-bold text-gray-900 mr-2`}>{address.name}</MyText> <MyText testID={`location-address-name-${address.id}`} style={tw`text-base font-bold text-gray-900 mr-2`}>{address.name}</MyText>
{address.isDefault && ( {address.isDefault && (
<View style={tw`bg-green-100 px-2 py-0.5 rounded-full`}> <View style={tw`bg-green-100 px-2 py-0.5 rounded-full`}>
<MyText style={tw`text-green-700 text-[10px] font-semibold`}>Default</MyText> <MyText style={tw`text-green-700 text-[10px] font-semibold`}>Default</MyText>

View file

@ -79,6 +79,12 @@ export function useRegion(): UseRegionResult {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const utils = trpc.useUtils() const utils = trpc.useUtils()
const auth = useAuthOptional() const auth = useAuthOptional()
// Components above AuthProvider (UpdateChecker / HealthTestWrapper /
// WebViewWrapper, through useGetEssentialConsts) also consume this hook.
// They have no auth context and must not settle the launch decision: without
// auth they cannot see the default/sole address, and would force the address
// chooser even when the user has a default address.
const hasAuthContext = auth != null
const isAuthenticated = auth?.isAuthenticated ?? false const isAuthenticated = auth?.isAuthenticated ?? false
const isAuthLoading = auth?.isLoading ?? false const isAuthLoading = auth?.isLoading ?? false
const userId = auth?.user?.id ?? null const userId = auth?.user?.id ?? null
@ -268,6 +274,10 @@ export function useRegion(): UseRegionResult {
// else let the user pick). // else let the user pick).
useEffect(() => { useEffect(() => {
if (!hydrated || startupResolved) return if (!hydrated || startupResolved) return
// Only the instance below AuthProvider owns the one-shot launch decision.
// An instance above it sees no user, so settling there would skip the
// default-address anchor and show the chooser on every location-off launch.
if (!hasAuthContext) return
const resolved = resolution.data const resolved = resolution.data
const locationSettled = const locationSettled =
@ -391,6 +401,7 @@ export function useRegion(): UseRegionResult {
setRegion, setRegion,
clearRegion, clearRegion,
queryClient, queryClient,
hasAuthContext,
isAuthenticated, isAuthenticated,
isAuthLoading, isAuthLoading,
cacheSnapshot.ready, cacheSnapshot.ready,

View file

@ -0,0 +1,136 @@
import React from 'react'
import { usePathname } from 'expo-router'
/**
* TEMPORARY diagnostic: logs one summary per ~1s window of React commits in the
* route tree, tagged with the active Expo route. A page that re-renders forever
* will keep producing a steadily growing `commits` count.
*
* The same summary is POSTed to a local dev sink (127.0.0.1:9099) so it can be
* watched from a terminal other than Metro. Remove this file + the wrapper in
* app/_layout.tsx once the investigation is done.
*/
const PROBE_ENDPOINT = 'http://127.0.0.1:9099/render'
type WindowStats = {
path: string
windowStart: number
commits: number
lastPhase: string
lastDuration: number
}
const componentWindows = new Map<string, { windowStart: number; renders: number }>()
/**
* Per-component render counter for the same diagnostic. Call it at the top of a
* component; it emits at most one summary per second per label.
*/
export function useRenderProbe(label: string) {
React.useEffect(() => {
if (!__DEV__) return
const now = Date.now()
let window = componentWindows.get(label)
if (!window) {
window = { windowStart: now, renders: 0 }
componentWindows.set(label, window)
}
window.renders += 1
const elapsed = now - window.windowStart
if (elapsed < 1000) return
const perSecond = (window.renders * 1000) / elapsed
const suspicious = perSecond > 15 ? ' [render-loop?]' : ''
const summary = {
kind: 'component',
label,
renders: window.renders,
elapsed,
perSecond: Number(perSecond.toFixed(1)),
ts: now,
}
console.log(
`[render-probe] component=${label} renders=${summary.renders}/${summary.elapsed}ms ` +
`(~${summary.perSecond}/s)${suspicious}`
)
fetch(PROBE_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(summary),
}).catch(() => {})
window.windowStart = now
window.renders = 0
})
}
export default function RenderCommitProbe({ children }: { children: React.ReactNode }) {
const pathname = usePathname()
const stats = React.useRef<WindowStats>({
path: pathname,
windowStart: Date.now(),
commits: 0,
lastPhase: 'mount',
lastDuration: 0,
})
React.useEffect(() => {
stats.current.path = pathname
stats.current.windowStart = Date.now()
stats.current.commits = 0
}, [pathname])
const onRender = React.useCallback(
(_id: string, phase: 'mount' | 'update' | 'nested-update', actualDuration: number) => {
if (!__DEV__) return
const s = stats.current
const now = Date.now()
s.commits += 1
s.lastPhase = phase
s.lastDuration = actualDuration
const elapsed = now - s.windowStart
if (elapsed < 1000) return
const perSecond = (s.commits * 1000) / elapsed
const suspicious = perSecond > 15 ? ' [render-loop?]' : ''
const summary = {
path: s.path,
commits: s.commits,
elapsed,
perSecond: Number(perSecond.toFixed(1)),
phase: s.lastPhase,
duration: Number(s.lastDuration.toFixed(1)),
ts: now,
}
console.log(
`[render-probe] path=${summary.path} commits=${summary.commits}/${summary.elapsed}ms ` +
`(~${summary.perSecond}/s) last=${summary.phase} ${summary.duration}ms${suspicious}`
)
fetch(PROBE_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(summary),
}).catch(() => {})
s.windowStart = now
s.commits = 0
},
[]
)
if (!__DEV__) return <>{children}</>
return (
<React.Profiler id="route" onRender={onRender}>
{children}
</React.Profiler>
)
}

View file

@ -638,6 +638,48 @@ describe('useRegion', () => {
} }
}) })
}) })
it('REGION-27: a consumer above AuthProvider does not settle the launch decision', async () => {
await withFreshModules(async (ctx) => {
const { REGION_1, REGION_2, A1, A2 } = ctx.fixtures
// UpdateChecker / HealthTestWrapper / WebViewWrapper consume useRegion
// through useGetEssentialConsts while mounted above AuthProvider.
ctx.auth.__setNoAuthContext(true)
ctx.auth.__setAuthState({ isAuthenticated: false, isLoading: false })
ctx.locationMock.__configure({ permission: 'denied' })
ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1, REGION_2] })
ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: A1 } })
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [A1, A2] } })
const { result, view, rerender } = ctx.renderRegion()
await ctx.testUtils.flush(5)
// Without an auth context there is no default/sole address anchor. It must
// stay unresolved instead of settling with regionId null, otherwise it
// shows the chooser and blocks the real gate via `startupCheckDone`.
expect(result.current.isResolvingRegion).toBe(true)
expect(result.current.regionId).toBeNull()
// The instance inside AuthProvider (LocationTestWrapper) can still settle
// and adopt the default address's region/bound.
ctx.auth.__setNoAuthContext(false)
ctx.auth.__setAuthState({
isAuthenticated: true,
isLoading: false,
user: { id: 388 },
})
await ctx.rtl.act(async () => {
rerender()
})
await ctx.testUtils.flush(8)
expect(result.current.isResolvingRegion).toBe(false)
expect(result.current.regionId).toBe(1)
expect(result.current.boundId).toBe(7)
expect(ctx.addressStore.getState().selectedAddressId).toBeNull()
view.unmount()
})
})
}) })

View file

@ -27,6 +27,10 @@ const initialState: MockAuthState = {
} }
let state: MockAuthState = { ...initialState } let state: MockAuthState = { ...initialState }
// Simulates a consumer mounted above AuthProvider (see useRegion's
// hasAuthContext guard): `useAuthOptional()` returns null, exactly like the real
// hook when no provider is in scope.
let noAuthContext = false
export const login = jest.fn(async () => undefined) export const login = jest.fn(async () => undefined)
export const loginWithToken = jest.fn(async () => undefined) export const loginWithToken = jest.fn(async () => undefined)
@ -39,8 +43,13 @@ export function __setAuthState(next: Partial<MockAuthState>) {
state = { ...state, ...next } state = { ...state, ...next }
} }
export function __setNoAuthContext(next: boolean) {
noAuthContext = next
}
export function __resetAuthState() { export function __resetAuthState() {
state = { ...initialState } state = { ...initialState }
noAuthContext = false
login.mockClear() login.mockClear()
loginWithToken.mockClear() loginWithToken.mockClear()
register.mockClear() register.mockClear()
@ -63,7 +72,7 @@ export const useAuth = () => ({
updateUserDetails, updateUserDetails,
}) })
export const useAuthOptional = () => useAuth() export const useAuthOptional = () => (noAuthContext ? null : useAuth())
export const useUserDetails = () => state.userDetails export const useUserDetails = () => state.userDetails
export default { AuthProvider, useAuth, useAuthOptional, useUserDetails } export default { AuthProvider, useAuth, useAuthOptional, useUserDetails }

Binary file not shown.

Before

Width:  |  Height:  |  Size: 235 KiB

View file

@ -8635,3 +8635,162 @@ ADDRF-10 updated, ADDRF-36/37 now use the chooser map). web-ui typecheck clean.
- Also: raise-complaint now closes the menu (instead of stacking a second Modal on - Also: raise-complaint now closes the menu (instead of stacking a second Modal on
top), and BottomDialog backdrop sits inside the KeyboardAvoidingView so outside top), and BottomDialog backdrop sits inside the KeyboardAvoidingView so outside
taps reliably dismiss. Verified: user-ui typecheck clean; order-menu 10/10. taps reliably dismiss. Verified: user-ui typecheck clean; order-menu 10/10.
[2026-10-21 23:43:25 IST] Centralize color tokens — shared foundation (no visual change intended).
- NEW packages/shared/design-tokens.ts: single source of truth (brand/flash/purple/gray
scales, tailwindPalette, semantic roles, order/coupon status colors, dashboard tile
palette, tag accents, me-menu icons, gradients, legacy aliases, flat colors map).
- packages/shared/index.ts: re-export ./design-tokens.
- packages/ui/src/lib/theme-colors.ts: now re-exports colors/colorsType from
@packages/shared/design-tokens (common-ui API unchanged).
- packages/ui/src/theme.ts: remove stale commented palette block.
- packages/ui/index.ts: re-export brand/flash/purple/gray/tailwindPalette/semantic/
legacyColors/role palettes/gradients.
- NEW scripts/generate-design-tokens-css.ts + root "colors:gen" script.
- GENERATED packages/shared/styles/theme.css (brand/flash/semantic + font tokens).
Next: web @theme imports, admin-ui Metro/TS aliases, then app literal migrations.
[2026-10-22 08:52:11 IST] Add tests/e2e/basic-sanity-runbook.yaml — complete runbook for the executed basic-sanity E2E.
+ tests/e2e/basic-sanity-runbook.yaml (new, 671 lines)
Records fixture IDs, admin tRPC mutations, cache rebuild versions, Maestro UI
steps and coordinates, assertions, final state, and deviations/caveats.
[2026-10-22 11:14:29 IST] E2E: add stable testIDs for the basic-sanity Maestro flow.
- apps/user-ui/components/ProductCard.tsx: wrap the card in a View with
testID={`product-card-${item.id}`} (keep the inner "product-card" for existing
tests), add testID={`add-to-cart-${item.id}`} around the mini add icon (keep
"add-to-cart-icon"), and testID={`out-of-stock-${item.id}`} inside the OOS badge
(keep "out-of-stock-badge").
- apps/user-ui/app/(drawer)/_layout.tsx: add tabBarButtonTestID tab-home/tab-offers/
tab-stores/tab-me and testID="tab-flash" on the custom flash tab button.
- apps/user-ui/src/components/location/LocationFallbackFlow.tsx: add
testID="location-close" to the close button.
- apps/user-ui/src/components/AddToCartDialog.tsx: slot row now carries
testID={`slot-option-${slot.id}`} so flows can select a known slot id.
- apps/user-ui/app/(drawer)/(tabs)/order-again/index.tsx: add offers-section/
combos-section and offers-show-more/combos-show-more testIDs.
- apps/user-ui/app/(drawer)/(tabs)/home/search-results/index.tsx: add
testID="search-empty" to the empty state.
- apps/user-ui/app/(drawer)/(tabs)/flash-delivery/_layout.tsx: add
testID="flash-unavailable" and testID="flash-unavailable-home".
- apps/user-ui/components/cart-page.tsx: add testID={`cart-sku-${item.skuId}`} to
each cart row and testID="cart-to-pay" on the total.
No behavior changes; IDs only.
[2026-10-22 11:26:00 IST] E2E: replace the percentage-based runbook with executable basic-sanity flows.
+ tests/e2e/basic-sanity-setup.sh: creates product A (2 SKUs), combo, dashboard tag,
2-hour slot, enables flash, uploads images, rebuilds caches; writes
tests/e2e/.basic-sanity.env and .basic-sanity-state.json.
+ tests/e2e/basic-sanity.yaml: Maestro flow using testIDs only (offers/combo,
home tag, search, regular checkout, My Orders, flash checkout).
+ tests/e2e/basic-sanity-admin-update.sh: packages both orders, disables flash,
suspends the combo, marks the 1kg SKU OOS, rebuilds caches.
+ tests/e2e/basic-sanity-after-admin.yaml: packaged glimpse, flash-disabled,
suspended-search, and OOS assertions by testID.
+ tests/e2e/run-basic-sanity.sh: one-command setup -> flow -> admin update -> checks.
[2026-10-22 12:53:07 IST] E2E basic-sanity: make every tap target reliably hittable.
- LocationFallbackFlow.tsx: add testID={`location-address-name-${address.id}`} on
the saved-address name text and testID="location-add-back-label" on the add-
address Back label. The card/testID wrappers span full width, so Maestro's
centre tap was landing on empty header space / the Default badge instead of
the touchable.
- home/index.tsx: add testID="home-tag-strip" to the horizontal dashboard-tag
ScrollView so flows can swipe the strip by id instead of screen percentages.
- order-again/index.tsx: move offers-show-more/combos-show-more from the
touchable to its inner MyText (the touchable is full width and sits behind the
floating cart bar; the text target is stable after scrolling).
- tests/e2e/basic-sanity.yaml: tap location-address-name, wait for home-search
before switching tabs, scroll the tag strip by id, add an extra scroll before
tapping combos-show-more/checkout-button (they start behind the floating cart
bar), centre the flash product before tapping, and reach My Orders via
order-success-continue -> Me -> My Orders instead of the racy View My Orders
handler.
- tests/e2e/basic-sanity-after-admin.yaml: assert product-card-${SKU_COMBO} is
absent instead of asserting an empty search results screen (search tokenises
the run id and still matches the two A variants).
- tests/e2e/run-basic-sanity.sh: pass SKU_COMBO to the post-admin flow.
Verified: main flow regular + flash segments, admin update, and post-admin all
pass on iOS 18.6 / device 5A64695E.
[2026-10-22 13:05:00 IST] E2E basic-sanity: finish the flow with a relaunch before My Orders.
- tests/e2e/basic-sanity.yaml: the flash catalogue is a nested stack with no
bottom tab bar, so Phase 5 cannot tap tab-me directly. Relaunch Expo Go, clear
the optional address sheet, then go Me -> My Orders and assert the order.
Verified the complete main flow end-to-end (regular + flash orders), the admin
update (packaged 2632/2633), and the post-admin flow on iOS 18.6.
[2026-10-22 13:10:00 IST] E2E: remove the stale percentage-based basic-sanity runbook.
- tests/e2e/basic-sanity-runbook.yaml: superseded by the executable, testID-only
basic-sanity.yaml + basic-sanity-after-admin.yaml + setup/admin/runner scripts.
[2026-10-22 13:14:00 IST] E2E setup: clear stale SANITY cart rows before a new run.
- tests/e2e/basic-sanity-setup.sh: resolve the local D1 sqlite file and delete
cart_items whose SKU belongs to a SANITY-% product, so a failed previous run
cannot leak items into the next regular/flash checkout.
[2026-10-22 13:30:00 IST] E2E: document the basic-sanity run.
+ tests/e2e/basic-sanity.md: prerequisites, one-command/manual run, env vars,
behaviour notes, troubleshooting, and cleanup.
- tests/e2e/basic-sanity.yaml / basic-sanity-after-admin.yaml: header now points
to basic-sanity.md.
- tests/e2e/basic-sanity-admin-update.sh: DB discovery uses the first matching
sqlite file, matching the setup script.
[2026-10-22 13:55:00 IST] DIAGNOSTIC (temporary): log the region startup decision.
- apps/user-ui/src/hooks/useRegion.ts: log locationStatus, resolved region,
auth state, default/sole address ids + regions, cache snapshot, live address
ids, and the final anchor so we can see why the address chooser is shown when
location is off and the user has a default address. Reverted after diagnosis.
[2026-10-22 13:56:00 IST] DIAGNOSTIC (reverted): remove the temporary region log.
- apps/user-ui/src/hooks/useRegion.ts: restored to its pre-diagnostic state; no
functional change. Finding: the startup decision can be settled by the
`useRegion` instance in `HealthTestWrapper` (above `AuthProvider`), which has
no auth context, so the default address is never used as the anchor.
[2026-10-22 14:02:00 IST] Fix region startup decision being settled above AuthProvider.
- apps/user-ui/src/hooks/useRegion.ts: instances mounted outside AuthProvider
(UpdateChecker / HealthTestWrapper / WebViewWrapper, via
useGetEssentialConsts) no longer settle the one-shot launch decision. They have
no auth context and therefore cannot see the default/sole address, so they
forced the address chooser when location was off and the user had a default
address. The instance inside AuthProvider (LocationTestWrapper) now owns the
decision.
Verified on iOS 18.6 / device 5A64695E with Location Services off and permission
denied: cold launch now lands on Home in the default address's region (one
address per John Wick default, plus the non-default Shafi address). tsc
--noEmit clean.
[2026-10-22 14:15:00 IST] Add a regression test for the AuthProvider-scoped startup decision.
- apps/user-ui/tests/mocks/auth-context.tsx: add `__setNoAuthContext(true)`
so a test can simulate a `useRegion` consumer mounted above AuthProvider
(UpdateChecker / HealthTestWrapper / WebViewWrapper). Reset it per test.
- apps/user-ui/tests/lib/use-region.test.tsx: REGION-27 asserts the
no-auth-context instance stays unresolved when location is off, then the
authenticated instance adopts the default address's region/bound.
- apps/user-ui/JEST-TEST-CASES.md: document REGION-27.
Verified: `npx jest --config tests/jest.config.js tests/lib/use-region.test.tsx`
passes 27/27; REGION-27 fails when the `hasAuthContext` guard is disabled, so it
is a real regression test for the fix. Tests typecheck still reports the
pre-existing `packages/ui/src/components/bottom-dropdown.tsx(89,5)` Timeout
typing error (unrelated to this change).
[2026-10-22 14:50:00 IST] TEMPORARY render-loop probe (diagnostic, to be removed).
- apps/user-ui/src/lib/render-probe.tsx: dev-only React.Profiler wrapper that
logs commits per second with the active Expo route to console and POSTs the
same summary to http://127.0.0.1:9099/render for capture outside Metro.
- apps/user-ui/app/_layout.tsx: wrap <Stack /> in RenderCommitProbe.
[2026-10-22 15:05:00 IST] Render-loop investigation (temporary probes, still in tree).
- Added useRenderProbe() to the route Profiler and instrumented TabLayoutWrapper,
LocationBar, FloatingCartBar, NextOrderGlimpse, LocationTestWrapper, the tabs
layout, and ProductCard. The probe writes `[render-probe]` console lines and
POSTs summaries to http://127.0.0.1:9099/render.
- Findings while idling on the main tabs: no runaway per-frame loop; Offers /
Stores / Flash show exactly one root commit every ~5s. ProductCard re-renders
6x per 5s window while Stores is active, from the still-mounted Offers tab.
Cause: ProductCard.tsx sets an unused `updater` state every 5000ms; the state
value is never read, but it forces every card to re-render forever.
- Me was idle after HMR settled (~2 commits/minute). Home was idle after entry.
A >15 commits/s burst during HMR was the only high-frequency window.

View file

@ -0,0 +1,45 @@
/* AUTO-GENERATED from packages/shared/design-tokens.ts — run `bun run colors:gen` */
@theme {
--color-brand-25: #F5FAFF;
--color-brand-50: #EFF8FF;
--color-brand-100: #D1E9FF;
--color-brand-200: #B2DDFF;
--color-brand-300: #84CAFF;
--color-brand-400: #53B1FD;
--color-brand-500: #2E90FA;
--color-brand-600: #1570EF;
--color-brand-700: #175CD3;
--color-brand-800: #1849A9;
--color-brand-900: #194185;
--color-flash-25: #FFF5F6;
--color-flash-50: #FFE8EA;
--color-flash-100: #FFD1D6;
--color-flash-200: #FFA3AE;
--color-flash-300: #FF7585;
--color-flash-400: #F81260;
--color-flash-500: #E11D48;
--color-flash-600: #C40E50;
--color-flash-700: #9E0A3F;
--color-success: #10B981;
--color-success-strong: #059669;
--color-success-soft: #D1FAE5;
--color-danger: #EF4444;
--color-danger-strong: #DC2626;
--color-danger-soft: #FEE2E2;
--color-warning: #F59E0B;
--color-warning-strong: #D97706;
--color-warning-soft: #FEF3C7;
--color-info: #3B82F6;
--color-info-strong: #2563EB;
--color-info-soft: #EFF8FF;
--color-pink-soft: #fff0f6;
--color-ink: #333;
--color-canvas-muted: #f2f2f2;
--color-accent: #F83758;
--font-sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
--font-display: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

View file

@ -0,0 +1,17 @@
{
"runId": "261022055216",
"productName": "SANITY-261022055216-A",
"comboName": "SANITY-261022055216-COMBO",
"tagName": "SANITY-261022055216",
"productAId": 155,
"sku500g": 157,
"sku1kg": 158,
"comboId": 156,
"skuCombo": 159,
"tagId": 12,
"slotId": 2121,
"slotDeliveryTime": "2026-10-22T07:52:19.000Z",
"slotFreezeTime": "2026-10-22T07:37:19.000Z",
"imageUrl": "https://da9b1aa7c1951c23e2c0c3246ba68a58.r2.cloudflarestorage.com/meatfarmer-dev/product-images/1792648337125.png?X-Amz-Expires=180&X-Amz-Date=20261022T055217Z&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=8fab47503efb9547b50e4fb317e35cc7%2F20261022%2Fapac%2Fs3%2Faws4_request&X-Amz-SignedHeaders=host&X-Amz-Signature=5bf72c1df987a4f4af776f461edfcfd100a02ab04daca3ae6645c20bb43e9e63",
"comboImageUrl": "https://da9b1aa7c1951c23e2c0c3246ba68a58.r2.cloudflarestorage.com/meatfarmer-dev/product-images/1792648337148.png?X-Amz-Expires=180&X-Amz-Date=20261022T055217Z&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=8fab47503efb9547b50e4fb317e35cc7%2F20261022%2Fapac%2Fs3%2Faws4_request&X-Amz-SignedHeaders=host&X-Amz-Signature=671d9f1bf8312e6138995ff391ae64d692c9ed8b743ccd51eb011595c4680389"
}

View file

@ -0,0 +1,11 @@
RUN_ID=261022055216
PRODUCT_NAME=SANITY-261022055216-A
COMBO_NAME=SANITY-261022055216-COMBO
TAG_NAME=SANITY-261022055216
PRODUCT_A_ID=155
SKU_500G=157
SKU_1KG=158
COMBO_ID=156
SKU_COMBO=159
TAG_ID=12
SLOT_ID=2121

View file

@ -1,167 +0,0 @@
appId: ${APP_ID || "in.freshyo.adminui"}
env:
APP_ID: ${APP_ID || "in.freshyo.adminui"}
STAFF_NAME: ${STAFF_NAME || ""}
STAFF_PASSWORD: ${STAFF_PASSWORD || ""}
PRODUCT_NAME: ${PRODUCT_NAME || "E2E Test Product"}
STORE_ID: ${STORE_ID || 1}
SKU1_QTY: ${SKU1_QTY || "500 g"}
SKU1_PRICE: ${SKU1_PRICE || "199"}
SKU1_MRP: ${SKU1_MRP || "249"}
SKU2_QTY: ${SKU2_QTY || "1 kg"}
SKU2_PRICE: ${SKU2_PRICE || "349"}
SKU2_MRP: ${SKU2_MRP || "399"}
SKU2_FLASH_PRICE: ${SKU2_FLASH_PRICE || "299"}
tags:
- products
- smoke
---
- addMedia:
- './assets/test-product.png'
- launchApp:
clearState: true
permissions:
storage: allow
- extendedWaitUntil:
visible:
id: login-name-input
timeout: 180000
- runFlow:
when:
visible:
id: login-name-input
commands:
- runFlow: subflows/login.yaml
- tapOn:
id: add-product-menu-item
- assertVisible:
id: product-name-input
- tapOn:
id: product-name-input
- inputText: ${PRODUCT_NAME}
- hideKeyboard
- scrollUntilVisible:
element:
id: product-store-dropdown
direction: DOWN
- tapOn:
id: product-store-dropdown
- tapOn:
id: product-store-dropdown-option-${STORE_ID}
- scrollUntilVisible:
element:
id: product-type-dropdown
direction: DOWN
- tapOn:
id: product-type-dropdown
- tapOn:
id: product-type-dropdown-option-item
- scrollUntilVisible:
element:
id: variant-0-attr-0-value
direction: DOWN
- tapOn:
id: variant-0-attr-0-value
- inputText: ${SKU1_QTY}
- hideKeyboard
- scrollUntilVisible:
element:
id: variant-0-price
direction: DOWN
- tapOn:
id: variant-0-price
- inputText: ${SKU1_PRICE}
- hideKeyboard
- scrollUntilVisible:
element:
id: variant-0-market-price
direction: DOWN
- tapOn:
id: variant-0-market-price
- inputText: ${SKU1_MRP}
- hideKeyboard
- scrollUntilVisible:
element:
id: variant-0-image-add
direction: DOWN
- tapOn:
id: variant-0-image-add
- runFlow: subflows/pick-image.yaml
- scrollUntilVisible:
element:
id: add-variant-button
direction: UP
- tapOn:
id: add-variant-button
- scrollUntilVisible:
element:
id: variant-1-attr-0-value
direction: DOWN
- tapOn:
id: variant-1-attr-0-value
- inputText: ${SKU2_QTY}
- hideKeyboard
- scrollUntilVisible:
element:
id: variant-1-price
direction: DOWN
- tapOn:
id: variant-1-price
- inputText: ${SKU2_PRICE}
- hideKeyboard
- scrollUntilVisible:
element:
id: variant-1-market-price
direction: DOWN
- tapOn:
id: variant-1-market-price
- inputText: ${SKU2_MRP}
- hideKeyboard
- scrollUntilVisible:
element:
id: variant-1-flash
direction: DOWN
- tapOn:
id: variant-1-flash
- scrollUntilVisible:
element:
id: variant-1-flash-price
direction: DOWN
- tapOn:
id: variant-1-flash-price
- inputText: ${SKU2_FLASH_PRICE}
- hideKeyboard
- scrollUntilVisible:
element:
id: variant-1-image-add
direction: DOWN
- tapOn:
id: variant-1-image-add
- runFlow: subflows/pick-image.yaml
- scrollUntilVisible:
element:
id: create-product-button
direction: DOWN
- tapOn:
id: create-product-button
- assertVisible: 'Product created successfully!'
- tapOn: 'OK'

View file

@ -1,61 +0,0 @@
appId: ${APP_ID || "in.freshyo.adminui"}
env:
APP_ID: ${APP_ID || "in.freshyo.adminui"}
STAFF_NAME: ${STAFF_NAME || ""}
STAFF_PASSWORD: ${STAFF_PASSWORD || ""}
PRODUCT_NAME: ${PRODUCT_NAME || "E2E Test Product"}
SLOT_DATE: ${SLOT_DATE || ""}
SLOT_HOUR: ${SLOT_HOUR || ""}
SLOT_MIN: ${SLOT_MIN || ""}
tags:
- slots
- smoke
---
- launchApp
- extendedWaitUntil:
visible:
id: 'login-name-input|add-product-menu-item'
timeout: 180000
- runFlow:
when:
visible:
id: login-name-input
commands:
- runFlow: subflows/login.yaml
- openLink: freshyoadmin://dashboard/slots/add
- extendedWaitUntil:
visible:
id: delivery-date-picker
timeout: 30000
- runFlow: subflows/set-slot-times.yaml
- scrollUntilVisible:
element:
id: slot-products-selector
direction: DOWN
- tapOn:
id: slot-products-selector
- tapOn:
id: slot-products-selector-search
- inputText: ${PRODUCT_NAME}
- hideKeyboard
- tapOn:
id: 'slot-products-selector-option-.*'
index: 0
- tapOn:
id: 'slot-products-selector-option-.*'
index: 1
- tapOn:
id: slot-products-selector-done
- scrollUntilVisible:
element:
id: create-slot-button
direction: DOWN
- tapOn:
id: create-slot-button
- assertVisible: 'Slot created successfully!'
- tapOn: 'OK'

View file

@ -0,0 +1,166 @@
#!/usr/bin/env bash
# Applies the admin-side changes between basic-sanity.yaml and
# basic-sanity-after-admin.yaml:
# - mark both new orders packaged
# - turn flash delivery off
# - suspend the combo
# - mark the 1kg SKU out of stock
# - rebuild caches
#
# Usage:
# ./tests/e2e/basic-sanity-admin-update.sh
#
# Reads tests/e2e/.basic-sanity-state.json.
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$ROOT"
API="${API:-https://devbackend.freshyo.in/api/trpc}"
LOCAL_API="${LOCAL_API:-http://localhost:8787}"
STATE_FILE="$ROOT/tests/e2e/.basic-sanity-state.json"
TOKEN="${ADMIN_TOKEN:-$(cat /tmp/dev_admin_token 2>/dev/null || true)}"
DB="$(ls apps/backend/.wrangler/state/v3/d1/miniflare-D1DatabaseObject/*.sqlite 2>/dev/null | head -n 1)"
if [[ ! -f "$STATE_FILE" ]]; then
echo "Missing $STATE_FILE. Run basic-sanity-setup.sh first." >&2
exit 1
fi
if [[ -z "$TOKEN" ]]; then
echo "ADMIN_TOKEN is required (or put the token in /tmp/dev_admin_token)" >&2
exit 1
fi
export API LOCAL_API STATE_FILE TOKEN DB
python3 - <<'PY'
import json
import os
import subprocess
import urllib.error
import urllib.request
from pathlib import Path
API = os.environ["API"].rstrip("/")
LOCAL_API = os.environ["LOCAL_API"].rstrip("/")
TOKEN = os.environ["TOKEN"]
STATE = json.loads(Path(os.environ["STATE_FILE"]).read_text())
DB = os.environ["DB"]
def trpc(procedure, payload):
req = urllib.request.Request(
f"{API}/{procedure}",
data=json.dumps(payload).encode(),
headers={
"content-type": "application/json",
"authorization": f"Bearer {TOKEN}",
"User-Agent": "freshyo-basic-sanity/1.0",
},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=60) as resp:
parsed = json.loads(resp.read())
except urllib.error.HTTPError as exc:
detail = exc.read().decode(errors="replace")
raise SystemExit(f"{procedure} failed ({exc.code}): {detail}") from exc
if "error" in parsed:
raise SystemExit(f"{procedure} failed: {json.dumps(parsed['error'])}")
return parsed["result"]["data"]
def db_query(sql):
out = subprocess.check_output(["sqlite3", DB, sql], text=True)
return [line for line in out.splitlines() if line.strip()]
sku_ids = [STATE["sku500g"], STATE["sku1kg"], STATE["skuCombo"]]
sku_csv = ",".join(str(int(sku)) for sku in sku_ids)
order_ids = db_query(
"SELECT DISTINCT o.id FROM orders o "
"JOIN order_items oi ON oi.order_id = o.id "
f"WHERE oi.sku_id IN ({sku_csv}) "
"AND o.created_at >= datetime('now', '-6 hours') "
"ORDER BY o.id;"
)
if len(order_ids) != 2:
raise SystemExit(
f"Expected 2 new orders for the fixtures, found {len(order_ids)}: {order_ids}"
)
for order_id in order_ids:
trpc("admin.order.updatePackaged", {"orderId": str(order_id), "isPackaged": True})
print(f"packaged order {order_id}")
# Flash off.
trpc(
"admin.region.updateBoundSettings",
{
"boundId": 1,
"settings": [{"key": "isFlashDeliveryEnabled", "value": "false"}],
},
)
print("flash delivery disabled")
# Suspend the combo SKU.
trpc(
"admin.product.updateProduct",
{
"id": STATE["comboId"],
"name": STATE["comboName"],
"shortDescription": "Basic sanity combo",
"longDescription": "Combo of the two product A variants",
"storeId": 1,
"incrementStep": 1,
"productType": "combo",
"skus": [
{
"id": STATE["skuCombo"],
"price": 499,
"marketPrice": 549,
"images": [STATE["comboImageUrl"]],
"isFlashAvailable": True,
"flashPrice": 399,
"isOutOfStock": False,
"isOffer": False,
"isComboOnly": False,
"isDeleted": False,
"isSuspended": True,
"features": [{"featureName": "quantity", "featureValue": "1 combo"}],
"comboItems": [
{"skuId": STATE["sku500g"]},
{"skuId": STATE["sku1kg"]},
],
}
],
},
)
print(f"suspended combo SKU {STATE['skuCombo']}")
# 1kg out of stock; 500g stays in stock.
trpc(
"admin.product.toggleOutOfStock",
{
"id": STATE["productAId"],
"skuIds": [STATE["sku1kg"]],
"isOutOfStock": True,
},
)
print(f"marked SKU {STATE['sku1kg']} out of stock")
req = urllib.request.Request(
f"{LOCAL_API}/api/test/rebuild?regionId=1",
data=b"",
headers={
"authorization": f"Bearer {TOKEN}",
"User-Agent": "freshyo-basic-sanity/1.0",
},
method="POST",
)
with urllib.request.urlopen(req, timeout=120) as resp:
print("cache rebuild:", resp.read().decode(errors="replace"))
PY

View file

@ -0,0 +1,99 @@
# Basic-sanity post-admin assertions.
# See tests/e2e/basic-sanity.md for full instructions and troubleshooting.
#
# Prerequisite: Expo Go is logged in as the test user and has address ADDRESS_ID.
#
# Run this AFTER tests/e2e/basic-sanity-admin-update.sh has:
# - packaged both orders
# - disabled flash delivery
# - suspended the combo
# - marked the 1kg SKU out of stock
# - rebuilt the caches
#
# Required env: PRODUCT_NAME, COMBO_NAME, SKU_1KG, SKU_COMBO.
appId: host.exp.Exponent
name: basic-sanity-after-admin
tags:
- e2e
- basic-sanity
---
- stopApp
- openLink: exp://127.0.0.1:8081
- extendedWaitUntil:
visible:
id: "location-address-name-${ADDRESS_ID}"
timeout: 60000
optional: true
- runFlow:
when:
visible:
id: "location-address-name-${ADDRESS_ID}"
commands:
- tapOn:
id: "location-address-name-${ADDRESS_ID}"
- extendedWaitUntil:
visible:
id: "tab-home"
timeout: 90000
- extendedWaitUntil:
visible:
id: "home-search"
timeout: 60000
- waitForAnimationToEnd:
timeout: 5000
# Both upcoming orders are packaged: the glimpse tracker shows the Packed dot.
- extendedWaitUntil:
visible:
id: "next-order-glimpse"
timeout: 30000
- assertVisible:
id: "order-status-dot-packed"
- assertNotVisible:
text: "PLACED"
# Flash delivery is off.
- tapOn:
id: "tab-flash"
- extendedWaitUntil:
visible:
id: "flash-unavailable"
timeout: 15000
# Suspended combo is no longer searchable.
- tapOn:
id: "tab-home"
- tapOn:
id: "home-search"
- extendedWaitUntil:
visible:
id: "search-input"
timeout: 20000
- tapOn:
id: "search-input"
- eraseText
- inputText: "${COMBO_NAME}"
- hideKeyboard
# Search tokenises the run id, so the two A variants still match. The suspended
# combo itself must be gone from the results.
- extendedWaitUntil:
visible:
id: "product-card-${SKU_1KG}"
timeout: 20000
- assertNotVisible:
id: "product-card-${SKU_COMBO}"
# The 1kg SKU is still searchable but flagged out of stock.
- tapOn:
id: "search-input"
- eraseText
- inputText: "${PRODUCT_NAME}"
- hideKeyboard
- extendedWaitUntil:
visible:
id: "product-card-${SKU_1KG}"
timeout: 20000
- assertVisible:
id: "out-of-stock-${SKU_1KG}"

312
tests/e2e/basic-sanity-setup.sh Executable file
View file

@ -0,0 +1,312 @@
#!/usr/bin/env bash
# Creates the fixtures used by tests/e2e/basic-sanity.yaml.
#
# Usage:
# ./tests/e2e/basic-sanity-setup.sh
#
# Optional environment variables:
# ADMIN_TOKEN admin bearer token (defaults to /tmp/dev_admin_token)
# RUN_ID unique suffix for fixture names (defaults to UTC timestamp)
# IMAGE image uploaded for every product/tag
# API admin tRPC base URL
# LOCAL_API local test-support base URL
#
# Writes tests/e2e/.basic-sanity.env and tests/e2e/.basic-sanity-state.json.
# Neither file contains credentials.
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$ROOT"
API="${API:-https://devbackend.freshyo.in/api/trpc}"
LOCAL_API="${LOCAL_API:-http://localhost:8787}"
RUN_ID="${RUN_ID:-$(date -u +%y%m%d%H%M%S)}"
IMAGE="${IMAGE:-$ROOT/apps/user-ui/assets/images/icon.png}"
ENV_FILE="$ROOT/tests/e2e/.basic-sanity.env"
STATE_FILE="$ROOT/tests/e2e/.basic-sanity-state.json"
DB="$(ls apps/backend/.wrangler/state/v3/d1/miniflare-D1DatabaseObject/*.sqlite 2>/dev/null | head -n 1)"
TOKEN="${ADMIN_TOKEN:-$(cat /tmp/dev_admin_token 2>/dev/null || true)}"
if [[ -z "$TOKEN" ]]; then
echo "ADMIN_TOKEN is required (or put the token in /tmp/dev_admin_token)" >&2
exit 1
fi
if [[ ! -f "$IMAGE" ]]; then
echo "Image not found: $IMAGE" >&2
exit 1
fi
export API LOCAL_API RUN_ID IMAGE ENV_FILE STATE_FILE DB TOKEN
python3 - <<'PY'
import json
import os
import sqlite3
import urllib.error
import urllib.request
from datetime import datetime, timedelta, timezone
from pathlib import Path
API = os.environ["API"].rstrip("/")
LOCAL_API = os.environ["LOCAL_API"].rstrip("/")
RUN_ID = os.environ["RUN_ID"]
IMAGE = os.environ["IMAGE"]
ENV_FILE = Path(os.environ["ENV_FILE"])
STATE_FILE = Path(os.environ["STATE_FILE"])
DB = os.environ["DB"]
TOKEN = os.environ["TOKEN"]
# Drop cart rows left by a previous SANITY run so the new flow starts clean.
if DB:
try:
with sqlite3.connect(DB, timeout=10) as conn:
conn.execute(
"DELETE FROM cart_items WHERE sku_id IN ("
"SELECT id FROM product_skus WHERE product_id IN ("
"SELECT id FROM product_info WHERE name LIKE 'SANITY-%'))"
)
except sqlite3.Error as exc:
print(f"warning: could not clear stale SANITY cart rows: {exc}")
def request(url, *, method="GET", payload=None, headers=None, raw=None):
body = raw
hdrs = {"User-Agent": "freshyo-basic-sanity/1.0"}
if headers:
hdrs.update(headers)
if payload is not None:
body = json.dumps(payload).encode()
hdrs["content-type"] = "application/json"
req = urllib.request.Request(url, data=body, headers=hdrs, method=method)
try:
with urllib.request.urlopen(req, timeout=60) as resp:
return resp.status, resp.read()
except urllib.error.HTTPError as exc:
detail = exc.read().decode(errors="replace")
raise SystemExit(f"{method} {url} failed ({exc.code}): {detail}") from exc
def trpc(procedure, payload):
status, data = request(
f"{API}/{procedure}",
method="POST",
payload=payload,
headers={"authorization": f"Bearer {TOKEN}"},
)
parsed = json.loads(data)
if "error" in parsed:
raise SystemExit(f"{procedure} failed: {json.dumps(parsed['error'])}")
return parsed["result"]["data"]
def upload(url):
data = Path(IMAGE).read_bytes()
status, _ = request(
url,
method="PUT",
raw=data,
headers={"content-type": "image/png"},
)
if status not in (200, 201):
raise SystemExit(f"upload failed with HTTP {status}")
def iso(dt):
return dt.strftime("%Y-%m-%dT%H:%M:%S.000Z")
product_name = f"SANITY-{RUN_ID}-A"
combo_name = f"SANITY-{RUN_ID}-COMBO"
tag_name = f"SANITY-{RUN_ID}"
# 1. Three product images.
uploads = trpc(
"common.generateUploadUrls",
{"contextString": "product_info", "mimeTypes": ["image/png"] * 3},
)["uploadUrls"]
for url in uploads:
upload(url)
# 2. Product A with two SKUs (500g flash-eligible, 1kg regular).
product_a = trpc(
"admin.product.createProduct",
{
"name": product_name,
"shortDescription": "Basic sanity product A",
"longDescription": "Created by tests/e2e/basic-sanity-setup.sh",
"storeId": 1,
"incrementStep": 1,
"productType": "item",
"skus": [
{
"price": 199,
"marketPrice": 249,
"images": [uploads[0]],
"isFlashAvailable": True,
"flashPrice": 149,
"isOutOfStock": False,
"isOffer": True,
"isComboOnly": False,
"isDeleted": False,
"isSuspended": False,
"features": [{"featureName": "quantity", "featureValue": "500g"}],
"comboItems": [],
},
{
"price": 349,
"marketPrice": 399,
"images": [uploads[1]],
"isFlashAvailable": False,
"flashPrice": None,
"isOutOfStock": False,
"isOffer": True,
"isComboOnly": False,
"isDeleted": False,
"isSuspended": False,
"features": [{"featureName": "quantity", "featureValue": "1kg"}],
"comboItems": [],
},
],
},
)["product"]
sku_500g, sku_1kg = [sku["id"] for sku in product_a["skus"]]
product_a_id = product_a["id"]
# 3. Combo product containing both A variants.
combo = trpc(
"admin.product.createProduct",
{
"name": combo_name,
"shortDescription": "Basic sanity combo",
"longDescription": "Combo of the two product A variants",
"storeId": 1,
"incrementStep": 1,
"productType": "combo",
"skus": [
{
"price": 499,
"marketPrice": 549,
"images": [uploads[2]],
"isFlashAvailable": True,
"flashPrice": 399,
"isOutOfStock": False,
"isOffer": False,
"isComboOnly": False,
"isDeleted": False,
"isSuspended": False,
"features": [{"featureName": "quantity", "featureValue": "1 combo"}],
"comboItems": [{"skuId": sku_500g}, {"skuId": sku_1kg}],
}
],
},
)["product"]
sku_combo = combo["skus"][0]["id"]
combo_id = combo["id"]
# 4. Dashboard tag. createProductTag's productIds are product_skus ids.
try:
tag = trpc(
"admin.product.createProductTag",
{
"tagName": tag_name,
"tagDescription": "Basic sanity dashboard tag",
"isDashboardTag": True,
"relatedStores": [1],
"productIds": [sku_500g, sku_1kg, sku_combo],
"uploadUrls": [],
},
)["tag"]
except SystemExit as exc:
if "already exists" not in str(exc):
raise
existing = trpc("admin.product.getProductTags", {"storeId": 1})
tags = existing.get("tags", existing) if isinstance(existing, dict) else existing
tag = next(t for t in tags if t["tagName"] == tag_name)
tag = trpc(
"admin.product.updateProductTag",
{
"id": tag["id"],
"productIds": [sku_500g, sku_1kg, sku_combo],
"relatedStores": [1],
"isDashboardTag": True,
},
)["tag"]
tag_id = tag["id"]
# 5. Slot: delivery in 2 hours, freeze 15 minutes before delivery.
delivery = datetime.now(timezone.utc) + timedelta(hours=2)
freeze = delivery - timedelta(minutes=15)
slot = trpc(
"admin.slots.createSlot",
{
"deliveryTime": iso(delivery),
"freezeTime": iso(freeze),
"isActive": True,
"skuIds": [sku_500g, sku_1kg, sku_combo],
"vendorSnippets": [],
"groupIds": [],
},
)["slot"]
slot_id = slot["id"]
# 6. Flash on, then rebuild every cache synchronously.
trpc(
"admin.region.updateBoundSettings",
{
"boundId": 1,
"settings": [{"key": "isFlashDeliveryEnabled", "value": "true"}],
},
)
status, rebuild_body = request(
f"{LOCAL_API}/api/test/rebuild?regionId=1",
method="POST",
headers={"authorization": f"Bearer {TOKEN}"},
)
if status != 200:
raise SystemExit(f"cache rebuild failed: {rebuild_body.decode(errors='replace')}")
state = {
"runId": RUN_ID,
"productName": product_name,
"comboName": combo_name,
"tagName": tag_name,
"productAId": product_a_id,
"sku500g": sku_500g,
"sku1kg": sku_1kg,
"comboId": combo_id,
"skuCombo": sku_combo,
"tagId": tag_id,
"slotId": slot_id,
"slotDeliveryTime": iso(delivery),
"slotFreezeTime": iso(freeze),
"imageUrl": uploads[0],
"comboImageUrl": uploads[2],
}
STATE_FILE.write_text(json.dumps(state, indent=2) + "\n")
env_lines = [
f"RUN_ID={RUN_ID}",
f"PRODUCT_NAME={product_name}",
f"COMBO_NAME={combo_name}",
f"TAG_NAME={tag_name}",
f"PRODUCT_A_ID={product_a_id}",
f"SKU_500G={sku_500g}",
f"SKU_1KG={sku_1kg}",
f"COMBO_ID={combo_id}",
f"SKU_COMBO={sku_combo}",
f"TAG_ID={tag_id}",
f"SLOT_ID={slot_id}",
]
ENV_FILE.write_text("\n".join(env_lines) + "\n")
print("Fixtures ready")
for key, value in state.items():
if key in {"imageUrl", "comboImageUrl"}:
continue
print(f" {key}: {value}")
print(f" state: {STATE_FILE}")
print(f" env: {ENV_FILE}")
PY

248
tests/e2e/basic-sanity.md Normal file
View file

@ -0,0 +1,248 @@
# Basic-sanity E2E
Executable, test-ID-only version of the basic-sanity scenario. It replaces the
old percentage/coordinate runbook.
## What it covers
1. **Offers / combo**
- Opens the Offers tab.
- Expands Combos.
- Opens the generated combo product.
- Checks the combo items and flash price.
2. **Dashboard tag**
- Swipes the horizontal tag strip by ID.
- Opens the generated tag.
- Checks both A variants and the combo are present.
3. **Regular order**
- Searches for the A product.
- Opens the 500g SKU.
- Adds it with the generated slot.
- Checks the cart row.
- Places the order.
- Opens My Orders and checks the product.
4. **Flash order**
- Opens the 1 Hr Delivery tab.
- Finds the generated 500g SKU near the end of the flash catalogue.
- Adds it and places the flash order.
5. **Post-admin assertions**
- Both orders are packaged (Packed dot, no PLACED).
- Flash delivery is disabled.
- The suspended combo is no longer searchable.
- The 1kg SKU is still searchable but flagged out of stock.
## Files
| File | Purpose |
| --- | --- |
| `basic-sanity-setup.sh` | Creates product A (500g + 1kg), the combo, dashboard tag, delivery slot and images. Enables flash, rebuilds caches, writes `.basic-sanity.env` and `.basic-sanity-state.json`. |
| `basic-sanity.yaml` | Main Maestro flow: regular order + flash order + My Orders. |
| `basic-sanity-admin-update.sh` | Packages the two new orders, disables flash, suspends the combo, marks the 1kg SKU out of stock, rebuilds caches. |
| `basic-sanity-after-admin.yaml` | Post-admin Maestro assertions. |
| `run-basic-sanity.sh` | Runs setup → main flow → admin update → post-admin flow. |
| `.basic-sanity.env` | Generated environment values. Do not edit by hand. |
| `.basic-sanity-state.json` | Generated fixture IDs and image URLs. Used by the admin update script. |
## Prerequisites
- iOS Simulator or connected iOS device with Maestro installed
(`~/.maestro/bin/maestro` by default).
- Expo Go installed and **logged in as the test user**.
- The test user has a saved address with ID `899` (or pass a different
`ADDRESS_ID`).
- Metro is serving the user app at `exp://127.0.0.1:8081`.
- The local backend is running at `http://localhost:8787` (used for the
synchronous cache rebuild).
- A valid admin token in `/tmp/dev_admin_token`, or exported as `ADMIN_TOKEN`.
- The app ID used by the flows is `host.exp.Exponent` (Expo Go).
## One-command run
```bash
cd /Users/mohammedshafiuddin/WebDev/freshyo
./tests/e2e/run-basic-sanity.sh
```
Optional overrides:
```bash
DEVICE=<maestro-device-id> \
ADDRESS_ID=899 \
ADMIN_TOKEN=<token> \
./tests/e2e/run-basic-sanity.sh
```
If only one simulator/device is connected, Maestro selects it automatically.
If several are connected, pass `DEVICE`.
## Manual step-by-step run
Use this when debugging a phase instead of running the whole scenario.
### 1. Create fixtures
```bash
cd /Users/mohammedshafiuddin/WebDev/freshyo
./tests/e2e/basic-sanity-setup.sh
source tests/e2e/.basic-sanity.env
```
The setup script prints the generated IDs and writes them to
`tests/e2e/.basic-sanity-state.json`.
### 2. Run the user flow
```bash
~/.maestro/bin/maestro test \
--device <device-id> \
-e PRODUCT_NAME="$PRODUCT_NAME" \
-e COMBO_NAME="$COMBO_NAME" \
-e SKU_500G="$SKU_500G" \
-e SKU_1KG="$SKU_1KG" \
-e SKU_COMBO="$SKU_COMBO" \
-e TAG_ID="$TAG_ID" \
-e SLOT_ID="$SLOT_ID" \
-e ADDRESS_ID="${ADDRESS_ID:-899}" \
tests/e2e/basic-sanity.yaml
```
### 3. Apply admin changes
```bash
./tests/e2e/basic-sanity-admin-update.sh
```
This expects **exactly two** orders for the current fixture SKUs. If the main
flow did not reach both checkouts, fix the failure and re-run from setup with a
fresh `RUN_ID` instead of continuing with a partial run.
### 4. Run post-admin assertions
```bash
~/.maestro/bin/maestro test \
--device <device-id> \
-e PRODUCT_NAME="$PRODUCT_NAME" \
-e COMBO_NAME="$COMBO_NAME" \
-e SKU_1KG="$SKU_1KG" \
-e SKU_COMBO="$SKU_COMBO" \
-e ADDRESS_ID="${ADDRESS_ID:-899}" \
tests/e2e/basic-sanity-after-admin.yaml
```
## Environment variables
### Setup script
| Variable | Default | Meaning |
| --- | --- | --- |
| `API` | `https://devbackend.freshyo.in/api/trpc` | Admin tRPC endpoint. |
| `LOCAL_API` | `http://localhost:8787` | Local backend used for `/api/test/rebuild`. |
| `RUN_ID` | UTC timestamp | Suffix for fixture names. Use a new value for every run. |
| `IMAGE` | `apps/user-ui/assets/images/icon.png` | Image uploaded for the generated products. |
| `ADMIN_TOKEN` | contents of `/tmp/dev_admin_token` | Admin bearer token. |
### Main flow
| Variable | Meaning |
| --- | --- |
| `PRODUCT_NAME` | Generated A product name (`SANITY-<RUN_ID>-A`). |
| `COMBO_NAME` | Generated combo name (`SANITY-<RUN_ID>-COMBO`). |
| `SKU_500G` | 500g SKU id. |
| `SKU_1KG` | 1kg SKU id. |
| `SKU_COMBO` | Combo SKU id. |
| `TAG_ID` | Generated dashboard tag id. |
| `SLOT_ID` | Generated delivery slot id. |
| `ADDRESS_ID` | Saved address to select at launch. Defaults to `899`. |
### Post-admin flow
`PRODUCT_NAME`, `COMBO_NAME`, `SKU_1KG`, `SKU_COMBO`, `ADDRESS_ID`.
## Important behaviour
- **No screen percentages.** Taps use `testID`s. Swipes use the tag strip's
`home-tag-strip` ID.
- **The location sheet is handled at launch.** The flow taps the saved address
name ID. There is no close button on the launch gate.
- **The cart/checkout buttons sit behind the floating cart bar.** The flows
scroll once more before tapping `combos-show-more`, `checkout-button`, and the
last combo/flash cards.
- **The flash catalogue is a nested stack with no bottom tab bar.** After the
flash order, the main flow relaunches Expo Go before opening My Orders.
- **The setup clears stale SANITY cart rows** so a failed previous run cannot
leak items into the next checkout.
- **Each setup creates a new fixture set** with a unique `RUN_ID`. Old SANITY
fixtures are not deleted automatically; they can remain visible in the
catalogue and tag strip. Use the cleanup section below if you need a pristine
dev DB.
## Troubleshooting
### `ADMIN_TOKEN is required`
Put a fresh admin token in `/tmp/dev_admin_token` or export `ADMIN_TOKEN`:
```bash
export ADMIN_TOKEN="<token>"
./tests/e2e/run-basic-sanity.sh
```
### `cache rebuild failed`
Make sure the local backend is running:
```bash
curl -X POST 'http://localhost:8787/api/test/rebuild?regionId=1' \
-H "authorization: Bearer $ADMIN_TOKEN"
```
### The flow stops at the location sheet
The test user must have the address ID passed as `ADDRESS_ID`. Check the saved
addresses in the app and use the matching id.
### The Offers/Combos Show More tap does nothing
The button is the last child and starts behind the floating cart bar. The flow
scrolls it up first. If you edit the flow, keep the extra `scroll` before the
tap.
### `place-order-button` is not found
The checkout screen opens but the button is below the fold. The flow uses
`scrollUntilVisible`; do not replace it with `assertVisible`.
### The flash product is not found
The generated SKU is appended near the end of the flash catalogue. Keep the
`timeout: 120000`, `speed: 90`, `visibilityPercentage: 50`, and
`centerElement: true` settings.
### Admin update says `Expected 2 new orders ... found N`
The main flow must place both the regular and flash orders first. If it failed
mid-way, run the whole runner again; setup creates fresh fixture SKUs, so the
partial run's orders will not match the new fixtures.
## Cleanup
After a successful run, the test fixture and order rows can be removed manually
if you want a pristine dev DB. The setup script creates them again on the next
run. The important cleanup targets are:
- orders for the generated SKUs, plus `order_items`, `order_status`, and
`coupon_usage` rows;
- `cart_items` for the generated SKUs;
- `product_combos`, `product_tags`, `product_market_stats`, `sku_features`,
`product_skus`, and `product_info` for the generated fixtures;
- the generated `product_tag_info` row and `delivery_slot_info` row;
- `upload_url_status` rows for the uploaded product images.
Rebuild the caches after cleanup:
```bash
curl -X POST 'http://localhost:8787/api/test/rebuild?regionId=1' \
-H "authorization: Bearer $ADMIN_TOKEN"
```
Do not run Drizzle migrations as part of this scenario.

View file

@ -0,0 +1,31 @@
open admin-ui
create a new product, with 2 skus. Upload images for it. Make one of them flash enabled
create a new combo product with 2 skus in it. Have images here too. Make it flash enabled
create a dashboard tag, add the only new products we created to it.
create new slots for the products. make the slots delivery time 2 hrs from now. freeze time should
be 15 mnts before delivery time. Add the newly created products to it.
go to app customization and ensure flash delivery is turned on.
wait for 60sec
open user-ui
go to offers tab from bottom navigation and find the newly created products. Ensure they are there
Ensuer the combo is present. Click on it, go to product details and ensure the list is correct
come back to the home tab and search for the products we created. Search and then add them to cart
in the slot we've created.
ensure the new tag we've created is visible and has our products in it
go to cart and then place the order.
ensure the order is visible in my orders.
then go to flash delivery and add those products to flash cart again. Create a flash order.
open admin-ui
go to manage orders and ensure both the orders are present and the items are proper there.
in both the orders mark all the items as packaged.
turn off the flash delivery in app customization
suspend one of the newly created products and mark one of them as out of stock
wait for 60sec
open user-ui
on the home screen find 2 orders' first order glimpse. See that they are packaged.
go to the flash screen and see ensure it is disabled
search for the suspended product and ensure it is not searchable and available
search for the out of stock product and ensure it is flagged out of stock.

377
tests/e2e/basic-sanity.yaml Normal file
View file

@ -0,0 +1,377 @@
# Basic-sanity user-side E2E.
# See tests/e2e/basic-sanity.md for full instructions and troubleshooting.
#
# Prerequisites:
# - Expo Go is already logged in as the test user.
# - The test user has the saved address ADDRESS_ID (defaults to 899).
# - Metro is serving exp://127.0.0.1:8081 and the dev backend is reachable.
#
# Fixtures are created by tests/e2e/basic-sanity-setup.sh. Run
# tests/e2e/run-basic-sanity.sh to execute setup -> this flow -> admin updates ->
# the post-admin flow. If you run this flow directly, pass every env value:
#
# maestro test \
# -e PRODUCT_NAME=SANITY-...-A \
# -e COMBO_NAME=SANITY-...-COMBO \
# -e SKU_500G=123 -e SKU_1KG=124 -e SKU_COMBO=125 \
# -e TAG_ID=12 -e SLOT_ID=2120 -e ADDRESS_ID=899 \
# tests/e2e/basic-sanity.yaml
#
# The flow uses testIDs only for taps. No hard-coded screen percentages.
appId: host.exp.Exponent
name: basic-sanity
tags:
- e2e
- basic-sanity
---
# ---------------------------------------------------------------------------
# Launch
# ---------------------------------------------------------------------------
- stopApp
- openLink: exp://127.0.0.1:8081
- extendedWaitUntil:
visible:
id: "location-address-name-${ADDRESS_ID}"
timeout: 60000
optional: true
- runFlow:
when:
visible:
id: "location-address-name-${ADDRESS_ID}"
commands:
- tapOn:
id: "location-address-name-${ADDRESS_ID}"
- extendedWaitUntil:
visible:
id: "tab-home"
timeout: 90000
- extendedWaitUntil:
visible:
id: "home-search"
timeout: 60000
- waitForAnimationToEnd:
timeout: 3000
# ---------------------------------------------------------------------------
# Phase 1: Offers tab, Show More, combo detail
# ---------------------------------------------------------------------------
- tapOn:
id: "tab-offers"
- extendedWaitUntil:
visible:
id: "offers-section"
timeout: 30000
- waitForAnimationToEnd:
timeout: 3000
- scrollUntilVisible:
element:
id: "combos-show-more"
direction: DOWN
timeout: 20000
# The button is the last child and initially sits behind the floating cart bar
# and the tab bar. One more scroll lifts it into the tappable area.
- scroll
- waitForAnimationToEnd:
timeout: 1000
- tapOn:
id: "combos-show-more"
waitToSettleTimeoutMs: 2000
- waitForAnimationToEnd:
timeout: 2000
- scrollUntilVisible:
element:
id: "product-card-${SKU_COMBO}"
direction: DOWN
timeout: 30000
# The last combo card reaches the bottom edge behind the floating cart bar.
- scroll
- waitForAnimationToEnd:
timeout: 1000
- tapOn:
id: "product-card-${SKU_COMBO}"
- scrollUntilVisible:
element:
id: "product-combo-items"
direction: DOWN
timeout: 30000
- assertVisible:
id: "combo-item-${SKU_500G}"
- assertVisible:
id: "combo-item-${SKU_1KG}"
- scrollUntilVisible:
element:
id: "product-flash-price"
direction: UP
timeout: 10000
- assertVisible:
id: "product-flash-price"
# Relaunch to return to Home deterministically (the native stack header back
# button has no testID).
- stopApp
- openLink: exp://127.0.0.1:8081
- extendedWaitUntil:
visible:
id: "location-address-name-${ADDRESS_ID}"
timeout: 60000
optional: true
- runFlow:
when:
visible:
id: "location-address-name-${ADDRESS_ID}"
commands:
- tapOn:
id: "location-address-name-${ADDRESS_ID}"
- extendedWaitUntil:
visible:
id: "tab-home"
timeout: 90000
- extendedWaitUntil:
visible:
id: "home-search"
timeout: 60000
- waitForAnimationToEnd:
timeout: 3000
# ---------------------------------------------------------------------------
# Phase 2: dashboard tag is visible and contains both products
# ---------------------------------------------------------------------------
# New dashboard tags are appended to the end of the horizontal strip.
- swipe:
from:
id: "home-tag-strip"
direction: LEFT
- swipe:
from:
id: "home-tag-strip"
direction: LEFT
- swipe:
from:
id: "home-tag-strip"
direction: LEFT
- extendedWaitUntil:
visible:
id: "tag-tab-${TAG_ID}"
timeout: 10000
- tapOn:
id: "tag-tab-${TAG_ID}"
- extendedWaitUntil:
visible:
id: "tag-grid-${TAG_ID}"
timeout: 15000
- assertVisible:
id: "tag-product-${SKU_500G}"
- assertVisible:
id: "tag-product-${SKU_1KG}"
- assertVisible:
id: "tag-product-${SKU_COMBO}"
# ---------------------------------------------------------------------------
# Phase 3: search, regular order
# ---------------------------------------------------------------------------
- tapOn:
id: "home-search"
- extendedWaitUntil:
visible:
id: "search-input"
timeout: 20000
- tapOn:
id: "search-input"
- inputText: "${PRODUCT_NAME}"
- hideKeyboard
- extendedWaitUntil:
visible:
id: "product-card-${SKU_500G}"
timeout: 20000
- tapOn:
id: "product-card-${SKU_500G}"
- extendedWaitUntil:
visible:
id: "product-add-to-cart"
timeout: 20000
- assertVisible:
id: "product-flash-badge"
- tapOn:
id: "product-add-to-cart"
- extendedWaitUntil:
visible:
id: "add-to-cart-confirm"
timeout: 20000
- scrollUntilVisible:
element:
id: "slot-option-${SLOT_ID}"
direction: DOWN
timeout: 15000
- tapOn:
id: "slot-option-${SLOT_ID}"
- tapOn:
id: "add-to-cart-confirm"
- extendedWaitUntil:
visible:
id: "go-to-cart"
timeout: 20000
- tapOn:
id: "go-to-cart"
- extendedWaitUntil:
visible:
id: "cart-sku-${SKU_500G}"
timeout: 20000
- scrollUntilVisible:
element:
id: "checkout-button"
direction: DOWN
timeout: 20000
# The checkout button sits at the bottom edge behind the floating cart bar.
- scroll
- waitForAnimationToEnd:
timeout: 1000
- tapOn:
id: "checkout-button"
- scrollUntilVisible:
element:
id: "place-order-button"
direction: DOWN
timeout: 30000
- tapOn:
id: "place-order-button"
- extendedWaitUntil:
visible:
id: "order-success-details"
timeout: 40000
- assertVisible:
id: "order-success-order-id"
- assertVisible:
id: "order-success-total"
# `order-success-view-orders` calls dismissAll() then push(), which can race
# when the success screen was pushed from checkout. Continue + Me is stable.
- tapOn:
id: "order-success-continue"
- extendedWaitUntil:
visible:
id: "home-search"
timeout: 30000
- tapOn:
id: "tab-me"
- extendedWaitUntil:
visible:
id: "me-menu-my-orders"
timeout: 20000
- tapOn:
id: "me-menu-my-orders"
- extendedWaitUntil:
visible:
id: "orders-list"
timeout: 30000
- assertVisible:
text: ".*${PRODUCT_NAME}.*"
# ---------------------------------------------------------------------------
# Phase 4: flash order
# ---------------------------------------------------------------------------
- tapOn:
id: "tab-flash"
# The fixture is appended near the end of the flash catalogue, and the last
# rows sit behind the floating cart bar unless centred.
- scrollUntilVisible:
element:
id: "flash-product-${SKU_500G}"
direction: DOWN
timeout: 120000
speed: 90
visibilityPercentage: 50
centerElement: true
- tapOn:
id: "flash-product-${SKU_500G}"
- extendedWaitUntil:
visible:
id: "product-add-to-cart"
timeout: 20000
- tapOn:
id: "product-add-to-cart"
- extendedWaitUntil:
visible:
id: "go-to-cart"
timeout: 20000
- tapOn:
id: "go-to-cart"
- extendedWaitUntil:
visible:
id: "cart-sku-${SKU_500G}"
timeout: 20000
- scrollUntilVisible:
element:
id: "checkout-button"
direction: DOWN
timeout: 20000
# The checkout button sits at the bottom edge behind the floating cart bar.
- scroll
- waitForAnimationToEnd:
timeout: 1000
- tapOn:
id: "checkout-button"
- scrollUntilVisible:
element:
id: "place-order-button"
direction: DOWN
timeout: 30000
- tapOn:
id: "place-order-button"
- extendedWaitUntil:
visible:
id: "order-success-details"
timeout: 40000
- assertVisible:
id: "order-success-order-id"
- assertVisible:
id: "order-success-total"
- tapOn:
id: "order-success-continue"
# The flash stack has no bottom tab bar; it returns to the flash catalogue.
- extendedWaitUntil:
visible:
id: "flash-product-search-input"
timeout: 30000
# ---------------------------------------------------------------------------
# Phase 5: both orders are in My Orders
# ---------------------------------------------------------------------------
# The flash stack has no bottom tab bar. Relaunch to return to the main tabs,
# then open My Orders from Me.
- stopApp
- openLink: exp://127.0.0.1:8081
- extendedWaitUntil:
visible:
id: "location-address-name-${ADDRESS_ID}"
timeout: 60000
optional: true
- runFlow:
when:
visible:
id: "location-address-name-${ADDRESS_ID}"
commands:
- tapOn:
id: "location-address-name-${ADDRESS_ID}"
- extendedWaitUntil:
visible:
id: "tab-home"
timeout: 90000
- extendedWaitUntil:
visible:
id: "home-search"
timeout: 60000
- tapOn:
id: "tab-me"
- extendedWaitUntil:
visible:
id: "me-menu-my-orders"
timeout: 20000
- tapOn:
id: "me-menu-my-orders"
- extendedWaitUntil:
visible:
id: "orders-list"
timeout: 30000
- assertVisible:
text: ".*${PRODUCT_NAME}.*"

View file

@ -1,10 +0,0 @@
flows:
- '*.yaml'
- '!config.yaml'
executionOrder:
continueOnFailure: false
flowsOrder:
- add-product
- add-slot-with-product
- user-order

View file

@ -1,47 +0,0 @@
appId: ${APP_ID || "in.freshyo.adminui"}
env:
APP_ID: ${APP_ID || "in.freshyo.adminui"}
STAFF_NAME: ${STAFF_NAME || ""}
STAFF_PASSWORD: ${STAFF_PASSWORD || ""}
SLOT_DATE: ${SLOT_DATE || ""}
SLOT_HOUR: ${SLOT_HOUR || ""}
SLOT_MIN: ${SLOT_MIN || ""}
tags:
- dev
---
- launchApp
- extendedWaitUntil:
visible:
id: 'login-name-input|add-product-menu-item'
timeout: 180000
- runFlow:
when:
visible:
id: login-name-input
commands:
- runFlow: ../subflows/login.yaml
- scrollUntilVisible:
element:
id: delivery-slots-menu-item
direction: DOWN
- tapOn:
id: delivery-slots-menu-item
- assertVisible:
id: add-slot-fab
- tapOn:
id: add-slot-fab
- assertVisible:
id: delivery-date-picker
- runFlow: ../subflows/set-slot-times.yaml
- scrollUntilVisible:
element:
id: create-slot-button
direction: DOWN
- tapOn:
id: create-slot-button
- assertVisible: 'Slot created successfully!'
- tapOn: 'OK'

72
tests/e2e/run-basic-sanity.sh Executable file
View file

@ -0,0 +1,72 @@
#!/usr/bin/env bash
# End-to-end driver for the basic-sanity scenario.
#
# 1. create fixtures + enable flash + rebuild caches
# 2. run the user-side Maestro flow (regular order + flash order)
# 3. package orders, disable flash, suspend combo, mark 1kg OOS, rebuild
# 4. run the post-admin Maestro assertions
#
# Usage:
# ./tests/e2e/run-basic-sanity.sh
#
# Optional:
# DEVICE=... Maestro device id (defaults to the only connected device)
# RUN_ID=... fixture name suffix
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$ROOT"
ENV_FILE="$ROOT/tests/e2e/.basic-sanity.env"
MAESTRO="${MAESTRO:-$HOME/.maestro/bin/maestro}"
if [[ ! -x "$MAESTRO" ]]; then
echo "Maestro not found at $MAESTRO (set MAESTRO=/path/to/maestro)" >&2
exit 1
fi
"$ROOT/tests/e2e/basic-sanity-setup.sh"
# shellcheck disable=SC1090
source "$ENV_FILE"
DEVICE_ARGS=()
if [[ -n "${DEVICE:-}" ]]; then
DEVICE_ARGS=(--device "$DEVICE")
fi
ADDRESS_ID="${ADDRESS_ID:-899}"
echo
echo "Running user flow (regular + flash orders)..."
"$MAESTRO" test "${DEVICE_ARGS[@]}" \
-e PRODUCT_NAME="$PRODUCT_NAME" \
-e COMBO_NAME="$COMBO_NAME" \
-e SKU_500G="$SKU_500G" \
-e SKU_1KG="$SKU_1KG" \
-e SKU_COMBO="$SKU_COMBO" \
-e TAG_ID="$TAG_ID" \
-e SLOT_ID="$SLOT_ID" \
-e ADDRESS_ID="$ADDRESS_ID" \
"$ROOT/tests/e2e/basic-sanity.yaml"
echo
echo "Applying admin-side changes..."
"$ROOT/tests/e2e/basic-sanity-admin-update.sh"
# The app refreshes essentialConsts on relaunch. The post-admin flow stops and
# relaunches Expo Go, so a short settle is enough.
sleep 5
echo
echo "Running post-admin assertions..."
"$MAESTRO" test "${DEVICE_ARGS[@]}" \
-e PRODUCT_NAME="$PRODUCT_NAME" \
-e COMBO_NAME="$COMBO_NAME" \
-e SKU_1KG="$SKU_1KG" \
-e SKU_COMBO="$SKU_COMBO" \
-e ADDRESS_ID="$ADDRESS_ID" \
"$ROOT/tests/e2e/basic-sanity-after-admin.yaml"
echo
echo "basic-sanity passed."

View file

@ -1,17 +0,0 @@
appId: ${USER_APP_ID}
env:
USER_MOBILE: ${USER_MOBILE || ""}
USER_PASSWORD: ${USER_PASSWORD || ""}
---
- tapOn:
id: user-login-mobile
- inputText: ${USER_MOBILE}
- pressKey: enter
- tapOn:
id: user-login-other-ways
- tapOn:
id: user-login-password
- inputText: ${USER_PASSWORD}
- pressKey: enter
- tapOn:
id: user-login-submit

View file

@ -1,16 +0,0 @@
appId: ${APP_ID || "in.freshyo.adminui"}
env:
STAFF_NAME: ${STAFF_NAME || ""}
STAFF_PASSWORD: ${STAFF_PASSWORD || ""}
---
- tapOn:
id: login-name-input
- inputText: ${STAFF_NAME}
- tapOn:
id: login-password-input
- inputText: ${STAFF_PASSWORD}
- hideKeyboard
- tapOn:
id: login-button
- assertVisible:
id: add-product-menu-item

View file

@ -1,26 +0,0 @@
appId: ${APP_ID || "in.freshyo.adminui"}
---
- runFlow:
when:
platform: Android
commands:
- extendedWaitUntil:
visible:
id: 'com\.(google\.)?android\.providers\.media\.module:id/icon_thumbnail'
timeout: 15000
- tapOn:
id: 'com\.(google\.)?android\.providers\.media\.module:id/icon_thumbnail'
index: 0
- extendedWaitUntil:
visible:
id: 'com\.(google\.)?android\.providers\.media\.module:id/button_add'
timeout: 10000
- tapOn:
id: 'com\.(google\.)?android\.providers\.media\.module:id/button_add'
- extendedWaitUntil:
visible:
id: app-root
timeout: 15000

View file

@ -1,43 +0,0 @@
appId: ${APP_ID || "in.freshyo.adminui"}
---
- tapOn:
id: delivery-date-picker
- tapOn:
id: 'android:id/button1'
- tapOn:
id: delivery-time-picker
- tapOn:
id: 'android:id/toggle_mode'
optional: true
- tapOn:
id: 'android:id/input_hour'
- eraseText
- inputText: ${SLOT_HOUR}
- tapOn:
id: 'android:id/input_minute'
- eraseText
- inputText: ${SLOT_MIN}
- tapOn:
id: 'android:id/button1'
- tapOn:
id: freeze-date-picker
- tapOn:
id: 'android:id/button1'
- tapOn:
id: freeze-time-picker
- tapOn:
id: 'android:id/toggle_mode'
optional: true
- tapOn:
id: 'android:id/input_hour'
- eraseText
- inputText: ${SLOT_FREEZE_HOUR}
- tapOn:
id: 'android:id/input_minute'
- eraseText
- inputText: ${SLOT_FREEZE_MIN}
- tapOn:
id: 'android:id/button1'

View file

@ -1,119 +0,0 @@
appId: ${USER_APP_ID}
env:
USER_APP_ID: ${USER_APP_ID || "in.freshyo.app"}
USER_MOBILE: ${USER_MOBILE || ""}
USER_PASSWORD: ${USER_PASSWORD || ""}
PRODUCT_NAME: ${PRODUCT_NAME || "E2E Test Product"}
SLOT_DATE: ${SLOT_DATE || ""}
SLOT_HOUR: ${SLOT_HOUR || ""}
SLOT_MIN: ${SLOT_MIN || ""}
tags:
- user
- smoke
---
- launchApp:
clearState: true
- extendedWaitUntil:
visible:
text: 'Next|Home'
timeout: 60000
- tapOn:
text: 'Next'
optional: true
- waitForAnimationToEnd
- extendedWaitUntil:
visible:
id: home-search
timeout: 30000
- tapOn:
id: home-search
- tapOn:
id: search-input-input
- inputText: ${PRODUCT_NAME}
- pressKey: enter
- tapOn: 'Add to Cart'
- extendedWaitUntil:
visible:
id: 'slot-${SLOT_DATE}-${SLOT_HOUR}-${SLOT_MIN}'
timeout: 20000
- tapOn:
id: 'slot-${SLOT_DATE}-${SLOT_HOUR}-${SLOT_MIN}'
- tapOn:
id: add-to-cart-confirm
- extendedWaitUntil:
visible:
id: go-to-cart
timeout: 20000
- tapOn:
id: go-to-cart
- scrollUntilVisible:
element:
id: checkout-button
direction: DOWN
- tapOn:
id: checkout-button
- extendedWaitUntil:
visible:
id: 'user-login-mobile|place-order-button'
timeout: 30000
- runFlow:
when:
visible:
id: user-login-mobile
commands:
- runFlow: subflows/login-user.yaml
- extendedWaitUntil:
visible:
id: home-search
timeout: 60000
- extendedWaitUntil:
visible:
id: go-to-cart
timeout: 20000
- tapOn:
id: go-to-cart
- scrollUntilVisible:
element:
id: checkout-button
direction: DOWN
- tapOn:
id: checkout-button
- extendedWaitUntil:
visible:
id: address-option-0
timeout: 30000
- scrollUntilVisible:
element:
id: place-order-button
direction: DOWN
- runFlow:
when:
visible:
id: select-address-error
commands:
- scrollUntilVisible:
element:
id: address-option-0
direction: UP
- tapOn:
id: address-option-0
- scrollUntilVisible:
element:
id: place-order-button
direction: DOWN
- extendedWaitUntil:
notVisible:
id: select-address-error
timeout: 15000
- tapOn:
id: place-order-button
- assertVisible: 'Order Placed Successfully!'