diff --git a/apps/admin-ui/app/(drawer)/dashboard/manage-orders/order-details/[id].tsx b/apps/admin-ui/app/(drawer)/dashboard/manage-orders/order-details/[id].tsx index 03a693a..67d766b 100644 --- a/apps/admin-ui/app/(drawer)/dashboard/manage-orders/order-details/[id].tsx +++ b/apps/admin-ui/app/(drawer)/dashboard/manage-orders/order-details/[id].tsx @@ -435,7 +435,7 @@ export default function OrderDetails() { {order.address.name} {' '} {order.address.line1} {order.address.line2 ? `, ${order.address.line2}` : ""} - {`\n${order.address.city}, ${order.address.state} - ${order.address.pincode}`} + {`\n${order.address.city}, ${order.address.state}`} diff --git a/apps/admin-ui/tests/screens/order-details.test.tsx b/apps/admin-ui/tests/screens/order-details.test.tsx index f355803..dc67889 100644 --- a/apps/admin-ui/tests/screens/order-details.test.tsx +++ b/apps/admin-ui/tests/screens/order-details.test.tsx @@ -35,7 +35,6 @@ const makeDetails = (overrides: Record = {}) => ({ line2: null, city: 'City', state: 'State', - pincode: '500001', phone: '9876543210', }, slotInfo: { time: '2026-01-02T10:00:00.000Z', sequence: null }, diff --git a/apps/admin-web/src/routes/dashboard.orders.$id.tsx b/apps/admin-web/src/routes/dashboard.orders.$id.tsx index 2f02e01..7aa3a26 100644 --- a/apps/admin-web/src/routes/dashboard.orders.$id.tsx +++ b/apps/admin-web/src/routes/dashboard.orders.$id.tsx @@ -404,7 +404,7 @@ function OrderDetails() { {order.address.name} {' '} {order.address.line1} {order.address.line2 ? `, ${order.address.line2}` : ''} - {`\n${order.address.city}, ${order.address.state} - ${order.address.pincode}`} + {`\n${order.address.city}, ${order.address.state}`} diff --git a/apps/backend/src/lib/post-order-handler.ts b/apps/backend/src/lib/post-order-handler.ts index 439818a..adddd60 100644 --- a/apps/backend/src/lib/post-order-handler.ts +++ b/apps/backend/src/lib/post-order-handler.ts @@ -69,7 +69,7 @@ const formatOrderMessageWithFullData = (ordersData: any[]): string => { if (order.address?.addressLine2) { message += ` ${order.address.addressLine2}\n`; } - message += ` ${order.address?.city || ''}, ${order.address?.state || ''} - ${order.address?.pincode || ''}\n`; + message += ` ${order.address?.city || ''}, ${order.address?.state || ''}\n`; if (order.address?.phone) { message += ` πŸ“ž ${order.address.phone}\n`; } 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 0bc3a08..5fb7eb4 100644 --- a/apps/backend/src/trpc/apis/user-apis/apis/address.ts +++ b/apps/backend/src/trpc/apis/user-apis/apis/address.ts @@ -20,9 +20,8 @@ import type { UserAddressDeleteResponse, } from '@packages/shared' -// Indian mobile numbers: exactly 10 digits starting 6-9. Pincode: exactly 6 digits. +// Indian mobile numbers: exactly 10 digits starting 6-9. const PHONE_REGEX = /^[6-9]\d{9}$/ -const PINCODE_REGEX = /^\d{6}$/ export const addressRouter = router({ getDefaultAddress: protectedProcedure @@ -52,8 +51,6 @@ export const addressRouter = router({ addressLine2: z.string().optional(), city: z.string().min(1, 'City is required'), state: z.string().min(1, 'State is required'), - pincode: z.string().trim().min(1, 'Pincode is required') - .regex(PINCODE_REGEX, 'Pincode must be 6 digits'), isDefault: z.boolean().optional(), // Coordinates picked on the map. The user app always sends them; the web // app may omit them (legacy), in which case the bound falls back to the @@ -64,7 +61,7 @@ export const addressRouter = router({ })) .mutation(async ({ input, ctx }): Promise => { const userId = ctx.user.userId; - const { name, phone, addressLine1, addressLine2, city, state, pincode, isDefault, googleMapsUrl } = input; + const { name, phone, addressLine1, addressLine2, city, state, isDefault, googleMapsUrl } = input; let { latitude, longitude } = input; @@ -88,7 +85,7 @@ export const addressRouter = router({ } // Validate required fields - if (!name || !phone || !addressLine1 || !city || !state || !pincode) { + if (!name || !phone || !addressLine1 || !city || !state) { throw new Error('Missing required fields'); } @@ -111,7 +108,6 @@ export const addressRouter = router({ addressLine2, city, state, - pincode, isDefault: makeDefault, latitude, longitude, @@ -132,8 +128,6 @@ export const addressRouter = router({ addressLine2: z.string().optional(), city: z.string().min(1, 'City is required'), state: z.string().min(1, 'State is required'), - pincode: z.string().trim().min(1, 'Pincode is required') - .regex(PINCODE_REGEX, 'Pincode must be 6 digits'), isDefault: z.boolean().optional(), // See createAddress: coordinates are optional for the legacy web client. latitude: z.number().min(-90).max(90).optional(), @@ -142,7 +136,7 @@ export const addressRouter = router({ })) .mutation(async ({ input, ctx }): Promise => { const userId = ctx.user.userId; - const { id, name, phone, addressLine1, addressLine2, city, state, pincode, isDefault, googleMapsUrl } = input; + const { id, name, phone, addressLine1, addressLine2, city, state, isDefault, googleMapsUrl } = input; let { latitude, longitude } = input; @@ -194,7 +188,6 @@ export const addressRouter = router({ addressLine2, city, state, - pincode, // An omitted isDefault means "leave it as it is": only an explicit value may change it. isDefault: isDefault ?? existingAddress.isDefault, googleMapsUrl, diff --git a/apps/backend/tests/api/misc-procedures.test.ts b/apps/backend/tests/api/misc-procedures.test.ts index 00f2ae2..fe21404 100644 --- a/apps/backend/tests/api/misc-procedures.test.ts +++ b/apps/backend/tests/api/misc-procedures.test.ts @@ -20,7 +20,6 @@ const addressBody = (over: Record = {}) => ({ addressLine1: '1 API Street', city: 'Mahabubnagar', state: 'Telangana', - pincode: '509001', isDefault: false, ...over, }) diff --git a/apps/backend/tests/helpers/fixtures.ts b/apps/backend/tests/helpers/fixtures.ts index d41695f..72f85dd 100644 --- a/apps/backend/tests/helpers/fixtures.ts +++ b/apps/backend/tests/helpers/fixtures.ts @@ -156,7 +156,6 @@ export async function ensureUserAddress(): Promise<{ addressId: number; created: addressLine1: '1 API Test Street', city: 'Mahabubnagar', state: 'Telangana', - pincode: '509001', isDefault: true, }) @@ -190,7 +189,6 @@ export async function registerUserWithAddress(): Promise<{ addressLine1: '1 API Test Street', city: 'Mahabubnagar', state: 'Telangana', - pincode: '509001', isDefault: true, }) diff --git a/apps/fallback-ui/src/routes/order-details.tsx b/apps/fallback-ui/src/routes/order-details.tsx index 686024f..eaf9bb5 100644 --- a/apps/fallback-ui/src/routes/order-details.tsx +++ b/apps/fallback-ui/src/routes/order-details.tsx @@ -139,7 +139,7 @@ export function OrderDetailsRoute() {

{order.address?.name} {order.address?.line1} {order.address?.line2 ? `, ${order.address.line2}` : ""} - {`\n${order.address?.city}, ${order.address?.state} - ${order.address?.pincode}`} + {`\n${order.address?.city}, ${order.address?.state}`}

diff --git a/apps/user-ui/app/(drawer)/(tabs)/me/addresses/index.tsx b/apps/user-ui/app/(drawer)/(tabs)/me/addresses/index.tsx index 43c3103..b48923b 100644 --- a/apps/user-ui/app/(drawer)/(tabs)/me/addresses/index.tsx +++ b/apps/user-ui/app/(drawer)/(tabs)/me/addresses/index.tsx @@ -10,7 +10,7 @@ import AddressForm from '@/src/components/AddressForm'; // Address view β€” required core of the shared UserAddress + optional geo fields type Address = Pick< UserAddress, - 'id' | 'regionId' | 'name' | 'phone' | 'addressLine1' | 'addressLine2' | 'city' | 'state' | 'pincode' | 'isDefault' + 'id' | 'regionId' | 'name' | 'phone' | 'addressLine1' | 'addressLine2' | 'city' | 'state' | 'isDefault' > & { latitude?: number | null longitude?: number | null @@ -25,7 +25,7 @@ function AddressCard({ address, onEdit, onDelete, onSetDefault, isDeleting }: { isDeleting?: boolean; }) { const formatAddress = (addr: Address) => { - return `${addr.addressLine1}${addr.addressLine2 ? `, ${addr.addressLine2}` : ''}, ${addr.city}, ${addr.state} - ${addr.pincode}`; + return `${addr.addressLine1}${addr.addressLine2 ? `, ${addr.addressLine2}` : ''}, ${addr.city}, ${addr.state}`; }; return ( @@ -159,7 +159,6 @@ export default function Addresses() { addressLine2: addressToUpdate.addressLine2 || undefined, city: addressToUpdate.city, state: addressToUpdate.state, - pincode: addressToUpdate.pincode, isDefault: true, // Keep the stored coordinates so the bound is not re-derived from a fallback. latitude: addressToUpdate.latitude ?? undefined, @@ -272,7 +271,6 @@ export default function Addresses() { addressLine2: editingAddress.addressLine2 || '', city: editingAddress.city, state: editingAddress.state, - pincode: editingAddress.pincode, isDefault: editingAddress.isDefault, latitude: editingAddress.googleMapsUrl ? undefined : (editingAddress.latitude ?? undefined), longitude: editingAddress.googleMapsUrl ? undefined : (editingAddress.longitude ?? undefined), diff --git a/apps/user-ui/components/CartAddressGate.tsx b/apps/user-ui/components/CartAddressGate.tsx new file mode 100644 index 0000000..bb181e4 --- /dev/null +++ b/apps/user-ui/components/CartAddressGate.tsx @@ -0,0 +1,112 @@ +import React, { useState } from 'react' +import { View, Modal } from 'react-native' +import MaterialIcons from '@expo/vector-icons/MaterialIcons' +import { tw, theme, MyText, MyTouchableOpacity } from 'common-ui' +import AddressForm from '@/src/components/AddressForm' +import { useLocationStore } from '@/src/store/locationStore' + +interface CartAddressGateProps { + /** Called once the first address has been saved. */ + onDone: () => void + /** Back out of the cart. */ + onBack: () => void +} + +/** + * Shown on the cart page when the browsing region/bound is known (from the + * device location) but the signed-in user has no delivery address yet. The + * first address they save becomes their default, and we then show the cart. + */ +const CartAddressGate: React.FC = ({ onDone, onBack }) => { + const coords = useLocationStore((state) => state.coords) + const [mode, setMode] = useState<'none' | 'current' | 'other'>('none') + + return ( + + + + + + + Add Delivery Address + + + + + Where should we deliver? + + You don’t have a delivery address yet. Add one to continue. + + + setMode('current')} + style={tw`bg-white border border-gray-200 rounded-2xl p-4 mb-3 shadow-sm ${!coords ? 'opacity-50' : ''}`} + > + + + + Address of current Location + + + + {coords + ? `Use your current location (${coords.latitude.toFixed(5)}, ${coords.longitude.toFixed(5)})` + : 'Turn on location to use this option'} + + + + setMode('other')} + style={tw`bg-white border border-gray-200 rounded-2xl p-4 shadow-sm`} + > + + + + Choose another location + + + Pick a point on the map + + + + setMode('none')} + > + + { + setMode('none') + onDone() + }} + /> + + + + ) +} + +export default CartAddressGate diff --git a/apps/user-ui/components/CheckoutAddressDisplay.tsx b/apps/user-ui/components/CheckoutAddressDisplay.tsx index ca94482..878644a 100644 --- a/apps/user-ui/components/CheckoutAddressDisplay.tsx +++ b/apps/user-ui/components/CheckoutAddressDisplay.tsx @@ -57,7 +57,7 @@ const CheckoutAddressDisplay: React.FC = () => { {address.addressLine2 ? `, ${address.addressLine2}` : ''} - {address.city}, {address.state} - {address.pincode} + {address.city}, {address.state} Phone: {address.phone} diff --git a/apps/user-ui/components/CheckoutAddressSelector.tsx b/apps/user-ui/components/CheckoutAddressSelector.tsx index ec3975c..d8451c1 100644 --- a/apps/user-ui/components/CheckoutAddressSelector.tsx +++ b/apps/user-ui/components/CheckoutAddressSelector.tsx @@ -155,7 +155,6 @@ const CheckoutAddressSelector: React.FC = ({ addressLine2: address.addressLine2 || '', city: address.city, state: address.state, - pincode: address.pincode, isDefault: address.isDefault, latitude, longitude, @@ -235,7 +234,7 @@ const CheckoutAddressSelector: React.FC = ({ {address.addressLine1}{address.addressLine2 ? `, ${address.addressLine2}` : ''} - {address.city}, {address.state} - {address.pincode} + {address.city}, {address.state} Phone: {address.phone} diff --git a/apps/user-ui/components/LocationTestWrapper.tsx b/apps/user-ui/components/LocationTestWrapper.tsx index d1a2bfe..75f87e3 100644 --- a/apps/user-ui/components/LocationTestWrapper.tsx +++ b/apps/user-ui/components/LocationTestWrapper.tsx @@ -1,5 +1,5 @@ import React, { useEffect } from 'react' -import { ActivityIndicator, View } from 'react-native' +import { ActivityIndicator, Linking, Platform, View } from 'react-native' import { MyText, theme, tw } from 'common-ui' import type { ReactParentComponent } from '@packages/shared' import { trpc } from '../src/trpc-client' @@ -16,11 +16,12 @@ const LoadingScreen: React.FC<{ label?: string }> = ({ label }) => ( /** * Region gate + location fallback. * - * 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, or coordinates outside every region bound β€” the user is - * asked to choose a region manually. + * The browsing region is derived from the device location (see `useRegion`), + * anchored on the user's default address: when the location resolves to the + * default's region (or to no serviceable region) we use the default; only a + * different serviceable region makes us ask. While that decision is in flight we + * show a spinner; once a region exists the app renders, otherwise the user is + * asked to choose an address. */ const LocationTestWrapper: React.FC = ({ children }) => { const { @@ -28,10 +29,46 @@ const LocationTestWrapper: React.FC = ({ children }) => { clearRegion, hydrated, isResolvingRegion, + locationStatus, } = useRegion() const { data: regions } = trpc.common.listRegions.useQuery() + // Tell the user *why* the location isn't usable before asking for an address. + const locationNotice = (() => { + switch (locationStatus) { + case 'denied': + return 'Location access is not granted. Allow location access for accurate delivery, or add a delivery address below.' + case 'services-off': + return 'Your device location is turned off. Turn it on, or add a delivery address below.' + case 'unavailable': + case 'error': + return 'We could not get your location. Please try again, or add a delivery address below.' + default: + return undefined + } + })() + + // Deep-link to the OS location settings when the app can't fix it itself + // (location services off, or permission denied β€” iOS won't re-prompt). + const openLocationSettings = () => { + void (async () => { + try { + if (Platform.OS === 'android') { + await Linking.sendIntent('android.settings.LOCATION_SOURCE_SETTINGS') + } else { + await Linking.openSettings() + } + } catch { + try { + await Linking.openSettings() + } catch { + // Give up silently β€” the notice still explains the situation. + } + } + })() + } + // Validate the saved region against the live list. A stale/unknown id must // lead to selection, never a silent checkout fallback. Membership-only: no // setRegion here, so this effect can never re-trigger itself. @@ -53,15 +90,22 @@ const LocationTestWrapper: React.FC = ({ children }) => { return } - // Still deriving the region from device location. + // Still deriving the region from device location / the default address. if (isResolvingRegion) { return } - // Location unavailable / denied / out of area -> pick an address or add one. + // No region resolved -> pick an address or add one. return ( - + ) } diff --git a/apps/user-ui/components/QuickDeliveryAddressSelector.tsx b/apps/user-ui/components/QuickDeliveryAddressSelector.tsx index 682022b..8b3ec11 100644 --- a/apps/user-ui/components/QuickDeliveryAddressSelector.tsx +++ b/apps/user-ui/components/QuickDeliveryAddressSelector.tsx @@ -107,7 +107,7 @@ const QuickDeliveryAddressSelector: React.FC const addressOptions = addresses.map(address => ({ id: address.id, name: address.name, - address: `${address.addressLine1}${address.addressLine2 ? `, ${address.addressLine2}` : ''}, ${address.city}, ${address.state} - ${address.pincode}`, + address: `${address.addressLine1}${address.addressLine2 ? `, ${address.addressLine2}` : ''}, ${address.city}, ${address.state}`, phone: address.phone, })); diff --git a/apps/user-ui/components/cart-page.tsx b/apps/user-ui/components/cart-page.tsx index a738808..ac415de 100644 --- a/apps/user-ui/components/cart-page.tsx +++ b/apps/user-ui/components/cart-page.tsx @@ -32,6 +32,7 @@ import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks'; import { useRegion } from '@/src/hooks/useRegion'; import CheckoutAddressSelector from '@/components/CheckoutAddressSelector'; import LoginWall from '@/components/LoginWall'; +import CartAddressGate from '@/components/CartAddressGate'; import { useAddressStore } from '@/src/store/addressStore'; import { useCheckoutStore } from '@/src/store/checkoutStore'; import type { FlashDeliveryProps } from '@packages/shared'; @@ -190,6 +191,10 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps const { selectedAddressId, setSelectedAddressId } = useAddressStore(); const { regionId } = useRegion(); + // First-address gate: the region can exist (from the location) with no address yet. + const addressesQuery = trpc.user.address.getUserAddresses.useQuery(undefined, { + enabled: isAuthenticated, + }); const userNotes = useCheckoutStore((state) => state.userNotes); const setUserNotes = useCheckoutStore((state) => state.setUserNotes); @@ -643,6 +648,27 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps ); } + // No delivery address yet (but a region exists from the location): ask for the + // first address before showing the cart β€” even when the cart is empty. The + // first saved address becomes the default. + if (addressesQuery.isLoading) { + return ( + + Loading... + + ); + } + if ((addressesQuery.data?.data?.length ?? 0) === 0) { + return ( + { + void addressesQuery.refetch(); + }} + onBack={() => router.back()} + /> + ); + } + return ( {/* Fixed Cart Type Header */} diff --git a/apps/user-ui/src/components/AddressForm.tsx b/apps/user-ui/src/components/AddressForm.tsx index a0e7d30..f6c3b18 100644 --- a/apps/user-ui/src/components/AddressForm.tsx +++ b/apps/user-ui/src/components/AddressForm.tsx @@ -5,10 +5,11 @@ import * as Yup from 'yup'; import { tw, MyText, MyTouchableOpacity , Checkbox , MyTextInput , LoadingDialog } from 'common-ui'; import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import { trpc } from '../trpc-client'; -import LocationAttacher from './LocationAttacher'; import LocationMapStep from './location/LocationMapStep'; import type { AddressFormProps } from '@packages/shared'; import { savePendingAddress } from '@/src/lib/pending-address'; +import { useRegion } from '@/src/hooks/useRegion'; +import { useLocationStore } from '@/src/store/locationStore'; type Coords = { latitude: number; longitude: number }; type ResolvedRegion = { regionId: number; boundId: number | null }; @@ -20,6 +21,8 @@ const AddressForm: React.FC = ({ draftMode = false, onResolvedRegion, }) => { + const { regionId: browsingRegionId, boundId: browsingBoundId } = useRegion(); + const deviceCoords = useLocationStore((state) => state.coords); const [isSubmitting, setIsSubmitting] = useState(false); const [submitError, setSubmitError] = useState(null); const [mapOpen, setMapOpen] = useState(false); @@ -28,12 +31,21 @@ const AddressForm: React.FC = ({ ? { latitude: initialValues.latitude, longitude: initialValues.longitude } : null ); - // Region is never picked directly: it is derived from the coordinates. - const [resolvedRegion, setResolvedRegion] = useState(null); + // The town (region) for this address. Pre-selected from the app's current + // browsing region when one exists; otherwise picked from the City dropdown. + const [resolvedRegion, setResolvedRegion] = useState(() => + browsingRegionId != null ? { regionId: browsingRegionId, boundId: browsingBoundId } : null + ); const [locationError, setLocationError] = useState(null); const utils = trpc.useUtils(); + // Towns (regions) the user can deliver in β€” the City field is a picker over them. + const { data: regionsData } = trpc.common.listRegions.useQuery(); + const regions = regionsData ?? []; + const [cityOpen, setCityOpen] = useState(false); + const cityName = regions.find((region) => region.id === resolvedRegion?.regionId)?.name ?? ''; + // Resolve coordinates -> region + bound. Used for whichever source the user // picks (attach current location or the map). Out-of-area points are refused. const resolveLocation = useCallback( @@ -64,6 +76,33 @@ const AddressForm: React.FC = ({ [utils, onResolvedRegion] ); + // The City field is a picker over the serviceable towns. Changing it re-checks + // that the chosen coordinates fall inside that town. + const handleCityChange = useCallback( + async (regionId: number) => { + if (!currentLocation) { + setResolvedRegion({ regionId, boundId: null }); + setLocationError('Attach or pick a location inside this town.'); + return; + } + setResolvedRegion({ regionId, boundId: null }); + setLocationError(null); + try { + const resolved = await utils.common.resolveBound.fetch({ + regionId, + lat: currentLocation.latitude, + lng: currentLocation.longitude, + }); + const info: ResolvedRegion = { regionId, boundId: resolved.boundId }; + setResolvedRegion(info); + onResolvedRegion?.(info); + } catch { + setLocationError('Your location is outside this town. Pick a point on the map inside it.'); + } + }, + [utils, currentLocation, onResolvedRegion] + ); + // Resolve any prefilled coordinates once (e.g. edit, or coming from the map). useEffect(() => { if (initialValues?.latitude != null && initialValues?.longitude != null) { @@ -72,6 +111,25 @@ const AddressForm: React.FC = ({ // eslint-disable-next-line react-hooks/exhaustive-deps }, []); + // If the app already knows the device location, attach it as the address + // location by default (the user can still choose another on the map). + useEffect(() => { + if (currentLocation != null) return; + if (initialValues?.latitude != null) return; + if (deviceCoords == null) return; + void resolveLocation(deviceCoords); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [deviceCoords]); + + // Pre-select the browsing town once the app knows it (e.g. after the location + // resolves) β€” unless the user already picked a town or attached a location. + useEffect(() => { + if (resolvedRegion != null || currentLocation != null) return; + if (browsingRegionId == null) return; + setResolvedRegion({ regionId: browsingRegionId, boundId: browsingBoundId }); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [browsingRegionId, browsingBoundId]); + const createAddressMutation = trpc.user.address.createAddress.useMutation({ onSuccess: (data) => { setIsSubmitting(false); @@ -103,9 +161,7 @@ const AddressForm: React.FC = ({ .matches(/^[6-9]\d{9}$/, 'Phone must be a 10-digit number starting with 6, 7, 8 or 9'), addressLine1: Yup.string().required('Address Line 1 is required'), addressLine2: Yup.string(), - city: Yup.string().required('City is required'), state: Yup.string().required('State is required'), - pincode: Yup.string().required('Pincode is required').matches(/^\d{6}$/, 'Pincode must be 6 digits'), isDefault: Yup.boolean(), }); @@ -127,7 +183,7 @@ const AddressForm: React.FC = ({ ℹ️ - We currently serve only in Mahabubnagar town + We currently serve only in the towns listed below @@ -144,9 +200,8 @@ const AddressForm: React.FC = ({ phone: '', addressLine1: '', addressLine2: '', - city: 'Mahabubnagar', + city: '', state: 'Telangana', - pincode: '509001', isDefault: false, googleMapsUrl: '', }} @@ -156,14 +211,15 @@ const AddressForm: React.FC = ({ setSubmitError('Please attach your current location or select it on the map.'); return; } - if (!resolvedRegion) { - setSubmitError(locationError || 'Please choose a location inside our delivery area.'); + if (!resolvedRegion || locationError) { + setSubmitError(locationError || 'Please choose a town and a location inside it.'); return; } setIsSubmitting(true); setSubmitError(null); const payload = { ...values, + city: cityName || values.city || '', regionId: resolvedRegion.regionId, latitude: currentLocation.latitude, longitude: currentLocation.longitude, @@ -179,9 +235,8 @@ const AddressForm: React.FC = ({ phone: values.phone, addressLine1: values.addressLine1, addressLine2: values.addressLine2 || undefined, - city: values.city, + city: cityName || values.city || '', state: values.state, - pincode: values.pincode, isDefault: values.isDefault, latitude: currentLocation.latitude, longitude: currentLocation.longitude, @@ -240,15 +295,47 @@ const AddressForm: React.FC = ({ value={values.addressLine2} /> - - {touched.city && errors.city && {errors.city}} + {/* City is a picker over the serviceable towns (regions). */} + + City * + setCityOpen((prev) => !prev)} + style={tw`border border-gray-200 rounded-lg p-3 flex-row items-center justify-between bg-gray-50`} + > + + {cityName || 'Select town'} + + + + {cityOpen && ( + + {regions.map((region) => ( + { + setCityOpen(false); + void handleCityChange(region.id); + }} + style={tw`p-3 border-b border-gray-50 flex-row items-center justify-between`} + > + {region.name} + {resolvedRegion?.regionId === region.id && ( + + )} + + ))} + {regions.length === 0 && ( + No towns available + )} + + )} + = ({ /> {touched.state && errors.state && {errors.state}} - - {touched.pincode && errors.pincode && {errors.pincode}} - - {/* Location is mandatory and drives the region: attach or pick on map. */} + {/* Location is mandatory: attach the device location or pick on the map. */} Delivery Location * - { - if (location) void resolveLocation(location); - }} - disabled={false} - /> - setMapOpen(true)} - style={tw`flex-row items-center mb-1`} - > - - Select on map - - - {currentLocation && ( - - πŸ“ {currentLocation.latitude.toFixed(5)}, {currentLocation.longitude.toFixed(5)} - + {currentLocation ? ( + <> + + + + Current Location Attached + + + + πŸ“ {currentLocation.latitude.toFixed(5)}, {currentLocation.longitude.toFixed(5)} + + setMapOpen(true)} + style={tw`flex-row items-center mt-2`} + > + + + Choose Another Location in Map + + + + ) : ( + setMapOpen(true)} + style={tw`flex-row items-center`} + > + + + Attach Location in map + + )} + {locationError && ( {locationError} )} @@ -311,14 +400,20 @@ const AddressForm: React.FC = ({ handleSubmit()} - disabled={isSubmitting} + disabled={isSubmitting || !currentLocation} > {isSubmitting ? (isEdit ? 'Updating...' : 'Adding...') : (isEdit ? 'Update Address' : 'Add Address')} + + {!currentLocation && touched.name && ( + + Attach a location to add address + + )} )} diff --git a/apps/user-ui/src/components/LocationBar.tsx b/apps/user-ui/src/components/LocationBar.tsx index 7baef2a..97b5c2c 100644 --- a/apps/user-ui/src/components/LocationBar.tsx +++ b/apps/user-ui/src/components/LocationBar.tsx @@ -12,9 +12,8 @@ const formatAddress = (address: { addressLine1: string addressLine2?: string | null city: string - pincode: string }) => - `${address.addressLine1}${address.addressLine2 ? `, ${address.addressLine2}` : ''}, ${address.city} - ${address.pincode}` + `${address.addressLine1}${address.addressLine2 ? `, ${address.addressLine2}` : ''}, ${address.city}` /** * Location bar shown at the top of every top-level tab screen. diff --git a/apps/user-ui/src/components/location/LocationFallbackFlow.tsx b/apps/user-ui/src/components/location/LocationFallbackFlow.tsx index 746698c..700709d 100644 --- a/apps/user-ui/src/components/location/LocationFallbackFlow.tsx +++ b/apps/user-ui/src/components/location/LocationFallbackFlow.tsx @@ -23,13 +23,22 @@ interface ChooserAddress { addressLine2: string | null city: string state: string - pincode: string isDefault: boolean } interface LocationFallbackFlowProps { /** Present when hosted in a sheet; lets the caller dismiss after a choice. */ onClose?: () => void + /** + * Why the location couldn't be used (permission not granted / turned off / + * couldn't get a fix). Shown above the address options. + */ + notice?: string + /** + * When set, the notice also shows a button that deep-links to the OS location + * settings (used when the OS state can't be fixed from inside the app). + */ + onOpenSettings?: () => void } /** @@ -37,7 +46,7 @@ interface LocationFallbackFlowProps { * (which switches the browsing region + bound and clears the cart) or adds a * new one (coordinates required, via attach-location or the map). */ -const LocationFallbackFlow: React.FC = ({ onClose }) => { +const LocationFallbackFlow: React.FC = ({ onClose, notice, onOpenSettings }) => { const queryClient = useQueryClient() const utils = trpc.useUtils() const auth = useAuthOptional() @@ -115,7 +124,6 @@ const LocationFallbackFlow: React.FC = ({ onClose }) addressLine2: address.addressLine2 || undefined, city: address.city, state: address.state, - pincode: address.pincode, isDefault: true, latitude: address.latitude ?? undefined, longitude: address.longitude ?? undefined, @@ -177,6 +185,25 @@ const LocationFallbackFlow: React.FC = ({ onClose }) )} + {notice && ( + + + + {notice} + + {onOpenSettings && ( + + Open location settings + + )} + + )} + {message && ( {message} @@ -207,7 +234,7 @@ const LocationFallbackFlow: React.FC = ({ onClose }) {address.addressLine1} - {address.addressLine2 ? `, ${address.addressLine2}` : ''}, {address.city} - {address.pincode} + {address.addressLine2 ? `, ${address.addressLine2}` : ''}, {address.city} diff --git a/apps/user-ui/src/hooks/useRegion.ts b/apps/user-ui/src/hooks/useRegion.ts index 46570b5..f6205ef 100644 --- a/apps/user-ui/src/hooks/useRegion.ts +++ b/apps/user-ui/src/hooks/useRegion.ts @@ -43,12 +43,12 @@ export interface UseRegionResult { bound: RegionBoundSummary | null /** Monotonic marker bumped on every region change; use it to ignore stale responses. */ regionGeneration: number - /** True once the persisted region has finished loading from storage. */ + /** Always true: the region store is in-memory (not persisted). */ hydrated: boolean /** Latest device coordinates, if the launch fix succeeded. */ coords: { latitude: number; longitude: number } | null /** Current state of the launch location read. */ - locationStatus: 'idle' | 'locating' | 'granted' | 'denied' | 'unavailable' | 'error' + locationStatus: 'idle' | 'locating' | 'granted' | 'denied' | 'services-off' | 'unavailable' | 'error' /** * True while the launch location check is still determining a region AND no * region is known yet. The UI should show a spinner rather than the chooser @@ -65,7 +65,9 @@ export interface UseRegionResult { export function useRegion(): UseRegionResult { const queryClient = useQueryClient() - const isAuthenticated = useAuthOptional()?.isAuthenticated ?? false + const auth = useAuthOptional() + const isAuthenticated = auth?.isAuthenticated ?? false + const isAuthLoading = auth?.isLoading ?? false const region = useRegionStore((state) => state.selectedRegion) const regionId = useRegionStore((state) => state.selectedRegionId) @@ -79,19 +81,26 @@ export function useRegion(): UseRegionResult { const startTracking = useLocationStore((state) => state.start) const refreshTracking = useLocationStore((state) => state.refresh) - const [hydrated, setHydrated] = useState(() => - useRegionStore.persist.hasHydrated() - ) + // The region store is in-memory (not persisted), so there is nothing to + // hydrate before we can decide. + const hydrated = true // True once the launch location check has a definitive outcome. const [startupResolved, setStartupResolved] = useState(false) - useEffect(() => { - if (useRegionStore.persist.hasHydrated()) { - setHydrated(true) - return - } - return useRegionStore.persist.onFinishHydration(() => setHydrated(true)) - }, []) + // The user's default address β€” the anchor for the startup region decision. + const defaultAddressQuery = trpc.user.address.getDefaultAddress.useQuery(undefined, { + enabled: hydrated && isAuthenticated, + staleTime: 60000, + }) + const defaultAddress = defaultAddressQuery.data?.data ?? null + + // Region summaries (needed to build the RegionSummary when adopting a region + // from the default address). + const regionsQuery = trpc.common.listRegions.useQuery(undefined, { + enabled: hydrated, + staleTime: 60000, + }) + const regions = regionsQuery.data ?? 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 @@ -135,18 +144,37 @@ export function useRegion(): UseRegionResult { refetchOnWindowFocus: false, }) - // Apply the launch outcome once: same region -> no-op, different -> switch. + // Apply the launch outcome once. The default address anchors the decision: + // - location resolves to the default's region, or to no serviceable region + // (location off / out of area) -> use the default address; + // - location resolves to a DIFFERENT serviceable region -> let the user pick. + // Without a default address we keep the previous behaviour (use the resolved + // region, else let the user pick). useEffect(() => { if (!hydrated || startupResolved) return + const resolved = resolution.data - const terminal = + const locationSettled = resolved != null || resolution.isFetched || resolution.isError || locationStatus === 'denied' || + locationStatus === 'services-off' || locationStatus === 'unavailable' || locationStatus === 'error' - if (!terminal) return + if (!locationSettled) return + + // Wait for auth to settle so signed-in users can anchor on the default + // address (otherwise we'd settle with isAuthenticated=false and never + // reconsider). + if (isAuthLoading) return + + // Signed-in users: wait for the default address (+ regions) so the decision + // is anchored correctly before we settle. + if (isAuthenticated) { + if (defaultAddressQuery.isLoading) return + if (defaultAddress?.regionId != null && !regions) return + } setStartupResolved(true) @@ -157,13 +185,42 @@ export function useRegion(): UseRegionResult { // Respect a manual pick made before the fix resolved. const userChangedRegion = startupLaunchRegionId !== undefined && startupLaunchRegionId !== regionId - if (resolved?.region && !userChangedRegion) { - if (resolved.region.id !== regionId) { - // New region -> full switch (clears carts, refreshes regional data). + if (userChangedRegion) return + + const defaultRegionId = isAuthenticated ? defaultAddress?.regionId ?? null : null + + if (defaultRegionId != null) { + const inDefaultRegion = resolved?.region?.id === defaultRegionId + // No serviceable region found -> treat like a disabled location. + const noServiceableRegion = resolved == null + if (inDefaultRegion || noServiceableRegion) { + const region = regions?.find((candidate) => candidate.id === defaultRegionId) ?? null + if (region) { + if (regionId == null) { + // First region of this launch β€” adopt it without clearing the cart. + setRegion(region, defaultAddress?.boundId ?? null) + } else if (region.id !== regionId) { + void confirmRegionSwitch(region, queryClient, defaultAddress?.boundId ?? null) + } else if (defaultAddress?.boundId != null && defaultAddress.boundId !== boundId) { + setRegion(region, defaultAddress.boundId) + } + } + return + } + + // Location is in another serviceable region -> ask the user to choose. + if (regionId != null) clearRegion() + return + } + + // No default address: derive the region from the location as before. + if (resolved?.region) { + if (regionId == null) { + // First region of this launch β€” adopt it without clearing the cart. + setRegion(resolved.region, resolved.bound?.id ?? null) + } else if (resolved.region.id !== regionId) { void confirmRegionSwitch(resolved.region, queryClient, resolved.bound?.id ?? null) } else if (resolved.bound && resolved.bound.id !== boundId) { - // Same region -> refresh the active bound from the location resolve - // (signed-out users get their bound from here; no cart clear). setRegion(resolved.region, resolved.bound.id) } } @@ -177,7 +234,13 @@ export function useRegion(): UseRegionResult { regionId, boundId, setRegion, + clearRegion, queryClient, + isAuthenticated, + isAuthLoading, + defaultAddressQuery.isLoading, + defaultAddress, + regions, ]) // Safety net: a hanging resolve must not strand the first-run spinner. diff --git a/apps/user-ui/src/lib/pending-address.ts b/apps/user-ui/src/lib/pending-address.ts index 7f07cc7..465ef05 100644 --- a/apps/user-ui/src/lib/pending-address.ts +++ b/apps/user-ui/src/lib/pending-address.ts @@ -14,7 +14,6 @@ export interface PendingAddressInput { addressLine2?: string city: string state: string - pincode: string isDefault?: boolean latitude: number longitude: number diff --git a/apps/user-ui/src/store/locationStore.ts b/apps/user-ui/src/store/locationStore.ts index 20ff3b3..784183e 100644 --- a/apps/user-ui/src/store/locationStore.ts +++ b/apps/user-ui/src/store/locationStore.ts @@ -14,7 +14,8 @@ export type LocationStatus = | 'locating' // permission requested / waiting for the fix | 'granted' // coordinates available | 'denied' // foreground permission refused - | 'unavailable' // services off, or no fix could be read + | 'services-off' // device location services are switched off + | 'unavailable' // no fix could be read (timeout / provider error) | 'error' export interface Coords { @@ -95,6 +96,7 @@ export const useLocationStore = create((set, get) => ({ if (token !== activeToken) return if (status !== 'granted') { + console.log('[user-ui] location permission denied') set({ status: 'denied', coords: null, error: null }) return } @@ -107,7 +109,8 @@ export const useLocationStore = create((set, get) => ({ : true if (token !== activeToken) return if (!servicesEnabled) { - set({ status: 'unavailable', coords: null, error: null }) + console.log('[user-ui] location services off') + set({ status: 'services-off', coords: null, error: null }) return } @@ -116,9 +119,12 @@ export const useLocationStore = create((set, get) => ({ FIRST_FIX_TIMEOUT_MS ) if (token !== activeToken) return - set({ status: 'granted', coords: toCoords(position), error: null }) + const nextCoords = toCoords(position) + console.log('[user-ui] location coords', nextCoords) + set({ status: 'granted', coords: nextCoords, error: null }) } catch (err) { if (token !== activeToken) return + console.log('[user-ui] location unavailable', err instanceof Error ? err.message : err) set({ status: 'unavailable', coords: null, diff --git a/apps/user-ui/src/store/regionStore.ts b/apps/user-ui/src/store/regionStore.ts index 88f62ac..749ca36 100644 --- a/apps/user-ui/src/store/regionStore.ts +++ b/apps/user-ui/src/store/regionStore.ts @@ -1,19 +1,21 @@ import { create } from 'zustand' -import { persist, createJSONStorage } from 'zustand/middleware' -import { StorageServiceCasual } from 'common-ui' import type { RegionSummary } from '@packages/shared' -// Browsing region β€” the single region the user is currently shopping in. -// Kept separate from account identity and persisted so the choice survives -// app restarts. `regionGeneration` is a monotonic marker bumped on every -// change so stale regional responses can be ignored. +// Browsing region β€” the region the user is currently shopping in. +// +// Deliberately NOT persisted: at each launch the region is re-derived from the +// device location, or from the user's default / chosen address. A persisted +// region would let the app show a stale region (e.g. the last one) whenever the +// location is unavailable, instead of asking the user to grant location or add +// an address. `regionGeneration` is a monotonic marker bumped on every change so +// stale regional responses can be ignored. interface RegionStore { selectedRegionId: number | null selectedRegion: RegionSummary | null /** * The bound whose consts the client should read for this region. Resolved - * from device location (the containing bound) or from the region's effective - * bound on a manual pick. `null` until known. + * from device location (the containing bound) or from a chosen address's + * bound. `null` until known. */ selectedBoundId: number | null regionGeneration: number @@ -21,62 +23,44 @@ interface RegionStore { clearRegion: () => void } -export const useRegionStore = create()( - persist( - (set) => ({ - selectedRegionId: null, - selectedRegion: null, - selectedBoundId: null, - regionGeneration: 0, - setRegion: (region, boundId = null) => - set((state) => { - // No-op when nothing actually changed: keeps regionGeneration stable - // and prevents effect loops that re-apply the same region. - if ( - state.selectedRegionId === region.id && - state.selectedBoundId === boundId && - state.selectedRegion?.name === region.name && - state.selectedRegion?.description === region.description - ) { - return state - } - return { - selectedRegionId: region.id, - selectedRegion: region, - selectedBoundId: boundId, - regionGeneration: state.regionGeneration + 1, - } - }), - clearRegion: () => - set((state) => { - if ( - state.selectedRegionId == null && - state.selectedRegion == null && - state.selectedBoundId == null - ) { - return state - } - return { - selectedRegionId: null, - selectedRegion: null, - selectedBoundId: null, - regionGeneration: state.regionGeneration + 1, - } - }), +export const useRegionStore = create((set) => ({ + selectedRegionId: null, + selectedRegion: null, + selectedBoundId: null, + regionGeneration: 0, + setRegion: (region, boundId = null) => + set((state) => { + // No-op when nothing actually changed: keeps regionGeneration stable + // and prevents effect loops that re-apply the same region. + if ( + state.selectedRegionId === region.id && + state.selectedBoundId === boundId && + state.selectedRegion?.name === region.name && + state.selectedRegion?.description === region.description + ) { + return state + } + return { + selectedRegionId: region.id, + selectedRegion: region, + selectedBoundId: boundId, + regionGeneration: state.regionGeneration + 1, + } }), - { - name: 'freshyo-region', - version: 1, - storage: createJSONStorage(() => StorageServiceCasual), - partialize: (state) => ({ - selectedRegionId: state.selectedRegionId, - selectedRegion: state.selectedRegion, - selectedBoundId: state.selectedBoundId, - regionGeneration: state.regionGeneration, - // Functions are dropped from the persisted payload. - setRegion: state.setRegion, - clearRegion: state.clearRegion, - }), - } - ) -) + clearRegion: () => + set((state) => { + if ( + state.selectedRegionId == null && + state.selectedRegion == null && + state.selectedBoundId == null + ) { + return state + } + return { + selectedRegionId: null, + selectedRegion: null, + selectedBoundId: null, + regionGeneration: state.regionGeneration + 1, + } + }), +})) diff --git a/apps/user-ui/tests/components/address-form.test.tsx b/apps/user-ui/tests/components/address-form.test.tsx index 74346b4..02c4248 100644 --- a/apps/user-ui/tests/components/address-form.test.tsx +++ b/apps/user-ui/tests/components/address-form.test.tsx @@ -74,7 +74,6 @@ describe('AddressForm', () => { addressLine1: '9 Office St', city: 'Hyderabad', state: 'Telangana', - pincode: '500002', isDefault: false, } as never } diff --git a/apps/user-ui/tests/components/address-selectors.test.tsx b/apps/user-ui/tests/components/address-selectors.test.tsx index bfd600b..d292542 100644 --- a/apps/user-ui/tests/components/address-selectors.test.tsx +++ b/apps/user-ui/tests/components/address-selectors.test.tsx @@ -25,7 +25,6 @@ const ADDRESSES = { addressLine2: 'Apt 4', city: 'Hyderabad', state: 'Telangana', - pincode: '500001', isDefault: false, }, { @@ -36,7 +35,6 @@ const ADDRESSES = { addressLine2: null, city: 'Hyderabad', state: 'Telangana', - pincode: '500002', isDefault: true, }, ], diff --git a/apps/user-ui/tests/components/slot-layout.test.tsx b/apps/user-ui/tests/components/slot-layout.test.tsx index c133c3e..121a507 100644 --- a/apps/user-ui/tests/components/slot-layout.test.tsx +++ b/apps/user-ui/tests/components/slot-layout.test.tsx @@ -27,7 +27,6 @@ const PROCEDURES = { addressLine2: null, city: 'Hyderabad', state: 'Telangana', - pincode: '500001', isDefault: true, }, ], diff --git a/apps/user-ui/tests/screens/checkout-coupons.test.tsx b/apps/user-ui/tests/screens/checkout-coupons.test.tsx index 098cecd..2f4b1a9 100644 --- a/apps/user-ui/tests/screens/checkout-coupons.test.tsx +++ b/apps/user-ui/tests/screens/checkout-coupons.test.tsx @@ -54,7 +54,6 @@ const ADDRESSES = { addressLine2: 'Apt 4', city: 'Hyderabad', state: 'Telangana', - pincode: '500001', isDefault: true, }, ], diff --git a/apps/user-ui/tests/screens/me-account.test.tsx b/apps/user-ui/tests/screens/me-account.test.tsx index 1f307c3..cb0480b 100644 --- a/apps/user-ui/tests/screens/me-account.test.tsx +++ b/apps/user-ui/tests/screens/me-account.test.tsx @@ -28,7 +28,6 @@ const ADDRESS = { addressLine2: 'Apt 4', city: 'Hyderabad', state: 'Telangana', - pincode: '500001', isDefault: false, } diff --git a/apps/user-ui/tests/screens/mutation-invalidation.test.tsx b/apps/user-ui/tests/screens/mutation-invalidation.test.tsx index 96158f5..bd0966e 100644 --- a/apps/user-ui/tests/screens/mutation-invalidation.test.tsx +++ b/apps/user-ui/tests/screens/mutation-invalidation.test.tsx @@ -44,7 +44,6 @@ const ADDRESS = { addressLine2: 'Apt 4', city: 'Hyderabad', state: 'Telangana', - pincode: '500001', isDefault: false, } diff --git a/apps/web-ui/src/components/AddressForm.tsx b/apps/web-ui/src/components/AddressForm.tsx index 0244049..b21cf2d 100644 --- a/apps/web-ui/src/components/AddressForm.tsx +++ b/apps/web-ui/src/components/AddressForm.tsx @@ -1,5 +1,6 @@ import React, { useCallback, useEffect, useState } from 'react' import { trpc } from '../lib/trpc-client' +import { useRegionStore } from '../lib/stores/region-store' import { p, pInput as PInput, MyButton, div } from 'web-components' import { MapPin } from 'lucide-react' import * as Yup from 'yup' @@ -13,9 +14,7 @@ const validationSchema = Yup.object({ phone: Yup.string().required('Phone is required').matches(/^\d{10}$/, 'Phone must be 10 digits'), addressLine1: Yup.string().required('Address Line 1 is required'), addressLine2: Yup.string(), - city: Yup.string().required('City is required'), state: Yup.string().required('State is required'), - pincode: Yup.string().required('Pincode is required').matches(/^\d{6}$/, 'Pincode must be 6 digits'), isDefault: Yup.boolean(), }) @@ -30,19 +29,55 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv ? { latitude: initialValues.latitude, longitude: initialValues.longitude } : null ) - // Region is derived from the coordinates, never picked directly. - const [resolvedRegion, setResolvedRegion] = useState(null) + const browsingRegionId = useRegionStore((state) => state.selectedRegionId) + const browsingRegion = useRegionStore((state) => state.selectedRegion) + // The town (region) for this address. Pre-selected from the app's current + // browsing region when one exists; otherwise picked from the City dropdown. + const [resolvedRegion, setResolvedRegion] = useState(() => + browsingRegionId != null + ? { regionId: browsingRegionId, boundId: browsingRegion?.effectiveBoundId ?? null } + : null + ) const utils = trpc.useUtils() + // Towns (regions) the user can deliver in β€” the City field is a picker over them. + const { data: regionsData } = trpc.common.listRegions.useQuery() + const regions = regionsData ?? [] + const cityName = regions.find((region) => region.id === resolvedRegion?.regionId)?.name ?? '' + + const handleCityChange = useCallback( + async (regionId: number) => { + if (!currentLocation) { + setResolvedRegion({ regionId, boundId: null }) + setLocationError('Use your location or pick a point inside this town.') + return + } + setResolvedRegion({ regionId, boundId: null }) + setLocationError(null) + try { + const resolved = await utils.common.resolveBound.fetch({ + regionId, + lat: currentLocation.latitude, + lng: currentLocation.longitude, + }) + const info: ResolvedRegion = { regionId, boundId: resolved.boundId } + setResolvedRegion(info) + onResolvedRegion?.(info) + } catch { + setLocationError('Your location is outside this town. Pick a point on the map inside it.') + } + }, + [utils, currentLocation, onResolvedRegion] + ) + const [values, setValues] = useState(() => ({ name: initialValues?.name || '', phone: initialValues?.phone || '', addressLine1: initialValues?.addressLine1 || '', addressLine2: initialValues?.addressLine2 || '', - city: initialValues?.city || 'Mahabubnagar', + city: initialValues?.city || '', state: initialValues?.state || 'Telangana', - pincode: initialValues?.pincode || '509001', isDefault: initialValues?.isDefault || false, googleMapsUrl: initialValues?.googleMapsUrl || '', })) @@ -84,6 +119,18 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv // eslint-disable-next-line react-hooks/exhaustive-deps }, []) + // Pre-select the browsing town once known β€” unless the user already picked a + // town or attached a location. + useEffect(() => { + if (resolvedRegion != null || currentLocation != null) return + if (browsingRegionId == null) return + setResolvedRegion({ + regionId: browsingRegionId, + boundId: browsingRegion?.effectiveBoundId ?? null, + }) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [browsingRegionId, browsingRegion]) + // Coordinates picked on the embedded map are delivered via postMessage. useEffect(() => { if (!mapOpen) return @@ -161,8 +208,8 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv setSubmitError('Please use your current location or select one on the map.') return } - if (!resolvedRegion) { - setSubmitError(locationError || 'Please choose a location inside our delivery area.') + if (!resolvedRegion || locationError) { + setSubmitError(locationError || 'Please choose a town and a location inside it.') return } setIsSubmitting(true) @@ -170,6 +217,7 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv const payload = { ...values, + city: cityName || values.city || '', regionId: resolvedRegion.regionId, latitude: currentLocation.latitude, longitude: currentLocation.longitude, @@ -199,7 +247,7 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
ℹ️ -

We currently serve only in Mahabubnagar town

+

We currently serve only in the towns listed below

@@ -251,44 +299,63 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
- + +
-
- -
- - {/* Location is mandatory and drives the region. */} + {/* Location is mandatory: attach the device location or pick on the map. */}

Delivery Location *

-
- - -
- - {currentLocation && ( -

- πŸ“ {currentLocation.latitude.toFixed(5)}, {currentLocation.longitude.toFixed(5)} -

+ {currentLocation ? ( +
+

+ Current Location Attached +

+

+ πŸ“ {currentLocation.latitude.toFixed(5)}, {currentLocation.longitude.toFixed(5)} +

+ +
+ ) : ( +
+ + +
)} {locationError &&

{locationError}

}
@@ -307,7 +374,7 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv fullWidth textContent={isSubmitting ? (isEdit ? 'Updating...' : 'Adding...') : (isEdit ? 'Update Address' : 'Add Address')} onClick={handleSubmit} - disabled={isSubmitting} + disabled={isSubmitting || !currentLocation} className="bg-brand-500 text-white" /> diff --git a/apps/web-ui/src/components/CheckoutAddressSelector.tsx b/apps/web-ui/src/components/CheckoutAddressSelector.tsx index b7a254e..23d8529 100644 --- a/apps/web-ui/src/components/CheckoutAddressSelector.tsx +++ b/apps/web-ui/src/components/CheckoutAddressSelector.tsx @@ -151,7 +151,7 @@ export function CheckoutAddressSelector({ onAddressSelect, onAddAddress, onEditA {address.addressLine2 ? `, ${address.addressLine2}` : ''}

- {address.city}, {address.state} - {address.pincode} + {address.city}, {address.state}

Phone: {address.phone} diff --git a/apps/web-ui/src/routes/me.addresses.tsx b/apps/web-ui/src/routes/me.addresses.tsx index b598b2d..781761d 100644 --- a/apps/web-ui/src/routes/me.addresses.tsx +++ b/apps/web-ui/src/routes/me.addresses.tsx @@ -12,7 +12,7 @@ export const Route = createFileRoute('/me/addresses')({ component: AddressesPage // Address view β€” required core of the shared UserAddress + optional geo fields type Address = Pick< UserAddress, - 'id' | 'regionId' | 'name' | 'phone' | 'addressLine1' | 'addressLine2' | 'city' | 'state' | 'pincode' | 'isDefault' + 'id' | 'regionId' | 'name' | 'phone' | 'addressLine1' | 'addressLine2' | 'city' | 'state' | 'isDefault' > & { latitude?: number | null longitude?: number | null @@ -20,7 +20,7 @@ type Address = Pick< } const formatAddress = (addr: Address) => { - return `${addr.addressLine1}${addr.addressLine2 ? `, ${addr.addressLine2}` : ''}, ${addr.city}, ${addr.state} - ${addr.pincode}` + return `${addr.addressLine1}${addr.addressLine2 ? `, ${addr.addressLine2}` : ''}, ${addr.city}, ${addr.state}` } function AddressCard({ @@ -143,7 +143,6 @@ function AddressesPage() { addressLine2: addressToUpdate.addressLine2 || undefined, city: addressToUpdate.city, state: addressToUpdate.state, - pincode: addressToUpdate.pincode, isDefault: true, // Keep the stored coordinates so the bound is not re-derived from a fallback. latitude: addressToUpdate.latitude ?? undefined, @@ -245,7 +244,6 @@ function AddressesPage() { addressLine2: editingAddress.addressLine2 || '', city: editingAddress.city, state: editingAddress.state, - pincode: editingAddress.pincode, isDefault: editingAddress.isDefault, latitude: editingAddress.googleMapsUrl ? undefined diff --git a/change-log.txt b/change-log.txt index bba3454..fd338fb 100644 --- a/change-log.txt +++ b/change-log.txt @@ -3746,3 +3746,250 @@ user-ui + loadGoogleMaps now resolves Map/Marker via google.maps.importLibrary('maps'|'marker') + GoogleMapsNamespace type narrowed to { importLibrary?, __ib__? } No dependency added. No migration. No tests run. + +2026-10-13 16:35:00 Location gate (user-ui): adopt the default address when the device location is unusable. + Previously, if location was disabled/denied/out-of-area and no region was saved, the gate always showed the address + chooser even when the user had a default address. + 1/1 apps/user-ui/components/LocationTestWrapper.tsx: + + reads auth (useAuthOptional) + user.address.getDefaultAddress + common.listRegions + + when hydrated + authenticated + location settled with no region and a default address exists: + confirmRegionSwitch(default-address region, default-address boundId) once (ref guard), showing a spinner + + shows "Setting up your address..." while auth / default-address / regions load so the chooser never flashes + + falls back to LocationFallbackFlow only when there is no default address + No dependency added. No migration. No tests run. + +2026-10-13 16:43:33 Startup region decision (user-ui): anchor on the default address. + Rule: with a default address, at launch use it unless the device location resolves to a *different* serviceable + region (then ask the user to choose an address). Same region or out-of-area/location-off -> use the default. + 1/2 apps/user-ui/src/hooks/useRegion.ts: + + reads auth (isLoading too), user.address.getDefaultAddress, common.listRegions + + startup effect rewritten: when a default address exists and the location settled -> + - resolved region == default's region, OR resolved == null (location off / out of area) -> + confirmRegionSwitch(default region, default bound) (no prompt) + - resolved region != default's region (another serviceable region) -> clearRegion() so the gate asks + when there is no default address -> previous behaviour (use the resolved region, else prompt) + + waits for auth/default-address/regions before settling (spinner covers it) + 2/2 apps/user-ui/components/LocationTestWrapper.tsx: reverted the local default-address auto-adopt + (useRegion is now the single source of truth; keeping it would re-adopt the default while prompting) + No dependency added. No migration. No tests run. + +2026-10-13 17:05:42 Cart page (user-ui): require a first delivery address before showing the cart. + When the region/bound is known (from location) but the signed-in user has no address yet, opening the cart now + shows an "add address" screen first: "Address of current Location" (prefills the device coords) or "Choose another + location" (map). The first saved address becomes the default (backend), then the cart is shown. + 1/1 NEW apps/user-ui/components/CartAddressGate.tsx: + + full-screen screen with the two options; "Address of current Location" opens AddressForm prefilled with + useLocationStore coords; "Choose another location" opens AddressForm (map picker) + + onSuccess -> close + onDone() + 2/2 apps/user-ui/components/cart-page.tsx: + + user.address.getUserAddresses query + + after auth/cart load, if authenticated and the cart has items and there is no address -> render CartAddressGate + (refetch on done) instead of the cart + No dependency added. No migration. No tests run. + +2026-10-13 17:08:19 Cart page (user-ui): apply the first-address gate even on an empty cart. + 1/1 apps/user-ui/components/cart-page.tsx: + - if (cartItems.length > 0) { ... } + + gate now runs regardless of cart contents (authenticated users with no address see CartAddressGate) + No dependency added. No migration. No tests run. + +2026-10-13 17:16:12 user-ui location tracking: log the captured coordinates. + 1/1 apps/user-ui/src/store/locationStore.ts (refresh): + + const nextCoords = toCoords(position) + + console.log('[user-ui] location coords', nextCoords) + + logs on the non-granted paths too ('location permission denied', 'location services disabled', + 'location unavailable', ) + No dependency added. No migration. No tests run. + +2026-10-13 17:20:49 Region selection (user-ui): stop persisting the browsing region. + Requirement: the region must always come from the device location or a chosen/default address β€” never a stale + saved region. Previously `freshyo-region` was persisted, so a signed-out user whose location was unavailable + still landed on the last region (e.g. Mahabubnagar) instead of being asked. + 1/2 apps/user-ui/src/store/regionStore.ts: + - persist(...) middleware (name 'freshyo-region', StorageServiceCasual) + + plain create(...); selectedRegionId/selectedRegion/selectedBoundId now reset each launch + 2/2 apps/user-ui/src/hooks/useRegion.ts: + - hydrated derived from useRegionStore.persist.hasHydrated()/onFinishHydration + + hydrated is always true (nothing to hydrate) + + startup effect: when regionId is null (fresh launch) adopt the resolved/default region via setRegion (which + does NOT clear the local cart); use confirmRegionSwitch only when switching away from an already-set region + No dependency added. No migration. No tests run. + +2026-10-13 17:29:05 Location gate (user-ui): tell the user why location is unavailable before asking for an address. + 1/4 apps/user-ui/src/store/locationStore.ts: + + LocationStatus gains 'services-off'; the `!servicesEnabled` branch now sets it (was 'unavailable') + + logs '[user-ui] location services off' + 2/4 apps/user-ui/src/hooks/useRegion.ts: + + UseRegionResult.locationStatus union includes 'services-off'; startup terminal check includes it + 3/4 apps/user-ui/src/components/location/LocationFallbackFlow.tsx: + + optional `notice` prop rendered as an amber banner above the address options + 4/4 apps/user-ui/components/LocationTestWrapper.tsx: + + maps locationStatus -> a message ('denied' = access not granted, 'services-off' = turned off, + 'unavailable'/'error' = could not access) and passes it to LocationFallbackFlow + No dependency added. No migration. No tests run. + +2026-10-13 17:32:51 Location gate (user-ui): add an "Open location settings" button. + When the OS can't be fixed from inside the app (location services off, or permission denied β€” iOS won't re-prompt), + the notice banner now has a button that deep-links to the relevant settings. + 1/2 apps/user-ui/src/components/location/LocationFallbackFlow.tsx: + + optional onOpenSettings prop; banner shows a "Open location settings" button when provided + 2/2 apps/user-ui/components/LocationTestWrapper.tsx: + + openLocationSettings(): Android -> Linking.sendIntent('android.settings.LOCATION_SOURCE_SETTINGS'), + else Linking.openSettings(); passed for locationStatus 'services-off' and 'denied' + No dependency added. No migration. No tests run. + +2026-10-13 17:45:43 Remove `pincode` field entirely from the delivery-address model and every usage (keep city/state). + Scope: sqlite schema + regions migration, shared types, sqlite/backend/postgres address+order mappings, user-ui/web-ui/ + admin-ui/admin-web/fallback-ui address displays and form fields, and test fixtures. No behavior change beyond dropping pincode. + No dependency added. No migration run. No tests run (typechecks only at the end). + + 1/29 packages/db_helper_sqlite/src/db/schema.ts (addresses table) + - pincode: text('pincode').notNull(), + + 2/29 packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql + - `pincode` text NOT NULL, (in __new_addresses CREATE TABLE) + - `pincode`, (column list of INSERT INTO __new_addresses) + - `pincode`, (SELECT list of the same INSERT) + + 3/29 packages/shared/types/user.ts + - pincode: string; (Address interface) + - pincode: string; (UserAddress interface) + + 4/29 packages/shared/types/admin.ts + - pincode: string; (AdminOrderDetailsAddress) + + 5/29 packages/shared/types/app-common.types.ts + - pincode: string (AddressFormProps.initialValues) + + 6/29 packages/db_helper_sqlite/src/user-apis/address.ts + - pincode: address.pincode, (mapUserAddress) + - pincode: string (createUserAddress input) + - pincode: input.pincode, (create insert values) + - pincode: string (updateUserAddress input) + - pincode: input.pincode, (update set values) + + 7/29 packages/db_helper_sqlite/src/user-apis/order.ts + - pincode: string | null (OrderWithFullData.address) + - pincode: true, (address columns, getOrdersByIdsWithFullData) + - pincode: true, (address columns, getOrderByIdWithFullData) + + 8/29 packages/db_helper_sqlite/src/admin-apis/order.ts + - pincode: orderData.address.pincode, (AdminOrderDetails address mapping) + - `...state} - ${order.address.pincode}` -> `...state}` (slot-order address string) + - `...state} - ${order.address.pincode}` -> `...state}` (list-order address string) + + 9/29 apps/backend/src/trpc/apis/user-apis/apis/address.ts + - comment `Pincode: exactly 6 digits.`; - const PINCODE_REGEX = /^\d{6}$/ + - pincode zod field (createAddress + updateAddress) + - pincode from destructuring (both handlers); pincode from required-fields check + - pincode from createUserAddressInDb/updateUserAddressInDb calls + + 10/29 apps/backend/src/lib/post-order-handler.ts + - `...state || ''} - ${order.address?.pincode || ''}` -> `...state || ''}` + + 11/29 apps/user-ui/src/components/AddressForm.tsx + - pincode Yup rule; pincode: '509001' default; pincode: values.pincode draft payload; Pincode MyTextInput + error text + + 12/29 apps/user-ui/src/lib/pending-address.ts + - pincode: string (PendingAddressInput) + + 13/29 apps/user-ui/src/components/location/LocationFallbackFlow.tsx + - pincode from ChooserAddress; pincode: address.pincode from set-default payload; `{address.city} - {address.pincode}` -> `{address.city}` + + 14/29 apps/user-ui/src/components/LocationBar.tsx + - pincode from formatAddress param; `...${address.city} - ${address.pincode}` -> `...${address.city}` + + 15/29 apps/user-ui/components/CartAddressGate.tsx + - pincode: '509001' from initialValues + + 16/29 apps/user-ui/components/CheckoutAddressSelector.tsx + - pincode: address.pincode from update payload; `{address.city}, {address.state} - {address.pincode}` -> `{address.city}, {address.state}` + + 17/29 apps/user-ui/components/CheckoutAddressDisplay.tsx + - `{address.city}, {address.state} - {address.pincode}` -> `{address.city}, {address.state}` + + 18/29 apps/user-ui/components/QuickDeliveryAddressSelector.tsx + - `...${address.state} - ${address.pincode}` -> `...${address.state}` + + 19/29 apps/user-ui/app/(drawer)/(tabs)/me/addresses/index.tsx + - 'pincode' from Pick; ` - ${addr.pincode}` from formatAddress; pincode from set-default payload; pincode from edit initialValues + + 20/29 apps/web-ui/src/components/AddressForm.tsx + - pincode Yup rule; pincode: initialValues?.pincode || '509001'; block + + 21/29 apps/web-ui/src/routes/me.addresses.tsx + - 'pincode' from Pick; ` - ${addr.pincode}` from formatAddress; pincode from set-default payload; pincode from edit initialValues + + 22/29 apps/web-ui/src/components/CheckoutAddressSelector.tsx + - `{address.city}, {address.state} - {address.pincode}` -> `{address.city}, {address.state}` + + 23/29 apps/admin-ui/app/(drawer)/dashboard/manage-orders/order-details/[id].tsx + - `...${order.address.state} - ${order.address.pincode}` -> `...${order.address.state}` + + 24/29 apps/admin-web/src/routes/dashboard.orders.$id.tsx + - `...${order.address.state} - ${order.address.pincode}` -> `...${order.address.state}` + + 25/29 apps/fallback-ui/src/routes/order-details.tsx + - `...${order.address?.state} - ${order.address?.pincode}` -> `...${order.address?.state}` + + 26/29 packages/db_helper_postgres/src/db/schema.ts + - pincode: varchar('pincode', { length: 10 }).notNull(), + + 27/29 packages/db_helper_postgres/src/user-apis/address.ts + - pincode mapping/input/insert/update (same shape as sqlite address.ts) + + 28/29 packages/db_helper_postgres/src/user-apis/order.ts + - pincode from OrderWithFullData address type and from both address column selects + + 29/29 packages/db_helper_postgres/src/admin-apis/order.ts + - pincode from AdminOrderDetails address mapping and from both address display strings + + Tests (fixtures): apps/backend/tests/api/misc-procedures.test.ts, apps/backend/tests/helpers/fixtures.ts (x2), + apps/admin-ui/tests/screens/order-details.test.tsx, apps/user-ui/tests/components/address-form.test.tsx, + apps/user-ui/tests/components/address-selectors.test.tsx (x2), apps/user-ui/tests/components/slot-layout.test.tsx, + apps/user-ui/tests/screens/checkout-coupons.test.tsx, apps/user-ui/tests/screens/me-account.test.tsx, + apps/user-ui/tests/screens/mutation-invalidation.test.tsx -> remove `pincode: '...'` fixture lines. + + NOTE: historical migrations packages/db_helper_sqlite/drizzle/0000_nifty_sauron.sql, + packages/db_helper_postgres/drizzle/0003_tricky_the_twelve.sql and the data dump apps/backend/migrated.sql were left + untouched (not in scope; the current migration 0006 recreates the addresses table instead). + +2026-10-13 17:57:08 Address form (user-ui + web-ui): City becomes a town/region picker (no hardcoded Mahabubnagar). + 1/2 apps/user-ui/src/components/AddressForm.tsx: + + common.listRegions query; City is now a dropdown over region names + + handleCityChange(regionId): re-checks the chosen coordinates fall inside that town via common.resolveBound + (out-of-town -> locationError); City is no longer a Formik field (derived from the resolved region) + + removed the `city` Yup rule and the hardcoded `city: 'Mahabubnagar'` default; submit blocks on locationError + + submit/draft payload city = the resolved region's name + + Service-Area notice no longer hardcodes Mahabubnagar ("...only in the towns listed below") + 2/2 apps/web-ui/src/components/AddressForm.tsx: same (City is a