From 92bf4e8b441a5b8ba23711771ced5b5cb28b2af9 Mon Sep 17 00:00:00 2001 From: shafi54 <108669266+shafi-aviz@users.noreply.github.com> Date: Fri, 9 Oct 2026 00:58:12 +0530 Subject: [PATCH] enh --- apps/backend/creds/demo.txt | 8 +- .../apis/common-apis/common-trpc-index.ts | 24 ++++ .../src/trpc/apis/user-apis/apis/address.ts | 12 +- .../src/trpc/apis/user-apis/apis/order.ts | 40 +++--- .../app/(drawer)/(tabs)/me/_layout.tsx | 25 +++- .../components/CheckoutAddressDisplay.tsx | 76 ++++++++++++ .../components/CheckoutAddressSelector.tsx | 2 +- .../components/LocationTestWrapper.tsx | 7 +- apps/user-ui/components/LoginWall.tsx | 65 ++++++++++ .../components/PaymentAndOrderComponent.tsx | 3 +- .../QuickDeliveryAddressSelector.tsx | 2 +- apps/user-ui/components/cart-page.tsx | 35 +++++- apps/user-ui/components/checkout-page.tsx | 30 +---- apps/user-ui/src/components/AddressForm.tsx | 3 +- .../src/components/LocationAttacher.tsx | 1 + .../user-ui/src/components/RegionSelector.tsx | 3 +- apps/user-ui/src/contexts/AuthContext.tsx | 19 +-- apps/user-ui/src/hooks/prominent-api-hooks.ts | 21 +++- apps/user-ui/src/hooks/useRegion.ts | 45 ++++--- apps/user-ui/src/store/locationStore.ts | 9 +- change-log.txt | 117 ++++++++++++++++++ .../drizzle/0007_addresses_bound_id.sql | 11 ++ .../drizzle/meta/_journal.json | 18 +-- packages/db_helper_sqlite/index.ts | 1 + packages/db_helper_sqlite/src/db/schema.ts | 1 + .../src/superadmin-apis/regions.ts | 27 +++- .../db_helper_sqlite/src/user-apis/address.ts | 5 + packages/shared/types/user.ts | 2 + 28 files changed, 498 insertions(+), 114 deletions(-) create mode 100644 apps/user-ui/components/CheckoutAddressDisplay.tsx create mode 100644 apps/user-ui/components/LoginWall.tsx create mode 100644 packages/db_helper_sqlite/drizzle/0007_addresses_bound_id.sql diff --git a/apps/backend/creds/demo.txt b/apps/backend/creds/demo.txt index a8d45b4..f6dc342 100644 --- a/apps/backend/creds/demo.txt +++ b/apps/backend/creds/demo.txt @@ -57,4 +57,10 @@ minRegularOrderValue freeDeliveryThreshold deliveryCharge flashFreeDeliveryThreshold -flashDeliveryCharge \ No newline at end of file +flashDeliveryCharge + + + + +ss gutta 16.748783, 78.004532 +appally 16.759780, 78.054594 \ No newline at end of file diff --git a/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts b/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts index b59d565..67ff142 100644 --- a/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts +++ b/apps/backend/src/trpc/apis/common-apis/common-trpc-index.ts @@ -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 }) => { diff --git a/apps/backend/src/trpc/apis/user-apis/apis/address.ts b/apps/backend/src/trpc/apis/user-apis/apis/address.ts index 56de68f..5c794e8 100644 --- a/apps/backend/src/trpc/apis/user-apis/apis/address.ts +++ b/apps/backend/src/trpc/apis/user-apis/apis/address.ts @@ -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, diff --git a/apps/backend/src/trpc/apis/user-apis/apis/order.ts b/apps/backend/src/trpc/apis/user-apis/apis/order.ts index 749f1d9..be2b639 100644 --- a/apps/backend/src/trpc/apis/user-apis/apis/order.ts +++ b/apps/backend/src/trpc/apis/user-apis/apis/order.ts @@ -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, diff --git a/apps/user-ui/app/(drawer)/(tabs)/me/_layout.tsx b/apps/user-ui/app/(drawer)/(tabs)/me/_layout.tsx index fcace8d..6f0341c 100644 --- a/apps/user-ui/app/(drawer)/(tabs)/me/_layout.tsx +++ b/apps/user-ui/app/(drawer)/(tabs)/me/_layout.tsx @@ -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 ( + + Loading... + + ); + } + + // Inline login gate so Back / tab switching still works. + if (!isAuthenticated) { + return ; + } return ( ); -} \ No newline at end of file +} diff --git a/apps/user-ui/components/CheckoutAddressDisplay.tsx b/apps/user-ui/components/CheckoutAddressDisplay.tsx new file mode 100644 index 0000000..ca94482 --- /dev/null +++ b/apps/user-ui/components/CheckoutAddressDisplay.tsx @@ -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 ( + + + + + + Delivery Address + + + {isLoading ? ( + Loading address... + ) : address ? ( + + + + {address.name} + + + {address.addressLine1} + {address.addressLine2 ? `, ${address.addressLine2}` : ''} + + + {address.city}, {address.state} - {address.pincode} + + Phone: {address.phone} + + ) : ( + + + No address selected + + )} + + ) +} + +export default CheckoutAddressDisplay diff --git a/apps/user-ui/components/CheckoutAddressSelector.tsx b/apps/user-ui/components/CheckoutAddressSelector.tsx index 06366ec..14e3983 100644 --- a/apps/user-ui/components/CheckoutAddressSelector.tsx +++ b/apps/user-ui/components/CheckoutAddressSelector.tsx @@ -113,7 +113,7 @@ const CheckoutAddressSelector: React.FC = ({ style: 'destructive', onPress: () => { void (async () => { - await confirmRegionSwitch(targetRegion, queryClient); + await confirmRegionSwitch(targetRegion, queryClient, address.boundId ?? targetRegion.effectiveBoundId ?? null); router.replace('/(drawer)/(tabs)/home'); })(); }, diff --git a/apps/user-ui/components/LocationTestWrapper.tsx b/apps/user-ui/components/LocationTestWrapper.tsx index b93e63e..19e4353 100644 --- a/apps/user-ui/components/LocationTestWrapper.tsx +++ b/apps/user-ui/components/LocationTestWrapper.tsx @@ -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 }) => ( @@ -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 = ({ children }) => { const { @@ -55,7 +54,7 @@ const LocationTestWrapper: React.FC = ({ children }) => { } // Still deriving the region from device location. - if (!isEmulator() && isResolvingRegion) { + if (isResolvingRegion) { return } diff --git a/apps/user-ui/components/LoginWall.tsx b/apps/user-ui/components/LoginWall.tsx new file mode 100644 index 0000000..f6d33fb --- /dev/null +++ b/apps/user-ui/components/LoginWall.tsx @@ -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 = ({ + 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 ( + + + + + {title} + {message} + + Log In + + {onBack && ( + + Go Back + + )} + + ) +} + +export default LoginWall diff --git a/apps/user-ui/components/PaymentAndOrderComponent.tsx b/apps/user-ui/components/PaymentAndOrderComponent.tsx index 7d5adec..ca8e659 100644 --- a/apps/user-ui/components/PaymentAndOrderComponent.tsx +++ b/apps/user-ui/components/PaymentAndOrderComponent.tsx @@ -61,7 +61,7 @@ const PaymentAndOrderComponent: React.FC = ({ const products = useCentralProductStore((state) => state.products); const productsById = useCentralProductStore((state) => state.productsById); const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); - const { regionId: selectedRegionId } = useRegion(); + const { regionId: selectedRegionId, boundId: activeBoundId } = useRegion(); // Memoized flash-eligible product IDs const flashEligibleProductIds = useMemo(() => { @@ -169,6 +169,7 @@ const PaymentAndOrderComponent: React.FC = ({ }), addressId: selectedAddress, regionId: selectedRegionId, + boundId: constsData?.boundId ?? activeBoundId ?? undefined, paymentMethod: paymentMethod, couponId: selectedCouponId || undefined, userNotes: userNotes, diff --git a/apps/user-ui/components/QuickDeliveryAddressSelector.tsx b/apps/user-ui/components/QuickDeliveryAddressSelector.tsx index c757fe5..682022b 100644 --- a/apps/user-ui/components/QuickDeliveryAddressSelector.tsx +++ b/apps/user-ui/components/QuickDeliveryAddressSelector.tsx @@ -72,7 +72,7 @@ const QuickDeliveryAddressSelector: React.FC style: 'destructive', onPress: () => { void (async () => { - await confirmRegionSwitch(targetRegion, queryClient); + await confirmRegionSwitch(targetRegion, queryClient, foreignAddress.boundId ?? targetRegion.effectiveBoundId ?? null); router.replace('/(drawer)/(tabs)/home'); })(); }, diff --git a/apps/user-ui/components/cart-page.tsx b/apps/user-ui/components/cart-page.tsx index 5842a9e..90fbd9d 100644 --- a/apps/user-ui/components/cart-page.tsx +++ b/apps/user-ui/components/cart-page.tsx @@ -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>({}); 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 ( + + Loading... + + ); + } + + if (!isAuthenticated) { + return ( + router.back()} + /> + ); + } + if (isLoading || (isSlotsLoading && !isFlashDelivery)) { return ( @@ -954,11 +978,16 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps ); })} + + )} - {/* Cart Type Switcher */} - {cartItems.length > 0 && ( + {/* Cart Type Switcher (hidden) */} + {false && cartItems.length > 0 && ( {/* First row: Text content */} diff --git a/apps/user-ui/components/checkout-page.tsx b/apps/user-ui/components/checkout-page.tsx index 7449461..90f483e 100644 --- a/apps/user-ui/components/checkout-page.tsx +++ b/apps/user-ui/components/checkout-page.tsx @@ -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 = ({ isFlashDelivery = false }) => { const params = useLocalSearchParams(); - const queryClient = useQueryClient(); const router = useRouter(); const { isAuthenticated } = useAuth(); @@ -49,8 +46,7 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) refetchSlots(); }); - const { selectedAddressId, setSelectedAddressId } = useAddressStore(); - const [showAddAddress, setShowAddAddress] = useState(false); + const { selectedAddressId } = useAddressStore(); const [selectedCouponId, setSelectedCouponId] = useState(null); @@ -261,10 +257,7 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) contentContainerStyle={tw`p-4 pb-32`} showsVerticalScrollIndicator={false} > - + = ({ isFlashDelivery = false }) /> - - - setShowAddAddress(false)}> - { - setShowAddAddress(false); - // Auto-select the newly added address - if (addressId) { - setSelectedAddressId(addressId); - } - queryClient.invalidateQueries(); - }} - /> - - ); }; diff --git a/apps/user-ui/src/components/AddressForm.tsx b/apps/user-ui/src/components/AddressForm.tsx index 63bb7ab..de99058 100644 --- a/apps/user-ui/src/components/AddressForm.tsx +++ b/apps/user-ui/src/components/AddressForm.tsx @@ -22,7 +22,7 @@ const AddressForm: React.FC = ({ 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 = ({ onSuccess, initialValues, isE const payload = { ...values, regionId: values.regionId, + boundId: browsingBoundId ?? undefined, latitude: currentLocation?.latitude, longitude: currentLocation?.longitude, googleMapsUrl: values.googleMapsUrl || undefined, diff --git a/apps/user-ui/src/components/LocationAttacher.tsx b/apps/user-ui/src/components/LocationAttacher.tsx index e6662a1..5ca66d7 100644 --- a/apps/user-ui/src/components/LocationAttacher.tsx +++ b/apps/user-ui/src/components/LocationAttacher.tsx @@ -68,6 +68,7 @@ export const LocationAttacher: React.FC = ({ }); const { latitude, longitude } = location.coords; + console.log({location}) const newLocation = { latitude, longitude }; setCurrentLocation(newLocation); setLocationSuccess(true); diff --git a/apps/user-ui/src/components/RegionSelector.tsx b/apps/user-ui/src/components/RegionSelector.tsx index 66b1aeb..a309d97 100644 --- a/apps/user-ui/src/components/RegionSelector.tsx +++ b/apps/user-ui/src/components/RegionSelector.tsx @@ -33,7 +33,8 @@ const RegionSelector: React.FC = ({ 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) diff --git a/apps/user-ui/src/contexts/AuthContext.tsx b/apps/user-ui/src/contexts/AuthContext.tsx index b3bcddc..7f230ba 100644 --- a/apps/user-ui/src/contexts/AuthContext.tsx +++ b/apps/user-ui/src/contexts/AuthContext.tsx @@ -129,8 +129,7 @@ export const AuthProvider: React.FC = ({ 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 = ({ 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) { diff --git a/apps/user-ui/src/hooks/prominent-api-hooks.ts b/apps/user-ui/src/hooks/prominent-api-hooks.ts index 58491bc..f844733 100644 --- a/apps/user-ui/src/hooks/prominent-api-hooks.ts +++ b/apps/user-ui/src/hooks/prominent-api-hooks.ts @@ -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(undefined) const [isReady, setIsReady] = useState(false) diff --git a/apps/user-ui/src/hooks/useRegion.ts b/apps/user-ui/src/hooks/useRegion.ts index e4afc3a..ab91ab2 100644 --- a/apps/user-ui/src/hooks/useRegion.ts +++ b/apps/user-ui/src/hooks/useRegion.ts @@ -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, diff --git a/apps/user-ui/src/store/locationStore.ts b/apps/user-ui/src/store/locationStore.ts index e7b8b0f..20ff3b3 100644 --- a/apps/user-ui/src/store/locationStore.ts +++ b/apps/user-ui/src/store/locationStore.ts @@ -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((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 diff --git a/change-log.txt b/change-log.txt index af71b0e..e2a5f62 100644 --- a/change-log.txt +++ b/change-log.txt @@ -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 ; me/_layout renders 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. diff --git a/packages/db_helper_sqlite/drizzle/0007_addresses_bound_id.sql b/packages/db_helper_sqlite/drizzle/0007_addresses_bound_id.sql new file mode 100644 index 0000000..9a1dfd2 --- /dev/null +++ b/packages/db_helper_sqlite/drizzle/0007_addresses_bound_id.sql @@ -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; diff --git a/packages/db_helper_sqlite/drizzle/meta/_journal.json b/packages/db_helper_sqlite/drizzle/meta/_journal.json index 9b894c6..41b53c5 100644 --- a/packages/db_helper_sqlite/drizzle/meta/_journal.json +++ b/packages/db_helper_sqlite/drizzle/meta/_journal.json @@ -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 } ] diff --git a/packages/db_helper_sqlite/index.ts b/packages/db_helper_sqlite/index.ts index f1bf075..34dba28 100644 --- a/packages/db_helper_sqlite/index.ts +++ b/packages/db_helper_sqlite/index.ts @@ -410,4 +410,5 @@ export { upsertRegionConstants, getEffectiveBoundId, getEffectiveRegionSettings, + getRegionSettingsForBound, } from './src/superadmin-apis/regions' diff --git a/packages/db_helper_sqlite/src/db/schema.ts b/packages/db_helper_sqlite/src/db/schema.ts index f7ee2e6..3e13448 100644 --- a/packages/db_helper_sqlite/src/db/schema.ts +++ b/packages/db_helper_sqlite/src/db/schema.ts @@ -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(), diff --git a/packages/db_helper_sqlite/src/superadmin-apis/regions.ts b/packages/db_helper_sqlite/src/superadmin-apis/regions.ts index 3fc4095..f57ffc0 100644 --- a/packages/db_helper_sqlite/src/superadmin-apis/regions.ts +++ b/packages/db_helper_sqlite/src/superadmin-apis/regions.ts @@ -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 { + 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 }, + } +} diff --git a/packages/db_helper_sqlite/src/user-apis/address.ts b/packages/db_helper_sqlite/src/user-apis/address.ts index 64c16d9..490d88d 100644 --- a/packages/db_helper_sqlite/src/user-apis/address.ts +++ b/packages/db_helper_sqlite/src/user-apis/address.ts @@ -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 { 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, diff --git a/packages/shared/types/user.ts b/packages/shared/types/user.ts index fb35b86..caf1683 100644 --- a/packages/shared/types/user.ts +++ b/packages/shared/types/user.ts @@ -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;