neo region commit
This commit is contained in:
parent
bac35e6562
commit
f9fb1c53a7
51 changed files with 3407 additions and 670 deletions
|
|
@ -8,7 +8,7 @@ import { LinearGradient } from 'expo-linear-gradient';
|
||||||
import { Ionicons } from '@expo/vector-icons';
|
import { Ionicons } from '@expo/vector-icons';
|
||||||
import NextOrderGlimpse from '@/components/NextOrderGlimpse';
|
import NextOrderGlimpse from '@/components/NextOrderGlimpse';
|
||||||
import AddressSwitcherSheet from '@/src/components/location/AddressSwitcherSheet';
|
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 { useAuth } from '@/src/contexts/AuthContext';
|
||||||
import { useNavigationTarget } from 'common-ui/hooks/useNavigationTarget';
|
import { useNavigationTarget } from 'common-ui/hooks/useNavigationTarget';
|
||||||
import { useGetEssentialConsts } from '@/src/hooks/prominent-api-hooks';
|
import { useGetEssentialConsts } from '@/src/hooks/prominent-api-hooks';
|
||||||
|
|
@ -22,7 +22,7 @@ export default function Me() {
|
||||||
const { logout } = useAuth();
|
const { logout } = useAuth();
|
||||||
const { getNavigationTarget } = useNavigationTarget();
|
const { getNavigationTarget } = useNavigationTarget();
|
||||||
const [regionDialogOpen, setRegionDialogOpen] = useState(false);
|
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.
|
// Same number the NextOrderGlimpse dials via tel: — Live Support opens it in WhatsApp.
|
||||||
const { data: essentialConsts } = useGetEssentialConsts();
|
const { data: essentialConsts } = useGetEssentialConsts();
|
||||||
const supportMobile = essentialConsts?.supportMobile ?? null;
|
const supportMobile = essentialConsts?.supportMobile ?? null;
|
||||||
|
|
@ -108,7 +108,7 @@ export default function Me() {
|
||||||
icon: 'globe-outline',
|
icon: 'globe-outline',
|
||||||
color: '#0EA5E9',
|
color: '#0EA5E9',
|
||||||
onPress: () => setRegionDialogOpen(true),
|
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',
|
title: 'Profile Settings',
|
||||||
|
|
|
||||||
|
|
@ -29,7 +29,9 @@ import BackHandlerWrapper from "@/components/BackHandler";
|
||||||
import AddToCartDialog from "@/src/components/AddToCartDialog";
|
import AddToCartDialog from "@/src/components/AddToCartDialog";
|
||||||
import PendingAddressSync from "@/src/components/PendingAddressSync";
|
import PendingAddressSync from "@/src/components/PendingAddressSync";
|
||||||
import NotifRegionSync from "@/src/components/NotifRegionSync";
|
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 React from "react";
|
||||||
import { GestureHandlerRootView } from "react-native-gesture-handler";
|
import { GestureHandlerRootView } from "react-native-gesture-handler";
|
||||||
import NotifChecker from "@/services/notif-service/notif-checker";
|
import NotifChecker from "@/services/notif-service/notif-checker";
|
||||||
|
|
@ -76,7 +78,7 @@ export default function RootLayout() {
|
||||||
<FirstUserWrapper>
|
<FirstUserWrapper>
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
<PendingAddressSync />
|
<PendingAddressSync />
|
||||||
<LocationTestWrapper>
|
<LocationWrapperNeo>
|
||||||
<NotificationProvider>
|
<NotificationProvider>
|
||||||
<NotifChecker />
|
<NotifChecker />
|
||||||
<NotifRegionSync />
|
<NotifRegionSync />
|
||||||
|
|
@ -93,7 +95,7 @@ export default function RootLayout() {
|
||||||
</RefreshProvider>
|
</RefreshProvider>
|
||||||
</PaperProvider>
|
</PaperProvider>
|
||||||
</NotificationProvider>
|
</NotificationProvider>
|
||||||
</LocationTestWrapper>
|
</LocationWrapperNeo>
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
</FirstUserWrapper>
|
</FirstUserWrapper>
|
||||||
</WebViewWrapper>
|
</WebViewWrapper>
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,10 @@ import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||||
import { tw, theme, MyText, MyTouchableOpacity } from 'common-ui'
|
import { tw, theme, MyText, MyTouchableOpacity } from 'common-ui'
|
||||||
import AddressForm from '@/src/components/AddressForm'
|
import AddressForm from '@/src/components/AddressForm'
|
||||||
import { useLocationStore } from '@/src/store/locationStore'
|
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.
|
// How often to re-check the device location while we still have no fix.
|
||||||
const LOCATION_POLL_MS = 3000
|
const LOCATION_POLL_MS = 3000
|
||||||
|
|
@ -21,7 +25,11 @@ interface CartAddressGateProps {
|
||||||
* first address they save becomes their default, and we then show the cart.
|
* first address they save becomes their default, and we then show the cart.
|
||||||
*/
|
*/
|
||||||
const CartAddressGate: React.FC<CartAddressGateProps> = ({ onDone, onBack }) => {
|
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 probeLocation = useLocationStore((state) => state.probe)
|
||||||
const refreshPosition = useLocationStore((state) => state.refresh)
|
const refreshPosition = useLocationStore((state) => state.refresh)
|
||||||
const [mode, setMode] = useState<'none' | 'current' | 'other'>('none')
|
const [mode, setMode] = useState<'none' | 'current' | 'other'>('none')
|
||||||
|
|
@ -118,7 +126,7 @@ const CartAddressGate: React.FC<CartAddressGateProps> = ({ onDone, onBack }) =>
|
||||||
phone: '',
|
phone: '',
|
||||||
addressLine1: '',
|
addressLine1: '',
|
||||||
addressLine2: '',
|
addressLine2: '',
|
||||||
city: 'Mahabubnagar',
|
city: neo.regionName,
|
||||||
state: 'Telangana',
|
state: 'Telangana',
|
||||||
isDefault: true,
|
isDefault: true,
|
||||||
latitude: coords.latitude,
|
latitude: coords.latitude,
|
||||||
|
|
@ -126,9 +134,20 @@ const CartAddressGate: React.FC<CartAddressGateProps> = ({ onDone, onBack }) =>
|
||||||
}
|
}
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
onSuccess={() => {
|
onSuccess={(addressId) => {
|
||||||
setMode('none')
|
void (async () => {
|
||||||
onDone()
|
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>
|
</View>
|
||||||
|
|
|
||||||
|
|
@ -2,28 +2,17 @@ import React from 'react'
|
||||||
import { View } from 'react-native'
|
import { View } from 'react-native'
|
||||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||||
import { tw, MyText } from 'common-ui'
|
import { tw, MyText } from 'common-ui'
|
||||||
import { trpc } from '@/src/trpc-client'
|
import { useRegionNeo } from '@/src/hooks/useRegionNeo'
|
||||||
import { useAuth } from '@/src/contexts/AuthContext'
|
import { addressIconName } from '@/src/lib/neo-address'
|
||||||
import { useAddressStore } from '@/src/store/addressStore'
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read-only delivery address card for the checkout page. The address is chosen
|
* Read-only delivery address card for the checkout page. The address is chosen
|
||||||
* on the cart page (CheckoutAddressSelector); checkout only shows it.
|
* on the cart page (CheckoutAddressSelector); checkout only shows it.
|
||||||
*/
|
*/
|
||||||
const CheckoutAddressDisplay: React.FC = () => {
|
const CheckoutAddressDisplay: React.FC = () => {
|
||||||
const { isAuthenticated } = useAuth()
|
// The hook guarantees the selection belongs to the current region, so this
|
||||||
const selectedAddressId = useAddressStore((state) => state.selectedAddressId)
|
// is the one address the order will use.
|
||||||
|
const address = useRegionNeo().selectedAddress
|
||||||
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
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View testID="checkout-address" style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}>
|
<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>
|
<MyText style={tw`text-base font-bold text-gray-900`}>Delivery Address</MyText>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
{isLoading ? (
|
{address ? (
|
||||||
<MyText testID="checkout-address-loading" style={tw`text-gray-500`}>Loading address...</MyText>
|
|
||||||
) : address ? (
|
|
||||||
<View style={tw`bg-gray-50 p-4 rounded-xl border border-gray-200`}>
|
<View style={tw`bg-gray-50 p-4 rounded-xl border border-gray-200`}>
|
||||||
<View style={tw`flex-row items-center mb-2`}>
|
<View style={tw`flex-row items-center mb-2`}>
|
||||||
<MaterialIcons
|
<MaterialIcons name={addressIconName(address.name)} size={20} color="#6B7280" />
|
||||||
name={
|
|
||||||
address.name.toLowerCase().includes('home')
|
|
||||||
? 'home'
|
|
||||||
: address.name.toLowerCase().includes('work')
|
|
||||||
? 'work'
|
|
||||||
: 'location-on'
|
|
||||||
}
|
|
||||||
size={20}
|
|
||||||
color="#6B7280"
|
|
||||||
/>
|
|
||||||
<MyText testID="checkout-address-name" style={tw`font-bold ml-2 text-gray-900`}>{address.name}</MyText>
|
<MyText testID="checkout-address-name" style={tw`font-bold ml-2 text-gray-900`}>{address.name}</MyText>
|
||||||
</View>
|
</View>
|
||||||
<MyText style={tw`text-gray-600 text-sm leading-5 mb-1`} numberOfLines={2}>
|
<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 { View, Text, TouchableOpacity, ScrollView, Alert, NativeSyntheticEvent, NativeScrollEvent } from 'react-native';
|
||||||
import { useRouter } from 'expo-router';
|
import { useRouter } from 'expo-router';
|
||||||
import { tw, BottomDialog, RawBottomDialog, MyText } from 'common-ui';
|
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 MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
||||||
import { trpc } from '@/src/trpc-client';
|
import { trpc } from '@/src/trpc-client';
|
||||||
import { useAuth } from '@/src/contexts/AuthContext';
|
import { useAuth } from '@/src/contexts/AuthContext';
|
||||||
import { useRegion } from '@/src/hooks/useRegion';
|
import { useRegionNeo } from '@/src/hooks/useRegionNeo';
|
||||||
import { confirmRegionSwitch } from '@/src/lib/region-switch';
|
import { addressIconName, toNeoAddress } from '@/src/lib/neo-address';
|
||||||
|
import { useNeoRegionStore } from '@/src/store/neoRegionStore';
|
||||||
import * as Location from 'expo-location';
|
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 CARD_WIDTH = 300; // 288 (w-72) + 12 (mr-3)
|
||||||
|
|
||||||
const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
|
const CheckoutAddressSelector: React.FC = () => {
|
||||||
selectedAddress,
|
const neo = useRegionNeo();
|
||||||
onAddressSelect,
|
const selectedAddress = neo.selectedAddressId;
|
||||||
}) => {
|
const selectAddress = neo.selectAddress;
|
||||||
|
const setAddresses = useNeoRegionStore((state) => state.setAddresses);
|
||||||
const [showAddAddress, setShowAddAddress] = useState(false);
|
const [showAddAddress, setShowAddAddress] = useState(false);
|
||||||
const [editingLocationAddressId, setEditingLocationAddressId] = useState<number | null>(null);
|
const [editingLocationAddressId, setEditingLocationAddressId] = useState<number | null>(null);
|
||||||
const [locationLoading, setLocationLoading] = useState(false);
|
const [locationLoading, setLocationLoading] = useState(false);
|
||||||
|
|
@ -31,13 +28,16 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
|
||||||
const utils = trpc.useUtils();
|
const utils = trpc.useUtils();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const scrollViewRef = useRef<ScrollView>(null);
|
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 { isAuthenticated } = useAuth();
|
||||||
const { regionId: selectedRegionId } = useRegion();
|
const selectedRegionId = neo.regionId;
|
||||||
const { data: addresses } = trpc.user.address.getUserAddresses.useQuery(
|
const { data: addresses } = trpc.user.address.getUserAddresses.useQuery(
|
||||||
undefined,
|
undefined,
|
||||||
{ enabled: isAuthenticated }
|
{ enabled: isAuthenticated }
|
||||||
);
|
);
|
||||||
const { data: regions } = trpc.common.listRegions.useQuery();
|
const regions = useNeoRegionStore((state) => state.regions);
|
||||||
|
|
||||||
const updateAddressMutation = trpc.user.address.updateAddress.useMutation({
|
const updateAddressMutation = trpc.user.address.updateAddress.useMutation({
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
|
|
@ -68,21 +68,6 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
|
||||||
});
|
});
|
||||||
}, [addresses?.data, selectedAddress]);
|
}, [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
|
// Reset scroll to left when address is selected
|
||||||
const resetScrollToLeft = () => {
|
const resetScrollToLeft = () => {
|
||||||
setCurrentIndex(0);
|
setCurrentIndex(0);
|
||||||
|
|
@ -94,8 +79,29 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
|
||||||
setCurrentIndex(index);
|
setCurrentIndex(index);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Selecting an address from another region requires an explicit confirmation
|
// Every cross-region selection goes through this confirmation, because the
|
||||||
// because it clears the cart and changes the browsing region.
|
// 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) => {
|
const handleAddressPress = (address: any) => {
|
||||||
if (selectedRegionId && address.regionId && address.regionId !== selectedRegionId) {
|
if (selectedRegionId && address.regionId && address.regionId !== selectedRegionId) {
|
||||||
const targetRegion = (regions ?? []).find((region) => region.id === address.regionId);
|
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.');
|
Alert.alert('Unavailable region', 'This address belongs to a region that is not currently available.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Alert.alert(
|
confirmSwitch(targetRegion.name, () => {
|
||||||
'Switch region?',
|
void (async () => {
|
||||||
`This address is in ${targetRegion.name}. Switching will clear your entire cart and take you home.`,
|
await selectAddress(address.id);
|
||||||
[
|
router.replace('/(drawer)/(tabs)/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');
|
|
||||||
})();
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
onAddressSelect(address.id);
|
void selectAddress(address.id);
|
||||||
resetScrollToLeft();
|
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 justify-between items-start mb-2`}>
|
||||||
<View style={tw`flex-row items-center`}>
|
<View style={tw`flex-row items-center`}>
|
||||||
<MaterialIcons
|
<MaterialIcons
|
||||||
name={address.name.toLowerCase().includes('home') ? 'home' : address.name.toLowerCase().includes('work') ? 'work' : 'location-on'}
|
name={addressIconName(address.name)}
|
||||||
size={20}
|
size={20}
|
||||||
color={selectedAddress === address.id ? '#EC4899' : '#6B7280'}
|
color={selectedAddress === address.id ? '#EC4899' : '#6B7280'}
|
||||||
/>
|
/>
|
||||||
|
|
@ -288,13 +283,44 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
|
||||||
<RawBottomDialog open={showAddAddress} onClose={() => setShowAddAddress(false)}>
|
<RawBottomDialog open={showAddAddress} onClose={() => setShowAddAddress(false)}>
|
||||||
|
|
||||||
<AddressForm
|
<AddressForm
|
||||||
|
onResolvedRegion={(info) => {
|
||||||
|
resolvedRegionRef.current = info;
|
||||||
|
}}
|
||||||
onSuccess={(addressId) => {
|
onSuccess={(addressId) => {
|
||||||
setShowAddAddress(false);
|
setShowAddAddress(false);
|
||||||
// Auto-select the newly added address
|
|
||||||
if (addressId) {
|
|
||||||
onAddressSelect(addressId);
|
|
||||||
}
|
|
||||||
queryClient.invalidateQueries();
|
queryClient.invalidateQueries();
|
||||||
|
if (addressId == null) return;
|
||||||
|
|
||||||
|
const resolved = resolvedRegionRef.current;
|
||||||
|
if (
|
||||||
|
resolved != null &&
|
||||||
|
selectedRegionId != null &&
|
||||||
|
resolved.regionId !== selectedRegionId
|
||||||
|
) {
|
||||||
|
const targetRegion = (regions ?? []).find((region) => region.id === resolved.regionId);
|
||||||
|
if (!targetRegion) {
|
||||||
|
Alert.alert(
|
||||||
|
'Unavailable region',
|
||||||
|
'This address belongs to a region that is not currently available.'
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// The address has been saved; only selecting it is destructive.
|
||||||
|
confirmSwitch(targetRegion.name, () => {
|
||||||
|
void (async () => {
|
||||||
|
await refreshAddresses();
|
||||||
|
await selectAddress(addressId);
|
||||||
|
router.replace('/(drawer)/(tabs)/home');
|
||||||
|
})();
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-select the newly added address.
|
||||||
|
void (async () => {
|
||||||
|
await refreshAddresses();
|
||||||
|
await selectAddress(addressId);
|
||||||
|
})();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</RawBottomDialog>
|
</RawBottomDialog>
|
||||||
|
|
|
||||||
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 { trpc } from '@/src/trpc-client';
|
||||||
import { useCentralProductStore } from '@/src/store/centralProductStore';
|
import { useCentralProductStore } from '@/src/store/centralProductStore';
|
||||||
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
|
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 { useCheckoutStore } from '@/src/store/checkoutStore';
|
||||||
import { clearLocalCart } from '@/hooks/cart-query-hooks';
|
import { clearLocalCart } from '@/hooks/cart-query-hooks';
|
||||||
import { useQueryClient } from '@tanstack/react-query';
|
import { useQueryClient } from '@tanstack/react-query';
|
||||||
|
|
@ -64,7 +64,9 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
|
||||||
const products = useCentralProductStore((state) => state.products);
|
const products = useCentralProductStore((state) => state.products);
|
||||||
const productsById = useCentralProductStore((state) => state.productsById);
|
const productsById = useCentralProductStore((state) => state.productsById);
|
||||||
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
|
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
|
// Memoized flash-eligible product IDs
|
||||||
const flashEligibleProductIds = useMemo(() => {
|
const flashEligibleProductIds = useMemo(() => {
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ import { useAddToCart, useGetCart, useUpdateCartItem, useRemoveFromCart } from '
|
||||||
import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier';
|
import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier';
|
||||||
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore';
|
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore';
|
||||||
import { useSlots } from '@/src/hooks/prominent-api-hooks';
|
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 FloatingCartBar from './floating-cart-bar';
|
||||||
import { useStoreHeaderStore } from '@/src/store/storeHeaderStore';
|
import { useStoreHeaderStore } from '@/src/store/storeHeaderStore';
|
||||||
import { useCartStore } from '@/src/store/cartStore';
|
import { useCartStore } from '@/src/store/cartStore';
|
||||||
|
|
@ -51,7 +51,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
|
||||||
const [hasMore, setHasMore] = useState(true);
|
const [hasMore, setHasMore] = useState(true);
|
||||||
const [reviewsOffset, setReviewsOffset] = useState(0);
|
const [reviewsOffset, setReviewsOffset] = useState(0);
|
||||||
const [refreshing, setRefreshing] = useState(false);
|
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
|
// 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.
|
// waits for it and the screen stays in its loading state until then.
|
||||||
const { data: productDetail, isLoading, error, refetch } = trpc.user.product.getProductDetails.useQuery(
|
const { data: productDetail, isLoading, error, refetch } = trpc.user.product.getProductDetails.useQuery(
|
||||||
|
|
|
||||||
|
|
@ -1,14 +1,11 @@
|
||||||
import React, { useState, useMemo } from 'react';
|
import React, { useState, useMemo } from 'react';
|
||||||
import { View, ScrollView, Dimensions, Alert } from 'react-native';
|
import { View, ScrollView, Dimensions, Alert } from 'react-native';
|
||||||
import { useRouter } from 'expo-router';
|
import { useRouter } from 'expo-router';
|
||||||
import { useQueryClient } from '@tanstack/react-query';
|
|
||||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
||||||
import { BottomDialog, MyTouchableOpacity, MyText, tw, theme } from 'common-ui';
|
import { BottomDialog, MyTouchableOpacity, MyText, tw, theme } from 'common-ui';
|
||||||
import { useAuth } from '@/src/contexts/AuthContext';
|
import { useAuth } from '@/src/contexts/AuthContext';
|
||||||
import { trpc } from '@/src/trpc-client';
|
import { trpc } from '@/src/trpc-client';
|
||||||
import { useAddressStore } from '@/src/store/addressStore';
|
import { useRegionNeo } from '@/src/hooks/useRegionNeo';
|
||||||
import { useRegion } from '@/src/hooks/useRegion';
|
|
||||||
import { confirmRegionSwitch } from '@/src/lib/region-switch';
|
|
||||||
import { useSlots } from '@/src/hooks/prominent-api-hooks';
|
import { useSlots } from '@/src/hooks/prominent-api-hooks';
|
||||||
import LocationBar from '@/src/components/LocationBar';
|
import LocationBar from '@/src/components/LocationBar';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
|
|
@ -30,7 +27,10 @@ const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps>
|
||||||
const [dialogOpen, setDialogOpen] = useState(false);
|
const [dialogOpen, setDialogOpen] = useState(false);
|
||||||
|
|
||||||
const { isAuthenticated } = useAuth();
|
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: defaultAddressData } = trpc.user.address.getDefaultAddress.useQuery();
|
||||||
const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, {
|
const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, {
|
||||||
|
|
@ -41,8 +41,6 @@ const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps>
|
||||||
const defaultAddress = defaultAddressData?.data;
|
const defaultAddress = defaultAddressData?.data;
|
||||||
const addresses = addressesData?.data || [];
|
const addresses = addressesData?.data || [];
|
||||||
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const { regionId: selectedRegionId } = useRegion();
|
|
||||||
const { data: regions } = trpc.common.listRegions.useQuery();
|
const { data: regions } = trpc.common.listRegions.useQuery();
|
||||||
|
|
||||||
// An address (selected or default) that belongs to another region than the
|
// An address (selected or default) that belongs to another region than the
|
||||||
|
|
@ -73,7 +71,7 @@ const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps>
|
||||||
style: 'destructive',
|
style: 'destructive',
|
||||||
onPress: () => {
|
onPress: () => {
|
||||||
void (async () => {
|
void (async () => {
|
||||||
await confirmRegionSwitch(targetRegion, queryClient, foreignAddress.boundId ?? targetRegion.effectiveBoundId ?? null);
|
await neo.selectAddress(foreignAddress.id);
|
||||||
router.replace('/(drawer)/(tabs)/home');
|
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'
|
address.id === (selectedAddressId || defaultAddress?.id) ? 'bg-brand50 border-brand500' : 'bg-white'
|
||||||
}`}
|
}`}
|
||||||
onPress={() => {
|
onPress={() => {
|
||||||
setSelectedAddressId(address.id);
|
void selectAddress?.(address.id);
|
||||||
setAddressDialogOpen(false);
|
setAddressDialogOpen(false);
|
||||||
}}
|
}}
|
||||||
activeOpacity={0.7}
|
activeOpacity={0.7}
|
||||||
|
|
|
||||||
|
|
@ -29,12 +29,12 @@ import { useCentralProductStore, type Product } from '@/src/store/centralProduct
|
||||||
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
|
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
|
||||||
import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-query-hooks';
|
import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-query-hooks';
|
||||||
import { useRegionalConsts } from '@/src/hooks/prominent-api-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 CheckoutAddressSelector from '@/components/CheckoutAddressSelector';
|
||||||
import CouponBreakdownDialog from '@/src/components/CouponBreakdownDialog';
|
import CouponBreakdownDialog from '@/src/components/CouponBreakdownDialog';
|
||||||
import LoginWall from '@/components/LoginWall';
|
import LoginWall from '@/components/LoginWall';
|
||||||
import CartAddressGate from '@/components/CartAddressGate';
|
import CartAddressGate from '@/components/CartAddressGate';
|
||||||
import { useAddressStore } from '@/src/store/addressStore';
|
|
||||||
import { useCheckoutStore } from '@/src/store/checkoutStore';
|
import { useCheckoutStore } from '@/src/store/checkoutStore';
|
||||||
import type { FlashDeliveryProps } from '@packages/shared';
|
import type { FlashDeliveryProps } from '@packages/shared';
|
||||||
import { computeCouponStack, computeCouponLineBreakdowns, evaluateCouponEligibility, type CartLine, type CouponLineBreakdown } 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 { isAuthenticated, isLoading: isAuthLoading } = useAuth();
|
||||||
const cartType: "regular" | "flash" = isFlashDelivery ? "flash" : "regular";
|
const cartType: "regular" | "flash" = isFlashDelivery ? "flash" : "regular";
|
||||||
|
|
||||||
const { selectedAddressId, setSelectedAddressId } = useAddressStore();
|
const neo = useRegionNeo();
|
||||||
const { regionId } = useRegion();
|
const selectedAddressId = neo.selectedAddressId;
|
||||||
|
const regionId = neo.regionId;
|
||||||
// First-address gate: the region can exist (from the location) with no address yet.
|
// First-address gate: the region can exist (from the location) with no address yet.
|
||||||
const addressesQuery = trpc.user.address.getUserAddresses.useQuery(undefined, {
|
const addressesQuery = trpc.user.address.getUserAddresses.useQuery(undefined, {
|
||||||
enabled: isAuthenticated,
|
enabled: isAuthenticated,
|
||||||
|
|
@ -879,7 +880,9 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
||||||
</View>
|
</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 (
|
return (
|
||||||
<CartAddressGate
|
<CartAddressGate
|
||||||
onDone={() => {
|
onDone={() => {
|
||||||
|
|
@ -1447,10 +1450,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
{/* Delivery Address */}
|
{/* Delivery Address */}
|
||||||
<CheckoutAddressSelector
|
<CheckoutAddressSelector />
|
||||||
selectedAddress={selectedAddressId}
|
|
||||||
onAddressSelect={setSelectedAddressId}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* Bottom Checkout Bar - Now Static */}
|
{/* Bottom Checkout Bar - Now Static */}
|
||||||
{hasAvailableItems && (
|
{hasAvailableItems && (
|
||||||
|
|
|
||||||
|
|
@ -12,11 +12,11 @@ import { useCentralProductStore } from '@/src/store/centralProductStore';
|
||||||
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
|
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
|
||||||
import { useGetCart } from '@/hooks/cart-query-hooks';
|
import { useGetCart } from '@/hooks/cart-query-hooks';
|
||||||
import { useRegionalConsts } from '@/src/hooks/prominent-api-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 PaymentAndOrderComponent from '@/components/PaymentAndOrderComponent';
|
||||||
import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay';
|
import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay';
|
||||||
import CouponBreakdownDialog from '@/src/components/CouponBreakdownDialog';
|
import CouponBreakdownDialog from '@/src/components/CouponBreakdownDialog';
|
||||||
import { useAddressStore } from '@/src/store/addressStore';
|
|
||||||
import type { FlashDeliveryProps } from '@packages/shared';
|
import type { FlashDeliveryProps } from '@packages/shared';
|
||||||
import { computeCouponStack, computeCouponLineBreakdowns, evaluateCouponEligibility, type CartLine, type CouponLineBreakdown } 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
|
// Slots are per-region and the order is placed with this same region
|
||||||
// (see PaymentAndOrderComponent), so scope the query to it.
|
// (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
|
// Protect checkout route and preserve query params
|
||||||
useAuthenticatedRoute({
|
useAuthenticatedRoute({
|
||||||
|
|
@ -57,7 +58,7 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
||||||
refetchSlots();
|
refetchSlots();
|
||||||
});
|
});
|
||||||
|
|
||||||
const { selectedAddressId } = useAddressStore();
|
const selectedAddressId = neo.selectedAddressId;
|
||||||
const [selectedCouponIds, setSelectedCouponIds] = useState<number[]>([]);
|
const [selectedCouponIds, setSelectedCouponIds] = useState<number[]>([]);
|
||||||
// Coupon whose per-product discount split is open (product-specific coupons only).
|
// Coupon whose per-product discount split is open (product-specific coupons only).
|
||||||
const [breakdownCouponId, setBreakdownCouponId] = useState<number | null>(null);
|
const [breakdownCouponId, setBreakdownCouponId] = useState<number | null>(null);
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ import { trpc } from '../trpc-client';
|
||||||
import LocationMapStep from './location/LocationMapStep';
|
import LocationMapStep from './location/LocationMapStep';
|
||||||
import type { AddressFormProps, RegionSummary } from '@packages/shared';
|
import type { AddressFormProps, RegionSummary } from '@packages/shared';
|
||||||
import { savePendingAddress } from '@/src/lib/pending-address';
|
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';
|
import { useLocationStore } from '@/src/store/locationStore';
|
||||||
|
|
||||||
type Coords = { latitude: number; longitude: number };
|
type Coords = { latitude: number; longitude: number };
|
||||||
|
|
@ -19,6 +19,12 @@ type LocationSource = 'device' | 'map';
|
||||||
const AddressForm: React.FC<AddressFormProps & {
|
const AddressForm: React.FC<AddressFormProps & {
|
||||||
/** Reported so a bottom sheet can size itself to the form when idle. */
|
/** Reported so a bottom sheet can size itself to the form when idle. */
|
||||||
onContentHeightChange?: (height: number) => void;
|
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,
|
onSuccess,
|
||||||
initialValues,
|
initialValues,
|
||||||
|
|
@ -26,8 +32,12 @@ const AddressForm: React.FC<AddressFormProps & {
|
||||||
draftMode = false,
|
draftMode = false,
|
||||||
onResolvedRegion,
|
onResolvedRegion,
|
||||||
onContentHeightChange,
|
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 deviceCoords = useLocationStore((state) => state.coords);
|
||||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
const [submitError, setSubmitError] = useState<string | null>(null);
|
const [submitError, setSubmitError] = useState<string | null>(null);
|
||||||
|
|
@ -205,6 +215,10 @@ const AddressForm: React.FC<AddressFormProps & {
|
||||||
const createAddressMutation = trpc.user.address.createAddress.useMutation({
|
const createAddressMutation = trpc.user.address.createAddress.useMutation({
|
||||||
onSuccess: (data) => {
|
onSuccess: (data) => {
|
||||||
setIsSubmitting(false);
|
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;
|
const addressId = data?.data?.id;
|
||||||
// Delay to allow modal to close animation
|
// Delay to allow modal to close animation
|
||||||
setTimeout(() => onSuccess(addressId), 350);
|
setTimeout(() => onSuccess(addressId), 350);
|
||||||
|
|
@ -218,6 +232,8 @@ const AddressForm: React.FC<AddressFormProps & {
|
||||||
const updateAddressMutation = trpc.user.address.updateAddress.useMutation({
|
const updateAddressMutation = trpc.user.address.updateAddress.useMutation({
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
setIsSubmitting(false);
|
setIsSubmitting(false);
|
||||||
|
void utils.user.address.getUserAddresses.invalidate();
|
||||||
|
void utils.user.address.getDefaultAddress.invalidate();
|
||||||
// Delay to allow modal to close animation
|
// Delay to allow modal to close animation
|
||||||
setTimeout(() => onSuccess(), 350);
|
setTimeout(() => onSuccess(), 350);
|
||||||
},
|
},
|
||||||
|
|
@ -242,6 +258,9 @@ const AddressForm: React.FC<AddressFormProps & {
|
||||||
// not be saveable.
|
// not be saveable.
|
||||||
const isLocationServiceable =
|
const isLocationServiceable =
|
||||||
currentLocation != null && resolvedRegion != null && !locationError && !isCheckingLocation;
|
currentLocation != null && resolvedRegion != null && !locationError && !isCheckingLocation;
|
||||||
|
const actionLabel = isEdit ? 'Update Address' : 'Add Address';
|
||||||
|
const progressingLabel = isEdit ? 'Updating...' : 'Adding...';
|
||||||
|
const submitLabel = isSubmitting ? progressingLabel : actionLabel;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<KeyboardAvoidingView
|
<KeyboardAvoidingView
|
||||||
|
|
@ -287,6 +306,10 @@ const AddressForm: React.FC<AddressFormProps & {
|
||||||
setSubmitError(locationError || 'Please choose a town and a location inside it.');
|
setSubmitError(locationError || 'Please choose a town and a location inside it.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (onBeforeSubmit) {
|
||||||
|
const allowed = await onBeforeSubmit();
|
||||||
|
if (!allowed) return;
|
||||||
|
}
|
||||||
setIsSubmitting(true);
|
setIsSubmitting(true);
|
||||||
setSubmitError(null);
|
setSubmitError(null);
|
||||||
const payload = {
|
const payload = {
|
||||||
|
|
@ -455,7 +478,7 @@ const AddressForm: React.FC<AddressFormProps & {
|
||||||
disabled={isSubmitting || !isLocationServiceable}
|
disabled={isSubmitting || !isLocationServiceable}
|
||||||
>
|
>
|
||||||
<MyText style={tw`text-white text-center font-bold`}>
|
<MyText style={tw`text-white text-center font-bold`}>
|
||||||
{isSubmitting ? (isEdit ? 'Updating...' : 'Adding...') : (isEdit ? 'Update Address' : 'Add Address')}
|
{submitLabel}
|
||||||
</MyText>
|
</MyText>
|
||||||
</MyTouchableOpacity>
|
</MyTouchableOpacity>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,20 +2,10 @@ import React, { useState } from 'react'
|
||||||
import { View } from 'react-native'
|
import { View } from 'react-native'
|
||||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||||
import { tw, theme, MyText, MyTouchableOpacity } from 'common-ui'
|
import { tw, theme, MyText, MyTouchableOpacity } from 'common-ui'
|
||||||
import { useRegion } from '@/src/hooks/useRegion'
|
import { useRegionNeo } from '@/src/hooks/useRegionNeo'
|
||||||
import { useAddressStore } from '@/src/store/addressStore'
|
|
||||||
import { useAuthOptional } from '@/src/contexts/AuthContext'
|
|
||||||
import { trpc } from '@/src/trpc-client'
|
|
||||||
import AddressSwitcherSheet from '@/src/components/location/AddressSwitcherSheet'
|
import AddressSwitcherSheet from '@/src/components/location/AddressSwitcherSheet'
|
||||||
import { useRenderProbe } from '@/src/lib/render-probe'
|
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.
|
* Location bar shown at the top of every top-level tab screen.
|
||||||
* Rendered INSIDE the scroll content (first item / ListHeaderComponent) so it
|
* Rendered INSIDE the scroll content (first item / ListHeaderComponent) so it
|
||||||
|
|
@ -28,27 +18,20 @@ const formatAddress = (address: {
|
||||||
const LocationBar: React.FC = () => {
|
const LocationBar: React.FC = () => {
|
||||||
useRenderProbe('component:LocationBar')
|
useRenderProbe('component:LocationBar')
|
||||||
const [sheetOpen, setSheetOpen] = useState(false)
|
const [sheetOpen, setSheetOpen] = useState(false)
|
||||||
const { region } = useRegion()
|
const neo = useRegionNeo()
|
||||||
|
const regionName = neo.regionName
|
||||||
const isAuthenticated = useAuthOptional()?.isAuthenticated ?? false
|
const fullAddress = neo.fullAddress
|
||||||
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
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={tw`px-4 pt-3 pb-1`}>
|
<View style={tw`px-4 pt-3 pb-1`}>
|
||||||
<MyTouchableOpacity
|
<MyTouchableOpacity
|
||||||
testID="location-bar"
|
testID="location-bar"
|
||||||
activeOpacity={0.85}
|
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`}
|
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`}>
|
<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-1`}>
|
||||||
<View style={tw`flex-row items-center`}>
|
<View style={tw`flex-row items-center`}>
|
||||||
<MyText style={tw`text-xs text-gray-500 mr-2`}>Deliver to</MyText>
|
<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
|
// 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
|
// pill shrinks (flex-shrink) so a long name truncates instead of
|
||||||
// pushing the chevron out of the row.
|
// pushing the chevron out of the row.
|
||||||
|
|
@ -68,7 +51,7 @@ const LocationBar: React.FC = () => {
|
||||||
numberOfLines={1}
|
numberOfLines={1}
|
||||||
ellipsizeMode="tail"
|
ellipsizeMode="tail"
|
||||||
>
|
>
|
||||||
{region.name}
|
{regionName}
|
||||||
</MyText>
|
</MyText>
|
||||||
</View>
|
</View>
|
||||||
) : (
|
) : (
|
||||||
|
|
@ -77,7 +60,7 @@ const LocationBar: React.FC = () => {
|
||||||
</MyText>
|
</MyText>
|
||||||
)}
|
)}
|
||||||
</View>
|
</View>
|
||||||
{activeAddress ? (
|
{fullAddress ? (
|
||||||
<MyText
|
<MyText
|
||||||
style={tw`text-xs text-gray-500 mt-1`}
|
style={tw`text-xs text-gray-500 mt-1`}
|
||||||
// Exactly one address line: anything longer ellipsises with "…"
|
// Exactly one address line: anything longer ellipsises with "…"
|
||||||
|
|
@ -85,7 +68,7 @@ const LocationBar: React.FC = () => {
|
||||||
numberOfLines={1}
|
numberOfLines={1}
|
||||||
ellipsizeMode="tail"
|
ellipsizeMode="tail"
|
||||||
>
|
>
|
||||||
{formatAddress(activeAddress)}
|
{fullAddress}
|
||||||
</MyText>
|
</MyText>
|
||||||
) : null}
|
) : null}
|
||||||
</View>
|
</View>
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import React, { useEffect, useRef } from 'react'
|
import React, { useEffect, useRef } from 'react'
|
||||||
import { trpc } from '@/src/trpc-client'
|
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'
|
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
|
* 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
|
* only place the push token is available. Both ways a region becomes known land
|
||||||
* here:
|
* here:
|
||||||
* - a tracked device location — useRegion resolves it (and `bound` is set only
|
* - a tracked device location — useRegionNeo resolves it (origin === 'device'), or
|
||||||
* for that path), or
|
|
||||||
* - an added address (incl. the signed-out local draft) — the location
|
* - an added address (incl. the signed-out local draft) — the location
|
||||||
* fallback switches the region, which clears the gate and mounts this
|
* fallback switches the region, which clears the gate and mounts this
|
||||||
* component with the new region already in place.
|
* 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 NotifRegionSync: React.FC = () => {
|
||||||
const { expoPushToken, notifPermission } = useNotification()
|
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
|
// Both calls are best-effort telemetry for notifications: a failure is logged
|
||||||
// and ignored, never surfaced or retried.
|
// and ignored, never surfaced or retried.
|
||||||
const savePushToken = trpc.user.user.savePushToken.useMutation({
|
const savePushToken = trpc.user.user.savePushToken.useMutation({
|
||||||
|
|
@ -45,19 +46,18 @@ const NotifRegionSync: React.FC = () => {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!expoPushToken || notifPermission !== 'granted' || regionId == null) return
|
if (!expoPushToken || notifPermission !== 'granted' || regionId == null) return
|
||||||
|
|
||||||
const fromLocation = bound != null
|
const fromLocation = origin === 'device'
|
||||||
const key = `${expoPushToken}:${regionId}:${fromLocation ? 'loc' : 'addr'}`
|
const key = `${expoPushToken}:${regionId}:${fromLocation ? 'loc' : 'addr'}`
|
||||||
if (lastSynced.current === key) return
|
if (lastSynced.current === key) return
|
||||||
lastSynced.current = key
|
lastSynced.current = key
|
||||||
|
|
||||||
savePushTokenMutate({ token: expoPushToken, regionId })
|
savePushTokenMutate({ token: expoPushToken, regionId })
|
||||||
|
|
||||||
// `bound` is set only when the region came from the device fix, so this is
|
// `origin === 'device'` is exactly the "location was tracked" case.
|
||||||
// exactly the "location was tracked" case.
|
|
||||||
if (fromLocation) {
|
if (fromLocation) {
|
||||||
recordTrackedRegionMutate({ regionId })
|
recordTrackedRegionMutate({ regionId })
|
||||||
}
|
}
|
||||||
}, [expoPushToken, notifPermission, regionId, bound, savePushTokenMutate, recordTrackedRegionMutate])
|
}, [expoPushToken, notifPermission, regionId, origin, savePushTokenMutate, recordTrackedRegionMutate])
|
||||||
|
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,8 @@ import { useEffect, useRef } from 'react'
|
||||||
import { trpc } from '@/src/trpc-client'
|
import { trpc } from '@/src/trpc-client'
|
||||||
import { useAuth } from '@/src/contexts/AuthContext'
|
import { useAuth } from '@/src/contexts/AuthContext'
|
||||||
import { clearPendingAddress, getPendingAddress } from '@/src/lib/pending-address'
|
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
|
* Posts a locally-drafted address (created while signed out in the location
|
||||||
|
|
@ -26,10 +28,23 @@ const PendingAddressSync: React.FC = () => {
|
||||||
|
|
||||||
isSyncing.current = true
|
isSyncing.current = true
|
||||||
try {
|
try {
|
||||||
await createAddress.mutateAsync(pending)
|
const created = await createAddress.mutateAsync(pending)
|
||||||
await clearPendingAddress()
|
await clearPendingAddress()
|
||||||
await utils.user.address.getUserAddresses.invalidate()
|
await utils.user.address.getUserAddresses.invalidate()
|
||||||
await utils.user.address.getDefaultAddress.invalidate()
|
await utils.user.address.getDefaultAddress.invalidate()
|
||||||
|
|
||||||
|
// The draft was the address the user was checking out with; make it the
|
||||||
|
// active selection as soon as the list is available.
|
||||||
|
try {
|
||||||
|
const response = await utils.user.address.getUserAddresses.fetch(undefined)
|
||||||
|
useNeoRegionStore.getState().setAddresses(response.data.map(toNeoAddress))
|
||||||
|
const createdId = created?.data?.id
|
||||||
|
if (createdId != null) {
|
||||||
|
await useNeoRegionStore.getState().selectAddress(createdId)
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// The subscription will refresh the list; the decision selects the default.
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Leave the draft in place; a later authenticated mount retries it.
|
// Leave the draft in place; a later authenticated mount retries it.
|
||||||
} finally {
|
} finally {
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import React from 'react'
|
import React from 'react'
|
||||||
import { Modal, View } from 'react-native'
|
import { Modal, View } from 'react-native'
|
||||||
import { tw } from 'common-ui'
|
import { tw } from 'common-ui'
|
||||||
import LocationFallbackFlow from './LocationFallbackFlow'
|
import NeoAddressFlow from './neo/NeoAddressFlow'
|
||||||
|
|
||||||
interface AddressSwitcherSheetProps {
|
interface AddressSwitcherSheetProps {
|
||||||
open: boolean
|
open: boolean
|
||||||
|
|
@ -16,7 +16,7 @@ interface AddressSwitcherSheetProps {
|
||||||
const AddressSwitcherSheet: React.FC<AddressSwitcherSheetProps> = ({ open, onClose }) => (
|
const AddressSwitcherSheet: React.FC<AddressSwitcherSheetProps> = ({ open, onClose }) => (
|
||||||
<Modal visible={open} animationType="slide" onRequestClose={onClose}>
|
<Modal visible={open} animationType="slide" onRequestClose={onClose}>
|
||||||
<View style={tw`flex-1 bg-white`}>
|
<View style={tw`flex-1 bg-white`}>
|
||||||
<LocationFallbackFlow onClose={onClose} />
|
<NeoAddressFlow onClose={onClose} />
|
||||||
</View>
|
</View>
|
||||||
</Modal>
|
</Modal>
|
||||||
)
|
)
|
||||||
|
|
|
||||||
206
apps/user-ui/src/components/location/neo/NeoAddressFlow.tsx
Normal file
206
apps/user-ui/src/components/location/neo/NeoAddressFlow.tsx
Normal file
|
|
@ -0,0 +1,206 @@
|
||||||
|
import React, { useEffect, useRef, useState } from 'react'
|
||||||
|
import { ScrollView, View } from 'react-native'
|
||||||
|
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||||
|
import { MyText, MyTouchableOpacity, tw } from 'common-ui'
|
||||||
|
import Login from '@/app/(auth)/login'
|
||||||
|
import { useAuthOptional } from '@/src/contexts/AuthContext'
|
||||||
|
import { useLocationStore } from '@/src/store/locationStore'
|
||||||
|
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
|
||||||
|
import { formatNeoAddress } from '@/src/lib/neo-address'
|
||||||
|
import NeoAddressForm from './NeoAddressForm'
|
||||||
|
|
||||||
|
interface NeoAddressFlowProps {
|
||||||
|
/** Present when hosted in the location-bar sheet. */
|
||||||
|
onClose?: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const NOTICE: Partial<Record<string, string>> = {
|
||||||
|
denied: 'Location access is not granted. Allow it for accurate delivery, or add an address below.',
|
||||||
|
'services-off': 'Your device location is turned off. Turn it on, or add an address below.',
|
||||||
|
unavailable: 'We could not get your location. Try again, or add an address below.',
|
||||||
|
error: 'We could not get your location. Try again, or add an address below.',
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The whole address fallback: choose a saved address, add one, or sign in.
|
||||||
|
* Used both by the wrapper (no usable region) and by the location bar sheet.
|
||||||
|
*/
|
||||||
|
const NeoAddressFlow: React.FC<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 locationStatus = useLocationStore((state) => state.status)
|
||||||
|
|
||||||
|
const [mode, setMode] = useState<'choose' | 'add' | 'login'>('choose')
|
||||||
|
const autoOpened = useRef(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (mode === 'login' && isAuthenticated) setMode('choose')
|
||||||
|
}, [mode, isAuthenticated])
|
||||||
|
|
||||||
|
// With exactly one saved address the startup gate can open it without making
|
||||||
|
// the user tap a one-item list. Only the gate: when this flow is the
|
||||||
|
// location-bar sheet (onClose) the user opened it to look at or change the
|
||||||
|
// address, so auto-selecting would flash the sheet open and closed — which
|
||||||
|
// reads as a dead tap. A published region also means the gate is not showing
|
||||||
|
// the startup chooser (e.g. "add an address here" from the confirmation).
|
||||||
|
useEffect(() => {
|
||||||
|
if (onClose != null || regionId != null) return
|
||||||
|
if (mode !== 'choose' || !isAuthenticated || autoOpened.current) return
|
||||||
|
if (addresses.length !== 1) return
|
||||||
|
autoOpened.current = true
|
||||||
|
void selectAddress(addresses[0].id).then(() => {
|
||||||
|
// Its region may no longer be serviceable; closing would strand the
|
||||||
|
// loading screen, so keep the chooser up instead.
|
||||||
|
if (useNeoRegionStore.getState().regionId == null) return
|
||||||
|
closeAddressFlow()
|
||||||
|
})
|
||||||
|
}, [onClose, regionId, mode, isAuthenticated, addresses, selectAddress, closeAddressFlow])
|
||||||
|
|
||||||
|
const pick = async (id: number) => {
|
||||||
|
await selectAddress(id)
|
||||||
|
closeAddressFlow()
|
||||||
|
onClose?.()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mode === 'add') {
|
||||||
|
return (
|
||||||
|
<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>
|
||||||
|
<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>
|
||||||
|
|
||||||
|
{NOTICE[locationStatus] && regionId == null && (
|
||||||
|
<View style={tw`mt-4 bg-amber-50 border border-amber-200 rounded-xl p-3`}>
|
||||||
|
<MyText style={tw`text-amber-800 text-sm`}>{NOTICE[locationStatus]}</MyText>
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<MyTouchableOpacity
|
||||||
|
testID="neo-add-address"
|
||||||
|
onPress={() => setMode('add')}
|
||||||
|
activeOpacity={0.85}
|
||||||
|
style={tw`mt-2 bg-indigo-600 py-3.5 rounded-xl items-center`}
|
||||||
|
>
|
||||||
|
<MyText style={tw`text-white font-bold`}>Add new address</MyText>
|
||||||
|
</MyTouchableOpacity>
|
||||||
|
|
||||||
|
{!isAuthenticated && (
|
||||||
|
<MyTouchableOpacity
|
||||||
|
testID="neo-location-login"
|
||||||
|
onPress={() => setMode('login')}
|
||||||
|
activeOpacity={0.85}
|
||||||
|
style={tw`mt-3 border border-gray-200 py-3.5 rounded-xl items-center`}
|
||||||
|
>
|
||||||
|
<MyText style={tw`text-gray-700 font-bold`}>Sign in to save your address</MyText>
|
||||||
|
</MyTouchableOpacity>
|
||||||
|
)}
|
||||||
|
</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
|
||||||
|
|
@ -6,8 +6,7 @@ import type { ProductPriceFlags } from '@packages/shared'
|
||||||
import { AllProductsApiType, StoresApiType, SlotsApiType, EssentialConstsApiType, StoreWithProductsApiType, AvailabilityApiType } from "@backend/trpc/router";
|
import { AllProductsApiType, StoresApiType, SlotsApiType, EssentialConstsApiType, StoreWithProductsApiType, AvailabilityApiType } from "@backend/trpc/router";
|
||||||
import { CACHE_FILENAMES, availabilityCacheUrl, cachedFileUrl, regionCacheUrl, slotsCacheUrl, storeDetailCacheUrl } from "@packages/shared";
|
import { CACHE_FILENAMES, availabilityCacheUrl, cachedFileUrl, regionCacheUrl, slotsCacheUrl, storeDetailCacheUrl } from "@packages/shared";
|
||||||
import { StorageServiceCasual } from 'common-ui';
|
import { StorageServiceCasual } from 'common-ui';
|
||||||
import { useRegion } from '@/src/hooks/useRegion'
|
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
|
||||||
import { useAddressStore } from '@/src/store/addressStore'
|
|
||||||
import { useAuthOptional } from '@/src/contexts/AuthContext'
|
import { useAuthOptional } from '@/src/contexts/AuthContext'
|
||||||
|
|
||||||
// Discovery payload: the flat per-bound consts object (global + region + bound
|
// 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}`
|
const essentialConstsKey = (boundId: number) => `essential_consts_b${boundId}`
|
||||||
|
|
||||||
export const useGetEssentialConsts = () => {
|
export const useGetEssentialConsts = () => {
|
||||||
// The active bound (least-priority bound among the user's addresses in the
|
// The active bound drives the constants. This hook runs above the location
|
||||||
// region, else the region's effective bound) drives the constants; at checkout
|
// wrapper (UpdateChecker / HealthTestWrapper), so it reads the store directly
|
||||||
// the selected address's bound overrides it.
|
// and tolerates an empty store instead of calling useRegionNeo.
|
||||||
const { boundId: activeBoundId, coords, regionId } = useRegion()
|
const activeBoundId = useNeoRegionStore((state) => state.boundId)
|
||||||
|
const regionId = useNeoRegionStore((state) => state.regionId)
|
||||||
const isAuthenticated = useAuthOptional()?.isAuthenticated ?? false
|
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, {
|
const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, {
|
||||||
enabled: isAuthenticated && selectedAddressId != null,
|
enabled: isAuthenticated && selectedAddressId != null,
|
||||||
|
|
@ -117,7 +117,7 @@ export type MergedProduct = BaseProduct & ProductPriceFlags & {
|
||||||
}
|
}
|
||||||
|
|
||||||
function useDiscoveryRegionId(essentialConsts: unknown): number | null {
|
function useDiscoveryRegionId(essentialConsts: unknown): number | null {
|
||||||
const { regionId: selectedRegionId } = useRegion()
|
const selectedRegionId = useNeoRegionStore((state) => state.regionId)
|
||||||
const discovery = essentialConsts as DiscoveryData | undefined
|
const discovery = essentialConsts as DiscoveryData | undefined
|
||||||
return discovery?.regionId ?? selectedRegionId
|
return discovery?.regionId ?? selectedRegionId
|
||||||
}
|
}
|
||||||
|
|
|
||||||
403
apps/user-ui/src/hooks/useRegionNeo.ts
Normal file
403
apps/user-ui/src/hooks/useRegionNeo.ts
Normal file
|
|
@ -0,0 +1,403 @@
|
||||||
|
import { useEffect, useRef, useState } from 'react'
|
||||||
|
import { useQueryClient } from '@tanstack/react-query'
|
||||||
|
import type { RegionSummary } from '@packages/shared'
|
||||||
|
import { trpc } from '@/src/trpc-client'
|
||||||
|
import { useAuthOptional } from '@/src/contexts/AuthContext'
|
||||||
|
import { useLocationStore } from '@/src/store/locationStore'
|
||||||
|
import {
|
||||||
|
bindNeoRegionQueryClient,
|
||||||
|
useNeoRegionStore,
|
||||||
|
type NeoRegionData,
|
||||||
|
} from '@/src/store/neoRegionStore'
|
||||||
|
import {
|
||||||
|
decideNeoRegion,
|
||||||
|
type NeoCachedSnapshot,
|
||||||
|
type NeoResolvedRegion,
|
||||||
|
} from '@/src/lib/neo-region-decision'
|
||||||
|
import { readNeoRegionSnapshot } from '@/src/lib/neo-region-cache'
|
||||||
|
import { applyRegionSwitch } from '@/src/lib/neo-region-switch'
|
||||||
|
import {
|
||||||
|
formatNeoAddress,
|
||||||
|
toNeoAddress,
|
||||||
|
type NeoAddress,
|
||||||
|
type NeoCoords,
|
||||||
|
} from '@/src/lib/neo-address'
|
||||||
|
|
||||||
|
export type { NeoRegionData }
|
||||||
|
|
||||||
|
// One launch decision per app launch. The recovery poll resets it deliberately.
|
||||||
|
let decisionStarted = false
|
||||||
|
let snapshotRead: Promise<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)
|
||||||
|
|
||||||
|
const addressesQuery = trpc.user.address.getUserAddresses.useQuery(undefined, {
|
||||||
|
enabled: isAuthenticated,
|
||||||
|
})
|
||||||
|
// Starts on mount, in parallel with the device fix. The decision waits for it
|
||||||
|
// instead of fetching regions inside `run`.
|
||||||
|
const regionsQuery = trpc.common.listRegions.useQuery()
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
bindNeoRegionQueryClient(queryClient)
|
||||||
|
}, [queryClient])
|
||||||
|
|
||||||
|
// One device fix per launch. The store is a singleton and start() is idempotent.
|
||||||
|
useEffect(() => {
|
||||||
|
startTracking()
|
||||||
|
}, [startTracking])
|
||||||
|
|
||||||
|
// Publish the persisted snapshot immediately; the decision may switch later.
|
||||||
|
useEffect(() => {
|
||||||
|
if (snapshotRead == null) snapshotRead = readNeoRegionSnapshot()
|
||||||
|
let cancelled = false
|
||||||
|
void snapshotRead.then((snapshot) => {
|
||||||
|
if (cancelled || snapshot == null) return
|
||||||
|
const current = useNeoRegionStore.getState()
|
||||||
|
if (current.regionId != null) return
|
||||||
|
const cachedAddress =
|
||||||
|
snapshot.selectedAddress != null &&
|
||||||
|
snapshot.selectedAddress.regionId === snapshot.regionId
|
||||||
|
? snapshot.selectedAddress
|
||||||
|
: null
|
||||||
|
if (cachedAddress != null) {
|
||||||
|
// Provisional: the live list replaces this entry, and validation clears
|
||||||
|
// the selection if the address no longer exists.
|
||||||
|
current.setAddresses([cachedAddress])
|
||||||
|
}
|
||||||
|
current.applyRegion({
|
||||||
|
regionId: snapshot.regionId,
|
||||||
|
boundId: snapshot.boundId,
|
||||||
|
regionName: snapshot.regionName,
|
||||||
|
coords: snapshot.coords,
|
||||||
|
origin: 'cache',
|
||||||
|
selectedAddressId: cachedAddress?.id ?? null,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
// Keep the store's address list in sync with the live query. Re-applying the
|
||||||
|
// selected address keeps its coords/bound fresh after an edit (e.g. attach
|
||||||
|
// current location), and is a no-op when nothing changed.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!addressesQuery.data) return
|
||||||
|
const store = useNeoRegionStore.getState()
|
||||||
|
store.setAddresses(addressesQuery.data.data.map(toNeoAddress))
|
||||||
|
const selectedId = useNeoRegionStore.getState().selectedAddressId
|
||||||
|
if (selectedId != null) void useNeoRegionStore.getState().selectAddress(selectedId)
|
||||||
|
}, [addressesQuery.data])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isAuthenticated) return
|
||||||
|
useNeoRegionStore.getState().setAddresses([])
|
||||||
|
}, [isAuthenticated])
|
||||||
|
|
||||||
|
// A hanging location read must not strand the first launch.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!hasAuthContext) return
|
||||||
|
const timer = setTimeout(() => setTimedOut(true), LOCATION_TIMEOUT_MS)
|
||||||
|
return () => clearTimeout(timer)
|
||||||
|
}, [hasAuthContext])
|
||||||
|
|
||||||
|
// Logging in or out changes the address anchor; re-run the decision once.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!hasAuthContext || isAuthLoading) return
|
||||||
|
if (lastAuthRef.current == null) {
|
||||||
|
lastAuthRef.current = isAuthenticated
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (lastAuthRef.current !== isAuthenticated) {
|
||||||
|
lastAuthRef.current = isAuthenticated
|
||||||
|
decisionStarted = false
|
||||||
|
setDecisionTick((tick) => tick + 1)
|
||||||
|
}
|
||||||
|
}, [hasAuthContext, isAuthLoading, isAuthenticated])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!hasAuthContext || isAuthLoading) return
|
||||||
|
if (decisionStarted) return
|
||||||
|
|
||||||
|
const settled =
|
||||||
|
coords != null ||
|
||||||
|
(TERMINAL_LOCATION_STATUSES as readonly string[]).includes(locationStatus)
|
||||||
|
if (!settled && !timedOut) return
|
||||||
|
|
||||||
|
// These queries start on mount / when auth settles; wait for them rather
|
||||||
|
// than fetching them sequentially here.
|
||||||
|
const regionsReady = regionsQuery.isFetched || regionsQuery.isError
|
||||||
|
const addressesReady =
|
||||||
|
!isAuthenticated || addressesQuery.isFetched || addressesQuery.isError
|
||||||
|
if (!regionsReady || !addressesReady) return
|
||||||
|
|
||||||
|
decisionStarted = true
|
||||||
|
|
||||||
|
const run = async () => {
|
||||||
|
const fix = useLocationStore.getState().coords
|
||||||
|
|
||||||
|
// The snapshot read and the coordinate resolve are independent.
|
||||||
|
const [snapshot, resolveResult] = await Promise.all([
|
||||||
|
snapshotRead ?? readNeoRegionSnapshot(),
|
||||||
|
fix != null
|
||||||
|
? utils.common.resolveRegionByLocation
|
||||||
|
.fetch({ lat: fix.latitude, lng: fix.longitude })
|
||||||
|
.catch(() => null)
|
||||||
|
: Promise.resolve(null),
|
||||||
|
])
|
||||||
|
|
||||||
|
const store = useNeoRegionStore.getState()
|
||||||
|
|
||||||
|
let cached: NeoCachedSnapshot | null = null
|
||||||
|
if (
|
||||||
|
store.regionId != null &&
|
||||||
|
store.boundId != null &&
|
||||||
|
store.regionName != null &&
|
||||||
|
store.coords != null
|
||||||
|
) {
|
||||||
|
cached = {
|
||||||
|
regionId: store.regionId,
|
||||||
|
boundId: store.boundId,
|
||||||
|
regionName: store.regionName,
|
||||||
|
coords: store.coords,
|
||||||
|
}
|
||||||
|
} else if (snapshot != null) {
|
||||||
|
cached = {
|
||||||
|
regionId: snapshot.regionId,
|
||||||
|
boundId: snapshot.boundId,
|
||||||
|
regionName: snapshot.regionName,
|
||||||
|
coords: snapshot.coords,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const regions = regionsQuery.data ?? store.regions
|
||||||
|
useNeoRegionStore.getState().setRegions(regions)
|
||||||
|
|
||||||
|
if (cached != null && !regions.some((region) => region.id === cached?.regionId)) {
|
||||||
|
useNeoRegionStore.getState().clearRegion()
|
||||||
|
cached = null
|
||||||
|
}
|
||||||
|
|
||||||
|
let addresses: NeoAddress[] = []
|
||||||
|
if (isAuthenticated) {
|
||||||
|
addresses =
|
||||||
|
addressesQuery.data != null
|
||||||
|
? addressesQuery.data.data.map(toNeoAddress)
|
||||||
|
: useNeoRegionStore.getState().addresses
|
||||||
|
}
|
||||||
|
useNeoRegionStore.getState().setAddresses(addresses)
|
||||||
|
// Read after setAddresses: it clears the selection if the cached address
|
||||||
|
// is no longer in the live list.
|
||||||
|
const selectedAddressId = useNeoRegionStore.getState().selectedAddressId
|
||||||
|
|
||||||
|
let resolved: NeoResolvedRegion | null = null
|
||||||
|
if (resolveResult != null) {
|
||||||
|
const region = regions.find((candidate) => candidate.id === resolveResult.region.id)
|
||||||
|
const boundId = resolveResult.bound?.id ?? region?.effectiveBoundId ?? null
|
||||||
|
if (boundId != null) {
|
||||||
|
resolved = { regionId: resolveResult.region.id, boundId }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const decision = decideNeoRegion({
|
||||||
|
cached,
|
||||||
|
fix,
|
||||||
|
resolved,
|
||||||
|
isAuthenticated,
|
||||||
|
addresses,
|
||||||
|
selectedAddressId,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (decision.action === 'needs-address-flow') {
|
||||||
|
useNeoRegionStore.getState().openAddressFlow()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const region = regions.find((candidate) => candidate.id === decision.regionId)
|
||||||
|
const boundId = decision.boundId ?? region?.effectiveBoundId ?? null
|
||||||
|
const decisionCoords = decision.action === 'ready' ? decision.coords : null
|
||||||
|
const targetCoords = decisionCoords ?? regionCoords(region) ?? cached?.coords ?? fix
|
||||||
|
|
||||||
|
if (region == null || boundId == null || targetCoords == null) {
|
||||||
|
useNeoRegionStore.getState().openAddressFlow()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// A decision that moves away from the published region is a real switch:
|
||||||
|
// stash/clear the carts and invalidate the region-scoped caches, exactly
|
||||||
|
// like an explicit changeRegion.
|
||||||
|
const previousRegionId = useNeoRegionStore.getState().regionId
|
||||||
|
if (previousRegionId != null && previousRegionId !== decision.regionId) {
|
||||||
|
await applyRegionSwitch(previousRegionId, decision.regionId, queryClient)
|
||||||
|
}
|
||||||
|
|
||||||
|
useNeoRegionStore.getState().applyRegion({
|
||||||
|
regionId: decision.regionId,
|
||||||
|
boundId,
|
||||||
|
regionName: region.name,
|
||||||
|
coords: targetCoords,
|
||||||
|
origin: decision.action === 'needs-confirmation' ? 'device' : decision.origin,
|
||||||
|
selectedAddressId:
|
||||||
|
decision.action === 'needs-confirmation' ? null : decision.selectedAddressId,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (decision.action === 'needs-confirmation') {
|
||||||
|
useNeoRegionStore.getState().setNeedsConfirmation(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void run().catch(() => {
|
||||||
|
// A failed decision must not strand the loading screen forever.
|
||||||
|
useNeoRegionStore.getState().openAddressFlow()
|
||||||
|
})
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [
|
||||||
|
hasAuthContext,
|
||||||
|
isAuthLoading,
|
||||||
|
isAuthenticated,
|
||||||
|
coords,
|
||||||
|
locationStatus,
|
||||||
|
timedOut,
|
||||||
|
decisionTick,
|
||||||
|
userId,
|
||||||
|
regionsQuery.data,
|
||||||
|
regionsQuery.isFetched,
|
||||||
|
regionsQuery.isError,
|
||||||
|
addressesQuery.data,
|
||||||
|
addressesQuery.isFetched,
|
||||||
|
addressesQuery.isError,
|
||||||
|
])
|
||||||
|
|
||||||
|
// If the user leaves for the OS settings and turns location on, recover
|
||||||
|
// without a restart while the address flow is up. Only poll when the location
|
||||||
|
// is actually unusable: when the flow is up because the user has no address,
|
||||||
|
// the fix already exists and re-deciding would just flicker the screen.
|
||||||
|
const locationIsUnusable =
|
||||||
|
locationStatus === 'denied' ||
|
||||||
|
locationStatus === 'services-off' ||
|
||||||
|
locationStatus === 'unavailable' ||
|
||||||
|
locationStatus === 'error'
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!state.needsAddressFormFlow || !locationIsUnusable) return
|
||||||
|
|
||||||
|
let cancelled = false
|
||||||
|
let busy = false
|
||||||
|
|
||||||
|
const check = async () => {
|
||||||
|
if (busy) return
|
||||||
|
busy = true
|
||||||
|
try {
|
||||||
|
const usable = await probeLocation()
|
||||||
|
if (cancelled || !usable) return
|
||||||
|
await refreshLocation()
|
||||||
|
if (cancelled) return
|
||||||
|
decisionStarted = false
|
||||||
|
useNeoRegionStore.getState().closeAddressFlow()
|
||||||
|
setDecisionTick((tick) => tick + 1)
|
||||||
|
} finally {
|
||||||
|
busy = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void check()
|
||||||
|
const timer = setInterval(() => void check(), LOCATION_POLL_MS)
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
clearInterval(timer)
|
||||||
|
}
|
||||||
|
}, [state.needsAddressFormFlow, locationIsUnusable, probeLocation, refreshLocation])
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The region/address data, never null.
|
||||||
|
*
|
||||||
|
* Only call this from components that LocationWrapperNeo renders — the wrapper
|
||||||
|
* guarantees the store holds a complete region before children appear. Calling
|
||||||
|
* it earlier is a bug, so it throws rather than handing out a half-answer.
|
||||||
|
*/
|
||||||
|
export function useRegionNeo(): NeoRegionData {
|
||||||
|
const state = useNeoRegionStore()
|
||||||
|
const isAuthenticated = useAuthOptional()?.isAuthenticated ?? false
|
||||||
|
const addressesQuery = trpc.user.address.getUserAddresses.useQuery(undefined, {
|
||||||
|
enabled: isAuthenticated,
|
||||||
|
})
|
||||||
|
|
||||||
|
const { regionId, boundId, regionName, coords, origin, selectedAddressId } = state
|
||||||
|
|
||||||
|
if (regionId == null || boundId == null || regionName == null || coords == null) {
|
||||||
|
throw new Error(
|
||||||
|
'useRegionNeo() called before LocationWrapperNeo published a region. ' +
|
||||||
|
'It may only be used by components rendered inside the wrapper.'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Live query data wins; the store is the fallback while the query loads (it
|
||||||
|
// also carries the provisional cached address from the snapshot).
|
||||||
|
const liveAddresses = addressesQuery.data?.data.map(toNeoAddress) ?? null
|
||||||
|
const addresses = liveAddresses ?? state.addresses
|
||||||
|
|
||||||
|
const selected =
|
||||||
|
selectedAddressId != null
|
||||||
|
? addresses.find((address) => address.id === selectedAddressId) ?? null
|
||||||
|
: null
|
||||||
|
|
||||||
|
return {
|
||||||
|
regionId,
|
||||||
|
boundId,
|
||||||
|
regionName,
|
||||||
|
coords,
|
||||||
|
selectedAddressId: selected?.id ?? null,
|
||||||
|
selectedAddress: selected,
|
||||||
|
fullAddress: selected != null ? formatNeoAddress(selected) : null,
|
||||||
|
isCache: origin === 'cache',
|
||||||
|
changeRegion: state.changeRegion,
|
||||||
|
// Async only because a cross-region selection awaits the cart switch.
|
||||||
|
// Never performs an address API call; the caller refreshes after mutations.
|
||||||
|
selectAddress: state.selectAddress,
|
||||||
|
}
|
||||||
|
}
|
||||||
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()
|
||||||
|
}
|
||||||
237
apps/user-ui/src/store/neoRegionStore.ts
Normal file
237
apps/user-ui/src/store/neoRegionStore.ts
Normal file
|
|
@ -0,0 +1,237 @@
|
||||||
|
import { create } from 'zustand'
|
||||||
|
import type { QueryClient } from '@tanstack/react-query'
|
||||||
|
import type { RegionSummary } from '@packages/shared'
|
||||||
|
import { applyRegionSwitch } from '@/src/lib/neo-region-switch'
|
||||||
|
import { writeNeoRegionSnapshot } from '@/src/lib/neo-region-cache'
|
||||||
|
import { addressCoords, type NeoAddress, type NeoCoords } from '@/src/lib/neo-address'
|
||||||
|
import type { NeoOrigin } from '@/src/lib/neo-region-decision'
|
||||||
|
|
||||||
|
export interface NeoRegionData {
|
||||||
|
regionId: number
|
||||||
|
boundId: number
|
||||||
|
regionName: string
|
||||||
|
coords: NeoCoords
|
||||||
|
selectedAddressId: number | null
|
||||||
|
/** The full selected address object (null when the region has no address). */
|
||||||
|
selectedAddress: NeoAddress | null
|
||||||
|
/** The selected address formatted as one line. */
|
||||||
|
fullAddress: string | null
|
||||||
|
isCache: boolean
|
||||||
|
changeRegion: (regionId: number, boundId?: number | null) => Promise<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
|
||||||
|
|
||||||
|
applyRegion: (data: ApplyRegionInput) => void
|
||||||
|
setRegions: (regions: RegionSummary[]) => void
|
||||||
|
setAddresses: (addresses: NeoAddress[]) => void
|
||||||
|
clearRegion: () => void
|
||||||
|
openAddressFlow: () => void
|
||||||
|
closeAddressFlow: () => void
|
||||||
|
setNeedsConfirmation: (value: boolean) => void
|
||||||
|
resetForLogout: () => void
|
||||||
|
|
||||||
|
changeRegion: (regionId: number, boundId?: number | null) => Promise<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,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The only writer of the region fields. The selection is validated against
|
||||||
|
* the region here, so `selectedAddressId != null` always means "the active
|
||||||
|
* address belongs to the active region".
|
||||||
|
*/
|
||||||
|
applyRegion: (data) => {
|
||||||
|
const state = get()
|
||||||
|
const selection =
|
||||||
|
data.selectedAddressId != null
|
||||||
|
? state.addresses.find((address) => address.id === data.selectedAddressId) ?? null
|
||||||
|
: null
|
||||||
|
const validSelection =
|
||||||
|
selection != null && selection.regionId === data.regionId ? selection : null
|
||||||
|
const regionName =
|
||||||
|
state.regions.find((region) => region.id === data.regionId)?.name ?? data.regionName
|
||||||
|
const coords = (validSelection ? addressCoords(validSelection) : null) ?? data.coords
|
||||||
|
const boundId = validSelection?.boundId ?? data.boundId
|
||||||
|
|
||||||
|
set({
|
||||||
|
regionId: data.regionId,
|
||||||
|
boundId,
|
||||||
|
regionName,
|
||||||
|
coords,
|
||||||
|
origin: validSelection != null ? 'address' : data.origin,
|
||||||
|
selectedAddressId: validSelection?.id ?? null,
|
||||||
|
needsAddressFormFlow: false,
|
||||||
|
needsAddressConfirmation: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
void writeNeoRegionSnapshot({
|
||||||
|
regionId: data.regionId,
|
||||||
|
boundId,
|
||||||
|
regionName,
|
||||||
|
coords,
|
||||||
|
selectedAddress: validSelection,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
setRegions: (regions) => {
|
||||||
|
const state = get()
|
||||||
|
const current = state.regionId != null
|
||||||
|
? regions.find((region) => region.id === state.regionId) ?? null
|
||||||
|
: null
|
||||||
|
set({
|
||||||
|
regions,
|
||||||
|
regionName: current?.name ?? state.regionName,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
setAddresses: (addresses) => {
|
||||||
|
const usable = addresses.filter((address) => address.regionId != null)
|
||||||
|
const state = get()
|
||||||
|
if (state.selectedAddressId == null) {
|
||||||
|
set({ addresses: usable })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const selected = usable.find((address) => address.id === state.selectedAddressId) ?? null
|
||||||
|
const stillValid =
|
||||||
|
selected != null &&
|
||||||
|
selected.regionId === state.regionId &&
|
||||||
|
(selected.boundId == null || state.boundId == null || selected.boundId === state.boundId)
|
||||||
|
set({
|
||||||
|
addresses: usable,
|
||||||
|
selectedAddressId: stillValid ? state.selectedAddressId : null,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
clearRegion: () => {
|
||||||
|
set({
|
||||||
|
regionId: null,
|
||||||
|
boundId: null,
|
||||||
|
regionName: null,
|
||||||
|
coords: null,
|
||||||
|
origin: null,
|
||||||
|
selectedAddressId: null,
|
||||||
|
needsAddressFormFlow: false,
|
||||||
|
needsAddressConfirmation: false,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
openAddressFlow: () => set({ needsAddressFormFlow: true, needsAddressConfirmation: false }),
|
||||||
|
|
||||||
|
closeAddressFlow: () => set({ needsAddressFormFlow: false }),
|
||||||
|
|
||||||
|
setNeedsConfirmation: (value) =>
|
||||||
|
set({
|
||||||
|
needsAddressConfirmation: value,
|
||||||
|
...(value ? { needsAddressFormFlow: false } : null),
|
||||||
|
}),
|
||||||
|
|
||||||
|
resetForLogout: () =>
|
||||||
|
set({
|
||||||
|
addresses: [],
|
||||||
|
selectedAddressId: null,
|
||||||
|
needsAddressFormFlow: false,
|
||||||
|
needsAddressConfirmation: false,
|
||||||
|
}),
|
||||||
|
|
||||||
|
changeRegion: async (regionId, boundId) => {
|
||||||
|
const state = get()
|
||||||
|
const region = state.regions.find((candidate) => candidate.id === regionId)
|
||||||
|
if (region == null) return
|
||||||
|
|
||||||
|
const nextBoundId = boundId ?? region.effectiveBoundId ?? null
|
||||||
|
if (nextBoundId == null) return
|
||||||
|
|
||||||
|
if (state.regionId !== regionId && boundQueryClient != null) {
|
||||||
|
await applyRegionSwitch(state.regionId, regionId, boundQueryClient)
|
||||||
|
}
|
||||||
|
|
||||||
|
const coords = regionCoords(region) ?? state.coords
|
||||||
|
if (coords == null) return
|
||||||
|
|
||||||
|
get().applyRegion({
|
||||||
|
regionId,
|
||||||
|
boundId: nextBoundId,
|
||||||
|
regionName: region.name,
|
||||||
|
coords,
|
||||||
|
origin: 'manual',
|
||||||
|
selectedAddressId: null,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
selectAddress: async (id) => {
|
||||||
|
const state = get()
|
||||||
|
const address = state.addresses.find((candidate) => candidate.id === id)
|
||||||
|
if (address == null || address.regionId == null) return
|
||||||
|
|
||||||
|
const region = state.regions.find((candidate) => candidate.id === address.regionId)
|
||||||
|
if (region == null) return
|
||||||
|
|
||||||
|
const boundId = address.boundId ?? region.effectiveBoundId ?? null
|
||||||
|
if (boundId == null) return
|
||||||
|
|
||||||
|
if (state.regionId !== address.regionId && boundQueryClient != null) {
|
||||||
|
await applyRegionSwitch(state.regionId, address.regionId, boundQueryClient)
|
||||||
|
}
|
||||||
|
|
||||||
|
const coords = addressCoords(address) ?? regionCoords(region) ?? state.coords
|
||||||
|
if (coords == null) return
|
||||||
|
|
||||||
|
get().applyRegion({
|
||||||
|
regionId: address.regionId,
|
||||||
|
boundId,
|
||||||
|
regionName: region.name,
|
||||||
|
coords,
|
||||||
|
origin: 'address',
|
||||||
|
selectedAddressId: address.id,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
@ -14,6 +14,7 @@
|
||||||
import * as React from 'react'
|
import * as React from 'react'
|
||||||
import { fireEvent, waitFor, within, act } from '@testing-library/react-native'
|
import { fireEvent, waitFor, within, act } from '@testing-library/react-native'
|
||||||
import AddressForm from '@/src/components/AddressForm'
|
import AddressForm from '@/src/components/AddressForm'
|
||||||
|
import { useLocationStore } from '@/src/store/locationStore'
|
||||||
import LocationMapStep from '@/src/components/location/LocationMapStep'
|
import LocationMapStep from '@/src/components/location/LocationMapStep'
|
||||||
import constants from '@/src/constants'
|
import constants from '@/src/constants'
|
||||||
import { renderWithProviders, seedRegion, flush } from '../helpers/test-utils'
|
import { renderWithProviders, seedRegion, flush } from '../helpers/test-utils'
|
||||||
|
|
@ -62,6 +63,7 @@ function grantLocation(latitude = 12.34, longitude = 56.78) {
|
||||||
servicesEnabled: true,
|
servicesEnabled: true,
|
||||||
position: { coords: { latitude, longitude, accuracy: 5 }, timestamp: 1 },
|
position: { coords: { latitude, longitude, accuracy: 5 }, timestamp: 1 },
|
||||||
})
|
})
|
||||||
|
useLocationStore.getState().start()
|
||||||
return { latitude, longitude }
|
return { latitude, longitude }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ import CheckoutAddressSelector from '@/components/CheckoutAddressSelector'
|
||||||
import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay'
|
import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay'
|
||||||
import AddressForm from '@/src/components/AddressForm'
|
import AddressForm from '@/src/components/AddressForm'
|
||||||
import { useRegionStore } from '@/src/store/regionStore'
|
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 { renderWithProviders, flush } from '../helpers/test-utils'
|
||||||
import { resetAllMocks } from '../helpers/reset'
|
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'
|
import { A1, A2, A3, REGION_1, REGION_2 } from '../fixtures'
|
||||||
|
|
||||||
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
|
jest.mock('@/src/contexts/AuthContext', () => require('../mocks/auth-context'))
|
||||||
jest.mock('@/src/hooks/useRegion', () => ({
|
jest.mock('@/src/hooks/useRegionNeo', () => ({
|
||||||
useRegion: () => (globalThis as any).__regionHook,
|
useRegionNeo: () => (globalThis as any).__neoHook,
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const ser = (address: any) => ({
|
const ser = (address: any) => ({
|
||||||
|
|
@ -47,24 +47,35 @@ const S3 = ser(A3) // NoRegion
|
||||||
|
|
||||||
function setRegionHook(overrides: Record<string, any> = {}) {
|
function setRegionHook(overrides: Record<string, any> = {}) {
|
||||||
const state: any = {
|
const state: any = {
|
||||||
region: null,
|
regionId: 1,
|
||||||
regionId: null,
|
boundId: 7,
|
||||||
boundId: null,
|
regionName: 'Mahabubnagar',
|
||||||
bound: null,
|
coords: { latitude: 16.7488, longitude: 77.9851 },
|
||||||
regionGeneration: 0,
|
selectedAddressId: null,
|
||||||
hydrated: true,
|
selectedAddress: null,
|
||||||
coords: null,
|
fullAddress: null,
|
||||||
locationStatus: 'idle',
|
isCache: false,
|
||||||
isResolvingRegion: false,
|
changeRegion: jest.fn(),
|
||||||
setRegion: jest.fn(),
|
selectAddress: jest.fn(),
|
||||||
clearRegion: jest.fn(),
|
|
||||||
refreshLocation: jest.fn(),
|
|
||||||
...overrides,
|
...overrides,
|
||||||
}
|
}
|
||||||
;(globalThis as any).__regionHook = state
|
;(globalThis as any).__neoHook = state
|
||||||
return 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() {
|
function signIn() {
|
||||||
__setAuthState({ isAuthenticated: true, isLoading: false })
|
__setAuthState({ isAuthenticated: true, isLoading: false })
|
||||||
}
|
}
|
||||||
|
|
@ -84,10 +95,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
|
||||||
it('CAS-01: the selected address is sorted first', async () => {
|
it('CAS-01: the selected address is sorted first', async () => {
|
||||||
signIn()
|
signIn()
|
||||||
setAddresses([S1, S2, S3])
|
setAddresses([S1, S2, S3])
|
||||||
const { getByTestId } = renderWithProviders(
|
const { getByTestId } = selector(12, jest.fn())
|
||||||
<CheckoutAddressSelector selectedAddress={12} onAddressSelect={jest.fn()} />,
|
|
||||||
{ auth: false }
|
|
||||||
)
|
|
||||||
await flush(2)
|
await flush(2)
|
||||||
expect(within(getByTestId('address-option-0')).getByText('Work')).toBeTruthy()
|
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 () => {
|
it('CAS-02: the default address is sorted after the selected one', async () => {
|
||||||
signIn()
|
signIn()
|
||||||
setAddresses([S1, S2, S3])
|
setAddresses([S1, S2, S3])
|
||||||
const { getByTestId } = renderWithProviders(
|
const { getByTestId } = selector(13, jest.fn())
|
||||||
<CheckoutAddressSelector selectedAddress={13} onAddressSelect={jest.fn()} />,
|
|
||||||
{ auth: false }
|
|
||||||
)
|
|
||||||
await flush(2)
|
await flush(2)
|
||||||
const optionOne = getByTestId('address-option-1')
|
const optionOne = getByTestId('address-option-1')
|
||||||
expect(within(optionOne).getByText('Home')).toBeTruthy()
|
expect(within(optionOne).getByText('Home')).toBeTruthy()
|
||||||
|
|
@ -111,60 +116,29 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
|
||||||
{ ...S1, isDefault: false },
|
{ ...S1, isDefault: false },
|
||||||
{ ...S2, isDefault: false },
|
{ ...S2, isDefault: false },
|
||||||
])
|
])
|
||||||
const { getByTestId } = renderWithProviders(
|
const { getByTestId } = selector(null, jest.fn())
|
||||||
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={jest.fn()} />,
|
|
||||||
{ auth: false }
|
|
||||||
)
|
|
||||||
await flush(2)
|
await flush(2)
|
||||||
expect(within(getByTestId('address-option-0')).getByText('Home')).toBeTruthy()
|
expect(within(getByTestId('address-option-0')).getByText('Home')).toBeTruthy()
|
||||||
expect(within(getByTestId('address-option-1')).getByText('Work')).toBeTruthy()
|
expect(within(getByTestId('address-option-1')).getByText('Work')).toBeTruthy()
|
||||||
expect(within(getByTestId('address-option-2')).getByText('NoRegion')).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 () => {
|
it('CAS-05: a default in another region is never auto-selected', async () => {
|
||||||
signIn()
|
signIn()
|
||||||
setAddresses([S2, S3])
|
setAddresses([S2, S3])
|
||||||
const onAddressSelect = jest.fn()
|
const onAddressSelect = jest.fn()
|
||||||
renderWithProviders(
|
selector(null, onAddressSelect)
|
||||||
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={onAddressSelect} />,
|
|
||||||
{ auth: false }
|
|
||||||
)
|
|
||||||
await flush(2)
|
await flush(2)
|
||||||
expect(onAddressSelect).not.toHaveBeenCalled()
|
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 () => {
|
it('CAS-07: tapping an address in another region opens the confirm dialog', async () => {
|
||||||
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||||
signIn()
|
signIn()
|
||||||
setAddresses([S1, S2])
|
setAddresses([S1, S2])
|
||||||
const { getByTestId } = renderWithProviders(
|
const { getByTestId } = selector(11, jest.fn())
|
||||||
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
|
|
||||||
{ auth: false }
|
|
||||||
)
|
|
||||||
await flush(2)
|
await flush(2)
|
||||||
fireEvent.press(getByTestId('address-option-1'))
|
fireEvent.press(getByTestId('address-option-1'))
|
||||||
expect(alertSpy).toHaveBeenCalled()
|
expect(alertSpy).toHaveBeenCalled()
|
||||||
|
|
@ -178,10 +152,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
|
||||||
useRegionStore.getState().setRegion(REGION_1, 7)
|
useRegionStore.getState().setRegion(REGION_1, 7)
|
||||||
setAddresses([S1, S2])
|
setAddresses([S1, S2])
|
||||||
const onAddressSelect = jest.fn()
|
const onAddressSelect = jest.fn()
|
||||||
const { getByTestId } = renderWithProviders(
|
const { getByTestId } = selector(11, onAddressSelect)
|
||||||
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={onAddressSelect} />,
|
|
||||||
{ auth: false }
|
|
||||||
)
|
|
||||||
await flush(2)
|
await flush(2)
|
||||||
fireEvent.press(getByTestId('address-option-1'))
|
fireEvent.press(getByTestId('address-option-1'))
|
||||||
const buttons = alertSpy.mock.calls[0][2] as any[]
|
const buttons = alertSpy.mock.calls[0][2] as any[]
|
||||||
|
|
@ -198,10 +169,8 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
|
||||||
signIn()
|
signIn()
|
||||||
useRegionStore.getState().setRegion(REGION_1, 7)
|
useRegionStore.getState().setRegion(REGION_1, 7)
|
||||||
setAddresses([S1, S2])
|
setAddresses([S1, S2])
|
||||||
const { getByTestId } = renderWithProviders(
|
const selectAddress = jest.fn()
|
||||||
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
|
const { getByTestId } = selector(11, selectAddress)
|
||||||
{ auth: false }
|
|
||||||
)
|
|
||||||
await flush(2)
|
await flush(2)
|
||||||
fireEvent.press(getByTestId('address-option-1'))
|
fireEvent.press(getByTestId('address-option-1'))
|
||||||
const buttons = alertSpy.mock.calls[0][2] as any[]
|
const buttons = alertSpy.mock.calls[0][2] as any[]
|
||||||
|
|
@ -209,9 +178,9 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
|
||||||
await act(async () => {
|
await act(async () => {
|
||||||
await confirm.onPress()
|
await confirm.onPress()
|
||||||
})
|
})
|
||||||
// `confirmRegionSwitch` awaits the cart clear before navigating.
|
// `selectAddress` performs the switch in the neo store before navigating.
|
||||||
await flush()
|
await flush()
|
||||||
expect(useRegionStore.getState().selectedRegionId).toBe(2)
|
expect(selectAddress).toHaveBeenCalledWith(12)
|
||||||
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
|
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
|
||||||
alertSpy.mockRestore()
|
alertSpy.mockRestore()
|
||||||
})
|
})
|
||||||
|
|
@ -220,10 +189,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
|
||||||
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||||
signIn()
|
signIn()
|
||||||
setAddresses([S1, { ...S2, id: 31, regionId: 99 }])
|
setAddresses([S1, { ...S2, id: 31, regionId: 99 }])
|
||||||
const { getByTestId } = renderWithProviders(
|
const { getByTestId } = selector(11, jest.fn())
|
||||||
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
|
|
||||||
{ auth: false }
|
|
||||||
)
|
|
||||||
await flush(2)
|
await flush(2)
|
||||||
fireEvent.press(getByTestId('address-option-1'))
|
fireEvent.press(getByTestId('address-option-1'))
|
||||||
expect(alertSpy).toHaveBeenCalledWith(
|
expect(alertSpy).toHaveBeenCalledWith(
|
||||||
|
|
@ -237,10 +203,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
|
||||||
signIn()
|
signIn()
|
||||||
setAddresses([S1, S2])
|
setAddresses([S1, S2])
|
||||||
const onAddressSelect = jest.fn()
|
const onAddressSelect = jest.fn()
|
||||||
const { getByTestId } = renderWithProviders(
|
const { getByTestId } = selector(null, onAddressSelect)
|
||||||
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={onAddressSelect} />,
|
|
||||||
{ auth: false }
|
|
||||||
)
|
|
||||||
await flush(2)
|
await flush(2)
|
||||||
|
|
||||||
fireEvent.scroll(getByTestId('address-scroll'), {
|
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 () => {
|
it('CAS-12: one pagination dot per address reflects the scroll index', async () => {
|
||||||
signIn()
|
signIn()
|
||||||
setAddresses([S1, S2, S3])
|
setAddresses([S1, S2, S3])
|
||||||
const { getAllByTestId, getByTestId } = renderWithProviders(
|
const { getAllByTestId, getByTestId } = selector(null, jest.fn())
|
||||||
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={jest.fn()} />,
|
|
||||||
{ auth: false }
|
|
||||||
)
|
|
||||||
await flush(2)
|
await flush(2)
|
||||||
expect(getAllByTestId(/address-dot-/)).toHaveLength(3)
|
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 () => {
|
it('CAS-13: with no addresses the empty card offers adding one', async () => {
|
||||||
signIn()
|
signIn()
|
||||||
setAddresses([])
|
setAddresses([])
|
||||||
const { getByText, getByTestId } = renderWithProviders(
|
const { getByText, getByTestId } = selector(null, jest.fn())
|
||||||
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={jest.fn()} />,
|
|
||||||
{ auth: false }
|
|
||||||
)
|
|
||||||
await flush(2)
|
await flush(2)
|
||||||
expect(getByText('No addresses found')).toBeTruthy()
|
expect(getByText('No addresses found')).toBeTruthy()
|
||||||
expect(getByTestId('add-address-empty')).toBeTruthy()
|
expect(getByTestId('add-address-empty')).toBeTruthy()
|
||||||
|
|
@ -296,10 +253,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
|
||||||
signIn()
|
signIn()
|
||||||
setAddresses([{ ...S1, latitude: null, longitude: null }])
|
setAddresses([{ ...S1, latitude: null, longitude: null }])
|
||||||
configureLocation({ permission: 'granted' })
|
configureLocation({ permission: 'granted' })
|
||||||
const { getByTestId } = renderWithProviders(
|
const { getByTestId } = selector(11, jest.fn())
|
||||||
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
|
|
||||||
{ auth: false }
|
|
||||||
)
|
|
||||||
await flush(2)
|
await flush(2)
|
||||||
expect(getByTestId('attach-location')).toBeTruthy()
|
expect(getByTestId('attach-location')).toBeTruthy()
|
||||||
fireEvent.press(getByTestId('attach-location'))
|
fireEvent.press(getByTestId('attach-location'))
|
||||||
|
|
@ -316,10 +270,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
|
||||||
signIn()
|
signIn()
|
||||||
setAddresses([{ ...S1, latitude: null, longitude: null }])
|
setAddresses([{ ...S1, latitude: null, longitude: null }])
|
||||||
configureLocation({ permission: 'denied' })
|
configureLocation({ permission: 'denied' })
|
||||||
const { getByTestId } = renderWithProviders(
|
const { getByTestId } = selector(11, jest.fn())
|
||||||
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
|
|
||||||
{ auth: false }
|
|
||||||
)
|
|
||||||
await flush(2)
|
await flush(2)
|
||||||
fireEvent.press(getByTestId('attach-location'))
|
fireEvent.press(getByTestId('attach-location'))
|
||||||
await flush(2)
|
await flush(2)
|
||||||
|
|
@ -336,10 +287,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
|
||||||
signIn()
|
signIn()
|
||||||
setAddresses([{ ...S1, latitude: null, longitude: null }])
|
setAddresses([{ ...S1, latitude: null, longitude: null }])
|
||||||
configureLocation({ permission: 'granted', throwOnPosition: true })
|
configureLocation({ permission: 'granted', throwOnPosition: true })
|
||||||
const { getByTestId, getByText } = renderWithProviders(
|
const { getByTestId, getByText } = selector(11, jest.fn())
|
||||||
<CheckoutAddressSelector selectedAddress={11} onAddressSelect={jest.fn()} />,
|
|
||||||
{ auth: false }
|
|
||||||
)
|
|
||||||
await flush(2)
|
await flush(2)
|
||||||
fireEvent.press(getByTestId('attach-location'))
|
fireEvent.press(getByTestId('attach-location'))
|
||||||
await flush(2)
|
await flush(2)
|
||||||
|
|
@ -355,10 +303,7 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
|
||||||
signIn()
|
signIn()
|
||||||
setAddresses([S1])
|
setAddresses([S1])
|
||||||
const onAddressSelect = jest.fn()
|
const onAddressSelect = jest.fn()
|
||||||
const { getByTestId, UNSAFE_getByType, queryClient } = renderWithProviders(
|
const { getByTestId, UNSAFE_getByType, queryClient } = selector(null, onAddressSelect)
|
||||||
<CheckoutAddressSelector selectedAddress={null} onAddressSelect={onAddressSelect} />,
|
|
||||||
{ auth: false }
|
|
||||||
)
|
|
||||||
await flush(2)
|
await flush(2)
|
||||||
const invalidateSpy = jest.spyOn(queryClient, 'invalidateQueries')
|
const invalidateSpy = jest.spyOn(queryClient, 'invalidateQueries')
|
||||||
fireEvent.press(getByTestId('add-new-address'))
|
fireEvent.press(getByTestId('add-new-address'))
|
||||||
|
|
@ -374,46 +319,36 @@ describe('CheckoutAddressSelector / Display (CAS)', () => {
|
||||||
it('CAS-18: the display shows the selected address', async () => {
|
it('CAS-18: the display shows the selected address', async () => {
|
||||||
signIn()
|
signIn()
|
||||||
setAddresses([S1, S2, S3])
|
setAddresses([S1, S2, S3])
|
||||||
useAddressStore.getState().setSelectedAddressId(12)
|
seedNeo([S1, S2, S3], 12)
|
||||||
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
|
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
|
||||||
await flush(2)
|
await flush(2)
|
||||||
expect(getByText('Work')).toBeTruthy()
|
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()
|
signIn()
|
||||||
setAddresses([S1, S2, S3])
|
setAddresses([S1, S2, S3])
|
||||||
useAddressStore.getState().setSelectedAddressId(null)
|
seedNeo([S1, S2, S3], null)
|
||||||
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
|
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
|
||||||
await flush(2)
|
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 () => {
|
it('CAS-20: the display shows an empty state with no address', async () => {
|
||||||
signIn()
|
signIn()
|
||||||
setAddresses([])
|
setAddresses([])
|
||||||
|
seedNeo([], null)
|
||||||
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
|
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
|
||||||
await flush(2)
|
await flush(2)
|
||||||
expect(getByText('No address selected')).toBeTruthy()
|
expect(getByText('No address selected')).toBeTruthy()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('CAS-21: the display shows a loading state while addresses load', () => {
|
it('CAS-22: the display does not query addresses when signed out', async () => {
|
||||||
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 () => {
|
|
||||||
__setAuthState({ isAuthenticated: false, isLoading: false })
|
__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()
|
await flush()
|
||||||
resetAllMocks()
|
resetAllMocks()
|
||||||
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
|
const { getByText } = renderWithProviders(<CheckoutAddressDisplay />, { auth: false })
|
||||||
await flush(2)
|
await flush(2)
|
||||||
expect(getByText('No address selected')).toBeTruthy()
|
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 AddressForm from '@/src/components/AddressForm'
|
||||||
import constants from '@/src/constants'
|
import constants from '@/src/constants'
|
||||||
import { useRegionStore } from '@/src/store/regionStore'
|
import { useRegionStore } from '@/src/store/regionStore'
|
||||||
|
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
|
||||||
import { useAddressStore } from '@/src/store/addressStore'
|
import { useAddressStore } from '@/src/store/addressStore'
|
||||||
import { useLocationStore } from '@/src/store/locationStore'
|
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 { resetAllMocks } from '../helpers/reset'
|
||||||
import {
|
import {
|
||||||
setProcedure,
|
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 () => {
|
it('LOC-20: the active address prefers the selection over the default (and is off at startup)', async () => {
|
||||||
signIn()
|
signIn()
|
||||||
setAddresses([S1, S2])
|
setAddresses([S1, S2])
|
||||||
useAddressStore.getState().setSelectedAddressId(12)
|
seedSelectedAddress(12)
|
||||||
const first = renderWithProviders(<LocationFallbackFlow />, { auth: false })
|
const first = renderWithProviders(<LocationFallbackFlow />, { auth: false })
|
||||||
await flush(2)
|
await flush(2)
|
||||||
expect(within(first.getByTestId('location-address-12')).getByTestId('location-address-active')).toBeTruthy()
|
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 })
|
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
|
||||||
signIn()
|
signIn()
|
||||||
setAddresses([S1, S2])
|
setAddresses([S1, S2])
|
||||||
useAddressStore.getState().setSelectedAddressId(11)
|
seedSelectedAddress(11)
|
||||||
const { getByTestId, getByText } = renderWithProviders(<LocationBar />, { auth: false })
|
const { getByTestId, getByText } = renderWithProviders(<LocationBar />, { auth: false })
|
||||||
await flush(2)
|
await flush(2)
|
||||||
expect(getByText('Mahabubnagar')).toBeTruthy()
|
expect(getByText('Mahabubnagar')).toBeTruthy()
|
||||||
|
|
@ -587,16 +588,12 @@ describe('Location components (LOC)', () => {
|
||||||
expect(getByText('Delivery Address')).toBeTruthy()
|
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 () => {
|
it('LOC-32: LocationBar prefers the selected address over the default', async () => {
|
||||||
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
|
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
|
||||||
signIn()
|
signIn()
|
||||||
setAddresses([S1, S2])
|
setAddresses([S1, S2])
|
||||||
useAddressStore.getState().setSelectedAddressId(12)
|
seedSelectedAddress(12)
|
||||||
const { getByText } = renderWithProviders(<LocationBar />, { auth: false })
|
const { getByText } = renderWithProviders(<LocationBar />, { auth: false })
|
||||||
await flush(2)
|
await flush(2)
|
||||||
expect(getByText('45 Office Street, Hyderabad')).toBeTruthy()
|
expect(getByText('45 Office Street, Hyderabad')).toBeTruthy()
|
||||||
|
|
@ -616,7 +613,7 @@ describe('Location components (LOC)', () => {
|
||||||
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
|
setRegionHook({ region: REGION_1, regionId: 1, boundId: 7 })
|
||||||
signIn()
|
signIn()
|
||||||
setAddresses([S1, S2])
|
setAddresses([S1, S2])
|
||||||
useAddressStore.getState().setSelectedAddressId(11)
|
seedSelectedAddress(11)
|
||||||
const { getByText } = renderWithProviders(<LocationBar />, { auth: false })
|
const { getByText } = renderWithProviders(<LocationBar />, { auth: false })
|
||||||
await flush(2)
|
await flush(2)
|
||||||
|
|
||||||
|
|
@ -780,6 +777,7 @@ describe('Location components (LOC)', () => {
|
||||||
|
|
||||||
it('LOC-46: CartAddressGate enables the current-location option and shows the coordinates', () => {
|
it('LOC-46: CartAddressGate enables the current-location option and shows the coordinates', () => {
|
||||||
useLocationStore.setState({ coords: { latitude: 17.1, longitude: 78.2 }, status: 'granted' })
|
useLocationStore.setState({ coords: { latitude: 17.1, longitude: 78.2 }, status: 'granted' })
|
||||||
|
useNeoRegionStore.setState({ coords: { latitude: 17.1, longitude: 78.2 } })
|
||||||
const { getByTestId, getByText } = renderWithProviders(
|
const { getByTestId, getByText } = renderWithProviders(
|
||||||
<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />,
|
<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />,
|
||||||
{ auth: false }
|
{ auth: false }
|
||||||
|
|
@ -788,37 +786,11 @@ describe('Location components (LOC)', () => {
|
||||||
expect(getByText('Use your current location (17.10000, 78.20000)')).toBeTruthy()
|
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 () => {
|
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' })
|
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(
|
const { getByTestId, UNSAFE_getByType } = renderWithProviders(
|
||||||
<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />,
|
<CartAddressGate onDone={jest.fn()} onBack={jest.fn()} />,
|
||||||
{ auth: false }
|
{ auth: false }
|
||||||
|
|
|
||||||
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 QuickDeliveryAddressSelector from '@/components/QuickDeliveryAddressSelector'
|
||||||
import { useRegionStore } from '@/src/store/regionStore'
|
import { useRegionStore } from '@/src/store/regionStore'
|
||||||
import { useAddressStore } from '@/src/store/addressStore'
|
|
||||||
|
|
||||||
import { renderWithProviders, flush, seedJsonCache } from '../helpers/test-utils'
|
import { renderWithProviders, flush, seedJsonCache } from '../helpers/test-utils'
|
||||||
import { resetAllMocks } from '../helpers/reset'
|
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'
|
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/contexts/AuthContext', () => require('../mocks/auth-context'))
|
||||||
jest.mock('@/src/hooks/useRegion', () => ({
|
jest.mock('@/src/hooks/useRegionNeo', () => ({
|
||||||
useRegion: () => (globalThis as any).__regionHook,
|
useRegionNeo: () => (globalThis as any).__neoHook,
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const ser = (address: any) => ({
|
const ser = (address: any) => ({
|
||||||
|
|
@ -42,21 +41,18 @@ const S3 = ser(A3) // NoRegion
|
||||||
|
|
||||||
function setRegionHook(overrides: Record<string, any> = {}) {
|
function setRegionHook(overrides: Record<string, any> = {}) {
|
||||||
const state: any = {
|
const state: any = {
|
||||||
region: null,
|
regionId: 1,
|
||||||
regionId: null,
|
boundId: 7,
|
||||||
boundId: null,
|
regionName: 'Mahabubnagar',
|
||||||
bound: null,
|
coords: { latitude: 16.7488, longitude: 77.9851 },
|
||||||
regionGeneration: 0,
|
selectedAddressId: null,
|
||||||
hydrated: true,
|
fullAddress: null,
|
||||||
coords: null,
|
isCache: false,
|
||||||
locationStatus: 'idle',
|
changeRegion: jest.fn(),
|
||||||
isResolvingRegion: false,
|
selectAddress: jest.fn(),
|
||||||
setRegion: jest.fn(),
|
|
||||||
clearRegion: jest.fn(),
|
|
||||||
refreshLocation: jest.fn(),
|
|
||||||
...overrides,
|
...overrides,
|
||||||
}
|
}
|
||||||
;(globalThis as any).__regionHook = state
|
;(globalThis as any).__neoHook = state
|
||||||
return 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 () => {
|
it('SLOTQ-01: a foreign address warns, confirms the switch and clears the cart/home', async () => {
|
||||||
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||||
useRegionStore.getState().setRegion(REGION_1, 7)
|
useRegionStore.getState().setRegion(REGION_1, 7)
|
||||||
useAddressStore.getState().setSelectedAddressId(12)
|
|
||||||
__set('cart_items', CART_REG)
|
__set('cart_items', CART_REG)
|
||||||
setup()
|
setup()
|
||||||
|
;(globalThis as any).__neoHook.selectedAddressId = 12
|
||||||
const { getByTestId, getByText } = renderWithProviders(<QuickDeliveryAddressSelector />, {
|
const { getByTestId, getByText } = renderWithProviders(<QuickDeliveryAddressSelector />, {
|
||||||
auth: false,
|
auth: false,
|
||||||
})
|
})
|
||||||
|
|
@ -117,8 +113,7 @@ describe('QuickDeliveryAddressSelector (SLOTQ)', () => {
|
||||||
await switchButton.onPress()
|
await switchButton.onPress()
|
||||||
})
|
})
|
||||||
|
|
||||||
expect(useRegionStore.getState().selectedRegionId).toBe(2)
|
expect((globalThis as any).__neoHook.selectAddress).toHaveBeenCalledWith(12)
|
||||||
expect(__snapshot().cart_items).toBe('[]')
|
|
||||||
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
|
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
|
||||||
alertSpy.mockRestore()
|
alertSpy.mockRestore()
|
||||||
})
|
})
|
||||||
|
|
@ -126,8 +121,8 @@ describe('QuickDeliveryAddressSelector (SLOTQ)', () => {
|
||||||
it('SLOTQ-02: an address in an unavailable region alerts instead of switching', async () => {
|
it('SLOTQ-02: an address in an unavailable region alerts instead of switching', async () => {
|
||||||
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
||||||
useRegionStore.getState().setRegion(REGION_1, 7)
|
useRegionStore.getState().setRegion(REGION_1, 7)
|
||||||
useAddressStore.getState().setSelectedAddressId(31)
|
|
||||||
setup({ addresses: [S1, { ...S1, id: 31, regionId: 99 }] })
|
setup({ addresses: [S1, { ...S1, id: 31, regionId: 99 }] })
|
||||||
|
;(globalThis as any).__neoHook.selectedAddressId = 31
|
||||||
const { getByTestId } = renderWithProviders(<QuickDeliveryAddressSelector />, {
|
const { getByTestId } = renderWithProviders(<QuickDeliveryAddressSelector />, {
|
||||||
auth: false,
|
auth: false,
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ import { __reset as resetNotifications } from '../mocks/expo-notifications-mock'
|
||||||
import { __resetRouterMock } from '../mocks/expo-router-mock'
|
import { __resetRouterMock } from '../mocks/expo-router-mock'
|
||||||
import { __resetAuthState } from '../mocks/auth-context'
|
import { __resetAuthState } from '../mocks/auth-context'
|
||||||
|
|
||||||
|
import { REGIONS } from '../fixtures'
|
||||||
import { useAppStore } from '@/src/store/appStore'
|
import { useAppStore } from '@/src/store/appStore'
|
||||||
import { useAddressStore } from '@/src/store/addressStore'
|
import { useAddressStore } from '@/src/store/addressStore'
|
||||||
import { useCartStore } from '@/src/store/cartStore'
|
import { useCartStore } from '@/src/store/cartStore'
|
||||||
|
|
@ -22,6 +23,7 @@ import { useCheckoutStore } from '@/src/store/checkoutStore'
|
||||||
import { useCentralProductStore } from '@/src/store/centralProductStore'
|
import { useCentralProductStore } from '@/src/store/centralProductStore'
|
||||||
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
|
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
|
||||||
import { useRegionStore } from '@/src/store/regionStore'
|
import { useRegionStore } from '@/src/store/regionStore'
|
||||||
|
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
|
||||||
import { useLocationStore } from '@/src/store/locationStore'
|
import { useLocationStore } from '@/src/store/locationStore'
|
||||||
import { useSlotStore } from '@/components/stores/slotStore'
|
import { useSlotStore } from '@/components/stores/slotStore'
|
||||||
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
|
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore'
|
||||||
|
|
@ -54,6 +56,20 @@ export function resetStores() {
|
||||||
// flip this back to false).
|
// flip this back to false).
|
||||||
hydrated: true,
|
hydrated: true,
|
||||||
})
|
})
|
||||||
|
// Most component tests mount a screen directly (no LocationWrapperNeo), so
|
||||||
|
// the store starts ready. No-region cases call clearNeoRegion() explicitly.
|
||||||
|
useNeoRegionStore.setState({
|
||||||
|
regionId: 1,
|
||||||
|
boundId: 7,
|
||||||
|
regionName: 'Mahabubnagar',
|
||||||
|
coords: { latitude: 16.7488, longitude: 77.9851 },
|
||||||
|
origin: 'manual',
|
||||||
|
regions: REGIONS as any,
|
||||||
|
addresses: [],
|
||||||
|
selectedAddressId: null,
|
||||||
|
needsAddressFormFlow: false,
|
||||||
|
needsAddressConfirmation: false,
|
||||||
|
})
|
||||||
useSlotStore.setState({ slotId: undefined, storeId: undefined })
|
useSlotStore.setState({ slotId: undefined, storeId: undefined })
|
||||||
useFlashNavigationStore.setState({ shouldNavigateToCart: false })
|
useFlashNavigationStore.setState({ shouldNavigateToCart: false })
|
||||||
useHomeTagStore.setState({ selectedTagId: null, expandedByTagId: {} })
|
useHomeTagStore.setState({ selectedTagId: null, expandedByTagId: {} })
|
||||||
|
|
|
||||||
|
|
@ -25,11 +25,15 @@ import {
|
||||||
storeDetailCacheUrl,
|
storeDetailCacheUrl,
|
||||||
storesCacheUrl,
|
storesCacheUrl,
|
||||||
A1,
|
A1,
|
||||||
|
A2,
|
||||||
|
A3,
|
||||||
REGION_1,
|
REGION_1,
|
||||||
|
REGION_2,
|
||||||
} from '../fixtures'
|
} from '../fixtures'
|
||||||
import { useCentralProductStore } from '@/src/store/centralProductStore'
|
import { useCentralProductStore } from '@/src/store/centralProductStore'
|
||||||
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
|
import { useCentralSlotStore } from '@/src/store/centralSlotStore'
|
||||||
import { useRegionStore } from '@/src/store/regionStore'
|
import { useRegionStore } from '@/src/store/regionStore'
|
||||||
|
import { bindNeoRegionQueryClient, useNeoRegionStore } from '@/src/store/neoRegionStore'
|
||||||
import { useAddressStore } from '@/src/store/addressStore'
|
import { useAddressStore } from '@/src/store/addressStore'
|
||||||
|
|
||||||
export function createTestQueryClient(): QueryClient {
|
export function createTestQueryClient(): QueryClient {
|
||||||
|
|
@ -85,6 +89,7 @@ export function renderWithProviders(
|
||||||
options: RenderOptions = {}
|
options: RenderOptions = {}
|
||||||
): RenderWithProvidersResult {
|
): RenderWithProvidersResult {
|
||||||
const queryClient = options.queryClient ?? createTestQueryClient()
|
const queryClient = options.queryClient ?? createTestQueryClient()
|
||||||
|
bindNeoRegionQueryClient(queryClient)
|
||||||
const auth = options.auth ?? 'out'
|
const auth = options.auth ?? 'out'
|
||||||
const withRefresh = options.withRefresh ?? true
|
const withRefresh = options.withRefresh ?? true
|
||||||
|
|
||||||
|
|
@ -166,18 +171,123 @@ export function seedCentralStores(options: { products?: any[]; slots?: any[] } =
|
||||||
/** Select a browsing region (+ bound) without going through the location flow. */
|
/** Select a browsing region (+ bound) without going through the location flow. */
|
||||||
export function seedRegion(region = REGION_1, boundId: number | null = 7) {
|
export function seedRegion(region = REGION_1, boundId: number | null = 7) {
|
||||||
useRegionStore.getState().setRegion(region as any, boundId)
|
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) {
|
export function seedSelectedAddress(addressId: number | null = A1.id) {
|
||||||
useAddressStore.getState().setSelectedAddressId(addressId)
|
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). */
|
/** 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 } = {}) {
|
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()
|
seedJsonCache()
|
||||||
seedCentralStores()
|
seedCentralStores()
|
||||||
seedRegion()
|
seedRegion()
|
||||||
seedSelectedAddress(options.addressId ?? null)
|
seedSelectedAddress(selectedId)
|
||||||
|
// The post-migration components read the neo store; seed a ready region so no
|
||||||
|
// test renders them outside LocationWrapperNeo with an empty store.
|
||||||
|
seedNeoRegion({
|
||||||
|
addresses: [NEO_A1, NEO_A2, NEO_A3],
|
||||||
|
selectedAddressId: selectedId,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setConsoleErrorMock() {
|
export function setConsoleErrorMock() {
|
||||||
|
|
|
||||||
|
|
@ -68,7 +68,6 @@ module.exports = {
|
||||||
'^expo-router$': '<rootDir>/mocks/native/expo-router.tsx',
|
'^expo-router$': '<rootDir>/mocks/native/expo-router.tsx',
|
||||||
'^expo-router/(.*)$': '<rootDir>/mocks/native/expo-router.tsx',
|
'^expo-router/(.*)$': '<rootDir>/mocks/native/expo-router.tsx',
|
||||||
'^expo-image$': '<rootDir>/mocks/native/common.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-linear-gradient$': '<rootDir>/mocks/native/common.tsx',
|
||||||
'^expo-blur$': '<rootDir>/mocks/native/common.tsx',
|
'^expo-blur$': '<rootDir>/mocks/native/common.tsx',
|
||||||
'^expo-status-bar$': '<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 * as React from 'react'
|
||||||
import { act, waitFor } from '@testing-library/react-native'
|
import { act, waitFor } from '@testing-library/react-native'
|
||||||
import { resetAllMocks } from '../helpers/reset'
|
import { resetAllMocks } from '../helpers/reset'
|
||||||
|
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
|
||||||
import {
|
import {
|
||||||
renderWithProviders,
|
renderWithProviders,
|
||||||
flush,
|
flush,
|
||||||
seedRegion,
|
seedRegion,
|
||||||
|
seedNeoRegion,
|
||||||
seedSelectedAddress,
|
seedSelectedAddress,
|
||||||
|
clearNeoRegion,
|
||||||
} from '../helpers/test-utils'
|
} from '../helpers/test-utils'
|
||||||
import {
|
import {
|
||||||
setJsonResponse,
|
setJsonResponse,
|
||||||
|
|
@ -85,6 +88,7 @@ describe('prominent API hooks', () => {
|
||||||
resetAllMocks()
|
resetAllMocks()
|
||||||
configureLocation({ permission: 'denied' })
|
configureLocation({ permission: 'denied' })
|
||||||
seedRegion(REGION_1 as any, 7)
|
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 () => {
|
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 () => {
|
it('API-02: a same-region selected address bound overrides the active bound', async () => {
|
||||||
__setAuthState({ isAuthenticated: true, isLoading: false })
|
__setAuthState({ isAuthenticated: true, isLoading: false })
|
||||||
seedSelectedAddress(A1.id)
|
seedSelectedAddress(A1.id)
|
||||||
|
useNeoRegionStore.setState({ selectedAddressId: A1.id })
|
||||||
setProcedure('user.address.getUserAddresses', { data: { data: [{ ...A1, boundId: 8 }] } })
|
setProcedure('user.address.getUserAddresses', { data: { data: [{ ...A1, boundId: 8 }] } })
|
||||||
|
|
||||||
const { element, result } = makeProbe(() => useGetEssentialConsts())
|
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 () => {
|
it('API-03: a selected address in another region is ignored', async () => {
|
||||||
__setAuthState({ isAuthenticated: true, isLoading: false })
|
__setAuthState({ isAuthenticated: true, isLoading: false })
|
||||||
seedSelectedAddress(A2.id)
|
seedSelectedAddress(A2.id)
|
||||||
|
useNeoRegionStore.setState({ selectedAddressId: A2.id })
|
||||||
|
|
||||||
const { element, result } = makeProbe(() => useGetEssentialConsts())
|
const { element, result } = makeProbe(() => useGetEssentialConsts())
|
||||||
renderWithProviders(element, { auth: false })
|
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 () => {
|
it('API-04: with no region/bound the consts query stays disabled', async () => {
|
||||||
|
clearNeoRegion()
|
||||||
useRegionStore.getState().clearRegion()
|
useRegionStore.getState().clearRegion()
|
||||||
|
|
||||||
const { element, result } = makeProbe(() => useGetEssentialConsts())
|
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_b7', JSON.stringify({ ...CONSTS, freeDeliveryThreshold: 111 }))
|
||||||
setSecureItem('essential_consts_b8', JSON.stringify({ ...CONSTS, boundId: 8, freeDeliveryThreshold: 222 }))
|
setSecureItem('essential_consts_b8', JSON.stringify({ ...CONSTS, boundId: 8, freeDeliveryThreshold: 222 }))
|
||||||
seedRegion(REGION_1 as any, 8)
|
seedRegion(REGION_1 as any, 8)
|
||||||
|
seedNeoRegion({ regionId: REGION_1.id, boundId: 8 })
|
||||||
|
|
||||||
const { element, result } = makeProbe(() => useGetEssentialConsts())
|
const { element, result } = makeProbe(() => useGetEssentialConsts())
|
||||||
renderWithProviders(element, { auth: false })
|
renderWithProviders(element, { auth: false })
|
||||||
|
|
@ -196,6 +204,7 @@ describe('prominent API hooks', () => {
|
||||||
JSON.stringify({ ...CONSTS, boundId: 7, freeDeliveryThreshold: 111 })
|
JSON.stringify({ ...CONSTS, boundId: 7, freeDeliveryThreshold: 111 })
|
||||||
)
|
)
|
||||||
seedRegion(REGION_1 as any, 8)
|
seedRegion(REGION_1 as any, 8)
|
||||||
|
seedNeoRegion({ regionId: REGION_1.id, boundId: 8 })
|
||||||
|
|
||||||
const { element, result } = makeProbe(() => useGetEssentialConsts())
|
const { element, result } = makeProbe(() => useGetEssentialConsts())
|
||||||
renderWithProviders(element, { auth: false })
|
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 () => {
|
it('API-18: a region change produces a new CDN URL / query key', async () => {
|
||||||
setProcedure('common.essentialConsts', {
|
setProcedure('common.essentialConsts', {
|
||||||
impl: () => {
|
impl: () => {
|
||||||
const regionId = useRegionStore.getState().selectedRegionId ?? 1
|
const regionId = useNeoRegionStore.getState().regionId ?? 1
|
||||||
return {
|
return {
|
||||||
...CONSTS,
|
...CONSTS,
|
||||||
regionId,
|
regionId,
|
||||||
|
|
@ -397,7 +406,7 @@ describe('prominent API hooks', () => {
|
||||||
await waitFor(() => expect(jsonCallsFor(productsCacheUrl(1))).toHaveLength(1))
|
await waitFor(() => expect(jsonCallsFor(productsCacheUrl(1))).toHaveLength(1))
|
||||||
|
|
||||||
await act(async () => {
|
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))
|
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 () => {
|
it('REGION-32: a persisted region/bound is hydrated before the launch decision', async () => {
|
||||||
await withFreshModules(async (ctx) => {
|
await withFreshModules(async (ctx) => {
|
||||||
|
|
@ -880,177 +837,8 @@ describe('useRegion', () => {
|
||||||
|
|
||||||
|
|
||||||
describe('Home region integration (REGION-16..18)', () => {
|
describe('Home region integration (REGION-16..18)', () => {
|
||||||
it('REGION-16: a default address and a location in its region open Home in that region', async () => {
|
|
||||||
await withFreshModules(async (ctx) => {
|
|
||||||
const { REGION_1, REGION_2, BOUND_1, A1, A2, productsCacheUrl } = ctx.fixtures
|
|
||||||
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false })
|
|
||||||
ctx.locationMock.__configure({ permission: 'granted' })
|
|
||||||
ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1, REGION_2] })
|
|
||||||
ctx.trpc.setProcedure('common.resolveRegionByLocation', {
|
|
||||||
data: { region: REGION_1, bound: BOUND_1 },
|
|
||||||
})
|
|
||||||
ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: A1 } })
|
|
||||||
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [A1, A2] } })
|
|
||||||
|
|
||||||
ctx.testUtils.seedJsonCache({ regionId: 1 })
|
|
||||||
ctx.testUtils.seedJsonCache({ regionId: 2 })
|
|
||||||
ctx.testUtils.seedCentralStores()
|
|
||||||
ctx.testUtils.seedSelectedAddress(A1.id)
|
|
||||||
|
|
||||||
const Home = require('@/app/(drawer)/(tabs)/home/index').default
|
|
||||||
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
|
|
||||||
await ctx.testUtils.flush(8)
|
|
||||||
|
|
||||||
expect(ctx.regionStore.getState().selectedRegionId).toBe(1)
|
|
||||||
expect(ctx.regionStore.getState().selectedBoundId).toBe(7)
|
|
||||||
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1)).length).toBeGreaterThan(0)
|
|
||||||
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2))).toHaveLength(0)
|
|
||||||
expect(view.getByText('Mahabubnagar')).toBeTruthy()
|
|
||||||
view.unmount()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('REGION-17: a location in another region clears the default region and opens the chooser', async () => {
|
|
||||||
await withFreshModules(async (ctx) => {
|
|
||||||
const { REGION_1, REGION_2, A1, A2, productsCacheUrl } = ctx.fixtures
|
|
||||||
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false })
|
|
||||||
ctx.locationMock.__configure({ permission: 'granted' })
|
|
||||||
ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1, REGION_2] })
|
|
||||||
ctx.trpc.setProcedure('common.resolveRegionByLocation', {
|
|
||||||
data: {
|
|
||||||
region: REGION_2,
|
|
||||||
bound: { id: 8, regionId: 2, priority: 1, name: 'Bound 2' },
|
|
||||||
},
|
|
||||||
})
|
|
||||||
ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: A1 } })
|
|
||||||
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [A1, A2] } })
|
|
||||||
|
|
||||||
ctx.testUtils.seedJsonCache({ regionId: 1 })
|
|
||||||
ctx.testUtils.seedJsonCache({ regionId: 2 })
|
|
||||||
ctx.testUtils.seedCentralStores()
|
|
||||||
|
|
||||||
const Home = require('@/app/(drawer)/(tabs)/home/index').default
|
|
||||||
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
|
|
||||||
await ctx.testUtils.flush(8)
|
|
||||||
|
|
||||||
expect(ctx.regionStore.getState().selectedRegionId).toBeNull()
|
|
||||||
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1))).toHaveLength(0)
|
|
||||||
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2))).toHaveLength(0)
|
|
||||||
expect(view.getByText('Choose your address')).toBeTruthy()
|
|
||||||
view.unmount()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('REGION-18: without a default address, the location alone opens its region', async () => {
|
|
||||||
await withFreshModules(async (ctx) => {
|
|
||||||
const { REGION_1, REGION_2, A1, A2, productsCacheUrl } = ctx.fixtures
|
|
||||||
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false })
|
|
||||||
ctx.locationMock.__configure({ permission: 'granted' })
|
|
||||||
ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1, REGION_2] })
|
|
||||||
ctx.trpc.setProcedure('common.resolveRegionByLocation', {
|
|
||||||
data: {
|
|
||||||
region: REGION_2,
|
|
||||||
bound: { id: 8, regionId: 2, priority: 1, name: 'Bound 2' },
|
|
||||||
},
|
|
||||||
})
|
|
||||||
ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: null } })
|
|
||||||
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [A1, A2] } })
|
|
||||||
ctx.trpc.setProcedure('common.essentialConsts', {
|
|
||||||
data: {
|
|
||||||
...ctx.fixtures.CONSTS,
|
|
||||||
regionId: 2,
|
|
||||||
boundId: 8,
|
|
||||||
// Published URLs must follow the payload's own region, exactly like the
|
|
||||||
// backend builds them.
|
|
||||||
essentialUrls: buildEssentialUrls({
|
|
||||||
assetsDomain: ctx.fixtures.CACHE_BASE,
|
|
||||||
apiCacheKey: ctx.fixtures.API_CACHE_KEY,
|
|
||||||
regionId: 2,
|
|
||||||
versions: {
|
|
||||||
products: ctx.fixtures.PRODUCTS_VERSION_NUM,
|
|
||||||
availability: ctx.fixtures.AVAILABILITY_VERSION_NUM,
|
|
||||||
slots: ctx.fixtures.SLOTS_VERSION_NUM,
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
ctx.testUtils.seedJsonCache({ regionId: 1 })
|
|
||||||
ctx.testUtils.seedJsonCache({ regionId: 2 })
|
|
||||||
ctx.testUtils.seedCentralStores()
|
|
||||||
|
|
||||||
const Home = require('@/app/(drawer)/(tabs)/home/index').default
|
|
||||||
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
|
|
||||||
await ctx.testUtils.flush(8)
|
|
||||||
|
|
||||||
expect(ctx.regionStore.getState().selectedRegionId).toBe(2)
|
|
||||||
expect(ctx.regionStore.getState().selectedBoundId).toBe(8)
|
|
||||||
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2)).length).toBeGreaterThan(0)
|
|
||||||
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1))).toHaveLength(0)
|
|
||||||
expect(view.getByText('Hyderabad')).toBeTruthy()
|
|
||||||
view.unmount()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('REGION-21: a sole non-default address opens Home with location off', async () => {
|
|
||||||
await withFreshModules(async (ctx) => {
|
|
||||||
const { REGION_1, REGION_2, A1, productsCacheUrl } = ctx.fixtures
|
|
||||||
const sole = { ...A1, isDefault: false }
|
|
||||||
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false })
|
|
||||||
ctx.locationMock.__configure({ permission: 'denied' })
|
|
||||||
ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1, REGION_2] })
|
|
||||||
ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: null } })
|
|
||||||
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [sole] } })
|
|
||||||
|
|
||||||
ctx.testUtils.seedJsonCache({ regionId: 1 })
|
|
||||||
ctx.testUtils.seedJsonCache({ regionId: 2 })
|
|
||||||
ctx.testUtils.seedCentralStores()
|
|
||||||
|
|
||||||
const Home = require('@/app/(drawer)/(tabs)/home/index').default
|
|
||||||
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
|
|
||||||
await ctx.testUtils.flush(8)
|
|
||||||
|
|
||||||
expect(ctx.regionStore.getState().selectedRegionId).toBe(1)
|
|
||||||
expect(ctx.regionStore.getState().selectedBoundId).toBe(7)
|
|
||||||
expect(ctx.addressStore.getState().selectedAddressId).toBe(sole.id)
|
|
||||||
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1)).length).toBeGreaterThan(0)
|
|
||||||
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2))).toHaveLength(0)
|
|
||||||
expect(view.getByText('Mahabubnagar')).toBeTruthy()
|
|
||||||
view.unmount()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('REGION-22: a sole non-default address opens Home even when location is elsewhere', async () => {
|
|
||||||
await withFreshModules(async (ctx) => {
|
|
||||||
const { REGION_1, REGION_2, A1, productsCacheUrl } = ctx.fixtures
|
|
||||||
const sole = { ...A1, isDefault: false }
|
|
||||||
ctx.auth.__setAuthState({ isAuthenticated: true, isLoading: false })
|
|
||||||
ctx.locationMock.__configure({ permission: 'granted' })
|
|
||||||
ctx.trpc.setProcedure('common.listRegions', { data: [REGION_1, REGION_2] })
|
|
||||||
ctx.trpc.setProcedure('common.resolveRegionByLocation', {
|
|
||||||
data: {
|
|
||||||
region: REGION_2,
|
|
||||||
bound: { id: 8, regionId: 2, priority: 1, name: 'Bound 2' },
|
|
||||||
},
|
|
||||||
})
|
|
||||||
ctx.trpc.setProcedure('user.address.getDefaultAddress', { data: { data: null } })
|
|
||||||
ctx.trpc.setProcedure('user.address.getUserAddresses', { data: { data: [sole] } })
|
|
||||||
|
|
||||||
ctx.testUtils.seedJsonCache({ regionId: 1 })
|
|
||||||
ctx.testUtils.seedJsonCache({ regionId: 2 })
|
|
||||||
ctx.testUtils.seedCentralStores()
|
|
||||||
|
|
||||||
const Home = require('@/app/(drawer)/(tabs)/home/index').default
|
|
||||||
const view = ctx.testUtils.renderWithProviders(ctx.React.createElement(Home), { auth: false })
|
|
||||||
await ctx.testUtils.flush(8)
|
|
||||||
|
|
||||||
expect(ctx.regionStore.getState().selectedRegionId).toBe(1)
|
|
||||||
expect(ctx.regionStore.getState().selectedBoundId).toBe(7)
|
|
||||||
expect(ctx.addressStore.getState().selectedAddressId).toBe(sole.id)
|
|
||||||
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(1)).length).toBeGreaterThan(0)
|
|
||||||
expect(ctx.fetchJson.jsonCallsFor(productsCacheUrl(2))).toHaveLength(0)
|
|
||||||
expect(view.getByText('Mahabubnagar')).toBeTruthy()
|
|
||||||
view.unmount()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,7 @@ import constants from '@/src/constants'
|
||||||
import { useAddressStore } from '@/src/store/addressStore'
|
import { useAddressStore } from '@/src/store/addressStore'
|
||||||
import { useCheckoutStore } from '@/src/store/checkoutStore'
|
import { useCheckoutStore } from '@/src/store/checkoutStore'
|
||||||
import { useRegionStore } from '@/src/store/regionStore'
|
import { useRegionStore } from '@/src/store/regionStore'
|
||||||
|
import { useNeoRegionStore } from '@/src/store/neoRegionStore'
|
||||||
|
|
||||||
import {
|
import {
|
||||||
renderWithProviders,
|
renderWithProviders,
|
||||||
|
|
@ -265,17 +266,6 @@ describe('Cart (scheduled) — CART-01..110', () => {
|
||||||
expect(getByText('Loading cart...')).toBeTruthy()
|
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 () => {
|
it('CART-08: a failing cart query shows "Failed to load your cart" with no retry', async () => {
|
||||||
seedBoot()
|
seedBoot()
|
||||||
|
|
@ -286,15 +276,6 @@ describe('Cart (scheduled) — CART-01..110', () => {
|
||||||
expect(queryByText('Retry')).toBeNull()
|
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 () => {
|
it('CART-10: no addresses show the CartAddressGate even when the cart is empty', async () => {
|
||||||
seedBoot()
|
seedBoot()
|
||||||
|
|
@ -1208,16 +1189,6 @@ describe('Cart (scheduled) — CART-01..110', () => {
|
||||||
expect(useAddressStore.getState().selectedAddressId).toBe(A1.id)
|
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 () => {
|
it('CART-91: tapping a cross-region address asks to confirm; Cancel changes nothing', async () => {
|
||||||
const alertSpy = spyAlert()
|
const alertSpy = spyAlert()
|
||||||
|
|
@ -1244,7 +1215,7 @@ describe('Cart (scheduled) — CART-01..110', () => {
|
||||||
})
|
})
|
||||||
fireEvent.press(getByTestId('address-option-1'))
|
fireEvent.press(getByTestId('address-option-1'))
|
||||||
await tapAlert(alertSpy, 'Switch & clear cart')
|
await tapAlert(alertSpy, 'Switch & clear cart')
|
||||||
expect(useRegionStore.getState().selectedRegionId).toBe(2)
|
expect(useNeoRegionStore.getState().regionId).toBe(2)
|
||||||
expect(storedLines()).toEqual([])
|
expect(storedLines()).toEqual([])
|
||||||
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
|
expect(router.replace).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
|
||||||
alertSpy.mockRestore()
|
alertSpy.mockRestore()
|
||||||
|
|
@ -1267,18 +1238,6 @@ describe('Cart (scheduled) — CART-01..110', () => {
|
||||||
alertSpy.mockRestore()
|
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 () => {
|
it('CART-95: attaching the current location updates the address with the coords', async () => {
|
||||||
const { getByTestId } = await mount({
|
const { getByTestId } = await mount({
|
||||||
|
|
|
||||||
|
|
@ -254,12 +254,14 @@ describe('Checkout — CHECK-01..35', () => {
|
||||||
expect(first.getByTestId('checkout-address-name')).toHaveTextContent('Home')
|
expect(first.getByTestId('checkout-address-name')).toHaveTextContent('Home')
|
||||||
first.unmount()
|
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({
|
const second = await mount({
|
||||||
addressId: null,
|
addressId: null,
|
||||||
lines: [line(1, 2, 2, 1849)],
|
lines: [line(1, 2, 2, 1849)],
|
||||||
params: { slots: '1849:1' },
|
params: { slots: '1849:1' },
|
||||||
})
|
})
|
||||||
expect(second.getByTestId('checkout-address-name')).toHaveTextContent('Home')
|
expect(second.getByTestId('checkout-address-empty')).toBeTruthy()
|
||||||
second.unmount()
|
second.unmount()
|
||||||
|
|
||||||
const third = await mount({
|
const third = await mount({
|
||||||
|
|
@ -270,14 +272,6 @@ describe('Checkout — CHECK-01..35', () => {
|
||||||
expect(third.getByTestId('checkout-address-empty')).toBeTruthy()
|
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 () => {
|
it('CHECK-28: the flash checkout uses the flash price in items and totals', async () => {
|
||||||
const { getByTestId } = await mount({
|
const { getByTestId } = await mount({
|
||||||
|
|
|
||||||
|
|
@ -84,14 +84,6 @@ describe('Me hub (ME-01..ME-19)', () => {
|
||||||
expect(view.getByText(`Delivering in ${REGION_1.name}`)).toBeTruthy()
|
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 () => {
|
it('ME-04: My Orders pushes the my-orders route', async () => {
|
||||||
const view = await renderHub()
|
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 () => {
|
it('ME-08: Delivery Address opens the address switcher sheet', async () => {
|
||||||
const view = await renderHub()
|
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'))
|
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 () => {
|
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()
|
expect(view.queryByTestId('location-bar')).toBeNull()
|
||||||
fireEvent.press(view.getByTestId('me-menu-delivery-address'))
|
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 () => {
|
it('ME-18: closing the address sheet dismisses it', async () => {
|
||||||
const view = await renderHub()
|
const view = await renderHub()
|
||||||
|
|
||||||
fireEvent.press(view.getByTestId('me-menu-delivery-address'))
|
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)
|
const modal = view.UNSAFE_getAllByType(Modal).find((candidate: any) => candidate.props.visible)
|
||||||
expect(modal).toBeTruthy()
|
expect(modal).toBeTruthy()
|
||||||
|
|
@ -232,7 +224,7 @@ describe('Me hub (ME-01..ME-19)', () => {
|
||||||
fireEvent(modal!, 'requestClose')
|
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 () => {
|
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()
|
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 () => {
|
it('PAY-04: no valid items alerts "No valid items to order"', async () => {
|
||||||
const alert = spyAlert()
|
const alert = spyAlert()
|
||||||
|
|
|
||||||
|
|
@ -90,13 +90,6 @@ const cartLine = (id: number, skuId: number, quantity: number, slotId: number) =
|
||||||
describe('ProductDetail', () => {
|
describe('ProductDetail', () => {
|
||||||
beforeEach(() => resetAllMocks())
|
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 () => {
|
it('PD-02: a pending product query keeps the loading copy', async () => {
|
||||||
seedBoot()
|
seedBoot()
|
||||||
|
|
|
||||||
|
|
@ -17,10 +17,15 @@ export const Route = createFileRoute('/location-selector')({
|
||||||
const parsed = Number(value)
|
const parsed = Number(value)
|
||||||
return Number.isFinite(parsed) ? parsed : undefined
|
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 {
|
return {
|
||||||
lat: num(search.lat),
|
lat: num(search.lat),
|
||||||
lng: num(search.lng),
|
lng: num(search.lng),
|
||||||
zoom: num(search.zoom),
|
zoom: num(search.zoom),
|
||||||
|
fixed: flag(search.fixed),
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
component: LocationSelectorPage,
|
component: LocationSelectorPage,
|
||||||
|
|
@ -188,6 +193,7 @@ function LocationSelectorPage() {
|
||||||
const [pendingCoords, setPendingCoords] = useState<LatLngLiteral | null>(null)
|
const [pendingCoords, setPendingCoords] = useState<LatLngLiteral | null>(null)
|
||||||
|
|
||||||
const search = Route.useSearch()
|
const search = Route.useSearch()
|
||||||
|
const isFixed = search.fixed === true
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!GOOGLE_MAPS_API_KEY) {
|
if (!GOOGLE_MAPS_API_KEY) {
|
||||||
|
|
@ -224,36 +230,40 @@ function LocationSelectorPage() {
|
||||||
})
|
})
|
||||||
mapRef.current = map
|
mapRef.current = map
|
||||||
|
|
||||||
// The pin is on the map from the start, at the map centre. Continue is
|
// The pin is on the map from the start, at the map centre. In the normal
|
||||||
// disabled until the user touches it (tap anywhere on the map, tap the
|
// mode Continue stays disabled until the user touches it (tap the map,
|
||||||
// pin, or drag the pin), which is what writes `pendingCoords`.
|
// 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({
|
const marker = new maps.Marker({
|
||||||
map,
|
map,
|
||||||
position: center,
|
position: center,
|
||||||
draggable: true,
|
draggable: !isFixed,
|
||||||
})
|
})
|
||||||
|
|
||||||
const chooseMarkerPosition = () => {
|
if (!isFixed) {
|
||||||
const position = marker.getPosition()
|
const chooseMarkerPosition = () => {
|
||||||
if (!position) return
|
const position = marker.getPosition()
|
||||||
setPendingCoords({ lat: position.lat(), lng: position.lng() })
|
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)
|
setIsLoading(false)
|
||||||
})
|
})
|
||||||
.catch((error: unknown) => {
|
.catch((error: unknown) => {
|
||||||
|
|
@ -265,7 +275,7 @@ function LocationSelectorPage() {
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true
|
cancelled = true
|
||||||
}
|
}
|
||||||
}, [])
|
}, [isFixed])
|
||||||
|
|
||||||
const handleConfirm = useCallback(() => {
|
const handleConfirm = useCallback(() => {
|
||||||
if (!pendingCoords) return
|
if (!pendingCoords) return
|
||||||
|
|
@ -327,7 +337,7 @@ function LocationSelectorPage() {
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!isLoading && !loadError && (
|
{!isLoading && !loadError && !isFixed && (
|
||||||
<div
|
<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)]"
|
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))' }}
|
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
|
||||||
300
change-log.txt
300
change-log.txt
|
|
@ -867,3 +867,303 @@ never read the new switch. WebViewWrapper was a third surface (host-gated
|
||||||
+ ROOT-34: closable store dialog renders Later and dismisses.
|
+ ROOT-34: closable store dialog renders Later and dismisses.
|
||||||
--- apps/user-ui/JEST-TEST-CASES.md
|
--- apps/user-ui/JEST-TEST-CASES.md
|
||||||
+ ROOT-33/ROOT-34 rows; ROOT-05/06 note the switch.
|
+ ROOT-33/ROOT-34 rows; ROOT-05/06 note the switch.
|
||||||
|
|
||||||
|
[2026-11-07 20:20:44 IST] redraw the hand-drawn location flow as a text-based HTML+SVG page.
|
||||||
|
|
||||||
|
The source `behaviour-flows/freshyo-location-flow.svg` is a tldraw export with
|
||||||
|
zero <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
|
||||||
|
+ 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
|
||||||
|
|
|
||||||
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).
|
||||||
Loading…
Add table
Reference in a new issue