This commit is contained in:
shafi54 2026-10-13 18:11:25 +05:30
parent d8e4b4c41d
commit e55ac915f4
44 changed files with 893 additions and 280 deletions

View file

@ -435,7 +435,7 @@ export default function OrderDetails() {
{order.address.name} {' '} {order.address.name} {' '}
{order.address.line1} {order.address.line1}
{order.address.line2 ? `, ${order.address.line2}` : ""} {order.address.line2 ? `, ${order.address.line2}` : ""}
{`\n${order.address.city}, ${order.address.state} - ${order.address.pincode}`} {`\n${order.address.city}, ${order.address.state}`}
</MyText> </MyText>
</View> </View>
</View> </View>

View file

@ -35,7 +35,6 @@ const makeDetails = (overrides: Record<string, unknown> = {}) => ({
line2: null, line2: null,
city: 'City', city: 'City',
state: 'State', state: 'State',
pincode: '500001',
phone: '9876543210', phone: '9876543210',
}, },
slotInfo: { time: '2026-01-02T10:00:00.000Z', sequence: null }, slotInfo: { time: '2026-01-02T10:00:00.000Z', sequence: null },

View file

@ -404,7 +404,7 @@ function OrderDetails() {
{order.address.name} {' '} {order.address.name} {' '}
{order.address.line1} {order.address.line1}
{order.address.line2 ? `, ${order.address.line2}` : ''} {order.address.line2 ? `, ${order.address.line2}` : ''}
{`\n${order.address.city}, ${order.address.state} - ${order.address.pincode}`} {`\n${order.address.city}, ${order.address.state}`}
</MyText> </MyText>
</div> </div>
</div> </div>

View file

@ -69,7 +69,7 @@ const formatOrderMessageWithFullData = (ordersData: any[]): string => {
if (order.address?.addressLine2) { if (order.address?.addressLine2) {
message += ` ${order.address.addressLine2}\n`; 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) { if (order.address?.phone) {
message += ` 📞 ${order.address.phone}\n`; message += ` 📞 ${order.address.phone}\n`;
} }

View file

@ -20,9 +20,8 @@ import type {
UserAddressDeleteResponse, UserAddressDeleteResponse,
} from '@packages/shared' } 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 PHONE_REGEX = /^[6-9]\d{9}$/
const PINCODE_REGEX = /^\d{6}$/
export const addressRouter = router({ export const addressRouter = router({
getDefaultAddress: protectedProcedure getDefaultAddress: protectedProcedure
@ -52,8 +51,6 @@ export const addressRouter = router({
addressLine2: z.string().optional(), addressLine2: z.string().optional(),
city: z.string().min(1, 'City is required'), city: z.string().min(1, 'City is required'),
state: z.string().min(1, 'State 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(), isDefault: z.boolean().optional(),
// Coordinates picked on the map. The user app always sends them; the web // 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 // 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<UserAddressResponse> => { .mutation(async ({ input, ctx }): Promise<UserAddressResponse> => {
const userId = ctx.user.userId; 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; let { latitude, longitude } = input;
@ -88,7 +85,7 @@ export const addressRouter = router({
} }
// Validate required fields // Validate required fields
if (!name || !phone || !addressLine1 || !city || !state || !pincode) { if (!name || !phone || !addressLine1 || !city || !state) {
throw new Error('Missing required fields'); throw new Error('Missing required fields');
} }
@ -111,7 +108,6 @@ export const addressRouter = router({
addressLine2, addressLine2,
city, city,
state, state,
pincode,
isDefault: makeDefault, isDefault: makeDefault,
latitude, latitude,
longitude, longitude,
@ -132,8 +128,6 @@ export const addressRouter = router({
addressLine2: z.string().optional(), addressLine2: z.string().optional(),
city: z.string().min(1, 'City is required'), city: z.string().min(1, 'City is required'),
state: z.string().min(1, 'State 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(), isDefault: z.boolean().optional(),
// See createAddress: coordinates are optional for the legacy web client. // See createAddress: coordinates are optional for the legacy web client.
latitude: z.number().min(-90).max(90).optional(), latitude: z.number().min(-90).max(90).optional(),
@ -142,7 +136,7 @@ export const addressRouter = router({
})) }))
.mutation(async ({ input, ctx }): Promise<UserAddressResponse> => { .mutation(async ({ input, ctx }): Promise<UserAddressResponse> => {
const userId = ctx.user.userId; 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; let { latitude, longitude } = input;
@ -194,7 +188,6 @@ export const addressRouter = router({
addressLine2, addressLine2,
city, city,
state, state,
pincode,
// An omitted isDefault means "leave it as it is": only an explicit value may change it. // An omitted isDefault means "leave it as it is": only an explicit value may change it.
isDefault: isDefault ?? existingAddress.isDefault, isDefault: isDefault ?? existingAddress.isDefault,
googleMapsUrl, googleMapsUrl,

View file

@ -20,7 +20,6 @@ const addressBody = (over: Record<string, unknown> = {}) => ({
addressLine1: '1 API Street', addressLine1: '1 API Street',
city: 'Mahabubnagar', city: 'Mahabubnagar',
state: 'Telangana', state: 'Telangana',
pincode: '509001',
isDefault: false, isDefault: false,
...over, ...over,
}) })

View file

@ -156,7 +156,6 @@ export async function ensureUserAddress(): Promise<{ addressId: number; created:
addressLine1: '1 API Test Street', addressLine1: '1 API Test Street',
city: 'Mahabubnagar', city: 'Mahabubnagar',
state: 'Telangana', state: 'Telangana',
pincode: '509001',
isDefault: true, isDefault: true,
}) })
@ -190,7 +189,6 @@ export async function registerUserWithAddress(): Promise<{
addressLine1: '1 API Test Street', addressLine1: '1 API Test Street',
city: 'Mahabubnagar', city: 'Mahabubnagar',
state: 'Telangana', state: 'Telangana',
pincode: '509001',
isDefault: true, isDefault: true,
}) })

View file

@ -139,7 +139,7 @@ export function OrderDetailsRoute() {
<p className="whitespace-pre-line"> <p className="whitespace-pre-line">
{order.address?.name} {order.address?.line1} {order.address?.name} {order.address?.line1}
{order.address?.line2 ? `, ${order.address.line2}` : ""} {order.address?.line2 ? `, ${order.address.line2}` : ""}
{`\n${order.address?.city}, ${order.address?.state} - ${order.address?.pincode}`} {`\n${order.address?.city}, ${order.address?.state}`}
</p> </p>
</div> </div>
</div> </div>

View file

@ -10,7 +10,7 @@ import AddressForm from '@/src/components/AddressForm';
// Address view — required core of the shared UserAddress + optional geo fields // Address view — required core of the shared UserAddress + optional geo fields
type Address = Pick< type Address = Pick<
UserAddress, UserAddress,
'id' | 'regionId' | 'name' | 'phone' | 'addressLine1' | 'addressLine2' | 'city' | 'state' | 'pincode' | 'isDefault' 'id' | 'regionId' | 'name' | 'phone' | 'addressLine1' | 'addressLine2' | 'city' | 'state' | 'isDefault'
> & { > & {
latitude?: number | null latitude?: number | null
longitude?: number | null longitude?: number | null
@ -25,7 +25,7 @@ function AddressCard({ address, onEdit, onDelete, onSetDefault, isDeleting }: {
isDeleting?: boolean; isDeleting?: boolean;
}) { }) {
const formatAddress = (addr: Address) => { 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 ( return (
@ -159,7 +159,6 @@ export default function Addresses() {
addressLine2: addressToUpdate.addressLine2 || undefined, addressLine2: addressToUpdate.addressLine2 || undefined,
city: addressToUpdate.city, city: addressToUpdate.city,
state: addressToUpdate.state, state: addressToUpdate.state,
pincode: addressToUpdate.pincode,
isDefault: true, isDefault: true,
// Keep the stored coordinates so the bound is not re-derived from a fallback. // Keep the stored coordinates so the bound is not re-derived from a fallback.
latitude: addressToUpdate.latitude ?? undefined, latitude: addressToUpdate.latitude ?? undefined,
@ -272,7 +271,6 @@ export default function Addresses() {
addressLine2: editingAddress.addressLine2 || '', addressLine2: editingAddress.addressLine2 || '',
city: editingAddress.city, city: editingAddress.city,
state: editingAddress.state, state: editingAddress.state,
pincode: editingAddress.pincode,
isDefault: editingAddress.isDefault, isDefault: editingAddress.isDefault,
latitude: editingAddress.googleMapsUrl ? undefined : (editingAddress.latitude ?? undefined), latitude: editingAddress.googleMapsUrl ? undefined : (editingAddress.latitude ?? undefined),
longitude: editingAddress.googleMapsUrl ? undefined : (editingAddress.longitude ?? undefined), longitude: editingAddress.googleMapsUrl ? undefined : (editingAddress.longitude ?? undefined),

View file

@ -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<CartAddressGateProps> = ({ onDone, onBack }) => {
const coords = useLocationStore((state) => state.coords)
const [mode, setMode] = useState<'none' | 'current' | 'other'>('none')
return (
<View style={tw`flex-1 bg-gray-50`}>
<View style={tw`bg-white px-4 py-3 border-b border-gray-100 mt-6`}>
<View style={tw`flex-row items-center`}>
<MyTouchableOpacity onPress={onBack} style={tw`p-2 -ml-2 mr-1`} activeOpacity={0.7}>
<MaterialIcons name="chevron-left" size={28} color="#374151" />
</MyTouchableOpacity>
<MyText style={tw`text-lg font-bold text-gray-900`}>Add Delivery Address</MyText>
</View>
</View>
<View style={tw`px-5 pt-6`}>
<MyText style={tw`text-2xl font-extrabold text-gray-900`}>Where should we deliver?</MyText>
<MyText style={tw`text-gray-500 mt-2 mb-6`}>
You don’t have a delivery address yet. Add one to continue.
</MyText>
<MyTouchableOpacity
testID="cart-address-current"
disabled={!coords}
activeOpacity={0.85}
onPress={() => setMode('current')}
style={tw`bg-white border border-gray-200 rounded-2xl p-4 mb-3 shadow-sm ${!coords ? 'opacity-50' : ''}`}
>
<View style={tw`flex-row items-center mb-1`}>
<MaterialIcons name="my-location" size={20} color={theme.colors.brand500} />
<MyText style={tw`text-base font-bold text-gray-900 ml-2`}>
Address of current Location
</MyText>
</View>
<MyText style={tw`text-gray-500 text-sm`}>
{coords
? `Use your current location (${coords.latitude.toFixed(5)}, ${coords.longitude.toFixed(5)})`
: 'Turn on location to use this option'}
</MyText>
</MyTouchableOpacity>
<MyTouchableOpacity
testID="cart-address-other"
activeOpacity={0.85}
onPress={() => setMode('other')}
style={tw`bg-white border border-gray-200 rounded-2xl p-4 shadow-sm`}
>
<View style={tw`flex-row items-center mb-1`}>
<MaterialIcons name="map" size={20} color={theme.colors.brand500} />
<MyText style={tw`text-base font-bold text-gray-900 ml-2`}>
Choose another location
</MyText>
</View>
<MyText style={tw`text-gray-500 text-sm`}>Pick a point on the map</MyText>
</MyTouchableOpacity>
</View>
<Modal
visible={mode !== 'none'}
animationType="slide"
onRequestClose={() => setMode('none')}
>
<View style={tw`flex-1 bg-white`}>
<AddressForm
// "Current location" prefills the device coordinates; "another
// location" starts empty so the user picks on the map.
initialValues={
mode === 'current' && coords
? {
name: '',
phone: '',
addressLine1: '',
addressLine2: '',
city: 'Mahabubnagar',
state: 'Telangana',
isDefault: true,
latitude: coords.latitude,
longitude: coords.longitude,
}
: undefined
}
onSuccess={() => {
setMode('none')
onDone()
}}
/>
</View>
</Modal>
</View>
)
}
export default CartAddressGate

View file

@ -57,7 +57,7 @@ const CheckoutAddressDisplay: React.FC = () => {
{address.addressLine2 ? `, ${address.addressLine2}` : ''} {address.addressLine2 ? `, ${address.addressLine2}` : ''}
</MyText> </MyText>
<MyText style={tw`text-gray-600 text-sm mb-1`}> <MyText style={tw`text-gray-600 text-sm mb-1`}>
{address.city}, {address.state} - {address.pincode} {address.city}, {address.state}
</MyText> </MyText>
<MyText style={tw`text-gray-500 text-xs mt-2`}>Phone: {address.phone}</MyText> <MyText style={tw`text-gray-500 text-xs mt-2`}>Phone: {address.phone}</MyText>
</View> </View>

View file

@ -155,7 +155,6 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
addressLine2: address.addressLine2 || '', addressLine2: address.addressLine2 || '',
city: address.city, city: address.city,
state: address.state, state: address.state,
pincode: address.pincode,
isDefault: address.isDefault, isDefault: address.isDefault,
latitude, latitude,
longitude, longitude,
@ -235,7 +234,7 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
{address.addressLine1}{address.addressLine2 ? `, ${address.addressLine2}` : ''} {address.addressLine1}{address.addressLine2 ? `, ${address.addressLine2}` : ''}
</Text> </Text>
<Text style={tw`text-gray-600 text-sm mb-1`}> <Text style={tw`text-gray-600 text-sm mb-1`}>
{address.city}, {address.state} - {address.pincode} {address.city}, {address.state}
</Text> </Text>
<Text style={tw`text-gray-500 text-xs mt-2`}> <Text style={tw`text-gray-500 text-xs mt-2`}>
Phone: {address.phone} Phone: {address.phone}

View file

@ -1,5 +1,5 @@
import React, { useEffect } from 'react' 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 { MyText, theme, tw } from 'common-ui'
import type { ReactParentComponent } from '@packages/shared' import type { ReactParentComponent } from '@packages/shared'
import { trpc } from '../src/trpc-client' import { trpc } from '../src/trpc-client'
@ -16,11 +16,12 @@ const LoadingScreen: React.FC<{ label?: string }> = ({ label }) => (
/** /**
* Region gate + location fallback. * Region gate + location fallback.
* *
* The browsing region is derived from the device location (see `useRegion`). * 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 * anchored on the user's default address: when the location resolves to the
* renders. When the location is unusable — device location switched off, * default's region (or to no serviceable region) we use the default; only a
* permission denied, or coordinates outside every region bound — the user is * different serviceable region makes us ask. While that decision is in flight we
* asked to choose a region manually. * show a spinner; once a region exists the app renders, otherwise the user is
* asked to choose an address.
*/ */
const LocationTestWrapper: React.FC<ReactParentComponent> = ({ children }) => { const LocationTestWrapper: React.FC<ReactParentComponent> = ({ children }) => {
const { const {
@ -28,10 +29,46 @@ const LocationTestWrapper: React.FC<ReactParentComponent> = ({ children }) => {
clearRegion, clearRegion,
hydrated, hydrated,
isResolvingRegion, isResolvingRegion,
locationStatus,
} = useRegion() } = useRegion()
const { data: regions } = trpc.common.listRegions.useQuery() 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 // Validate the saved region against the live list. A stale/unknown id must
// lead to selection, never a silent checkout fallback. Membership-only: no // lead to selection, never a silent checkout fallback. Membership-only: no
// setRegion here, so this effect can never re-trigger itself. // setRegion here, so this effect can never re-trigger itself.
@ -53,15 +90,22 @@ const LocationTestWrapper: React.FC<ReactParentComponent> = ({ children }) => {
return <LoadingScreen /> return <LoadingScreen />
} }
// Still deriving the region from device location. // Still deriving the region from device location / the default address.
if (isResolvingRegion) { if (isResolvingRegion) {
return <LoadingScreen label="Finding your region..." /> return <LoadingScreen label="Finding your region..." />
} }
// Location unavailable / denied / out of area -> pick an address or add one. // No region resolved -> pick an address or add one.
return ( return (
<View style={tw`flex-1 bg-white`}> <View style={tw`flex-1 bg-white`}>
<LocationFallbackFlow /> <LocationFallbackFlow
notice={locationNotice}
onOpenSettings={
locationStatus === 'services-off' || locationStatus === 'denied'
? openLocationSettings
: undefined
}
/>
</View> </View>
) )
} }

View file

@ -107,7 +107,7 @@ const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps>
const addressOptions = addresses.map(address => ({ const addressOptions = addresses.map(address => ({
id: address.id, id: address.id,
name: address.name, 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, phone: address.phone,
})); }));

View file

@ -32,6 +32,7 @@ import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks';
import { useRegion } from '@/src/hooks/useRegion'; import { useRegion } from '@/src/hooks/useRegion';
import CheckoutAddressSelector from '@/components/CheckoutAddressSelector'; import CheckoutAddressSelector from '@/components/CheckoutAddressSelector';
import LoginWall from '@/components/LoginWall'; import LoginWall from '@/components/LoginWall';
import CartAddressGate from '@/components/CartAddressGate';
import { useAddressStore } from '@/src/store/addressStore'; import { useAddressStore } from '@/src/store/addressStore';
import { useCheckoutStore } from '@/src/store/checkoutStore'; import { useCheckoutStore } from '@/src/store/checkoutStore';
import type { FlashDeliveryProps } from '@packages/shared'; import type { FlashDeliveryProps } from '@packages/shared';
@ -190,6 +191,10 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
const { selectedAddressId, setSelectedAddressId } = useAddressStore(); const { selectedAddressId, setSelectedAddressId } = useAddressStore();
const { regionId } = useRegion(); 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 userNotes = useCheckoutStore((state) => state.userNotes);
const setUserNotes = useCheckoutStore((state) => state.setUserNotes); 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 (
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
<MyText style={tw`text-gray-500 font-medium`}>Loading...</MyText>
</View>
);
}
if ((addressesQuery.data?.data?.length ?? 0) === 0) {
return (
<CartAddressGate
onDone={() => {
void addressesQuery.refetch();
}}
onBack={() => router.back()}
/>
);
}
return ( return (
<View style={tw`flex-1 bg-gray-50`}> <View style={tw`flex-1 bg-gray-50`}>
{/* Fixed Cart Type Header */} {/* Fixed Cart Type Header */}

View file

@ -5,10 +5,11 @@ import * as Yup from 'yup';
import { tw, MyText, MyTouchableOpacity , Checkbox , MyTextInput , LoadingDialog } from 'common-ui'; import { tw, MyText, MyTouchableOpacity , Checkbox , MyTextInput , LoadingDialog } from 'common-ui';
import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { trpc } from '../trpc-client'; import { trpc } from '../trpc-client';
import LocationAttacher from './LocationAttacher';
import LocationMapStep from './location/LocationMapStep'; import LocationMapStep from './location/LocationMapStep';
import type { AddressFormProps } from '@packages/shared'; import type { AddressFormProps } from '@packages/shared';
import { savePendingAddress } from '@/src/lib/pending-address'; 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 Coords = { latitude: number; longitude: number };
type ResolvedRegion = { regionId: number; boundId: number | null }; type ResolvedRegion = { regionId: number; boundId: number | null };
@ -20,6 +21,8 @@ const AddressForm: React.FC<AddressFormProps> = ({
draftMode = false, draftMode = false,
onResolvedRegion, onResolvedRegion,
}) => { }) => {
const { regionId: browsingRegionId, boundId: browsingBoundId } = useRegion();
const deviceCoords = useLocationStore((state) => state.coords);
const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null); const [submitError, setSubmitError] = useState<string | null>(null);
const [mapOpen, setMapOpen] = useState(false); const [mapOpen, setMapOpen] = useState(false);
@ -28,12 +31,21 @@ const AddressForm: React.FC<AddressFormProps> = ({
? { latitude: initialValues.latitude, longitude: initialValues.longitude } ? { latitude: initialValues.latitude, longitude: initialValues.longitude }
: null : null
); );
// Region is never picked directly: it is derived from the coordinates. // The town (region) for this address. Pre-selected from the app's current
const [resolvedRegion, setResolvedRegion] = useState<ResolvedRegion | null>(null); // browsing region when one exists; otherwise picked from the City dropdown.
const [resolvedRegion, setResolvedRegion] = useState<ResolvedRegion | null>(() =>
browsingRegionId != null ? { regionId: browsingRegionId, boundId: browsingBoundId } : null
);
const [locationError, setLocationError] = useState<string | null>(null); const [locationError, setLocationError] = useState<string | null>(null);
const utils = trpc.useUtils(); 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 // Resolve coordinates -> region + bound. Used for whichever source the user
// picks (attach current location or the map). Out-of-area points are refused. // picks (attach current location or the map). Out-of-area points are refused.
const resolveLocation = useCallback( const resolveLocation = useCallback(
@ -64,6 +76,33 @@ const AddressForm: React.FC<AddressFormProps> = ({
[utils, onResolvedRegion] [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). // Resolve any prefilled coordinates once (e.g. edit, or coming from the map).
useEffect(() => { useEffect(() => {
if (initialValues?.latitude != null && initialValues?.longitude != null) { if (initialValues?.latitude != null && initialValues?.longitude != null) {
@ -72,6 +111,25 @@ const AddressForm: React.FC<AddressFormProps> = ({
// eslint-disable-next-line react-hooks/exhaustive-deps // 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({ const createAddressMutation = trpc.user.address.createAddress.useMutation({
onSuccess: (data) => { onSuccess: (data) => {
setIsSubmitting(false); setIsSubmitting(false);
@ -103,9 +161,7 @@ const AddressForm: React.FC<AddressFormProps> = ({
.matches(/^[6-9]\d{9}$/, 'Phone must be a 10-digit number starting with 6, 7, 8 or 9'), .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'), addressLine1: Yup.string().required('Address Line 1 is required'),
addressLine2: Yup.string(), addressLine2: Yup.string(),
city: Yup.string().required('City is required'),
state: Yup.string().required('State 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(), isDefault: Yup.boolean(),
}); });
@ -127,7 +183,7 @@ const AddressForm: React.FC<AddressFormProps> = ({
<View style={tw`flex-row items-center`}> <View style={tw`flex-row items-center`}>
<MyText style={tw`text-amber-600 mr-2`}>ℹ️</MyText> <MyText style={tw`text-amber-600 mr-2`}>ℹ️</MyText>
<MyText style={tw`text-amber-800 text-sm flex-1`}> <MyText style={tw`text-amber-800 text-sm flex-1`}>
We currently serve only in Mahabubnagar town We currently serve only in the towns listed below
</MyText> </MyText>
</View> </View>
</View> </View>
@ -144,9 +200,8 @@ const AddressForm: React.FC<AddressFormProps> = ({
phone: '', phone: '',
addressLine1: '', addressLine1: '',
addressLine2: '', addressLine2: '',
city: 'Mahabubnagar', city: '',
state: 'Telangana', state: 'Telangana',
pincode: '509001',
isDefault: false, isDefault: false,
googleMapsUrl: '', googleMapsUrl: '',
}} }}
@ -156,14 +211,15 @@ const AddressForm: React.FC<AddressFormProps> = ({
setSubmitError('Please attach your current location or select it on the map.'); setSubmitError('Please attach your current location or select it on the map.');
return; return;
} }
if (!resolvedRegion) { if (!resolvedRegion || locationError) {
setSubmitError(locationError || 'Please choose a location inside our delivery area.'); setSubmitError(locationError || 'Please choose a town and a location inside it.');
return; return;
} }
setIsSubmitting(true); setIsSubmitting(true);
setSubmitError(null); setSubmitError(null);
const payload = { const payload = {
...values, ...values,
city: cityName || values.city || '',
regionId: resolvedRegion.regionId, regionId: resolvedRegion.regionId,
latitude: currentLocation.latitude, latitude: currentLocation.latitude,
longitude: currentLocation.longitude, longitude: currentLocation.longitude,
@ -179,9 +235,8 @@ const AddressForm: React.FC<AddressFormProps> = ({
phone: values.phone, phone: values.phone,
addressLine1: values.addressLine1, addressLine1: values.addressLine1,
addressLine2: values.addressLine2 || undefined, addressLine2: values.addressLine2 || undefined,
city: values.city, city: cityName || values.city || '',
state: values.state, state: values.state,
pincode: values.pincode,
isDefault: values.isDefault, isDefault: values.isDefault,
latitude: currentLocation.latitude, latitude: currentLocation.latitude,
longitude: currentLocation.longitude, longitude: currentLocation.longitude,
@ -240,15 +295,47 @@ const AddressForm: React.FC<AddressFormProps> = ({
value={values.addressLine2} value={values.addressLine2}
/> />
<MyTextInput {/* City is a picker over the serviceable towns (regions). */}
placeholder="City" <View style={tw`mb-1`}>
shrunkPadding={true} <MyText style={tw`text-gray-500 text-xs mb-1`}>City *</MyText>
onChangeText={handleChange('city')} <MyTouchableOpacity
onBlur={handleBlur('city')} testID="address-city"
value={values.city} onPress={() => setCityOpen((prev) => !prev)}
disabled={true} style={tw`border border-gray-200 rounded-lg p-3 flex-row items-center justify-between bg-gray-50`}
/> >
{touched.city && errors.city && <MyText style={tw`text-red-500 mb-2`}>{errors.city}</MyText>} <MyText style={tw`${cityName ? 'text-gray-900' : 'text-gray-400'}`}>
{cityName || 'Select town'}
</MyText>
<MaterialIcons
name={cityOpen ? 'keyboard-arrow-up' : 'keyboard-arrow-down'}
size={20}
color="#9CA3AF"
/>
</MyTouchableOpacity>
{cityOpen && (
<View style={tw`border border-gray-200 rounded-lg mt-1 bg-white overflow-hidden`}>
{regions.map((region) => (
<MyTouchableOpacity
key={region.id}
testID={`address-city-option-${region.id}`}
onPress={() => {
setCityOpen(false);
void handleCityChange(region.id);
}}
style={tw`p-3 border-b border-gray-50 flex-row items-center justify-between`}
>
<MyText style={tw`text-gray-800`}>{region.name}</MyText>
{resolvedRegion?.regionId === region.id && (
<MaterialIcons name="check" size={18} color="#3B82F6" />
)}
</MyTouchableOpacity>
))}
{regions.length === 0 && (
<MyText style={tw`p-3 text-gray-400 text-sm`}>No towns available</MyText>
)}
</View>
)}
</View>
<MyTextInput <MyTextInput
placeholder="State" placeholder="State"
@ -260,42 +347,44 @@ const AddressForm: React.FC<AddressFormProps> = ({
/> />
{touched.state && errors.state && <MyText style={tw`text-red-500 mb-2`}>{errors.state}</MyText>} {touched.state && errors.state && <MyText style={tw`text-red-500 mb-2`}>{errors.state}</MyText>}
<MyTextInput {/* Location is mandatory: attach the device location or pick on the map. */}
placeholder="Pincode"
shrunkPadding={true}
keyboardType="numeric"
onChangeText={handleChange('pincode')}
onBlur={handleBlur('pincode')}
value={values.pincode}
disabled={true}
/>
{touched.pincode && errors.pincode && <MyText style={tw`text-red-500 mb-2`}>{errors.pincode}</MyText>}
{/* Location is mandatory and drives the region: attach or pick on map. */}
<View style={tw`mt-1`}> <View style={tw`mt-1`}>
<MyText style={tw`text-gray-500 text-xs mb-2`}>Delivery Location *</MyText> <MyText style={tw`text-gray-500 text-xs mb-2`}>Delivery Location *</MyText>
<LocationAttacher {currentLocation ? (
initialLocation={currentLocation || undefined} <>
showGoogleMapsOption={false} <View style={tw`flex-row items-center`}>
onLocationChange={(location) => { <MaterialIcons name="check-circle" size={16} color="#16A34A" />
if (location) void resolveLocation(location); <MyText style={tw`text-green-600 font-bold text-sm ml-1`}>
}} Current Location Attached
disabled={false} </MyText>
/> </View>
<MyTouchableOpacity <MyText style={tw`text-gray-500 text-xs mt-1`}>
testID="address-select-from-map" 📍 {currentLocation.latitude.toFixed(5)}, {currentLocation.longitude.toFixed(5)}
onPress={() => setMapOpen(true)} </MyText>
style={tw`flex-row items-center mb-1`} <MyTouchableOpacity
> testID="address-choose-location"
<MaterialIcons name="map" size={18} color="#3B82F6" /> onPress={() => setMapOpen(true)}
<MyText style={tw`text-blue-500 text-sm font-medium ml-1`}>Select on map</MyText> style={tw`flex-row items-center mt-2`}
</MyTouchableOpacity> >
<MaterialIcons name="map" size={18} color="#3B82F6" />
{currentLocation && ( <MyText style={tw`text-blue-500 text-sm font-medium ml-1`}>
<MyText style={tw`text-gray-500 text-xs mt-1`}> Choose Another Location in Map
📍 {currentLocation.latitude.toFixed(5)}, {currentLocation.longitude.toFixed(5)} </MyText>
</MyText> </MyTouchableOpacity>
</>
) : (
<MyTouchableOpacity
testID="address-attach-location"
onPress={() => setMapOpen(true)}
style={tw`flex-row items-center`}
>
<MaterialIcons name="place" size={18} color="#3B82F6" />
<MyText style={tw`text-blue-500 text-sm font-medium ml-1`}>
Attach Location in map
</MyText>
</MyTouchableOpacity>
)} )}
{locationError && ( {locationError && (
<MyText style={tw`text-red-500 text-sm mt-1`}>{locationError}</MyText> <MyText style={tw`text-red-500 text-sm mt-1`}>{locationError}</MyText>
)} )}
@ -311,14 +400,20 @@ const AddressForm: React.FC<AddressFormProps> = ({
<MyTouchableOpacity <MyTouchableOpacity
testID="address-submit" testID="address-submit"
style={tw`bg-indigo-600 p-3 rounded ${isSubmitting ? 'opacity-50' : ''}`} style={tw`bg-indigo-600 p-3 rounded ${isSubmitting || !currentLocation ? 'opacity-50' : ''}`}
onPress={() => handleSubmit()} onPress={() => handleSubmit()}
disabled={isSubmitting} disabled={isSubmitting || !currentLocation}
> >
<MyText style={tw`text-white text-center font-bold`}> <MyText style={tw`text-white text-center font-bold`}>
{isSubmitting ? (isEdit ? 'Updating...' : 'Adding...') : (isEdit ? 'Update Address' : 'Add Address')} {isSubmitting ? (isEdit ? 'Updating...' : 'Adding...') : (isEdit ? 'Update Address' : 'Add Address')}
</MyText> </MyText>
</MyTouchableOpacity> </MyTouchableOpacity>
{!currentLocation && touched.name && (
<MyText style={tw`text-red-500 text-sm text-center`}>
Attach a location to add address
</MyText>
)}
<View style={tw`h-8`}></View> <View style={tw`h-8`}></View>
</View> </View>
)} )}

View file

@ -12,9 +12,8 @@ const formatAddress = (address: {
addressLine1: string addressLine1: string
addressLine2?: string | null addressLine2?: string | null
city: string 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. * Location bar shown at the top of every top-level tab screen.

View file

@ -23,13 +23,22 @@ interface ChooserAddress {
addressLine2: string | null addressLine2: string | null
city: string city: string
state: string state: string
pincode: string
isDefault: boolean isDefault: boolean
} }
interface LocationFallbackFlowProps { interface LocationFallbackFlowProps {
/** Present when hosted in a sheet; lets the caller dismiss after a choice. */ /** Present when hosted in a sheet; lets the caller dismiss after a choice. */
onClose?: () => void 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 * (which switches the browsing region + bound and clears the cart) or adds a
* new one (coordinates required, via attach-location or the map). * new one (coordinates required, via attach-location or the map).
*/ */
const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({ onClose }) => { const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({ onClose, notice, onOpenSettings }) => {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const utils = trpc.useUtils() const utils = trpc.useUtils()
const auth = useAuthOptional() const auth = useAuthOptional()
@ -115,7 +124,6 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({ onClose })
addressLine2: address.addressLine2 || undefined, addressLine2: address.addressLine2 || undefined,
city: address.city, city: address.city,
state: address.state, state: address.state,
pincode: address.pincode,
isDefault: true, isDefault: true,
latitude: address.latitude ?? undefined, latitude: address.latitude ?? undefined,
longitude: address.longitude ?? undefined, longitude: address.longitude ?? undefined,
@ -177,6 +185,25 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({ onClose })
)} )}
</View> </View>
{notice && (
<View style={tw`mx-5 mb-3 bg-amber-50 border border-amber-200 rounded-xl p-3`}>
<View style={tw`flex-row`}>
<MaterialIcons name="location-off" size={18} color="#B45309" style={tw`mr-2`} />
<MyText style={tw`text-amber-800 text-sm flex-1`}>{notice}</MyText>
</View>
{onOpenSettings && (
<MyTouchableOpacity
testID="open-location-settings"
onPress={onOpenSettings}
activeOpacity={0.85}
style={tw`mt-3 bg-amber-600 px-4 py-2 rounded-lg self-start`}
>
<MyText style={tw`text-white font-bold text-sm`}>Open location settings</MyText>
</MyTouchableOpacity>
)}
</View>
)}
{message && ( {message && (
<View style={tw`mx-5 mb-2 bg-red-50 border border-red-200 rounded-xl p-3`}> <View style={tw`mx-5 mb-2 bg-red-50 border border-red-200 rounded-xl p-3`}>
<MyText style={tw`text-red-600 text-sm`}>{message}</MyText> <MyText style={tw`text-red-600 text-sm`}>{message}</MyText>
@ -207,7 +234,7 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({ onClose })
</View> </View>
<MyText style={tw`text-gray-600 text-sm`}> <MyText style={tw`text-gray-600 text-sm`}>
{address.addressLine1} {address.addressLine1}
{address.addressLine2 ? `, ${address.addressLine2}` : ''}, {address.city} - {address.pincode} {address.addressLine2 ? `, ${address.addressLine2}` : ''}, {address.city}
</MyText> </MyText>
</MyTouchableOpacity> </MyTouchableOpacity>

View file

@ -43,12 +43,12 @@ export interface UseRegionResult {
bound: RegionBoundSummary | null bound: RegionBoundSummary | null
/** Monotonic marker bumped on every region change; use it to ignore stale responses. */ /** Monotonic marker bumped on every region change; use it to ignore stale responses. */
regionGeneration: number regionGeneration: number
/** True once the persisted region has finished loading from storage. */ /** Always true: the region store is in-memory (not persisted). */
hydrated: boolean hydrated: boolean
/** Latest device coordinates, if the launch fix succeeded. */ /** Latest device coordinates, if the launch fix succeeded. */
coords: { latitude: number; longitude: number } | null coords: { latitude: number; longitude: number } | null
/** Current state of the launch location read. */ /** 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 * 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 * 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 { export function useRegion(): UseRegionResult {
const queryClient = useQueryClient() 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 region = useRegionStore((state) => state.selectedRegion)
const regionId = useRegionStore((state) => state.selectedRegionId) const regionId = useRegionStore((state) => state.selectedRegionId)
@ -79,19 +81,26 @@ export function useRegion(): UseRegionResult {
const startTracking = useLocationStore((state) => state.start) const startTracking = useLocationStore((state) => state.start)
const refreshTracking = useLocationStore((state) => state.refresh) const refreshTracking = useLocationStore((state) => state.refresh)
const [hydrated, setHydrated] = useState<boolean>(() => // The region store is in-memory (not persisted), so there is nothing to
useRegionStore.persist.hasHydrated() // hydrate before we can decide.
) const hydrated = true
// True once the launch location check has a definitive outcome. // True once the launch location check has a definitive outcome.
const [startupResolved, setStartupResolved] = useState(false) const [startupResolved, setStartupResolved] = useState(false)
useEffect(() => { // The user's default address — the anchor for the startup region decision.
if (useRegionStore.persist.hasHydrated()) { const defaultAddressQuery = trpc.user.address.getDefaultAddress.useQuery(undefined, {
setHydrated(true) enabled: hydrated && isAuthenticated,
return staleTime: 60000,
} })
return useRegionStore.persist.onFinishHydration(() => setHydrated(true)) 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 // 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 // region, else the region's effective bound. Derived server-side (the client
@ -135,18 +144,37 @@ export function useRegion(): UseRegionResult {
refetchOnWindowFocus: false, 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(() => { useEffect(() => {
if (!hydrated || startupResolved) return if (!hydrated || startupResolved) return
const resolved = resolution.data const resolved = resolution.data
const terminal = const locationSettled =
resolved != null || resolved != null ||
resolution.isFetched || resolution.isFetched ||
resolution.isError || resolution.isError ||
locationStatus === 'denied' || locationStatus === 'denied' ||
locationStatus === 'services-off' ||
locationStatus === 'unavailable' || locationStatus === 'unavailable' ||
locationStatus === 'error' 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) setStartupResolved(true)
@ -157,13 +185,42 @@ export function useRegion(): UseRegionResult {
// Respect a manual pick made before the fix resolved. // Respect a manual pick made before the fix resolved.
const userChangedRegion = const userChangedRegion =
startupLaunchRegionId !== undefined && startupLaunchRegionId !== regionId startupLaunchRegionId !== undefined && startupLaunchRegionId !== regionId
if (resolved?.region && !userChangedRegion) { if (userChangedRegion) return
if (resolved.region.id !== regionId) {
// New region -> full switch (clears carts, refreshes regional data). 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) void confirmRegionSwitch(resolved.region, queryClient, resolved.bound?.id ?? null)
} else if (resolved.bound && resolved.bound.id !== boundId) { } 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) setRegion(resolved.region, resolved.bound.id)
} }
} }
@ -177,7 +234,13 @@ export function useRegion(): UseRegionResult {
regionId, regionId,
boundId, boundId,
setRegion, setRegion,
clearRegion,
queryClient, queryClient,
isAuthenticated,
isAuthLoading,
defaultAddressQuery.isLoading,
defaultAddress,
regions,
]) ])
// Safety net: a hanging resolve must not strand the first-run spinner. // Safety net: a hanging resolve must not strand the first-run spinner.

View file

@ -14,7 +14,6 @@ export interface PendingAddressInput {
addressLine2?: string addressLine2?: string
city: string city: string
state: string state: string
pincode: string
isDefault?: boolean isDefault?: boolean
latitude: number latitude: number
longitude: number longitude: number

View file

@ -14,7 +14,8 @@ export type LocationStatus =
| 'locating' // permission requested / waiting for the fix | 'locating' // permission requested / waiting for the fix
| 'granted' // coordinates available | 'granted' // coordinates available
| 'denied' // foreground permission refused | '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' | 'error'
export interface Coords { export interface Coords {
@ -95,6 +96,7 @@ export const useLocationStore = create<LocationStoreState>((set, get) => ({
if (token !== activeToken) return if (token !== activeToken) return
if (status !== 'granted') { if (status !== 'granted') {
console.log('[user-ui] location permission denied')
set({ status: 'denied', coords: null, error: null }) set({ status: 'denied', coords: null, error: null })
return return
} }
@ -107,7 +109,8 @@ export const useLocationStore = create<LocationStoreState>((set, get) => ({
: true : true
if (token !== activeToken) return if (token !== activeToken) return
if (!servicesEnabled) { 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 return
} }
@ -116,9 +119,12 @@ export const useLocationStore = create<LocationStoreState>((set, get) => ({
FIRST_FIX_TIMEOUT_MS FIRST_FIX_TIMEOUT_MS
) )
if (token !== activeToken) return 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) { } catch (err) {
if (token !== activeToken) return if (token !== activeToken) return
console.log('[user-ui] location unavailable', err instanceof Error ? err.message : err)
set({ set({
status: 'unavailable', status: 'unavailable',
coords: null, coords: null,

View file

@ -1,19 +1,21 @@
import { create } from 'zustand' import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { StorageServiceCasual } from 'common-ui'
import type { RegionSummary } from '@packages/shared' import type { RegionSummary } from '@packages/shared'
// Browsing region — the single region the user is currently shopping in. // Browsing region — the 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 // Deliberately NOT persisted: at each launch the region is re-derived from the
// change so stale regional responses can be ignored. // 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 { interface RegionStore {
selectedRegionId: number | null selectedRegionId: number | null
selectedRegion: RegionSummary | null selectedRegion: RegionSummary | null
/** /**
* The bound whose consts the client should read for this region. Resolved * The bound whose consts the client should read for this region. Resolved
* from device location (the containing bound) or from the region's effective * from device location (the containing bound) or from a chosen address's
* bound on a manual pick. `null` until known. * bound. `null` until known.
*/ */
selectedBoundId: number | null selectedBoundId: number | null
regionGeneration: number regionGeneration: number
@ -21,62 +23,44 @@ interface RegionStore {
clearRegion: () => void clearRegion: () => void
} }
export const useRegionStore = create<RegionStore>()( export const useRegionStore = create<RegionStore>((set) => ({
persist( selectedRegionId: null,
(set) => ({ selectedRegion: null,
selectedRegionId: null, selectedBoundId: null,
selectedRegion: null, regionGeneration: 0,
selectedBoundId: null, setRegion: (region, boundId = null) =>
regionGeneration: 0, set((state) => {
setRegion: (region, boundId = null) => // No-op when nothing actually changed: keeps regionGeneration stable
set((state) => { // and prevents effect loops that re-apply the same region.
// No-op when nothing actually changed: keeps regionGeneration stable if (
// and prevents effect loops that re-apply the same region. state.selectedRegionId === region.id &&
if ( state.selectedBoundId === boundId &&
state.selectedRegionId === region.id && state.selectedRegion?.name === region.name &&
state.selectedBoundId === boundId && state.selectedRegion?.description === region.description
state.selectedRegion?.name === region.name && ) {
state.selectedRegion?.description === region.description return state
) { }
return state return {
} selectedRegionId: region.id,
return { selectedRegion: region,
selectedRegionId: region.id, selectedBoundId: boundId,
selectedRegion: region, regionGeneration: state.regionGeneration + 1,
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,
}
}),
}), }),
{ clearRegion: () =>
name: 'freshyo-region', set((state) => {
version: 1, if (
storage: createJSONStorage<RegionStore>(() => StorageServiceCasual), state.selectedRegionId == null &&
partialize: (state) => ({ state.selectedRegion == null &&
selectedRegionId: state.selectedRegionId, state.selectedBoundId == null
selectedRegion: state.selectedRegion, ) {
selectedBoundId: state.selectedBoundId, return state
regionGeneration: state.regionGeneration, }
// Functions are dropped from the persisted payload. return {
setRegion: state.setRegion, selectedRegionId: null,
clearRegion: state.clearRegion, selectedRegion: null,
}), selectedBoundId: null,
} regionGeneration: state.regionGeneration + 1,
) }
) }),
}))

View file

@ -74,7 +74,6 @@ describe('AddressForm', () => {
addressLine1: '9 Office St', addressLine1: '9 Office St',
city: 'Hyderabad', city: 'Hyderabad',
state: 'Telangana', state: 'Telangana',
pincode: '500002',
isDefault: false, isDefault: false,
} as never } as never
} }

View file

@ -25,7 +25,6 @@ const ADDRESSES = {
addressLine2: 'Apt 4', addressLine2: 'Apt 4',
city: 'Hyderabad', city: 'Hyderabad',
state: 'Telangana', state: 'Telangana',
pincode: '500001',
isDefault: false, isDefault: false,
}, },
{ {
@ -36,7 +35,6 @@ const ADDRESSES = {
addressLine2: null, addressLine2: null,
city: 'Hyderabad', city: 'Hyderabad',
state: 'Telangana', state: 'Telangana',
pincode: '500002',
isDefault: true, isDefault: true,
}, },
], ],

View file

@ -27,7 +27,6 @@ const PROCEDURES = {
addressLine2: null, addressLine2: null,
city: 'Hyderabad', city: 'Hyderabad',
state: 'Telangana', state: 'Telangana',
pincode: '500001',
isDefault: true, isDefault: true,
}, },
], ],

View file

@ -54,7 +54,6 @@ const ADDRESSES = {
addressLine2: 'Apt 4', addressLine2: 'Apt 4',
city: 'Hyderabad', city: 'Hyderabad',
state: 'Telangana', state: 'Telangana',
pincode: '500001',
isDefault: true, isDefault: true,
}, },
], ],

View file

@ -28,7 +28,6 @@ const ADDRESS = {
addressLine2: 'Apt 4', addressLine2: 'Apt 4',
city: 'Hyderabad', city: 'Hyderabad',
state: 'Telangana', state: 'Telangana',
pincode: '500001',
isDefault: false, isDefault: false,
} }

View file

@ -44,7 +44,6 @@ const ADDRESS = {
addressLine2: 'Apt 4', addressLine2: 'Apt 4',
city: 'Hyderabad', city: 'Hyderabad',
state: 'Telangana', state: 'Telangana',
pincode: '500001',
isDefault: false, isDefault: false,
} }

View file

@ -1,5 +1,6 @@
import React, { useCallback, useEffect, useState } from 'react' import React, { useCallback, useEffect, useState } from 'react'
import { trpc } from '../lib/trpc-client' import { trpc } from '../lib/trpc-client'
import { useRegionStore } from '../lib/stores/region-store'
import { p, pInput as PInput, MyButton, div } from 'web-components' import { p, pInput as PInput, MyButton, div } from 'web-components'
import { MapPin } from 'lucide-react' import { MapPin } from 'lucide-react'
import * as Yup from 'yup' 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'), phone: Yup.string().required('Phone is required').matches(/^\d{10}$/, 'Phone must be 10 digits'),
addressLine1: Yup.string().required('Address Line 1 is required'), addressLine1: Yup.string().required('Address Line 1 is required'),
addressLine2: Yup.string(), addressLine2: Yup.string(),
city: Yup.string().required('City is required'),
state: Yup.string().required('State 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(), isDefault: Yup.boolean(),
}) })
@ -30,19 +29,55 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
? { latitude: initialValues.latitude, longitude: initialValues.longitude } ? { latitude: initialValues.latitude, longitude: initialValues.longitude }
: null : null
) )
// Region is derived from the coordinates, never picked directly. const browsingRegionId = useRegionStore((state) => state.selectedRegionId)
const [resolvedRegion, setResolvedRegion] = useState<ResolvedRegion | null>(null) 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<ResolvedRegion | null>(() =>
browsingRegionId != null
? { regionId: browsingRegionId, boundId: browsingRegion?.effectiveBoundId ?? null }
: null
)
const utils = trpc.useUtils() 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(() => ({ const [values, setValues] = useState(() => ({
name: initialValues?.name || '', name: initialValues?.name || '',
phone: initialValues?.phone || '', phone: initialValues?.phone || '',
addressLine1: initialValues?.addressLine1 || '', addressLine1: initialValues?.addressLine1 || '',
addressLine2: initialValues?.addressLine2 || '', addressLine2: initialValues?.addressLine2 || '',
city: initialValues?.city || 'Mahabubnagar', city: initialValues?.city || '',
state: initialValues?.state || 'Telangana', state: initialValues?.state || 'Telangana',
pincode: initialValues?.pincode || '509001',
isDefault: initialValues?.isDefault || false, isDefault: initialValues?.isDefault || false,
googleMapsUrl: initialValues?.googleMapsUrl || '', googleMapsUrl: initialValues?.googleMapsUrl || '',
})) }))
@ -84,6 +119,18 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
// eslint-disable-next-line react-hooks/exhaustive-deps // 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. // Coordinates picked on the embedded map are delivered via postMessage.
useEffect(() => { useEffect(() => {
if (!mapOpen) return 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.') setSubmitError('Please use your current location or select one on the map.')
return return
} }
if (!resolvedRegion) { if (!resolvedRegion || locationError) {
setSubmitError(locationError || 'Please choose a location inside our delivery area.') setSubmitError(locationError || 'Please choose a town and a location inside it.')
return return
} }
setIsSubmitting(true) setIsSubmitting(true)
@ -170,6 +217,7 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
const payload = { const payload = {
...values, ...values,
city: cityName || values.city || '',
regionId: resolvedRegion.regionId, regionId: resolvedRegion.regionId,
latitude: currentLocation.latitude, latitude: currentLocation.latitude,
longitude: currentLocation.longitude, longitude: currentLocation.longitude,
@ -199,7 +247,7 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
<div className="mb-4 rounded-lg border border-amber-200 bg-amber-50 p-3"> <div className="mb-4 rounded-lg border border-amber-200 bg-amber-50 p-3">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span className="text-amber-600">ℹ️</span> <span className="text-amber-600">ℹ️</span>
<p className="flex-1 text-sm text-amber-800">We currently serve only in Mahabubnagar town</p> <p className="flex-1 text-sm text-amber-800">We currently serve only in the towns listed below</p>
</div> </div>
</div> </div>
@ -251,44 +299,63 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<div> <div>
<PInput placeholder="City" value={values.city} disabled className="bg-gray-100" /> <label className="mb-1 block text-xs text-gray-500">City *</label>
<select
value={resolvedRegion?.regionId ?? ''}
onChange={(e) => void handleCityChange(Number(e.target.value))}
className="w-full rounded-lg border border-gray-200 bg-gray-50 p-3 text-base outline-none"
>
<option value="">Select town</option>
{regions.map((region) => (
<option key={region.id} value={region.id}>
{region.name}
</option>
))}
</select>
</div> </div>
<div> <div>
<PInput placeholder="State" value={values.state} disabled className="bg-gray-100" /> <PInput placeholder="State" value={values.state} disabled className="bg-gray-100" />
</div> </div>
</div> </div>
<div> {/* Location is mandatory: attach the device location or pick on the map. */}
<PInput placeholder="Pincode" value={values.pincode} disabled className="bg-gray-100" />
</div>
{/* Location is mandatory and drives the region. */}
<div className="rounded-lg border border-gray-200 p-3"> <div className="rounded-lg border border-gray-200 p-3">
<p className="mb-2 text-xs text-gray-500">Delivery Location *</p> <p className="mb-2 text-xs text-gray-500">Delivery Location *</p>
<div className="flex flex-col gap-2"> {currentLocation ? (
<button <div className="flex flex-col gap-2">
type="button" <p className="flex items-center gap-2 text-sm font-bold text-green-600">
onClick={handleDetectLocation} <MapPin className="h-4 w-4" /> Current Location Attached
disabled={locating} </p>
className="flex items-center gap-2 text-left text-sm font-medium text-blue-500 disabled:opacity-50" <p className="text-xs text-gray-500">
> 📍 {currentLocation.latitude.toFixed(5)}, {currentLocation.longitude.toFixed(5)}
<MapPin className="h-4 w-4" /> </p>
{locating ? 'Fetching location…' : 'Use my current location'} <button
</button> type="button"
<button onClick={() => setMapOpen(true)}
type="button" className="flex items-center gap-2 text-left text-sm font-medium text-blue-500"
onClick={() => setMapOpen(true)} >
className="flex items-center gap-2 text-left text-sm font-medium text-blue-500" <MapPin className="h-4 w-4" /> Choose Another Location in Map
> </button>
<MapPin className="h-4 w-4" /> </div>
Select on map ) : (
</button> <div className="flex flex-col gap-2">
</div> <button
type="button"
{currentLocation && ( onClick={() => setMapOpen(true)}
<p className="mt-2 text-xs text-gray-500"> className="flex items-center gap-2 text-left text-sm font-medium text-blue-500"
📍 {currentLocation.latitude.toFixed(5)}, {currentLocation.longitude.toFixed(5)} >
</p> <MapPin className="h-4 w-4" /> Attach Location in map
</button>
<button
type="button"
onClick={handleDetectLocation}
disabled={locating}
className="flex items-center gap-2 text-left text-xs font-medium text-gray-500 disabled:opacity-50"
>
<MapPin className="h-4 w-4" />
{locating ? 'Fetching location…' : 'Use my current location'}
</button>
</div>
)} )}
{locationError && <p className="mt-1 text-sm text-red-500">{locationError}</p>} {locationError && <p className="mt-1 text-sm text-red-500">{locationError}</p>}
</div> </div>
@ -307,7 +374,7 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
fullWidth fullWidth
textContent={isSubmitting ? (isEdit ? 'Updating...' : 'Adding...') : (isEdit ? 'Update Address' : 'Add Address')} textContent={isSubmitting ? (isEdit ? 'Updating...' : 'Adding...') : (isEdit ? 'Update Address' : 'Add Address')}
onClick={handleSubmit} onClick={handleSubmit}
disabled={isSubmitting} disabled={isSubmitting || !currentLocation}
className="bg-brand-500 text-white" className="bg-brand-500 text-white"
/> />
</div> </div>

View file

@ -151,7 +151,7 @@ export function CheckoutAddressSelector({ onAddressSelect, onAddAddress, onEditA
{address.addressLine2 ? `, ${address.addressLine2}` : ''} {address.addressLine2 ? `, ${address.addressLine2}` : ''}
</p> </p>
<p className="text-sm text-gray-600"> <p className="text-sm text-gray-600">
{address.city}, {address.state} - {address.pincode} {address.city}, {address.state}
</p> </p>
<p className="mt-1 text-xs text-gray-500"> <p className="mt-1 text-xs text-gray-500">
Phone: {address.phone} Phone: {address.phone}

View file

@ -12,7 +12,7 @@ export const Route = createFileRoute('/me/addresses')({ component: AddressesPage
// Address view — required core of the shared UserAddress + optional geo fields // Address view — required core of the shared UserAddress + optional geo fields
type Address = Pick< type Address = Pick<
UserAddress, UserAddress,
'id' | 'regionId' | 'name' | 'phone' | 'addressLine1' | 'addressLine2' | 'city' | 'state' | 'pincode' | 'isDefault' 'id' | 'regionId' | 'name' | 'phone' | 'addressLine1' | 'addressLine2' | 'city' | 'state' | 'isDefault'
> & { > & {
latitude?: number | null latitude?: number | null
longitude?: number | null longitude?: number | null
@ -20,7 +20,7 @@ type Address = Pick<
} }
const formatAddress = (addr: Address) => { 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({ function AddressCard({
@ -143,7 +143,6 @@ function AddressesPage() {
addressLine2: addressToUpdate.addressLine2 || undefined, addressLine2: addressToUpdate.addressLine2 || undefined,
city: addressToUpdate.city, city: addressToUpdate.city,
state: addressToUpdate.state, state: addressToUpdate.state,
pincode: addressToUpdate.pincode,
isDefault: true, isDefault: true,
// Keep the stored coordinates so the bound is not re-derived from a fallback. // Keep the stored coordinates so the bound is not re-derived from a fallback.
latitude: addressToUpdate.latitude ?? undefined, latitude: addressToUpdate.latitude ?? undefined,
@ -245,7 +244,6 @@ function AddressesPage() {
addressLine2: editingAddress.addressLine2 || '', addressLine2: editingAddress.addressLine2 || '',
city: editingAddress.city, city: editingAddress.city,
state: editingAddress.state, state: editingAddress.state,
pincode: editingAddress.pincode,
isDefault: editingAddress.isDefault, isDefault: editingAddress.isDefault,
latitude: editingAddress.googleMapsUrl latitude: editingAddress.googleMapsUrl
? undefined ? undefined

View file

@ -3746,3 +3746,250 @@ user-ui
+ loadGoogleMaps now resolves Map/Marker via google.maps.importLibrary('maps'|'marker') + loadGoogleMaps now resolves Map/Marker via google.maps.importLibrary('maps'|'marker')
+ GoogleMapsNamespace type narrowed to { importLibrary?, __ib__? } + GoogleMapsNamespace type narrowed to { importLibrary?, __ib__? }
No dependency added. No migration. No tests run. 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', <err>)
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'; <PInput placeholder="Pincode" .../> 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 <select> over regions; handleCityChange via
common.resolveBound; city from the resolved region; notice copy updated)
State stays hardcoded 'Telangana' and uneditable in both forms.
No dependency added. No migration. No tests run.
2026-10-13 17:58:16 Address form (user-ui + web-ui): pre-select the City from the app's current region.
1/2 apps/user-ui/src/components/AddressForm.tsx:
+ useRegion(): initialise resolvedRegion from the browsing region (regionId + boundId) when one exists and there
are no prefilled coords; an effect fills it in if the region becomes known later
2/2 apps/web-ui/src/components/AddressForm.tsx:
+ useRegionStore(): initialise resolvedRegion from selectedRegionId (bound = selectedRegion.effectiveBoundId ??
null); same later-fill effect
No dependency added. No migration. No tests run.
2026-10-13 18:03:01 Address form location UX (user-ui + web-ui).
- If a location is attached: show "Current Location Attached" + a "Choose Another Location in Map" button.
- If not: show an "Attach Location in map" button.
- The "Add Address" button is disabled until a location is attached.
1/2 apps/user-ui/src/components/AddressForm.tsx:
+ dropped LocationAttacher; default the address location to the app's device coords (useLocationStore) when
available (and no initialValues coords); attach via the map picker otherwise
+ submit button disabled while currentLocation is null
2/2 apps/web-ui/src/components/AddressForm.tsx: same two-state UI; kept a small "Use my current location"
(browser geolocation) action in the no-location state; submit disabled until a location is attached
No dependency added. No migration. No tests run.
2026-10-13 18:08:11 Address form (user-ui): hint under the submit button when no location is attached.
apps/user-ui/src/components/AddressForm.tsx:
+ below the Add Address button, when !currentLocation and the first field (Name) has been touched, show a red
"Attach a location to add address"
No dependency added. No migration. No tests run.

View file

@ -200,7 +200,6 @@ export async function getOrderDetails(orderId: number): Promise<AdminOrderDetail
line2: orderData.address.addressLine2, line2: orderData.address.addressLine2,
city: orderData.address.city, city: orderData.address.city,
state: orderData.address.state, state: orderData.address.state,
pincode: orderData.address.pincode,
phone: orderData.address.phone, phone: orderData.address.phone,
}, },
slotInfo: orderData.slot slotInfo: orderData.slot
@ -373,9 +372,7 @@ export async function getSlotOrders(slotId: string): Promise<AdminGetSlotOrdersR
customerName: order.user.name || order.user.mobile+'', customerName: order.user.name || order.user.mobile+'',
address: `${order.address.addressLine1}${ address: `${order.address.addressLine1}${
order.address.addressLine2 ? `, ${order.address.addressLine2}` : '' order.address.addressLine2 ? `, ${order.address.addressLine2}` : ''
}, ${order.address.city}, ${order.address.state} - ${ }, ${order.address.city}, ${order.address.state}, Phone: ${order.address.phone}`,
order.address.pincode
}, Phone: ${order.address.phone}`,
addressId: order.addressId, addressId: order.addressId,
latitude: order.address.adminLatitude ?? order.address.latitude, latitude: order.address.adminLatitude ?? order.address.latitude,
longitude: order.address.adminLongitude ?? order.address.longitude, longitude: order.address.adminLongitude ?? order.address.longitude,
@ -515,9 +512,7 @@ export async function getAllOrders(input: GetAllOrdersInput): Promise<AdminGetAl
customerMobile: order.user.mobile, customerMobile: order.user.mobile,
address: `${order.address.addressLine1}${ address: `${order.address.addressLine1}${
order.address.addressLine2 ? `, ${order.address.addressLine2}` : '' order.address.addressLine2 ? `, ${order.address.addressLine2}` : ''
}, ${order.address.city}, ${order.address.state} - ${ }, ${order.address.city}, ${order.address.state}, Phone: ${order.address.phone}`,
order.address.pincode
}, Phone: ${order.address.phone}`,
addressId: order.addressId, addressId: order.addressId,
latitude: order.address.adminLatitude ?? order.address.latitude, latitude: order.address.adminLatitude ?? order.address.latitude,
longitude: order.address.adminLongitude ?? order.address.longitude, longitude: order.address.adminLongitude ?? order.address.longitude,

View file

@ -44,7 +44,6 @@ export const addresses = mf.table('addresses', {
addressLine2: varchar('address_line2', { length: 255 }), addressLine2: varchar('address_line2', { length: 255 }),
city: varchar('city', { length: 100 }).notNull(), city: varchar('city', { length: 100 }).notNull(),
state: varchar('state', { length: 100 }).notNull(), state: varchar('state', { length: 100 }).notNull(),
pincode: varchar('pincode', { length: 10 }).notNull(),
isDefault: boolean('is_default').notNull().default(false), isDefault: boolean('is_default').notNull().default(false),
latitude: real('latitude'), latitude: real('latitude'),
longitude: real('longitude'), longitude: real('longitude'),

View file

@ -15,7 +15,6 @@ const mapUserAddress = (address: AddressRow): UserAddress => ({
addressLine2: address.addressLine2 ?? null, addressLine2: address.addressLine2 ?? null,
city: address.city, city: address.city,
state: address.state, state: address.state,
pincode: address.pincode,
isDefault: address.isDefault, isDefault: address.isDefault,
latitude: address.latitude ?? null, latitude: address.latitude ?? null,
longitude: address.longitude ?? null, longitude: address.longitude ?? null,
@ -63,7 +62,6 @@ export async function createUserAddress(input: {
addressLine2?: string addressLine2?: string
city: string city: string
state: string state: string
pincode: string
isDefault: boolean isDefault: boolean
latitude?: number latitude?: number
longitude?: number longitude?: number
@ -77,7 +75,6 @@ export async function createUserAddress(input: {
addressLine2: input.addressLine2, addressLine2: input.addressLine2,
city: input.city, city: input.city,
state: input.state, state: input.state,
pincode: input.pincode,
isDefault: input.isDefault, isDefault: input.isDefault,
latitude: input.latitude, latitude: input.latitude,
longitude: input.longitude, longitude: input.longitude,
@ -96,7 +93,6 @@ export async function updateUserAddress(input: {
addressLine2?: string addressLine2?: string
city: string city: string
state: string state: string
pincode: string
isDefault: boolean isDefault: boolean
latitude?: number latitude?: number
longitude?: number longitude?: number
@ -110,7 +106,6 @@ export async function updateUserAddress(input: {
addressLine2: input.addressLine2, addressLine2: input.addressLine2,
city: input.city, city: input.city,
state: input.state, state: input.state,
pincode: input.pincode,
isDefault: input.isDefault, isDefault: input.isDefault,
googleMapsUrl: input.googleMapsUrl, googleMapsUrl: input.googleMapsUrl,
latitude: input.latitude, latitude: input.latitude,

View file

@ -558,7 +558,6 @@ export interface OrderWithFullData {
addressLine2: string | null addressLine2: string | null
city: string | null city: string | null
state: string | null state: string | null
pincode: string | null
phone: string | null phone: string | null
} | null } | null
orderItems: Array<{ orderItems: Array<{
@ -585,7 +584,6 @@ export async function getOrdersByIdsWithFullData(
addressLine2: true, addressLine2: true,
city: true, city: true,
state: true, state: true,
pincode: true,
phone: true, phone: true,
}, },
}, },
@ -626,7 +624,6 @@ export async function getOrderByIdWithFullData(
addressLine2: true, addressLine2: true,
city: true, city: true,
state: true, state: true,
pincode: true,
phone: true, phone: true,
}, },
}, },

View file

@ -297,7 +297,6 @@ CREATE TABLE `__new_addresses` (
`address_line2` text, `address_line2` text,
`city` text NOT NULL, `city` text NOT NULL,
`state` text NOT NULL, `state` text NOT NULL,
`pincode` text NOT NULL,
`is_default` integer DEFAULT false NOT NULL, `is_default` integer DEFAULT false NOT NULL,
`latitude` real, `latitude` real,
`longitude` real, `longitude` real,
@ -314,8 +313,8 @@ CREATE TABLE `__new_addresses` (
FOREIGN KEY (`bound_id`) REFERENCES `region_bounds`(`id`) ON UPDATE no action ON DELETE no action FOREIGN KEY (`bound_id`) REFERENCES `region_bounds`(`id`) ON UPDATE no action ON DELETE no action
); );
--> statement-breakpoint --> statement-breakpoint
INSERT INTO `__new_addresses` (`id`,`user_id`,`name`,`phone`,`address_line1`,`address_line2`,`city`,`state`,`pincode`,`is_default`,`latitude`,`longitude`,`google_maps_url`,`admin_latitude`,`admin_longitude`,`zone_id`,`created_at`,`region_id`,`bound_id`,`vague_backfilled_coords`) INSERT INTO `__new_addresses` (`id`,`user_id`,`name`,`phone`,`address_line1`,`address_line2`,`city`,`state`,`is_default`,`latitude`,`longitude`,`google_maps_url`,`admin_latitude`,`admin_longitude`,`zone_id`,`created_at`,`region_id`,`bound_id`,`vague_backfilled_coords`)
SELECT `id`,`user_id`,`name`,`phone`,`address_line1`,`address_line2`,`city`,`state`,`pincode`,`is_default`,COALESCE(`latitude`, 16.750504),COALESCE(`longitude`, 77.993621),`google_maps_url`,`admin_latitude`,`admin_longitude`,`zone_id`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar'),(SELECT `id` FROM `region_bounds` WHERE `region_id` = (SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') ORDER BY CAST(`priority` AS REAL) ASC LIMIT 1),CASE WHEN `latitude` IS NULL OR `longitude` IS NULL THEN 1 ELSE 0 END FROM `addresses`; SELECT `id`,`user_id`,`name`,`phone`,`address_line1`,`address_line2`,`city`,`state`,`is_default`,COALESCE(`latitude`, 16.750504),COALESCE(`longitude`, 77.993621),`google_maps_url`,`admin_latitude`,`admin_longitude`,`zone_id`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar'),(SELECT `id` FROM `region_bounds` WHERE `region_id` = (SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') ORDER BY CAST(`priority` AS REAL) ASC LIMIT 1),CASE WHEN `latitude` IS NULL OR `longitude` IS NULL THEN 1 ELSE 0 END FROM `addresses`;
--> statement-breakpoint --> statement-breakpoint
CREATE TABLE `__new_coupons` ( CREATE TABLE `__new_coupons` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,

View file

@ -223,7 +223,6 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
line2: orderData.address.addressLine2, line2: orderData.address.addressLine2,
city: orderData.address.city, city: orderData.address.city,
state: orderData.address.state, state: orderData.address.state,
pincode: orderData.address.pincode,
phone: orderData.address.phone, phone: orderData.address.phone,
}, },
slotInfo: orderData.slot slotInfo: orderData.slot
@ -426,9 +425,7 @@ export async function getSlotOrders(regionId: number, slotId: string): Promise<A
customerName: order.user.name || order.user.mobile+'', customerName: order.user.name || order.user.mobile+'',
address: `${order.address.addressLine1}${ address: `${order.address.addressLine1}${
order.address.addressLine2 ? `, ${order.address.addressLine2}` : '' order.address.addressLine2 ? `, ${order.address.addressLine2}` : ''
}, ${order.address.city}, ${order.address.state} - ${ }, ${order.address.city}, ${order.address.state}, Phone: ${order.address.phone}`,
order.address.pincode
}, Phone: ${order.address.phone}`,
addressId: order.addressId, addressId: order.addressId,
latitude: order.address.adminLatitude ?? order.address.latitude, latitude: order.address.adminLatitude ?? order.address.latitude,
longitude: order.address.adminLongitude ?? order.address.longitude, longitude: order.address.adminLongitude ?? order.address.longitude,
@ -590,9 +587,7 @@ export async function getAllOrders(regionId: number, input: GetAllOrdersInput):
customerMobile: order.user.mobile, customerMobile: order.user.mobile,
address: `${order.address.addressLine1}${ address: `${order.address.addressLine1}${
order.address.addressLine2 ? `, ${order.address.addressLine2}` : '' order.address.addressLine2 ? `, ${order.address.addressLine2}` : ''
}, ${order.address.city}, ${order.address.state} - ${ }, ${order.address.city}, ${order.address.state}, Phone: ${order.address.phone}`,
order.address.pincode
}, Phone: ${order.address.phone}`,
addressId: order.addressId, addressId: order.addressId,
latitude: order.address.adminLatitude ?? order.address.latitude, latitude: order.address.adminLatitude ?? order.address.latitude,
longitude: order.address.adminLongitude ?? order.address.longitude, longitude: order.address.adminLongitude ?? order.address.longitude,

View file

@ -116,7 +116,6 @@ export const addresses = sqliteTable('addresses', {
addressLine2: text('address_line2'), addressLine2: text('address_line2'),
city: text('city').notNull(), city: text('city').notNull(),
state: text('state').notNull(), state: text('state').notNull(),
pincode: text('pincode').notNull(),
isDefault: integer('is_default', { mode: 'boolean' }).notNull().default(false), isDefault: integer('is_default', { mode: 'boolean' }).notNull().default(false),
latitude: real('latitude'), latitude: real('latitude'),
longitude: real('longitude'), longitude: real('longitude'),

View file

@ -17,7 +17,6 @@ const mapUserAddress = (address: AddressRow): UserAddress => ({
addressLine2: address.addressLine2 ?? null, addressLine2: address.addressLine2 ?? null,
city: address.city, city: address.city,
state: address.state, state: address.state,
pincode: address.pincode,
isDefault: address.isDefault, isDefault: address.isDefault,
latitude: address.latitude ?? null, latitude: address.latitude ?? null,
longitude: address.longitude ?? null, longitude: address.longitude ?? null,
@ -68,7 +67,6 @@ export async function createUserAddress(input: {
addressLine2?: string addressLine2?: string
city: string city: string
state: string state: string
pincode: string
isDefault: boolean isDefault: boolean
latitude?: number latitude?: number
longitude?: number longitude?: number
@ -84,7 +82,6 @@ export async function createUserAddress(input: {
addressLine2: input.addressLine2, addressLine2: input.addressLine2,
city: input.city, city: input.city,
state: input.state, state: input.state,
pincode: input.pincode,
isDefault: input.isDefault, isDefault: input.isDefault,
latitude: input.latitude, latitude: input.latitude,
longitude: input.longitude, longitude: input.longitude,
@ -105,7 +102,6 @@ export async function updateUserAddress(input: {
addressLine2?: string addressLine2?: string
city: string city: string
state: string state: string
pincode: string
isDefault: boolean isDefault: boolean
latitude?: number latitude?: number
longitude?: number longitude?: number
@ -122,7 +118,6 @@ export async function updateUserAddress(input: {
addressLine2: input.addressLine2, addressLine2: input.addressLine2,
city: input.city, city: input.city,
state: input.state, state: input.state,
pincode: input.pincode,
isDefault: input.isDefault, isDefault: input.isDefault,
googleMapsUrl: input.googleMapsUrl, googleMapsUrl: input.googleMapsUrl,
latitude: input.latitude, latitude: input.latitude,

View file

@ -791,7 +791,6 @@ export interface OrderWithFullData {
addressLine2: string | null addressLine2: string | null
city: string | null city: string | null
state: string | null state: string | null
pincode: string | null
phone: string | null phone: string | null
} | null } | null
orderItems: Array<{ orderItems: Array<{
@ -823,7 +822,6 @@ export async function getOrdersByIdsWithFullData(
addressLine2: true, addressLine2: true,
city: true, city: true,
state: true, state: true,
pincode: true,
phone: true, phone: true,
}, },
}, },
@ -873,7 +871,6 @@ export async function getOrderByIdWithFullData(
addressLine2: true, addressLine2: true,
city: true, city: true,
state: true, state: true,
pincode: true,
phone: true, phone: true,
}, },
}, },

View file

@ -81,7 +81,6 @@ export interface AdminOrderDetailsAddress {
line2: string | null; line2: string | null;
city: string; city: string;
state: string; state: string;
pincode: string;
phone: string; phone: string;
} }

View file

@ -48,7 +48,6 @@ export interface AddressFormProps {
addressLine2: string addressLine2: string
city: string city: string
state: string state: string
pincode: string
isDefault: boolean isDefault: boolean
latitude?: number latitude?: number
longitude?: number longitude?: number

View file

@ -31,7 +31,6 @@ export interface Address {
addressLine2: string | null; addressLine2: string | null;
city: string; city: string;
state: string; state: string;
pincode: string;
lat: number | null; lat: number | null;
lng: number | null; lng: number | null;
isDefault: boolean; isDefault: boolean;
@ -49,7 +48,6 @@ export interface UserAddress {
addressLine2: string | null; addressLine2: string | null;
city: string; city: string;
state: string; state: string;
pincode: string;
isDefault: boolean; isDefault: boolean;
latitude: number | null; latitude: number | null;
longitude: number | null; longitude: number | null;