This commit is contained in:
shafi54 2026-10-09 00:58:12 +05:30
parent 6e5790e1fd
commit 92bf4e8b44
28 changed files with 498 additions and 114 deletions

View file

@ -57,4 +57,10 @@ minRegularOrderValue
freeDeliveryThreshold
deliveryCharge
flashFreeDeliveryThreshold
flashDeliveryCharge
flashDeliveryCharge
ss gutta 16.748783, 78.004532
appally 16.759780, 78.054594

View file

@ -7,6 +7,9 @@ import {
getAllRegions,
getAllRegionsWithBounds,
getEffectiveRegionSettings,
getBoundsForRegion,
getEffectiveBoundId,
getUserAddresses,
} from '@/src/dbService'
import type { StoresSummaryResponse, RegionGeoJson, ResolvedRegion } from '@packages/shared'
import { polygon as turfPolygon, point as turfPoint } from '@turf/helpers';
@ -239,6 +242,27 @@ export const commonApiRouter = router({
return effective
}),
// The active bound for a region: the least-priority bound among the user's
// addresses in that region, else the region's effective (least-priority) bound.
activeBound: protectedProcedure
.input(z.object({ regionId: z.number().int().positive() }))
.query(async ({ ctx, input }): Promise<{ regionId: number; boundId: number | null }> => {
const addresses = await getUserAddresses(ctx.user.userId)
const boundIds = new Set(
addresses
.filter((address) => address.regionId === input.regionId && address.boundId != null)
.map((address) => address.boundId as number)
)
if (boundIds.size > 0) {
const bounds = await getBoundsForRegion(input.regionId) // priority ascending
const least = bounds.find((bound) => boundIds.has(bound.id))
if (least) return { regionId: input.regionId, boundId: least.id }
}
return { regionId: input.regionId, boundId: await getEffectiveBoundId(input.regionId) }
}),
essentialConsts: publicProcedure
.input(z.object({ boundId: z.number().int().positive() }))
.query(async ({ ctx, input }) => {

View file

@ -38,6 +38,7 @@ export const addressRouter = router({
createAddress: protectedProcedure
.input(z.object({
regionId: z.number().int().positive('Region is required'),
boundId: z.number().int().positive().optional(),
name: z.string().min(1, 'Name is required'),
phone: z.string().min(1, 'Phone is required'),
addressLine1: z.string().min(1, 'Address line 1 is required'),
@ -69,14 +70,19 @@ export const addressRouter = router({
throw new Error('Missing required fields');
}
// The first address a user adds becomes their default.
const existingAddresses = await getUserAddressesInDb(userId)
const makeDefault = isDefault || existingAddresses.length === 0
// If setting as default, unset other defaults
if (isDefault) {
if (makeDefault) {
await clearDefaultAddressInDb(userId)
}
const newAddress = await createUserAddressInDb({
userId,
regionId: input.regionId,
boundId: input.boundId,
name,
phone,
addressLine1,
@ -84,7 +90,7 @@ export const addressRouter = router({
city,
state,
pincode,
isDefault: isDefault || false,
isDefault: makeDefault,
latitude,
longitude,
googleMapsUrl,
@ -97,6 +103,7 @@ export const addressRouter = router({
.input(z.object({
id: z.number().int().positive(),
regionId: z.number().int().positive('Region is required'),
boundId: z.number().int().positive().optional(),
name: z.string().min(1, 'Name is required'),
phone: z.string().min(1, 'Phone is required'),
addressLine1: z.string().min(1, 'Address line 1 is required'),
@ -138,6 +145,7 @@ export const addressRouter = router({
userId,
addressId: id,
regionId: input.regionId,
boundId: input.boundId,
name,
phone,
addressLine1,

View file

@ -16,6 +16,8 @@ import {
getUserOrdersWithRelations,
getUserSlotCapacityStatus,
getEffectiveRegionSettings,
getEffectiveBoundId,
getRegionSettingsForBound,
orders,
orderItems,
orderStatus,
@ -40,6 +42,7 @@ import type {
const placeOrderUtil = async (params: {
userId: number;
regionId: number;
boundId?: number | null;
selectedItems: Array<{
skuId: number;
quantity: number;
@ -60,21 +63,7 @@ const placeOrderUtil = async (params: {
userNotes,
} = params;
const effective = await getEffectiveRegionSettings(params.regionId);
const boundSettings = effective?.settings ?? {};
const numSetting = (key: string): number => {
const raw = boundSettings[key];
const parsed = raw == null ? NaN : Number(raw);
return Number.isFinite(parsed) ? parsed : 0;
};
const isFlashDelivery = params.isFlash;
const minOrderValue = isFlashDelivery
? numSetting(CONST_KEYS.flashFreeDeliveryThreshold)
: numSetting(CONST_KEYS.minRegularOrderValue);
const deliveryCharge = isFlashDelivery
? numSetting(CONST_KEYS.flashDeliveryCharge)
: numSetting(CONST_KEYS.deliveryCharge);
const orderGroupId = `${Date.now()}-${userId}`;
@ -91,6 +80,26 @@ const placeOrderUtil = async (params: {
);
}
// Bound-level constants (delivery charge/thresholds/min order) come from the
// active bound the client is browsing in, falling back to the region's
// effective bound. Region-level constants are shared across the region's bounds.
const boundId = params.boundId ?? (await getEffectiveBoundId(params.regionId));
const effective =
(boundId != null ? await getRegionSettingsForBound(params.regionId, boundId) : null) ??
(await getEffectiveRegionSettings(params.regionId));
const boundSettings = effective?.settings ?? {};
const numSetting = (key: string): number => {
const raw = boundSettings[key];
const parsed = raw == null ? NaN : Number(raw);
return Number.isFinite(parsed) ? parsed : 0;
};
const minOrderValue = isFlashDelivery
? numSetting(CONST_KEYS.flashFreeDeliveryThreshold)
: numSetting(CONST_KEYS.minRegularOrderValue);
const deliveryCharge = isFlashDelivery
? numSetting(CONST_KEYS.flashDeliveryCharge)
: numSetting(CONST_KEYS.deliveryCharge);
const ordersBySlot = new Map<
number | null,
Array<{
@ -268,6 +277,7 @@ export const orderRouter = router({
),
addressId: z.number().int().positive(),
regionId: z.number().int().positive(),
boundId: z.number().int().positive().optional(),
paymentMethod: z.enum(["online", "cod"]),
couponId: z.number().int().positive().optional(),
userNotes: z.string().optional(),
@ -286,6 +296,7 @@ export const orderRouter = router({
selectedItems,
addressId,
regionId,
boundId,
paymentMethod,
couponId,
userNotes,
@ -323,6 +334,7 @@ export const orderRouter = router({
return await placeOrderUtil({
userId,
regionId,
boundId,
selectedItems: processedItems,
addressId,
paymentMethod,

View file

@ -1,11 +1,24 @@
import { useAuthenticatedRoute } from "@/hooks/useAuthenticatedRoute";
import { Stack } from "expo-router";
import { View } from "react-native";
import { tw, MyText } from "common-ui";
import { useAuth } from "@/src/contexts/AuthContext";
import LoginWall from "@/components/LoginWall";
export default function MeLayout() {
// Protect all profile routes - redirect to login if not authenticated
useAuthenticatedRoute({
targetUrl: '/(drawer)/(tabs)/me'
});
const { isAuthenticated, isLoading } = useAuth();
if (isLoading) {
return (
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
<MyText style={tw`text-gray-500 font-medium`}>Loading...</MyText>
</View>
);
}
// Inline login gate so Back / tab switching still works.
if (!isAuthenticated) {
return <LoginWall message="Log in to view your profile, orders and more." />;
}
return (
<Stack
@ -14,4 +27,4 @@ export default function MeLayout() {
}}
/>
);
}
}

View file

@ -0,0 +1,76 @@
import React from 'react'
import { View } from 'react-native'
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import { tw, MyText } from 'common-ui'
import { trpc } from '@/src/trpc-client'
import { useAuth } from '@/src/contexts/AuthContext'
import { useAddressStore } from '@/src/store/addressStore'
/**
* Read-only delivery address card for the checkout page. The address is chosen
* on the cart page (CheckoutAddressSelector); checkout only shows it.
*/
const CheckoutAddressDisplay: React.FC = () => {
const { isAuthenticated } = useAuth()
const selectedAddressId = useAddressStore((state) => state.selectedAddressId)
const { data: addressesData, isLoading } = trpc.user.address.getUserAddresses.useQuery(
undefined,
{ enabled: isAuthenticated }
)
const addresses = addressesData?.data ?? []
const address =
addresses.find((candidate) => candidate.id === selectedAddressId) ??
addresses.find((candidate) => candidate.isDefault) ??
null
return (
<View style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}>
<View style={tw`flex-row items-center mb-3`}>
<View style={tw`w-8 h-8 bg-blue-50 rounded-full items-center justify-center mr-3`}>
<MaterialIcons name="location-on" size={18} color="#3B82F6" />
</View>
<MyText style={tw`text-base font-bold text-gray-900`}>Delivery Address</MyText>
</View>
{isLoading ? (
<MyText 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`flex-row items-center mb-2`}>
<MaterialIcons
name={
address.name.toLowerCase().includes('home')
? 'home'
: address.name.toLowerCase().includes('work')
? 'work'
: 'location-on'
}
size={20}
color="#6B7280"
/>
<MyText style={tw`font-bold ml-2 text-gray-900`}>{address.name}</MyText>
</View>
<MyText style={tw`text-gray-600 text-sm leading-5 mb-1`} numberOfLines={2}>
{address.addressLine1}
{address.addressLine2 ? `, ${address.addressLine2}` : ''}
</MyText>
<MyText style={tw`text-gray-600 text-sm mb-1`}>
{address.city}, {address.state} - {address.pincode}
</MyText>
<MyText style={tw`text-gray-500 text-xs mt-2`}>Phone: {address.phone}</MyText>
</View>
) : (
<View
style={tw`bg-gray-50 p-6 rounded-xl border border-gray-200 border-dashed items-center justify-center`}
>
<MaterialIcons name="location-off" size={32} color="#9CA3AF" />
<MyText style={tw`text-gray-500 mt-2`}>No address selected</MyText>
</View>
)}
</View>
)
}
export default CheckoutAddressDisplay

View file

@ -113,7 +113,7 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
style: 'destructive',
onPress: () => {
void (async () => {
await confirmRegionSwitch(targetRegion, queryClient);
await confirmRegionSwitch(targetRegion, queryClient, address.boundId ?? targetRegion.effectiveBoundId ?? null);
router.replace('/(drawer)/(tabs)/home');
})();
},

View file

@ -5,7 +5,6 @@ import type { ReactParentComponent } from '@packages/shared'
import { trpc } from '../src/trpc-client'
import { useRegion } from '@/src/hooks/useRegion'
import RegionSelector from '@/src/components/RegionSelector'
import { isEmulator } from '@/src/lib/is-emulator'
const LoadingScreen: React.FC<{ label?: string }> = ({ label }) => (
<View style={tw`flex-1 justify-center items-center bg-white`}>
@ -20,8 +19,8 @@ const LoadingScreen: React.FC<{ label?: string }> = ({ label }) => (
* The browsing region is derived from the device location (see `useRegion`).
* While that is in flight we show a spinner; once a region exists the app
* renders. When the location is unusable — device location switched off,
* permission denied, a simulator, or coordinates outside every region bound —
* the user is asked to choose a region manually.
* permission denied, or coordinates outside every region bound — the user is
* asked to choose a region manually.
*/
const LocationTestWrapper: React.FC<ReactParentComponent> = ({ children }) => {
const {
@ -55,7 +54,7 @@ const LocationTestWrapper: React.FC<ReactParentComponent> = ({ children }) => {
}
// Still deriving the region from device location.
if (!isEmulator() && isResolvingRegion) {
if (isResolvingRegion) {
return <LoadingScreen label="Finding your region..." />
}

View file

@ -0,0 +1,65 @@
import React from 'react'
import { View } from 'react-native'
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import { usePathname, useRouter } from 'expo-router'
import { tw, MyText, MyTouchableOpacity, StorageServiceCasual } from 'common-ui'
import constants from '@/src/constants'
interface LoginWallProps {
/** Headline shown above the message. */
title?: string
/** Supporting copy. */
message?: string
/** When provided, a "Go Back" action is rendered under the Log In button. */
onBack?: () => void
}
/**
* Inline login gate. Renders a "please log in" prompt instead of redirecting, so
* the screen the user came from stays in the navigation stack and Back works
* normally (a push-based redirect would bounce them back into the wall).
*/
const LoginWall: React.FC<LoginWallProps> = ({
title = 'Please log in',
message = 'Log in to continue.',
onBack,
}) => {
const router = useRouter()
const pathname = usePathname()
const handleLogIn = async () => {
try {
// Remember where the user was, so login returns them to this page.
await StorageServiceCasual.setItem(
constants.AUTH_REDIRECT_KEY,
JSON.stringify({ targetUrl: pathname, queryParams: {}, timestamp: Date.now() })
)
} catch {
// ignore storage failure — still navigate to login
}
router.push('/(auth)/login')
}
return (
<View style={tw`flex-1 bg-gray-50 justify-center items-center px-6`}>
<View style={tw`w-20 h-20 bg-blue-50 rounded-full items-center justify-center mb-4`}>
<MaterialIcons name="lock-outline" size={36} color="#2563EB" />
</View>
<MyText style={tw`text-lg font-bold text-gray-900`}>{title}</MyText>
<MyText style={tw`text-gray-500 text-center mt-2 mb-6`}>{message}</MyText>
<MyTouchableOpacity
style={tw`bg-brand500 px-6 py-3 rounded-xl`}
onPress={handleLogIn}
>
<MyText style={tw`text-white font-bold`}>Log In</MyText>
</MyTouchableOpacity>
{onBack && (
<MyTouchableOpacity style={tw`mt-4`} onPress={onBack}>
<MyText style={tw`text-gray-500 font-medium`}>Go Back</MyText>
</MyTouchableOpacity>
)}
</View>
)
}
export default LoginWall

View file

@ -61,7 +61,7 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
const products = useCentralProductStore((state) => state.products);
const productsById = useCentralProductStore((state) => state.productsById);
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
const { regionId: selectedRegionId } = useRegion();
const { regionId: selectedRegionId, boundId: activeBoundId } = useRegion();
// Memoized flash-eligible product IDs
const flashEligibleProductIds = useMemo(() => {
@ -169,6 +169,7 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
}),
addressId: selectedAddress,
regionId: selectedRegionId,
boundId: constsData?.boundId ?? activeBoundId ?? undefined,
paymentMethod: paymentMethod,
couponId: selectedCouponId || undefined,
userNotes: userNotes,

View file

@ -72,7 +72,7 @@ const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps>
style: 'destructive',
onPress: () => {
void (async () => {
await confirmRegionSwitch(targetRegion, queryClient);
await confirmRegionSwitch(targetRegion, queryClient, foreignAddress.boundId ?? targetRegion.effectiveBoundId ?? null);
router.replace('/(drawer)/(tabs)/home');
})();
},

View file

@ -28,6 +28,9 @@ import { useCentralProductStore } from '@/src/store/centralProductStore';
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-query-hooks';
import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks';
import CheckoutAddressSelector from '@/components/CheckoutAddressSelector';
import LoginWall from '@/components/LoginWall';
import { useAddressStore } from '@/src/store/addressStore';
import type { FlashDeliveryProps } from '@packages/shared';
const formatDeliverySlot = (deliveryTime: string): string => {
@ -178,9 +181,11 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
// Hide tabs when cart page is active
useHideTabNav();
const { isAuthenticated } = useAuth();
const { isAuthenticated, isLoading: isAuthLoading } = useAuth();
const cartType: "regular" | "flash" = isFlashDelivery ? "flash" : "regular";
const { selectedAddressId, setSelectedAddressId } = useAddressStore();
const [quantities, setQuantities] = useState<Record<number, number>>({});
const {
data: cartData,
@ -574,6 +579,25 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
// Login wall: render the prompt inline instead of redirecting, so the user can
// still navigate back out of the cart (a push-based redirect would loop).
if (isAuthLoading) {
return (
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
<MyText style={tw`text-gray-500 font-medium`}>Loading...</MyText>
</View>
);
}
if (!isAuthenticated) {
return (
<LoginWall
message="Log in to view your cart and continue to checkout."
onBack={() => router.back()}
/>
);
}
if (isLoading || (isSlotsLoading && !isFlashDelivery)) {
return (
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
@ -954,11 +978,16 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
);
})}
</View>
<CheckoutAddressSelector
selectedAddress={selectedAddressId}
onAddressSelect={setSelectedAddressId}
/>
</>
)}
{/* Cart Type Switcher */}
{cartItems.length > 0 && (
{/* Cart Type Switcher (hidden) */}
{false && cartItems.length > 0 && (
<View style={tw`bg-white rounded-2xl shadow-sm mb-4 border border-gray-100 overflow-hidden`}>
<View style={tw`p-4`}>
{/* First row: Text content */}

View file

@ -1,10 +1,8 @@
import React, { useState, useMemo } from 'react';
import { View, ScrollView } from 'react-native';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { tw, useMarkDataFetchers , BottomDialog, MyText, MyTouchableOpacity, RawBottomDialog } from 'common-ui';
import { tw, useMarkDataFetchers , BottomDialog, MyText, MyTouchableOpacity } from 'common-ui';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { useQueryClient } from '@tanstack/react-query';
import AddressForm from '@/src/components/AddressForm';
import { useAuthenticatedRoute } from '@/hooks/useAuthenticatedRoute';
import { useAuth } from '@/src/contexts/AuthContext';
@ -14,13 +12,12 @@ import { useCentralSlotStore } from '@/src/store/centralSlotStore';
import { useGetCart } from '@/hooks/cart-query-hooks';
import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks';
import PaymentAndOrderComponent from '@/components/PaymentAndOrderComponent';
import CheckoutAddressSelector from '@/components/CheckoutAddressSelector';
import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay';
import { useAddressStore } from '@/src/store/addressStore';
import type { FlashDeliveryProps } from '@packages/shared';
const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false }) => {
const params = useLocalSearchParams();
const queryClient = useQueryClient();
const router = useRouter();
const { isAuthenticated } = useAuth();
@ -49,8 +46,7 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
refetchSlots();
});
const { selectedAddressId, setSelectedAddressId } = useAddressStore();
const [showAddAddress, setShowAddAddress] = useState(false);
const { selectedAddressId } = useAddressStore();
const [selectedCouponId, setSelectedCouponId] = useState<number | null>(null);
@ -261,10 +257,7 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
contentContainerStyle={tw`p-4 pb-32`}
showsVerticalScrollIndicator={false}
>
<CheckoutAddressSelector
selectedAddress={selectedAddressId}
onAddressSelect={setSelectedAddressId}
/>
<CheckoutAddressDisplay />
<PaymentAndOrderComponent
selectedAddress={selectedAddressId}
@ -283,21 +276,6 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
/>
</ScrollView>
<RawBottomDialog open={showAddAddress} onClose={() => setShowAddAddress(false)}>
<AddressForm
onSuccess={(addressId) => {
setShowAddAddress(false);
// Auto-select the newly added address
if (addressId) {
setSelectedAddressId(addressId);
}
queryClient.invalidateQueries();
}}
/>
</RawBottomDialog>
</View>
);
};

View file

@ -22,7 +22,7 @@ const AddressForm: React.FC<AddressFormProps> = ({ onSuccess, initialValues, isE
: null
);
const { regionId: browsingRegionId } = useRegion();
const { regionId: browsingRegionId, boundId: browsingBoundId } = useRegion();
const { data: regions } = trpc.common.listRegions.useQuery();
// Edits keep the stored region unless the user explicitly changes it; new
@ -118,6 +118,7 @@ const AddressForm: React.FC<AddressFormProps> = ({ onSuccess, initialValues, isE
const payload = {
...values,
regionId: values.regionId,
boundId: browsingBoundId ?? undefined,
latitude: currentLocation?.latitude,
longitude: currentLocation?.longitude,
googleMapsUrl: values.googleMapsUrl || undefined,

View file

@ -68,6 +68,7 @@ export const LocationAttacher: React.FC<LocationAttacherProps> = ({
});
const { latitude, longitude } = location.coords;
console.log({location})
const newLocation = { latitude, longitude };
setCurrentLocation(newLocation);
setLocationSuccess(true);

View file

@ -33,7 +33,8 @@ const RegionSelector: React.FC<RegionSelectorProps> = ({
const applySwitch = async (region: RegionSummary) => {
setIsSwitching(true)
try {
await confirmRegionSwitch(region, queryClient, region.effectiveBoundId ?? null)
// The active bound is derived from the user's addresses (see useRegion).
await confirmRegionSwitch(region, queryClient)
onComplete?.(region)
} finally {
setIsSwitching(false)

View file

@ -129,8 +129,7 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
// Check if the redirect state is not too old (24 hours)
const isExpired = Date.now() - redirectState.timestamp > 24 * 60 * 60 * 1000;
if (isExpired) {
// router.replace('/');
router.back();
router.replace('/');
return;
}
@ -148,12 +147,10 @@ export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
targetPath += `?${searchParams.toString()}`;
}
// Navigate to the target URL with params
// router.replace(targetPath as any);
router.back();
// Navigate to the page the user was trying to reach.
router.replace(targetPath as any);
} else {
// No stored redirect state, navigate to home
// router.replace('/');
// No stored redirect state, go back to the previous screen.
router.back();
}
} catch (error) {
@ -323,6 +320,14 @@ export const useAuth = (): AuthContextType => {
return context;
};
/**
* Non-throwing auth read for hooks that can render OUTSIDE the AuthProvider
* (e.g. UpdateChecker sits above it). Returns null when there is no provider.
*/
export const useAuthOptional = (): AuthContextType | null => {
return useContext(AuthContext) ?? null;
};
export const useUserDetails = (): UserDetails | null => {
const context = useContext(AuthContext);
if (context === undefined) {

View file

@ -7,6 +7,8 @@ import { AllProductsApiType, StoresApiType, SlotsApiType, EssentialConstsApiType
import { CACHE_FILENAMES } from "@packages/shared";
import { StorageServiceCasual } from 'common-ui';
import { useRegion } from '@/src/hooks/useRegion'
import { useAddressStore } from '@/src/store/addressStore'
import { useAuthOptional } from '@/src/contexts/AuthContext'
// Discovery payload: the flat per-bound consts object (global + region + bound
// merged by the backend) plus identity/env fields.
@ -17,7 +19,24 @@ export type DiscoveryData = EssentialConstsApiType
const essentialConstsKey = (boundId: number) => `essential_consts_b${boundId}`
export const useGetEssentialConsts = () => {
const { boundId } = useRegion()
// The active bound (least-priority bound among the user's addresses in the
// region, else the region's effective bound) drives the constants; at checkout
// the selected address's bound overrides it.
const { boundId: activeBoundId, coords, regionId } = useRegion()
const isAuthenticated = useAuthOptional()?.isAuthenticated ?? false
const selectedAddressId = useAddressStore((state) => state.selectedAddressId)
const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, {
enabled: isAuthenticated && selectedAddressId != null,
})
const selectedAddress = addressesData?.data?.find((address) => address.id === selectedAddressId)
const boundId =
selectedAddress && selectedAddress.regionId === regionId && selectedAddress.boundId != null
? selectedAddress.boundId
: activeBoundId
// console.log('[user-ui] essentialConsts boundId', boundId, 'coords', coords)
const [initialData, setInitialData] = useState<DiscoveryData | undefined>(undefined)
const [isReady, setIsReady] = useState(false)

View file

@ -5,6 +5,7 @@ import { useRegionStore } from '@/src/store/regionStore'
import { useLocationStore } from '@/src/store/locationStore'
import { trpc } from '@/src/trpc-client'
import { confirmRegionSwitch } from '@/src/lib/region-switch'
import { useAuthOptional } from '@/src/contexts/AuthContext'
// Give up on the backend resolve and fall back to the saved region / chooser.
const RESOLVE_TIMEOUT_MS = 8000
@ -25,11 +26,11 @@ let startupLaunchRegionId: number | null | undefined
* hooks can never drift out of sync.
*
* On every launch the hook takes ONE device fix (no movement tracking) and
* resolves it to a region + bound. If the resolved region equals the saved one
* nothing happens; if it differs, the region is switched (which clears carts and
* refreshes region-scoped data). When the location is unusable — permission
* denied, services off, a simulator, or coordinates outside every bound — the
* saved region is kept, or the chooser is shown when there is none.
* resolves it to a region. The active bound is NOT taken from the location; it is
* the least-priority bound among the user's addresses in that region (else the
* region's effective bound). If the resolved region differs from the saved one
* the region is switched (clears carts, refreshes region-scoped data). When the
* location is unusable the saved region is kept, or the chooser is shown.
*/
export interface UseRegionResult {
/** The region the user is currently browsing. `null` until one is chosen. */
@ -64,6 +65,7 @@ export interface UseRegionResult {
export function useRegion(): UseRegionResult {
const queryClient = useQueryClient()
const isAuthenticated = useAuthOptional()?.isAuthenticated ?? false
const region = useRegionStore((state) => state.selectedRegion)
const regionId = useRegionStore((state) => state.selectedRegionId)
@ -91,23 +93,24 @@ export function useRegion(): UseRegionResult {
return useRegionStore.persist.onFinishHydration(() => setHydrated(true))
}, [])
// The bound whose consts the client reads. Falls back to the region's
// effective bound so a region persisted before boundId existed still resolves.
const boundId = storedBoundId ?? region?.effectiveBoundId ?? null
// Active bound = the least-priority bound among the user's addresses in the
// region, else the region's effective bound. Derived server-side (the client
// does not know bound priorities).
const activeBoundQuery = trpc.common.activeBound.useQuery(
{ regionId: regionId ?? 0 },
{ enabled: hydrated && regionId != null && isAuthenticated, staleTime: 60000 }
)
const activeBoundId = activeBoundQuery.data?.boundId ?? region?.effectiveBoundId ?? null
// Backfill a missing bound from the region list (also covers a manual pick
// whose stored region summary lacked effectiveBoundId).
const regionsQuery = trpc.common.listRegions.useQuery(undefined, {
enabled: hydrated && regionId != null && boundId == null,
staleTime: Infinity,
})
// Keep the stored bound in sync with the derived active bound (region-level).
useEffect(() => {
if (regionId == null || boundId != null) return
const match = regionsQuery.data?.find((r) => r.id === regionId)
if (match && match.effectiveBoundId != null) {
setRegion(match, match.effectiveBoundId)
if (regionId == null || !region) return
if (activeBoundId != null && activeBoundId !== storedBoundId) {
setRegion(region, activeBoundId)
}
}, [regionId, boundId, regionsQuery.data, setRegion])
}, [regionId, region, activeBoundId, storedBoundId, setRegion])
const boundId = storedBoundId ?? activeBoundId
// Take the single launch fix — even when a region is already saved, so a
// device that has moved to another region is detected on startup.
@ -153,7 +156,9 @@ export function useRegion(): UseRegionResult {
const userChangedRegion =
startupLaunchRegionId !== undefined && startupLaunchRegionId !== regionId
if (resolved?.region && !userChangedRegion && resolved.region.id !== regionId) {
void confirmRegionSwitch(resolved.region, queryClient, resolved.bound?.id ?? null)
// New region -> full switch (clears carts, refreshes regional data). The
// active bound is derived separately from the user's addresses.
void confirmRegionSwitch(resolved.region, queryClient)
}
}, [
hydrated,

View file

@ -1,6 +1,5 @@
import { create } from 'zustand'
import * as Location from 'expo-location'
import { isEmulator } from '@/src/lib/is-emulator'
/**
* Device-location reading, owned by the app (not by individual screens).
@ -15,7 +14,7 @@ export type LocationStatus =
| 'locating' // permission requested / waiting for the fix
| 'granted' // coordinates available
| 'denied' // foreground permission refused
| 'unavailable' // services off, emulator, or no fix could be read
| 'unavailable' // services off, or no fix could be read
| 'error'
export interface Coords {
@ -92,12 +91,6 @@ export const useLocationStore = create<LocationStoreState>((set, get) => ({
set({ status: 'locating', error: null })
try {
// Simulators have no meaningful fix; let the caller ask the user instead.
if (isEmulator()) {
set({ status: 'unavailable', coords: null, error: null })
return
}
const { status } = await Location.requestForegroundPermissionsAsync()
if (token !== activeToken) return

View file

@ -1185,3 +1185,120 @@ No backend changes. No tests run.
- useRegion: check runs on every launch (saved region included); same -> no-op,
different -> confirmRegionSwitch (option a: clears carts, refreshes screens);
unusable/null -> keep saved region (or chooser when none). Single-flight switch + manual-pick race guard.
[2026-10-08 20:05:00] Checkout constants now come from the DELIVERY ADDRESS's bound (effective bound fallback).
packages/db_helper_sqlite/src/superadmin-apis/regions.ts
- add getRegionSettingsForBound(regionId, boundId): region_consts + that bound's region_bound_consts
(null when the bound does not belong to the region).
packages/db_helper_sqlite/index.ts - export it.
apps/backend/src/lib/region-resolve.ts (new)
- boundToPolygons + resolveBoundForRegionPoint(regionId, lat, lng): first containing bound in
priority-ascending order.
apps/backend/src/trpc/apis/user-apis/apis/order.ts
- placeOrderUtil resolves the bound from the address coords (adminLatitude/Longitude ?? latitude/longitude),
falls back to getEffectiveBoundId(regionId); bound-level constants (delivery charge/thresholds/min order)
read via getRegionSettingsForBound. Region-level constants unchanged.
apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts
- new protectedProcedure common.resolveAddressBound({ addressId }) -> { regionId, boundId } (same resolver).
apps/user-ui/src/hooks/prominent-api-hooks.ts
- useGetEssentialConsts uses the selected address's bound (when its region matches) else the browsing bound,
so displayed delivery constants match what checkout charges.
Typechecks: db_helper, backend, user-ui clean.
[2026-10-08 20:23:32] user-ui: emulators/simulators are treated like physical devices for location.
apps/user-ui/src/store/locationStore.ts - remove the isEmulator() short-circuit (and import); emulators
go through the normal permission + getCurrentPositionAsync path (they can supply a mock fix).
apps/user-ui/components/LocationTestWrapper.tsx - drop the emulator check from the spinner condition
(and import); update the doc comment.
apps/user-ui/src/lib/is-emulator.ts left in place (now unused by location code).
[2026-10-08 20:30:00] user-ui: log the bound id used for essentialConsts.
apps/user-ui/src/hooks/prominent-api-hooks.ts - console.log the resolved boundId (+ source/region).
[2026-10-08 20:55:00] Active-bound model: addresses carry a bound_id; checkout uses the active bound.
Data model
- schema.ts: addresses.boundId (FK region_bounds.id, nullable).
- shared/types/user.ts: UserAddress.boundId.
- drizzle/0007_addresses_bound_id.sql (new, NOT run): ADD COLUMN bound_id; backfill existing rows to 1.
- meta/_journal.json: drop stale 0007/0008/0009 entries; add idx 7 = 0007_addresses_bound_id.
db_helper (user-apis/address.ts): mapUserAddress.boundId; create/update accept+persist boundId.
backend
- user-apis/apis/address.ts: createAddress/updateAddress accept boundId; FIRST address becomes default.
- user-apis/apis/order.ts: placeOrder accepts boundId; placeOrderUtil uses getRegionSettingsForBound(regionId,boundId)
(fallback effective). Remove the address-coordinate bound resolution.
- common-apis/common-trpc-index.ts: remove resolveAddressBound; lib/region-resolve.ts removed.
user-ui
- prominent-api-hooks: useGetEssentialConsts uses the active bound only (drop resolveAddressBound override).
- RegionSelector / region-switch: manual region pick uses the default address's bound (fallback effective).
- AddressForm / CheckoutAddressSelector / me addresses: send boundId = active bound on create/update.
- Checkout + quick-delivery address lists filtered to the active bound.
[2026-10-08 21:10:00] Active-bound model implemented. Typechecks: db_helper, backend, admin-ui, admin-web,
superadmin-ui, user-ui clean. (web-ui still has the known flat-JSON errors; out of scope.)
- addresses.bound_id column + migration 0007 (backfill 1); journal tail fixed.
- user-ui: manual region pick uses the default address's bound else effective; new addresses get the
active bound; checkout/quick-delivery lists filtered to the active bound; order sends active boundId.
- first address a user adds becomes their default.
- startup location still wins for the active bound.
[2026-10-08 21:15:00] user-ui: log coords alongside the bound id in useGetEssentialConsts.
[2026-10-09 10:00:00] Active bound from the user's addresses (least-priority bound in the region).
backend
- common-apis/common-trpc-index.ts: new common.activeBound({ regionId }) (protected) ->
least-priority bound among the user's addresses in that region, else the region's effective bound.
user-ui
- useRegion: region from location/manual; active bound from common.activeBound (fallback effective),
persisted via setRegion; no longer uses the location's bound. Derivation runs on region change.
- prominent-api-hooks: essentialConsts bound = selected checkout address's bound (same region) ?? active bound.
- CheckoutAddressSelector / QuickDeliveryAddressSelector: show ALL addresses (no bound filter);
same-region bound selection just re-adjusts consts, cross-region still confirms + switches.
- PaymentAndOrderComponent: send boundId = the bound used for the displayed consts.
- RegionSelector: manual pick no longer computes an address bound (derivation handles it).
[2026-10-09 10:15:00] activeBound model implemented. Typechecks: db_helper, backend, user-ui clean.
- common.activeBound({regionId}) -> least-priority bound among the user's addresses in the region,
else the region's effective bound.
- useRegion derives the active bound from common.activeBound (fallback effective); location only sets region.
- useGetEssentialConsts: bound = selected checkout address's bound (same region) ?? active bound.
- Checkout/quick-delivery address lists show all addresses (all regions/bounds); same-region bound
selection re-adjusts consts; cross-region still confirms then switches.
- placeOrder boundId = constsData.boundId (the displayed bound).
[2026-10-09 10:30:00] fix: hooks rendered above AuthProvider no longer require it.
- AuthContext: add useAuthOptional() (returns null instead of throwing when there is no provider).
- useRegion + prominent-api-hooks use useAuthOptional so UpdateChecker (mounted above AuthProvider)
no longer throws "useAuth must be used within an AuthProvider". Typecheck clean.
[2026-10-09 10:35:00] user-ui: comment out the essentialConsts boundId/coords console log (kept for later).
[2026-10-09 10:45:00] user-ui: address selector moves to the cart page; checkout shows it read-only.
- new components/CheckoutAddressDisplay.tsx: read-only card for the selected (or default) address.
- components/cart-page.tsx: render CheckoutAddressSelector (interactive) at the top of the scroll.
- components/checkout-page.tsx: replace CheckoutAddressSelector with CheckoutAddressDisplay;
drop the add-address dialog + AddressForm from checkout (no changing there).
[2026-10-09 10:55:00] done. user-ui typecheck clean.
- cart-page shows the interactive CheckoutAddressSelector (top of the scroll, non-empty cart).
- checkout-page shows CheckoutAddressDisplay (read-only; selected or default address); add-address
dialog + AddressForm removed from checkout.
[2026-10-09 11:05:00] user-ui: cart page behind the login wall (useAuthenticatedRoute), covering both routes.
[2026-10-09 11:20:00] user-ui: fix cart login-wall back-loop. Replace the push-based useAuthenticatedRoute
on the cart with an inline gate (renders a login prompt when signed out) so back navigation works.
[2026-10-09 11:35:00] user-ui: extract the login wall into components/LoginWall.tsx; use it on the cart and the me tab.
- cart-page uses <LoginWall onBack=... />; me/_layout renders <LoginWall /> when signed out (replaces
the push-based useAuthenticatedRoute on the me tab).
[2026-10-09 11:45:00] done. components/LoginWall.tsx (title/message/onBack); cart-page + me/_layout use it.
me/_layout no longer uses useAuthenticatedRoute (checkout still does). user-ui typecheck clean.
[2026-10-09 12:00:00] user-ui: post-login returns to the intended page.
- LoginWall records the current pathname in AUTH_REDIRECT_KEY before pushing /(auth)/login.
- AuthContext.handlePostLoginRedirect now router.replace(targetPath) (was router.back()), so the
user lands on the page they were gated from (cart/me/checkout), not home. user-ui typecheck clean.
[2026-10-09 12:10:00] user-ui cart: address selector moved below the items; "Go to 1 Hr Delivery" switcher
card hidden ({false && ...}). user-ui typecheck clean.

View file

@ -0,0 +1,11 @@
-- Migration: addresses.bound_id — the bound a saved address belongs to.
--
-- Every address is assigned to a bound; new addresses get the user's active
-- bound. Existing rows are backfilled to bound 1.
--
-- NOTE: SQLite has no ADD COLUMN IF NOT EXISTS; rely on the migration journal to
-- run this once.
ALTER TABLE `addresses` ADD COLUMN `bound_id` integer REFERENCES `region_bounds`(`id`);
--> statement-breakpoint
UPDATE `addresses` SET `bound_id` = 1 WHERE `bound_id` IS NULL;

View file

@ -54,22 +54,8 @@
{
"idx": 7,
"version": "6",
"when": 1791368000000,
"tag": "0007_region_columns_backfill",
"breakpoints": true
},
{
"idx": 8,
"version": "6",
"when": 1791374400000,
"tag": "0008_region_cache_versions",
"breakpoints": true
},
{
"idx": 9,
"version": "6",
"when": 1792000000000,
"tag": "0009_three_const_tables",
"when": 1792010000000,
"tag": "0007_addresses_bound_id",
"breakpoints": true
}
]

View file

@ -410,4 +410,5 @@ export {
upsertRegionConstants,
getEffectiveBoundId,
getEffectiveRegionSettings,
getRegionSettingsForBound,
} from './src/superadmin-apis/regions'

View file

@ -106,6 +106,7 @@ export const userCreds = sqliteTable('user_creds', {
export const addresses = sqliteTable('addresses', {
id: integer().primaryKey({ autoIncrement: true }),
regionId: integer('region_id').references(() => regions.id),
boundId: integer('bound_id').references(() => regionBounds.id),
userId: integer('user_id').notNull().references(() => users.id),
name: text('name').notNull(),
phone: text('phone').notNull(),

View file

@ -1,6 +1,6 @@
import { db } from '../db/db_index'
import { regions, regionBounds, regionConsts, regionBoundConsts } from '../db/schema'
import { eq, sql } from 'drizzle-orm'
import { eq, sql, and } from 'drizzle-orm'
import { BOUND_CONST_KEYS, CONST_DEFAULTS, REGION_CONST_KEYS } from '../lib/const-keys'
import type {
RegionSummary,
@ -312,3 +312,28 @@ export async function getEffectiveRegionSettings(regionId: number): Promise<Effe
settings: { ...regionValues, ...boundValues },
}
}
/**
* Region + a SPECIFIC bound's settings (bound wins over region). Used at checkout
* to apply the delivery address's bound instead of the region's effective bound.
* Returns null when the bound does not belong to the region.
*/
export async function getRegionSettingsForBound(
regionId: number,
boundId: number
): Promise<EffectiveRegionSettings | null> {
const bound = await db.query.regionBounds.findFirst({
where: and(eq(regionBounds.id, boundId), eq(regionBounds.regionId, regionId)),
})
if (!bound) return null
const [regionValues, boundValues] = await Promise.all([
getRegionConstants(regionId),
getBoundSettings(boundId),
])
return {
regionId,
boundId,
priority: bound.priority ?? '',
settings: { ...regionValues, ...boundValues },
}
}

View file

@ -10,6 +10,7 @@ const mapUserAddress = (address: AddressRow): UserAddress => ({
id: address.id,
userId: address.userId,
regionId: address.regionId ?? null,
boundId: address.boundId ?? null,
name: address.name,
phone: address.phone,
addressLine1: address.addressLine1,
@ -59,6 +60,7 @@ export async function clearDefaultAddress(userId: number): Promise<void> {
export async function createUserAddress(input: {
userId: number
regionId: number
boundId?: number | null
name: string
phone: string
addressLine1: string
@ -74,6 +76,7 @@ export async function createUserAddress(input: {
const [newAddress] = await db.insert(addresses).values({
userId: input.userId,
regionId: input.regionId,
boundId: input.boundId ?? null,
name: input.name,
phone: input.phone,
addressLine1: input.addressLine1,
@ -94,6 +97,7 @@ export async function updateUserAddress(input: {
userId: number
addressId: number
regionId: number
boundId?: number | null
name: string
phone: string
addressLine1: string
@ -109,6 +113,7 @@ export async function updateUserAddress(input: {
const [updatedAddress] = await db.update(addresses)
.set({
regionId: input.regionId,
...(input.boundId !== undefined ? { boundId: input.boundId } : {}),
name: input.name,
phone: input.phone,
addressLine1: input.addressLine1,

View file

@ -41,6 +41,8 @@ export interface UserAddress {
id: number;
userId: number;
regionId: number | null;
/** The bound this address belongs to. Drives the active bound at checkout. */
boundId: number | null;
name: string;
phone: string;
addressLine1: string;