Compare commits
No commits in common. "e55ac915f497433a5e1c1a1d55274e21518e7eda" and "a7456473e9db0291478498d4d3a373d9de034f71" have entirely different histories.
e55ac915f4
...
a7456473e9
45 changed files with 302 additions and 1056 deletions
|
|
@ -435,7 +435,7 @@ export default function OrderDetails() {
|
|||
{order.address.name} {' '}
|
||||
{order.address.line1}
|
||||
{order.address.line2 ? `, ${order.address.line2}` : ""}
|
||||
{`\n${order.address.city}, ${order.address.state}`}
|
||||
{`\n${order.address.city}, ${order.address.state} - ${order.address.pincode}`}
|
||||
</MyText>
|
||||
</View>
|
||||
</View>
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ const makeDetails = (overrides: Record<string, unknown> = {}) => ({
|
|||
line2: null,
|
||||
city: 'City',
|
||||
state: 'State',
|
||||
pincode: '500001',
|
||||
phone: '9876543210',
|
||||
},
|
||||
slotInfo: { time: '2026-01-02T10:00:00.000Z', sequence: null },
|
||||
|
|
|
|||
|
|
@ -404,7 +404,7 @@ function OrderDetails() {
|
|||
{order.address.name} {' '}
|
||||
{order.address.line1}
|
||||
{order.address.line2 ? `, ${order.address.line2}` : ''}
|
||||
{`\n${order.address.city}, ${order.address.state}`}
|
||||
{`\n${order.address.city}, ${order.address.state} - ${order.address.pincode}`}
|
||||
</MyText>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -69,7 +69,7 @@ const formatOrderMessageWithFullData = (ordersData: any[]): string => {
|
|||
if (order.address?.addressLine2) {
|
||||
message += ` ${order.address.addressLine2}\n`;
|
||||
}
|
||||
message += ` ${order.address?.city || ''}, ${order.address?.state || ''}\n`;
|
||||
message += ` ${order.address?.city || ''}, ${order.address?.state || ''} - ${order.address?.pincode || ''}\n`;
|
||||
if (order.address?.phone) {
|
||||
message += ` 📞 ${order.address.phone}\n`;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,8 +20,9 @@ import type {
|
|||
UserAddressDeleteResponse,
|
||||
} from '@packages/shared'
|
||||
|
||||
// Indian mobile numbers: exactly 10 digits starting 6-9.
|
||||
// Indian mobile numbers: exactly 10 digits starting 6-9. Pincode: exactly 6 digits.
|
||||
const PHONE_REGEX = /^[6-9]\d{9}$/
|
||||
const PINCODE_REGEX = /^\d{6}$/
|
||||
|
||||
export const addressRouter = router({
|
||||
getDefaultAddress: protectedProcedure
|
||||
|
|
@ -51,6 +52,8 @@ export const addressRouter = router({
|
|||
addressLine2: z.string().optional(),
|
||||
city: z.string().min(1, 'City is required'),
|
||||
state: z.string().min(1, 'State is required'),
|
||||
pincode: z.string().trim().min(1, 'Pincode is required')
|
||||
.regex(PINCODE_REGEX, 'Pincode must be 6 digits'),
|
||||
isDefault: z.boolean().optional(),
|
||||
// Coordinates picked on the map. The user app always sends them; the web
|
||||
// app may omit them (legacy), in which case the bound falls back to the
|
||||
|
|
@ -61,7 +64,7 @@ export const addressRouter = router({
|
|||
}))
|
||||
.mutation(async ({ input, ctx }): Promise<UserAddressResponse> => {
|
||||
const userId = ctx.user.userId;
|
||||
const { name, phone, addressLine1, addressLine2, city, state, isDefault, googleMapsUrl } = input;
|
||||
const { name, phone, addressLine1, addressLine2, city, state, pincode, isDefault, googleMapsUrl } = input;
|
||||
|
||||
let { latitude, longitude } = input;
|
||||
|
||||
|
|
@ -85,7 +88,7 @@ export const addressRouter = router({
|
|||
}
|
||||
|
||||
// Validate required fields
|
||||
if (!name || !phone || !addressLine1 || !city || !state) {
|
||||
if (!name || !phone || !addressLine1 || !city || !state || !pincode) {
|
||||
throw new Error('Missing required fields');
|
||||
}
|
||||
|
||||
|
|
@ -108,6 +111,7 @@ export const addressRouter = router({
|
|||
addressLine2,
|
||||
city,
|
||||
state,
|
||||
pincode,
|
||||
isDefault: makeDefault,
|
||||
latitude,
|
||||
longitude,
|
||||
|
|
@ -128,6 +132,8 @@ export const addressRouter = router({
|
|||
addressLine2: z.string().optional(),
|
||||
city: z.string().min(1, 'City is required'),
|
||||
state: z.string().min(1, 'State is required'),
|
||||
pincode: z.string().trim().min(1, 'Pincode is required')
|
||||
.regex(PINCODE_REGEX, 'Pincode must be 6 digits'),
|
||||
isDefault: z.boolean().optional(),
|
||||
// See createAddress: coordinates are optional for the legacy web client.
|
||||
latitude: z.number().min(-90).max(90).optional(),
|
||||
|
|
@ -136,7 +142,7 @@ export const addressRouter = router({
|
|||
}))
|
||||
.mutation(async ({ input, ctx }): Promise<UserAddressResponse> => {
|
||||
const userId = ctx.user.userId;
|
||||
const { id, name, phone, addressLine1, addressLine2, city, state, isDefault, googleMapsUrl } = input;
|
||||
const { id, name, phone, addressLine1, addressLine2, city, state, pincode, isDefault, googleMapsUrl } = input;
|
||||
|
||||
let { latitude, longitude } = input;
|
||||
|
||||
|
|
@ -188,6 +194,7 @@ export const addressRouter = router({
|
|||
addressLine2,
|
||||
city,
|
||||
state,
|
||||
pincode,
|
||||
// An omitted isDefault means "leave it as it is": only an explicit value may change it.
|
||||
isDefault: isDefault ?? existingAddress.isDefault,
|
||||
googleMapsUrl,
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ const addressBody = (over: Record<string, unknown> = {}) => ({
|
|||
addressLine1: '1 API Street',
|
||||
city: 'Mahabubnagar',
|
||||
state: 'Telangana',
|
||||
pincode: '509001',
|
||||
isDefault: false,
|
||||
...over,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -156,6 +156,7 @@ export async function ensureUserAddress(): Promise<{ addressId: number; created:
|
|||
addressLine1: '1 API Test Street',
|
||||
city: 'Mahabubnagar',
|
||||
state: 'Telangana',
|
||||
pincode: '509001',
|
||||
isDefault: true,
|
||||
})
|
||||
|
||||
|
|
@ -189,6 +190,7 @@ export async function registerUserWithAddress(): Promise<{
|
|||
addressLine1: '1 API Test Street',
|
||||
city: 'Mahabubnagar',
|
||||
state: 'Telangana',
|
||||
pincode: '509001',
|
||||
isDefault: true,
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -139,7 +139,7 @@ export function OrderDetailsRoute() {
|
|||
<p className="whitespace-pre-line">
|
||||
{order.address?.name} {order.address?.line1}
|
||||
{order.address?.line2 ? `, ${order.address.line2}` : ""}
|
||||
{`\n${order.address?.city}, ${order.address?.state}`}
|
||||
{`\n${order.address?.city}, ${order.address?.state} - ${order.address?.pincode}`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import AddressForm from '@/src/components/AddressForm';
|
|||
// Address view — required core of the shared UserAddress + optional geo fields
|
||||
type Address = Pick<
|
||||
UserAddress,
|
||||
'id' | 'regionId' | 'name' | 'phone' | 'addressLine1' | 'addressLine2' | 'city' | 'state' | 'isDefault'
|
||||
'id' | 'regionId' | 'name' | 'phone' | 'addressLine1' | 'addressLine2' | 'city' | 'state' | 'pincode' | 'isDefault'
|
||||
> & {
|
||||
latitude?: number | null
|
||||
longitude?: number | null
|
||||
|
|
@ -25,7 +25,7 @@ function AddressCard({ address, onEdit, onDelete, onSetDefault, isDeleting }: {
|
|||
isDeleting?: boolean;
|
||||
}) {
|
||||
const formatAddress = (addr: Address) => {
|
||||
return `${addr.addressLine1}${addr.addressLine2 ? `, ${addr.addressLine2}` : ''}, ${addr.city}, ${addr.state}`;
|
||||
return `${addr.addressLine1}${addr.addressLine2 ? `, ${addr.addressLine2}` : ''}, ${addr.city}, ${addr.state} - ${addr.pincode}`;
|
||||
};
|
||||
|
||||
return (
|
||||
|
|
@ -159,6 +159,7 @@ export default function Addresses() {
|
|||
addressLine2: addressToUpdate.addressLine2 || undefined,
|
||||
city: addressToUpdate.city,
|
||||
state: addressToUpdate.state,
|
||||
pincode: addressToUpdate.pincode,
|
||||
isDefault: true,
|
||||
// Keep the stored coordinates so the bound is not re-derived from a fallback.
|
||||
latitude: addressToUpdate.latitude ?? undefined,
|
||||
|
|
@ -271,6 +272,7 @@ export default function Addresses() {
|
|||
addressLine2: editingAddress.addressLine2 || '',
|
||||
city: editingAddress.city,
|
||||
state: editingAddress.state,
|
||||
pincode: editingAddress.pincode,
|
||||
isDefault: editingAddress.isDefault,
|
||||
latitude: editingAddress.googleMapsUrl ? undefined : (editingAddress.latitude ?? undefined),
|
||||
longitude: editingAddress.googleMapsUrl ? undefined : (editingAddress.longitude ?? undefined),
|
||||
|
|
|
|||
|
|
@ -1,112 +0,0 @@
|
|||
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
|
||||
|
|
@ -57,7 +57,7 @@ const CheckoutAddressDisplay: React.FC = () => {
|
|||
{address.addressLine2 ? `, ${address.addressLine2}` : ''}
|
||||
</MyText>
|
||||
<MyText style={tw`text-gray-600 text-sm mb-1`}>
|
||||
{address.city}, {address.state}
|
||||
{address.city}, {address.state} - {address.pincode}
|
||||
</MyText>
|
||||
<MyText style={tw`text-gray-500 text-xs mt-2`}>Phone: {address.phone}</MyText>
|
||||
</View>
|
||||
|
|
|
|||
|
|
@ -155,6 +155,7 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
|
|||
addressLine2: address.addressLine2 || '',
|
||||
city: address.city,
|
||||
state: address.state,
|
||||
pincode: address.pincode,
|
||||
isDefault: address.isDefault,
|
||||
latitude,
|
||||
longitude,
|
||||
|
|
@ -234,7 +235,7 @@ const CheckoutAddressSelector: React.FC<AddressSelectorProps> = ({
|
|||
{address.addressLine1}{address.addressLine2 ? `, ${address.addressLine2}` : ''}
|
||||
</Text>
|
||||
<Text style={tw`text-gray-600 text-sm mb-1`}>
|
||||
{address.city}, {address.state}
|
||||
{address.city}, {address.state} - {address.pincode}
|
||||
</Text>
|
||||
<Text style={tw`text-gray-500 text-xs mt-2`}>
|
||||
Phone: {address.phone}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import React, { useEffect } from 'react'
|
||||
import { ActivityIndicator, Linking, Platform, View } from 'react-native'
|
||||
import { ActivityIndicator, View } from 'react-native'
|
||||
import { MyText, theme, tw } from 'common-ui'
|
||||
import type { ReactParentComponent } from '@packages/shared'
|
||||
import { trpc } from '../src/trpc-client'
|
||||
|
|
@ -16,12 +16,11 @@ const LoadingScreen: React.FC<{ label?: string }> = ({ label }) => (
|
|||
/**
|
||||
* Region gate + location fallback.
|
||||
*
|
||||
* The browsing region is derived from the device location (see `useRegion`),
|
||||
* anchored on the user's default address: when the location resolves to the
|
||||
* default's region (or to no serviceable region) we use the default; only a
|
||||
* different serviceable region makes us ask. While that decision is in flight we
|
||||
* show a spinner; once a region exists the app renders, otherwise the user is
|
||||
* asked to choose an address.
|
||||
* The browsing region is derived from the device location (see `useRegion`).
|
||||
* While that is in flight we show a spinner; once a region exists the app
|
||||
* renders. When the location is unusable — device location switched off,
|
||||
* permission denied, or coordinates outside every region bound — the user is
|
||||
* asked to choose a region manually.
|
||||
*/
|
||||
const LocationTestWrapper: React.FC<ReactParentComponent> = ({ children }) => {
|
||||
const {
|
||||
|
|
@ -29,46 +28,10 @@ const LocationTestWrapper: React.FC<ReactParentComponent> = ({ children }) => {
|
|||
clearRegion,
|
||||
hydrated,
|
||||
isResolvingRegion,
|
||||
locationStatus,
|
||||
} = useRegion()
|
||||
|
||||
const { data: regions } = trpc.common.listRegions.useQuery()
|
||||
|
||||
// Tell the user *why* the location isn't usable before asking for an address.
|
||||
const locationNotice = (() => {
|
||||
switch (locationStatus) {
|
||||
case 'denied':
|
||||
return 'Location access is not granted. Allow location access for accurate delivery, or add a delivery address below.'
|
||||
case 'services-off':
|
||||
return 'Your device location is turned off. Turn it on, or add a delivery address below.'
|
||||
case 'unavailable':
|
||||
case 'error':
|
||||
return 'We could not get your location. Please try again, or add a delivery address below.'
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
})()
|
||||
|
||||
// Deep-link to the OS location settings when the app can't fix it itself
|
||||
// (location services off, or permission denied — iOS won't re-prompt).
|
||||
const openLocationSettings = () => {
|
||||
void (async () => {
|
||||
try {
|
||||
if (Platform.OS === 'android') {
|
||||
await Linking.sendIntent('android.settings.LOCATION_SOURCE_SETTINGS')
|
||||
} else {
|
||||
await Linking.openSettings()
|
||||
}
|
||||
} catch {
|
||||
try {
|
||||
await Linking.openSettings()
|
||||
} catch {
|
||||
// Give up silently — the notice still explains the situation.
|
||||
}
|
||||
}
|
||||
})()
|
||||
}
|
||||
|
||||
// Validate the saved region against the live list. A stale/unknown id must
|
||||
// lead to selection, never a silent checkout fallback. Membership-only: no
|
||||
// setRegion here, so this effect can never re-trigger itself.
|
||||
|
|
@ -90,22 +53,15 @@ const LocationTestWrapper: React.FC<ReactParentComponent> = ({ children }) => {
|
|||
return <LoadingScreen />
|
||||
}
|
||||
|
||||
// Still deriving the region from device location / the default address.
|
||||
// Still deriving the region from device location.
|
||||
if (isResolvingRegion) {
|
||||
return <LoadingScreen label="Finding your region..." />
|
||||
}
|
||||
|
||||
// No region resolved -> pick an address or add one.
|
||||
// Location unavailable / denied / out of area -> pick an address or add one.
|
||||
return (
|
||||
<View style={tw`flex-1 bg-white`}>
|
||||
<LocationFallbackFlow
|
||||
notice={locationNotice}
|
||||
onOpenSettings={
|
||||
locationStatus === 'services-off' || locationStatus === 'denied'
|
||||
? openLocationSettings
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<LocationFallbackFlow />
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -107,7 +107,7 @@ const QuickDeliveryAddressSelector: React.FC<QuickDeliveryAddressSelectorProps>
|
|||
const addressOptions = addresses.map(address => ({
|
||||
id: address.id,
|
||||
name: address.name,
|
||||
address: `${address.addressLine1}${address.addressLine2 ? `, ${address.addressLine2}` : ''}, ${address.city}, ${address.state}`,
|
||||
address: `${address.addressLine1}${address.addressLine2 ? `, ${address.addressLine2}` : ''}, ${address.city}, ${address.state} - ${address.pincode}`,
|
||||
phone: address.phone,
|
||||
}));
|
||||
|
||||
|
|
|
|||
|
|
@ -32,7 +32,6 @@ import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks';
|
|||
import { useRegion } from '@/src/hooks/useRegion';
|
||||
import CheckoutAddressSelector from '@/components/CheckoutAddressSelector';
|
||||
import LoginWall from '@/components/LoginWall';
|
||||
import CartAddressGate from '@/components/CartAddressGate';
|
||||
import { useAddressStore } from '@/src/store/addressStore';
|
||||
import { useCheckoutStore } from '@/src/store/checkoutStore';
|
||||
import type { FlashDeliveryProps } from '@packages/shared';
|
||||
|
|
@ -191,10 +190,6 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
|||
|
||||
const { selectedAddressId, setSelectedAddressId } = useAddressStore();
|
||||
const { regionId } = useRegion();
|
||||
// First-address gate: the region can exist (from the location) with no address yet.
|
||||
const addressesQuery = trpc.user.address.getUserAddresses.useQuery(undefined, {
|
||||
enabled: isAuthenticated,
|
||||
});
|
||||
const userNotes = useCheckoutStore((state) => state.userNotes);
|
||||
const setUserNotes = useCheckoutStore((state) => state.setUserNotes);
|
||||
|
||||
|
|
@ -648,27 +643,6 @@ 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 (
|
||||
<View style={tw`flex-1 bg-gray-50`}>
|
||||
{/* Fixed Cart Type Header */}
|
||||
|
|
|
|||
|
|
@ -5,11 +5,10 @@ import * as Yup from 'yup';
|
|||
import { tw, MyText, MyTouchableOpacity , Checkbox , MyTextInput , LoadingDialog } from 'common-ui';
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
||||
import { trpc } from '../trpc-client';
|
||||
import LocationAttacher from './LocationAttacher';
|
||||
import LocationMapStep from './location/LocationMapStep';
|
||||
import type { AddressFormProps } from '@packages/shared';
|
||||
import { savePendingAddress } from '@/src/lib/pending-address';
|
||||
import { useRegion } from '@/src/hooks/useRegion';
|
||||
import { useLocationStore } from '@/src/store/locationStore';
|
||||
|
||||
type Coords = { latitude: number; longitude: number };
|
||||
type ResolvedRegion = { regionId: number; boundId: number | null };
|
||||
|
|
@ -21,8 +20,6 @@ const AddressForm: React.FC<AddressFormProps> = ({
|
|||
draftMode = false,
|
||||
onResolvedRegion,
|
||||
}) => {
|
||||
const { regionId: browsingRegionId, boundId: browsingBoundId } = useRegion();
|
||||
const deviceCoords = useLocationStore((state) => state.coords);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [submitError, setSubmitError] = useState<string | null>(null);
|
||||
const [mapOpen, setMapOpen] = useState(false);
|
||||
|
|
@ -31,21 +28,12 @@ const AddressForm: React.FC<AddressFormProps> = ({
|
|||
? { latitude: initialValues.latitude, longitude: initialValues.longitude }
|
||||
: null
|
||||
);
|
||||
// The town (region) for this address. Pre-selected from the app's current
|
||||
// browsing region when one exists; otherwise picked from the City dropdown.
|
||||
const [resolvedRegion, setResolvedRegion] = useState<ResolvedRegion | null>(() =>
|
||||
browsingRegionId != null ? { regionId: browsingRegionId, boundId: browsingBoundId } : null
|
||||
);
|
||||
// Region is never picked directly: it is derived from the coordinates.
|
||||
const [resolvedRegion, setResolvedRegion] = useState<ResolvedRegion | null>(null);
|
||||
const [locationError, setLocationError] = useState<string | null>(null);
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
// Towns (regions) the user can deliver in — the City field is a picker over them.
|
||||
const { data: regionsData } = trpc.common.listRegions.useQuery();
|
||||
const regions = regionsData ?? [];
|
||||
const [cityOpen, setCityOpen] = useState(false);
|
||||
const cityName = regions.find((region) => region.id === resolvedRegion?.regionId)?.name ?? '';
|
||||
|
||||
// Resolve coordinates -> region + bound. Used for whichever source the user
|
||||
// picks (attach current location or the map). Out-of-area points are refused.
|
||||
const resolveLocation = useCallback(
|
||||
|
|
@ -76,33 +64,6 @@ const AddressForm: React.FC<AddressFormProps> = ({
|
|||
[utils, onResolvedRegion]
|
||||
);
|
||||
|
||||
// The City field is a picker over the serviceable towns. Changing it re-checks
|
||||
// that the chosen coordinates fall inside that town.
|
||||
const handleCityChange = useCallback(
|
||||
async (regionId: number) => {
|
||||
if (!currentLocation) {
|
||||
setResolvedRegion({ regionId, boundId: null });
|
||||
setLocationError('Attach or pick a location inside this town.');
|
||||
return;
|
||||
}
|
||||
setResolvedRegion({ regionId, boundId: null });
|
||||
setLocationError(null);
|
||||
try {
|
||||
const resolved = await utils.common.resolveBound.fetch({
|
||||
regionId,
|
||||
lat: currentLocation.latitude,
|
||||
lng: currentLocation.longitude,
|
||||
});
|
||||
const info: ResolvedRegion = { regionId, boundId: resolved.boundId };
|
||||
setResolvedRegion(info);
|
||||
onResolvedRegion?.(info);
|
||||
} catch {
|
||||
setLocationError('Your location is outside this town. Pick a point on the map inside it.');
|
||||
}
|
||||
},
|
||||
[utils, currentLocation, onResolvedRegion]
|
||||
);
|
||||
|
||||
// Resolve any prefilled coordinates once (e.g. edit, or coming from the map).
|
||||
useEffect(() => {
|
||||
if (initialValues?.latitude != null && initialValues?.longitude != null) {
|
||||
|
|
@ -111,25 +72,6 @@ const AddressForm: React.FC<AddressFormProps> = ({
|
|||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// If the app already knows the device location, attach it as the address
|
||||
// location by default (the user can still choose another on the map).
|
||||
useEffect(() => {
|
||||
if (currentLocation != null) return;
|
||||
if (initialValues?.latitude != null) return;
|
||||
if (deviceCoords == null) return;
|
||||
void resolveLocation(deviceCoords);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [deviceCoords]);
|
||||
|
||||
// Pre-select the browsing town once the app knows it (e.g. after the location
|
||||
// resolves) — unless the user already picked a town or attached a location.
|
||||
useEffect(() => {
|
||||
if (resolvedRegion != null || currentLocation != null) return;
|
||||
if (browsingRegionId == null) return;
|
||||
setResolvedRegion({ regionId: browsingRegionId, boundId: browsingBoundId });
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [browsingRegionId, browsingBoundId]);
|
||||
|
||||
const createAddressMutation = trpc.user.address.createAddress.useMutation({
|
||||
onSuccess: (data) => {
|
||||
setIsSubmitting(false);
|
||||
|
|
@ -161,7 +103,9 @@ const AddressForm: React.FC<AddressFormProps> = ({
|
|||
.matches(/^[6-9]\d{9}$/, 'Phone must be a 10-digit number starting with 6, 7, 8 or 9'),
|
||||
addressLine1: Yup.string().required('Address Line 1 is required'),
|
||||
addressLine2: Yup.string(),
|
||||
city: Yup.string().required('City is required'),
|
||||
state: Yup.string().required('State is required'),
|
||||
pincode: Yup.string().required('Pincode is required').matches(/^\d{6}$/, 'Pincode must be 6 digits'),
|
||||
isDefault: Yup.boolean(),
|
||||
});
|
||||
|
||||
|
|
@ -183,7 +127,7 @@ const AddressForm: React.FC<AddressFormProps> = ({
|
|||
<View style={tw`flex-row items-center`}>
|
||||
<MyText style={tw`text-amber-600 mr-2`}>ℹ️</MyText>
|
||||
<MyText style={tw`text-amber-800 text-sm flex-1`}>
|
||||
We currently serve only in the towns listed below
|
||||
We currently serve only in Mahabubnagar town
|
||||
</MyText>
|
||||
</View>
|
||||
</View>
|
||||
|
|
@ -200,8 +144,9 @@ const AddressForm: React.FC<AddressFormProps> = ({
|
|||
phone: '',
|
||||
addressLine1: '',
|
||||
addressLine2: '',
|
||||
city: '',
|
||||
city: 'Mahabubnagar',
|
||||
state: 'Telangana',
|
||||
pincode: '509001',
|
||||
isDefault: false,
|
||||
googleMapsUrl: '',
|
||||
}}
|
||||
|
|
@ -211,15 +156,14 @@ const AddressForm: React.FC<AddressFormProps> = ({
|
|||
setSubmitError('Please attach your current location or select it on the map.');
|
||||
return;
|
||||
}
|
||||
if (!resolvedRegion || locationError) {
|
||||
setSubmitError(locationError || 'Please choose a town and a location inside it.');
|
||||
if (!resolvedRegion) {
|
||||
setSubmitError(locationError || 'Please choose a location inside our delivery area.');
|
||||
return;
|
||||
}
|
||||
setIsSubmitting(true);
|
||||
setSubmitError(null);
|
||||
const payload = {
|
||||
...values,
|
||||
city: cityName || values.city || '',
|
||||
regionId: resolvedRegion.regionId,
|
||||
latitude: currentLocation.latitude,
|
||||
longitude: currentLocation.longitude,
|
||||
|
|
@ -235,8 +179,9 @@ const AddressForm: React.FC<AddressFormProps> = ({
|
|||
phone: values.phone,
|
||||
addressLine1: values.addressLine1,
|
||||
addressLine2: values.addressLine2 || undefined,
|
||||
city: cityName || values.city || '',
|
||||
city: values.city,
|
||||
state: values.state,
|
||||
pincode: values.pincode,
|
||||
isDefault: values.isDefault,
|
||||
latitude: currentLocation.latitude,
|
||||
longitude: currentLocation.longitude,
|
||||
|
|
@ -295,47 +240,15 @@ const AddressForm: React.FC<AddressFormProps> = ({
|
|||
value={values.addressLine2}
|
||||
/>
|
||||
|
||||
{/* City is a picker over the serviceable towns (regions). */}
|
||||
<View style={tw`mb-1`}>
|
||||
<MyText style={tw`text-gray-500 text-xs mb-1`}>City *</MyText>
|
||||
<MyTouchableOpacity
|
||||
testID="address-city"
|
||||
onPress={() => setCityOpen((prev) => !prev)}
|
||||
style={tw`border border-gray-200 rounded-lg p-3 flex-row items-center justify-between bg-gray-50`}
|
||||
>
|
||||
<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"
|
||||
<MyTextInput
|
||||
placeholder="City"
|
||||
shrunkPadding={true}
|
||||
onChangeText={handleChange('city')}
|
||||
onBlur={handleBlur('city')}
|
||||
value={values.city}
|
||||
disabled={true}
|
||||
/>
|
||||
</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>
|
||||
{touched.city && errors.city && <MyText style={tw`text-red-500 mb-2`}>{errors.city}</MyText>}
|
||||
|
||||
<MyTextInput
|
||||
placeholder="State"
|
||||
|
|
@ -347,44 +260,42 @@ const AddressForm: React.FC<AddressFormProps> = ({
|
|||
/>
|
||||
{touched.state && errors.state && <MyText style={tw`text-red-500 mb-2`}>{errors.state}</MyText>}
|
||||
|
||||
{/* Location is mandatory: attach the device location or pick on the map. */}
|
||||
<MyTextInput
|
||||
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`}>
|
||||
<MyText style={tw`text-gray-500 text-xs mb-2`}>Delivery Location *</MyText>
|
||||
{currentLocation ? (
|
||||
<>
|
||||
<View style={tw`flex-row items-center`}>
|
||||
<MaterialIcons name="check-circle" size={16} color="#16A34A" />
|
||||
<MyText style={tw`text-green-600 font-bold text-sm ml-1`}>
|
||||
Current Location Attached
|
||||
</MyText>
|
||||
</View>
|
||||
<LocationAttacher
|
||||
initialLocation={currentLocation || undefined}
|
||||
showGoogleMapsOption={false}
|
||||
onLocationChange={(location) => {
|
||||
if (location) void resolveLocation(location);
|
||||
}}
|
||||
disabled={false}
|
||||
/>
|
||||
<MyTouchableOpacity
|
||||
testID="address-select-from-map"
|
||||
onPress={() => setMapOpen(true)}
|
||||
style={tw`flex-row items-center mb-1`}
|
||||
>
|
||||
<MaterialIcons name="map" size={18} color="#3B82F6" />
|
||||
<MyText style={tw`text-blue-500 text-sm font-medium ml-1`}>Select on map</MyText>
|
||||
</MyTouchableOpacity>
|
||||
|
||||
{currentLocation && (
|
||||
<MyText style={tw`text-gray-500 text-xs mt-1`}>
|
||||
📍 {currentLocation.latitude.toFixed(5)}, {currentLocation.longitude.toFixed(5)}
|
||||
</MyText>
|
||||
<MyTouchableOpacity
|
||||
testID="address-choose-location"
|
||||
onPress={() => setMapOpen(true)}
|
||||
style={tw`flex-row items-center mt-2`}
|
||||
>
|
||||
<MaterialIcons name="map" size={18} color="#3B82F6" />
|
||||
<MyText style={tw`text-blue-500 text-sm font-medium ml-1`}>
|
||||
Choose Another Location in Map
|
||||
</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 && (
|
||||
<MyText style={tw`text-red-500 text-sm mt-1`}>{locationError}</MyText>
|
||||
)}
|
||||
|
|
@ -400,20 +311,14 @@ const AddressForm: React.FC<AddressFormProps> = ({
|
|||
|
||||
<MyTouchableOpacity
|
||||
testID="address-submit"
|
||||
style={tw`bg-indigo-600 p-3 rounded ${isSubmitting || !currentLocation ? 'opacity-50' : ''}`}
|
||||
style={tw`bg-indigo-600 p-3 rounded ${isSubmitting ? 'opacity-50' : ''}`}
|
||||
onPress={() => handleSubmit()}
|
||||
disabled={isSubmitting || !currentLocation}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<MyText style={tw`text-white text-center font-bold`}>
|
||||
{isSubmitting ? (isEdit ? 'Updating...' : 'Adding...') : (isEdit ? 'Update Address' : 'Add Address')}
|
||||
</MyText>
|
||||
</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>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -3,44 +3,18 @@ import { View } from 'react-native'
|
|||
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
|
||||
import { tw, theme, MyText, MyTouchableOpacity } from 'common-ui'
|
||||
import { useRegion } from '@/src/hooks/useRegion'
|
||||
import { useAddressStore } from '@/src/store/addressStore'
|
||||
import { useAuthOptional } from '@/src/contexts/AuthContext'
|
||||
import { trpc } from '@/src/trpc-client'
|
||||
import AddressSwitcherSheet from '@/src/components/location/AddressSwitcherSheet'
|
||||
|
||||
const formatAddress = (address: {
|
||||
addressLine1: string
|
||||
addressLine2?: string | null
|
||||
city: string
|
||||
}) =>
|
||||
`${address.addressLine1}${address.addressLine2 ? `, ${address.addressLine2}` : ''}, ${address.city}`
|
||||
|
||||
/**
|
||||
* Location bar shown at the top of every top-level tab screen.
|
||||
* Rendered INSIDE the scroll content (first item / ListHeaderComponent) so it
|
||||
* scrolls out with the page instead of sticking. Tapping opens the address
|
||||
* switcher: pick a saved address (region follows it) or add a new one.
|
||||
*
|
||||
* Shows "Deliver to: <region>" (truncated) on the first line and the active
|
||||
* address beneath it.
|
||||
*/
|
||||
const LocationBar: React.FC = () => {
|
||||
const [sheetOpen, setSheetOpen] = useState(false)
|
||||
const { region } = useRegion()
|
||||
|
||||
const isAuthenticated = useAuthOptional()?.isAuthenticated ?? false
|
||||
const selectedAddressId = useAddressStore((state) => state.selectedAddressId)
|
||||
const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, {
|
||||
enabled: isAuthenticated,
|
||||
})
|
||||
|
||||
const addresses = addressesData?.data ?? []
|
||||
// Prefer the address the user selected at checkout, else their default.
|
||||
const activeAddress =
|
||||
addresses.find((address) => address.id === selectedAddressId) ??
|
||||
addresses.find((address) => address.isDefault) ??
|
||||
null
|
||||
|
||||
return (
|
||||
<View style={tw`px-4 pt-3 pb-1`}>
|
||||
<MyTouchableOpacity
|
||||
|
|
@ -53,21 +27,12 @@ const LocationBar: React.FC = () => {
|
|||
<MaterialIcons name="location-on" size={20} color={theme.colors.brand500} />
|
||||
</View>
|
||||
<View style={tw`flex-1`}>
|
||||
<MyText style={tw`text-sm text-gray-500`} numberOfLines={1} ellipsizeMode="tail">
|
||||
Deliver to:{' '}
|
||||
<MyText weight="bold" style={tw`text-gray-900`}>
|
||||
<MyText style={tw`text-gray-400 text-[11px] font-semibold uppercase tracking-wider`}>
|
||||
Deliver to
|
||||
</MyText>
|
||||
<MyText style={tw`text-gray-900 text-base font-bold`} numberOfLines={1}>
|
||||
{region?.name ?? 'Choose your address'}
|
||||
</MyText>
|
||||
</MyText>
|
||||
{activeAddress ? (
|
||||
<MyText
|
||||
style={tw`text-xs text-gray-500 mt-0.5`}
|
||||
numberOfLines={2}
|
||||
ellipsizeMode="tail"
|
||||
>
|
||||
{formatAddress(activeAddress)}
|
||||
</MyText>
|
||||
) : null}
|
||||
</View>
|
||||
<MaterialIcons name="keyboard-arrow-down" size={24} color="#9CA3AF" />
|
||||
</MyTouchableOpacity>
|
||||
|
|
|
|||
|
|
@ -23,22 +23,13 @@ interface ChooserAddress {
|
|||
addressLine2: string | null
|
||||
city: string
|
||||
state: string
|
||||
pincode: string
|
||||
isDefault: boolean
|
||||
}
|
||||
|
||||
interface LocationFallbackFlowProps {
|
||||
/** Present when hosted in a sheet; lets the caller dismiss after a choice. */
|
||||
onClose?: () => void
|
||||
/**
|
||||
* Why the location couldn't be used (permission not granted / turned off /
|
||||
* couldn't get a fix). Shown above the address options.
|
||||
*/
|
||||
notice?: string
|
||||
/**
|
||||
* When set, the notice also shows a button that deep-links to the OS location
|
||||
* settings (used when the OS state can't be fixed from inside the app).
|
||||
*/
|
||||
onOpenSettings?: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -46,7 +37,7 @@ interface LocationFallbackFlowProps {
|
|||
* (which switches the browsing region + bound and clears the cart) or adds a
|
||||
* new one (coordinates required, via attach-location or the map).
|
||||
*/
|
||||
const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({ onClose, notice, onOpenSettings }) => {
|
||||
const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({ onClose }) => {
|
||||
const queryClient = useQueryClient()
|
||||
const utils = trpc.useUtils()
|
||||
const auth = useAuthOptional()
|
||||
|
|
@ -124,6 +115,7 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({ onClose, no
|
|||
addressLine2: address.addressLine2 || undefined,
|
||||
city: address.city,
|
||||
state: address.state,
|
||||
pincode: address.pincode,
|
||||
isDefault: true,
|
||||
latitude: address.latitude ?? undefined,
|
||||
longitude: address.longitude ?? undefined,
|
||||
|
|
@ -185,25 +177,6 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({ onClose, no
|
|||
)}
|
||||
</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 && (
|
||||
<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>
|
||||
|
|
@ -234,7 +207,7 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({ onClose, no
|
|||
</View>
|
||||
<MyText style={tw`text-gray-600 text-sm`}>
|
||||
{address.addressLine1}
|
||||
{address.addressLine2 ? `, ${address.addressLine2}` : ''}, {address.city}
|
||||
{address.addressLine2 ? `, ${address.addressLine2}` : ''}, {address.city} - {address.pincode}
|
||||
</MyText>
|
||||
</MyTouchableOpacity>
|
||||
|
||||
|
|
|
|||
|
|
@ -43,12 +43,12 @@ export interface UseRegionResult {
|
|||
bound: RegionBoundSummary | null
|
||||
/** Monotonic marker bumped on every region change; use it to ignore stale responses. */
|
||||
regionGeneration: number
|
||||
/** Always true: the region store is in-memory (not persisted). */
|
||||
/** True once the persisted region has finished loading from storage. */
|
||||
hydrated: boolean
|
||||
/** Latest device coordinates, if the launch fix succeeded. */
|
||||
coords: { latitude: number; longitude: number } | null
|
||||
/** Current state of the launch location read. */
|
||||
locationStatus: 'idle' | 'locating' | 'granted' | 'denied' | 'services-off' | 'unavailable' | 'error'
|
||||
locationStatus: 'idle' | 'locating' | 'granted' | 'denied' | 'unavailable' | 'error'
|
||||
/**
|
||||
* True while the launch location check is still determining a region AND no
|
||||
* region is known yet. The UI should show a spinner rather than the chooser
|
||||
|
|
@ -65,9 +65,7 @@ export interface UseRegionResult {
|
|||
|
||||
export function useRegion(): UseRegionResult {
|
||||
const queryClient = useQueryClient()
|
||||
const auth = useAuthOptional()
|
||||
const isAuthenticated = auth?.isAuthenticated ?? false
|
||||
const isAuthLoading = auth?.isLoading ?? false
|
||||
const isAuthenticated = useAuthOptional()?.isAuthenticated ?? false
|
||||
|
||||
const region = useRegionStore((state) => state.selectedRegion)
|
||||
const regionId = useRegionStore((state) => state.selectedRegionId)
|
||||
|
|
@ -81,26 +79,19 @@ export function useRegion(): UseRegionResult {
|
|||
const startTracking = useLocationStore((state) => state.start)
|
||||
const refreshTracking = useLocationStore((state) => state.refresh)
|
||||
|
||||
// The region store is in-memory (not persisted), so there is nothing to
|
||||
// hydrate before we can decide.
|
||||
const hydrated = true
|
||||
const [hydrated, setHydrated] = useState<boolean>(() =>
|
||||
useRegionStore.persist.hasHydrated()
|
||||
)
|
||||
// True once the launch location check has a definitive outcome.
|
||||
const [startupResolved, setStartupResolved] = useState(false)
|
||||
|
||||
// The user's default address — the anchor for the startup region decision.
|
||||
const defaultAddressQuery = trpc.user.address.getDefaultAddress.useQuery(undefined, {
|
||||
enabled: hydrated && isAuthenticated,
|
||||
staleTime: 60000,
|
||||
})
|
||||
const defaultAddress = defaultAddressQuery.data?.data ?? null
|
||||
|
||||
// Region summaries (needed to build the RegionSummary when adopting a region
|
||||
// from the default address).
|
||||
const regionsQuery = trpc.common.listRegions.useQuery(undefined, {
|
||||
enabled: hydrated,
|
||||
staleTime: 60000,
|
||||
})
|
||||
const regions = regionsQuery.data ?? null
|
||||
useEffect(() => {
|
||||
if (useRegionStore.persist.hasHydrated()) {
|
||||
setHydrated(true)
|
||||
return
|
||||
}
|
||||
return useRegionStore.persist.onFinishHydration(() => setHydrated(true))
|
||||
}, [])
|
||||
|
||||
// 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
|
||||
|
|
@ -144,37 +135,18 @@ export function useRegion(): UseRegionResult {
|
|||
refetchOnWindowFocus: false,
|
||||
})
|
||||
|
||||
// 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).
|
||||
// Apply the launch outcome once: same region -> no-op, different -> switch.
|
||||
useEffect(() => {
|
||||
if (!hydrated || startupResolved) return
|
||||
|
||||
const resolved = resolution.data
|
||||
const locationSettled =
|
||||
const terminal =
|
||||
resolved != null ||
|
||||
resolution.isFetched ||
|
||||
resolution.isError ||
|
||||
locationStatus === 'denied' ||
|
||||
locationStatus === 'services-off' ||
|
||||
locationStatus === 'unavailable' ||
|
||||
locationStatus === 'error'
|
||||
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
|
||||
}
|
||||
if (!terminal) return
|
||||
|
||||
setStartupResolved(true)
|
||||
|
||||
|
|
@ -185,42 +157,13 @@ export function useRegion(): UseRegionResult {
|
|||
// Respect a manual pick made before the fix resolved.
|
||||
const userChangedRegion =
|
||||
startupLaunchRegionId !== undefined && startupLaunchRegionId !== regionId
|
||||
if (userChangedRegion) return
|
||||
|
||||
const defaultRegionId = isAuthenticated ? defaultAddress?.regionId ?? null : null
|
||||
|
||||
if (defaultRegionId != null) {
|
||||
const inDefaultRegion = resolved?.region?.id === defaultRegionId
|
||||
// No serviceable region found -> treat like a disabled location.
|
||||
const noServiceableRegion = resolved == null
|
||||
if (inDefaultRegion || noServiceableRegion) {
|
||||
const region = regions?.find((candidate) => candidate.id === defaultRegionId) ?? null
|
||||
if (region) {
|
||||
if (regionId == null) {
|
||||
// First region of this launch — adopt it without clearing the cart.
|
||||
setRegion(region, defaultAddress?.boundId ?? null)
|
||||
} else if (region.id !== regionId) {
|
||||
void confirmRegionSwitch(region, queryClient, defaultAddress?.boundId ?? null)
|
||||
} else if (defaultAddress?.boundId != null && defaultAddress.boundId !== boundId) {
|
||||
setRegion(region, defaultAddress.boundId)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Location is in another serviceable region -> ask the user to choose.
|
||||
if (regionId != null) clearRegion()
|
||||
return
|
||||
}
|
||||
|
||||
// No default address: derive the region from the location as before.
|
||||
if (resolved?.region) {
|
||||
if (regionId == null) {
|
||||
// First region of this launch — adopt it without clearing the cart.
|
||||
setRegion(resolved.region, resolved.bound?.id ?? null)
|
||||
} else if (resolved.region.id !== regionId) {
|
||||
if (resolved?.region && !userChangedRegion) {
|
||||
if (resolved.region.id !== regionId) {
|
||||
// New region -> full switch (clears carts, refreshes regional data).
|
||||
void confirmRegionSwitch(resolved.region, queryClient, resolved.bound?.id ?? null)
|
||||
} else if (resolved.bound && resolved.bound.id !== boundId) {
|
||||
// Same region -> refresh the active bound from the location resolve
|
||||
// (signed-out users get their bound from here; no cart clear).
|
||||
setRegion(resolved.region, resolved.bound.id)
|
||||
}
|
||||
}
|
||||
|
|
@ -234,13 +177,7 @@ export function useRegion(): UseRegionResult {
|
|||
regionId,
|
||||
boundId,
|
||||
setRegion,
|
||||
clearRegion,
|
||||
queryClient,
|
||||
isAuthenticated,
|
||||
isAuthLoading,
|
||||
defaultAddressQuery.isLoading,
|
||||
defaultAddress,
|
||||
regions,
|
||||
])
|
||||
|
||||
// Safety net: a hanging resolve must not strand the first-run spinner.
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ export interface PendingAddressInput {
|
|||
addressLine2?: string
|
||||
city: string
|
||||
state: string
|
||||
pincode: string
|
||||
isDefault?: boolean
|
||||
latitude: number
|
||||
longitude: number
|
||||
|
|
|
|||
|
|
@ -14,8 +14,7 @@ export type LocationStatus =
|
|||
| 'locating' // permission requested / waiting for the fix
|
||||
| 'granted' // coordinates available
|
||||
| 'denied' // foreground permission refused
|
||||
| 'services-off' // device location services are switched off
|
||||
| 'unavailable' // no fix could be read (timeout / provider error)
|
||||
| 'unavailable' // services off, or no fix could be read
|
||||
| 'error'
|
||||
|
||||
export interface Coords {
|
||||
|
|
@ -96,7 +95,6 @@ export const useLocationStore = create<LocationStoreState>((set, get) => ({
|
|||
if (token !== activeToken) return
|
||||
|
||||
if (status !== 'granted') {
|
||||
console.log('[user-ui] location permission denied')
|
||||
set({ status: 'denied', coords: null, error: null })
|
||||
return
|
||||
}
|
||||
|
|
@ -109,8 +107,7 @@ export const useLocationStore = create<LocationStoreState>((set, get) => ({
|
|||
: true
|
||||
if (token !== activeToken) return
|
||||
if (!servicesEnabled) {
|
||||
console.log('[user-ui] location services off')
|
||||
set({ status: 'services-off', coords: null, error: null })
|
||||
set({ status: 'unavailable', coords: null, error: null })
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -119,12 +116,9 @@ export const useLocationStore = create<LocationStoreState>((set, get) => ({
|
|||
FIRST_FIX_TIMEOUT_MS
|
||||
)
|
||||
if (token !== activeToken) return
|
||||
const nextCoords = toCoords(position)
|
||||
console.log('[user-ui] location coords', nextCoords)
|
||||
set({ status: 'granted', coords: nextCoords, error: null })
|
||||
set({ status: 'granted', coords: toCoords(position), error: null })
|
||||
} catch (err) {
|
||||
if (token !== activeToken) return
|
||||
console.log('[user-ui] location unavailable', err instanceof Error ? err.message : err)
|
||||
set({
|
||||
status: 'unavailable',
|
||||
coords: null,
|
||||
|
|
|
|||
|
|
@ -1,21 +1,19 @@
|
|||
import { create } from 'zustand'
|
||||
import { persist, createJSONStorage } from 'zustand/middleware'
|
||||
import { StorageServiceCasual } from 'common-ui'
|
||||
import type { RegionSummary } from '@packages/shared'
|
||||
|
||||
// Browsing region — the region the user is currently shopping in.
|
||||
//
|
||||
// Deliberately NOT persisted: at each launch the region is re-derived from the
|
||||
// device location, or from the user's default / chosen address. A persisted
|
||||
// region would let the app show a stale region (e.g. the last one) whenever the
|
||||
// location is unavailable, instead of asking the user to grant location or add
|
||||
// an address. `regionGeneration` is a monotonic marker bumped on every change so
|
||||
// stale regional responses can be ignored.
|
||||
// Browsing region — the single region the user is currently shopping in.
|
||||
// Kept separate from account identity and persisted so the choice survives
|
||||
// app restarts. `regionGeneration` is a monotonic marker bumped on every
|
||||
// change so stale regional responses can be ignored.
|
||||
interface RegionStore {
|
||||
selectedRegionId: number | null
|
||||
selectedRegion: RegionSummary | null
|
||||
/**
|
||||
* The bound whose consts the client should read for this region. Resolved
|
||||
* from device location (the containing bound) or from a chosen address's
|
||||
* bound. `null` until known.
|
||||
* from device location (the containing bound) or from the region's effective
|
||||
* bound on a manual pick. `null` until known.
|
||||
*/
|
||||
selectedBoundId: number | null
|
||||
regionGeneration: number
|
||||
|
|
@ -23,7 +21,9 @@ interface RegionStore {
|
|||
clearRegion: () => void
|
||||
}
|
||||
|
||||
export const useRegionStore = create<RegionStore>((set) => ({
|
||||
export const useRegionStore = create<RegionStore>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
selectedRegionId: null,
|
||||
selectedRegion: null,
|
||||
selectedBoundId: null,
|
||||
|
|
@ -63,4 +63,20 @@ export const useRegionStore = create<RegionStore>((set) => ({
|
|||
regionGeneration: state.regionGeneration + 1,
|
||||
}
|
||||
}),
|
||||
}))
|
||||
}),
|
||||
{
|
||||
name: 'freshyo-region',
|
||||
version: 1,
|
||||
storage: createJSONStorage<RegionStore>(() => StorageServiceCasual),
|
||||
partialize: (state) => ({
|
||||
selectedRegionId: state.selectedRegionId,
|
||||
selectedRegion: state.selectedRegion,
|
||||
selectedBoundId: state.selectedBoundId,
|
||||
regionGeneration: state.regionGeneration,
|
||||
// Functions are dropped from the persisted payload.
|
||||
setRegion: state.setRegion,
|
||||
clearRegion: state.clearRegion,
|
||||
}),
|
||||
}
|
||||
)
|
||||
)
|
||||
|
|
|
|||
|
|
@ -74,6 +74,7 @@ describe('AddressForm', () => {
|
|||
addressLine1: '9 Office St',
|
||||
city: 'Hyderabad',
|
||||
state: 'Telangana',
|
||||
pincode: '500002',
|
||||
isDefault: false,
|
||||
} as never
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ const ADDRESSES = {
|
|||
addressLine2: 'Apt 4',
|
||||
city: 'Hyderabad',
|
||||
state: 'Telangana',
|
||||
pincode: '500001',
|
||||
isDefault: false,
|
||||
},
|
||||
{
|
||||
|
|
@ -35,6 +36,7 @@ const ADDRESSES = {
|
|||
addressLine2: null,
|
||||
city: 'Hyderabad',
|
||||
state: 'Telangana',
|
||||
pincode: '500002',
|
||||
isDefault: true,
|
||||
},
|
||||
],
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ const PROCEDURES = {
|
|||
addressLine2: null,
|
||||
city: 'Hyderabad',
|
||||
state: 'Telangana',
|
||||
pincode: '500001',
|
||||
isDefault: true,
|
||||
},
|
||||
],
|
||||
|
|
|
|||
|
|
@ -54,6 +54,7 @@ const ADDRESSES = {
|
|||
addressLine2: 'Apt 4',
|
||||
city: 'Hyderabad',
|
||||
state: 'Telangana',
|
||||
pincode: '500001',
|
||||
isDefault: true,
|
||||
},
|
||||
],
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ const ADDRESS = {
|
|||
addressLine2: 'Apt 4',
|
||||
city: 'Hyderabad',
|
||||
state: 'Telangana',
|
||||
pincode: '500001',
|
||||
isDefault: false,
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -44,6 +44,7 @@ const ADDRESS = {
|
|||
addressLine2: 'Apt 4',
|
||||
city: 'Hyderabad',
|
||||
state: 'Telangana',
|
||||
pincode: '500001',
|
||||
isDefault: false,
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import React, { useCallback, useEffect, useState } from 'react'
|
||||
import { trpc } from '../lib/trpc-client'
|
||||
import { useRegionStore } from '../lib/stores/region-store'
|
||||
import { p, pInput as PInput, MyButton, div } from 'web-components'
|
||||
import { MapPin } from 'lucide-react'
|
||||
import * as Yup from 'yup'
|
||||
|
|
@ -14,7 +13,9 @@ const validationSchema = Yup.object({
|
|||
phone: Yup.string().required('Phone is required').matches(/^\d{10}$/, 'Phone must be 10 digits'),
|
||||
addressLine1: Yup.string().required('Address Line 1 is required'),
|
||||
addressLine2: Yup.string(),
|
||||
city: Yup.string().required('City is required'),
|
||||
state: Yup.string().required('State is required'),
|
||||
pincode: Yup.string().required('Pincode is required').matches(/^\d{6}$/, 'Pincode must be 6 digits'),
|
||||
isDefault: Yup.boolean(),
|
||||
})
|
||||
|
||||
|
|
@ -29,55 +30,19 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
|
|||
? { latitude: initialValues.latitude, longitude: initialValues.longitude }
|
||||
: null
|
||||
)
|
||||
const browsingRegionId = useRegionStore((state) => state.selectedRegionId)
|
||||
const browsingRegion = useRegionStore((state) => state.selectedRegion)
|
||||
// The town (region) for this address. Pre-selected from the app's current
|
||||
// browsing region when one exists; otherwise picked from the City dropdown.
|
||||
const [resolvedRegion, setResolvedRegion] = useState<ResolvedRegion | null>(() =>
|
||||
browsingRegionId != null
|
||||
? { regionId: browsingRegionId, boundId: browsingRegion?.effectiveBoundId ?? null }
|
||||
: null
|
||||
)
|
||||
// Region is derived from the coordinates, never picked directly.
|
||||
const [resolvedRegion, setResolvedRegion] = useState<ResolvedRegion | null>(null)
|
||||
|
||||
const utils = trpc.useUtils()
|
||||
|
||||
// Towns (regions) the user can deliver in — the City field is a picker over them.
|
||||
const { data: regionsData } = trpc.common.listRegions.useQuery()
|
||||
const regions = regionsData ?? []
|
||||
const cityName = regions.find((region) => region.id === resolvedRegion?.regionId)?.name ?? ''
|
||||
|
||||
const handleCityChange = useCallback(
|
||||
async (regionId: number) => {
|
||||
if (!currentLocation) {
|
||||
setResolvedRegion({ regionId, boundId: null })
|
||||
setLocationError('Use your location or pick a point inside this town.')
|
||||
return
|
||||
}
|
||||
setResolvedRegion({ regionId, boundId: null })
|
||||
setLocationError(null)
|
||||
try {
|
||||
const resolved = await utils.common.resolveBound.fetch({
|
||||
regionId,
|
||||
lat: currentLocation.latitude,
|
||||
lng: currentLocation.longitude,
|
||||
})
|
||||
const info: ResolvedRegion = { regionId, boundId: resolved.boundId }
|
||||
setResolvedRegion(info)
|
||||
onResolvedRegion?.(info)
|
||||
} catch {
|
||||
setLocationError('Your location is outside this town. Pick a point on the map inside it.')
|
||||
}
|
||||
},
|
||||
[utils, currentLocation, onResolvedRegion]
|
||||
)
|
||||
|
||||
const [values, setValues] = useState(() => ({
|
||||
name: initialValues?.name || '',
|
||||
phone: initialValues?.phone || '',
|
||||
addressLine1: initialValues?.addressLine1 || '',
|
||||
addressLine2: initialValues?.addressLine2 || '',
|
||||
city: initialValues?.city || '',
|
||||
city: initialValues?.city || 'Mahabubnagar',
|
||||
state: initialValues?.state || 'Telangana',
|
||||
pincode: initialValues?.pincode || '509001',
|
||||
isDefault: initialValues?.isDefault || false,
|
||||
googleMapsUrl: initialValues?.googleMapsUrl || '',
|
||||
}))
|
||||
|
|
@ -119,18 +84,6 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
|
|||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
// Pre-select the browsing town once known — unless the user already picked a
|
||||
// town or attached a location.
|
||||
useEffect(() => {
|
||||
if (resolvedRegion != null || currentLocation != null) return
|
||||
if (browsingRegionId == null) return
|
||||
setResolvedRegion({
|
||||
regionId: browsingRegionId,
|
||||
boundId: browsingRegion?.effectiveBoundId ?? null,
|
||||
})
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [browsingRegionId, browsingRegion])
|
||||
|
||||
// Coordinates picked on the embedded map are delivered via postMessage.
|
||||
useEffect(() => {
|
||||
if (!mapOpen) return
|
||||
|
|
@ -208,8 +161,8 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
|
|||
setSubmitError('Please use your current location or select one on the map.')
|
||||
return
|
||||
}
|
||||
if (!resolvedRegion || locationError) {
|
||||
setSubmitError(locationError || 'Please choose a town and a location inside it.')
|
||||
if (!resolvedRegion) {
|
||||
setSubmitError(locationError || 'Please choose a location inside our delivery area.')
|
||||
return
|
||||
}
|
||||
setIsSubmitting(true)
|
||||
|
|
@ -217,7 +170,6 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
|
|||
|
||||
const payload = {
|
||||
...values,
|
||||
city: cityName || values.city || '',
|
||||
regionId: resolvedRegion.regionId,
|
||||
latitude: currentLocation.latitude,
|
||||
longitude: currentLocation.longitude,
|
||||
|
|
@ -247,7 +199,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="flex items-center gap-2">
|
||||
<span className="text-amber-600">ℹ️</span>
|
||||
<p className="flex-1 text-sm text-amber-800">We currently serve only in the towns listed below</p>
|
||||
<p className="flex-1 text-sm text-amber-800">We currently serve only in Mahabubnagar town</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -299,63 +251,44 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
|
|||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<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>
|
||||
<PInput placeholder="City" value={values.city} disabled className="bg-gray-100" />
|
||||
</div>
|
||||
<div>
|
||||
<PInput placeholder="State" value={values.state} disabled className="bg-gray-100" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Location is mandatory: attach the device location or pick on the map. */}
|
||||
<div>
|
||||
<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">
|
||||
<p className="mb-2 text-xs text-gray-500">Delivery Location *</p>
|
||||
{currentLocation ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="flex items-center gap-2 text-sm font-bold text-green-600">
|
||||
<MapPin className="h-4 w-4" /> Current Location Attached
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
📍 {currentLocation.latitude.toFixed(5)}, {currentLocation.longitude.toFixed(5)}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
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>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMapOpen(true)}
|
||||
className="flex items-center gap-2 text-left text-sm font-medium text-blue-500"
|
||||
>
|
||||
<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"
|
||||
className="flex items-center gap-2 text-left text-sm font-medium text-blue-500 disabled:opacity-50"
|
||||
>
|
||||
<MapPin className="h-4 w-4" />
|
||||
{locating ? 'Fetching location…' : 'Use my current location'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMapOpen(true)}
|
||||
className="flex items-center gap-2 text-left text-sm font-medium text-blue-500"
|
||||
>
|
||||
<MapPin className="h-4 w-4" />
|
||||
Select on map
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{currentLocation && (
|
||||
<p className="mt-2 text-xs text-gray-500">
|
||||
📍 {currentLocation.latitude.toFixed(5)}, {currentLocation.longitude.toFixed(5)}
|
||||
</p>
|
||||
)}
|
||||
{locationError && <p className="mt-1 text-sm text-red-500">{locationError}</p>}
|
||||
</div>
|
||||
|
|
@ -374,7 +307,7 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
|
|||
fullWidth
|
||||
textContent={isSubmitting ? (isEdit ? 'Updating...' : 'Adding...') : (isEdit ? 'Update Address' : 'Add Address')}
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting || !currentLocation}
|
||||
disabled={isSubmitting}
|
||||
className="bg-brand-500 text-white"
|
||||
/>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -151,7 +151,7 @@ export function CheckoutAddressSelector({ onAddressSelect, onAddAddress, onEditA
|
|||
{address.addressLine2 ? `, ${address.addressLine2}` : ''}
|
||||
</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
{address.city}, {address.state}
|
||||
{address.city}, {address.state} - {address.pincode}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-gray-500">
|
||||
Phone: {address.phone}
|
||||
|
|
|
|||
|
|
@ -36,27 +36,13 @@ interface GoogleMarker {
|
|||
setMap: (map: GoogleMap | null) => void
|
||||
setPosition: (position: LatLngLiteral) => void
|
||||
}
|
||||
interface GoogleMapConstructor {
|
||||
new (element: HTMLElement, options: Record<string, unknown>): GoogleMap
|
||||
}
|
||||
interface GoogleMarkerConstructor {
|
||||
new (options: Record<string, unknown>): GoogleMarker
|
||||
}
|
||||
// The resolved `maps` + `marker` libraries (both constructors present).
|
||||
interface GoogleMapsApi {
|
||||
Map: GoogleMapConstructor
|
||||
Marker: GoogleMarkerConstructor
|
||||
}
|
||||
type GoogleImportLibrary = (library: string, ...rest: string[]) => Promise<any>
|
||||
// The global `google.maps` namespace, including the dynamic-import entry point.
|
||||
interface GoogleMapsNamespace {
|
||||
importLibrary?: GoogleImportLibrary
|
||||
// Set by the bootstrap; the API invokes it once the namespace is fully ready.
|
||||
__ib__?: () => void
|
||||
Map: new (element: HTMLElement, options: Record<string, unknown>) => GoogleMap
|
||||
Marker: new (options: Record<string, unknown>) => GoogleMarker
|
||||
}
|
||||
type ReactNativeWebViewBridge = { postMessage: (message: string) => void }
|
||||
type GoogleWindow = Window & {
|
||||
google?: { maps?: GoogleMapsNamespace }
|
||||
google?: { maps: GoogleMapsNamespace }
|
||||
// Injected by react-native-webview when this page is embedded in user-ui.
|
||||
ReactNativeWebView?: ReactNativeWebViewBridge
|
||||
}
|
||||
|
|
@ -70,82 +56,26 @@ const DEFAULT_ZOOM = 12
|
|||
// VITE_GOOGLE_MAPS_API_KEY=your-key
|
||||
const GOOGLE_MAPS_API_KEY = import.meta.env.VITE_GOOGLE_MAPS_API_KEY as string | undefined
|
||||
|
||||
let googleMapsLoader: Promise<GoogleMapsApi> | null = null
|
||||
let googleMapsLoader: Promise<GoogleMapsNamespace> | null = null
|
||||
|
||||
/**
|
||||
* Google's recommended "Dynamic Library Import" bootstrap
|
||||
* (https://goo.gle/js-api-loading).
|
||||
*
|
||||
* It defines `google.maps.importLibrary` synchronously and loads the API with
|
||||
* the `callback` signal, so we never read `google.maps` before it exists. A raw
|
||||
* `<script onload>` check races with `loading=async` (onload fires before the
|
||||
* namespace is populated) and reports the namespace as unavailable.
|
||||
*/
|
||||
function ensureImportLibrary(apiKey: string): GoogleImportLibrary {
|
||||
const w = window as GoogleWindow
|
||||
const g = (w.google ??= {})
|
||||
const maps = (g.maps ??= {})
|
||||
if (maps.importLibrary) return maps.importLibrary
|
||||
|
||||
const requested = new Set<string>()
|
||||
let loading: Promise<void> | null = null
|
||||
|
||||
const load = () => {
|
||||
if (loading) return loading
|
||||
loading = new Promise<void>((resolve, reject) => {
|
||||
const params = new URLSearchParams()
|
||||
params.set('key', apiKey)
|
||||
params.set('v', 'weekly')
|
||||
params.set('libraries', Array.from(requested).join(','))
|
||||
params.set('loading', 'async')
|
||||
params.set('callback', 'google.maps.__ib__')
|
||||
|
||||
const script = document.createElement('script')
|
||||
script.src = `https://maps.googleapis.com/maps/api/js?${params.toString()}`
|
||||
script.async = true
|
||||
const nonce = document.querySelector('script[nonce]')?.getAttribute('nonce')
|
||||
if (nonce) script.setAttribute('nonce', nonce)
|
||||
script.onerror = () => reject(new Error('The Google Maps JavaScript API could not load.'))
|
||||
// The API calls this once it — and its namespace — is ready.
|
||||
maps.__ib__ = () => resolve()
|
||||
document.head.appendChild(script)
|
||||
})
|
||||
return loading
|
||||
}
|
||||
|
||||
const importLibrary: GoogleImportLibrary = (library, ...rest) => {
|
||||
requested.add(library)
|
||||
for (const name of rest) requested.add(name)
|
||||
return load().then(() => {
|
||||
const real = maps.importLibrary
|
||||
if (!real || real === importLibrary) {
|
||||
throw new Error('Google Maps importLibrary did not initialize.')
|
||||
}
|
||||
return real(library, ...rest)
|
||||
})
|
||||
}
|
||||
|
||||
maps.importLibrary = importLibrary
|
||||
return importLibrary
|
||||
}
|
||||
|
||||
function loadGoogleMaps(apiKey: string): Promise<GoogleMapsApi> {
|
||||
function loadGoogleMaps(apiKey: string): Promise<GoogleMapsNamespace> {
|
||||
const existing = (window as GoogleWindow).google?.maps
|
||||
if (existing) return Promise.resolve(existing)
|
||||
if (googleMapsLoader) return googleMapsLoader
|
||||
|
||||
googleMapsLoader = (async () => {
|
||||
const importLibrary = ensureImportLibrary(apiKey)
|
||||
// Register both libraries so the bootstrap fetches them together.
|
||||
const [mapsLib, markerLib] = await Promise.all([
|
||||
importLibrary('maps'),
|
||||
importLibrary('marker'),
|
||||
])
|
||||
const Map: GoogleMapConstructor | undefined = mapsLib?.Map
|
||||
const Marker: GoogleMarkerConstructor | undefined = markerLib?.Marker
|
||||
if (!Map || !Marker) {
|
||||
throw new Error('Google Maps loaded but the maps/marker libraries are unavailable.')
|
||||
googleMapsLoader = new Promise<GoogleMapsNamespace>((resolve, reject) => {
|
||||
const script = document.createElement('script')
|
||||
script.src = `https://maps.googleapis.com/maps/api/js?key=${encodeURIComponent(apiKey)}`
|
||||
script.async = true
|
||||
script.defer = true
|
||||
script.onload = () => {
|
||||
const maps = (window as GoogleWindow).google?.maps
|
||||
if (maps) resolve(maps)
|
||||
else reject(new Error('Google Maps loaded but the maps namespace is unavailable.'))
|
||||
}
|
||||
return { Map, Marker }
|
||||
})()
|
||||
script.onerror = () => reject(new Error('Failed to load the Google Maps script.'))
|
||||
document.head.appendChild(script)
|
||||
})
|
||||
|
||||
return googleMapsLoader
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ export const Route = createFileRoute('/me/addresses')({ component: AddressesPage
|
|||
// Address view — required core of the shared UserAddress + optional geo fields
|
||||
type Address = Pick<
|
||||
UserAddress,
|
||||
'id' | 'regionId' | 'name' | 'phone' | 'addressLine1' | 'addressLine2' | 'city' | 'state' | 'isDefault'
|
||||
'id' | 'regionId' | 'name' | 'phone' | 'addressLine1' | 'addressLine2' | 'city' | 'state' | 'pincode' | 'isDefault'
|
||||
> & {
|
||||
latitude?: number | null
|
||||
longitude?: number | null
|
||||
|
|
@ -20,7 +20,7 @@ type Address = Pick<
|
|||
}
|
||||
|
||||
const formatAddress = (addr: Address) => {
|
||||
return `${addr.addressLine1}${addr.addressLine2 ? `, ${addr.addressLine2}` : ''}, ${addr.city}, ${addr.state}`
|
||||
return `${addr.addressLine1}${addr.addressLine2 ? `, ${addr.addressLine2}` : ''}, ${addr.city}, ${addr.state} - ${addr.pincode}`
|
||||
}
|
||||
|
||||
function AddressCard({
|
||||
|
|
@ -143,6 +143,7 @@ function AddressesPage() {
|
|||
addressLine2: addressToUpdate.addressLine2 || undefined,
|
||||
city: addressToUpdate.city,
|
||||
state: addressToUpdate.state,
|
||||
pincode: addressToUpdate.pincode,
|
||||
isDefault: true,
|
||||
// Keep the stored coordinates so the bound is not re-derived from a fallback.
|
||||
latitude: addressToUpdate.latitude ?? undefined,
|
||||
|
|
@ -244,6 +245,7 @@ function AddressesPage() {
|
|||
addressLine2: editingAddress.addressLine2 || '',
|
||||
city: editingAddress.city,
|
||||
state: editingAddress.state,
|
||||
pincode: editingAddress.pincode,
|
||||
isDefault: editingAddress.isDefault,
|
||||
latitude: editingAddress.googleMapsUrl
|
||||
? undefined
|
||||
|
|
|
|||
282
change-log.txt
282
change-log.txt
|
|
@ -3711,285 +3711,3 @@ user-ui
|
|||
localuserweb.freshyo.in -> http://localhost:4174; DNS CNAME routed; running detached.
|
||||
- apps/web-ui/vite.config.ts: add `server.allowedHosts: ['.freshyo.in']` so the Vite
|
||||
dev server does not 403 the tunneled hostname (same fix as superadmin-ui). No tests run.
|
||||
|
||||
2026-10-13 14:04:49 LocationBar (user-ui): show the active address beneath the region.
|
||||
apps/user-ui/src/components/LocationBar.tsx:
|
||||
+ reads selectedAddressId (useAddressStore) and user.address.getUserAddresses (auth-gated);
|
||||
active address = selected -> default -> none
|
||||
+ line 1 (single line, truncated with ellipsis): "Deliver to: <region name>"
|
||||
+ next line(s): the formatted address (line1[, line2], city - pincode), max 2 lines
|
||||
- removed the separate uppercase "Deliver to" label row
|
||||
No dependency added. No migration. No tests run.
|
||||
|
||||
2026-10-13 14:08:13 web-ui /location-selector: load the Google Maps JS API with the recommended async pattern.
|
||||
The loader added the script without `loading=async`, which triggers the console warning
|
||||
"Google Maps JavaScript API has been loaded directly without loading=async".
|
||||
1/1 apps/web-ui/src/routes/location-selector.tsx:
|
||||
- script.src = `https://maps.googleapis.com/maps/api/js?key=${...}`
|
||||
+ script.src = `https://maps.googleapis.com/maps/api/js?key=${...}&loading=async`
|
||||
+ after onload, resolve Map/Marker via google.maps.importLibrary('maps'|'marker')
|
||||
(falls back to the legacy google.maps.Map/.Marker if importLibrary is absent)
|
||||
+ split the structural types: GoogleMapsApi { Map, Marker } (resolved) vs GoogleMapsNamespace
|
||||
(window.google.maps, optional constructors + importLibrary)
|
||||
No dependency added. No migration. No tests run.
|
||||
|
||||
2026-10-13 14:14:50 web-ui /location-selector: fix the Maps readiness race using Google's recommended dynamic
|
||||
library import. The prior `loading=async` change read window.google.maps in the script `onload`, but the async
|
||||
bootstrap defines the namespace only afterwards, so the loader rejected with
|
||||
"Google Maps loaded but the maps namespace is unavailable."
|
||||
1/1 apps/web-ui/src/routes/location-selector.tsx:
|
||||
- raw <script onload> readiness check (races with loading=async)
|
||||
+ ensureImportLibrary(apiKey): installs Google's official dynamic-import bootstrap. It defines
|
||||
google.maps.importLibrary synchronously and loads
|
||||
https://maps.googleapis.com/maps/api/js?key&v=weekly&libraries=...&loading=async&callback=google.maps.__ib__ ,
|
||||
resolving the load promise from the callback (no early namespace read).
|
||||
+ loadGoogleMaps now resolves Map/Marker via google.maps.importLibrary('maps'|'marker')
|
||||
+ GoogleMapsNamespace type narrowed to { importLibrary?, __ib__? }
|
||||
No dependency added. No migration. No tests run.
|
||||
|
||||
2026-10-13 16:35:00 Location gate (user-ui): adopt the default address when the device location is unusable.
|
||||
Previously, if location was disabled/denied/out-of-area and no region was saved, the gate always showed the address
|
||||
chooser even when the user had a default address.
|
||||
1/1 apps/user-ui/components/LocationTestWrapper.tsx:
|
||||
+ reads auth (useAuthOptional) + user.address.getDefaultAddress + common.listRegions
|
||||
+ when hydrated + authenticated + location settled with no region and a default address exists:
|
||||
confirmRegionSwitch(default-address region, default-address boundId) once (ref guard), showing a spinner
|
||||
+ shows "Setting up your address..." while auth / default-address / regions load so the chooser never flashes
|
||||
+ falls back to LocationFallbackFlow only when there is no default address
|
||||
No dependency added. No migration. No tests run.
|
||||
|
||||
2026-10-13 16:43:33 Startup region decision (user-ui): anchor on the default address.
|
||||
Rule: with a default address, at launch use it unless the device location resolves to a *different* serviceable
|
||||
region (then ask the user to choose an address). Same region or out-of-area/location-off -> use the default.
|
||||
1/2 apps/user-ui/src/hooks/useRegion.ts:
|
||||
+ reads auth (isLoading too), user.address.getDefaultAddress, common.listRegions
|
||||
+ startup effect rewritten: when a default address exists and the location settled ->
|
||||
- resolved region == default's region, OR resolved == null (location off / out of area) ->
|
||||
confirmRegionSwitch(default region, default bound) (no prompt)
|
||||
- resolved region != default's region (another serviceable region) -> clearRegion() so the gate asks
|
||||
when there is no default address -> previous behaviour (use the resolved region, else prompt)
|
||||
+ waits for auth/default-address/regions before settling (spinner covers it)
|
||||
2/2 apps/user-ui/components/LocationTestWrapper.tsx: reverted the local default-address auto-adopt
|
||||
(useRegion is now the single source of truth; keeping it would re-adopt the default while prompting)
|
||||
No dependency added. No migration. No tests run.
|
||||
|
||||
2026-10-13 17:05:42 Cart page (user-ui): require a first delivery address before showing the cart.
|
||||
When the region/bound is known (from location) but the signed-in user has no address yet, opening the cart now
|
||||
shows an "add address" screen first: "Address of current Location" (prefills the device coords) or "Choose another
|
||||
location" (map). The first saved address becomes the default (backend), then the cart is shown.
|
||||
1/1 NEW apps/user-ui/components/CartAddressGate.tsx:
|
||||
+ full-screen screen with the two options; "Address of current Location" opens AddressForm prefilled with
|
||||
useLocationStore coords; "Choose another location" opens AddressForm (map picker)
|
||||
+ onSuccess -> close + onDone()
|
||||
2/2 apps/user-ui/components/cart-page.tsx:
|
||||
+ user.address.getUserAddresses query
|
||||
+ after auth/cart load, if authenticated and the cart has items and there is no address -> render CartAddressGate
|
||||
(refetch on done) instead of the cart
|
||||
No dependency added. No migration. No tests run.
|
||||
|
||||
2026-10-13 17:08:19 Cart page (user-ui): apply the first-address gate even on an empty cart.
|
||||
1/1 apps/user-ui/components/cart-page.tsx:
|
||||
- if (cartItems.length > 0) { ... }
|
||||
+ gate now runs regardless of cart contents (authenticated users with no address see CartAddressGate)
|
||||
No dependency added. No migration. No tests run.
|
||||
|
||||
2026-10-13 17:16:12 user-ui location tracking: log the captured coordinates.
|
||||
1/1 apps/user-ui/src/store/locationStore.ts (refresh):
|
||||
+ const nextCoords = toCoords(position)
|
||||
+ console.log('[user-ui] location coords', nextCoords)
|
||||
+ logs on the non-granted paths too ('location permission denied', 'location services disabled',
|
||||
'location unavailable', <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.
|
||||
|
|
|
|||
|
|
@ -200,6 +200,7 @@ export async function getOrderDetails(orderId: number): Promise<AdminOrderDetail
|
|||
line2: orderData.address.addressLine2,
|
||||
city: orderData.address.city,
|
||||
state: orderData.address.state,
|
||||
pincode: orderData.address.pincode,
|
||||
phone: orderData.address.phone,
|
||||
},
|
||||
slotInfo: orderData.slot
|
||||
|
|
@ -372,7 +373,9 @@ export async function getSlotOrders(slotId: string): Promise<AdminGetSlotOrdersR
|
|||
customerName: order.user.name || order.user.mobile+'',
|
||||
address: `${order.address.addressLine1}${
|
||||
order.address.addressLine2 ? `, ${order.address.addressLine2}` : ''
|
||||
}, ${order.address.city}, ${order.address.state}, Phone: ${order.address.phone}`,
|
||||
}, ${order.address.city}, ${order.address.state} - ${
|
||||
order.address.pincode
|
||||
}, Phone: ${order.address.phone}`,
|
||||
addressId: order.addressId,
|
||||
latitude: order.address.adminLatitude ?? order.address.latitude,
|
||||
longitude: order.address.adminLongitude ?? order.address.longitude,
|
||||
|
|
@ -512,7 +515,9 @@ export async function getAllOrders(input: GetAllOrdersInput): Promise<AdminGetAl
|
|||
customerMobile: order.user.mobile,
|
||||
address: `${order.address.addressLine1}${
|
||||
order.address.addressLine2 ? `, ${order.address.addressLine2}` : ''
|
||||
}, ${order.address.city}, ${order.address.state}, Phone: ${order.address.phone}`,
|
||||
}, ${order.address.city}, ${order.address.state} - ${
|
||||
order.address.pincode
|
||||
}, Phone: ${order.address.phone}`,
|
||||
addressId: order.addressId,
|
||||
latitude: order.address.adminLatitude ?? order.address.latitude,
|
||||
longitude: order.address.adminLongitude ?? order.address.longitude,
|
||||
|
|
|
|||
|
|
@ -44,6 +44,7 @@ export const addresses = mf.table('addresses', {
|
|||
addressLine2: varchar('address_line2', { length: 255 }),
|
||||
city: varchar('city', { length: 100 }).notNull(),
|
||||
state: varchar('state', { length: 100 }).notNull(),
|
||||
pincode: varchar('pincode', { length: 10 }).notNull(),
|
||||
isDefault: boolean('is_default').notNull().default(false),
|
||||
latitude: real('latitude'),
|
||||
longitude: real('longitude'),
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ const mapUserAddress = (address: AddressRow): UserAddress => ({
|
|||
addressLine2: address.addressLine2 ?? null,
|
||||
city: address.city,
|
||||
state: address.state,
|
||||
pincode: address.pincode,
|
||||
isDefault: address.isDefault,
|
||||
latitude: address.latitude ?? null,
|
||||
longitude: address.longitude ?? null,
|
||||
|
|
@ -62,6 +63,7 @@ export async function createUserAddress(input: {
|
|||
addressLine2?: string
|
||||
city: string
|
||||
state: string
|
||||
pincode: string
|
||||
isDefault: boolean
|
||||
latitude?: number
|
||||
longitude?: number
|
||||
|
|
@ -75,6 +77,7 @@ export async function createUserAddress(input: {
|
|||
addressLine2: input.addressLine2,
|
||||
city: input.city,
|
||||
state: input.state,
|
||||
pincode: input.pincode,
|
||||
isDefault: input.isDefault,
|
||||
latitude: input.latitude,
|
||||
longitude: input.longitude,
|
||||
|
|
@ -93,6 +96,7 @@ export async function updateUserAddress(input: {
|
|||
addressLine2?: string
|
||||
city: string
|
||||
state: string
|
||||
pincode: string
|
||||
isDefault: boolean
|
||||
latitude?: number
|
||||
longitude?: number
|
||||
|
|
@ -106,6 +110,7 @@ export async function updateUserAddress(input: {
|
|||
addressLine2: input.addressLine2,
|
||||
city: input.city,
|
||||
state: input.state,
|
||||
pincode: input.pincode,
|
||||
isDefault: input.isDefault,
|
||||
googleMapsUrl: input.googleMapsUrl,
|
||||
latitude: input.latitude,
|
||||
|
|
|
|||
|
|
@ -558,6 +558,7 @@ export interface OrderWithFullData {
|
|||
addressLine2: string | null
|
||||
city: string | null
|
||||
state: string | null
|
||||
pincode: string | null
|
||||
phone: string | null
|
||||
} | null
|
||||
orderItems: Array<{
|
||||
|
|
@ -584,6 +585,7 @@ export async function getOrdersByIdsWithFullData(
|
|||
addressLine2: true,
|
||||
city: true,
|
||||
state: true,
|
||||
pincode: true,
|
||||
phone: true,
|
||||
},
|
||||
},
|
||||
|
|
@ -624,6 +626,7 @@ export async function getOrderByIdWithFullData(
|
|||
addressLine2: true,
|
||||
city: true,
|
||||
state: true,
|
||||
pincode: true,
|
||||
phone: true,
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -297,6 +297,7 @@ CREATE TABLE `__new_addresses` (
|
|||
`address_line2` text,
|
||||
`city` text NOT NULL,
|
||||
`state` text NOT NULL,
|
||||
`pincode` text NOT NULL,
|
||||
`is_default` integer DEFAULT false NOT NULL,
|
||||
`latitude` real,
|
||||
`longitude` real,
|
||||
|
|
@ -313,8 +314,8 @@ CREATE TABLE `__new_addresses` (
|
|||
FOREIGN KEY (`bound_id`) REFERENCES `region_bounds`(`id`) ON UPDATE no action ON DELETE no action
|
||||
);
|
||||
--> statement-breakpoint
|
||||
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`,`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`;
|
||||
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`)
|
||||
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`;
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `__new_coupons` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
|
|
|
|||
|
|
@ -223,6 +223,7 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
|
|||
line2: orderData.address.addressLine2,
|
||||
city: orderData.address.city,
|
||||
state: orderData.address.state,
|
||||
pincode: orderData.address.pincode,
|
||||
phone: orderData.address.phone,
|
||||
},
|
||||
slotInfo: orderData.slot
|
||||
|
|
@ -425,7 +426,9 @@ export async function getSlotOrders(regionId: number, slotId: string): Promise<A
|
|||
customerName: order.user.name || order.user.mobile+'',
|
||||
address: `${order.address.addressLine1}${
|
||||
order.address.addressLine2 ? `, ${order.address.addressLine2}` : ''
|
||||
}, ${order.address.city}, ${order.address.state}, Phone: ${order.address.phone}`,
|
||||
}, ${order.address.city}, ${order.address.state} - ${
|
||||
order.address.pincode
|
||||
}, Phone: ${order.address.phone}`,
|
||||
addressId: order.addressId,
|
||||
latitude: order.address.adminLatitude ?? order.address.latitude,
|
||||
longitude: order.address.adminLongitude ?? order.address.longitude,
|
||||
|
|
@ -587,7 +590,9 @@ export async function getAllOrders(regionId: number, input: GetAllOrdersInput):
|
|||
customerMobile: order.user.mobile,
|
||||
address: `${order.address.addressLine1}${
|
||||
order.address.addressLine2 ? `, ${order.address.addressLine2}` : ''
|
||||
}, ${order.address.city}, ${order.address.state}, Phone: ${order.address.phone}`,
|
||||
}, ${order.address.city}, ${order.address.state} - ${
|
||||
order.address.pincode
|
||||
}, Phone: ${order.address.phone}`,
|
||||
addressId: order.addressId,
|
||||
latitude: order.address.adminLatitude ?? order.address.latitude,
|
||||
longitude: order.address.adminLongitude ?? order.address.longitude,
|
||||
|
|
|
|||
|
|
@ -116,6 +116,7 @@ export const addresses = sqliteTable('addresses', {
|
|||
addressLine2: text('address_line2'),
|
||||
city: text('city').notNull(),
|
||||
state: text('state').notNull(),
|
||||
pincode: text('pincode').notNull(),
|
||||
isDefault: integer('is_default', { mode: 'boolean' }).notNull().default(false),
|
||||
latitude: real('latitude'),
|
||||
longitude: real('longitude'),
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ const mapUserAddress = (address: AddressRow): UserAddress => ({
|
|||
addressLine2: address.addressLine2 ?? null,
|
||||
city: address.city,
|
||||
state: address.state,
|
||||
pincode: address.pincode,
|
||||
isDefault: address.isDefault,
|
||||
latitude: address.latitude ?? null,
|
||||
longitude: address.longitude ?? null,
|
||||
|
|
@ -67,6 +68,7 @@ export async function createUserAddress(input: {
|
|||
addressLine2?: string
|
||||
city: string
|
||||
state: string
|
||||
pincode: string
|
||||
isDefault: boolean
|
||||
latitude?: number
|
||||
longitude?: number
|
||||
|
|
@ -82,6 +84,7 @@ export async function createUserAddress(input: {
|
|||
addressLine2: input.addressLine2,
|
||||
city: input.city,
|
||||
state: input.state,
|
||||
pincode: input.pincode,
|
||||
isDefault: input.isDefault,
|
||||
latitude: input.latitude,
|
||||
longitude: input.longitude,
|
||||
|
|
@ -102,6 +105,7 @@ export async function updateUserAddress(input: {
|
|||
addressLine2?: string
|
||||
city: string
|
||||
state: string
|
||||
pincode: string
|
||||
isDefault: boolean
|
||||
latitude?: number
|
||||
longitude?: number
|
||||
|
|
@ -118,6 +122,7 @@ export async function updateUserAddress(input: {
|
|||
addressLine2: input.addressLine2,
|
||||
city: input.city,
|
||||
state: input.state,
|
||||
pincode: input.pincode,
|
||||
isDefault: input.isDefault,
|
||||
googleMapsUrl: input.googleMapsUrl,
|
||||
latitude: input.latitude,
|
||||
|
|
|
|||
|
|
@ -791,6 +791,7 @@ export interface OrderWithFullData {
|
|||
addressLine2: string | null
|
||||
city: string | null
|
||||
state: string | null
|
||||
pincode: string | null
|
||||
phone: string | null
|
||||
} | null
|
||||
orderItems: Array<{
|
||||
|
|
@ -822,6 +823,7 @@ export async function getOrdersByIdsWithFullData(
|
|||
addressLine2: true,
|
||||
city: true,
|
||||
state: true,
|
||||
pincode: true,
|
||||
phone: true,
|
||||
},
|
||||
},
|
||||
|
|
@ -871,6 +873,7 @@ export async function getOrderByIdWithFullData(
|
|||
addressLine2: true,
|
||||
city: true,
|
||||
state: true,
|
||||
pincode: true,
|
||||
phone: true,
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -81,6 +81,7 @@ export interface AdminOrderDetailsAddress {
|
|||
line2: string | null;
|
||||
city: string;
|
||||
state: string;
|
||||
pincode: string;
|
||||
phone: string;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -48,6 +48,7 @@ export interface AddressFormProps {
|
|||
addressLine2: string
|
||||
city: string
|
||||
state: string
|
||||
pincode: string
|
||||
isDefault: boolean
|
||||
latitude?: number
|
||||
longitude?: number
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ export interface Address {
|
|||
addressLine2: string | null;
|
||||
city: string;
|
||||
state: string;
|
||||
pincode: string;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
isDefault: boolean;
|
||||
|
|
@ -48,6 +49,7 @@ export interface UserAddress {
|
|||
addressLine2: string | null;
|
||||
city: string;
|
||||
state: string;
|
||||
pincode: string;
|
||||
isDefault: boolean;
|
||||
latitude: number | null;
|
||||
longitude: number | null;
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue