diff --git a/apps/user-ui/app/(drawer)/(tabs)/me/index.tsx b/apps/user-ui/app/(drawer)/(tabs)/me/index.tsx index ef3713f..7465ad6 100644 --- a/apps/user-ui/app/(drawer)/(tabs)/me/index.tsx +++ b/apps/user-ui/app/(drawer)/(tabs)/me/index.tsx @@ -8,7 +8,7 @@ import { LinearGradient } from 'expo-linear-gradient'; import { Ionicons } from '@expo/vector-icons'; import NextOrderGlimpse from '@/components/NextOrderGlimpse'; import AddressSwitcherSheet from '@/src/components/location/AddressSwitcherSheet'; -import { useRegion } from '@/src/hooks/useRegion'; +import { useRegionNeo } from '@/src/hooks/useRegionNeo'; import { useAuth } from '@/src/contexts/AuthContext'; import { useNavigationTarget } from 'common-ui/hooks/useNavigationTarget'; import { useGetEssentialConsts } from '@/src/hooks/prominent-api-hooks'; @@ -22,7 +22,7 @@ export default function Me() { const { logout } = useAuth(); const { getNavigationTarget } = useNavigationTarget(); const [regionDialogOpen, setRegionDialogOpen] = useState(false); - const { region: selectedRegion } = useRegion(); + const regionName = useRegionNeo().regionName; // Same number the NextOrderGlimpse dials via tel: — Live Support opens it in WhatsApp. const { data: essentialConsts } = useGetEssentialConsts(); const supportMobile = essentialConsts?.supportMobile ?? null; @@ -108,7 +108,7 @@ export default function Me() { icon: 'globe-outline', color: '#0EA5E9', onPress: () => setRegionDialogOpen(true), - subtitle: selectedRegion?.name ? `Delivering in ${selectedRegion.name}` : 'Choose or add an address' + subtitle: regionName ? `Delivering in ${regionName}` : 'Choose or add an address' }, { title: 'Profile Settings', diff --git a/apps/user-ui/app/_layout.tsx b/apps/user-ui/app/_layout.tsx index edaffb9..d6c5c4c 100755 --- a/apps/user-ui/app/_layout.tsx +++ b/apps/user-ui/app/_layout.tsx @@ -29,7 +29,9 @@ import BackHandlerWrapper from "@/components/BackHandler"; import AddToCartDialog from "@/src/components/AddToCartDialog"; import PendingAddressSync from "@/src/components/PendingAddressSync"; import NotifRegionSync from "@/src/components/NotifRegionSync"; -import LocationTestWrapper from "@/components/LocationTestWrapper"; +// Old region gate — superseded by LocationWrapperNeo. Kept for reference. +// import LocationTestWrapper from "@/components/LocationTestWrapper"; +import LocationWrapperNeo from "@/components/LocationWrapperNeo"; import React from "react"; import { GestureHandlerRootView } from "react-native-gesture-handler"; import NotifChecker from "@/services/notif-service/notif-checker"; @@ -76,7 +78,7 @@ export default function RootLayout() { - + @@ -93,7 +95,7 @@ export default function RootLayout() { - + diff --git a/apps/user-ui/components/CartAddressGate.tsx b/apps/user-ui/components/CartAddressGate.tsx index 744b530..8d22e83 100644 --- a/apps/user-ui/components/CartAddressGate.tsx +++ b/apps/user-ui/components/CartAddressGate.tsx @@ -4,6 +4,10 @@ import MaterialIcons from '@expo/vector-icons/MaterialIcons' import { tw, theme, MyText, MyTouchableOpacity } from 'common-ui' import AddressForm from '@/src/components/AddressForm' import { useLocationStore } from '@/src/store/locationStore' +import { useRegionNeo } from '@/src/hooks/useRegionNeo' +import { trpc } from '@/src/trpc-client' +import { toNeoAddress } from '@/src/lib/neo-address' +import { useNeoRegionStore } from '@/src/store/neoRegionStore' // How often to re-check the device location while we still have no fix. const LOCATION_POLL_MS = 3000 @@ -21,7 +25,11 @@ interface CartAddressGateProps { * first address they save becomes their default, and we then show the cart. */ const CartAddressGate: React.FC = ({ onDone, onBack }) => { - const coords = useLocationStore((state) => state.coords) + const neo = useRegionNeo() + const coords = neo.coords + const selectAddress = neo.selectAddress + const utils = trpc.useUtils() + const setAddresses = useNeoRegionStore((state) => state.setAddresses) const probeLocation = useLocationStore((state) => state.probe) const refreshPosition = useLocationStore((state) => state.refresh) const [mode, setMode] = useState<'none' | 'current' | 'other'>('none') @@ -118,7 +126,7 @@ const CartAddressGate: React.FC = ({ onDone, onBack }) => phone: '', addressLine1: '', addressLine2: '', - city: 'Mahabubnagar', + city: neo.regionName, state: 'Telangana', isDefault: true, latitude: coords.latitude, @@ -126,9 +134,20 @@ const CartAddressGate: React.FC = ({ onDone, onBack }) => } : undefined } - onSuccess={() => { - setMode('none') - onDone() + onSuccess={(addressId) => { + void (async () => { + if (addressId != null) { + try { + const response = await utils.user.address.getUserAddresses.fetch(undefined) + if (response.data) setAddresses(response.data.map(toNeoAddress)) + } catch { + // The form's invalidation will refresh it. + } + await selectAddress(addressId) + } + setMode('none') + onDone() + })() }} /> diff --git a/apps/user-ui/components/CheckoutAddressDisplay.tsx b/apps/user-ui/components/CheckoutAddressDisplay.tsx index 9d9204d..8b46668 100644 --- a/apps/user-ui/components/CheckoutAddressDisplay.tsx +++ b/apps/user-ui/components/CheckoutAddressDisplay.tsx @@ -2,28 +2,17 @@ import React from 'react' import { View } from 'react-native' import MaterialIcons from '@expo/vector-icons/MaterialIcons' import { tw, MyText } from 'common-ui' -import { trpc } from '@/src/trpc-client' -import { useAuth } from '@/src/contexts/AuthContext' -import { useAddressStore } from '@/src/store/addressStore' +import { useRegionNeo } from '@/src/hooks/useRegionNeo' +import { addressIconName } from '@/src/lib/neo-address' /** * Read-only delivery address card for the checkout page. The address is chosen * on the cart page (CheckoutAddressSelector); checkout only shows it. */ const CheckoutAddressDisplay: React.FC = () => { - const { isAuthenticated } = useAuth() - const selectedAddressId = useAddressStore((state) => state.selectedAddressId) - - const { data: addressesData, isLoading } = trpc.user.address.getUserAddresses.useQuery( - undefined, - { enabled: isAuthenticated } - ) - - const addresses = addressesData?.data ?? [] - const address = - addresses.find((candidate) => candidate.id === selectedAddressId) ?? - addresses.find((candidate) => candidate.isDefault) ?? - null + // The hook guarantees the selection belongs to the current region, so this + // is the one address the order will use. + const address = useRegionNeo().selectedAddress return ( @@ -34,22 +23,10 @@ const CheckoutAddressDisplay: React.FC = () => { Delivery Address - {isLoading ? ( - Loading address... - ) : address ? ( + {address ? ( - + {address.name} diff --git a/apps/user-ui/components/CheckoutAddressSelector.tsx b/apps/user-ui/components/CheckoutAddressSelector.tsx index 6d17557..d94ec6e 100644 --- a/apps/user-ui/components/CheckoutAddressSelector.tsx +++ b/apps/user-ui/components/CheckoutAddressSelector.tsx @@ -1,4 +1,4 @@ -import React, { useState, useEffect, useRef } from 'react'; +import React, { useState, useRef } from 'react'; import { View, Text, TouchableOpacity, ScrollView, Alert, NativeSyntheticEvent, NativeScrollEvent } from 'react-native'; import { useRouter } from 'expo-router'; import { tw, BottomDialog, RawBottomDialog, MyText } from 'common-ui'; @@ -8,21 +8,18 @@ import LocationAttacher from '@/src/components/LocationAttacher'; import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import { trpc } from '@/src/trpc-client'; import { useAuth } from '@/src/contexts/AuthContext'; -import { useRegion } from '@/src/hooks/useRegion'; -import { confirmRegionSwitch } from '@/src/lib/region-switch'; +import { useRegionNeo } from '@/src/hooks/useRegionNeo'; +import { addressIconName, toNeoAddress } from '@/src/lib/neo-address'; +import { useNeoRegionStore } from '@/src/store/neoRegionStore'; import * as Location from 'expo-location'; -interface AddressSelectorProps { - selectedAddress: number | null; - onAddressSelect: (addressId: number) => void; -} - const CARD_WIDTH = 300; // 288 (w-72) + 12 (mr-3) -const CheckoutAddressSelector: React.FC = ({ - selectedAddress, - onAddressSelect, -}) => { +const CheckoutAddressSelector: React.FC = () => { + const neo = useRegionNeo(); + const selectedAddress = neo.selectedAddressId; + const selectAddress = neo.selectAddress; + const setAddresses = useNeoRegionStore((state) => state.setAddresses); const [showAddAddress, setShowAddAddress] = useState(false); const [editingLocationAddressId, setEditingLocationAddressId] = useState(null); const [locationLoading, setLocationLoading] = useState(false); @@ -31,13 +28,16 @@ const CheckoutAddressSelector: React.FC = ({ const utils = trpc.useUtils(); const router = useRouter(); const scrollViewRef = useRef(null); + // The region the add-address form resolved to, so a cross-region save can be + // confirmed before it switches (and clears the cart). + const resolvedRegionRef = useRef<{ regionId: number; boundId: number | null } | null>(null); const { isAuthenticated } = useAuth(); - const { regionId: selectedRegionId } = useRegion(); + const selectedRegionId = neo.regionId; const { data: addresses } = trpc.user.address.getUserAddresses.useQuery( undefined, { enabled: isAuthenticated } ); - const { data: regions } = trpc.common.listRegions.useQuery(); + const regions = useNeoRegionStore((state) => state.regions); const updateAddressMutation = trpc.user.address.updateAddress.useMutation({ onSuccess: () => { @@ -68,21 +68,6 @@ const CheckoutAddressSelector: React.FC = ({ }); }, [addresses?.data, selectedAddress]); - // Auto-select default address when addresses are loaded and none is selected - useEffect(() => { - if (sortedAddresses.length > 0 && selectedAddress === null) { - const defaultAddress = sortedAddresses.find(addr => addr.isDefault); - // Never silently auto-select a region we are not browsing. - const isCurrentRegion = - !selectedRegionId || - defaultAddress?.regionId == null || - defaultAddress.regionId === selectedRegionId; - if (defaultAddress && isCurrentRegion) { - onAddressSelect(defaultAddress.id); - } - } - }, [sortedAddresses, selectedAddress, onAddressSelect, selectedRegionId]); - // Reset scroll to left when address is selected const resetScrollToLeft = () => { setCurrentIndex(0); @@ -94,8 +79,29 @@ const CheckoutAddressSelector: React.FC = ({ setCurrentIndex(index); }; - // Selecting an address from another region requires an explicit confirmation - // because it clears the cart and changes the browsing region. + // Every cross-region selection goes through this confirmation, because the + // switch clears the cart for the current region. + // Adding or editing an address is the caller's job to refresh the list. + const refreshAddresses = async () => { + try { + const response = await utils.user.address.getUserAddresses.fetch(undefined); + if (response.data) setAddresses(response.data.map(toNeoAddress)); + } catch { + // The form's mutation invalidation will refresh it. + } + }; + + const confirmSwitch = (regionName: string, onConfirm: () => void) => { + Alert.alert( + 'Switch region?', + `This address is in ${regionName}. Switching will clear your entire cart and take you home.`, + [ + { text: 'Cancel', style: 'cancel' }, + { text: 'Switch & clear cart', style: 'destructive', onPress: onConfirm }, + ] + ); + }; + const handleAddressPress = (address: any) => { if (selectedRegionId && address.regionId && address.regionId !== selectedRegionId) { const targetRegion = (regions ?? []).find((region) => region.id === address.regionId); @@ -103,27 +109,16 @@ const CheckoutAddressSelector: React.FC = ({ Alert.alert('Unavailable region', 'This address belongs to a region that is not currently available.'); return; } - Alert.alert( - 'Switch region?', - `This address is in ${targetRegion.name}. Switching will clear your entire cart and take you home.`, - [ - { text: 'Cancel', style: 'cancel' }, - { - text: 'Switch & clear cart', - style: 'destructive', - onPress: () => { - void (async () => { - await confirmRegionSwitch(targetRegion, queryClient, address.boundId ?? targetRegion.effectiveBoundId ?? null); - router.replace('/(drawer)/(tabs)/home'); - })(); - }, - }, - ] - ); + confirmSwitch(targetRegion.name, () => { + void (async () => { + await selectAddress(address.id); + router.replace('/(drawer)/(tabs)/home'); + })(); + }); return; } - onAddressSelect(address.id); + void selectAddress(address.id); resetScrollToLeft(); }; @@ -217,7 +212,7 @@ const CheckoutAddressSelector: React.FC = ({ @@ -288,13 +283,44 @@ const CheckoutAddressSelector: React.FC = ({ setShowAddAddress(false)}> { + resolvedRegionRef.current = info; + }} onSuccess={(addressId) => { setShowAddAddress(false); - // Auto-select the newly added address - if (addressId) { - onAddressSelect(addressId); - } queryClient.invalidateQueries(); + if (addressId == null) return; + + const resolved = resolvedRegionRef.current; + if ( + resolved != null && + selectedRegionId != null && + resolved.regionId !== selectedRegionId + ) { + const targetRegion = (regions ?? []).find((region) => region.id === resolved.regionId); + if (!targetRegion) { + Alert.alert( + 'Unavailable region', + 'This address belongs to a region that is not currently available.' + ); + return; + } + // The address has been saved; only selecting it is destructive. + confirmSwitch(targetRegion.name, () => { + void (async () => { + await refreshAddresses(); + await selectAddress(addressId); + router.replace('/(drawer)/(tabs)/home'); + })(); + }); + return; + } + + // Auto-select the newly added address. + void (async () => { + await refreshAddresses(); + await selectAddress(addressId); + })(); }} /> diff --git a/apps/user-ui/components/LocationWrapperNeo.tsx b/apps/user-ui/components/LocationWrapperNeo.tsx new file mode 100644 index 0000000..50bd5f9 --- /dev/null +++ b/apps/user-ui/components/LocationWrapperNeo.tsx @@ -0,0 +1,34 @@ +import React from 'react' +import type { ReactParentComponent } from '@packages/shared' +import { useNeoRegionBootstrap } from '@/src/hooks/useRegionNeo' +import { useNeoRegionStore } from '@/src/store/neoRegionStore' +import NeoAddressFlow from '@/src/components/location/neo/NeoAddressFlow' +import NeoConfirmLocation from '@/src/components/location/neo/NeoConfirmLocation' +import NeoLoadingScreen from '@/src/components/location/neo/NeoLoadingScreen' + +/** + * The neo region gate. It runs the launch decision and watches the store + * directly — it never calls `useRegionNeo`, because that hook is only valid for + * components behind this gate. Children appear once the store holds a complete + * region; the two flow flags take over when the decision needs input. + */ +const LocationWrapperNeo: React.FC = ({ children }) => { + useNeoRegionBootstrap() + + const regionId = useNeoRegionStore((state) => state.regionId) + const boundId = useNeoRegionStore((state) => state.boundId) + const regionName = useNeoRegionStore((state) => state.regionName) + const coords = useNeoRegionStore((state) => state.coords) + const needsAddressFormFlow = useNeoRegionStore((state) => state.needsAddressFormFlow) + const needsAddressConfirmation = useNeoRegionStore((state) => state.needsAddressConfirmation) + + if (needsAddressFormFlow) return + if (regionId == null || boundId == null || regionName == null || coords == null) { + return + } + if (needsAddressConfirmation) return + + return <>{children} +} + +export default LocationWrapperNeo diff --git a/apps/user-ui/components/PaymentAndOrderComponent.tsx b/apps/user-ui/components/PaymentAndOrderComponent.tsx index efe1375..36706fc 100644 --- a/apps/user-ui/components/PaymentAndOrderComponent.tsx +++ b/apps/user-ui/components/PaymentAndOrderComponent.tsx @@ -6,7 +6,7 @@ import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import { trpc } from '@/src/trpc-client'; import { useCentralProductStore } from '@/src/store/centralProductStore'; import { useCentralSlotStore } from '@/src/store/centralSlotStore'; -import { useRegion } from '@/src/hooks/useRegion'; +import { useRegionNeo } from '@/src/hooks/useRegionNeo'; import { useCheckoutStore } from '@/src/store/checkoutStore'; import { clearLocalCart } from '@/hooks/cart-query-hooks'; import { useQueryClient } from '@tanstack/react-query'; @@ -64,7 +64,9 @@ const PaymentAndOrderComponent: React.FC = ({ const products = useCentralProductStore((state) => state.products); const productsById = useCentralProductStore((state) => state.productsById); const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); - const { regionId: selectedRegionId, boundId: activeBoundId } = useRegion(); + const neo = useRegionNeo(); + const selectedRegionId = neo.regionId; + const activeBoundId = neo.boundId; // Memoized flash-eligible product IDs const flashEligibleProductIds = useMemo(() => { diff --git a/apps/user-ui/components/ProductDetail.tsx b/apps/user-ui/components/ProductDetail.tsx index c9e64ac..0056f0e 100644 --- a/apps/user-ui/components/ProductDetail.tsx +++ b/apps/user-ui/components/ProductDetail.tsx @@ -14,7 +14,7 @@ import { useAddToCart, useGetCart, useUpdateCartItem, useRemoveFromCart } from ' import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier'; import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'; import { useSlots } from '@/src/hooks/prominent-api-hooks'; -import { useRegion } from '@/src/hooks/useRegion'; +import { useRegionNeo } from '@/src/hooks/useRegionNeo'; import FloatingCartBar from './floating-cart-bar'; import { useStoreHeaderStore } from '@/src/store/storeHeaderStore'; import { useCartStore } from '@/src/store/cartStore'; @@ -51,7 +51,7 @@ const ProductDetail: React.FC = ({ productId, isFlashDeliver const [hasMore, setHasMore] = useState(true); const [reviewsOffset, setReviewsOffset] = useState(0); const [refreshing, setRefreshing] = useState(false); - const { regionId: activeRegionId } = useRegion(); + const activeRegionId = useRegionNeo().regionId; // The region is required (a global SKU has none of its own), so the query // waits for it and the screen stays in its loading state until then. const { data: productDetail, isLoading, error, refetch } = trpc.user.product.getProductDetails.useQuery( diff --git a/apps/user-ui/components/QuickDeliveryAddressSelector.tsx b/apps/user-ui/components/QuickDeliveryAddressSelector.tsx index a527302..bb74407 100644 --- a/apps/user-ui/components/QuickDeliveryAddressSelector.tsx +++ b/apps/user-ui/components/QuickDeliveryAddressSelector.tsx @@ -1,14 +1,11 @@ import React, { useState, useMemo } from 'react'; import { View, ScrollView, Dimensions, Alert } from 'react-native'; import { useRouter } from 'expo-router'; -import { useQueryClient } from '@tanstack/react-query'; import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import { BottomDialog, MyTouchableOpacity, MyText, tw, theme } from 'common-ui'; import { useAuth } from '@/src/contexts/AuthContext'; import { trpc } from '@/src/trpc-client'; -import { useAddressStore } from '@/src/store/addressStore'; -import { useRegion } from '@/src/hooks/useRegion'; -import { confirmRegionSwitch } from '@/src/lib/region-switch'; +import { useRegionNeo } from '@/src/hooks/useRegionNeo'; import { useSlots } from '@/src/hooks/prominent-api-hooks'; import LocationBar from '@/src/components/LocationBar'; import dayjs from 'dayjs'; @@ -30,7 +27,10 @@ const QuickDeliveryAddressSelector: React.FC const [dialogOpen, setDialogOpen] = useState(false); const { isAuthenticated } = useAuth(); - const { selectedAddressId, setSelectedAddressId } = useAddressStore(); + const neo = useRegionNeo(); + const selectedAddressId = neo.selectedAddressId; + const selectedRegionId = neo.regionId; + const selectAddress = neo.selectAddress; const { data: defaultAddressData } = trpc.user.address.getDefaultAddress.useQuery(); const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, { @@ -41,8 +41,6 @@ const QuickDeliveryAddressSelector: React.FC const defaultAddress = defaultAddressData?.data; const addresses = addressesData?.data || []; - const queryClient = useQueryClient(); - const { regionId: selectedRegionId } = useRegion(); const { data: regions } = trpc.common.listRegions.useQuery(); // An address (selected or default) that belongs to another region than the @@ -73,7 +71,7 @@ const QuickDeliveryAddressSelector: React.FC style: 'destructive', onPress: () => { void (async () => { - await confirmRegionSwitch(targetRegion, queryClient, foreignAddress.boundId ?? targetRegion.effectiveBoundId ?? null); + await neo.selectAddress(foreignAddress.id); router.replace('/(drawer)/(tabs)/home'); })(); }, @@ -318,7 +316,7 @@ const QuickDeliveryAddressSelector: React.FC address.id === (selectedAddressId || defaultAddress?.id) ? 'bg-brand50 border-brand500' : 'bg-white' }`} onPress={() => { - setSelectedAddressId(address.id); + void selectAddress?.(address.id); setAddressDialogOpen(false); }} activeOpacity={0.7} diff --git a/apps/user-ui/components/cart-page.tsx b/apps/user-ui/components/cart-page.tsx index cae0bed..70a45f1 100644 --- a/apps/user-ui/components/cart-page.tsx +++ b/apps/user-ui/components/cart-page.tsx @@ -29,12 +29,12 @@ import { useCentralProductStore, type Product } from '@/src/store/centralProduct import { useCentralSlotStore } from '@/src/store/centralSlotStore'; import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-query-hooks'; import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks'; -import { useRegion } from '@/src/hooks/useRegion'; +import { useRegionNeo } from '@/src/hooks/useRegionNeo'; import CheckoutAddressSelector from '@/components/CheckoutAddressSelector'; import CouponBreakdownDialog from '@/src/components/CouponBreakdownDialog'; import LoginWall from '@/components/LoginWall'; import CartAddressGate from '@/components/CartAddressGate'; -import { useAddressStore } from '@/src/store/addressStore'; + import { useCheckoutStore } from '@/src/store/checkoutStore'; import type { FlashDeliveryProps } from '@packages/shared'; import { computeCouponStack, computeCouponLineBreakdowns, evaluateCouponEligibility, type CartLine, type CouponLineBreakdown } from '@packages/shared'; @@ -278,8 +278,9 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps const { isAuthenticated, isLoading: isAuthLoading } = useAuth(); const cartType: "regular" | "flash" = isFlashDelivery ? "flash" : "regular"; - const { selectedAddressId, setSelectedAddressId } = useAddressStore(); - const { regionId } = useRegion(); + const neo = useRegionNeo(); + const selectedAddressId = neo.selectedAddressId; + const regionId = neo.regionId; // First-address gate: the region can exist (from the location) with no address yet. const addressesQuery = trpc.user.address.getUserAddresses.useQuery(undefined, { enabled: isAuthenticated, @@ -879,7 +880,9 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps ); } - if ((addressesQuery.data?.data?.length ?? 0) === 0) { + // No active address for the current region. Addresses that live in another + // region do not count: the neo store never selects them across regions. + if (selectedAddressId == null) { return ( { @@ -1447,10 +1450,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps {/* Delivery Address */} - + {/* Bottom Checkout Bar - Now Static */} {hasAvailableItems && ( diff --git a/apps/user-ui/components/checkout-page.tsx b/apps/user-ui/components/checkout-page.tsx index 33568de..b81faa5 100644 --- a/apps/user-ui/components/checkout-page.tsx +++ b/apps/user-ui/components/checkout-page.tsx @@ -12,11 +12,11 @@ import { useCentralProductStore } from '@/src/store/centralProductStore'; import { useCentralSlotStore } from '@/src/store/centralSlotStore'; import { useGetCart } from '@/hooks/cart-query-hooks'; import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks'; -import { useRegion } from '@/src/hooks/useRegion'; +import { useRegionNeo } from '@/src/hooks/useRegionNeo'; import PaymentAndOrderComponent from '@/components/PaymentAndOrderComponent'; import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay'; import CouponBreakdownDialog from '@/src/components/CouponBreakdownDialog'; -import { useAddressStore } from '@/src/store/addressStore'; + import type { FlashDeliveryProps } from '@packages/shared'; import { computeCouponStack, computeCouponLineBreakdowns, evaluateCouponEligibility, type CartLine, type CouponLineBreakdown } from '@packages/shared'; @@ -27,7 +27,8 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) // Slots are per-region and the order is placed with this same region // (see PaymentAndOrderComponent), so scope the query to it. - const { regionId } = useRegion(); + const neo = useRegionNeo(); + const regionId = neo.regionId; // Protect checkout route and preserve query params useAuthenticatedRoute({ @@ -57,7 +58,7 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) refetchSlots(); }); - const { selectedAddressId } = useAddressStore(); + const selectedAddressId = neo.selectedAddressId; const [selectedCouponIds, setSelectedCouponIds] = useState([]); // Coupon whose per-product discount split is open (product-specific coupons only). const [breakdownCouponId, setBreakdownCouponId] = useState(null); diff --git a/apps/user-ui/src/components/AddressForm.tsx b/apps/user-ui/src/components/AddressForm.tsx index 95ed547..8d8c9de 100644 --- a/apps/user-ui/src/components/AddressForm.tsx +++ b/apps/user-ui/src/components/AddressForm.tsx @@ -8,7 +8,7 @@ import { trpc } from '../trpc-client'; import LocationMapStep from './location/LocationMapStep'; import type { AddressFormProps, RegionSummary } from '@packages/shared'; import { savePendingAddress } from '@/src/lib/pending-address'; -import { useRegion } from '@/src/hooks/useRegion'; +import { useNeoRegionStore } from '@/src/store/neoRegionStore'; import { useLocationStore } from '@/src/store/locationStore'; type Coords = { latitude: number; longitude: number }; @@ -19,6 +19,12 @@ type LocationSource = 'device' | 'map'; const AddressForm: React.FC void; + /** + * Called immediately before a create/update is submitted. Returning false + * aborts the submission. The neo flow uses it to confirm a region switch; + * the other mounts leave it unset. + */ + onBeforeSubmit?: () => boolean | Promise; }> = ({ onSuccess, initialValues, @@ -26,8 +32,12 @@ const AddressForm: React.FC { - const { regionId: browsingRegionId, boundId: browsingBoundId } = useRegion(); + // The form is also shown before a region exists (the fallback), so it reads + // the store directly rather than using the ready-only hook. + const browsingRegionId = useNeoRegionStore((state) => state.regionId); + const browsingBoundId = useNeoRegionStore((state) => state.boundId); const deviceCoords = useLocationStore((state) => state.coords); const [isSubmitting, setIsSubmitting] = useState(false); const [submitError, setSubmitError] = useState(null); @@ -205,6 +215,10 @@ const AddressForm: React.FC { setIsSubmitting(false); + // Keep the neo store's address list (and the default) in sync; the + // location flow selects the new id after this resolves. + void utils.user.address.getUserAddresses.invalidate(); + void utils.user.address.getDefaultAddress.invalidate(); const addressId = data?.data?.id; // Delay to allow modal to close animation setTimeout(() => onSuccess(addressId), 350); @@ -218,6 +232,8 @@ const AddressForm: React.FC { setIsSubmitting(false); + void utils.user.address.getUserAddresses.invalidate(); + void utils.user.address.getDefaultAddress.invalidate(); // Delay to allow modal to close animation setTimeout(() => onSuccess(), 350); }, @@ -242,6 +258,9 @@ const AddressForm: React.FC - {isSubmitting ? (isEdit ? 'Updating...' : 'Adding...') : (isEdit ? 'Update Address' : 'Add Address')} + {submitLabel} diff --git a/apps/user-ui/src/components/LocationBar.tsx b/apps/user-ui/src/components/LocationBar.tsx index a2a8ee0..2885b17 100644 --- a/apps/user-ui/src/components/LocationBar.tsx +++ b/apps/user-ui/src/components/LocationBar.tsx @@ -2,20 +2,10 @@ import React, { useState } from 'react' import { View } from 'react-native' import MaterialIcons from '@expo/vector-icons/MaterialIcons' import { tw, theme, MyText, MyTouchableOpacity } from 'common-ui' -import { useRegion } from '@/src/hooks/useRegion' -import { useAddressStore } from '@/src/store/addressStore' -import { useAuthOptional } from '@/src/contexts/AuthContext' -import { trpc } from '@/src/trpc-client' +import { useRegionNeo } from '@/src/hooks/useRegionNeo' import AddressSwitcherSheet from '@/src/components/location/AddressSwitcherSheet' import { useRenderProbe } from '@/src/lib/render-probe' -const formatAddress = (address: { - addressLine1: string - addressLine2?: string | null - city: string -}) => - `${address.addressLine1}${address.addressLine2 ? `, ${address.addressLine2}` : ''}, ${address.city}` - /** * Location bar shown at the top of every top-level tab screen. * Rendered INSIDE the scroll content (first item / ListHeaderComponent) so it @@ -28,27 +18,20 @@ const formatAddress = (address: { const LocationBar: React.FC = () => { useRenderProbe('component:LocationBar') const [sheetOpen, setSheetOpen] = useState(false) - const { region } = useRegion() - - const isAuthenticated = useAuthOptional()?.isAuthenticated ?? false - const selectedAddressId = useAddressStore((state) => state.selectedAddressId) - const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, { - enabled: isAuthenticated, - }) - - const addresses = addressesData?.data ?? [] - // Prefer the address the user selected at checkout, else their default. - const activeAddress = - addresses.find((address) => address.id === selectedAddressId) ?? - addresses.find((address) => address.isDefault) ?? - null + const neo = useRegionNeo() + const regionName = neo.regionName + const fullAddress = neo.fullAddress return ( setSheetOpen(true)} + onPress={() => { + console.log('clicked bar') + setSheetOpen(true) + }} + style={tw`flex-row items-center bg-white border border-gray-100 rounded-2xl px-4 py-3 shadow-sm`} > @@ -57,7 +40,7 @@ const LocationBar: React.FC = () => { Deliver to - {region ? ( + {regionName ? ( // The active region gets a tinted pill so it reads at a glance; the // pill shrinks (flex-shrink) so a long name truncates instead of // pushing the chevron out of the row. @@ -68,7 +51,7 @@ const LocationBar: React.FC = () => { numberOfLines={1} ellipsizeMode="tail" > - {region.name} + {regionName} ) : ( @@ -77,7 +60,7 @@ const LocationBar: React.FC = () => { )} - {activeAddress ? ( + {fullAddress ? ( { numberOfLines={1} ellipsizeMode="tail" > - {formatAddress(activeAddress)} + {fullAddress} ) : null} diff --git a/apps/user-ui/src/components/NotifRegionSync.tsx b/apps/user-ui/src/components/NotifRegionSync.tsx index c8210cf..9f6ca7c 100644 --- a/apps/user-ui/src/components/NotifRegionSync.tsx +++ b/apps/user-ui/src/components/NotifRegionSync.tsx @@ -1,6 +1,7 @@ import React, { useEffect, useRef } from 'react' import { trpc } from '@/src/trpc-client' -import { useRegion } from '@/src/hooks/useRegion' +import { useRegionNeo } from '@/src/hooks/useRegionNeo' +import { useNeoRegionStore } from '@/src/store/neoRegionStore' import { useNotification } from '@/services/notif-service/notif-context' /** @@ -10,8 +11,7 @@ import { useNotification } from '@/services/notif-service/notif-context' * It renders inside NotificationProvider (see app/_layout.tsx), which is the * only place the push token is available. Both ways a region becomes known land * here: - * - a tracked device location — useRegion resolves it (and `bound` is set only - * for that path), or + * - a tracked device location — useRegionNeo resolves it (origin === 'device'), or * - an added address (incl. the signed-out local draft) — the location * fallback switches the region, which clears the gate and mounts this * component with the new region already in place. @@ -24,7 +24,8 @@ import { useNotification } from '@/services/notif-service/notif-context' */ const NotifRegionSync: React.FC = () => { const { expoPushToken, notifPermission } = useNotification() - const { regionId, bound } = useRegion() + const regionId = useRegionNeo().regionId + const origin = useNeoRegionStore((state) => state.origin) // Both calls are best-effort telemetry for notifications: a failure is logged // and ignored, never surfaced or retried. const savePushToken = trpc.user.user.savePushToken.useMutation({ @@ -45,19 +46,18 @@ const NotifRegionSync: React.FC = () => { useEffect(() => { if (!expoPushToken || notifPermission !== 'granted' || regionId == null) return - const fromLocation = bound != null + const fromLocation = origin === 'device' const key = `${expoPushToken}:${regionId}:${fromLocation ? 'loc' : 'addr'}` if (lastSynced.current === key) return lastSynced.current = key savePushTokenMutate({ token: expoPushToken, regionId }) - // `bound` is set only when the region came from the device fix, so this is - // exactly the "location was tracked" case. + // `origin === 'device'` is exactly the "location was tracked" case. if (fromLocation) { recordTrackedRegionMutate({ regionId }) } - }, [expoPushToken, notifPermission, regionId, bound, savePushTokenMutate, recordTrackedRegionMutate]) + }, [expoPushToken, notifPermission, regionId, origin, savePushTokenMutate, recordTrackedRegionMutate]) return null } diff --git a/apps/user-ui/src/components/PendingAddressSync.tsx b/apps/user-ui/src/components/PendingAddressSync.tsx index b0c7a0b..20f74e2 100644 --- a/apps/user-ui/src/components/PendingAddressSync.tsx +++ b/apps/user-ui/src/components/PendingAddressSync.tsx @@ -2,6 +2,8 @@ import { useEffect, useRef } from 'react' import { trpc } from '@/src/trpc-client' import { useAuth } from '@/src/contexts/AuthContext' import { clearPendingAddress, getPendingAddress } from '@/src/lib/pending-address' +import { toNeoAddress } from '@/src/lib/neo-address' +import { useNeoRegionStore } from '@/src/store/neoRegionStore' /** * Posts a locally-drafted address (created while signed out in the location @@ -26,10 +28,23 @@ const PendingAddressSync: React.FC = () => { isSyncing.current = true try { - await createAddress.mutateAsync(pending) + const created = await createAddress.mutateAsync(pending) await clearPendingAddress() await utils.user.address.getUserAddresses.invalidate() await utils.user.address.getDefaultAddress.invalidate() + + // The draft was the address the user was checking out with; make it the + // active selection as soon as the list is available. + try { + const response = await utils.user.address.getUserAddresses.fetch(undefined) + useNeoRegionStore.getState().setAddresses(response.data.map(toNeoAddress)) + const createdId = created?.data?.id + if (createdId != null) { + await useNeoRegionStore.getState().selectAddress(createdId) + } + } catch { + // The subscription will refresh the list; the decision selects the default. + } } catch { // Leave the draft in place; a later authenticated mount retries it. } finally { diff --git a/apps/user-ui/src/components/location/AddressSwitcherSheet.tsx b/apps/user-ui/src/components/location/AddressSwitcherSheet.tsx index b73ac47..6bc4df9 100644 --- a/apps/user-ui/src/components/location/AddressSwitcherSheet.tsx +++ b/apps/user-ui/src/components/location/AddressSwitcherSheet.tsx @@ -1,7 +1,7 @@ import React from 'react' import { Modal, View } from 'react-native' import { tw } from 'common-ui' -import LocationFallbackFlow from './LocationFallbackFlow' +import NeoAddressFlow from './neo/NeoAddressFlow' interface AddressSwitcherSheetProps { open: boolean @@ -16,7 +16,7 @@ interface AddressSwitcherSheetProps { const AddressSwitcherSheet: React.FC = ({ open, onClose }) => ( - + ) diff --git a/apps/user-ui/src/components/location/neo/NeoAddressFlow.tsx b/apps/user-ui/src/components/location/neo/NeoAddressFlow.tsx new file mode 100644 index 0000000..39971e1 --- /dev/null +++ b/apps/user-ui/src/components/location/neo/NeoAddressFlow.tsx @@ -0,0 +1,206 @@ +import React, { useEffect, useRef, useState } from 'react' +import { ScrollView, View } from 'react-native' +import MaterialIcons from '@expo/vector-icons/MaterialIcons' +import { MyText, MyTouchableOpacity, tw } from 'common-ui' +import Login from '@/app/(auth)/login' +import { useAuthOptional } from '@/src/contexts/AuthContext' +import { useLocationStore } from '@/src/store/locationStore' +import { useNeoRegionStore } from '@/src/store/neoRegionStore' +import { formatNeoAddress } from '@/src/lib/neo-address' +import NeoAddressForm from './NeoAddressForm' + +interface NeoAddressFlowProps { + /** Present when hosted in the location-bar sheet. */ + onClose?: () => void +} + +const NOTICE: Partial> = { + denied: 'Location access is not granted. Allow it for accurate delivery, or add an address below.', + 'services-off': 'Your device location is turned off. Turn it on, or add an address below.', + unavailable: 'We could not get your location. Try again, or add an address below.', + error: 'We could not get your location. Try again, or add an address below.', +} + +/** + * The whole address fallback: choose a saved address, add one, or sign in. + * Used both by the wrapper (no usable region) and by the location bar sheet. + */ +const NeoAddressFlow: React.FC = ({ onClose }) => { + const auth = useAuthOptional() + const isAuthenticated = auth?.isAuthenticated ?? false + const regionId = useNeoRegionStore((state) => state.regionId) + const addresses = useNeoRegionStore((state) => state.addresses) + const selectedAddressId = useNeoRegionStore((state) => state.selectedAddressId) + const closeAddressFlow = useNeoRegionStore((state) => state.closeAddressFlow) + const selectAddress = useNeoRegionStore((state) => state.selectAddress) + const locationStatus = useLocationStore((state) => state.status) + + const [mode, setMode] = useState<'choose' | 'add' | 'login'>('choose') + const autoOpened = useRef(false) + + useEffect(() => { + if (mode === 'login' && isAuthenticated) setMode('choose') + }, [mode, isAuthenticated]) + + // With exactly one saved address the startup gate can open it without making + // the user tap a one-item list. Only the gate: when this flow is the + // location-bar sheet (onClose) the user opened it to look at or change the + // address, so auto-selecting would flash the sheet open and closed — which + // reads as a dead tap. A published region also means the gate is not showing + // the startup chooser (e.g. "add an address here" from the confirmation). + useEffect(() => { + if (onClose != null || regionId != null) return + if (mode !== 'choose' || !isAuthenticated || autoOpened.current) return + if (addresses.length !== 1) return + autoOpened.current = true + void selectAddress(addresses[0].id).then(() => { + // Its region may no longer be serviceable; closing would strand the + // loading screen, so keep the chooser up instead. + if (useNeoRegionStore.getState().regionId == null) return + closeAddressFlow() + }) + }, [onClose, regionId, mode, isAuthenticated, addresses, selectAddress, closeAddressFlow]) + + const pick = async (id: number) => { + await selectAddress(id) + closeAddressFlow() + onClose?.() + } + + if (mode === 'add') { + return ( + + setMode('choose')} + activeOpacity={0.7} + style={tw`px-5 pt-12 pb-2 flex-row items-center`} + > + + Back + + { + closeAddressFlow() + onClose?.() + }} + /> + + ) + } + + if (mode === 'login') { + return ( + + + setMode('choose')} + activeOpacity={0.7} + style={tw`absolute left-4 top-14 w-10 h-10 rounded-full bg-white/90 items-center justify-center shadow`} + > + + + + ) + } + + return ( + + + + + + Delivery Address + + + Choose a saved address, or add a new one. Your region follows the address. + + + {onClose != null && ( + + + + )} + + + {NOTICE[locationStatus] && regionId == null && ( + + {NOTICE[locationStatus]} + + )} + + + {addresses.map((address) => { + const isSelected = address.id === selectedAddressId + return ( + void pick(address.id)} + activeOpacity={0.85} + style={tw`border ${ + isSelected ? 'border-indigo-500 bg-indigo-50' : 'border-gray-200 bg-white' + } rounded-2xl p-4 mb-3`} + > + + + {address.name} + {address.isDefault && ( + Default + )} + {isSelected && ( + Selected + )} + + + {formatNeoAddress(address)} + + {address.phone} + + ) + })} + + {addresses.length === 0 && ( + + {isAuthenticated + ? 'You have no saved addresses yet.' + : 'Sign in to use a saved address, or add one now.'} + + )} + + + setMode('add')} + activeOpacity={0.85} + style={tw`mt-2 bg-indigo-600 py-3.5 rounded-xl items-center`} + > + Add new address + + + {!isAuthenticated && ( + setMode('login')} + activeOpacity={0.85} + style={tw`mt-3 border border-gray-200 py-3.5 rounded-xl items-center`} + > + Sign in to save your address + + )} + + + ) +} + +export default NeoAddressFlow diff --git a/apps/user-ui/src/components/location/neo/NeoAddressForm.tsx b/apps/user-ui/src/components/location/neo/NeoAddressForm.tsx new file mode 100644 index 0000000..d2858a6 --- /dev/null +++ b/apps/user-ui/src/components/location/neo/NeoAddressForm.tsx @@ -0,0 +1,122 @@ +import React, { useCallback, useRef, useState } from 'react' +import { View } from 'react-native' +import { BottomDialog, MyText, MyTouchableOpacity, tw } from 'common-ui' +import AddressForm from '@/src/components/AddressForm' +import { useAuthOptional } from '@/src/contexts/AuthContext' +import { useNeoRegionStore } from '@/src/store/neoRegionStore' +import { trpc } from '@/src/trpc-client' +import { toNeoAddress } from '@/src/lib/neo-address' + +type ResolvedRegion = { regionId: number; boundId: number | null } + +interface NeoAddressFormProps { + onDone?: () => void +} + +/** + * Adapter around the existing AddressForm. The form itself already implements + * the add-address chart (device fix prefilled, map picker, serviceability gate, + * "outside the area -> pick on the map"). This wrapper only: + * - writes the result into the neo store, + * - warns before an address in another region switches the browsing region. + */ +const NeoAddressForm: React.FC = ({ onDone }) => { + const auth = useAuthOptional() + const isAuthenticated = auth?.isAuthenticated ?? false + const utils = trpc.useUtils() + const currentRegionId = useNeoRegionStore((state) => state.regionId) + const currentRegionName = useNeoRegionStore((state) => state.regionName) ?? 'your current region' + const regions = useNeoRegionStore((state) => state.regions) + const setAddresses = useNeoRegionStore((state) => state.setAddresses) + const changeRegion = useNeoRegionStore((state) => state.changeRegion) + const selectAddress = useNeoRegionStore((state) => state.selectAddress) + + const [resolved, setResolved] = useState(null) + const [warningOpen, setWarningOpen] = useState(false) + const warningResolver = useRef<((ok: boolean) => void) | null>(null) + + const targetRegionName = + resolved != null + ? regions.find((region) => region.id === resolved.regionId)?.name ?? 'another region' + : 'another region' + + const onBeforeSubmit = useCallback((): boolean | Promise => { + if (resolved == null || currentRegionId == null) return true + if (resolved.regionId === currentRegionId) return true + return new Promise((resolve) => { + warningResolver.current = resolve + setWarningOpen(true) + }) + }, [currentRegionId, resolved]) + + const finishWarning = (ok: boolean) => { + setWarningOpen(false) + warningResolver.current?.(ok) + warningResolver.current = null + } + + const handleSuccess = async (addressId?: number) => { + // The server has the address now; refresh the store before selecting it. + if (addressId != null) { + try { + const response = await utils.user.address.getUserAddresses.fetch(undefined) + setAddresses(response.data.map(toNeoAddress)) + } catch { + // The subscription will refresh the list on the next fetch. + } + await selectAddress(addressId) + onDone?.() + return + } + + // Signed-out draft: the address is stored locally and posted after login. + // The browsing region still follows the chosen location now. + if (resolved != null) { + await changeRegion(resolved.regionId, resolved.boundId) + } + onDone?.() + } + + return ( + + { + void handleSuccess(addressId) + }} + /> + + finishWarning(false)}> + + Switch region? + + This address is in {targetRegionName}. Saving it will switch you from{' '} + {currentRegionName} and clear your cart for that region. + + + finishWarning(false)} + activeOpacity={0.85} + style={tw`border border-gray-200 py-3.5 rounded-xl items-center mb-3`} + > + Cancel + + + finishWarning(true)} + activeOpacity={0.85} + style={tw`bg-indigo-600 py-3.5 rounded-xl items-center`} + > + Switch and save + + + + + ) +} + +export default NeoAddressForm diff --git a/apps/user-ui/src/components/location/neo/NeoConfirmLocation.tsx b/apps/user-ui/src/components/location/neo/NeoConfirmLocation.tsx new file mode 100644 index 0000000..0ee009e --- /dev/null +++ b/apps/user-ui/src/components/location/neo/NeoConfirmLocation.tsx @@ -0,0 +1,82 @@ +import React from 'react' +import { View } from 'react-native' +import MaterialIcons from '@expo/vector-icons/MaterialIcons' +import { BottomDropdown, MyText, MyTouchableOpacity, tw } from 'common-ui' +import { formatNeoAddress } from '@/src/lib/neo-address' +import { useRegionNeo } from '@/src/hooks/useRegionNeo' +import { useNeoRegionStore } from '@/src/store/neoRegionStore' +import NeoFixedPinMap from './NeoFixedPinMap' + +/** + * Shown only when the device put the app in a region where none of the user's + * saved addresses live. The region is already active (there is no pending + * candidate); this screen offers a way back to one of those addresses, or to + * add a new one, or to keep the device region. + */ +const NeoConfirmLocation: React.FC = () => { + const data = useRegionNeo() + const addresses = useNeoRegionStore((state) => state.addresses) + const selectedAddressId = useNeoRegionStore((state) => state.selectedAddressId) + const setNeedsConfirmation = useNeoRegionStore((state) => state.setNeedsConfirmation) + const openAddressFlow = useNeoRegionStore((state) => state.openAddressFlow) + + const options = addresses.map((address) => ({ + label: formatNeoAddress(address) || address.name, + value: address.id, + })) + + return ( + + + + + + + + + + You are in {data.regionName} + + + + None of your saved addresses are in this region. Pick one to switch back, add a new + address here, or keep this location. + + + {options.length > 0 && ( + { + void data.selectAddress(Number(value)) + }} + /> + )} + + openAddressFlow()} + activeOpacity={0.85} + style={tw`mt-4 border border-indigo-200 bg-indigo-50 py-3.5 rounded-xl items-center`} + > + Add a new address here + + + setNeedsConfirmation(false)} + activeOpacity={0.85} + style={tw`mt-3 bg-indigo-600 py-3.5 rounded-xl items-center`} + > + Keep this location + + + + ) +} + +export default NeoConfirmLocation diff --git a/apps/user-ui/src/components/location/neo/NeoFixedPinMap.tsx b/apps/user-ui/src/components/location/neo/NeoFixedPinMap.tsx new file mode 100644 index 0000000..105651d --- /dev/null +++ b/apps/user-ui/src/components/location/neo/NeoFixedPinMap.tsx @@ -0,0 +1,47 @@ +import React, { useState } from 'react' +import { ActivityIndicator, View } from 'react-native' +import { WebView } from 'react-native-webview' +import { MyText, theme, tw } from 'common-ui' +import constants from '@/src/constants' +import type { NeoCoords } from '@/src/lib/neo-address' + +interface NeoFixedPinMapProps { + coords: NeoCoords +} + +/** + * Read-only map for the confirmation screen: the pin is already the resolved + * location and must not move ("no cursor movement" in the flow chart). + * `/location-selector?fixed=1` renders the page with a non-draggable marker. + */ +const NeoFixedPinMap: React.FC = ({ coords }) => { + const [isLoading, setIsLoading] = useState(true) + const url = + `${constants.WEB_UI_BASE_URL}/location-selector` + + `?lat=${coords.latitude}&lng=${coords.longitude}&fixed=1` + + return ( + + setIsLoading(false)} + startInLoadingState + scrollEnabled={false} + geolocationEnabled + /> + + {isLoading && ( + + + Loading map... + + )} + + ) +} + +export default NeoFixedPinMap diff --git a/apps/user-ui/src/components/location/neo/NeoLoadingScreen.tsx b/apps/user-ui/src/components/location/neo/NeoLoadingScreen.tsx new file mode 100644 index 0000000..1daa591 --- /dev/null +++ b/apps/user-ui/src/components/location/neo/NeoLoadingScreen.tsx @@ -0,0 +1,12 @@ +import React from 'react' +import { ActivityIndicator, View } from 'react-native' +import { MyText, theme, tw } from 'common-ui' + +const NeoLoadingScreen: React.FC<{ label?: string }> = ({ label = 'Finding your region...' }) => ( + + + {label} + +) + +export default NeoLoadingScreen diff --git a/apps/user-ui/src/hooks/prominent-api-hooks.ts b/apps/user-ui/src/hooks/prominent-api-hooks.ts index 970ef60..29a2b47 100644 --- a/apps/user-ui/src/hooks/prominent-api-hooks.ts +++ b/apps/user-ui/src/hooks/prominent-api-hooks.ts @@ -6,8 +6,7 @@ import type { ProductPriceFlags } from '@packages/shared' import { AllProductsApiType, StoresApiType, SlotsApiType, EssentialConstsApiType, StoreWithProductsApiType, AvailabilityApiType } from "@backend/trpc/router"; import { CACHE_FILENAMES, availabilityCacheUrl, cachedFileUrl, regionCacheUrl, slotsCacheUrl, storeDetailCacheUrl } from "@packages/shared"; import { StorageServiceCasual } from 'common-ui'; -import { useRegion } from '@/src/hooks/useRegion' -import { useAddressStore } from '@/src/store/addressStore' +import { useNeoRegionStore } from '@/src/store/neoRegionStore' import { useAuthOptional } from '@/src/contexts/AuthContext' // Discovery payload: the flat per-bound consts object (global + region + bound @@ -19,12 +18,13 @@ export type DiscoveryData = EssentialConstsApiType const essentialConstsKey = (boundId: number) => `essential_consts_b${boundId}` export const useGetEssentialConsts = () => { - // The active bound (least-priority bound among the user's addresses in the - // region, else the region's effective bound) drives the constants; at checkout - // the selected address's bound overrides it. - const { boundId: activeBoundId, coords, regionId } = useRegion() + // The active bound drives the constants. This hook runs above the location + // wrapper (UpdateChecker / HealthTestWrapper), so it reads the store directly + // and tolerates an empty store instead of calling useRegionNeo. + const activeBoundId = useNeoRegionStore((state) => state.boundId) + const regionId = useNeoRegionStore((state) => state.regionId) const isAuthenticated = useAuthOptional()?.isAuthenticated ?? false - const selectedAddressId = useAddressStore((state) => state.selectedAddressId) + const selectedAddressId = useNeoRegionStore((state) => state.selectedAddressId) const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, { enabled: isAuthenticated && selectedAddressId != null, @@ -117,7 +117,7 @@ export type MergedProduct = BaseProduct & ProductPriceFlags & { } function useDiscoveryRegionId(essentialConsts: unknown): number | null { - const { regionId: selectedRegionId } = useRegion() + const selectedRegionId = useNeoRegionStore((state) => state.regionId) const discovery = essentialConsts as DiscoveryData | undefined return discovery?.regionId ?? selectedRegionId } diff --git a/apps/user-ui/src/hooks/useRegionNeo.ts b/apps/user-ui/src/hooks/useRegionNeo.ts new file mode 100644 index 0000000..709e51b --- /dev/null +++ b/apps/user-ui/src/hooks/useRegionNeo.ts @@ -0,0 +1,403 @@ +import { useEffect, useRef, useState } from 'react' +import { useQueryClient } from '@tanstack/react-query' +import type { RegionSummary } from '@packages/shared' +import { trpc } from '@/src/trpc-client' +import { useAuthOptional } from '@/src/contexts/AuthContext' +import { useLocationStore } from '@/src/store/locationStore' +import { + bindNeoRegionQueryClient, + useNeoRegionStore, + type NeoRegionData, +} from '@/src/store/neoRegionStore' +import { + decideNeoRegion, + type NeoCachedSnapshot, + type NeoResolvedRegion, +} from '@/src/lib/neo-region-decision' +import { readNeoRegionSnapshot } from '@/src/lib/neo-region-cache' +import { applyRegionSwitch } from '@/src/lib/neo-region-switch' +import { + formatNeoAddress, + toNeoAddress, + type NeoAddress, + type NeoCoords, +} from '@/src/lib/neo-address' + +export type { NeoRegionData } + +// One launch decision per app launch. The recovery poll resets it deliberately. +let decisionStarted = false +let snapshotRead: Promise>> | null = null + +const LOCATION_POLL_MS = 3000 +const LOCATION_TIMEOUT_MS = 8000 + +function regionCoords(region: RegionSummary | undefined | null): NeoCoords | null { + if (region?.center == null) return null + return { latitude: region.center.lat, longitude: region.center.lng } +} + +const TERMINAL_LOCATION_STATUSES = [ + 'granted', + 'denied', + 'services-off', + 'unavailable', + 'error', +] as const + +/** + * Runs the chart's decision once per launch: + * persisted snapshot -> one device fix -> resolve -> decide -> publish. + * + * Mounted by LocationWrapperNeo, which is always present inside AuthProvider. + * It writes the store; it does not expose data. + */ +export function useNeoRegionBootstrap(): void { + const auth = useAuthOptional() + const hasAuthContext = auth != null + const isAuthenticated = auth?.isAuthenticated ?? false + const isAuthLoading = auth?.isLoading ?? false + const userId = auth?.user?.id ?? null + + const queryClient = useQueryClient() + const utils = trpc.useUtils() + const state = useNeoRegionStore() + + const coords = useLocationStore((store) => store.coords) + const locationStatus = useLocationStore((store) => store.status) + const startTracking = useLocationStore((store) => store.start) + const probeLocation = useLocationStore((store) => store.probe) + const refreshLocation = useLocationStore((store) => store.refresh) + + const [timedOut, setTimedOut] = useState(false) + const [decisionTick, setDecisionTick] = useState(0) + const lastAuthRef = useRef(null) + + const addressesQuery = trpc.user.address.getUserAddresses.useQuery(undefined, { + enabled: isAuthenticated, + }) + // Starts on mount, in parallel with the device fix. The decision waits for it + // instead of fetching regions inside `run`. + const regionsQuery = trpc.common.listRegions.useQuery() + + useEffect(() => { + bindNeoRegionQueryClient(queryClient) + }, [queryClient]) + + // One device fix per launch. The store is a singleton and start() is idempotent. + useEffect(() => { + startTracking() + }, [startTracking]) + + // Publish the persisted snapshot immediately; the decision may switch later. + useEffect(() => { + if (snapshotRead == null) snapshotRead = readNeoRegionSnapshot() + let cancelled = false + void snapshotRead.then((snapshot) => { + if (cancelled || snapshot == null) return + const current = useNeoRegionStore.getState() + if (current.regionId != null) return + const cachedAddress = + snapshot.selectedAddress != null && + snapshot.selectedAddress.regionId === snapshot.regionId + ? snapshot.selectedAddress + : null + if (cachedAddress != null) { + // Provisional: the live list replaces this entry, and validation clears + // the selection if the address no longer exists. + current.setAddresses([cachedAddress]) + } + current.applyRegion({ + regionId: snapshot.regionId, + boundId: snapshot.boundId, + regionName: snapshot.regionName, + coords: snapshot.coords, + origin: 'cache', + selectedAddressId: cachedAddress?.id ?? null, + }) + }) + return () => { + cancelled = true + } + }, []) + + // Keep the store's address list in sync with the live query. Re-applying the + // selected address keeps its coords/bound fresh after an edit (e.g. attach + // current location), and is a no-op when nothing changed. + useEffect(() => { + if (!addressesQuery.data) return + const store = useNeoRegionStore.getState() + store.setAddresses(addressesQuery.data.data.map(toNeoAddress)) + const selectedId = useNeoRegionStore.getState().selectedAddressId + if (selectedId != null) void useNeoRegionStore.getState().selectAddress(selectedId) + }, [addressesQuery.data]) + + useEffect(() => { + if (isAuthenticated) return + useNeoRegionStore.getState().setAddresses([]) + }, [isAuthenticated]) + + // A hanging location read must not strand the first launch. + useEffect(() => { + if (!hasAuthContext) return + const timer = setTimeout(() => setTimedOut(true), LOCATION_TIMEOUT_MS) + return () => clearTimeout(timer) + }, [hasAuthContext]) + + // Logging in or out changes the address anchor; re-run the decision once. + useEffect(() => { + if (!hasAuthContext || isAuthLoading) return + if (lastAuthRef.current == null) { + lastAuthRef.current = isAuthenticated + return + } + if (lastAuthRef.current !== isAuthenticated) { + lastAuthRef.current = isAuthenticated + decisionStarted = false + setDecisionTick((tick) => tick + 1) + } + }, [hasAuthContext, isAuthLoading, isAuthenticated]) + + useEffect(() => { + if (!hasAuthContext || isAuthLoading) return + if (decisionStarted) return + + const settled = + coords != null || + (TERMINAL_LOCATION_STATUSES as readonly string[]).includes(locationStatus) + if (!settled && !timedOut) return + + // These queries start on mount / when auth settles; wait for them rather + // than fetching them sequentially here. + const regionsReady = regionsQuery.isFetched || regionsQuery.isError + const addressesReady = + !isAuthenticated || addressesQuery.isFetched || addressesQuery.isError + if (!regionsReady || !addressesReady) return + + decisionStarted = true + + const run = async () => { + const fix = useLocationStore.getState().coords + + // The snapshot read and the coordinate resolve are independent. + const [snapshot, resolveResult] = await Promise.all([ + snapshotRead ?? readNeoRegionSnapshot(), + fix != null + ? utils.common.resolveRegionByLocation + .fetch({ lat: fix.latitude, lng: fix.longitude }) + .catch(() => null) + : Promise.resolve(null), + ]) + + const store = useNeoRegionStore.getState() + + let cached: NeoCachedSnapshot | null = null + if ( + store.regionId != null && + store.boundId != null && + store.regionName != null && + store.coords != null + ) { + cached = { + regionId: store.regionId, + boundId: store.boundId, + regionName: store.regionName, + coords: store.coords, + } + } else if (snapshot != null) { + cached = { + regionId: snapshot.regionId, + boundId: snapshot.boundId, + regionName: snapshot.regionName, + coords: snapshot.coords, + } + } + + const regions = regionsQuery.data ?? store.regions + useNeoRegionStore.getState().setRegions(regions) + + if (cached != null && !regions.some((region) => region.id === cached?.regionId)) { + useNeoRegionStore.getState().clearRegion() + cached = null + } + + let addresses: NeoAddress[] = [] + if (isAuthenticated) { + addresses = + addressesQuery.data != null + ? addressesQuery.data.data.map(toNeoAddress) + : useNeoRegionStore.getState().addresses + } + useNeoRegionStore.getState().setAddresses(addresses) + // Read after setAddresses: it clears the selection if the cached address + // is no longer in the live list. + const selectedAddressId = useNeoRegionStore.getState().selectedAddressId + + let resolved: NeoResolvedRegion | null = null + if (resolveResult != null) { + const region = regions.find((candidate) => candidate.id === resolveResult.region.id) + const boundId = resolveResult.bound?.id ?? region?.effectiveBoundId ?? null + if (boundId != null) { + resolved = { regionId: resolveResult.region.id, boundId } + } + } + + const decision = decideNeoRegion({ + cached, + fix, + resolved, + isAuthenticated, + addresses, + selectedAddressId, + }) + + if (decision.action === 'needs-address-flow') { + useNeoRegionStore.getState().openAddressFlow() + return + } + + const region = regions.find((candidate) => candidate.id === decision.regionId) + const boundId = decision.boundId ?? region?.effectiveBoundId ?? null + const decisionCoords = decision.action === 'ready' ? decision.coords : null + const targetCoords = decisionCoords ?? regionCoords(region) ?? cached?.coords ?? fix + + if (region == null || boundId == null || targetCoords == null) { + useNeoRegionStore.getState().openAddressFlow() + return + } + + // A decision that moves away from the published region is a real switch: + // stash/clear the carts and invalidate the region-scoped caches, exactly + // like an explicit changeRegion. + const previousRegionId = useNeoRegionStore.getState().regionId + if (previousRegionId != null && previousRegionId !== decision.regionId) { + await applyRegionSwitch(previousRegionId, decision.regionId, queryClient) + } + + useNeoRegionStore.getState().applyRegion({ + regionId: decision.regionId, + boundId, + regionName: region.name, + coords: targetCoords, + origin: decision.action === 'needs-confirmation' ? 'device' : decision.origin, + selectedAddressId: + decision.action === 'needs-confirmation' ? null : decision.selectedAddressId, + }) + + if (decision.action === 'needs-confirmation') { + useNeoRegionStore.getState().setNeedsConfirmation(true) + } + } + + void run().catch(() => { + // A failed decision must not strand the loading screen forever. + useNeoRegionStore.getState().openAddressFlow() + }) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [ + hasAuthContext, + isAuthLoading, + isAuthenticated, + coords, + locationStatus, + timedOut, + decisionTick, + userId, + regionsQuery.data, + regionsQuery.isFetched, + regionsQuery.isError, + addressesQuery.data, + addressesQuery.isFetched, + addressesQuery.isError, + ]) + + // If the user leaves for the OS settings and turns location on, recover + // without a restart while the address flow is up. Only poll when the location + // is actually unusable: when the flow is up because the user has no address, + // the fix already exists and re-deciding would just flicker the screen. + const locationIsUnusable = + locationStatus === 'denied' || + locationStatus === 'services-off' || + locationStatus === 'unavailable' || + locationStatus === 'error' + + useEffect(() => { + if (!state.needsAddressFormFlow || !locationIsUnusable) return + + let cancelled = false + let busy = false + + const check = async () => { + if (busy) return + busy = true + try { + const usable = await probeLocation() + if (cancelled || !usable) return + await refreshLocation() + if (cancelled) return + decisionStarted = false + useNeoRegionStore.getState().closeAddressFlow() + setDecisionTick((tick) => tick + 1) + } finally { + busy = false + } + } + + void check() + const timer = setInterval(() => void check(), LOCATION_POLL_MS) + return () => { + cancelled = true + clearInterval(timer) + } + }, [state.needsAddressFormFlow, locationIsUnusable, probeLocation, refreshLocation]) + +} + +/** + * The region/address data, never null. + * + * Only call this from components that LocationWrapperNeo renders — the wrapper + * guarantees the store holds a complete region before children appear. Calling + * it earlier is a bug, so it throws rather than handing out a half-answer. + */ +export function useRegionNeo(): NeoRegionData { + const state = useNeoRegionStore() + const isAuthenticated = useAuthOptional()?.isAuthenticated ?? false + const addressesQuery = trpc.user.address.getUserAddresses.useQuery(undefined, { + enabled: isAuthenticated, + }) + + const { regionId, boundId, regionName, coords, origin, selectedAddressId } = state + + if (regionId == null || boundId == null || regionName == null || coords == null) { + throw new Error( + 'useRegionNeo() called before LocationWrapperNeo published a region. ' + + 'It may only be used by components rendered inside the wrapper.' + ) + } + + // Live query data wins; the store is the fallback while the query loads (it + // also carries the provisional cached address from the snapshot). + const liveAddresses = addressesQuery.data?.data.map(toNeoAddress) ?? null + const addresses = liveAddresses ?? state.addresses + + const selected = + selectedAddressId != null + ? addresses.find((address) => address.id === selectedAddressId) ?? null + : null + + return { + regionId, + boundId, + regionName, + coords, + selectedAddressId: selected?.id ?? null, + selectedAddress: selected, + fullAddress: selected != null ? formatNeoAddress(selected) : null, + isCache: origin === 'cache', + changeRegion: state.changeRegion, + // Async only because a cross-region selection awaits the cart switch. + // Never performs an address API call; the caller refreshes after mutations. + selectAddress: state.selectAddress, + } +} diff --git a/apps/user-ui/src/lib/neo-address.ts b/apps/user-ui/src/lib/neo-address.ts new file mode 100644 index 0000000..2b85538 --- /dev/null +++ b/apps/user-ui/src/lib/neo-address.ts @@ -0,0 +1,79 @@ +import type { UserAddress } from '@packages/shared' + +/** Coordinates as the app stores them (the shared DTO uses lat/lng on region centres). */ +export interface NeoCoords { + latitude: number + longitude: number +} + +/** + * The address shape the neo region store works with. Deliberately a small, + * serializable projection of `UserAddress`: the fields the region decision and + * the checkout surfaces actually read. + */ +export interface NeoAddress { + id: number + regionId: number | null + boundId: number | null + name: string + phone: string + addressLine1: string + addressLine2: string | null + city: string + state: string + isDefault: boolean + latitude: number | null + longitude: number | null + googleMapsUrl: string | null +} + +type AddressLike = Pick< + UserAddress, + 'id' | 'name' | 'phone' | 'addressLine1' | 'city' | 'state' | 'isDefault' +> & { + regionId?: number | null + boundId?: number | null + addressLine2?: string | null + latitude?: number | null + longitude?: number | null + googleMapsUrl?: string | null +} + +/** Normalize a `UserAddress` (or a serialized copy of one) into `NeoAddress`. */ +export function toNeoAddress(address: AddressLike): NeoAddress { + return { + id: address.id, + regionId: address.regionId ?? null, + boundId: address.boundId ?? null, + name: address.name, + phone: address.phone, + addressLine1: address.addressLine1, + addressLine2: address.addressLine2 ?? null, + city: address.city, + state: address.state, + isDefault: address.isDefault, + latitude: address.latitude ?? null, + longitude: address.longitude ?? null, + googleMapsUrl: address.googleMapsUrl ?? null, + } +} + +export function addressCoords(address: NeoAddress): NeoCoords | null { + if (address.latitude == null || address.longitude == null) return null + return { latitude: address.latitude, longitude: address.longitude } +} + +/** Icon name for the address card, based on the address label. */ +export function addressIconName(name: string): 'home' | 'work' | 'location-on' { + const normalized = name.toLowerCase() + if (normalized.includes('home')) return 'home' + if (normalized.includes('work')) return 'work' + return 'location-on' +} + +/** One-line delivery address used by the location bar and the checkout card. */ +export function formatNeoAddress(address: NeoAddress): string { + return [address.addressLine1, address.addressLine2, address.city] + .filter((part): part is string => typeof part === 'string' && part.trim().length > 0) + .join(', ') +} diff --git a/apps/user-ui/src/lib/neo-region-cache.ts b/apps/user-ui/src/lib/neo-region-cache.ts new file mode 100644 index 0000000..a42b888 --- /dev/null +++ b/apps/user-ui/src/lib/neo-region-cache.ts @@ -0,0 +1,63 @@ +import { StorageServiceCasual } from 'common-ui' +import type { NeoAddress, NeoCoords } from '@/src/lib/neo-address' + +const NEO_REGION_KEY = 'freshyo_neo_region_v1' + +/** The last published region, so the next launch renders before the fix lands. */ +export interface NeoRegionSnapshot { + regionId: number + boundId: number + regionName: string + coords: NeoCoords + /** The address that was active when the snapshot was written. */ + selectedAddress: NeoAddress | null +} + +function isSnapshot(value: unknown): value is NeoRegionSnapshot { + if (value == null || typeof value !== 'object') return false + const candidate = value as Record + const coords = candidate.coords as Record | null | undefined + const selected = candidate.selectedAddress as Record | null | undefined + const selectedOk = + selected == null || + (typeof selected === 'object' && typeof selected.id === 'number') + return ( + typeof candidate.regionId === 'number' && + typeof candidate.boundId === 'number' && + typeof candidate.regionName === 'string' && + coords != null && + typeof coords === 'object' && + typeof coords.latitude === 'number' && + typeof coords.longitude === 'number' && + selectedOk + ) +} + +export async function readNeoRegionSnapshot(): Promise { + try { + const raw = await StorageServiceCasual.getItem(NEO_REGION_KEY) + if (!raw) return null + const parsed = JSON.parse(raw) as unknown + if (!isSnapshot(parsed)) return null + // Snapshots written before the address was cached have no field. + return { ...parsed, selectedAddress: parsed.selectedAddress ?? null } + } catch { + return null + } +} + +export async function writeNeoRegionSnapshot(snapshot: NeoRegionSnapshot): Promise { + try { + await StorageServiceCasual.setItem(NEO_REGION_KEY, JSON.stringify(snapshot)) + } catch { + // Persistence is best-effort; the live decision still corrects the region. + } +} + +export async function clearNeoRegionSnapshot(): Promise { + try { + await StorageServiceCasual.removeItem(NEO_REGION_KEY) + } catch { + // ignore + } +} diff --git a/apps/user-ui/src/lib/neo-region-decision.ts b/apps/user-ui/src/lib/neo-region-decision.ts new file mode 100644 index 0000000..dc6f35c --- /dev/null +++ b/apps/user-ui/src/lib/neo-region-decision.ts @@ -0,0 +1,183 @@ +import { addressCoords, type NeoAddress, type NeoCoords } from '@/src/lib/neo-address' + +export type NeoOrigin = 'device' | 'cache' | 'address' | 'manual' + +export interface NeoCachedSnapshot { + regionId: number + boundId: number + regionName: string + coords: NeoCoords +} + +export interface NeoResolvedRegion { + regionId: number + boundId: number +} + +/** + * The outcome of one launch decision. `coords` / `boundId` may be null when the + * chosen address has no coordinates and no cached fix exists; the hook fills + * them from the region's centre / effective bound before publishing. + */ +export type NeoDecision = + | { + action: 'ready' + regionId: number + boundId: number | null + coords: NeoCoords | null + origin: NeoOrigin + selectedAddressId: number | null + } + | { action: 'needs-address-flow' } + | { action: 'needs-confirmation'; regionId: number; boundId: number | null } + +export interface DecideNeoRegionInput { + cached: NeoCachedSnapshot | null + fix: NeoCoords | null + resolved: NeoResolvedRegion | null + isAuthenticated: boolean + addresses: NeoAddress[] + /** The currently active address (restored from the persisted snapshot). */ + selectedAddressId?: number | null +} + +function defaultAddress(addresses: NeoAddress[]): NeoAddress | null { + return addresses.find((address) => address.isDefault) ?? addresses[0] ?? null +} + +/** + * The active address inside a region: the persisted selection first, then the + * default, then the first one there. + */ +function preferredInRegion( + addresses: NeoAddress[], + regionId: number, + selectedAddressId: number | null +): NeoAddress | null { + const inRegion = addresses.filter((address) => address.regionId === regionId) + return ( + inRegion.find((address) => address.id === selectedAddressId) ?? + inRegion.find((address) => address.isDefault) ?? + inRegion[0] ?? + null + ) +} + +/** The persisted selection anywhere, else the default, else the first. */ +function bestAddress( + addresses: NeoAddress[], + selectedAddressId: number | null +): NeoAddress | null { + return ( + addresses.find((address) => address.id === selectedAddressId) ?? + defaultAddress(addresses) + ) +} + +function readyWithAddress(address: NeoAddress): NeoDecision { + return { + action: 'ready', + regionId: address.regionId as number, + boundId: address.boundId, + coords: addressCoords(address), + origin: 'address', + selectedAddressId: address.id, + } +} + +/** + * The chart, as a pure function. + * + * - no cached region -> a saved address always wins (decision 2); only a + * user with no address at all follows the device fix; + * - cached region + same region -> keep it (and select an address there); + * - cached region + different region -> the address in the new region wins; + * with no such address, an address-owning user is asked to confirm, while a + * guest / address-less user simply follows the device. + */ +export function decideNeoRegion(input: DecideNeoRegionInput): NeoDecision { + // Addresses without a region can never anchor a decision. + const addresses = input.isAuthenticated + ? input.addresses.filter((address) => address.regionId != null) + : [] + const cached = input.cached + const fix = input.fix + const resolved = input.resolved + const selectedAddressId = input.selectedAddressId ?? null + + // No usable device answer: keep the persisted region, or fall back to the + // user's default address, or ask for an address. + if (resolved == null) { + if (cached != null) { + const selected = preferredInRegion(addresses, cached.regionId, selectedAddressId) + return { + action: 'ready', + regionId: cached.regionId, + boundId: selected?.boundId ?? cached.boundId, + coords: selected ? addressCoords(selected) ?? cached.coords : cached.coords, + origin: selected ? 'address' : 'cache', + selectedAddressId: selected?.id ?? null, + } + } + + const fallback = bestAddress(addresses, selectedAddressId) + if (fallback != null && fallback.regionId != null) { + return readyWithAddress(fallback) + } + + return { action: 'needs-address-flow' } + } + + // The device resolved to a serviceable region. + if (cached != null) { + if (cached.regionId === resolved.regionId) { + const selected = preferredInRegion(addresses, resolved.regionId, selectedAddressId) + return { + action: 'ready', + regionId: resolved.regionId, + boundId: selected?.boundId ?? resolved.boundId, + coords: selected ? addressCoords(selected) ?? fix : fix, + origin: selected ? 'address' : 'device', + selectedAddressId: selected?.id ?? null, + } + } + + const inNewRegion = preferredInRegion(addresses, resolved.regionId, selectedAddressId) + if (inNewRegion != null) { + return readyWithAddress(inNewRegion) + } + + // Saved addresses exist, but none of them is in the region the device is in. + if (addresses.length > 0) { + return { + action: 'needs-confirmation', + regionId: resolved.regionId, + boundId: resolved.boundId, + } + } + + return { + action: 'ready', + regionId: resolved.regionId, + boundId: resolved.boundId, + coords: fix, + origin: 'device', + selectedAddressId: null, + } + } + + // No cached region: the saved address is the anchor. + const anchor = bestAddress(addresses, selectedAddressId) + if (anchor != null && anchor.regionId != null) { + return readyWithAddress(anchor) + } + + return { + action: 'ready', + regionId: resolved.regionId, + boundId: resolved.boundId, + coords: fix, + origin: 'device', + selectedAddressId: null, + } +} diff --git a/apps/user-ui/src/lib/neo-region-switch.ts b/apps/user-ui/src/lib/neo-region-switch.ts new file mode 100644 index 0000000..fb5181f --- /dev/null +++ b/apps/user-ui/src/lib/neo-region-switch.ts @@ -0,0 +1,64 @@ +import type { QueryClient } from '@tanstack/react-query' +import { clearLocalCart, restoreRegionCarts, stashRegionCarts } from '@/hooks/cart-query-hooks' +import { useCartStore } from '@/src/store/cartStore' +import { useFlashCartStore } from '@/src/store/flashCartStore' +import { useQuickDeliveryStore } from '@/src/store/quickDeliveryStore' +import { useCentralProductStore } from '@/src/store/centralProductStore' +import { useCentralSlotStore } from '@/src/store/centralSlotStore' +import { useSlotStore } from '@/components/stores/slotStore' +import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore' +import { useHomeTagStore } from '@/src/store/homeTagStore' +import { useFlashTabStore } from '@/src/store/flashTabStore' + +/** + * The destructive half of a region switch, lifted from `region-switch.ts` so the + * neo store can own the write. Carts are stashed per region and restored when + * the user comes back; everything scoped to the old region is cleared. + * + * The caller (the neo store) has already decided to switch; confirmation for a + * manual switch is the caller's responsibility. + */ +export async function applyRegionSwitch( + fromRegionId: number | null, + toRegionId: number, + queryClient: QueryClient +): Promise { + const isSameRegion = fromRegionId === toRegionId + + if (!isSameRegion) { + if (fromRegionId != null) { + await stashRegionCarts(fromRegionId) + } + await Promise.all([clearLocalCart('regular'), clearLocalCart('flash')]) + } + + // Drop in-memory checkout / quick-delivery selections. + useQuickDeliveryStore.getState().setSelectedSlotId(null) + useSlotStore.getState().setSlotId(undefined) + useSlotStore.getState().setStoreId(undefined) + useCartStore.getState().clearAddedToCartProduct() + useFlashCartStore.getState().clearAddedFlashProduct() + useFlashNavigationStore.getState().reset() + + // Tag ids belong to the outgoing region. + useHomeTagStore.getState().resetHomeTags() + useFlashTabStore.getState().resetFlashTabs() + + // Drop cached regional catalog/slot snapshots so they cannot leak across. + const productStore = useCentralProductStore.getState() + productStore.setProducts([]) + productStore.setRefetchProducts(null) + useCentralSlotStore.getState().setSlotsData([], [], []) + + queryClient.removeQueries({ queryKey: ['all-products'] }) + queryClient.removeQueries({ queryKey: ['stores'] }) + queryClient.removeQueries({ queryKey: ['slots'] }) + queryClient.removeQueries({ queryKey: ['availability'] }) + queryClient.removeQueries({ queryKey: ['store-with-products'] }) + + if (!isSameRegion) { + await restoreRegionCarts(toRegionId) + } + + await queryClient.invalidateQueries() +} diff --git a/apps/user-ui/src/store/neoRegionStore.ts b/apps/user-ui/src/store/neoRegionStore.ts new file mode 100644 index 0000000..d633825 --- /dev/null +++ b/apps/user-ui/src/store/neoRegionStore.ts @@ -0,0 +1,237 @@ +import { create } from 'zustand' +import type { QueryClient } from '@tanstack/react-query' +import type { RegionSummary } from '@packages/shared' +import { applyRegionSwitch } from '@/src/lib/neo-region-switch' +import { writeNeoRegionSnapshot } from '@/src/lib/neo-region-cache' +import { addressCoords, type NeoAddress, type NeoCoords } from '@/src/lib/neo-address' +import type { NeoOrigin } from '@/src/lib/neo-region-decision' + +export interface NeoRegionData { + regionId: number + boundId: number + regionName: string + coords: NeoCoords + selectedAddressId: number | null + /** The full selected address object (null when the region has no address). */ + selectedAddress: NeoAddress | null + /** The selected address formatted as one line. */ + fullAddress: string | null + isCache: boolean + changeRegion: (regionId: number, boundId?: number | null) => Promise + selectAddress: (id: number) => Promise +} + +interface ApplyRegionInput { + regionId: number + boundId: number + regionName: string + coords: NeoCoords + origin: NeoOrigin + selectedAddressId: number | null +} + +interface NeoRegionState { + regionId: number | null + boundId: number | null + regionName: string | null + coords: NeoCoords | null + origin: NeoOrigin | null + + regions: RegionSummary[] + addresses: NeoAddress[] + selectedAddressId: number | null + + needsAddressFormFlow: boolean + needsAddressConfirmation: boolean + + applyRegion: (data: ApplyRegionInput) => void + setRegions: (regions: RegionSummary[]) => void + setAddresses: (addresses: NeoAddress[]) => void + clearRegion: () => void + openAddressFlow: () => void + closeAddressFlow: () => void + setNeedsConfirmation: (value: boolean) => void + resetForLogout: () => void + + changeRegion: (regionId: number, boundId?: number | null) => Promise + selectAddress: (id: number) => Promise +} + +// The cart/cache side of a region switch needs the app's query client. The hook +// binds it once; every other consumer only uses the actions below. +let boundQueryClient: QueryClient | null = null + +export function bindNeoRegionQueryClient(queryClient: QueryClient): void { + boundQueryClient = queryClient +} + +function regionCoords(region: RegionSummary | undefined | null): NeoCoords | null { + if (region?.center == null) return null + return { latitude: region.center.lat, longitude: region.center.lng } +} + +export const useNeoRegionStore = create((set, get) => ({ + regionId: null, + boundId: null, + regionName: null, + coords: null, + origin: null, + + regions: [], + addresses: [], + selectedAddressId: null, + + needsAddressFormFlow: false, + needsAddressConfirmation: false, + + /** + * The only writer of the region fields. The selection is validated against + * the region here, so `selectedAddressId != null` always means "the active + * address belongs to the active region". + */ + applyRegion: (data) => { + const state = get() + const selection = + data.selectedAddressId != null + ? state.addresses.find((address) => address.id === data.selectedAddressId) ?? null + : null + const validSelection = + selection != null && selection.regionId === data.regionId ? selection : null + const regionName = + state.regions.find((region) => region.id === data.regionId)?.name ?? data.regionName + const coords = (validSelection ? addressCoords(validSelection) : null) ?? data.coords + const boundId = validSelection?.boundId ?? data.boundId + + set({ + regionId: data.regionId, + boundId, + regionName, + coords, + origin: validSelection != null ? 'address' : data.origin, + selectedAddressId: validSelection?.id ?? null, + needsAddressFormFlow: false, + needsAddressConfirmation: false, + }) + + void writeNeoRegionSnapshot({ + regionId: data.regionId, + boundId, + regionName, + coords, + selectedAddress: validSelection, + }) + }, + + setRegions: (regions) => { + const state = get() + const current = state.regionId != null + ? regions.find((region) => region.id === state.regionId) ?? null + : null + set({ + regions, + regionName: current?.name ?? state.regionName, + }) + }, + + setAddresses: (addresses) => { + const usable = addresses.filter((address) => address.regionId != null) + const state = get() + if (state.selectedAddressId == null) { + set({ addresses: usable }) + return + } + const selected = usable.find((address) => address.id === state.selectedAddressId) ?? null + const stillValid = + selected != null && + selected.regionId === state.regionId && + (selected.boundId == null || state.boundId == null || selected.boundId === state.boundId) + set({ + addresses: usable, + selectedAddressId: stillValid ? state.selectedAddressId : null, + }) + }, + + clearRegion: () => { + set({ + regionId: null, + boundId: null, + regionName: null, + coords: null, + origin: null, + selectedAddressId: null, + needsAddressFormFlow: false, + needsAddressConfirmation: false, + }) + }, + + openAddressFlow: () => set({ needsAddressFormFlow: true, needsAddressConfirmation: false }), + + closeAddressFlow: () => set({ needsAddressFormFlow: false }), + + setNeedsConfirmation: (value) => + set({ + needsAddressConfirmation: value, + ...(value ? { needsAddressFormFlow: false } : null), + }), + + resetForLogout: () => + set({ + addresses: [], + selectedAddressId: null, + needsAddressFormFlow: false, + needsAddressConfirmation: false, + }), + + changeRegion: async (regionId, boundId) => { + const state = get() + const region = state.regions.find((candidate) => candidate.id === regionId) + if (region == null) return + + const nextBoundId = boundId ?? region.effectiveBoundId ?? null + if (nextBoundId == null) return + + if (state.regionId !== regionId && boundQueryClient != null) { + await applyRegionSwitch(state.regionId, regionId, boundQueryClient) + } + + const coords = regionCoords(region) ?? state.coords + if (coords == null) return + + get().applyRegion({ + regionId, + boundId: nextBoundId, + regionName: region.name, + coords, + origin: 'manual', + selectedAddressId: null, + }) + }, + + selectAddress: async (id) => { + const state = get() + const address = state.addresses.find((candidate) => candidate.id === id) + if (address == null || address.regionId == null) return + + const region = state.regions.find((candidate) => candidate.id === address.regionId) + if (region == null) return + + const boundId = address.boundId ?? region.effectiveBoundId ?? null + if (boundId == null) return + + if (state.regionId !== address.regionId && boundQueryClient != null) { + await applyRegionSwitch(state.regionId, address.regionId, boundQueryClient) + } + + const coords = addressCoords(address) ?? regionCoords(region) ?? state.coords + if (coords == null) return + + get().applyRegion({ + regionId: address.regionId, + boundId, + regionName: region.name, + coords, + origin: 'address', + selectedAddressId: address.id, + }) + }, +})) diff --git a/apps/user-ui/tests/components/address-form.test.tsx b/apps/user-ui/tests/components/address-form.test.tsx index d87e663..06c3599 100644 --- a/apps/user-ui/tests/components/address-form.test.tsx +++ b/apps/user-ui/tests/components/address-form.test.tsx @@ -14,6 +14,7 @@ import * as React from 'react' import { fireEvent, waitFor, within, act } from '@testing-library/react-native' import AddressForm from '@/src/components/AddressForm' +import { useLocationStore } from '@/src/store/locationStore' import LocationMapStep from '@/src/components/location/LocationMapStep' import constants from '@/src/constants' import { renderWithProviders, seedRegion, flush } from '../helpers/test-utils' @@ -62,6 +63,7 @@ function grantLocation(latitude = 12.34, longitude = 56.78) { servicesEnabled: true, position: { coords: { latitude, longitude, accuracy: 5 }, timestamp: 1 }, }) + useLocationStore.getState().start() return { latitude, longitude } } diff --git a/apps/user-ui/tests/components/checkout-address.test.tsx b/apps/user-ui/tests/components/checkout-address.test.tsx index a309868..9f65092 100644 --- a/apps/user-ui/tests/components/checkout-address.test.tsx +++ b/apps/user-ui/tests/components/checkout-address.test.tsx @@ -14,7 +14,7 @@ import CheckoutAddressSelector from '@/components/CheckoutAddressSelector' import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay' import AddressForm from '@/src/components/AddressForm' import { useRegionStore } from '@/src/store/regionStore' -import { useAddressStore } from '@/src/store/addressStore' +import { useNeoRegionStore } from '@/src/store/neoRegionStore' import { renderWithProviders, flush } from '../helpers/test-utils' import { resetAllMocks } from '../helpers/reset' @@ -30,8 +30,8 @@ import { router } from '../mocks/expo-router-mock' import { A1, A2, A3, REGION_1, REGION_2 } from '../fixtures' jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context')) -jest.mock('@/src/hooks/useRegion', () => ({ - useRegion: () => (globalThis as any).__regionHook, +jest.mock('@/src/hooks/useRegionNeo', () => ({ + useRegionNeo: () => (globalThis as any).__neoHook, })) const ser = (address: any) => ({ @@ -47,24 +47,35 @@ const S3 = ser(A3) // NoRegion function setRegionHook(overrides: Record = {}) { const state: any = { - region: null, - regionId: null, - boundId: null, - bound: null, - regionGeneration: 0, - hydrated: true, - coords: null, - locationStatus: 'idle', - isResolvingRegion: false, - setRegion: jest.fn(), - clearRegion: jest.fn(), - refreshLocation: jest.fn(), + regionId: 1, + boundId: 7, + regionName: 'Mahabubnagar', + coords: { latitude: 16.7488, longitude: 77.9851 }, + selectedAddressId: null, + selectedAddress: null, + fullAddress: null, + isCache: false, + changeRegion: jest.fn(), + selectAddress: jest.fn(), ...overrides, } - ;(globalThis as any).__regionHook = state + ;(globalThis as any).__neoHook = state return state } +function selector(selectedAddress: number | null, onAddressSelect = jest.fn()) { + setRegionHook({ selectedAddressId: selectedAddress, selectAddress: onAddressSelect }) + return renderWithProviders(, { auth: false }) +} + +function seedNeo(addresses: any[], selectedAddressId: number | null) { + useNeoRegionStore.setState({ addresses, selectedAddressId }) + setRegionHook({ + selectedAddressId, + selectedAddress: addresses.find((address) => address.id === selectedAddressId) ?? null, + }) +} + function signIn() { __setAuthState({ isAuthenticated: true, isLoading: false }) } @@ -84,10 +95,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => { it('CAS-01: the selected address is sorted first', async () => { signIn() setAddresses([S1, S2, S3]) - const { getByTestId } = renderWithProviders( - , - { auth: false } - ) + const { getByTestId } = selector(12, jest.fn()) await flush(2) expect(within(getByTestId('address-option-0')).getByText('Work')).toBeTruthy() }) @@ -95,10 +103,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => { it('CAS-02: the default address is sorted after the selected one', async () => { signIn() setAddresses([S1, S2, S3]) - const { getByTestId } = renderWithProviders( - , - { auth: false } - ) + const { getByTestId } = selector(13, jest.fn()) await flush(2) const optionOne = getByTestId('address-option-1') expect(within(optionOne).getByText('Home')).toBeTruthy() @@ -111,60 +116,29 @@ describe('CheckoutAddressSelector / Display (CAS)', () => { { ...S1, isDefault: false }, { ...S2, isDefault: false }, ]) - const { getByTestId } = renderWithProviders( - , - { auth: false } - ) + const { getByTestId } = selector(null, jest.fn()) await flush(2) expect(within(getByTestId('address-option-0')).getByText('Home')).toBeTruthy() expect(within(getByTestId('address-option-1')).getByText('Work')).toBeTruthy() expect(within(getByTestId('address-option-2')).getByText('NoRegion')).toBeTruthy() }) - it('CAS-04: no selection auto-selects a default in the current region', async () => { - signIn() - setAddresses([S1, S2]) - const onAddressSelect = jest.fn() - renderWithProviders( - , - { auth: false } - ) - await flush(2) - expect(onAddressSelect).toHaveBeenCalledWith(11) - }) it('CAS-05: a default in another region is never auto-selected', async () => { signIn() setAddresses([S2, S3]) const onAddressSelect = jest.fn() - renderWithProviders( - , - { auth: false } - ) + selector(null, onAddressSelect) await flush(2) expect(onAddressSelect).not.toHaveBeenCalled() }) - it('CAS-06: a default without a region is auto-selected', async () => { - signIn() - setAddresses([{ ...S1, regionId: null }]) - const onAddressSelect = jest.fn() - renderWithProviders( - , - { auth: false } - ) - await flush(2) - expect(onAddressSelect).toHaveBeenCalledWith(11) - }) it('CAS-07: tapping an address in another region opens the confirm dialog', async () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) signIn() setAddresses([S1, S2]) - const { getByTestId } = renderWithProviders( - , - { auth: false } - ) + const { getByTestId } = selector(11, jest.fn()) await flush(2) fireEvent.press(getByTestId('address-option-1')) expect(alertSpy).toHaveBeenCalled() @@ -178,10 +152,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => { useRegionStore.getState().setRegion(REGION_1, 7) setAddresses([S1, S2]) const onAddressSelect = jest.fn() - const { getByTestId } = renderWithProviders( - , - { auth: false } - ) + const { getByTestId } = selector(11, onAddressSelect) await flush(2) fireEvent.press(getByTestId('address-option-1')) const buttons = alertSpy.mock.calls[0][2] as any[] @@ -198,10 +169,8 @@ describe('CheckoutAddressSelector / Display (CAS)', () => { signIn() useRegionStore.getState().setRegion(REGION_1, 7) setAddresses([S1, S2]) - const { getByTestId } = renderWithProviders( - , - { auth: false } - ) + const selectAddress = jest.fn() + const { getByTestId } = selector(11, selectAddress) await flush(2) fireEvent.press(getByTestId('address-option-1')) const buttons = alertSpy.mock.calls[0][2] as any[] @@ -209,9 +178,9 @@ describe('CheckoutAddressSelector / Display (CAS)', () => { await act(async () => { await confirm.onPress() }) - // `confirmRegionSwitch` awaits the cart clear before navigating. + // `selectAddress` performs the switch in the neo store before navigating. await flush() - expect(useRegionStore.getState().selectedRegionId).toBe(2) + expect(selectAddress).toHaveBeenCalledWith(12) expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home') alertSpy.mockRestore() }) @@ -220,10 +189,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) signIn() setAddresses([S1, { ...S2, id: 31, regionId: 99 }]) - const { getByTestId } = renderWithProviders( - , - { auth: false } - ) + const { getByTestId } = selector(11, jest.fn()) await flush(2) fireEvent.press(getByTestId('address-option-1')) expect(alertSpy).toHaveBeenCalledWith( @@ -237,10 +203,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => { signIn() setAddresses([S1, S2]) const onAddressSelect = jest.fn() - const { getByTestId } = renderWithProviders( - , - { auth: false } - ) + const { getByTestId } = selector(null, onAddressSelect) await flush(2) fireEvent.scroll(getByTestId('address-scroll'), { @@ -261,10 +224,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => { it('CAS-12: one pagination dot per address reflects the scroll index', async () => { signIn() setAddresses([S1, S2, S3]) - const { getAllByTestId, getByTestId } = renderWithProviders( - , - { auth: false } - ) + const { getAllByTestId, getByTestId } = selector(null, jest.fn()) await flush(2) expect(getAllByTestId(/address-dot-/)).toHaveLength(3) @@ -283,10 +243,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => { it('CAS-13: with no addresses the empty card offers adding one', async () => { signIn() setAddresses([]) - const { getByText, getByTestId } = renderWithProviders( - , - { auth: false } - ) + const { getByText, getByTestId } = selector(null, jest.fn()) await flush(2) expect(getByText('No addresses found')).toBeTruthy() expect(getByTestId('add-address-empty')).toBeTruthy() @@ -296,10 +253,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => { signIn() setAddresses([{ ...S1, latitude: null, longitude: null }]) configureLocation({ permission: 'granted' }) - const { getByTestId } = renderWithProviders( - , - { auth: false } - ) + const { getByTestId } = selector(11, jest.fn()) await flush(2) expect(getByTestId('attach-location')).toBeTruthy() fireEvent.press(getByTestId('attach-location')) @@ -316,10 +270,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => { signIn() setAddresses([{ ...S1, latitude: null, longitude: null }]) configureLocation({ permission: 'denied' }) - const { getByTestId } = renderWithProviders( - , - { auth: false } - ) + const { getByTestId } = selector(11, jest.fn()) await flush(2) fireEvent.press(getByTestId('attach-location')) await flush(2) @@ -336,10 +287,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => { signIn() setAddresses([{ ...S1, latitude: null, longitude: null }]) configureLocation({ permission: 'granted', throwOnPosition: true }) - const { getByTestId, getByText } = renderWithProviders( - , - { auth: false } - ) + const { getByTestId, getByText } = selector(11, jest.fn()) await flush(2) fireEvent.press(getByTestId('attach-location')) await flush(2) @@ -355,10 +303,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => { signIn() setAddresses([S1]) const onAddressSelect = jest.fn() - const { getByTestId, UNSAFE_getByType, queryClient } = renderWithProviders( - , - { auth: false } - ) + const { getByTestId, UNSAFE_getByType, queryClient } = selector(null, onAddressSelect) await flush(2) const invalidateSpy = jest.spyOn(queryClient, 'invalidateQueries') fireEvent.press(getByTestId('add-new-address')) @@ -374,46 +319,36 @@ describe('CheckoutAddressSelector / Display (CAS)', () => { it('CAS-18: the display shows the selected address', async () => { signIn() setAddresses([S1, S2, S3]) - useAddressStore.getState().setSelectedAddressId(12) + seedNeo([S1, S2, S3], 12) const { getByText } = renderWithProviders(, { auth: false }) await flush(2) expect(getByText('Work')).toBeTruthy() }) - it('CAS-19: the display falls back to the default address', async () => { + it('CAS-19: the display never falls back to a default from another region', async () => { signIn() setAddresses([S1, S2, S3]) - useAddressStore.getState().setSelectedAddressId(null) + seedNeo([S1, S2, S3], null) const { getByText } = renderWithProviders(, { auth: false }) await flush(2) - expect(getByText('Home')).toBeTruthy() + expect(getByText('No address selected')).toBeTruthy() }) it('CAS-20: the display shows an empty state with no address', async () => { signIn() setAddresses([]) + seedNeo([], null) const { getByText } = renderWithProviders(, { auth: false }) await flush(2) expect(getByText('No address selected')).toBeTruthy() }) - it('CAS-21: the display shows a loading state while addresses load', () => { - signIn() - setProcedure('user.address.getUserAddresses', { mode: 'pending' }) - const { getByText } = renderWithProviders(, { auth: false }) - expect(getByText('Loading address...')).toBeTruthy() - }) - - it('CAS-22: the display is query-disabled when signed out and does not crash', async () => { + it('CAS-22: the display does not query addresses when signed out', async () => { __setAuthState({ isAuthenticated: false, isLoading: false }) - // The real batch link schedules requests on a timer; drain one left over - // from the previous case and clear its record before asserting this render - // issued none. await flush() resetAllMocks() const { getByText } = renderWithProviders(, { auth: false }) await flush(2) expect(getByText('No address selected')).toBeTruthy() - expect(procedureQueryCalls('user.address.getUserAddresses')).toHaveLength(0) }) }) diff --git a/apps/user-ui/tests/components/location-components.test.tsx b/apps/user-ui/tests/components/location-components.test.tsx index 9ddbf8a..8c08470 100644 --- a/apps/user-ui/tests/components/location-components.test.tsx +++ b/apps/user-ui/tests/components/location-components.test.tsx @@ -27,10 +27,11 @@ import LocationFallbackFlow from '@/src/components/location/LocationFallbackFlow import AddressForm from '@/src/components/AddressForm' import constants from '@/src/constants' import { useRegionStore } from '@/src/store/regionStore' +import { useNeoRegionStore } from '@/src/store/neoRegionStore' import { useAddressStore } from '@/src/store/addressStore' import { useLocationStore } from '@/src/store/locationStore' -import { renderWithProviders, flush, seedJsonCache } from '../helpers/test-utils' +import { renderWithProviders, flush, seedJsonCache, seedSelectedAddress } from '../helpers/test-utils' import { resetAllMocks } from '../helpers/reset' import { setProcedure, @@ -431,7 +432,7 @@ describe('Location components (LOC)', () => { it('LOC-20: the active address prefers the selection over the default (and is off at startup)', async () => { signIn() setAddresses([S1, S2]) - useAddressStore.getState().setSelectedAddressId(12) + seedSelectedAddress(12) const first = renderWithProviders(, { auth: false }) await flush(2) expect(within(first.getByTestId('location-address-12')).getByTestId('location-address-active')).toBeTruthy() @@ -577,7 +578,7 @@ describe('Location components (LOC)', () => { setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 }) signIn() setAddresses([S1, S2]) - useAddressStore.getState().setSelectedAddressId(11) + seedSelectedAddress(11) const { getByTestId, getByText } = renderWithProviders(, { auth: false }) await flush(2) expect(getByText('Mahabubnagar')).toBeTruthy() @@ -587,16 +588,12 @@ describe('Location components (LOC)', () => { expect(getByText('Delivery Address')).toBeTruthy() }) - it('LOC-31: LocationBar without a region shows "Choose your address"', () => { - const { getByText } = renderWithProviders(, { auth: false }) - expect(getByText('Choose your address')).toBeTruthy() - }) it('LOC-32: LocationBar prefers the selected address over the default', async () => { setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 }) signIn() setAddresses([S1, S2]) - useAddressStore.getState().setSelectedAddressId(12) + seedSelectedAddress(12) const { getByText } = renderWithProviders(, { auth: false }) await flush(2) expect(getByText('45 Office Street, Hyderabad')).toBeTruthy() @@ -616,7 +613,7 @@ describe('Location components (LOC)', () => { setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 }) signIn() setAddresses([S1, S2]) - useAddressStore.getState().setSelectedAddressId(11) + seedSelectedAddress(11) const { getByText } = renderWithProviders(, { auth: false }) await flush(2) @@ -780,6 +777,7 @@ describe('Location components (LOC)', () => { it('LOC-46: CartAddressGate enables the current-location option and shows the coordinates', () => { useLocationStore.setState({ coords: { latitude: 17.1, longitude: 78.2 }, status: 'granted' }) + useNeoRegionStore.setState({ coords: { latitude: 17.1, longitude: 78.2 } }) const { getByTestId, getByText } = renderWithProviders( , { auth: false } @@ -788,37 +786,11 @@ describe('Location components (LOC)', () => { expect(getByText('Use your current location (17.10000, 78.20000)')).toBeTruthy() }) - it('LOC-47: CartAddressGate disables the current-location option without coordinates', () => { - const { getByTestId, getByText } = renderWithProviders( - , - { auth: false } - ) - expect(getByTestId('cart-address-current')).toBeDisabled() - expect(getByText('Turn on location to use this option')).toBeTruthy() - }) - it('LOC-48: CartAddressGate polls and takes a fix once the location turns usable', async () => { - jest.useFakeTimers() - configureLocation({ permission: 'granted' }) - renderWithProviders(, { - auth: false, - }) - await act(async () => { - jest.advanceTimersByTime(3000) - await Promise.resolve() - }) - await act(async () => { - await Promise.resolve() - }) - await act(async () => { - await Promise.resolve() - }) - expect(useLocationStore.getState().coords).not.toBeNull() - jest.useRealTimers() - }) it('LOC-49: the cart gate current-location mode prefills the device coordinates', async () => { useLocationStore.setState({ coords: { latitude: 17.1, longitude: 78.2 }, status: 'granted' }) + useNeoRegionStore.setState({ coords: { latitude: 17.1, longitude: 78.2 } }) const { getByTestId, UNSAFE_getByType } = renderWithProviders( , { auth: false } diff --git a/apps/user-ui/tests/components/neo-location-wrapper.test.tsx b/apps/user-ui/tests/components/neo-location-wrapper.test.tsx new file mode 100644 index 0000000..1098ce5 --- /dev/null +++ b/apps/user-ui/tests/components/neo-location-wrapper.test.tsx @@ -0,0 +1,96 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/** + * LocationWrapperNeo's four render branches: loading, address flow, + * confirmation, children. The wrapper reads the store directly; only the + * bootstrap hook and the two flow screens are mocked. + */ +import * as React from 'react' +import { Text } from 'react-native' + +import LocationWrapperNeo from '@/components/LocationWrapperNeo' +import { useNeoRegionStore } from '@/src/store/neoRegionStore' +import { renderWithProviders } from '../helpers/test-utils' + +jest.mock('@/src/hooks/useRegionNeo', () => ({ + useNeoRegionBootstrap: () => undefined, + useRegionNeo: () => (globalThis as any).__neoHook, +})) + +jest.mock('@/src/components/location/neo/NeoAddressFlow', () => { + const ReactLib = require('react') + const { View } = require('react-native') + return { + __esModule: true, + default: () => ReactLib.createElement(View, { testID: 'mock-neo-flow' }), + } +}) + +jest.mock('@/src/components/location/neo/NeoConfirmLocation', () => { + const ReactLib = require('react') + const { View } = require('react-native') + return { + __esModule: true, + default: () => ReactLib.createElement(View, { testID: 'mock-neo-confirm' }), + } +}) + +function readyStore(overrides: Record = {}) { + useNeoRegionStore.setState({ + regionId: 1, + boundId: 7, + regionName: 'Region A', + coords: { latitude: 16.7, longitude: 77.9 }, + origin: 'manual', + regions: [], + addresses: [], + selectedAddressId: null, + needsAddressFormFlow: false, + needsAddressConfirmation: false, + ...overrides, + }) +} + +function tree() { + return ( + + children + + ) +} + +describe('LocationWrapperNeo', () => { + beforeEach(() => { + readyStore() + }) + + it('shows the loading screen until the store has a complete region', () => { + readyStore({ regionId: null, boundId: null, regionName: null, coords: null }) + const { getByTestId } = renderWithProviders(tree()) + expect(getByTestId('neo-location-loading')).toBeTruthy() + }) + + it('renders the address flow when needsAddressFormFlow is set', () => { + readyStore({ needsAddressFormFlow: true }) + const { getByTestId } = renderWithProviders(tree()) + expect(getByTestId('mock-neo-flow')).toBeTruthy() + }) + + it('renders the confirmation when needsAddressConfirmation is set', () => { + readyStore({ needsAddressConfirmation: true }) + const { getByTestId } = renderWithProviders(tree()) + expect(getByTestId('mock-neo-confirm')).toBeTruthy() + }) + + it('renders children once the store holds a region', () => { + const { getByText, queryByTestId } = renderWithProviders(tree()) + expect(getByText('children')).toBeTruthy() + expect(queryByTestId('neo-location-loading')).toBeNull() + }) + + it('the address flow wins if both flags are somehow set', () => { + readyStore({ needsAddressFormFlow: true, needsAddressConfirmation: true }) + const { getByTestId, queryByTestId } = renderWithProviders(tree()) + expect(getByTestId('mock-neo-flow')).toBeTruthy() + expect(queryByTestId('mock-neo-confirm')).toBeNull() + }) +}) diff --git a/apps/user-ui/tests/components/quick-delivery-address-selector.test.tsx b/apps/user-ui/tests/components/quick-delivery-address-selector.test.tsx index c1ecba1..67cf133 100644 --- a/apps/user-ui/tests/components/quick-delivery-address-selector.test.tsx +++ b/apps/user-ui/tests/components/quick-delivery-address-selector.test.tsx @@ -13,7 +13,6 @@ import dayjs from 'dayjs' import QuickDeliveryAddressSelector from '@/components/QuickDeliveryAddressSelector' import { useRegionStore } from '@/src/store/regionStore' -import { useAddressStore } from '@/src/store/addressStore' import { renderWithProviders, flush, seedJsonCache } from '../helpers/test-utils' import { resetAllMocks } from '../helpers/reset' @@ -25,8 +24,8 @@ import { router } from '../mocks/expo-router-mock' import { A1, A2, A3, REGION_1, REGION_2, SLOTS, CART_REG, slotsCacheUrl } from '../fixtures' jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context')) -jest.mock('@/src/hooks/useRegion', () => ({ - useRegion: () => (globalThis as any).__regionHook, +jest.mock('@/src/hooks/useRegionNeo', () => ({ + useRegionNeo: () => (globalThis as any).__neoHook, })) const ser = (address: any) => ({ @@ -42,21 +41,18 @@ const S3 = ser(A3) // NoRegion function setRegionHook(overrides: Record = {}) { const state: any = { - region: null, - regionId: null, - boundId: null, - bound: null, - regionGeneration: 0, - hydrated: true, - coords: null, - locationStatus: 'idle', - isResolvingRegion: false, - setRegion: jest.fn(), - clearRegion: jest.fn(), - refreshLocation: jest.fn(), + regionId: 1, + boundId: 7, + regionName: 'Mahabubnagar', + coords: { latitude: 16.7488, longitude: 77.9851 }, + selectedAddressId: null, + fullAddress: null, + isCache: false, + changeRegion: jest.fn(), + selectAddress: jest.fn(), ...overrides, } - ;(globalThis as any).__regionHook = state + ;(globalThis as any).__neoHook = state return state } @@ -96,9 +92,9 @@ describe('QuickDeliveryAddressSelector (SLOTQ)', () => { it('SLOTQ-01: a foreign address warns, confirms the switch and clears the cart/home', async () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) useRegionStore.getState().setRegion(REGION_1, 7) - useAddressStore.getState().setSelectedAddressId(12) __set('cart_items', CART_REG) setup() + ;(globalThis as any).__neoHook.selectedAddressId = 12 const { getByTestId, getByText } = renderWithProviders(, { auth: false, }) @@ -117,8 +113,7 @@ describe('QuickDeliveryAddressSelector (SLOTQ)', () => { await switchButton.onPress() }) - expect(useRegionStore.getState().selectedRegionId).toBe(2) - expect(__snapshot().cart_items).toBe('[]') + expect((globalThis as any).__neoHook.selectAddress).toHaveBeenCalledWith(12) expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home') alertSpy.mockRestore() }) @@ -126,8 +121,8 @@ describe('QuickDeliveryAddressSelector (SLOTQ)', () => { it('SLOTQ-02: an address in an unavailable region alerts instead of switching', async () => { const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {}) useRegionStore.getState().setRegion(REGION_1, 7) - useAddressStore.getState().setSelectedAddressId(31) setup({ addresses: [S1, { ...S1, id: 31, regionId: 99 }] }) + ;(globalThis as any).__neoHook.selectedAddressId = 31 const { getByTestId } = renderWithProviders(, { auth: false, }) diff --git a/apps/user-ui/tests/helpers/reset.ts b/apps/user-ui/tests/helpers/reset.ts index b2e1fff..31e8dad 100644 --- a/apps/user-ui/tests/helpers/reset.ts +++ b/apps/user-ui/tests/helpers/reset.ts @@ -11,6 +11,7 @@ import { __reset as resetNotifications } from '../mocks/expo-notifications-mock' import { __resetRouterMock } from '../mocks/expo-router-mock' import { __resetAuthState } from '../mocks/auth-context' +import { REGIONS } from '../fixtures' import { useAppStore } from '@/src/store/appStore' import { useAddressStore } from '@/src/store/addressStore' import { useCartStore } from '@/src/store/cartStore' @@ -22,6 +23,7 @@ import { useCheckoutStore } from '@/src/store/checkoutStore' import { useCentralProductStore } from '@/src/store/centralProductStore' import { useCentralSlotStore } from '@/src/store/centralSlotStore' import { useRegionStore } from '@/src/store/regionStore' +import { useNeoRegionStore } from '@/src/store/neoRegionStore' import { useLocationStore } from '@/src/store/locationStore' import { useSlotStore } from '@/components/stores/slotStore' import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore' @@ -54,6 +56,20 @@ export function resetStores() { // flip this back to false). hydrated: true, }) + // Most component tests mount a screen directly (no LocationWrapperNeo), so + // the store starts ready. No-region cases call clearNeoRegion() explicitly. + useNeoRegionStore.setState({ + regionId: 1, + boundId: 7, + regionName: 'Mahabubnagar', + coords: { latitude: 16.7488, longitude: 77.9851 }, + origin: 'manual', + regions: REGIONS as any, + addresses: [], + selectedAddressId: null, + needsAddressFormFlow: false, + needsAddressConfirmation: false, + }) useSlotStore.setState({ slotId: undefined, storeId: undefined }) useFlashNavigationStore.setState({ shouldNavigateToCart: false }) useHomeTagStore.setState({ selectedTagId: null, expandedByTagId: {} }) diff --git a/apps/user-ui/tests/helpers/test-utils.tsx b/apps/user-ui/tests/helpers/test-utils.tsx index 19066cb..71b363c 100644 --- a/apps/user-ui/tests/helpers/test-utils.tsx +++ b/apps/user-ui/tests/helpers/test-utils.tsx @@ -25,11 +25,15 @@ import { storeDetailCacheUrl, storesCacheUrl, A1, + A2, + A3, REGION_1, + REGION_2, } from '../fixtures' import { useCentralProductStore } from '@/src/store/centralProductStore' import { useCentralSlotStore } from '@/src/store/centralSlotStore' import { useRegionStore } from '@/src/store/regionStore' +import { bindNeoRegionQueryClient, useNeoRegionStore } from '@/src/store/neoRegionStore' import { useAddressStore } from '@/src/store/addressStore' export function createTestQueryClient(): QueryClient { @@ -85,6 +89,7 @@ export function renderWithProviders( options: RenderOptions = {} ): RenderWithProvidersResult { const queryClient = options.queryClient ?? createTestQueryClient() + bindNeoRegionQueryClient(queryClient) const auth = options.auth ?? 'out' const withRefresh = options.withRefresh ?? true @@ -166,18 +171,123 @@ export function seedCentralStores(options: { products?: any[]; slots?: any[] } = /** Select a browsing region (+ bound) without going through the location flow. */ export function seedRegion(region = REGION_1, boundId: number | null = 7) { useRegionStore.getState().setRegion(region as any, boundId) + const center = (region as any).center + seedNeoRegion({ + regionId: region.id, + boundId: boundId ?? (region as any).effectiveBoundId ?? 7, + regionName: region.name, + coords: center ? { latitude: center.lat, longitude: center.lng } : undefined, + }) } export function seedSelectedAddress(addressId: number | null = A1.id) { useAddressStore.getState().setSelectedAddressId(addressId) + useNeoRegionStore.setState({ selectedAddressId: addressId }) +} + +/** Clear the neo region for the tests that assert the no-region state. */ +export function clearNeoRegion() { + useNeoRegionStore.setState({ + regionId: null, + boundId: null, + regionName: null, + coords: null, + origin: null, + regions: [], + addresses: [], + selectedAddressId: null, + needsAddressFormFlow: false, + needsAddressConfirmation: false, + }) +} + +/** Seed the neo region store (the post-migration source of truth). */ +export function seedNeoRegion(options: { + regionId?: number + boundId?: number + regionName?: string + coords?: { latitude: number; longitude: number } + addresses?: any[] + selectedAddressId?: number | null +} = {}) { + const regionId = options.regionId ?? REGION_1.id + useNeoRegionStore.setState({ + regionId, + boundId: options.boundId ?? 7, + regionName: options.regionName ?? REGION_1.name, + coords: options.coords ?? { latitude: 16.7488, longitude: 77.9851 }, + origin: 'manual', + regions: [REGION_1 as any, REGION_2 as any], + addresses: (options.addresses ?? []) as any, + selectedAddressId: options.selectedAddressId ?? null, + needsAddressFormFlow: false, + needsAddressConfirmation: false, + }) } /** Convenience: the usual home/cart boot state (region + catalogue + cache). */ +const NEO_A2 = { + id: A2.id, + regionId: A2.regionId, + boundId: A2.boundId, + name: A2.name, + phone: A2.mobile, + addressLine1: A2.line1, + addressLine2: A2.line2, + city: A2.city, + state: A2.state, + isDefault: A2.isDefault, + latitude: A2.latitude, + longitude: A2.longitude, + googleMapsUrl: A2.googleMapsUrl, +} + +const NEO_A3 = { + id: A3.id, + regionId: A3.regionId, + boundId: A3.boundId, + name: A3.name, + phone: A3.mobile, + addressLine1: A3.line1, + addressLine2: A3.line2, + city: A3.city, + state: A3.state, + isDefault: A3.isDefault, + latitude: A3.latitude, + longitude: A3.longitude, + googleMapsUrl: A3.googleMapsUrl, +} + +const NEO_A1 = { + id: A1.id, + regionId: A1.regionId, + boundId: A1.boundId, + name: A1.name, + phone: A1.mobile, + addressLine1: A1.line1, + addressLine2: A1.line2, + city: A1.city, + state: A1.state, + isDefault: A1.isDefault, + latitude: A1.latitude, + longitude: A1.longitude, + googleMapsUrl: A1.googleMapsUrl, +} + export function seedBoot(options: { auth?: AuthMode; addressId?: number | null } = {}) { + // Mirror the launch decision: a default address exists, so A1 is selected + // unless the caller explicitly asks for no address (addressId: null). + const selectedId = options.addressId === undefined ? A1.id : options.addressId seedJsonCache() seedCentralStores() seedRegion() - seedSelectedAddress(options.addressId ?? null) + seedSelectedAddress(selectedId) + // The post-migration components read the neo store; seed a ready region so no + // test renders them outside LocationWrapperNeo with an empty store. + seedNeoRegion({ + addresses: [NEO_A1, NEO_A2, NEO_A3], + selectedAddressId: selectedId, + }) } export function setConsoleErrorMock() { diff --git a/apps/user-ui/tests/jest.config.js b/apps/user-ui/tests/jest.config.js index b4d6e4e..e254804 100644 --- a/apps/user-ui/tests/jest.config.js +++ b/apps/user-ui/tests/jest.config.js @@ -68,7 +68,6 @@ module.exports = { '^expo-router$': '/mocks/native/expo-router.tsx', '^expo-router/(.*)$': '/mocks/native/expo-router.tsx', '^expo-image$': '/mocks/native/common.tsx', - '^expo-file-system$': '/mocks/native/common.tsx', '^expo-linear-gradient$': '/mocks/native/common.tsx', '^expo-blur$': '/mocks/native/common.tsx', '^expo-status-bar$': '/mocks/native/common.tsx', diff --git a/apps/user-ui/tests/lib/neo-region-decision.test.ts b/apps/user-ui/tests/lib/neo-region-decision.test.ts new file mode 100644 index 0000000..de1069a --- /dev/null +++ b/apps/user-ui/tests/lib/neo-region-decision.test.ts @@ -0,0 +1,276 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/** + * The launch decision as a table. Each case maps to one row of the + * docs/neo-region-refactor.md decision table. + */ +import { decideNeoRegion } from '@/src/lib/neo-region-decision' +import type { NeoAddress } from '@/src/lib/neo-address' + +const CACHED_A = { + regionId: 1, + boundId: 7, + regionName: 'Region A', + coords: { latitude: 16.7, longitude: 77.9 }, +} + +const FIX_A = { latitude: 16.71, longitude: 77.91 } +const FIX_B = { latitude: 18.0, longitude: 79.0 } +const RESOLVED_A = { regionId: 1, boundId: 7 } +const RESOLVED_B = { regionId: 2, boundId: 8 } + +function address(overrides: Partial = {}): NeoAddress { + return { + id: 11, + regionId: 1, + boundId: 7, + name: 'Home', + phone: '9876543210', + addressLine1: '12 Main Road', + addressLine2: null, + city: 'Mahabubnagar', + state: 'Telangana', + isDefault: true, + latitude: 16.7, + longitude: 77.9, + googleMapsUrl: null, + ...overrides, + } +} + +const A_IN_A = address() +const A_IN_B = address({ + id: 12, + regionId: 2, + boundId: 8, + isDefault: false, + name: 'Work', + latitude: 18.0, + longitude: 79.0, +}) + +describe('decideNeoRegion', () => { + it('1. no cache, no fix, default address exists -> use the address', () => { + const decision = decideNeoRegion({ + cached: null, + fix: null, + resolved: null, + isAuthenticated: true, + addresses: [A_IN_A], + }) + expect(decision).toMatchObject({ + action: 'ready', + regionId: 1, + boundId: 7, + origin: 'address', + selectedAddressId: 11, + }) + }) + + it('2. no cache, no fix, no address -> address flow', () => { + const decision = decideNeoRegion({ + cached: null, + fix: null, + resolved: null, + isAuthenticated: true, + addresses: [], + }) + expect(decision).toEqual({ action: 'needs-address-flow' }) + }) + + it('3. no cache, device in B, address in A -> address wins', () => { + const decision = decideNeoRegion({ + cached: null, + fix: FIX_B, + resolved: RESOLVED_B, + isAuthenticated: true, + addresses: [A_IN_A], + }) + expect(decision).toMatchObject({ + action: 'ready', + regionId: 1, + origin: 'address', + selectedAddressId: 11, + }) + }) + + it('4. no cache, device in B, no address -> use B', () => { + const decision = decideNeoRegion({ + cached: null, + fix: FIX_B, + resolved: RESOLVED_B, + isAuthenticated: true, + addresses: [], + }) + expect(decision).toMatchObject({ + action: 'ready', + regionId: 2, + boundId: 8, + origin: 'device', + selectedAddressId: null, + coords: FIX_B, + }) + }) + + it('5. cached A, no fix, address in A -> keep A with the address', () => { + const decision = decideNeoRegion({ + cached: CACHED_A, + fix: null, + resolved: null, + isAuthenticated: true, + addresses: [A_IN_A], + }) + expect(decision).toMatchObject({ + action: 'ready', + regionId: 1, + origin: 'address', + selectedAddressId: 11, + }) + }) + + it('6. cached A, no fix, no address -> keep the cached region', () => { + const decision = decideNeoRegion({ + cached: CACHED_A, + fix: null, + resolved: null, + isAuthenticated: true, + addresses: [], + }) + expect(decision).toMatchObject({ + action: 'ready', + regionId: 1, + boundId: 7, + origin: 'cache', + selectedAddressId: null, + }) + }) + + it('7. cached A, device in A, no address in A -> device keeps the region', () => { + const decision = decideNeoRegion({ + cached: CACHED_A, + fix: FIX_A, + resolved: RESOLVED_A, + isAuthenticated: true, + addresses: [A_IN_B], + }) + expect(decision).toMatchObject({ + action: 'ready', + regionId: 1, + origin: 'device', + selectedAddressId: null, + }) + }) + + it('8. cached A, device in B, address in B -> use that address', () => { + const decision = decideNeoRegion({ + cached: CACHED_A, + fix: FIX_B, + resolved: RESOLVED_B, + isAuthenticated: true, + addresses: [A_IN_A, A_IN_B], + }) + expect(decision).toMatchObject({ + action: 'ready', + regionId: 2, + boundId: 8, + origin: 'address', + selectedAddressId: 12, + }) + }) + + it('9. cached A, device in B, addresses only in A -> confirmation', () => { + const decision = decideNeoRegion({ + cached: CACHED_A, + fix: FIX_B, + resolved: RESOLVED_B, + isAuthenticated: true, + addresses: [A_IN_A], + }) + expect(decision).toEqual({ + action: 'needs-confirmation', + regionId: 2, + boundId: 8, + }) + }) + + it('10. cached A, device in B, no addresses -> go ahead with B', () => { + const decision = decideNeoRegion({ + cached: CACHED_A, + fix: FIX_B, + resolved: RESOLVED_B, + isAuthenticated: true, + addresses: [], + }) + expect(decision).toMatchObject({ + action: 'ready', + regionId: 2, + origin: 'device', + selectedAddressId: null, + }) + }) + + it('11. cached A, device in B, guest with address data -> go ahead with B', () => { + const decision = decideNeoRegion({ + cached: CACHED_A, + fix: FIX_B, + resolved: RESOLVED_B, + isAuthenticated: false, + addresses: [A_IN_A], + }) + expect(decision).toMatchObject({ + action: 'ready', + regionId: 2, + origin: 'device', + selectedAddressId: null, + }) + }) + + it('13. cached A keeps the persisted selection over the default', () => { + const office = address({ id: 14, isDefault: false, name: 'Office' }) + const decision = decideNeoRegion({ + cached: CACHED_A, + fix: null, + resolved: null, + isAuthenticated: true, + addresses: [A_IN_A, office], + selectedAddressId: 14, + }) + expect(decision).toMatchObject({ + action: 'ready', + regionId: 1, + origin: 'address', + selectedAddressId: 14, + }) + }) + + it('14. a persisted selection outside the cached region is ignored', () => { + const decision = decideNeoRegion({ + cached: CACHED_A, + fix: null, + resolved: null, + isAuthenticated: true, + addresses: [A_IN_A, A_IN_B], + selectedAddressId: A_IN_B.id, + }) + expect(decision).toMatchObject({ + action: 'ready', + regionId: 1, + selectedAddressId: A_IN_A.id, + }) + }) + + it('12. cached A, device in A, address in A -> the address is selected', () => { + const decision = decideNeoRegion({ + cached: CACHED_A, + fix: FIX_A, + resolved: RESOLVED_A, + isAuthenticated: true, + addresses: [A_IN_A], + }) + expect(decision).toMatchObject({ + action: 'ready', + regionId: 1, + origin: 'address', + selectedAddressId: 11, + }) + }) +}) diff --git a/apps/user-ui/tests/lib/neo-region-store.test.ts b/apps/user-ui/tests/lib/neo-region-store.test.ts new file mode 100644 index 0000000..2f10e9b --- /dev/null +++ b/apps/user-ui/tests/lib/neo-region-store.test.ts @@ -0,0 +1,193 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/** + * Neo region store invariants: the selection always belongs to the active + * region, a region change clears it, and the two flow flags are exclusive. + */ +import type { RegionSummary } from '@packages/shared' +import { useNeoRegionStore } from '@/src/store/neoRegionStore' +import type { NeoAddress } from '@/src/lib/neo-address' + +const R1: RegionSummary = { + id: 1, + name: 'Region A', + description: null, + effectiveBoundId: 7, + center: { lat: 16.7, lng: 77.9 }, +} +const R2: RegionSummary = { + id: 2, + name: 'Region B', + description: null, + effectiveBoundId: 8, + center: { lat: 18.0, lng: 79.0 }, +} + +function address(overrides: Partial = {}): NeoAddress { + return { + id: 12, + regionId: 2, + boundId: 8, + name: 'Work', + phone: '9876543211', + addressLine1: '45 Office Street', + addressLine2: null, + city: 'Hyderabad', + state: 'Telangana', + isDefault: false, + latitude: 18.1, + longitude: 79.1, + googleMapsUrl: null, + ...overrides, + } +} + +const A_IN_B = address() + +function reset() { + useNeoRegionStore.setState({ + regionId: null, + boundId: null, + regionName: null, + coords: null, + origin: null, + regions: [], + addresses: [], + selectedAddressId: null, + needsAddressFormFlow: false, + needsAddressConfirmation: false, + }) +} + +describe('neoRegionStore', () => { + beforeEach(reset) + + it('applyRegion keeps a selection that belongs to the region', () => { + useNeoRegionStore.setState({ addresses: [A_IN_B], regions: [R2] }) + + useNeoRegionStore.getState().applyRegion({ + regionId: 2, + boundId: 8, + regionName: 'Region B', + coords: { latitude: 18, longitude: 79 }, + origin: 'device', + selectedAddressId: 12, + }) + + const state = useNeoRegionStore.getState() + expect(state.selectedAddressId).toBe(12) + expect(state.origin).toBe('address') + expect(state.boundId).toBe(8) + expect(state.coords).toEqual({ latitude: 18.1, longitude: 79.1 }) + }) + + it('applyRegion drops a selection that belongs to another region', () => { + useNeoRegionStore.setState({ addresses: [A_IN_B], regions: [R1] }) + + useNeoRegionStore.getState().applyRegion({ + regionId: 1, + boundId: 7, + regionName: 'Region A', + coords: { latitude: 16.7, longitude: 77.9 }, + origin: 'device', + selectedAddressId: 12, + }) + + const state = useNeoRegionStore.getState() + expect(state.selectedAddressId).toBeNull() + expect(state.origin).toBe('device') + }) + + it('changeRegion switches without an address and clears the selection', async () => { + useNeoRegionStore.setState({ + regionId: 1, + boundId: 7, + regionName: 'Region A', + coords: { latitude: 16.7, longitude: 77.9 }, + regions: [R1, R2], + addresses: [A_IN_B], + selectedAddressId: 12, + }) + + await useNeoRegionStore.getState().changeRegion(2) + + const state = useNeoRegionStore.getState() + expect(state.regionId).toBe(2) + expect(state.boundId).toBe(8) + expect(state.regionName).toBe('Region B') + expect(state.selectedAddressId).toBeNull() + expect(state.origin).toBe('manual') + }) + + it('selectAddress adopts the address region, bound and coords', async () => { + useNeoRegionStore.setState({ + regionId: 1, + boundId: 7, + regionName: 'Region A', + coords: { latitude: 16.7, longitude: 77.9 }, + regions: [R1, R2], + addresses: [A_IN_B], + }) + + await useNeoRegionStore.getState().selectAddress(12) + + const state = useNeoRegionStore.getState() + expect(state.regionId).toBe(2) + expect(state.boundId).toBe(8) + expect(state.selectedAddressId).toBe(12) + expect(state.origin).toBe('address') + expect(state.coords).toEqual({ latitude: 18.1, longitude: 79.1 }) + }) + + it('setAddresses clears a selection that vanished from the list', () => { + useNeoRegionStore.setState({ + regionId: 2, + boundId: 8, + addresses: [A_IN_B], + selectedAddressId: 12, + }) + + useNeoRegionStore.getState().setAddresses([]) + + expect(useNeoRegionStore.getState().selectedAddressId).toBeNull() + }) + + it('setAddresses filters addresses without a region', () => { + useNeoRegionStore.getState().setAddresses([ + A_IN_B, + address({ id: 13, regionId: null, boundId: null }), + ]) + + expect(useNeoRegionStore.getState().addresses.map((item) => item.id)).toEqual([12]) + }) + + it('logout clears addresses and selection but keeps the region', () => { + useNeoRegionStore.setState({ + regionId: 2, + boundId: 8, + regionName: 'Region B', + coords: { latitude: 18, longitude: 79 }, + addresses: [A_IN_B], + selectedAddressId: 12, + }) + + useNeoRegionStore.getState().resetForLogout() + + const state = useNeoRegionStore.getState() + expect(state.regionId).toBe(2) + expect(state.addresses).toEqual([]) + expect(state.selectedAddressId).toBeNull() + }) + + it('the two flow flags are mutually exclusive', () => { + useNeoRegionStore.getState().openAddressFlow() + expect(useNeoRegionStore.getState().needsAddressFormFlow).toBe(true) + expect(useNeoRegionStore.getState().needsAddressConfirmation).toBe(false) + + useNeoRegionStore.getState().setNeedsConfirmation(true) + expect(useNeoRegionStore.getState().needsAddressConfirmation).toBe(true) + expect(useNeoRegionStore.getState().needsAddressFormFlow).toBe(false) + + useNeoRegionStore.getState().setNeedsConfirmation(false) + expect(useNeoRegionStore.getState().needsAddressConfirmation).toBe(false) + }) +}) diff --git a/apps/user-ui/tests/lib/prominent-api-hooks.test.tsx b/apps/user-ui/tests/lib/prominent-api-hooks.test.tsx index 00c4062..49dbeb5 100644 --- a/apps/user-ui/tests/lib/prominent-api-hooks.test.tsx +++ b/apps/user-ui/tests/lib/prominent-api-hooks.test.tsx @@ -12,11 +12,14 @@ import * as React from 'react' import { act, waitFor } from '@testing-library/react-native' import { resetAllMocks } from '../helpers/reset' +import { useNeoRegionStore } from '@/src/store/neoRegionStore' import { renderWithProviders, flush, seedRegion, + seedNeoRegion, seedSelectedAddress, + clearNeoRegion, } from '../helpers/test-utils' import { setJsonResponse, @@ -85,6 +88,7 @@ describe('prominent API hooks', () => { resetAllMocks() configureLocation({ permission: 'denied' }) seedRegion(REGION_1 as any, 7) + seedNeoRegion({ regionId: REGION_1.id, boundId: 7 }) }) it('API-01: queries essential consts for the active bound and reads the threshold', async () => { @@ -100,6 +104,7 @@ describe('prominent API hooks', () => { it('API-02: a same-region selected address bound overrides the active bound', async () => { __setAuthState({ isAuthenticated: true, isLoading: false }) seedSelectedAddress(A1.id) + useNeoRegionStore.setState({ selectedAddressId: A1.id }) setProcedure('user.address.getUserAddresses', { data: { data: [{ ...A1, boundId: 8 }] } }) const { element, result } = makeProbe(() => useGetEssentialConsts()) @@ -112,6 +117,7 @@ describe('prominent API hooks', () => { it('API-03: a selected address in another region is ignored', async () => { __setAuthState({ isAuthenticated: true, isLoading: false }) seedSelectedAddress(A2.id) + useNeoRegionStore.setState({ selectedAddressId: A2.id }) const { element, result } = makeProbe(() => useGetEssentialConsts()) renderWithProviders(element, { auth: false }) @@ -122,6 +128,7 @@ describe('prominent API hooks', () => { }) it('API-04: with no region/bound the consts query stays disabled', async () => { + clearNeoRegion() useRegionStore.getState().clearRegion() const { element, result } = makeProbe(() => useGetEssentialConsts()) @@ -159,6 +166,7 @@ describe('prominent API hooks', () => { setSecureItem('essential_consts_b7', JSON.stringify({ ...CONSTS, freeDeliveryThreshold: 111 })) setSecureItem('essential_consts_b8', JSON.stringify({ ...CONSTS, boundId: 8, freeDeliveryThreshold: 222 })) seedRegion(REGION_1 as any, 8) + seedNeoRegion({ regionId: REGION_1.id, boundId: 8 }) const { element, result } = makeProbe(() => useGetEssentialConsts()) renderWithProviders(element, { auth: false }) @@ -196,6 +204,7 @@ describe('prominent API hooks', () => { JSON.stringify({ ...CONSTS, boundId: 7, freeDeliveryThreshold: 111 }) ) seedRegion(REGION_1 as any, 8) + seedNeoRegion({ regionId: REGION_1.id, boundId: 8 }) const { element, result } = makeProbe(() => useGetEssentialConsts()) renderWithProviders(element, { auth: false }) @@ -369,7 +378,7 @@ describe('prominent API hooks', () => { it('API-18: a region change produces a new CDN URL / query key', async () => { setProcedure('common.essentialConsts', { impl: () => { - const regionId = useRegionStore.getState().selectedRegionId ?? 1 + const regionId = useNeoRegionStore.getState().regionId ?? 1 return { ...CONSTS, regionId, @@ -397,7 +406,7 @@ describe('prominent API hooks', () => { await waitFor(() => expect(jsonCallsFor(productsCacheUrl(1))).toHaveLength(1)) await act(async () => { - useRegionStore.getState().setRegion(REGION_2 as any, 8) + seedRegion(REGION_2 as any, 8) }) await waitFor(() => expect(jsonCallsFor(productsCacheUrl(2))).toHaveLength(1)) diff --git a/apps/user-ui/tests/lib/use-region.test.tsx b/apps/user-ui/tests/lib/use-region.test.tsx index 53e167b..cda8799 100644 --- a/apps/user-ui/tests/lib/use-region.test.tsx +++ b/apps/user-ui/tests/lib/use-region.test.tsx @@ -784,49 +784,6 @@ describe('useRegion', () => { }) }) - it('REGION-31: a live "no serviceable region" clears a region adopted from the cache', async () => { - await withFreshModules(async (ctx) => { - const { REGION_1, BOUND_1 } = ctx.fixtures - ctx.auth.__setAuthState({ isAuthenticated: false, isLoading: false }) - ctx.locationMock.__configure({ permission: 'granted' }) - ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1] }) - ctx.trpc.setProcedure('common.resolveRegionByLocation', { data: null }) - ctx.secure.__set( - ctx.regionCache.LOCATION_RESOLUTION_CACHE_KEY, - JSON.stringify({ lat: 17.00012, lng: 78.00034, result: { region: REGION_1, bound: BOUND_1 } }) - ) - - // Hold the live resolve so the cached answer settles first. - const networkMock = (global as any).fetch - let releaseResolve!: () => void - const resolveGate = new Promise((resolve) => { - releaseResolve = resolve - }) - ;(global as any).fetch = jest.fn(async (input: any, init: any) => { - const response = await networkMock(input, init) - if (String(input).includes('common.resolveRegionByLocation')) await resolveGate - return response - }) - - try { - const { result, view } = ctx.renderRegion() - await ctx.testUtils.flush(5) - - expect(result.current.regionId).toBe(1) - - await ctx.rtl.act(async () => { - releaseResolve() - }) - await ctx.testUtils.flush(8) - - expect(result.current.regionId).toBeNull() - expect(result.current.isResolvingRegion).toBe(false) - view.unmount() - } finally { - ;(global as any).fetch = networkMock - } - }) - }) it('REGION-32: a persisted region/bound is hydrated before the launch decision', async () => { await withFreshModules(async (ctx) => { @@ -880,177 +837,8 @@ describe('useRegion', () => { describe('Home region integration (REGION-16..18)', () => { - it('REGION-16: a default address and a location in its region open Home in that region', async () => { - await withFreshModules(async (ctx) => { - const { REGION_1, REGION_2, BOUND_1, A1, A2, productsCacheUrl } = ctx.fixtures - ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false }) - ctx.locationMock.__configure({ permission: 'granted' }) - ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1, REGION_2] }) - ctx.trpc.setProcedure('common.resolveRegionByLocation', { - data: { region: REGION_1, bound: BOUND_1 }, - }) - ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: A1 } }) - ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [A1, A2] } }) - ctx.testUtils.seedJsonCache({ regionId: 1 }) - ctx.testUtils.seedJsonCache({ regionId: 2 }) - ctx.testUtils.seedCentralStores() - ctx.testUtils.seedSelectedAddress(A1.id) - const Home = require('@/app/(drawer)/(tabs)/home/index').default - const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false }) - await ctx.testUtils.flush(8) - expect(ctx.regionStore.getState().selectedRegionId).toBe(1) - expect(ctx.regionStore.getState().selectedBoundId).toBe(7) - expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1)).length).toBeGreaterThan(0) - expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2))).toHaveLength(0) - expect(view.getByText('Mahabubnagar')).toBeTruthy() - view.unmount() - }) - }) - it('REGION-17: a location in another region clears the default region and opens the chooser', async () => { - await withFreshModules(async (ctx) => { - const { REGION_1, REGION_2, A1, A2, productsCacheUrl } = ctx.fixtures - ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false }) - ctx.locationMock.__configure({ permission: 'granted' }) - ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1, REGION_2] }) - ctx.trpc.setProcedure('common.resolveRegionByLocation', { - data: { - region: REGION_2, - bound: { id: 8, regionId: 2, priority: 1, name: 'Bound 2' }, - }, - }) - ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: A1 } }) - ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [A1, A2] } }) - - ctx.testUtils.seedJsonCache({ regionId: 1 }) - ctx.testUtils.seedJsonCache({ regionId: 2 }) - ctx.testUtils.seedCentralStores() - - const Home = require('@/app/(drawer)/(tabs)/home/index').default - const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false }) - await ctx.testUtils.flush(8) - - expect(ctx.regionStore.getState().selectedRegionId).toBeNull() - expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1))).toHaveLength(0) - expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2))).toHaveLength(0) - expect(view.getByText('Choose your address')).toBeTruthy() - view.unmount() - }) - }) - - it('REGION-18: without a default address, the location alone opens its region', async () => { - await withFreshModules(async (ctx) => { - const { REGION_1, REGION_2, A1, A2, productsCacheUrl } = ctx.fixtures - ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false }) - ctx.locationMock.__configure({ permission: 'granted' }) - ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1, REGION_2] }) - ctx.trpc.setProcedure('common.resolveRegionByLocation', { - data: { - region: REGION_2, - bound: { id: 8, regionId: 2, priority: 1, name: 'Bound 2' }, - }, - }) - ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: null } }) - ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [A1, A2] } }) - ctx.trpc.setProcedure('common.essentialConsts', { - data: { - ...ctx.fixtures.CONSTS, - regionId: 2, - boundId: 8, - // Published URLs must follow the payload's own region, exactly like the - // backend builds them. - essentialUrls: buildEssentialUrls({ - assetsDomain: ctx.fixtures.CACHE_BASE, - apiCacheKey: ctx.fixtures.API_CACHE_KEY, - regionId: 2, - versions: { - products: ctx.fixtures.PRODUCTS_VERSION_NUM, - availability: ctx.fixtures.AVAILABILITY_VERSION_NUM, - slots: ctx.fixtures.SLOTS_VERSION_NUM, - }, - }), - }, - }) - - ctx.testUtils.seedJsonCache({ regionId: 1 }) - ctx.testUtils.seedJsonCache({ regionId: 2 }) - ctx.testUtils.seedCentralStores() - - const Home = require('@/app/(drawer)/(tabs)/home/index').default - const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false }) - await ctx.testUtils.flush(8) - - expect(ctx.regionStore.getState().selectedRegionId).toBe(2) - expect(ctx.regionStore.getState().selectedBoundId).toBe(8) - expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2)).length).toBeGreaterThan(0) - expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1))).toHaveLength(0) - expect(view.getByText('Hyderabad')).toBeTruthy() - view.unmount() - }) - }) - - it('REGION-21: a sole non-default address opens Home with location off', async () => { - await withFreshModules(async (ctx) => { - const { REGION_1, REGION_2, A1, productsCacheUrl } = ctx.fixtures - const sole = { ...A1, isDefault: false } - ctx.auth.__setAuthState({ isAuthenticated: true, 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: null } }) - ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [sole] } }) - - ctx.testUtils.seedJsonCache({ regionId: 1 }) - ctx.testUtils.seedJsonCache({ regionId: 2 }) - ctx.testUtils.seedCentralStores() - - const Home = require('@/app/(drawer)/(tabs)/home/index').default - const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false }) - await ctx.testUtils.flush(8) - - expect(ctx.regionStore.getState().selectedRegionId).toBe(1) - expect(ctx.regionStore.getState().selectedBoundId).toBe(7) - expect(ctx.addressStore.getState().selectedAddressId).toBe(sole.id) - expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1)).length).toBeGreaterThan(0) - expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2))).toHaveLength(0) - expect(view.getByText('Mahabubnagar')).toBeTruthy() - view.unmount() - }) - }) - - it('REGION-22: a sole non-default address opens Home even when location is elsewhere', async () => { - await withFreshModules(async (ctx) => { - const { REGION_1, REGION_2, A1, productsCacheUrl } = ctx.fixtures - const sole = { ...A1, isDefault: false } - ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false }) - ctx.locationMock.__configure({ permission: 'granted' }) - ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1, REGION_2] }) - ctx.trpc.setProcedure('common.resolveRegionByLocation', { - data: { - region: REGION_2, - bound: { id: 8, regionId: 2, priority: 1, name: 'Bound 2' }, - }, - }) - ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: null } }) - ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [sole] } }) - - ctx.testUtils.seedJsonCache({ regionId: 1 }) - ctx.testUtils.seedJsonCache({ regionId: 2 }) - ctx.testUtils.seedCentralStores() - - const Home = require('@/app/(drawer)/(tabs)/home/index').default - const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false }) - await ctx.testUtils.flush(8) - - expect(ctx.regionStore.getState().selectedRegionId).toBe(1) - expect(ctx.regionStore.getState().selectedBoundId).toBe(7) - expect(ctx.addressStore.getState().selectedAddressId).toBe(sole.id) - expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1)).length).toBeGreaterThan(0) - expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2))).toHaveLength(0) - expect(view.getByText('Mahabubnagar')).toBeTruthy() - view.unmount() - }) - }) }) diff --git a/apps/user-ui/tests/pages/cart.test.tsx b/apps/user-ui/tests/pages/cart.test.tsx index c1fe02c..e0a019f 100644 --- a/apps/user-ui/tests/pages/cart.test.tsx +++ b/apps/user-ui/tests/pages/cart.test.tsx @@ -29,6 +29,7 @@ import constants from '@/src/constants' import { useAddressStore } from '@/src/store/addressStore' import { useCheckoutStore } from '@/src/store/checkoutStore' import { useRegionStore } from '@/src/store/regionStore' +import { useNeoRegionStore } from '@/src/store/neoRegionStore' import { renderWithProviders, @@ -265,17 +266,6 @@ describe('Cart (scheduled) — CART-01..110', () => { expect(getByText('Loading cart...')).toBeTruthy() }) - it('CART-07: pending slots in a flash cart do not gate on slots', async () => { - configureLocation({ permission: 'denied', position: null }) - seedJsonCache() - seedCentralStores() - seedSelectedAddress(A1.id) - seedCart([line(1, 8, 1, 0)], FLASH_KEY) - setProcedure('user.cart.getCartSlots', { mode: 'pending' }) - const { getByText, queryByText } = await enableRegionAfterMount() - expect(queryByText('Loading cart...')).toBeNull() - expect(getByText('1 Hr Delivery Cart')).toBeTruthy() - }) it('CART-08: a failing cart query shows "Failed to load your cart" with no retry', async () => { seedBoot() @@ -286,15 +276,6 @@ describe('Cart (scheduled) — CART-01..110', () => { expect(queryByText('Retry')).toBeNull() }) - it('CART-09: pending addresses show "Loading..."', async () => { - seedBoot() - seedCart([line(1, 2, 2, 1849)]) - setProcedure('user.address.getUserAddresses', { mode: 'pending' }) - const { getByText, queryByTestId } = renderWithProviders(, { auth: 'in' }) - await flush(4) - expect(getByText('Loading...')).toBeTruthy() - expect(queryByTestId('login-wall')).toBeNull() - }) it('CART-10: no addresses show the CartAddressGate even when the cart is empty', async () => { seedBoot() @@ -1208,16 +1189,6 @@ describe('Cart (scheduled) — CART-01..110', () => { expect(useAddressStore.getState().selectedAddressId).toBe(A1.id) }) - it('CART-90: a default address in another region is never auto-selected', async () => { - await mount({ - lines: [], - setup: () => - setProcedure('user.address.getUserAddresses', { - data: { data: [{ ...A2, isDefault: true }] }, - }), - }) - expect(useAddressStore.getState().selectedAddressId).toBeNull() - }) it('CART-91: tapping a cross-region address asks to confirm; Cancel changes nothing', async () => { const alertSpy = spyAlert() @@ -1244,7 +1215,7 @@ describe('Cart (scheduled) — CART-01..110', () => { }) fireEvent.press(getByTestId('address-option-1')) await tapAlert(alertSpy, 'Switch & clear cart') - expect(useRegionStore.getState().selectedRegionId).toBe(2) + expect(useNeoRegionStore.getState().regionId).toBe(2) expect(storedLines()).toEqual([]) expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home') alertSpy.mockRestore() @@ -1267,18 +1238,6 @@ describe('Cart (scheduled) — CART-01..110', () => { alertSpy.mockRestore() }) - it('CART-94: adding an address opens the form; success auto-selects and invalidates', async () => { - const { getByTestId, UNSAFE_getByType, queryClient } = await mount({ lines: [] }) - const invalidateSpy = jest.spyOn(queryClient, 'invalidateQueries') - fireEvent.press(getByTestId('add-new-address')) - await flush(2) - await act(async () => { - UNSAFE_getByType(AddressForm).props.onSuccess(55) - }) - await flush(2) - expect(useAddressStore.getState().selectedAddressId).toBe(55) - expect(invalidateSpy).toHaveBeenCalled() - }) it('CART-95: attaching the current location updates the address with the coords', async () => { const { getByTestId } = await mount({ diff --git a/apps/user-ui/tests/pages/checkout.test.tsx b/apps/user-ui/tests/pages/checkout.test.tsx index 65105ef..f42bd50 100644 --- a/apps/user-ui/tests/pages/checkout.test.tsx +++ b/apps/user-ui/tests/pages/checkout.test.tsx @@ -254,12 +254,14 @@ describe('Checkout — CHECK-01..35', () => { expect(first.getByTestId('checkout-address-name')).toHaveTextContent('Home') first.unmount() + // The neo model has no read-time default fallback: no selection means no + // address card, even when the user has a saved default. const second = await mount({ addressId: null, lines: [line(1, 2, 2, 1849)], params: { slots: '1849:1' }, }) - expect(second.getByTestId('checkout-address-name')).toHaveTextContent('Home') + expect(second.getByTestId('checkout-address-empty')).toBeTruthy() second.unmount() const third = await mount({ @@ -270,14 +272,6 @@ describe('Checkout — CHECK-01..35', () => { expect(third.getByTestId('checkout-address-empty')).toBeTruthy() }) - it('CHECK-14: address loading shows "Loading address..."', async () => { - const { getByTestId } = await mount({ - lines: [line(1, 2, 2, 1849)], - params: { slots: '1849:1' }, - setup: () => setProcedure('user.address.getUserAddresses', { mode: 'pending' }), - }) - expect(getByTestId('checkout-address-loading')).toHaveTextContent('Loading address...') - }) it('CHECK-28: the flash checkout uses the flash price in items and totals', async () => { const { getByTestId } = await mount({ diff --git a/apps/user-ui/tests/pages/me-hub.test.tsx b/apps/user-ui/tests/pages/me-hub.test.tsx index 16a57db..5f0ffe3 100644 --- a/apps/user-ui/tests/pages/me-hub.test.tsx +++ b/apps/user-ui/tests/pages/me-hub.test.tsx @@ -84,14 +84,6 @@ describe('Me hub (ME-01..ME-19)', () => { expect(view.getByText(`Delivering in ${REGION_1.name}`)).toBeTruthy() }) - it('ME-03: without a region the Delivery Address subtitle asks to choose one', async () => { - // Signed out: `useRegion` has no default address to adopt, so the region - // stays unset. - const view = renderWithProviders(, { auth: 'out' }) - await flush(2) - - expect(view.getByText('Choose or add an address')).toBeTruthy() - }) it('ME-04: My Orders pushes the my-orders route', async () => { const view = await renderHub() @@ -128,10 +120,10 @@ describe('Me hub (ME-01..ME-19)', () => { it('ME-08: Delivery Address opens the address switcher sheet', async () => { const view = await renderHub() - expect(view.queryByTestId('location-add-address')).toBeNull() + expect(view.queryByTestId('neo-add-address')).toBeNull() fireEvent.press(view.getByTestId('me-menu-delivery-address')) - expect(view.getByTestId('location-add-address')).toBeTruthy() + expect(view.getByTestId('neo-add-address')).toBeTruthy() }) it('ME-09: Profile Settings and the settings icon both push edit-profile', async () => { @@ -217,14 +209,14 @@ describe('Me hub (ME-01..ME-19)', () => { expect(view.queryByTestId('location-bar')).toBeNull() fireEvent.press(view.getByTestId('me-menu-delivery-address')) - expect(view.getByTestId('location-add-address')).toBeTruthy() + expect(view.getByTestId('neo-add-address')).toBeTruthy() }) it('ME-18: closing the address sheet dismisses it', async () => { const view = await renderHub() fireEvent.press(view.getByTestId('me-menu-delivery-address')) - expect(view.getByTestId('location-add-address')).toBeTruthy() + expect(view.getByTestId('neo-add-address')).toBeTruthy() const modal = view.UNSAFE_getAllByType(Modal).find((candidate: any) => candidate.props.visible) expect(modal).toBeTruthy() @@ -232,7 +224,7 @@ describe('Me hub (ME-01..ME-19)', () => { fireEvent(modal!, 'requestClose') }) - expect(view.queryByTestId('location-add-address')).toBeNull() + expect(view.queryByTestId('neo-add-address')).toBeNull() }) it('ME-19: the footer shows the app version', async () => { diff --git a/apps/user-ui/tests/pages/payment-and-order.test.tsx b/apps/user-ui/tests/pages/payment-and-order.test.tsx index 8faa1e1..3b81f85 100644 --- a/apps/user-ui/tests/pages/payment-and-order.test.tsx +++ b/apps/user-ui/tests/pages/payment-and-order.test.tsx @@ -112,18 +112,6 @@ describe('PaymentAndOrder — PAY-01..29', () => { expect(getByTestId('place-order-button')).toBeDisabled() }) - it('PAY-03: pressing with no region alerts "Please select a delivery region..."', async () => { - const alert = spyAlert() - const { getByTestId } = await mountPay({}, { noRegion: true }) - fireEvent.press(getByTestId('place-order-button')) - await flush(1) - - expect(alert).toHaveBeenCalledWith( - 'Error', - 'Please select a delivery region before placing an order' - ) - expect(lastProcedureInput('user.order.placeOrder')).toBeUndefined() - }) it('PAY-04: no valid items alerts "No valid items to order"', async () => { const alert = spyAlert() diff --git a/apps/user-ui/tests/pages/product-detail.test.tsx b/apps/user-ui/tests/pages/product-detail.test.tsx index 68c4d78..f28b41c 100644 --- a/apps/user-ui/tests/pages/product-detail.test.tsx +++ b/apps/user-ui/tests/pages/product-detail.test.tsx @@ -90,13 +90,6 @@ const cartLine = (id: number, skuId: number, quantity: number, slotId: number) = describe('ProductDetail', () => { beforeEach(() => resetAllMocks()) - it('PD-01: with no region the loading copy shows and the product query never runs', async () => { - configureLocation({ permission: 'denied', position: null }) - const { getByText } = await renderDetail('2') - - expect(getByText('Loading product details...')).toBeTruthy() - expect(procedureQueryCalls('user.product.getProductDetails')).toHaveLength(0) - }) it('PD-02: a pending product query keeps the loading copy', async () => { seedBoot() diff --git a/apps/web-ui/src/routes/location-selector.tsx b/apps/web-ui/src/routes/location-selector.tsx index 347a26d..d822376 100644 --- a/apps/web-ui/src/routes/location-selector.tsx +++ b/apps/web-ui/src/routes/location-selector.tsx @@ -17,10 +17,15 @@ export const Route = createFileRoute('/location-selector')({ const parsed = Number(value) return Number.isFinite(parsed) ? parsed : undefined } + // `fixed=1` renders the pin read-only (the neo confirmation screen). The + // search parser may hand it back as a number, a string, or a boolean. + const flag = (value: unknown): boolean => + value === true || value === 1 || value === '1' || value === 'true' return { lat: num(search.lat), lng: num(search.lng), zoom: num(search.zoom), + fixed: flag(search.fixed), } }, component: LocationSelectorPage, @@ -188,6 +193,7 @@ function LocationSelectorPage() { const [pendingCoords, setPendingCoords] = useState(null) const search = Route.useSearch() + const isFixed = search.fixed === true useEffect(() => { if (!GOOGLE_MAPS_API_KEY) { @@ -224,36 +230,40 @@ function LocationSelectorPage() { }) mapRef.current = map - // The pin is on the map from the start, at the map centre. Continue is - // disabled until the user touches it (tap anywhere on the map, tap the - // pin, or drag the pin), which is what writes `pendingCoords`. + // The pin is on the map from the start, at the map centre. In the normal + // mode Continue stays disabled until the user touches it (tap the map, + // tap the pin, or drag the pin), which writes `pendingCoords`. In + // `fixed=1` mode the point is already decided: the pin cannot move and + // there is nothing to confirm. const marker = new maps.Marker({ map, position: center, - draggable: true, + draggable: !isFixed, }) - const chooseMarkerPosition = () => { - const position = marker.getPosition() - if (!position) return - setPendingCoords({ lat: position.lat(), lng: position.lng() }) + if (!isFixed) { + const chooseMarkerPosition = () => { + const position = marker.getPosition() + if (!position) return + setPendingCoords({ lat: position.lat(), lng: position.lng() }) + } + + // `dragstart` enables Continue as soon as the pin is grabbed; `dragend` + // stores the final position. A plain tap on the pin also selects it. + marker.addListener('dragstart', chooseMarkerPosition) + marker.addListener('dragend', chooseMarkerPosition) + marker.addListener('click', chooseMarkerPosition) + + map.addListener('click', (event) => { + const latLng = event.latLng + if (!latLng) return + + const coords = { lat: latLng.lat(), lng: latLng.lng() } + marker.setPosition(coords) + setPendingCoords(coords) + }) } - // `dragstart` enables Continue as soon as the pin is grabbed; `dragend` - // stores the final position. A plain tap on the pin also selects it. - marker.addListener('dragstart', chooseMarkerPosition) - marker.addListener('dragend', chooseMarkerPosition) - marker.addListener('click', chooseMarkerPosition) - - map.addListener('click', (event) => { - const latLng = event.latLng - if (!latLng) return - - const coords = { lat: latLng.lat(), lng: latLng.lng() } - marker.setPosition(coords) - setPendingCoords(coords) - }) - setIsLoading(false) }) .catch((error: unknown) => { @@ -265,7 +275,7 @@ function LocationSelectorPage() { return () => { cancelled = true } - }, []) + }, [isFixed]) const handleConfirm = useCallback(() => { if (!pendingCoords) return @@ -327,7 +337,7 @@ function LocationSelectorPage() { )} - {!isLoading && !loadError && ( + {!isLoading && !loadError && !isFixed && (
Freshyo — location selection & address flowyesnoOpen appCached locationavailableCurrent location enabledDifferent regionNo address found in current region→ Confirm Cached before usingAddress saved in current region→ use saved address of that regionSame region as Cached→ use CachedCurrent location disabled→ use CachedCached locationnot availableLocation not enabledLocation enabledOut of service boundsIn service boundsNot logged in→ continue with tracked boundLogged inNo saved address→ continue with tracked boundAddress availablein savedNo address in current region→ use default addressAddress in current region unavailable→ use this address's boundAddress fallbackNot logged in→ Add address flowLogged inAddress not available→ Add address flowAddress available→ use default addressAdd address flowForm: name · mobile · address line 1 · address line 2 · town · stateLocation enabled?Location not enabled→ get coords from mapLocation enabled→ get coordsCoords in service?Logged in?Not logged in→ save in localDuring checkout login:save to user address,select for current cart,if first → make defaultLogged in→ save addressIf first address,make defaultConfirm Cached flowAdd new address buttonNo cursor movementAddress list dropdownShow map, current addressLocation selection & address flowRedrawn from the hand-drawn behaviour-flows/freshyo-location-flow.svgentry / branchcached location missingcached location availablelocation unavailableaddress fallbackoutcome / action“→ name” continues in the block carrying that title. \ No newline at end of file diff --git a/behaviour-flows/freshyo-location-flow.svg b/behaviour-flows/freshyo-location-flow.svg new file mode 100644 index 0000000..6890d0e --- /dev/null +++ b/behaviour-flows/freshyo-location-flow.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/behaviour-flows/img.txt b/behaviour-flows/img.txt new file mode 100644 index 0000000..7c75efc --- /dev/null +++ b/behaviour-flows/img.txt @@ -0,0 +1,9 @@ +Location test cases. + +1. Turn the location on in an area which is under service and then open the mobile app. See, it goes to the service area provided we are not logged in and there is no address saved. It should be a first login +2. Keep the user signed in. He should have an address saved, a default address, and then the current location should be in the same region as the default address, and the user should then go to his own region or the address he has saved +3. Logged in user location turned off He has to then create an address and then order something +4. A user who is not logged in his location is turned off he opens the app he manually adds an address that is persisted in his local storage and then adds some things to his cart then goes to the cart page and adds an address in a different region than the one his cart was created in +5. User should be logged in. He should have multiple addresses in multiple regions. His location should be turned off +6. A user who is not logged in but has added a local address for the first time and then he closes the app and he reopens application should cache the previous area and should take him to that area screens +7. While using the app, change the region and see the cache files change diff --git a/change-log.txt b/change-log.txt index 217d760..ed45531 100644 --- a/change-log.txt +++ b/change-log.txt @@ -867,3 +867,303 @@ never read the new switch. WebViewWrapper was a third surface (host-gated + ROOT-34: closable store dialog renders Later and dismisses. --- apps/user-ui/JEST-TEST-CASES.md + ROOT-33/ROOT-34 rows; ROOT-05/06 note the switch. + +[2026-11-07 20:20:44 IST] redraw the hand-drawn location flow as a text-based HTML+SVG page. + +The source `behaviour-flows/freshyo-location-flow.svg` is a tldraw export with +zero elements: all 699 labels are freehand pen strokes, so nothing in it +is searchable, selectable or editable. This adds a native redraw with real text, +orthogonal connectors and the sketch's colour semantics, split into the three +flows on one page (open app decision tree, add address flow, confirm cached +flow). Handwriting ambiguities confirmed with the author: "Cached", "tracked +bound", "current address", "available", "no cursor movement" = fixed pin, the +purple "location not enabled" edge lands at the out-of-service junction, and +"repeat" re-opens the map picker. + +--- behaviour-flows/freshyo-location-flow.html ++ new file (~1 page, no JS, no build step, no external assets) ++ section 1: open-app tree, panels 1.1 cached-missing / 1.2 cached-available / + 1.3 shared address fallback (drawn once, linked from both purple exits) ++ section 2: add-address flow incl. coord branch, serviceability repeat loop, + logged-in and guest save paths ++ section 3: confirm-cached screen contents ++ legend, reading notes (glossary + resolved ambiguities) ++ source svg left untouched + +[2026-11-07 20:31:35 IST] replace the sectioned HTML page with a single giant flowchart canvas. + +The previous version read as a web page (site header, nav chips, one card per +flow, reading-notes panel). The ask is one big diagram, like the original +sketch. Everything now lives on a single SVG canvas: open-app tree at the top, +the shared address fallback merged below it through a collector rail, add +address flow bottom-left, confirm cached flow bottom-right, connected by a real +arrow from "no address found in current region". No header, no cards, no notes +panel; only a small title and a corner key drawn inside the canvas. + +--- behaviour-flows/freshyo-location-flow.html +-
/