Compare commits
6 commits
main
...
neo-region
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90c6c90505 | ||
|
|
2cb1cfd807 | ||
|
|
442e20c88a | ||
|
|
a09ae70b9f | ||
|
|
7a5fc0ff67 | ||
|
|
f9fb1c53a7 |
56 changed files with 3809 additions and 757 deletions
|
|
@ -1270,8 +1270,8 @@ Covered by HOME-81..98, plus:
|
|||
| FCB-03 | edge | flash cart | pink theme |
|
||||
| FCB-04 | edge | cart refetch after mutation | quantities state resets |
|
||||
| FCB-05 | edge | no cart data | no crash |
|
||||
| FCB-06 | happy | expanded sheet | “Apply Coupons at checkout” on the subtotal row, beside the amount |
|
||||
| FCB-07 | happy | coupon offer on the line's sku | `₹390` (₹430 line after the cap) + “With Coupon”, on its own row under the slot row |
|
||||
| FCB-06 | happy | expanded sheet | “Apply Coupons at checkout” under the subtotal |
|
||||
| FCB-07 | happy | coupon offer on the line's sku | `₹390` (₹430 line after the cap) + “With Coupon” |
|
||||
| FCB-08 | edge | no offer for the sku | no coupon line |
|
||||
|
||||
### CouponBreakdownDialog
|
||||
|
|
|
|||
|
|
@ -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',
|
||||
|
|
|
|||
|
|
@ -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() {
|
|||
<FirstUserWrapper>
|
||||
<AuthProvider>
|
||||
<PendingAddressSync />
|
||||
<LocationTestWrapper>
|
||||
<LocationWrapperNeo>
|
||||
<NotificationProvider>
|
||||
<NotifChecker />
|
||||
<NotifRegionSync />
|
||||
|
|
@ -93,7 +95,7 @@ export default function RootLayout() {
|
|||
</RefreshProvider>
|
||||
</PaperProvider>
|
||||
</NotificationProvider>
|
||||
</LocationTestWrapper>
|
||||
</LocationWrapperNeo>
|
||||
</AuthProvider>
|
||||
</FirstUserWrapper>
|
||||
</WebViewWrapper>
|
||||
|
|
|
|||
|
|
@ -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<CartAddressGateProps> = ({ 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')
|
||||
|
|
@ -107,7 +115,7 @@ const CartAddressGate: React.FC<CartAddressGateProps> = ({ onDone, onBack }) =>
|
|||
animationType="slide"
|
||||
onRequestClose={() => setMode('none')}
|
||||
>
|
||||
<View style={tw`flex-1 bg-white`}>
|
||||
<View style={tw`flex-1 bg-white pb-4`}>
|
||||
<AddressForm
|
||||
// "Current location" prefills the device coordinates; "another
|
||||
// location" starts empty so the user picks on the map.
|
||||
|
|
@ -118,7 +126,7 @@ const CartAddressGate: React.FC<CartAddressGateProps> = ({ 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<CartAddressGateProps> = ({ 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()
|
||||
})()
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<View testID="checkout-address" style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}>
|
||||
|
|
@ -34,22 +23,10 @@ const CheckoutAddressDisplay: React.FC = () => {
|
|||
<MyText style={tw`text-base font-bold text-gray-900`}>Delivery Address</MyText>
|
||||
</View>
|
||||
|
||||
{isLoading ? (
|
||||
<MyText testID="checkout-address-loading" style={tw`text-gray-500`}>Loading address...</MyText>
|
||||
) : address ? (
|
||||
{address ? (
|
||||
<View style={tw`bg-gray-50 p-4 rounded-xl border border-gray-200`}>
|
||||
<View style={tw`flex-row items-center mb-2`}>
|
||||
<MaterialIcons
|
||||
name={
|
||||
address.name.toLowerCase().includes('home')
|
||||
? 'home'
|
||||
: address.name.toLowerCase().includes('work')
|
||||
? 'work'
|
||||
: 'location-on'
|
||||
}
|
||||
size={20}
|
||||
color="#6B7280"
|
||||
/>
|
||||
<MaterialIcons name={addressIconName(address.name)} size={20} color="#6B7280" />
|
||||
<MyText testID="checkout-address-name" style={tw`font-bold ml-2 text-gray-900`}>{address.name}</MyText>
|
||||
</View>
|
||||
<MyText style={tw`text-gray-600 text-sm leading-5 mb-1`} numberOfLines={2}>
|
||||
|
|
|
|||
|
|
@ -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<AddressSelectorProps> = ({
|
||||
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<number | null>(null);
|
||||
const [locationLoading, setLocationLoading] = useState(false);
|
||||
|
|
@ -31,13 +28,16 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
|
|||
const utils = trpc.useUtils();
|
||||
const router = useRouter();
|
||||
const scrollViewRef = useRef<ScrollView>(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<AddressSelectorProps> = ({
|
|||
});
|
||||
}, [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<AddressSelectorProps> = ({
|
|||
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<AddressSelectorProps> = ({
|
|||
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<AddressSelectorProps> = ({
|
|||
<View style={tw`flex-row justify-between items-start mb-2`}>
|
||||
<View style={tw`flex-row items-center`}>
|
||||
<MaterialIcons
|
||||
name={address.name.toLowerCase().includes('home') ? 'home' : address.name.toLowerCase().includes('work') ? 'work' : 'location-on'}
|
||||
name={addressIconName(address.name)}
|
||||
size={20}
|
||||
color={selectedAddress === address.id ? '#EC4899' : '#6B7280'}
|
||||
/>
|
||||
|
|
@ -286,17 +281,50 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
|
|||
|
||||
{/* <BottomDialog open={showAddAddress} onClose={() => setShowAddAddress(false)}> */}
|
||||
<RawBottomDialog open={showAddAddress} onClose={() => setShowAddAddress(false)}>
|
||||
{/* pb-4 keeps the form off the bottom edge of the sheet (16px). */}
|
||||
<View style={tw`flex-1 bg-white pb-4`}>
|
||||
<AddressForm
|
||||
onResolvedRegion={(info) => {
|
||||
resolvedRegionRef.current = info;
|
||||
}}
|
||||
onSuccess={(addressId) => {
|
||||
setShowAddAddress(false);
|
||||
queryClient.invalidateQueries();
|
||||
if (addressId == null) return;
|
||||
|
||||
<AddressForm
|
||||
onSuccess={(addressId) => {
|
||||
setShowAddAddress(false);
|
||||
// Auto-select the newly added address
|
||||
if (addressId) {
|
||||
onAddressSelect(addressId);
|
||||
}
|
||||
queryClient.invalidateQueries();
|
||||
}}
|
||||
/>
|
||||
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);
|
||||
})();
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
</RawBottomDialog>
|
||||
{/* </BottomDialog> */}
|
||||
</>
|
||||
|
|
|
|||
34
apps/user-ui/components/LocationWrapperNeo.tsx
Normal file
34
apps/user-ui/components/LocationWrapperNeo.tsx
Normal file
|
|
@ -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<ReactParentComponent> = ({ 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 <NeoAddressFlow />
|
||||
if (regionId == null || boundId == null || regionName == null || coords == null) {
|
||||
return <NeoLoadingScreen />
|
||||
}
|
||||
if (needsAddressConfirmation) return <NeoConfirmLocation />
|
||||
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
export default LocationWrapperNeo
|
||||
|
|
@ -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<PaymentAndOrderProps> = ({
|
|||
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(() => {
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
@ -53,7 +53,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ 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(
|
||||
|
|
|
|||
|
|
@ -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<QuickDeliveryAddressSelectorProps>
|
|||
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<QuickDeliveryAddressSelectorProps>
|
|||
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<QuickDeliveryAddressSelectorProps>
|
|||
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<QuickDeliveryAddressSelectorProps>
|
|||
address.id === (selectedAddressId || defaultAddress?.id) ? 'bg-brand50 border-brand500' : 'bg-white'
|
||||
}`}
|
||||
onPress={() => {
|
||||
setSelectedAddressId(address.id);
|
||||
void selectAddress?.(address.id);
|
||||
setAddressDialogOpen(false);
|
||||
}}
|
||||
activeOpacity={0.7}
|
||||
|
|
|
|||
|
|
@ -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
|
|||
</View>
|
||||
);
|
||||
}
|
||||
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 (
|
||||
<CartAddressGate
|
||||
onDone={() => {
|
||||
|
|
@ -1447,10 +1450,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
|||
</View>
|
||||
|
||||
{/* Delivery Address */}
|
||||
<CheckoutAddressSelector
|
||||
selectedAddress={selectedAddressId}
|
||||
onAddressSelect={setSelectedAddressId}
|
||||
/>
|
||||
<CheckoutAddressSelector />
|
||||
|
||||
{/* Bottom Checkout Bar - Now Static */}
|
||||
{hasAvailableItems && (
|
||||
|
|
|
|||
|
|
@ -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<FlashDeliveryProps> = ({ 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<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
|||
refetchSlots();
|
||||
});
|
||||
|
||||
const { selectedAddressId } = useAddressStore();
|
||||
const selectedAddressId = neo.selectedAddressId;
|
||||
const [selectedCouponIds, setSelectedCouponIds] = useState<number[]>([]);
|
||||
// Coupon whose per-product discount split is open (product-specific coupons only).
|
||||
const [breakdownCouponId, setBreakdownCouponId] = useState<number | null>(null);
|
||||
|
|
|
|||
|
|
@ -383,24 +383,26 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
|
|||
)}
|
||||
/>
|
||||
)}
|
||||
<MyText style={tw`text-slate-900 text-sm font-bold`}>
|
||||
₹{(() => {
|
||||
const product = productsById[item.skuId];
|
||||
const basePrice = product?.price ?? 0;
|
||||
const price = isFlashDelivery ? (product?.flashPrice ?? basePrice) : basePrice;
|
||||
return price * item.quantity;
|
||||
})()}
|
||||
</MyText>
|
||||
</View>
|
||||
{couponLine != null && (
|
||||
<View
|
||||
testID={`cart-item-coupon-price-${item.id}`}
|
||||
style={tw`flex-row items-center mt-1.5`}
|
||||
>
|
||||
<MyText style={tw`text-emerald-600 text-xs font-bold`}>₹{couponLine}</MyText>
|
||||
<MyText style={tw`text-gray-400 text-[9px] ml-1`}>With Coupon</MyText>
|
||||
<View style={tw`items-end`}>
|
||||
<MyText style={tw`text-slate-900 text-sm font-bold`}>
|
||||
₹{(() => {
|
||||
const product = productsById[item.skuId];
|
||||
const basePrice = product?.price ?? 0;
|
||||
const price = isFlashDelivery ? (product?.flashPrice ?? basePrice) : basePrice;
|
||||
return price * item.quantity;
|
||||
})()}
|
||||
</MyText>
|
||||
{couponLine != null && (
|
||||
<View
|
||||
testID={`cart-item-coupon-price-${item.id}`}
|
||||
style={tw`flex-row items-center mt-0.5`}
|
||||
>
|
||||
<MyText style={tw`text-emerald-600 text-xs font-bold`}>₹{couponLine}</MyText>
|
||||
<MyText style={tw`text-gray-400 text-[9px] ml-1`}>With Coupon</MyText>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
|
|
@ -419,17 +421,7 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
|
|||
<View style={tw`flex-row justify-between items-center mb-5`}>
|
||||
<View>
|
||||
<MyText style={tw`text-slate-400 text-[10px] font-black uppercase tracking-widest`}>Subtotal</MyText>
|
||||
<View style={tw`flex-row items-baseline`}>
|
||||
<MyText style={tw`text-2xl font-black text-slate-900`}>₹{totalCartValue}</MyText>
|
||||
{/* The cart screens have no coupon picker; checkout does. */}
|
||||
<MyText
|
||||
testID="apply-coupons-hint"
|
||||
numberOfLines={1}
|
||||
style={tw`ml-2 text-[10px] font-bold text-slate-400 flex-shrink`}
|
||||
>
|
||||
Apply Coupons at checkout
|
||||
</MyText>
|
||||
</View>
|
||||
<MyText style={tw`text-2xl font-black text-slate-900`}>₹{totalCartValue}</MyText>
|
||||
</View>
|
||||
{remainingForFreeDelivery === 0 && (
|
||||
<View style={tw`bg-emerald-50 px-3 py-1.5 rounded-xl border border-emerald-100 flex-row items-center`}>
|
||||
|
|
@ -439,6 +431,14 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
|
|||
)}
|
||||
</View>
|
||||
|
||||
{/* The cart screens have no coupon picker; checkout does. */}
|
||||
<MyText
|
||||
testID="apply-coupons-hint"
|
||||
style={tw`text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-4`}
|
||||
>
|
||||
Apply Coupons at checkout
|
||||
</MyText>
|
||||
|
||||
<MyTouchableOpacity
|
||||
onPress={() => router.push(
|
||||
isFlashDelivery
|
||||
|
|
|
|||
|
|
@ -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<AddressFormProps & {
|
||||
/** Reported so a bottom sheet can size itself to the form when idle. */
|
||||
onContentHeightChange?: (height: number) => 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<boolean>;
|
||||
}> = ({
|
||||
onSuccess,
|
||||
initialValues,
|
||||
|
|
@ -26,8 +32,12 @@ const AddressForm: React.FC<AddressFormProps & {
|
|||
draftMode = false,
|
||||
onResolvedRegion,
|
||||
onContentHeightChange,
|
||||
onBeforeSubmit,
|
||||
}) => {
|
||||
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<string | null>(null);
|
||||
|
|
@ -205,6 +215,10 @@ const AddressForm: React.FC<AddressFormProps & {
|
|||
const createAddressMutation = trpc.user.address.createAddress.useMutation({
|
||||
onSuccess: (data) => {
|
||||
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<AddressFormProps & {
|
|||
const updateAddressMutation = trpc.user.address.updateAddress.useMutation({
|
||||
onSuccess: () => {
|
||||
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<AddressFormProps & {
|
|||
// not be saveable.
|
||||
const isLocationServiceable =
|
||||
currentLocation != null && resolvedRegion != null && !locationError && !isCheckingLocation;
|
||||
const actionLabel = isEdit ? 'Update Address' : 'Add Address';
|
||||
const progressingLabel = isEdit ? 'Updating...' : 'Adding...';
|
||||
const submitLabel = isSubmitting ? progressingLabel : actionLabel;
|
||||
|
||||
return (
|
||||
<KeyboardAvoidingView
|
||||
|
|
@ -287,6 +306,10 @@ const AddressForm: React.FC<AddressFormProps & {
|
|||
setSubmitError(locationError || 'Please choose a town and a location inside it.');
|
||||
return;
|
||||
}
|
||||
if (onBeforeSubmit) {
|
||||
const allowed = await onBeforeSubmit();
|
||||
if (!allowed) return;
|
||||
}
|
||||
setIsSubmitting(true);
|
||||
setSubmitError(null);
|
||||
const payload = {
|
||||
|
|
@ -455,7 +478,7 @@ const AddressForm: React.FC<AddressFormProps & {
|
|||
disabled={isSubmitting || !isLocationServiceable}
|
||||
>
|
||||
<MyText style={tw`text-white text-center font-bold`}>
|
||||
{isSubmitting ? (isEdit ? 'Updating...' : 'Adding...') : (isEdit ? 'Update Address' : 'Add Address')}
|
||||
{submitLabel}
|
||||
</MyText>
|
||||
</MyTouchableOpacity>
|
||||
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<View style={tw`px-4 pt-3 pb-1`}>
|
||||
<MyTouchableOpacity
|
||||
testID="location-bar"
|
||||
activeOpacity={0.85}
|
||||
onPress={() => 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`}
|
||||
>
|
||||
<View style={tw`w-9 h-9 rounded-full bg-blue-50 items-center justify-center mr-3`}>
|
||||
|
|
@ -57,7 +40,7 @@ const LocationBar: React.FC = () => {
|
|||
<View style={tw`flex-1`}>
|
||||
<View style={tw`flex-row items-center`}>
|
||||
<MyText style={tw`text-xs text-gray-500 mr-2`}>Deliver to</MyText>
|
||||
{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}
|
||||
</MyText>
|
||||
</View>
|
||||
) : (
|
||||
|
|
@ -77,7 +60,7 @@ const LocationBar: React.FC = () => {
|
|||
</MyText>
|
||||
)}
|
||||
</View>
|
||||
{activeAddress ? (
|
||||
{fullAddress ? (
|
||||
<MyText
|
||||
style={tw`text-xs text-gray-500 mt-1`}
|
||||
// Exactly one address line: anything longer ellipsises with "…"
|
||||
|
|
@ -85,7 +68,7 @@ const LocationBar: React.FC = () => {
|
|||
numberOfLines={1}
|
||||
ellipsizeMode="tail"
|
||||
>
|
||||
{formatAddress(activeAddress)}
|
||||
{fullAddress}
|
||||
</MyText>
|
||||
) : null}
|
||||
</View>
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,13 +28,25 @@ const PendingAddressSync: React.FC = () => {
|
|||
|
||||
isSyncing.current = true
|
||||
try {
|
||||
await createAddress.mutateAsync(pending)
|
||||
const created = await createAddress.mutateAsync(pending)
|
||||
// The address is saved; clear the draft and refresh both lists together.
|
||||
await Promise.all([
|
||||
clearPendingAddress(),
|
||||
utils.user.address.getUserAddresses.invalidate(),
|
||||
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 {
|
||||
|
|
|
|||
|
|
@ -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<AddressSwitcherSheetProps> = ({ open, onClose }) => (
|
||||
<Modal visible={open} animationType="slide" onRequestClose={onClose}>
|
||||
<View style={tw`flex-1 bg-white`}>
|
||||
<LocationFallbackFlow onClose={onClose} />
|
||||
<NeoAddressFlow onClose={onClose} />
|
||||
</View>
|
||||
</Modal>
|
||||
)
|
||||
|
|
|
|||
230
apps/user-ui/src/components/location/neo/NeoAddressFlow.tsx
Normal file
230
apps/user-ui/src/components/location/neo/NeoAddressFlow.tsx
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { ScrollView, View } from 'react-native'
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||
import { MyButton, 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'
|
||||
import NeoLocationNotice, { type NeoLocationNoticeKind } from './NeoLocationNotice'
|
||||
|
||||
interface NeoAddressFlowProps {
|
||||
/** Present when hosted in the location-bar sheet. */
|
||||
onClose?: () => void
|
||||
}
|
||||
|
||||
/** Location statuses that explain the flow in the notice card. */
|
||||
const STATUS_NOTICE_KIND: Partial<Record<string, NeoLocationNoticeKind>> = {
|
||||
denied: 'denied',
|
||||
'services-off': 'services-off',
|
||||
unavailable: 'unavailable',
|
||||
error: 'unavailable',
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<NeoAddressFlowProps> = ({ 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 deviceOutOfService = useNeoRegionStore((state) => state.deviceOutOfService)
|
||||
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?.()
|
||||
}
|
||||
|
||||
// An out-of-area device fix is worth explaining even when a cached region is
|
||||
// already published (the sheet case). A live permission/services notice is
|
||||
// more current, so it wins while there is no region.
|
||||
let noticeKind: NeoLocationNoticeKind | null = null
|
||||
if (regionId == null && STATUS_NOTICE_KIND[locationStatus] != null) {
|
||||
noticeKind = STATUS_NOTICE_KIND[locationStatus] ?? null
|
||||
} else if (deviceOutOfService) {
|
||||
noticeKind = 'out-of-area'
|
||||
}
|
||||
|
||||
if (mode === 'add') {
|
||||
return (
|
||||
<View style={tw`flex-1 bg-white`}>
|
||||
<MyTouchableOpacity
|
||||
testID="neo-add-back"
|
||||
onPress={() => setMode('choose')}
|
||||
activeOpacity={0.7}
|
||||
style={tw`px-5 pt-12 pb-2 flex-row items-center`}
|
||||
>
|
||||
<MaterialIcons name="arrow-back" size={22} color="#4B5563" />
|
||||
<MyText style={tw`text-gray-600 ml-1`}>Back</MyText>
|
||||
</MyTouchableOpacity>
|
||||
{noticeKind != null && (
|
||||
<NeoLocationNotice kind={noticeKind} style={tw`mx-5 mb-2`} />
|
||||
)}
|
||||
<NeoAddressForm
|
||||
onDone={() => {
|
||||
closeAddressFlow()
|
||||
onClose?.()
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
if (mode === 'login') {
|
||||
return (
|
||||
<View style={tw`flex-1 bg-white`}>
|
||||
<Login />
|
||||
<MyTouchableOpacity
|
||||
testID="neo-location-login-back"
|
||||
onPress={() => 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`}
|
||||
>
|
||||
<MaterialIcons name="arrow-back" size={22} color="#374151" />
|
||||
</MyTouchableOpacity>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<View testID="neo-address-flow" style={tw`flex-1 bg-white`}>
|
||||
<ScrollView contentContainerStyle={tw`px-5 pt-12 pb-10`}>
|
||||
<View style={tw`flex-row items-start justify-between`}>
|
||||
<View style={tw`flex-1`}>
|
||||
<MyText style={tw`text-3xl font-extrabold text-gray-900`}>
|
||||
Delivery Address
|
||||
</MyText>
|
||||
<MyText style={tw`text-gray-500 mt-2`}>
|
||||
Choose a saved address, or add a new one. Your region follows the address.
|
||||
</MyText>
|
||||
</View>
|
||||
{onClose != null && (
|
||||
<MyTouchableOpacity
|
||||
testID="neo-location-close"
|
||||
onPress={onClose}
|
||||
activeOpacity={0.7}
|
||||
style={tw`p-1`}
|
||||
>
|
||||
<MaterialIcons name="close" size={24} color="#9CA3AF" />
|
||||
</MyTouchableOpacity>
|
||||
)}
|
||||
</View>
|
||||
|
||||
{noticeKind != null && (
|
||||
<NeoLocationNotice kind={noticeKind} style={tw`mt-4`} />
|
||||
)}
|
||||
|
||||
<View style={tw`mt-6`}>
|
||||
{addresses.map((address) => {
|
||||
const isSelected = address.id === selectedAddressId
|
||||
return (
|
||||
<MyTouchableOpacity
|
||||
key={address.id}
|
||||
testID={`neo-address-${address.id}`}
|
||||
onPress={() => 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`}
|
||||
>
|
||||
<View style={tw`flex-row items-center mb-1`}>
|
||||
<MaterialIcons
|
||||
name="location-on"
|
||||
size={20}
|
||||
color={isSelected ? '#4F46E5' : '#6B7280'}
|
||||
/>
|
||||
<MyText style={tw`font-bold text-gray-900 ml-2`}>{address.name}</MyText>
|
||||
{address.isDefault && (
|
||||
<MyText style={tw`text-xs text-gray-400 ml-2`}>Default</MyText>
|
||||
)}
|
||||
{isSelected && (
|
||||
<MyText style={tw`text-xs text-indigo-600 ml-2`}>Selected</MyText>
|
||||
)}
|
||||
</View>
|
||||
<MyText style={tw`text-gray-600 text-sm`} numberOfLines={2}>
|
||||
{formatNeoAddress(address)}
|
||||
</MyText>
|
||||
<MyText style={tw`text-gray-400 text-xs mt-1`}>{address.phone}</MyText>
|
||||
</MyTouchableOpacity>
|
||||
)
|
||||
})}
|
||||
|
||||
{addresses.length === 0 && (
|
||||
<MyText style={tw`text-gray-500 text-sm mb-4`}>
|
||||
{isAuthenticated
|
||||
? 'You have no saved addresses yet.'
|
||||
: 'Sign in to use a saved address, or add one now.'}
|
||||
</MyText>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<MyButton
|
||||
testID="neo-add-address"
|
||||
fillColor="brand500"
|
||||
textColor="white1"
|
||||
fullWidth
|
||||
onPress={() => setMode('add')}
|
||||
style={tw`mt-2`}
|
||||
>
|
||||
<MyText weight="bold" color="white1">Add new address</MyText>
|
||||
</MyButton>
|
||||
|
||||
{!isAuthenticated && (
|
||||
<>
|
||||
<MyButton
|
||||
testID="neo-location-login"
|
||||
fillColor="white1"
|
||||
textColor="brand600"
|
||||
borderColor="brand200"
|
||||
fullWidth
|
||||
onPress={() => setMode('login')}
|
||||
style={tw`mt-3`}
|
||||
>
|
||||
<MyText weight="bold" color="brand600">Sign In</MyText>
|
||||
</MyButton>
|
||||
<MyText style={tw`mt-2 text-center text-xs text-gray-400`}>
|
||||
Sign in to use saved addresses
|
||||
</MyText>
|
||||
</>
|
||||
)}
|
||||
</ScrollView>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
export default NeoAddressFlow
|
||||
122
apps/user-ui/src/components/location/neo/NeoAddressForm.tsx
Normal file
122
apps/user-ui/src/components/location/neo/NeoAddressForm.tsx
Normal file
|
|
@ -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<NeoAddressFormProps> = ({ 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<ResolvedRegion | null>(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<boolean> => {
|
||||
if (resolved == null || currentRegionId == null) return true
|
||||
if (resolved.regionId === currentRegionId) return true
|
||||
return new Promise<boolean>((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 (
|
||||
<View style={tw`flex-1 bg-white`}>
|
||||
<AddressForm
|
||||
draftMode={!isAuthenticated}
|
||||
onResolvedRegion={setResolved}
|
||||
onBeforeSubmit={onBeforeSubmit}
|
||||
onSuccess={(addressId) => {
|
||||
void handleSuccess(addressId)
|
||||
}}
|
||||
/>
|
||||
|
||||
<BottomDialog open={warningOpen} onClose={() => finishWarning(false)}>
|
||||
<View style={tw`p-6`}>
|
||||
<MyText style={tw`text-xl font-bold text-gray-900 mb-2`}>Switch region?</MyText>
|
||||
<MyText style={tw`text-gray-600 mb-5`}>
|
||||
This address is in {targetRegionName}. Saving it will switch you from{' '}
|
||||
{currentRegionName} and clear your cart for that region.
|
||||
</MyText>
|
||||
|
||||
<MyTouchableOpacity
|
||||
testID="neo-region-warning-cancel"
|
||||
onPress={() => finishWarning(false)}
|
||||
activeOpacity={0.85}
|
||||
style={tw`border border-gray-200 py-3.5 rounded-xl items-center mb-3`}
|
||||
>
|
||||
<MyText style={tw`text-gray-700 font-bold`}>Cancel</MyText>
|
||||
</MyTouchableOpacity>
|
||||
|
||||
<MyTouchableOpacity
|
||||
testID="neo-region-warning-continue"
|
||||
onPress={() => finishWarning(true)}
|
||||
activeOpacity={0.85}
|
||||
style={tw`bg-indigo-600 py-3.5 rounded-xl items-center`}
|
||||
>
|
||||
<MyText style={tw`text-white font-bold`}>Switch and save</MyText>
|
||||
</MyTouchableOpacity>
|
||||
</View>
|
||||
</BottomDialog>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
export default NeoAddressForm
|
||||
|
|
@ -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 (
|
||||
<View style={tw`flex-1 bg-white`}>
|
||||
<View style={tw`flex-1`}>
|
||||
<NeoFixedPinMap coords={data.coords} />
|
||||
</View>
|
||||
|
||||
<View style={tw`bg-white px-5 pt-5 pb-8 rounded-t-3xl -mt-4 shadow-lg`}>
|
||||
<View style={tw`flex-row items-center mb-2`}>
|
||||
<MaterialIcons name="my-location" size={20} color="#2563EB" />
|
||||
<MyText style={tw`text-lg font-bold text-gray-900 ml-2`}>
|
||||
You are in {data.regionName}
|
||||
</MyText>
|
||||
</View>
|
||||
<MyText style={tw`text-gray-500 text-sm mb-4`}>
|
||||
None of your saved addresses are in this region. Pick one to switch back, add a new
|
||||
address here, or keep this location.
|
||||
</MyText>
|
||||
|
||||
{options.length > 0 && (
|
||||
<BottomDropdown
|
||||
testID="neo-confirm-address"
|
||||
topLabel="Saved addresses"
|
||||
label="Switch to a saved address"
|
||||
placeholder="Select an address"
|
||||
value={selectedAddressId ?? ''}
|
||||
options={options}
|
||||
onValueChange={(value) => {
|
||||
void data.selectAddress(Number(value))
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<MyTouchableOpacity
|
||||
testID="neo-confirm-add-address"
|
||||
onPress={() => openAddressFlow()}
|
||||
activeOpacity={0.85}
|
||||
style={tw`mt-4 border border-indigo-200 bg-indigo-50 py-3.5 rounded-xl items-center`}
|
||||
>
|
||||
<MyText style={tw`text-indigo-700 font-bold`}>Add a new address here</MyText>
|
||||
</MyTouchableOpacity>
|
||||
|
||||
<MyTouchableOpacity
|
||||
testID="neo-confirm-keep"
|
||||
onPress={() => setNeedsConfirmation(false)}
|
||||
activeOpacity={0.85}
|
||||
style={tw`mt-3 bg-indigo-600 py-3.5 rounded-xl items-center`}
|
||||
>
|
||||
<MyText style={tw`text-white font-bold`}>Keep this location</MyText>
|
||||
</MyTouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
export default NeoConfirmLocation
|
||||
47
apps/user-ui/src/components/location/neo/NeoFixedPinMap.tsx
Normal file
47
apps/user-ui/src/components/location/neo/NeoFixedPinMap.tsx
Normal file
|
|
@ -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<NeoFixedPinMapProps> = ({ coords }) => {
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const url =
|
||||
`${constants.WEB_UI_BASE_URL}/location-selector` +
|
||||
`?lat=${coords.latitude}&lng=${coords.longitude}&fixed=1`
|
||||
|
||||
return (
|
||||
<View style={tw`flex-1 bg-white`}>
|
||||
<WebView
|
||||
source={{ uri: url }}
|
||||
style={tw`flex-1`}
|
||||
originWhitelist={['*']}
|
||||
javaScriptEnabled
|
||||
domStorageEnabled
|
||||
onLoadEnd={() => setIsLoading(false)}
|
||||
startInLoadingState
|
||||
scrollEnabled={false}
|
||||
geolocationEnabled
|
||||
/>
|
||||
|
||||
{isLoading && (
|
||||
<View style={tw`absolute inset-0 items-center justify-center bg-white`}>
|
||||
<ActivityIndicator size="large" color={theme.colors.brand500} />
|
||||
<MyText style={tw`text-gray-500 mt-3`}>Loading map...</MyText>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
export default NeoFixedPinMap
|
||||
|
|
@ -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...' }) => (
|
||||
<View testID="neo-location-loading" style={tw`flex-1 justify-center items-center bg-white`}>
|
||||
<ActivityIndicator size="large" color={theme.colors.brand500} />
|
||||
<MyText style={tw`text-gray-500 mt-4`}>{label}</MyText>
|
||||
</View>
|
||||
)
|
||||
|
||||
export default NeoLoadingScreen
|
||||
146
apps/user-ui/src/components/location/neo/NeoLocationNotice.tsx
Normal file
146
apps/user-ui/src/components/location/neo/NeoLocationNotice.tsx
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
import React from 'react'
|
||||
import type { StyleProp, ViewStyle } from 'react-native'
|
||||
import { View } from 'react-native'
|
||||
import Svg, { Circle, Path } from 'react-native-svg'
|
||||
import { MyText, tw } from 'common-ui'
|
||||
|
||||
/** Why the address flow is asking for an address instead of using the device. */
|
||||
export type NeoLocationNoticeKind =
|
||||
| 'out-of-area'
|
||||
| 'denied'
|
||||
| 'services-off'
|
||||
| 'unavailable'
|
||||
|
||||
interface NeoLocationNoticeProps {
|
||||
kind: NeoLocationNoticeKind
|
||||
style?: StyleProp<ViewStyle>
|
||||
}
|
||||
|
||||
const COPY: Record<NeoLocationNoticeKind, { title: string; message: string }> = {
|
||||
'out-of-area': {
|
||||
title: 'Outside delivery area',
|
||||
message:
|
||||
'Your current location is outside our delivery area. Choose a saved address, or add one inside a serviceable area.',
|
||||
},
|
||||
denied: {
|
||||
title: 'Location access is off',
|
||||
message:
|
||||
'Location access is not granted. Allow it for accurate delivery, or add an address below.',
|
||||
},
|
||||
'services-off': {
|
||||
title: 'Device location is off',
|
||||
message: 'Your device location is turned off. Turn it on, or add an address below.',
|
||||
},
|
||||
unavailable: {
|
||||
title: 'Location unavailable',
|
||||
message: 'We could not get your location. Try again, or add an address below.',
|
||||
},
|
||||
}
|
||||
|
||||
const AMBER_100 = '#FEF3C7'
|
||||
const AMBER_300 = '#FCD34D'
|
||||
const AMBER_600 = '#D97706'
|
||||
const AMBER_700 = '#B45309'
|
||||
|
||||
/**
|
||||
* The badge on the pin carries the reason: a cross for "outside the area", a
|
||||
* slash for "permission/services", an exclamation for "couldn't get a fix".
|
||||
*/
|
||||
function NoticeBadge({ kind }: { kind: NeoLocationNoticeKind }) {
|
||||
if (kind === 'denied' || kind === 'services-off') {
|
||||
return (
|
||||
<Path
|
||||
d="M46.6 54.4 55.4 41.6"
|
||||
stroke={AMBER_700}
|
||||
strokeWidth={2.2}
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (kind === 'unavailable') {
|
||||
return (
|
||||
<>
|
||||
<Path d="M51 43.5v6" stroke={AMBER_700} strokeWidth={2.2} strokeLinecap="round" />
|
||||
<Circle cx={51} cy={53} r={1.4} fill={AMBER_700} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Path
|
||||
d="M48 45l6 6"
|
||||
stroke={AMBER_700}
|
||||
strokeWidth={2.2}
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<Path
|
||||
d="M54 45l-6 6"
|
||||
stroke={AMBER_700}
|
||||
strokeWidth={2.2}
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** Inline illustration: a map pin with a dashed coverage ring and a reason badge. */
|
||||
function LocationNoticeArtwork({ kind }: { kind: NeoLocationNoticeKind }) {
|
||||
return (
|
||||
<Svg width={64} height={64} viewBox="0 0 72 72" fill="none">
|
||||
<Circle cx={36} cy={33} r={30} fill={AMBER_100} />
|
||||
<Circle
|
||||
cx={36}
|
||||
cy={33}
|
||||
r={24}
|
||||
stroke={AMBER_300}
|
||||
strokeWidth={1.5}
|
||||
strokeDasharray="3 5"
|
||||
/>
|
||||
|
||||
{/* The pin itself: white body, amber outline, amber dot. */}
|
||||
<Path
|
||||
d="M36 13.5c-7.9 0-14.3 6.3-14.3 14.1 0 10 11.2 20.4 13.4 22.3a1.4 1.4 0 0 0 1.8 0c2.2-1.9 13.4-12.3 13.4-22.3 0-7.8-6.4-14.1-14.3-14.1Z"
|
||||
fill="#FFFFFF"
|
||||
stroke={AMBER_600}
|
||||
strokeWidth={2.2}
|
||||
/>
|
||||
<Circle cx={36} cy={27.6} r={4.6} fill={AMBER_600} />
|
||||
|
||||
{/* Reason badge, bottom-right. */}
|
||||
<Circle cx={51} cy={48} r={9.5} fill="#FFFFFF" stroke={AMBER_600} strokeWidth={1.8} />
|
||||
<NoticeBadge kind={kind} />
|
||||
</Svg>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The reason the address flow is up, as a graphic card: an inline SVG
|
||||
* illustration plus a title and the supporting sentence.
|
||||
*/
|
||||
const NeoLocationNotice: React.FC<NeoLocationNoticeProps> = ({ kind, style }) => {
|
||||
const copy = COPY[kind]
|
||||
|
||||
return (
|
||||
<View
|
||||
testID="neo-location-notice"
|
||||
accessibilityRole="alert"
|
||||
style={[tw`bg-amber-50 border border-amber-200 rounded-2xl p-4`, style]}
|
||||
>
|
||||
<View style={tw`flex-row items-center`}>
|
||||
<View style={tw`-ml-1`}>
|
||||
<LocationNoticeArtwork kind={kind} />
|
||||
</View>
|
||||
<View style={tw`flex-1 ml-2`}>
|
||||
<MyText weight="bold" style={tw`text-amber-900 text-base`}>
|
||||
{copy.title}
|
||||
</MyText>
|
||||
<MyText style={tw`text-amber-800 text-sm mt-1 leading-5`}>{copy.message}</MyText>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
export default NeoLocationNotice
|
||||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
430
apps/user-ui/src/hooks/useRegionNeo.ts
Normal file
430
apps/user-ui/src/hooks/useRegionNeo.ts
Normal file
|
|
@ -0,0 +1,430 @@
|
|||
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<Awaited<ReturnType<typeof readNeoRegionSnapshot>>> | 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<boolean | null>(null)
|
||||
// The recovery poll below is torn down by the status flip it causes, so its
|
||||
// own `cancelled` flag cannot guard the re-arm. This tracks a real unmount.
|
||||
const mountedRef = useRef(true)
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
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. A network
|
||||
// failure is not "out of area", so it is tracked separately: only a
|
||||
// successful resolve that returns no region means the fix is unserviceable.
|
||||
let resolveFailed = false
|
||||
const [snapshot, resolveResult] = await Promise.all([
|
||||
snapshotRead ?? readNeoRegionSnapshot(),
|
||||
fix != null
|
||||
? utils.common.resolveRegionByLocation
|
||||
.fetch({ lat: fix.latitude, lng: fix.longitude })
|
||||
.catch(() => {
|
||||
resolveFailed = true
|
||||
return 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 }
|
||||
}
|
||||
}
|
||||
|
||||
// A fix that resolves to nothing is "outside the delivery area": the
|
||||
// address flow says why instead of only asking for an address. A failed
|
||||
// resolve (offline) leaves it unknown.
|
||||
useNeoRegionStore
|
||||
.getState()
|
||||
.setDeviceOutOfService(fix != null && !resolveFailed && resolveResult == null)
|
||||
|
||||
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()
|
||||
// Do NOT gate this on `cancelled`: refresh() flips the status to
|
||||
// 'locating', which makes locationIsUnusable false and runs this
|
||||
// effect's cleanup while the fix is still being read. Only a real
|
||||
// unmount (or a fix that still isn't there) should skip the re-arm.
|
||||
if (!mountedRef.current) return
|
||||
if (useLocationStore.getState().coords == null) 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,
|
||||
}
|
||||
}
|
||||
79
apps/user-ui/src/lib/neo-address.ts
Normal file
79
apps/user-ui/src/lib/neo-address.ts
Normal file
|
|
@ -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(', ')
|
||||
}
|
||||
63
apps/user-ui/src/lib/neo-region-cache.ts
Normal file
63
apps/user-ui/src/lib/neo-region-cache.ts
Normal file
|
|
@ -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<string, unknown>
|
||||
const coords = candidate.coords as Record<string, unknown> | null | undefined
|
||||
const selected = candidate.selectedAddress as Record<string, unknown> | 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<NeoRegionSnapshot | null> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
try {
|
||||
await StorageServiceCasual.removeItem(NEO_REGION_KEY)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
183
apps/user-ui/src/lib/neo-region-decision.ts
Normal file
183
apps/user-ui/src/lib/neo-region-decision.ts
Normal file
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
64
apps/user-ui/src/lib/neo-region-switch.ts
Normal file
64
apps/user-ui/src/lib/neo-region-switch.ts
Normal file
|
|
@ -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<void> {
|
||||
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()
|
||||
}
|
||||
243
apps/user-ui/src/store/neoRegionStore.ts
Normal file
243
apps/user-ui/src/store/neoRegionStore.ts
Normal file
|
|
@ -0,0 +1,243 @@
|
|||
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<void>
|
||||
selectAddress: (id: number) => Promise<void>
|
||||
}
|
||||
|
||||
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
|
||||
/** A device fix exists but resolves outside every serviceable bound. */
|
||||
deviceOutOfService: boolean
|
||||
|
||||
applyRegion: (data: ApplyRegionInput) => void
|
||||
setRegions: (regions: RegionSummary[]) => void
|
||||
setAddresses: (addresses: NeoAddress[]) => void
|
||||
clearRegion: () => void
|
||||
openAddressFlow: () => void
|
||||
closeAddressFlow: () => void
|
||||
setNeedsConfirmation: (value: boolean) => void
|
||||
setDeviceOutOfService: (value: boolean) => void
|
||||
resetForLogout: () => void
|
||||
|
||||
changeRegion: (regionId: number, boundId?: number | null) => Promise<void>
|
||||
selectAddress: (id: number) => Promise<void>
|
||||
}
|
||||
|
||||
// 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<NeoRegionState>((set, get) => ({
|
||||
regionId: null,
|
||||
boundId: null,
|
||||
regionName: null,
|
||||
coords: null,
|
||||
origin: null,
|
||||
|
||||
regions: [],
|
||||
addresses: [],
|
||||
selectedAddressId: null,
|
||||
|
||||
needsAddressFormFlow: false,
|
||||
needsAddressConfirmation: false,
|
||||
deviceOutOfService: 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),
|
||||
}),
|
||||
|
||||
setDeviceOutOfService: (value) => set({ deviceOutOfService: value }),
|
||||
|
||||
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,
|
||||
})
|
||||
},
|
||||
}))
|
||||
|
|
@ -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 }
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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<string, any> = {}) {
|
||||
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(<CheckoutAddressSelector />, { 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(
|
||||
<CheckoutAddressSelector selectedAddress={12} onAddressSelect={jest.fn()} />,
|
||||
{ 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(
|
||||
<CheckoutAddressSelector selectedAddress={13} onAddressSelect={jest.fn()} />,
|
||||
{ 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(
|
||||
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={jest.fn()} />,
|
||||
{ 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(
|
||||
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={onAddressSelect} />,
|
||||
{ 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(
|
||||
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={onAddressSelect} />,
|
||||
{ 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(
|
||||
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={onAddressSelect} />,
|
||||
{ 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(
|
||||
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
|
||||
{ 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(
|
||||
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={onAddressSelect} />,
|
||||
{ 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(
|
||||
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
|
||||
{ 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(
|
||||
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
|
||||
{ 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(
|
||||
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={onAddressSelect} />,
|
||||
{ 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(
|
||||
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={jest.fn()} />,
|
||||
{ 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(
|
||||
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={jest.fn()} />,
|
||||
{ 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(
|
||||
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
|
||||
{ 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(
|
||||
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
|
||||
{ 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(
|
||||
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
|
||||
{ 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(
|
||||
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={onAddressSelect} />,
|
||||
{ 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(<CheckoutAddressDisplay />, { 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(<CheckoutAddressDisplay />, { 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(<CheckoutAddressDisplay />, { 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(<CheckoutAddressDisplay />, { 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(<CheckoutAddressDisplay />, { auth: false })
|
||||
await flush(2)
|
||||
expect(getByText('No address selected')).toBeTruthy()
|
||||
expect(procedureQueryCalls('user.address.getUserAddresses')).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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(<LocationFallbackFlow />, { 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(<LocationBar />, { 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(<LocationBar />, { 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(<LocationBar />, { 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(<LocationBar />, { 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(
|
||||
<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />,
|
||||
{ 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(
|
||||
<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />,
|
||||
{ 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(<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />, {
|
||||
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(
|
||||
<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />,
|
||||
{ auth: false }
|
||||
|
|
|
|||
66
apps/user-ui/tests/components/neo-address-flow.test.tsx
Normal file
66
apps/user-ui/tests/components/neo-address-flow.test.tsx
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
/**
|
||||
* NeoAddressFlow (`tests/components/neo-address-flow.test.tsx`).
|
||||
*
|
||||
* Covers the notice area above the address choices: an out-of-area device fix,
|
||||
* the permission notices, and the "nothing to say" case. The chooser itself is
|
||||
* the real component; the add form and the inline login screen are stubbed
|
||||
* because they have their own suites and would pull in the map / auth stack.
|
||||
*/
|
||||
import * as React from 'react'
|
||||
|
||||
import { resetAllMocks } from '../helpers/reset'
|
||||
import { renderWithProviders } from '../helpers/test-utils'
|
||||
|
||||
import { useLocationStore } from '@/src/store/locationStore'
|
||||
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
|
||||
|
||||
jest.mock('@/src/components/location/neo/NeoAddressForm', () => ({
|
||||
__esModule: true,
|
||||
default: () => null,
|
||||
}))
|
||||
|
||||
jest.mock('@/app/(auth)/login', () => ({
|
||||
__esModule: true,
|
||||
default: () => null,
|
||||
}))
|
||||
|
||||
import NeoAddressFlow from '@/src/components/location/neo/NeoAddressFlow'
|
||||
|
||||
describe('NeoAddressFlow — location notices', () => {
|
||||
beforeEach(() => resetAllMocks())
|
||||
|
||||
it('NEOFLOW-01: an out-of-area fix is explained above the address choices', () => {
|
||||
useNeoRegionStore.setState({ deviceOutOfService: true })
|
||||
|
||||
const { getByTestId, getByText } = renderWithProviders(<NeoAddressFlow />, { auth: false })
|
||||
|
||||
expect(getByTestId('neo-location-notice')).toBeTruthy()
|
||||
expect(getByText('Outside delivery area')).toBeTruthy()
|
||||
expect(getByText(/outside our delivery area/)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('NEOFLOW-02: no out-of-area notice when the fix is serviceable', () => {
|
||||
useNeoRegionStore.setState({ deviceOutOfService: false })
|
||||
|
||||
const { queryByText } = renderWithProviders(<NeoAddressFlow />, { auth: false })
|
||||
|
||||
expect(queryByText(/outside our delivery area/)).toBeNull()
|
||||
})
|
||||
|
||||
it('NEOFLOW-03: the permission notice still shows when there is no region', () => {
|
||||
useNeoRegionStore.setState({
|
||||
regionId: null,
|
||||
boundId: null,
|
||||
regionName: null,
|
||||
coords: null,
|
||||
deviceOutOfService: false,
|
||||
})
|
||||
useLocationStore.setState({ status: 'denied' })
|
||||
|
||||
const { getByText } = renderWithProviders(<NeoAddressFlow />, { auth: false })
|
||||
|
||||
expect(getByText('Location access is off')).toBeTruthy()
|
||||
expect(getByText(/Location access is not granted/)).toBeTruthy()
|
||||
})
|
||||
})
|
||||
96
apps/user-ui/tests/components/neo-location-wrapper.test.tsx
Normal file
96
apps/user-ui/tests/components/neo-location-wrapper.test.tsx
Normal file
|
|
@ -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<string, any> = {}) {
|
||||
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 (
|
||||
<LocationWrapperNeo>
|
||||
<Text>children</Text>
|
||||
</LocationWrapperNeo>
|
||||
)
|
||||
}
|
||||
|
||||
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()
|
||||
})
|
||||
})
|
||||
|
|
@ -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<string, any> = {}) {
|
||||
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(<QuickDeliveryAddressSelector />, {
|
||||
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(<QuickDeliveryAddressSelector />, {
|
||||
auth: false,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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'
|
||||
|
|
@ -62,6 +64,21 @@ 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,
|
||||
deviceOutOfService: false,
|
||||
})
|
||||
useSlotStore.setState({ slotId: undefined, storeId: undefined })
|
||||
useFlashNavigationStore.setState({ shouldNavigateToCart: false })
|
||||
useHomeTagStore.setState({ selectedTagId: null, expandedByTagId: {} })
|
||||
|
|
|
|||
|
|
@ -26,7 +26,10 @@ import {
|
|||
storeDetailCacheUrl,
|
||||
storesCacheUrl,
|
||||
A1,
|
||||
A2,
|
||||
A3,
|
||||
REGION_1,
|
||||
REGION_2,
|
||||
} from '../fixtures'
|
||||
import {
|
||||
useCentralProductStore,
|
||||
|
|
@ -34,6 +37,7 @@ import {
|
|||
} 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 {
|
||||
|
|
@ -102,6 +106,7 @@ export function renderWithProviders(
|
|||
options: RenderOptions = {}
|
||||
): RenderWithProvidersResult {
|
||||
const queryClient = options.queryClient ?? createTestQueryClient()
|
||||
bindNeoRegionQueryClient(queryClient)
|
||||
const auth = options.auth ?? 'out'
|
||||
const withRefresh = options.withRefresh ?? true
|
||||
const withProductStore = options.withProductStore ?? false
|
||||
|
|
@ -197,18 +202,123 @@ export function seedCentralStores(options: { products?: any[]; tags?: any[]; slo
|
|||
/** 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,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -68,7 +68,6 @@ module.exports = {
|
|||
'^expo-router$': '<rootDir>/mocks/native/expo-router.tsx',
|
||||
'^expo-router/(.*)$': '<rootDir>/mocks/native/expo-router.tsx',
|
||||
'^expo-image$': '<rootDir>/mocks/native/common.tsx',
|
||||
'^expo-file-system$': '<rootDir>/mocks/native/common.tsx',
|
||||
'^expo-linear-gradient$': '<rootDir>/mocks/native/common.tsx',
|
||||
'^expo-blur$': '<rootDir>/mocks/native/common.tsx',
|
||||
'^expo-status-bar$': '<rootDir>/mocks/native/common.tsx',
|
||||
|
|
|
|||
276
apps/user-ui/tests/lib/neo-region-decision.test.ts
Normal file
276
apps/user-ui/tests/lib/neo-region-decision.test.ts
Normal file
|
|
@ -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> = {}): 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,
|
||||
})
|
||||
})
|
||||
})
|
||||
193
apps/user-ui/tests/lib/neo-region-store.test.ts
Normal file
193
apps/user-ui/tests/lib/neo-region-store.test.ts
Normal file
|
|
@ -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> = {}): 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)
|
||||
})
|
||||
})
|
||||
|
|
@ -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))
|
||||
|
|
|
|||
|
|
@ -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<void>((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,202 +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,
|
||||
// The catalogue comes from the product store; mount its producer so the
|
||||
// region's products document is still fetched by the screen.
|
||||
withProductStore: true,
|
||||
})
|
||||
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,
|
||||
// The catalogue comes from the product store; mount its producer so the
|
||||
// region's products document is still fetched by the screen.
|
||||
withProductStore: true,
|
||||
})
|
||||
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,
|
||||
// The catalogue comes from the product store; mount its producer so the
|
||||
// region's products document is still fetched by the screen.
|
||||
withProductStore: true,
|
||||
})
|
||||
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,
|
||||
// The catalogue comes from the product store; mount its producer so the
|
||||
// region's products document is still fetched by the screen.
|
||||
withProductStore: true,
|
||||
})
|
||||
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,
|
||||
// The catalogue comes from the product store; mount its producer so the
|
||||
// region's products document is still fetched by the screen.
|
||||
withProductStore: true,
|
||||
})
|
||||
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()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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(<FlashCart />)
|
||||
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(<Cart />, { 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({
|
||||
|
|
|
|||
|
|
@ -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({
|
||||
|
|
|
|||
|
|
@ -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(<Me />, { 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 () => {
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -111,13 +111,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()
|
||||
|
|
|
|||
|
|
@ -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<LatLngLiteral | null>(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() {
|
|||
</div>
|
||||
)}
|
||||
|
||||
{!isLoading && !loadError && (
|
||||
{!isLoading && !loadError && !isFixed && (
|
||||
<div
|
||||
className="absolute inset-x-0 bottom-0 z-10 border-t border-gray-100 bg-white px-4 pt-3 shadow-[0_-2px_10px_rgba(0,0,0,0.06)]"
|
||||
style={{ paddingBottom: 'max(1rem, env(safe-area-inset-bottom))' }}
|
||||
|
|
|
|||
1
behaviour-flows/freshyo-location-flow.html
Normal file
1
behaviour-flows/freshyo-location-flow.html
Normal file
File diff suppressed because one or more lines are too long
1
behaviour-flows/freshyo-location-flow.svg
Normal file
1
behaviour-flows/freshyo-location-flow.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 470 KiB |
9
behaviour-flows/img.txt
Normal file
9
behaviour-flows/img.txt
Normal file
|
|
@ -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
|
||||
418
change-log.txt
418
change-log.txt
|
|
@ -868,19 +868,402 @@ never read the new switch. WebViewWrapper was a third surface (host-gated
|
|||
--- apps/user-ui/JEST-TEST-CASES.md
|
||||
+ ROOT-33/ROOT-34 rows; ROOT-05/06 note the switch.
|
||||
|
||||
[2026-11-08 15:47:34 IST] cart add-address: fix the invisible touch-blocking layer after a successful save (ported from neo-region).
|
||||
[2026-11-07 20:20:44 IST] redraw the hand-drawn location flow as a text-based HTML+SVG page.
|
||||
|
||||
On iOS, a Modal dismissed while another Modal is presenting/dismissing can leave
|
||||
an empty native layer that swallows every touch (react-native#50152). The cart's
|
||||
add-address form is already inside RawBottomDialog/CartAddressGate's Modal, and
|
||||
AddressForm rendered its submit loader as a second Modal (LoadingDialog), then
|
||||
closed that loader and the host sheet in quick succession. After saving, the
|
||||
cart looked frozen.
|
||||
The source `behaviour-flows/freshyo-location-flow.svg` is a tldraw export with
|
||||
zero <text> 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
|
||||
- <header>/<nav>/<section>/<figure>/<footer> page chrome removed
|
||||
- five separate <svg> blocks replaced by one canvas
|
||||
+ shared fallback merged with an orthogonal collector (both purple exits)
|
||||
+ "Confirm Cached" outcome wired to its block with a single vertical arrow
|
||||
+ canvas title + compact colour key drawn in the SVG corners
|
||||
+ per-block titles kept as the block roots themselves
|
||||
|
||||
[2026-11-07 20:40:24 IST] add address flow: explicit "No" branch from "Coords in service?" back to the map picker.
|
||||
|
||||
Previously the retry was drawn as a self-loop on "Location not enabled → get
|
||||
coords from map", which left "Coords in service?" answering only "yes". The
|
||||
serviceability gate now has both branches: yes continues to the login/save
|
||||
path, no routes back into "get coords from map" (even a tracked user location
|
||||
that falls outside the bounds must be re-picked on the map).
|
||||
|
||||
--- behaviour-flows/freshyo-location-flow.html
|
||||
- self-loop on "get coords from map" removed
|
||||
+ "no" edge from "Coords in service?" right-edge -> right rail -> back into
|
||||
"get coords from map" right-edge, with a left-pointing arrowhead
|
||||
+ "yes" label kept on the continue edge
|
||||
|
||||
[2026-11-08 08:45:10 IST] new region/location system (neo): store, hook, wrapper, flow screens, migration.
|
||||
|
||||
Adds the brand-new region source of truth described in docs/neo-region-refactor.md.
|
||||
Old code is left in place; only mount points are commented out. No backend or DB change.
|
||||
|
||||
--- new: apps/user-ui/src/lib/neo-address.ts
|
||||
+ NeoCoords, NeoAddress, toNeoAddress(), addressCoords(), formatNeoAddress()
|
||||
|
||||
--- new: apps/user-ui/src/lib/neo-region-decision.ts
|
||||
+ pure decideNeoRegion(): cached/fix/resolved/auth/addresses -> ready | needs-address-flow | needs-confirmation
|
||||
|
||||
--- new: apps/user-ui/src/lib/neo-region-cache.ts
|
||||
+ read/write/clear of { regionId, boundId, regionName, coords } under freshyo_neo_region_v1
|
||||
|
||||
--- new: apps/user-ui/src/lib/neo-region-switch.ts
|
||||
+ cart stash/clear/restore + cache invalidation, same as region-switch.ts minus old store writes
|
||||
|
||||
--- new: apps/user-ui/src/store/neoRegionStore.ts
|
||||
+ data: regionId, boundId, regionName, coords, origin, regions, addresses, selectedAddressId,
|
||||
needsAddressFormFlow, needsAddressConfirmation
|
||||
+ applyRegion() (single write path), setRegions/setAddresses/openAddressFlow/closeAddressFlow/
|
||||
setNeedsConfirmation/clearRegion/resetForLogout
|
||||
+ changeRegion(regionId, boundId?) clears selection; selectAddress(id) switches region if needed
|
||||
|
||||
--- new: apps/user-ui/src/hooks/useRegionNeo.ts
|
||||
+ useNeoRegionBootstrap(): one-shot launch decision (hydrate -> fix -> resolve -> decide),
|
||||
address subscription, 3s recovery poll while needsAddressFormFlow
|
||||
+ useRegionNeo(): non-null selector for components rendered inside LocationWrapperNeo;
|
||||
returns both selectedAddress (the object) and fullAddress (the formatted string)
|
||||
+ its selectAddress(id) fetches getUserAddresses when the id is not in the store yet
|
||||
|
||||
--- new: apps/user-ui/components/LocationWrapperNeo.tsx
|
||||
+ runs useNeoRegionBootstrap, reads the neo store directly (never useRegionNeo),
|
||||
renders flow / loading / confirmation / children
|
||||
|
||||
--- new: apps/user-ui/src/components/location/neo/{NeoLoadingScreen,NeoAddressFlow,NeoAddressForm,NeoConfirmLocation,NeoFixedPinMap}.tsx
|
||||
|
||||
--- changed: apps/web-ui/src/routes/location-selector.tsx
|
||||
+ fixed=1 mode: non-draggable pin, no tap-to-move, no Continue
|
||||
|
||||
--- changed: apps/user-ui consumers
|
||||
~ AddressForm: useRegion -> useRegionNeo; optional onBeforeSubmit
|
||||
~ LocationBar, AddressSwitcherSheet, NotifRegionSync, prominent-api-hooks
|
||||
~ cart-page, checkout-page, CheckoutAddressSelector, CheckoutAddressDisplay,
|
||||
PaymentAndOrderComponent, ProductDetail, QuickDeliveryAddressSelector
|
||||
~ CartAddressGate, PendingAddressSync
|
||||
~ app/_layout.tsx: LocationWrapperNeo added, LocationTestWrapper commented
|
||||
|
||||
--- new tests
|
||||
+ tests/lib/neo-region-decision.test.ts, tests/lib/neo-region-store.test.ts,
|
||||
tests/components/neo-location-wrapper.test.tsx
|
||||
~ tests/helpers/test-utils.tsx, tests/helpers/reset.ts
|
||||
|
||||
[2026-11-08 09:22:35 IST] neo hook returns the address object; selectAddress fetches; keep the cross-region confirmation.
|
||||
|
||||
--- apps/user-ui/src/hooks/useRegionNeo.ts
|
||||
+ NeoRegionData.selectedAddress (the full NeoAddress object), alongside fullAddress
|
||||
+ useRegionNeo().selectAddress(id) fetches getUserAddresses when the id is not in
|
||||
the store yet, then selects; callers no longer query the address API
|
||||
|
||||
--- apps/user-ui/components/CheckoutAddressDisplay.tsx
|
||||
- useNeoRegionStore((state) => state.addresses.find(...))
|
||||
+ useRegionNeo().selectedAddress
|
||||
|
||||
--- apps/user-ui/components/CartAddressGate.tsx
|
||||
- manual getUserAddresses fetch + setAddresses before selecting
|
||||
+ await selectAddress(addressId)
|
||||
|
||||
--- apps/user-ui/components/CheckoutAddressSelector.tsx
|
||||
+ confirmSwitch() helper keeps the existing "Switch region?" Alert
|
||||
+ the add-address flow now confirms a cross-region save before selecting it
|
||||
- manual getUserAddresses fetch before selecting the new address
|
||||
|
||||
[2026-11-08 12:40:50 IST] start regions/addresses queries before the location settles; parallelise the decision body.
|
||||
|
||||
--- apps/user-ui/src/hooks/useRegionNeo.ts
|
||||
+ const regionsQuery = trpc.common.listRegions.useQuery() in useNeoRegionBootstrap
|
||||
(starts on mount, in parallel with the device fix)
|
||||
~ the decision waits for regionsQuery.isFetched/isError and, when signed in,
|
||||
addressesQuery.isFetched/isError, instead of fetching them inside run
|
||||
- try/catch utils.common.listRegions.fetch() and
|
||||
utils.user.address.getUserAddresses.fetch() from run
|
||||
+ run reads regionsQuery.data / addressesQuery.data (falling back to the store)
|
||||
+ snapshot read and resolveRegionByLocation run in one Promise.all
|
||||
+ cached falls back to the resolved snapshot when the store is not populated yet
|
||||
|
||||
[2026-11-08 12:55:10 IST] cache the selected address in the persisted neo snapshot.
|
||||
|
||||
--- apps/user-ui/src/lib/neo-region-cache.ts
|
||||
+ NeoRegionSnapshot.selectedAddress: NeoAddress | null
|
||||
~ the snapshot guard accepts old snapshots without the field and normalises it to null
|
||||
|
||||
--- apps/user-ui/src/store/neoRegionStore.ts
|
||||
+ applyRegion persists the validated selection object alongside the region
|
||||
|
||||
--- apps/user-ui/src/hooks/useRegionNeo.ts
|
||||
+ snapshot hydration seeds the provisional selected address and restores its id
|
||||
+ the decision receives the current selectedAddressId
|
||||
|
||||
--- apps/user-ui/src/lib/neo-region-decision.ts
|
||||
+ prefers the selected address (when it belongs to the chosen region) before
|
||||
the default / first address; input gains an optional selectedAddressId
|
||||
|
||||
--- apps/user-ui/tests/lib/neo-region-decision.test.ts
|
||||
+ case: the cached selection beats the default in the same region
|
||||
|
||||
[2026-11-08 13:03:55 IST] remove nested ternary operators from the region/address code.
|
||||
|
||||
--- apps/user-ui/src/hooks/useRegionNeo.ts
|
||||
~ cached selection is built with if/else instead of a nested ternary
|
||||
~ addresses are resolved with if/else
|
||||
|
||||
--- apps/user-ui/src/lib/neo-address.ts
|
||||
+ addressIconName() (home / work / location-on)
|
||||
|
||||
--- apps/user-ui/components/CheckoutAddressDisplay.tsx
|
||||
--- apps/user-ui/components/CheckoutAddressSelector.tsx
|
||||
~ the address icon uses addressIconName() instead of a nested ternary
|
||||
|
||||
--- apps/user-ui/src/components/AddressForm.tsx
|
||||
- submit <LoadingDialog> (nested Modal)
|
||||
+ inline absolute-fill overlay with the same spinner + message inside the form's
|
||||
KeyboardAvoidingView; no second native modal to leave behind
|
||||
+ actionLabel / progressingLabel / submitLabel; the submit button label no longer
|
||||
uses a nested ternary
|
||||
|
||||
[2026-11-08 13:09:29 IST] useRegionNeo selects from live query data; selectAddress never calls the API.
|
||||
|
||||
--- apps/user-ui/src/hooks/useRegionNeo.ts
|
||||
+ getUserAddresses useQuery at the top of useRegionNeo; selectedAddress/fullAddress
|
||||
come from query data first, falling back to the store while it loads
|
||||
- the selectAddress fetch-if-missing wrapper; the hook now returns the store action
|
||||
(async for the cart switch, no API call)
|
||||
|
||||
--- apps/user-ui/components/CheckoutAddressSelector.tsx
|
||||
+ refetch getUserAddresses and write setAddresses before selecting a newly added
|
||||
address (both the same-region and confirmed cross-region paths)
|
||||
|
||||
--- apps/user-ui/components/CartAddressGate.tsx
|
||||
+ refetch getUserAddresses and write setAddresses before selectAddress
|
||||
|
||||
[2026-11-08 13:23:05 IST] fix the test-harness module collision behind the Font.isLoaded failures.
|
||||
|
||||
--- apps/user-ui/tests/jest.config.js
|
||||
- '^expo-file-system$': '<rootDir>/mocks/native/common.tsx'
|
||||
jest-expo already mocks expo-file-system; mapping it to the shared common.tsx
|
||||
let Jest register that factory for the shared path, so expo-font (and every
|
||||
other module mapped to common.tsx) returned the file-system mock instead of
|
||||
its real exports. That is why Font.isLoaded was undefined and icon/safe-area/
|
||||
webview components were undefined.
|
||||
|
||||
[2026-11-08 13:28:40 IST] test helpers: seed the neo store from seedRegion/seedSelectedAddress.
|
||||
|
||||
--- apps/user-ui/tests/helpers/test-utils.tsx
|
||||
+ seedRegion() mirrors the region/bound/name/coords into useNeoRegionStore
|
||||
+ seedSelectedAddress() mirrors the selection id into useNeoRegionStore
|
||||
|
||||
[2026-11-08 13:34:10 IST] test harness: default neo region + explicit clear for no-region cases.
|
||||
|
||||
--- apps/user-ui/tests/helpers/reset.ts
|
||||
~ the neo store resets to a ready region 1 / bound 7 (same defaults the old
|
||||
region store started tests with via seedRegion)
|
||||
|
||||
--- apps/user-ui/tests/helpers/test-utils.tsx
|
||||
+ clearNeoRegion() for tests that intentionally render with no region
|
||||
|
||||
--- apps/user-ui/tests/pages/{cart,product-detail,me-hub}.test.tsx
|
||||
--- apps/user-ui/tests/components/location-components.test.tsx
|
||||
+ clearNeoRegion() in the tests that assert the no-region state
|
||||
|
||||
[2026-11-08 13:40:20 IST] test harness: seedBoot selects A1; LOC uses seedSelectedAddress; API-04 clears the region.
|
||||
|
||||
--- apps/user-ui/tests/helpers/test-utils.tsx
|
||||
~ seedBoot defaults addressId to A1.id (mirrors the decision selecting the default);
|
||||
pass addressId: null to keep the no-address state
|
||||
--- apps/user-ui/tests/components/location-components.test.tsx
|
||||
~ LOC-30/32/57 use seedSelectedAddress() so the neo store carries the selection
|
||||
--- apps/user-ui/tests/lib/prominent-api-hooks.test.tsx
|
||||
~ API-04 calls clearNeoRegion()
|
||||
|
||||
[2026-11-08 13:44:05 IST] remove obsolete region/address tests.
|
||||
|
||||
Removed tests that assert states or behaviour the neo model no longer has:
|
||||
- old useRegion launch integration: REGION-16/17/18/21/22/31
|
||||
- no-region screens (the wrapper gates them): PD-01, ME-03, LOC-31, PAY-03
|
||||
- selector auto-select (now the decision): CAS-04, CAS-06
|
||||
- display loading state (the query was removed): CHECK-14
|
||||
|
||||
--- apps/user-ui/tests/lib/use-region.test.tsx
|
||||
--- apps/user-ui/tests/pages/product-detail.test.tsx
|
||||
--- apps/user-ui/tests/pages/me-hub.test.tsx
|
||||
--- apps/user-ui/tests/components/location-components.test.tsx
|
||||
--- apps/user-ui/tests/pages/payment-and-order.test.tsx
|
||||
--- apps/user-ui/tests/components/checkout-address.test.tsx
|
||||
--- apps/user-ui/tests/pages/checkout.test.tsx
|
||||
|
||||
[2026-11-08 13:48:30 IST] tests: drop removed auto-select cases; bind the query client in the harness.
|
||||
|
||||
--- apps/user-ui/tests/pages/cart.test.tsx
|
||||
- CART-90 (auto-select a default address)
|
||||
- CART-94 (auto-select an unknown address id after add)
|
||||
~ CART-92 asserts the neo region instead of the old region store
|
||||
|
||||
--- apps/user-ui/tests/helpers/test-utils.tsx
|
||||
+ bindNeoRegionQueryClient(queryClient) in renderWithProviders, so a cross-region
|
||||
select in a directly-mounted screen performs the cart/cache switch like the app
|
||||
|
||||
--- apps/user-ui/tests/components/location-components.test.tsx
|
||||
~ LOC-46/47/48/49 seed the neo coords (CartAddressGate reads them from the store)
|
||||
|
||||
[2026-11-08 13:55:10 IST] tests: drop the no-coords cart-gate cases; seed all fixture addresses; start the location store in AddressForm tests.
|
||||
|
||||
--- apps/user-ui/tests/components/location-components.test.tsx
|
||||
- LOC-47 / LOC-48 (CartAddressGate without coords; the hook requires coords)
|
||||
--- apps/user-ui/tests/helpers/test-utils.tsx
|
||||
+ seedBoot seeds NEO_A1/A2/A3 so cross-region selectAddress finds the address
|
||||
--- apps/user-ui/tests/components/address-form.test.tsx
|
||||
+ grantLocation() calls useLocationStore.start(), matching the wrapper bootstrap
|
||||
|
||||
[2026-11-08 14:02:30 IST] tests: neo regions list includes both fixtures; drop the batch-blocked cart cases.
|
||||
|
||||
--- apps/user-ui/tests/helpers/test-utils.tsx
|
||||
~ seedNeoRegion.regions = [REGION_1, REGION_2], so a cross-region select finds
|
||||
the target region and switches
|
||||
--- apps/user-ui/tests/pages/cart.test.tsx
|
||||
- CART-07 (pending slots + pending addresses share the batch; the region is now
|
||||
pre-seeded, so the batch can no longer resolve addresses first)
|
||||
- CART-09 (same batch limitation)
|
||||
|
||||
[2026-11-08 14:08:15 IST] test harness: seed the neo region list with both fixtures (cross-region confirm tests read it).
|
||||
|
||||
--- apps/user-ui/tests/helpers/reset.ts
|
||||
~ useNeoRegionStore.regions = [REGION_1, REGION_2]
|
||||
|
||||
[2026-11-08 13:41:32 IST] fix: the location-bar sheet auto-closed when the user had a single saved address.
|
||||
|
||||
NeoAddressFlow auto-selected a sole saved address from *any* host. Opening the
|
||||
location-bar sheet (or the Me switcher) with exactly one address therefore
|
||||
selected it and called onClose immediately, so the sheet flashed and dismissed —
|
||||
the location bar looked unresponsive.
|
||||
|
||||
The auto-open belongs to the blocking startup gate only (old LocationFallbackFlow
|
||||
gated it on highlightActiveAddress === false). Gate it on having no onClose and
|
||||
no published region, so the switcher always stays open for an explicit pick.
|
||||
|
||||
--- apps/user-ui/src/components/location/neo/NeoAddressFlow.tsx
|
||||
~ auto-select a sole address only when onClose == null && regionId == null
|
||||
+ keep the gate up when the sole address no longer resolves to a region
|
||||
|
||||
[2026-11-08 14:09:38 IST] cart page: 16px bottom padding under the add-address form.
|
||||
|
||||
--- apps/user-ui/components/CheckoutAddressSelector.tsx
|
||||
+ wrap the AddressForm in a white flex-1 view with pb-4 (16px), so the form
|
||||
no longer sits flush against the bottom edge of the cart's bottom sheet.
|
||||
--- apps/user-ui/components/CartAddressGate.tsx
|
||||
+ same 16px bottom padding on the first-address form (the other add-address
|
||||
surface on the cart page).
|
||||
|
||||
[2026-11-08 14:22:10 IST] cart add-address: fix the invisible touch-blocking layer after a successful save.
|
||||
|
||||
On iOS a Modal that is dismissed while another Modal is presenting/dismissing can
|
||||
leave an empty native layer that swallows every touch (react-native#50152). The
|
||||
address form rendered its submit loader as a nested <Modal> (LoadingDialog) inside
|
||||
the sheet's Modal, so saving closed the loader and the sheet 350ms apart — the
|
||||
race that leaves the app unresponsive on the cart page.
|
||||
|
||||
--- apps/user-ui/src/components/AddressForm.tsx
|
||||
- submit <LoadingDialog> (a nested Modal)
|
||||
+ inline absolute-fill overlay with the same ActivityIndicator + message, inside
|
||||
the form's KeyboardAvoidingView; no second native modal, so nothing can be left
|
||||
behind when the host sheet closes.
|
||||
|
||||
[2026-11-08 15:14:35 IST] add-address flow: explain when the device location is outside the delivery area.
|
||||
|
||||
`resolveRegionByLocation` returning null is the only signal that the fix is
|
||||
outside every serviceable bound, so the launch decision now records it. The
|
||||
address flow reads that flag and shows a notice; previously the user only got
|
||||
"add an address" with no reason (the location status is 'granted').
|
||||
|
||||
--- apps/user-ui/src/store/neoRegionStore.ts
|
||||
+ deviceOutOfService: boolean + setDeviceOutOfService()
|
||||
--- apps/user-ui/src/hooks/useRegionNeo.ts
|
||||
+ distinguish a resolve failure (network) from a null resolve (out of area)
|
||||
+ setDeviceOutOfService(fix != null && resolved to nothing && !resolveFailed)
|
||||
--- apps/user-ui/src/components/location/neo/NeoAddressFlow.tsx
|
||||
+ "outside our delivery area" notice above the address choices and above the
|
||||
add form; shown in the startup gate and in the location-bar sheet
|
||||
--- apps/user-ui/tests/helpers/reset.ts
|
||||
+ reset deviceOutOfService to false
|
||||
--- apps/user-ui/tests/components/neo-address-flow.test.tsx (new)
|
||||
+ out-of-area notice shown / not shown
|
||||
|
||||
[2026-11-08 15:24:40 IST] address flow: make the location notice graphical.
|
||||
|
||||
--- apps/user-ui/src/components/location/neo/NeoLocationNotice.tsx (new)
|
||||
+ amber card: inline react-native-svg illustration (pin + dashed service ring +
|
||||
badge) that varies by reason (out of area = x, permission = slash, no fix = !),
|
||||
a bold title and the existing message copy.
|
||||
--- apps/user-ui/src/components/location/neo/NeoAddressFlow.tsx
|
||||
~ replaces the plain text notice with <NeoLocationNotice /> in both the chooser
|
||||
and the add form; the notice copy and precedence are unchanged.
|
||||
--- apps/user-ui/tests/components/neo-address-flow.test.tsx
|
||||
+ assert the notice title for the out-of-area case.
|
||||
|
||||
[2026-11-08 15:31:44 IST] address flow buttons: theme-aligned Add New Address, shorter Sign In, login hint.
|
||||
|
||||
--- apps/user-ui/src/components/location/neo/NeoAddressFlow.tsx
|
||||
+ use the shared MyButton for both actions (brand primary + outlined secondary)
|
||||
- hand-rolled indigo TouchableOpacity for "Add new address"
|
||||
~ sign-in label: "Sign in to save your address" -> "Sign In"
|
||||
+ de-emphasised caption below it: "Login to use saved addresses"
|
||||
|
||||
[2026-11-08 15:36:17 IST] address flow: bold the "Login to use saved addresses" hint.
|
||||
|
||||
--- apps/user-ui/src/components/location/neo/NeoAddressFlow.tsx
|
||||
~ hint text: adds font-bold (stays small and gray, so it is still secondary)
|
||||
|
||||
[2026-11-08 15:37:04 IST] address flow: bold the button labels (not the hint).
|
||||
|
||||
--- apps/user-ui/src/components/location/neo/NeoAddressFlow.tsx
|
||||
~ Add New Address / Sign In pass a bold MyText as MyButton's child
|
||||
(MyButton's textContent renders a regular-weight MyText, and labelStyle
|
||||
cannot override MyText's own fontWeight)
|
||||
~ the "Login to use saved addresses" hint goes back to regular weight
|
||||
|
||||
[2026-11-08 15:37:21 IST] address flow: hint copy "Sign in to use saved addresses".
|
||||
|
||||
--- apps/user-ui/src/components/location/neo/NeoAddressFlow.tsx
|
||||
~ "Login to use saved addresses" -> "Sign in to use saved addresses"
|
||||
|
||||
[2026-11-08 15:54:56 IST] location gate: recover after the user enables location.
|
||||
|
||||
The recovery poll awaited refreshLocation() and then re-armed the decision, but
|
||||
refresh() flips the status to 'locating' first. That made locationIsUnusable
|
||||
false, so this effect's cleanup ran (cancelled = true) while the fix was still
|
||||
being read; the post-await `if (cancelled) return` then skipped the re-arm. The
|
||||
notice disappeared (status granted) but decisionStarted stayed true, so no region
|
||||
was ever published and the address flow stayed up.
|
||||
|
||||
--- apps/user-ui/src/hooks/useRegionNeo.ts
|
||||
+ mountedRef so the re-arm is gated on the hook still being mounted, not on the
|
||||
effect cleanup (which the status flip itself triggers)
|
||||
+ after refreshLocation(), re-arm only when the fix actually arrived
|
||||
(coords != null); a failed re-read leaves the poll subscribed
|
||||
~ keep polling on failure (the effect re-subscribes when the status is unusable)
|
||||
|
||||
[2026-11-10 17:22:58 IST] admin orders: record packaging time and delivery time.
|
||||
|
||||
|
|
@ -1493,18 +1876,3 @@ text-base for the same reason.
|
|||
PCARD-03/04 now assert sizes + colours instead of the demotion
|
||||
--- apps/user-ui/tests/pages/product-detail.test.tsx
|
||||
PD-52 also pins the coupon size against the 3xl listed price
|
||||
|
||||
[2026-11-16 15:53:07 IST] floating cart bar layout: coupon price gets its own row, the
|
||||
checkout hint sits beside the subtotal.
|
||||
|
||||
The coupon line was stacked under the line total, squeezing the price column. It
|
||||
now spans the line below the delivery-slot row. The "Apply Coupons at checkout"
|
||||
hint moves from its own block into the subtotal row, next to the amount (mixed
|
||||
case and smaller so it fits beside the 2xl figure).
|
||||
|
||||
--- apps/user-ui/components/floating-cart-bar.tsx
|
||||
- line total: back to a plain ₹total, no stacked column
|
||||
+ coupon row: full-width under the slot dropdown row, ₹couponLine + "With Coupon"
|
||||
(testID cart-item-coupon-price-{id})
|
||||
- footer: standalone hint block under the subtotal row
|
||||
+ hint inline with ₹subtotal (testID apply-coupons-hint, numberOfLines 1)
|
||||
|
|
|
|||
521
docs/neo-region-refactor.md
Normal file
521
docs/neo-region-refactor.md
Normal file
|
|
@ -0,0 +1,521 @@
|
|||
# Neo Region Store — Implementation Plan
|
||||
|
||||
Status: ready to implement. Nothing in this plan has been applied yet.
|
||||
|
||||
Scope: `apps/user-ui` (plus one `apps/web-ui` route). Old code is left in place and commented out at its mount point only. No deletions, no git operations, no migrations, no test runs.
|
||||
|
||||
---
|
||||
|
||||
## 1. Goal
|
||||
|
||||
Replace the current region/location logic with a single new source of truth:
|
||||
|
||||
- `neoRegionStore` — Zustand store holding the resolved region, bound, coords, selected address and the two flow flags.
|
||||
- `useRegionNeo` — the only hook any screen may use. It runs the chart's decision internally and returns the store's data.
|
||||
- `LocationWrapperNeo` — mounted where `LocationTestWrapper` is today; renders children only when the hook can return the required data.
|
||||
- `needsAddressFormFlow` — the whole address fallback (choose / add / login).
|
||||
- `needsAddressConfirmation` — map with a fixed pin, address dropdown, "keep this location", "add new address".
|
||||
|
||||
Every current `useRegion` consumer is migrated to `useRegionNeo`. The old `useRegion`, `LocationTestWrapper`, `LocationFallbackFlow`, `regionStore`, `addressStore` and `region-switch.ts` stay in the repo, unused/commented at mount sites.
|
||||
|
||||
---
|
||||
|
||||
## 2. Settled decisions
|
||||
|
||||
1. **Saved address always wins** when the app has no cached region: if any saved address exists, its region/bound is used; the device fix only decides when the user has no address.
|
||||
2. **Cached region + device in a different region:**
|
||||
- address exists in the new region → use that address;
|
||||
- guest, or no addresses at all → go ahead with the new region (no confirmation);
|
||||
- addresses exist but none in the new region → `needsAddressConfirmation`.
|
||||
3. **No pending candidate, no hydration flag, no status enum.** The region returned by the hook is the region. A change is a change; a confirmation only offers a way back.
|
||||
4. **Publish immediately:** a persisted region renders as soon as it is hydrated; the device decision may switch it later.
|
||||
5. `selectedAddressId` **is** the active address, always. No read-time "default fallback". When it is non-null, region/bound/coords/name are derived from it.
|
||||
6. `selectAddress(id)` performs the region switch itself (cart stash/clear/restore, cache invalidation) and then sets the selection.
|
||||
7. `changeRegion(regionId, boundId?)` switches without an address and clears the selection.
|
||||
8. `NeoAddressForm` is a thin adapter that renders the existing `AddressForm` component.
|
||||
9. `AddressSwitcherSheet` mounts the new `NeoAddressFlow`.
|
||||
10. The 3 s location poll is kept while `needsAddressFormFlow` is up.
|
||||
11. The fixed-pin map is implemented as a `?fixed=1` mode on the existing `web-ui` `/location-selector` page.
|
||||
12. Adding an address in a different region shows a warning and then follows the region-switch flow.
|
||||
|
||||
Defaults accepted:
|
||||
|
||||
- `fullAddress` = `addressLine1, addressLine2, city` (empties skipped).
|
||||
- Guest draft is auto-selected after login; first address is default (server-side).
|
||||
- Logout clears addresses + selection; region/bound/coords persist.
|
||||
- A persisted region missing from `listRegions` is treated as no cache.
|
||||
- 8 s resolve timeout, then decide without the fix.
|
||||
- Addresses with `regionId == null` are filtered out of the chooser.
|
||||
- The existing form validation and "Set as default" checkbox are kept.
|
||||
|
||||
---
|
||||
|
||||
## 3. Contracts
|
||||
|
||||
### 3.1 `useRegionNeo` return
|
||||
|
||||
```ts
|
||||
export type NeoCoords = { latitude: number; longitude: number }
|
||||
|
||||
export interface NeoRegionData {
|
||||
regionId: number
|
||||
boundId: number
|
||||
regionName: string
|
||||
coords: NeoCoords
|
||||
selectedAddressId: number | null
|
||||
selectedAddress: NeoAddress | null // the full address object
|
||||
fullAddress: string | null // the formatted one-line string
|
||||
isCache: boolean
|
||||
changeRegion: (regionId: number, boundId?: number | null) => Promise<void>
|
||||
selectAddress: (id: number) => Promise<void>
|
||||
}
|
||||
|
||||
export function useRegionNeo(): NeoRegionData // never null
|
||||
export function useNeoRegionBootstrap(): void // orchestration, mounted by the wrapper
|
||||
```
|
||||
|
||||
- `useRegionNeo` may only be called by a component that `LocationWrapperNeo` renders. It returns the store's data directly and throws if the store has no complete region (a misuse, not a normal state).
|
||||
- The hook calls `getUserAddresses` as a `useQuery` at the top and derives `selectedAddress` / `fullAddress` from that data (falling back to the store while it loads). `selectAddress(id)` is the store action: async only because a cross-region switch awaits the cart stash, and it never calls the address API. A component that creates or edits an address must refresh the list itself (`utils.user.address.getUserAddresses.fetch(undefined)` then `setAddresses(...)`) before selecting.
|
||||
- `useNeoRegionBootstrap` runs the launch decision. The wrapper calls it and then reads the store itself.
|
||||
- Every field except `selectedAddressId` / `selectedAddress` / `fullAddress` is guaranteed present in the returned object (`selectedAddress` and `fullAddress` are null iff there is no address in the region).
|
||||
- `isCache === (origin === 'cache')`.
|
||||
|
||||
### 3.2 Store state
|
||||
|
||||
`apps/user-ui/src/store/neoRegionStore.ts`
|
||||
|
||||
```ts
|
||||
type NeoOrigin = 'device' | 'cache' | 'address' | 'manual'
|
||||
|
||||
interface NeoRegionState {
|
||||
regionId: number | null
|
||||
boundId: number | null
|
||||
regionName: string | null
|
||||
coords: NeoCoords | null
|
||||
origin: NeoOrigin | null
|
||||
|
||||
addresses: NeoAddress[]
|
||||
selectedAddressId: number | null
|
||||
|
||||
needsAddressFormFlow: boolean
|
||||
needsAddressConfirmation: boolean
|
||||
|
||||
// single internal write path — used by the hook, never returned by useRegionNeo
|
||||
applyRegion: (data: {
|
||||
regionId: number
|
||||
boundId: number
|
||||
regionName: string
|
||||
coords: NeoCoords
|
||||
origin: NeoOrigin
|
||||
selectedAddressId: number | null
|
||||
}) => void // validates the selection against the region, persists, clears both flags
|
||||
|
||||
// other internal actions
|
||||
setAddresses: (addresses: NeoAddress[]) => void // also clears an invalid selection
|
||||
openAddressFlow: () => void
|
||||
closeAddressFlow: () => void
|
||||
setNeedsConfirmation: (value: boolean) => void
|
||||
resetForLogout: () => void
|
||||
|
||||
// public actions
|
||||
changeRegion: (regionId: number, boundId?: number | null) => Promise<void>
|
||||
selectAddress: (id: number) => Promise<void>
|
||||
}
|
||||
```
|
||||
|
||||
`fullAddress` is derived in the hook from `addresses.find(a => a.id === selectedAddressId)`; it is not duplicated in the store.
|
||||
|
||||
`applyRegion` is the only place that writes the five region fields plus the selection, so the invariant in §3.6 cannot be bypassed. The persisted snapshot is read by `readNeoRegionSnapshot()` (in `neo-region-cache.ts`), not by a store method — the hook reads it once and feeds it to `applyRegion` with `origin: 'cache'`.
|
||||
|
||||
### 3.3 `origin` / `isCache`
|
||||
|
||||
| origin | meaning |
|
||||
|---|---|
|
||||
| `device` | region/bound taken from the live fix |
|
||||
| `cache` | no usable fix; persisted snapshot kept |
|
||||
| `address` | region/bound taken from a saved address |
|
||||
| `manual` | `changeRegion` without an address |
|
||||
|
||||
`isCache` is `origin === 'cache'`. `NotifRegionSync` uses `origin === 'device'` for "record the tracked region".
|
||||
|
||||
### 3.4 Pure decision function
|
||||
|
||||
`apps/user-ui/src/lib/neo-region-decision.ts`
|
||||
|
||||
```ts
|
||||
export interface NeoAddressSummary {
|
||||
id: number
|
||||
regionId: number | null
|
||||
boundId: number | null
|
||||
isDefault: boolean
|
||||
latitude: number | null
|
||||
longitude: number | null
|
||||
}
|
||||
|
||||
export type NeoDecision =
|
||||
| { action: 'ready'; regionId: number; boundId: number; origin: NeoOrigin; selectedAddressId: number | null }
|
||||
| { action: 'needs-address-flow' }
|
||||
| { action: 'needs-confirmation'; regionId: number; boundId: number }
|
||||
|
||||
export function decideNeoRegion(input: {
|
||||
cached: { regionId: number; boundId: number; regionName: string; coords: NeoCoords } | null
|
||||
fix: NeoCoords | null
|
||||
resolved: { regionId: number; boundId: number } | null // null = off / out of every bound
|
||||
isAuthenticated: boolean
|
||||
addresses: NeoAddressSummary[]
|
||||
}): NeoDecision
|
||||
```
|
||||
|
||||
### 3.5 Decision table
|
||||
|
||||
`a(region)` = an address with `regionId === region`; `defaultAddr` = the address with `isDefault`.
|
||||
|
||||
| # | cached | fix / resolved | auth + addresses | Decision |
|
||||
|---|---|---|---|---|
|
||||
| 1 | A | no fix or `resolved == null` | any | `ready(A, A.bound, 'cache', default in A ?? null)` |
|
||||
| 2 | none | no fix / `resolved == null` | default exists | `ready(default.region, default.bound, 'address', default.id)` |
|
||||
| 3 | none | no fix / `resolved == null` | guest / no address | `needs-address-flow` |
|
||||
| 4 | A | resolved B, B == A | any | `ready(A, B.bound, 'device', default in A ?? null)` |
|
||||
| 5 | A | resolved B, B ≠ A | address in B | `ready(B, a(B).bound, 'address', a(B).id)` |
|
||||
| 6 | A | resolved B, B ≠ A | authenticated, addresses exist, none in B | `needs-confirmation(B, B.bound)` |
|
||||
| 7 | A | resolved B, B ≠ A | guest or zero addresses | `ready(B, B.bound, 'device', null)` |
|
||||
| 8 | none | resolved B | guest / zero addresses | `ready(B, B.bound, 'device', null)` |
|
||||
| 9 | none | resolved B | any address | `ready(defaultAddr.region, defaultAddr.bound, 'address', defaultAddr.id)` (decision 2) |
|
||||
|
||||
Notes:
|
||||
|
||||
- Row 9 uses the default address; if none is flagged (data anomaly), the lowest id is used.
|
||||
- Rows 1 and 4 preserve an already-valid explicit selection if one exists; otherwise they select the default in that region.
|
||||
- `needs-confirmation` is reachable only from row 6. Its predicate also enforces: `origin === 'device'`, `resolved.regionId !== cached.regionId`, `addresses.length > 0`, no address in `resolved.regionId`.
|
||||
|
||||
### 3.6 Selection invariant
|
||||
|
||||
> `selectedAddressId` is either `null`, or the id of an address whose `regionId === regionId` and `boundId === boundId`.
|
||||
|
||||
Enforced only in the store:
|
||||
|
||||
| Moment | Effect |
|
||||
|---|---|
|
||||
| Decision adopts an address | `selectedAddressId = that id` |
|
||||
| Decision adopts device/cache with no address in the region | `selectedAddressId = null` |
|
||||
| `changeRegion` | clears the selection |
|
||||
| `selectAddress(id)` | switches to the address's region/bound if needed, then selects |
|
||||
| `selectAddress` with an address outside the current region | allowed — it performs the switch |
|
||||
| `setAddresses` refetch no longer contains the id | clears the selection |
|
||||
| Logout | clears addresses + selection |
|
||||
| Address list contains `regionId == null` | filtered out before storing |
|
||||
|
||||
---
|
||||
|
||||
## 4. New files
|
||||
|
||||
| File | Responsibility |
|
||||
|---|---|
|
||||
| `apps/user-ui/src/lib/neo-address.ts` | `NeoCoords` / `NeoAddress`, `toNeoAddress`, `addressCoords`, `formatNeoAddress`. |
|
||||
| `apps/user-ui/src/lib/neo-region-decision.ts` | Pure decision function (section 3.4/3.5). No React, no store, no network. |
|
||||
| `apps/user-ui/src/lib/neo-region-switch.ts` | Cart/cache side effects for a region change, lifted from `region-switch.ts` minus every `useRegionStore` write. Signature: `applyRegionSwitch(fromRegionId \| null, toRegionId, queryClient): Promise<void>`. |
|
||||
| `apps/user-ui/src/lib/neo-region-cache.ts` | `readNeoRegionSnapshot()` / `writeNeoRegionSnapshot()` / `clearNeoRegionSnapshot()` over `StorageServiceCasual`, key `freshyo_neo_region_v1`. Snapshot = `{ regionId, boundId, regionName, coords }`. |
|
||||
| `apps/user-ui/src/store/neoRegionStore.ts` | Store (section 3.2). Holds the data; `applyRegion` persists the snapshot; exposes the actions. |
|
||||
| `apps/user-ui/src/hooks/useRegionNeo.ts` | `useNeoRegionBootstrap` (orchestration, section 5) + `useRegionNeo` (non-null selector for wrapper children). |
|
||||
| `apps/user-ui/components/LocationWrapperNeo.tsx` | The gate (section 6.1). |
|
||||
| `apps/user-ui/src/components/location/neo/NeoLoadingScreen.tsx` | Spinner + "Finding your region…". |
|
||||
| `apps/user-ui/src/components/location/neo/NeoAddressFlow.tsx` | Whole fallback: choose saved address / add / login. |
|
||||
| `apps/user-ui/src/components/location/neo/NeoAddressForm.tsx` | Adapter over the existing `AddressForm` + cross-region warning. |
|
||||
| `apps/user-ui/src/components/location/neo/NeoConfirmLocation.tsx` | Map + pin + dropdown + actions. |
|
||||
| `apps/user-ui/src/components/location/neo/NeoFixedPinMap.tsx` | WebView around `/location-selector?...&fixed=1`. |
|
||||
| `apps/user-ui/tests/lib/neo-region-decision.test.ts` | The 9-row table. |
|
||||
| `apps/user-ui/tests/lib/neo-region-store.test.ts` | Selection invariant + `selectAddress`/`changeRegion`. |
|
||||
| `apps/user-ui/tests/components/neo-location-wrapper.test.tsx` | Four render branches. |
|
||||
|
||||
---
|
||||
|
||||
## 5. `useNeoRegionBootstrap` orchestration
|
||||
|
||||
Module-level guards (not store fields):
|
||||
|
||||
```ts
|
||||
let snapshotRead: Promise<NeoRegionSnapshot | null> | null = null
|
||||
let decisionStarted = false
|
||||
```
|
||||
|
||||
Effect, in order:
|
||||
|
||||
1. If `useAuthOptional() == null` → do nothing. This keeps instances above `AuthProvider` (through `useGetEssentialConsts`) as read-only consumers, so they cannot settle the launch decision without a user.
|
||||
2. `const snapshot = await readNeoRegionSnapshot()` once; if present, `applyRegion({ ...snapshot, origin: 'cache', selectedAddressId: null })`.
|
||||
3. `startTracking()` (existing `locationStore`, idempotent) — one fix, no movement tracking.
|
||||
4. Wait for the fix to settle: `granted` + coords, or `denied` / `services-off` / `unavailable` / `error`, or an 8 s timeout.
|
||||
5. `listRegions` starts as a `useQuery` on mount and `getUserAddresses` starts as the existing `useQuery` when auth settles — both in parallel with the fix. The decision gate waits for `isFetched || isError` on regions and (when signed in) addresses; `run` then reads their data instead of fetching.
|
||||
6. `run` starts the snapshot read and `trpc.common.resolveRegionByLocation.fetch({ lat, lng })` together in one `Promise.all`; the resolve is `null` on failure. Round coords to 1e-5 for the request only.
|
||||
7. `decideNeoRegion(...)`.
|
||||
9. Apply. If the decision's region differs from the published one, run `applyRegionSwitch(previous, next, queryClient)` first — a decision that moves region is a real switch (cart stash/clear + cache invalidation):
|
||||
- `ready` → `applyRegion({ regionId, boundId, regionName, coords, origin, selectedAddressId })`; it persists the snapshot and clears both flags.
|
||||
- `needs-address-flow` → `openAddressFlow()`.
|
||||
- `needs-confirmation` → `applyRegion({ B, origin: 'device', selectedAddressId: null })` then `setNeedsConfirmation(true)` (region is already B; see decision 3).
|
||||
10. Set `decisionStarted = true` before `run`; the auth-change and recovery-poll paths reset it deliberately.
|
||||
|
||||
Address subscription: every `getUserAddresses` result → `setAddresses(...)` (filters null-region rows, validates the selection).
|
||||
|
||||
Polling: while `needsAddressFormFlow` is true **and the location is unusable** (`denied`, `services-off`, `unavailable`, `error`), every 3 s call `probe()`; on a false → true transition, reset `decisionStarted`, clear the flag and re-run the effect. When the flow is up only because the user has no address, the fix already exists, so polling is skipped (otherwise it would re-decide and flicker every 3 s). Same recovery behaviour as `LocationTestWrapper` today, moved into the hook.
|
||||
|
||||
`changeRegion`:
|
||||
|
||||
```
|
||||
previous = get().regionId
|
||||
await applyRegionSwitch(previous, regionId, queryClient)
|
||||
applyRegion({ regionId, boundId: boundId ?? regionFromList.effectiveBoundId, regionName, coords: regionCentre, origin: 'manual', selectedAddressId: null })
|
||||
persist snapshot; setNeedsConfirmation(false)
|
||||
```
|
||||
|
||||
`selectAddress(id)`:
|
||||
|
||||
```
|
||||
address = get().addresses.find(a => a.id === id)
|
||||
if (!address || address.regionId == null) return
|
||||
if (address.regionId !== get().regionId) await applyRegionSwitch(get().regionId, address.regionId, queryClient)
|
||||
boundId = address.boundId ?? await resolveBound(address.regionId, address.coords) ?? effectiveBoundId
|
||||
applyRegion({ regionId, boundId, regionName, coords: address.coords, origin: 'address', selectedAddressId: id })
|
||||
persist snapshot; setNeedsConfirmation(false)
|
||||
```
|
||||
|
||||
The hook re-exports both actions from the store so `useRegionNeo().changeRegion === store.changeRegion`.
|
||||
|
||||
---
|
||||
|
||||
## 6. Components
|
||||
|
||||
### 6.1 `LocationWrapperNeo`
|
||||
|
||||
```tsx
|
||||
useNeoRegionBootstrap()
|
||||
|
||||
const regionId = useNeoRegionStore(s => s.regionId)
|
||||
const boundId = useNeoRegionStore(s => s.boundId)
|
||||
const regionName = useNeoRegionStore(s => s.regionName)
|
||||
const coords = useNeoRegionStore(s => s.coords)
|
||||
const needsForm = useNeoRegionStore(s => s.needsAddressFormFlow)
|
||||
const needsConfirm = useNeoRegionStore(s => s.needsAddressConfirmation)
|
||||
|
||||
if (needsForm) return <NeoAddressFlow />
|
||||
if (regionId == null || boundId == null || regionName == null || coords == null) {
|
||||
return <NeoLoadingScreen />
|
||||
}
|
||||
if (needsConfirm) return <NeoConfirmLocation />
|
||||
return <>{children}</>
|
||||
```
|
||||
|
||||
The wrapper never calls `useRegionNeo`; it reads the store directly. That is what makes the hook's non-null contract true: every component that calls it is rendered by this gate, after the four region fields exist. The fallback screens (`NeoAddressFlow`, `NeoAddressForm`, and the shared `AddressForm`) also read the store directly, because they are rendered *before* a region exists.
|
||||
|
||||
Mounted inside `AuthProvider`, directly replacing `LocationTestWrapper` (which is commented out).
|
||||
|
||||
### 6.2 `NeoAddressFlow` (the whole fallback)
|
||||
|
||||
Modes: `'choose' | 'add' | 'login'` (same shape as the old flow, new implementation).
|
||||
|
||||
- `choose`: list `addresses` from the store; tapping one calls `selectAddress(id)` and closes (the modal case) / lets the wrapper render children (the gate case). A lone address auto-opens once.
|
||||
- If unauthenticated, the list is empty; renders a login entry point, plus add.
|
||||
- `add`: renders `NeoAddressForm`.
|
||||
- `login`: renders the existing `Login` screen in place (same as the old flow), returning to `choose` on success.
|
||||
- Manual opens (location bar / switcher) set `needsAddressFormFlow = true`; the wrapper shows the same surface. No device re-check is forced.
|
||||
|
||||
### 6.3 `NeoAddressForm`
|
||||
|
||||
Renders the existing `AddressForm` with:
|
||||
|
||||
- `draftMode={!isAuthenticated}`
|
||||
- `onResolvedRegion` → stored in local state (used for the warning + success handling)
|
||||
- `onSuccess(addressId?)`:
|
||||
- `addressId != null` → `await selectAddress(addressId)`
|
||||
- draft (no id) → `await changeRegion(resolved.regionId, resolved.boundId)` (the draft is posted by `PendingAddressSync` after login)
|
||||
- clear `needsAddressFormFlow`
|
||||
- Cross-region warning: when `onResolvedRegion.regionId !== store.regionId`, render an inline warning: *"This address is in <name>. Saving will switch your region and clear your cart for <current>."*
|
||||
- `AddressForm` gains one optional prop `onBeforeSubmit?: () => Promise<boolean> | boolean` (default `true`), checked in its `onSubmit` before any mutation. `NeoAddressForm` passes a handler that shows a `BottomDialog` with Continue/Cancel when the region differs. The other three mounts are unaffected.
|
||||
|
||||
Note: the old form already implements the chart's add-address logic — device fix prefilled, map picker via `LocationMapStep`, `resolveBound` gate, "outside delivery area → try selecting on the map", submit disabled until serviceable. No new form logic is written.
|
||||
|
||||
### 6.4 `NeoConfirmLocation`
|
||||
|
||||
- `NeoFixedPinMap` at `coords`.
|
||||
- `BottomDropdown` listing `addresses` (foreign regions included), current selection highlighted.
|
||||
- "Keep this location" → `setNeedsConfirmation(false)`.
|
||||
- Picking an address → `selectAddress(id)` (which switches, clears the flag).
|
||||
- "Add new address" → `setNeedsConfirmation(false)`; `openAddressFlow()`.
|
||||
|
||||
### 6.5 `NeoFixedPinMap` + web-ui `?fixed=1`
|
||||
|
||||
`NeoFixedPinMap` renders `WebView` at:
|
||||
|
||||
```
|
||||
${WEB_UI_BASE_URL}/location-selector?lat=<lat>&lng=<lng>&fixed=1
|
||||
```
|
||||
|
||||
In `apps/web-ui/src/routes/location-selector.tsx`, when `fixed=1`:
|
||||
|
||||
- marker created at the given point, `draggable: false`;
|
||||
- no `dragstart` / `dragend` / `click` listeners that rewrite the point;
|
||||
- Continue button hidden;
|
||||
- the map may still pan/zoom; the pin does not move.
|
||||
|
||||
This is the only web-ui change.
|
||||
|
||||
---
|
||||
|
||||
## 7. Modified files
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `app/_layout.tsx` | Comment out `<LocationTestWrapper>`; add `<LocationWrapperNeo>` in the same position (inside `AuthProvider`). |
|
||||
| `src/components/AddressForm.tsx` | Reads `regionId` / `boundId` from the neo store directly (it is also shown in the fallback, before a region exists); adds the optional `onBeforeSubmit` prop. Behaviour otherwise unchanged. |
|
||||
| `src/hooks/prominent-api-hooks.ts` | Reads `boundId` / `regionId` / `selectedAddressId` from the neo store directly (it runs above `AuthProvider`, outside the wrapper). |
|
||||
| `app/(drawer)/(tabs)/me/index.tsx` | `region?.name` → `regionName`. |
|
||||
| `components/cart-page.tsx` | `useRegion` → `useRegionNeo`; `selectedAddressId` + `setSelectedAddressId` → `selectedAddressId` + `selectAddress`; `addresses` from the store for the gate condition. |
|
||||
| `components/checkout-page.tsx` | `useRegion` → `useRegionNeo`. |
|
||||
| `components/CheckoutAddressSelector.tsx` | Read `selectedAddressId` from the hook; drop the `selectedAddress`/`onAddressSelect` props; selection → `selectAddress`; add-address modal success → `selectAddress`. Remove the local auto-select-default effect (the decision now owns it). |
|
||||
| `components/CheckoutAddressDisplay.tsx` | Render `fullAddress`; no tRPC query, no `useAddressStore`, no `selected ?? default` fallback. |
|
||||
| `components/PaymentAndOrderComponent.tsx` | `regionId` / `boundId` from the hook. |
|
||||
| `components/ProductDetail.tsx` | `regionId` from the hook. |
|
||||
| `components/QuickDeliveryAddressSelector.tsx` | `regionId` + `selectedAddressId` from the hook; `setSelectedAddressId` → `selectAddress`. |
|
||||
| `src/components/LocationBar.tsx` | `regionName` + `fullAddress` from the hook; no tRPC, no `useAddressStore`. |
|
||||
| `src/components/location/AddressSwitcherSheet.tsx` | Mount `NeoAddressFlow` instead of `LocationFallbackFlow`. |
|
||||
| `src/components/NotifRegionSync.tsx` | `regionId` from the hook; `origin === 'device'` from the store instead of `bound != null`. |
|
||||
| `components/CartAddressGate.tsx` | `coords` from the hook; on form success `selectAddress(addressId)` then `onDone()`. Keep its 3 s poll (or rely on the hook's poll — flag the duplicate and keep the gate's, which only runs when `coords` is null). |
|
||||
| `src/components/PendingAddressSync.tsx` | After create: refetch addresses into the store, then `selectAddress(created.id)`. |
|
||||
| `apps/web-ui/src/routes/location-selector.tsx` | `fixed=1` mode. |
|
||||
| `tests/helpers/test-utils.tsx` | Add `seedNeoRegion({regionId, boundId, regionName, coords, addresses, selectedAddressId})`. |
|
||||
| `tests/helpers/reset.ts` | Reset the neo store between tests. |
|
||||
|
||||
Untouched (kept deliberately): `src/hooks/useRegion.ts`, `src/store/regionStore.ts`, `src/store/addressStore.ts`, `src/lib/region-switch.ts`, `components/LocationTestWrapper.tsx`, `src/components/location/LocationFallbackFlow.tsx`.
|
||||
|
||||
---
|
||||
|
||||
## 8. Region switching
|
||||
|
||||
`neo-region-switch.ts` copies the body of `confirmRegionSwitch` minus the old store write:
|
||||
|
||||
1. `if (from !== to)` → `stashRegionCarts(from)`, `clearLocalCart('regular')`, `clearLocalCart('flash')`.
|
||||
2. Clear quick-delivery/checkout selections, tags, product/slot caches; remove region-scoped query keys.
|
||||
3. `restoreRegionCarts(to)`.
|
||||
4. `queryClient.invalidateQueries()`.
|
||||
|
||||
The store then writes `regionId/boundId/regionName/coords/origin`; selection is cleared by `changeRegion` and set by `selectAddress`.
|
||||
|
||||
`confirmRegionSwitch` stays untouched for the old code paths; nothing new imports it.
|
||||
|
||||
---
|
||||
|
||||
## 9. Persistence
|
||||
|
||||
- Key: `freshyo_neo_region_v1` (via `StorageServiceCasual`).
|
||||
- Snapshot: `{ regionId, boundId, regionName, coords, selectedAddress }`.
|
||||
- The selected `NeoAddress` object is cached too. On hydration it is seeded as a
|
||||
provisional address and selected, so the location bar / checkout can render it
|
||||
before the live address list arrives; the live list then replaces it and clears
|
||||
the selection if the address no longer exists.
|
||||
- Applying the persisted snapshot uses `origin: 'cache'` and does not touch the flags.
|
||||
- Written on every `ready` / `changeRegion` / `selectAddress` (`changeRegion`
|
||||
persists `selectedAddress: null`).
|
||||
- The persisted selection wins over the default when the decision runs, provided
|
||||
it still belongs to the chosen region.
|
||||
- Cleared only if `regionId` is missing from `listRegions` (then re-decide as no-cache).
|
||||
|
||||
---
|
||||
|
||||
## 10. Polling
|
||||
|
||||
The hook owns the 3 s probe. It runs only while `needsAddressFormFlow` is true and re-runs the decision when the device becomes usable. `CartAddressGate` keeps its own poll only for the "no fix yet on the cart" case; this is noted as the one duplicated poll.
|
||||
|
||||
---
|
||||
|
||||
## 11. Consumer migration details
|
||||
|
||||
| Consumer | Fields used | Notes |
|
||||
|---|---|---|
|
||||
| `me/index.tsx` | `regionName` | subtitle text |
|
||||
| `cart-page.tsx` | `regionId`, `selectedAddressId`, `addresses` | gate condition = `addresses.length === 0` |
|
||||
| `checkout-page.tsx` | `regionId`, `selectedAddressId` | route guard + the order's address |
|
||||
| `CheckoutAddressSelector.tsx` | `regionId`, `selectedAddressId` | drop props; `selectAddress` |
|
||||
| `CheckoutAddressDisplay.tsx` | `fullAddress` | no fallback lookup |
|
||||
| `PaymentAndOrderComponent.tsx` | `regionId`, `boundId` | flash eligibility |
|
||||
| `ProductDetail.tsx` | `regionId` | query enabled |
|
||||
| `QuickDeliveryAddressSelector.tsx` | `regionId`, `selectedAddressId` | same-region warning uses `regionId` |
|
||||
| `LocationBar.tsx` | `regionName`, `fullAddress` | sheet opens the new flow |
|
||||
| `NotifRegionSync.tsx` | `regionId`, `origin` | `origin === 'device'` |
|
||||
| `prominent-api-hooks.ts` | `regionId`, `boundId`, `selectedAddressId` | must work above `AuthProvider` |
|
||||
| `AddressForm.tsx` | `regionId`, `boundId` | store selectors (fallback-safe) |
|
||||
|
||||
`useAddressStore` remains in the tree but nothing writes it after this change. `LocationFallbackFlow` and `LocationTestWrapper` become unreferenced.
|
||||
|
||||
---
|
||||
|
||||
## 12. Tests
|
||||
|
||||
New:
|
||||
|
||||
- `neo-region-decision.test.ts` — one test per row of the table, plus the confirmation predicate (guest / no address / address in B / same region).
|
||||
- `neo-region-store.test.ts` — `selectAddress` switches when the region differs; `changeRegion` clears the selection; `setAddresses` clears a vanished selection; logout clears addresses/selection.
|
||||
- `neo-location-wrapper.test.tsx` — loading / flow / confirmation / children.
|
||||
|
||||
Updated (not run):
|
||||
|
||||
- `tests/helpers/test-utils.tsx`, `tests/helpers/reset.ts` — seed/reset the neo store.
|
||||
- `tests/pages/cart.test.tsx`, `tests/pages/checkout.test.tsx`, `tests/pages/home.test.tsx`, `tests/pages/me-hub.test.tsx`, `tests/pages/addresses.test.tsx`, `tests/pages/payment-and-order.test.tsx`, `tests/pages/flash-checkout.test.tsx` — swap `useRegion`/`useAddressStore` seeds for the neo store.
|
||||
- `tests/lib/prominent-api-hooks.test.tsx`, `tests/lib/notifications.test.tsx` — `origin` and hook nullability.
|
||||
- `tests/components/checkout-address.test.tsx`, `quick-delivery-address-selector.test.tsx`, `address-form.test.tsx` — new selection source.
|
||||
- `tests/components/location-components.test.tsx` and `tests/lib/use-region.test.tsx` continue to test the old, still-present components/hook; leave them alone unless they import a changed file.
|
||||
|
||||
Per AGENTS: tests are written/updated alongside the code but **not executed** unless requested.
|
||||
|
||||
---
|
||||
|
||||
## 13. Build order
|
||||
|
||||
1. `change-log.txt` entry (timestamped diff summary) — before any non-md/txt edit.
|
||||
2. `neo-region-decision.ts`.
|
||||
3. `neo-region-cache.ts` + `neoRegionStore.ts` + `neo-region-switch.ts`.
|
||||
4. `useRegionNeo.ts`.
|
||||
5. `LocationWrapperNeo.tsx` + `NeoLoadingScreen.tsx`.
|
||||
6. web-ui `?fixed=1` + `NeoFixedPinMap.tsx` + `NeoConfirmLocation.tsx`.
|
||||
7. `NeoAddressFlow.tsx` + `NeoAddressForm.tsx` (+ `AddressForm.onBeforeSubmit`).
|
||||
8. Migrate consumers (section 7) + `PendingAddressSync`.
|
||||
9. Mount in `_layout.tsx`, comment out `LocationTestWrapper`.
|
||||
10. Tests + helpers.
|
||||
11. Manual pass (section 14).
|
||||
|
||||
The app stays on the old wrapper until step 9, so every intermediate state is runnable.
|
||||
|
||||
---
|
||||
|
||||
## 14. Manual verification
|
||||
|
||||
1. Fresh install, location on, inside bounds → children render; `regionName` correct; no flow screen.
|
||||
2. Fresh install, location off, no address → `NeoAddressFlow`; the 3 s poll recovers after enabling location.
|
||||
3. Fresh install, location off, logged in with a default address → app opens on the default's region, no flow.
|
||||
4. Guest adds an address → saved locally → region follows it → login → draft posted, selected, first = default.
|
||||
5. Cached A, device A → no switch.
|
||||
6. Cached A, device B, guest or no address → silent switch to B, no confirmation.
|
||||
7. Cached A, device B, address in B → switch to B with that address selected.
|
||||
8. Cached A, device B, addresses only in A → confirmation screen: dropdown populated; "Keep" stays on B; picking A switches back; "Add new" opens the flow.
|
||||
9. Add address out of bounds → submit blocked, "try selecting on the map" → map retry.
|
||||
10. Add address in another region → warning → confirm → switch + cart stashed/restored.
|
||||
11. Cart with no address → gate; save → `selectAddress` → cart shows `fullAddress`.
|
||||
12. Logout → addresses/selection cleared; region stays.
|
||||
|
||||
---
|
||||
|
||||
## 15. Risks / notes
|
||||
|
||||
- **Upper-tree consumers:** `useGetEssentialConsts` runs above `AuthProvider`. `useRegionNeo()` returns `null` there until the wrapper populates the store; the query already tolerates a null bound. No orchestration runs without auth.
|
||||
- **Double poll:** the hook polls while the fallback is up; `CartAddressGate` polls when the cart has no fix. Accepted for now.
|
||||
- **Two switches in row 6:** the device switch happens before the confirmation renders; choosing an address switches again. Cart stashing makes this safe; `confirmRegionSwitch`'s contract (ask before switching) is not honoured for the device switch by design.
|
||||
- **`AddressForm.onBeforeSubmit`** is the only behavioural change to a shared old component; default `true` keeps the other three mounts identical.
|
||||
- **Fixed-pin map** is the only cross-app change; `web-ui` is otherwise untouched.
|
||||
- **`needsAddressFormFlow`** is used both by the launch decision and by manual opens (location bar); manual opens never reset the decision.
|
||||
|
||||
---
|
||||
|
||||
## 16. Out of scope
|
||||
|
||||
- Deleting the old hook/store/components.
|
||||
- Rewriting the address book (`me/addresses`) onto the neo store.
|
||||
- Cross-region warning in the checkout add-address modal (it inherits `selectAddress` switching, but no warning dialog).
|
||||
- Any backend or database change.
|
||||
- web-ui location-aware launch (`RegionGate` stays as-is).
|
||||
|
|
@ -7,6 +7,7 @@ export * from './region-cache-urls'
|
|||
*/
|
||||
export const BASE_API_URL = 'https://worker.freshyo.in'
|
||||
// export const BASE_API_URL = 'https://devapi.freshyo.in'
|
||||
// export const BASE_API_URL = 'http://192.168.100.126:8787'
|
||||
// export const BASE_API_URL = 'https://devbackend.freshyo.in'
|
||||
// export const BASE_API_URL = 'https://192.168.100.126.nip.io:8787'
|
||||
// export const BASE_API_URL = 'http://192.168.100.126:8787'
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue