Compare commits

...

2 commits

Author SHA1 Message Date
shafi54
64ef5d8ea6 enh 2026-10-16 20:18:56 +05:30
shafi54
fd5c532844 enh 2026-10-15 22:35:28 +05:30
19 changed files with 579 additions and 158 deletions

View file

@ -10,6 +10,7 @@ import {
import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import { REFRESH_EVENT } from "common-ui/src/lib/const-strs";
import { useStaffAuth } from "@/components/context/staff-auth-context";
import { trpc } from "@/src/trpc-client";
import { tw, MyText, theme } from "common-ui";
const SCREEN_TITLES: Record<string, string> = {
@ -33,21 +34,45 @@ const SCREEN_TITLES: Record<string, string> = {
function CustomDrawerContent() {
const router = useRouter();
const { logout, staff } = useStaffAuth();
const { logout, staff, isLoggedIn, regionId } = useStaffAuth();
// Server truth for the header: the login payload carries only regionId and a
// session restored from storage may predate this screen, so ask the API.
const { data: me } = trpc.admin.staffUser.me.useQuery(undefined, {
enabled: isLoggedIn,
});
const staffName = me?.name ?? staff?.name ?? "Unknown user";
// regionId 0 is the backend's "staff has no region" value.
const staffRegionId = me?.regionId ?? regionId;
const regionLabel =
me?.regionName ??
(staffRegionId ? `Region #${staffRegionId}` : "No region");
return (
<DrawerContentScrollView>
{staff && (
<View style={tw`p-4 border-b border-gray-200`}>
<View style={tw`p-4 border-b border-gray-200`}>
<View style={tw`flex-row items-center`}>
<MaterialIcons name="person" size={40} color="#3B82F6" />
<View style={tw`mt-2`}>
<MyText style={tw`text-lg font-semibold text-gray-800`}>
{staff.name}
<View style={tw`ml-3 flex-1`}>
<MyText
style={tw`text-lg font-semibold text-gray-800`}
numberOfLines={1}
>
{staffName}
</MyText>
<MyText style={tw`text-sm text-gray-600`}>Staff Member</MyText>
<View style={tw`flex-row items-center mt-1`}>
<MaterialIcons name="place" size={14} color="#6B7280" />
<MyText
style={tw`text-sm text-gray-600 ml-1`}
numberOfLines={1}
>
{regionLabel}
</MyText>
</View>
</View>
</View>
)}
</View>
<DrawerItem
label="Dashboard"
onPress={() => router.dismissTo("/(drawer)/dashboard" as any)}

View file

@ -4,7 +4,7 @@ import queryClient from "@/utils/queryClient";
import { DeviceEventEmitter } from "react-native";
import { FORCE_LOGOUT_EVENT } from "common-ui/src/lib/const-strs";
import { trpc } from "@/src/trpc-client";
import { saveJWT, getJWT, deleteJWT } from "@/hooks/useJWT";
import { saveJWT, getJWT, deleteJWT, saveStaff, getStaff, deleteStaff } from "@/hooks/useJWT";
import type { IdName } from '@packages/shared';
interface Staff extends IdName {
@ -38,9 +38,10 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => {
const checkAuth = async () => {
const token = await getJWT();
if (token) {
// TODO: Optionally decode token to get staff info
// Restore the staff identity saved at login so screens (e.g. the drawer
// header) still know who is signed in after a reload.
setStaff(await getStaff());
setIsLoggedIn(true);
// For now, assume staff info is not needed beyond login state
} else {
setIsLoggedIn(false);
if (!pathname.includes("login")) {
@ -60,6 +61,7 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => {
{
onSuccess: async (data) => {
await saveJWT(data.token);
await saveStaff(data.staff);
setStaff(data.staff);
setIsLoggedIn(true);
router.replace("/(drawer)/dashboard");
@ -73,6 +75,7 @@ export const StaffAuthProvider = ({ children }: { children: ReactNode }) => {
const logout = async () => {
await deleteJWT();
await deleteStaff();
setIsLoggedIn(false);
setStaff(null);
queryClient.clear();

View file

@ -1,6 +1,18 @@
import { StorageService } from 'common-ui'
export const JWT_KEY = 'jwt_token'
export const STAFF_KEY = 'staff_session'
/**
* The staff identity returned by `admin.staffUser.login`, persisted so the drawer
* can still show who is signed in after an app reload (the JWT itself only
* carries the staff name, and the region name is fetched from the API).
*/
export interface StoredStaff {
id: number
name: string
regionId?: number | null
}
export async function saveJWT(token: string) {
await StorageService.setItem(JWT_KEY, token)
@ -13,3 +25,21 @@ export async function getJWT() {
export async function deleteJWT() {
await StorageService.removeItem(JWT_KEY)
}
export async function saveStaff(staff: StoredStaff) {
await StorageService.setItem(STAFF_KEY, JSON.stringify(staff))
}
export async function getStaff(): Promise<StoredStaff | null> {
const raw = await StorageService.getItem(STAFF_KEY)
if (!raw) return null
try {
return JSON.parse(raw) as StoredStaff
} catch {
return null
}
}
export async function deleteStaff() {
await StorageService.removeItem(STAFF_KEY)
}

View file

@ -66,8 +66,8 @@ export function setupApiMocks(opts: ApiMockOptions = {}) {
return { fetchMock }
}
/** Clear the in-memory auth token + any casual storage. Call from beforeEach. */
/** Clear the in-memory auth token + cached staff identity + any casual storage. Call from beforeEach. */
export async function resetStorage() {
await StorageService.clearAll(['jwt_token'])
await StorageService.clearAll(['jwt_token', 'staff_session'])
await StorageServiceCasual.clearAll([])
}

View file

@ -12,6 +12,8 @@ export interface StaffAuthMockState {
isLoggedIn: boolean
isLoading: boolean
staff: unknown
/** Region of the signed-in staff member; suites opt in by setting this. */
regionId: number | null
isLoggingIn: boolean
loginError: string | null
login: jest.Mock
@ -22,6 +24,7 @@ export const staffAuthMock: StaffAuthMockState = {
isLoggedIn: true,
isLoading: false,
staff: { id: 1, name: 'shafi' },
regionId: null,
isLoggingIn: false,
loginError: null,
login: jest.fn(async () => {}),
@ -32,6 +35,7 @@ export function resetStaffAuthMock() {
staffAuthMock.isLoggedIn = true
staffAuthMock.isLoading = false
staffAuthMock.staff = { id: 1, name: 'shafi' }
staffAuthMock.regionId = null
staffAuthMock.isLoggingIn = false
staffAuthMock.loginError = null
}
@ -43,6 +47,7 @@ export function staffAuthContextMock() {
isLoggedIn: staffAuthMock.isLoggedIn,
isLoading: staffAuthMock.isLoading,
staff: staffAuthMock.staff,
regionId: staffAuthMock.regionId,
isLoggingIn: staffAuthMock.isLoggingIn,
loginError: staffAuthMock.loginError,
login: staffAuthMock.login,

View file

@ -79,7 +79,7 @@ jest.mock('@react-navigation/drawer', () => {
import React from 'react'
import { ActivityIndicator, DeviceEventEmitter } from 'react-native'
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import { fireEvent, screen } from '@testing-library/react-native'
import { fireEvent, screen, waitFor } from '@testing-library/react-native'
import { REFRESH_EVENT } from 'common-ui/src/lib/const-strs'
import Layout from '@/app/(drawer)/_layout'
@ -96,11 +96,21 @@ const iconByName = (name: string) =>
describe('Drawer layout', () => {
beforeEach(async () => {
resetStaffAuthMock()
staffAuthMock.regionId = 1
mockRedirects.length = 0
mockNavigation.openDrawer.mockClear()
resetRouterMock()
await resetStorage()
setupApiMocks()
setupApiMocks({
procedures: {
'admin.staffUser.me': {
id: 1,
name: 'shafi',
regionId: 1,
regionName: 'Hyderabad',
},
},
})
jest.spyOn(DeviceEventEmitter, 'emit')
})
@ -121,11 +131,11 @@ describe('Drawer layout', () => {
expect(mockRedirects).toEqual(['/login'])
})
it('renders the staff name and navigation items', () => {
it('renders the staff name, region and navigation items', async () => {
renderWithProviders(<Layout />)
expect(screen.getByText('shafi')).toBeVisible()
expect(screen.getByText('Staff Member')).toBeVisible()
await waitFor(() => expect(screen.getByText('Hyderabad')).toBeVisible())
expect(screen.getByText('Dashboard')).toBeVisible()
expect(screen.getByText('Products')).toBeVisible()
expect(screen.getByText('Prices Overview')).toBeVisible()

View file

@ -1,4 +1,4 @@
import { router, publicProcedure, protectedProcedure } from '@/src/trpc/trpc-index'
import { router, publicProcedure, protectedProcedure, staffProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod';
import bcrypt from 'bcryptjs';
import { SignJWT } from 'jose';
@ -12,6 +12,7 @@ import {
createStaffUser,
getAllRoles,
upsertStaffNotifCred,
getRegionById,
} from '@/src/dbService'
import { notifyAllAdmins } from '@/src/lib/admin-notif'
@ -51,6 +52,17 @@ export const staffUserRouter = router({
};
}),
/**
* The signed-in staff member plus their region name. The login payload only
* carries `regionId`, so clients (e.g. the admin-ui drawer header) use this to
* show who is signed in without decoding the JWT.
*/
me: staffProcedure.query(async ({ ctx }) => {
const { id, name, regionId } = ctx.staffUser!
const region = regionId ? await getRegionById(regionId) : null
return { id, name, regionId, regionName: region?.name ?? null }
}),
getStaff: protectedProcedure
.query(async ({ ctx }) => {
const staff = await getAllStaff();

View file

@ -56,6 +56,14 @@ export const superadminRegionsRouter = router({
.input(z.object({
name: z.string().min(1),
description: z.string().nullish(),
// Optional explicit region centre; falls back to the first-priority bound's
// computed centre.
center: z
.object({
lat: z.number().min(-90).max(90),
lng: z.number().min(-180).max(180),
})
.nullish(),
// A region is unusable without bounds; at least one must be provided.
bounds: z
.array(z.object({
@ -70,6 +78,7 @@ export const superadminRegionsRouter = router({
const { region, bounds } = await createRegionWithBounds({
name: input.name,
description: input.description ?? null,
center: input.center ?? null,
bounds: input.bounds.map((bound) => ({
description: bound.description ?? null,
geojson: bound.geojson,

View file

@ -1,8 +1,5 @@
import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router'
import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'
import { TanStackDevtools } from '@tanstack/react-devtools'
import { QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import { trpc, getTrpcClient } from '../lib/trpc-client'
import { getQueryClient } from '../lib/query-client'
import { AuthProvider } from '../lib/auth-context'
@ -43,19 +40,9 @@ function RootDocument({ children }: { children: React.ReactNode }) {
<div id="app">{children}</div>
{/* Imperative alert()/confirm()/prompt() dialogs (shadcn AlertDialog). */}
<DialogHost />
<ReactQueryDevtools />
</AuthProvider>
</trpc.Provider>
</QueryClientProvider>
<TanStackDevtools
config={{ position: 'bottom-right' }}
plugins={[
{
name: 'Tanstack Router',
render: <TanStackRouterDevtoolsPanel />,
},
]}
/>
<Scripts />
</body>
</html>

View file

@ -112,6 +112,8 @@ function CreateRegionForm({ onCreated }: { onCreated: (regionId: number) => void
const [name, setName] = useState('')
const [description, setDescription] = useState('')
const [centerLat, setCenterLat] = useState('')
const [centerLng, setCenterLng] = useState('')
const [bounds, setBounds] = useState<BoundDraft[]>([emptyBound()])
const [error, setError] = useState<string | null>(null)
@ -145,14 +147,33 @@ function CreateRegionForm({ onCreated }: { onCreated: (regionId: number) => void
}
})
// Optional region centre. Both fields or neither; otherwise the first
// bound's geometry decides it.
const hasLat = centerLat.trim() !== ''
const hasLng = centerLng.trim() !== ''
if (hasLat !== hasLng) {
throw new Error('Region Center needs both a latitude and a longitude')
}
const lat = Number(centerLat)
const lng = Number(centerLng)
const center = hasLat
? { lat, lng }
: null
if (center && (!Number.isFinite(lat) || !Number.isFinite(lng))) {
throw new Error('Region Center must be numeric')
}
const result = await createRegion.mutateAsync({
name: name.trim(),
description: description.trim() || null,
center,
bounds: parsedBounds,
})
setName('')
setDescription('')
setCenterLat('')
setCenterLng('')
setBounds([emptyBound()])
utils.superadmin.regions.list.invalidate()
onCreated(result.id)
@ -183,6 +204,25 @@ function CreateRegionForm({ onCreated }: { onCreated: (regionId: number) => void
/>
</div>
<div className="mt-3 grid gap-3 sm:grid-cols-2">
<PInput
topLabel="Region Center — Latitude (optional)"
value={centerLat}
onChange={(e) => setCenterLat(e.target.value)}
placeholder="e.g. 16.7488"
/>
<PInput
topLabel="Region Center — Longitude (optional)"
value={centerLng}
onChange={(e) => setCenterLng(e.target.value)}
placeholder="e.g. 77.9851"
/>
</div>
<MyText className="mt-1 block text-xs text-gray-500">
Leave both empty to use the centre of the first-priority bound. Used to focus a map on the
region.
</MyText>
<div className="mt-5 rounded-lg border border-gray-200 bg-gray-50 p-4">
<div className="mb-3 flex items-center justify-between">
<MyText className="block text-sm font-semibold text-gray-700">

View file

@ -6,7 +6,7 @@ import { tw, MyText, MyTouchableOpacity , Checkbox , MyTextInput , LoadingDialog
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { trpc } from '../trpc-client';
import LocationMapStep from './location/LocationMapStep';
import type { AddressFormProps } from '@packages/shared';
import type { AddressFormProps, RegionSummary } from '@packages/shared';
import { savePendingAddress } from '@/src/lib/pending-address';
import { useRegion } from '@/src/hooks/useRegion';
import { useLocationStore } from '@/src/store/locationStore';
@ -51,46 +51,40 @@ const AddressForm: React.FC<AddressFormProps> = ({
const [cityOpen, setCityOpen] = useState(false);
const cityName = regions.find((region) => region.id === resolvedRegion?.regionId)?.name ?? '';
// The map focuses on the region the address will belong to: the region a picked
// location resolved to, else the browsing region. Its stored centre
// (first-priority bound) becomes the map's centre.
const mapRegion =
regions.find((region) => region.id === (resolvedRegion?.regionId ?? browsingRegionId)) ?? null;
/** Centre the map WebView opens on (null = the page's own default). */
const [mapCenter, setMapCenter] = useState<{ lat: number; lng: number } | null>(null);
/**
* The pending "which region is this map for?" confirmation. Only the two
* location triggers ask — the City selector's "Select in Map" opens straight
* away. Null means no dialog.
* Region picker for the map: the two location triggers list every region and
* the chosen one becomes the map's centre. ("Select in Map" skips it.)
*/
const [mapDialog, setMapDialog] = useState<{ regionName: string | null } | null>(null);
const [mapRegionPickerOpen, setMapRegionPickerOpen] = useState(false);
const requestMapForAddressRegion = useCallback(() => {
Keyboard.dismiss();
setMapCenter(mapRegion?.center ?? null);
setMapDialog({ regionName: mapRegion?.name ?? null });
}, [mapRegion]);
setMapRegionPickerOpen(true);
}, []);
// The City selector's fallback: no town picked, so open the map straight away,
// focused on the first region's bound (the first row of that selector).
// Picked a region in that list: open the map focused on its bound.
const openMapAtRegion = useCallback((region: RegionSummary) => {
setMapRegionPickerOpen(false);
setMapCenter(region.center ?? null);
setMapOpen(true);
}, []);
const closeMapRegionPicker = useCallback(() => {
setMapRegionPickerOpen(false);
}, []);
// "Select in Map" (City selector and region picker): no region named, so open
// the map straight away on the first region's bound.
const openMapForFirstRegion = useCallback(() => {
const firstRegion = regions[0] ?? null;
setCityOpen(false);
setMapRegionPickerOpen(false);
setMapCenter(firstRegion?.center ?? null);
setMapOpen(true);
}, [regions]);
const confirmMapDialog = useCallback(() => {
setMapDialog(null);
setMapOpen(true);
}, []);
const dismissMapDialog = useCallback(() => {
setMapDialog(null);
setMapCenter(null);
}, []);
const closeMap = useCallback(() => {
setMapOpen(false);
setMapCenter(null);
@ -382,10 +376,9 @@ const AddressForm: React.FC<AddressFormProps> = ({
<MyTouchableOpacity
testID="address-city-option-map"
onPress={openMapForFirstRegion}
style={tw`p-3 flex-row items-center`}
style={tw`p-3 border-b border-gray-50 flex-row items-center justify-between`}
>
<MaterialIcons name="map" size={18} color="#3B82F6" />
<MyText style={tw`text-blue-500 font-medium ml-2`}>Select in Map</MyText>
<MyText style={tw`text-gray-800`}>Select in Map</MyText>
</MyTouchableOpacity>
</View>
)}
@ -480,43 +473,56 @@ const AddressForm: React.FC<AddressFormProps> = ({
message={isEdit ? "Updating address..." : "Adding address..."}
/>
{/* Confirm the region before handing over to the map WebView, which opens
focused on that region's centre. ("Select in Map" skips this.) */}
<BottomDialog open={mapDialog !== null} onClose={dismissMapDialog}>
{/* Region picker: the map opens focused on whichever region is chosen. */}
<BottomDialog open={mapRegionPickerOpen} onClose={closeMapRegionPicker}>
<View style={tw`p-6`}>
<View style={tw`flex-row items-center mb-3`}>
<View style={tw`flex-row items-center mb-1`}>
<View style={tw`w-10 h-10 bg-blue-50 rounded-full items-center justify-center mr-3`}>
<MaterialIcons name="map" size={20} color="#2563EB" />
</View>
<MyText style={tw`text-lg font-bold text-gray-900 flex-1`}>
{mapDialog?.regionName
? `Open the map for ${mapDialog.regionName}?`
: 'Open the map?'}
</MyText>
<MyText style={tw`text-lg font-bold text-gray-900 flex-1`}>Select a region</MyText>
</View>
<MyText style={tw`text-gray-600 text-sm`}>
{mapDialog?.regionName
? `The map will open on ${mapDialog.regionName}. Pick a point inside this region.`
: 'Pick a point on the map.'}
<MyText style={tw`text-gray-500 text-sm mb-4`}>
The map opens on the region you pick.
</MyText>
<View style={tw`flex-row gap-3 mt-6`}>
{regions.map((region) => (
<MyTouchableOpacity
testID="address-map-confirm-cancel"
onPress={dismissMapDialog}
style={tw`flex-1 border border-gray-200 py-3.5 rounded-xl items-center`}
key={region.id}
testID={`address-map-region-${region.id}`}
onPress={() => openMapAtRegion(region)}
activeOpacity={0.7}
style={tw`py-3 border-b border-gray-50 flex-row items-center justify-between`}
>
<MyText style={tw`text-gray-700 font-bold`}>Cancel</MyText>
<MyText style={tw`text-gray-800`}>{region.name}</MyText>
{region.id === (resolvedRegion?.regionId ?? browsingRegionId) && (
<MyText style={tw`text-xs text-gray-400`}>Current</MyText>
)}
</MyTouchableOpacity>
<MyTouchableOpacity
testID="address-map-confirm-open"
onPress={confirmMapDialog}
style={tw`flex-1 bg-brand500 py-3.5 rounded-xl items-center`}
>
<MyText style={tw`text-white font-bold`}>Open map</MyText>
</MyTouchableOpacity>
</View>
))}
{regions.length === 0 && (
<MyText style={tw`text-gray-400 text-sm py-3`}>No regions available</MyText>
)}
{/* After the regions: skip naming one and open the map on the first
region's bound. Styled as just another option in the list. */}
<MyTouchableOpacity
testID="address-map-region-select-in-map"
onPress={openMapForFirstRegion}
activeOpacity={0.7}
style={tw`py-3 border-b border-gray-50 flex-row items-center`}
>
<MyText style={tw`text-gray-800`}>Select in Map</MyText>
</MyTouchableOpacity>
<MyTouchableOpacity
testID="address-map-region-cancel"
onPress={closeMapRegionPicker}
style={tw`mt-3 border border-gray-200 py-3.5 rounded-xl items-center`}
>
<MyText style={tw`text-gray-700 font-bold`}>Cancel</MyText>
</MyTouchableOpacity>
</View>
</BottomDialog>

View file

@ -53,15 +53,31 @@ 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`}>
{region?.name ?? 'Choose your address'}
</MyText>
</MyText>
<View style={tw`flex-row items-center`}>
<MyText style={tw`text-xs text-gray-500 mr-2`}>Deliver to</MyText>
{region ? (
// The active region gets a tinted pill so it reads at a glance; the
// pill shrinks (flex-shrink) so a long name truncates instead of
// pushing the chevron out of the row.
<View style={tw`bg-brand50 px-2 py-0.5 rounded-full flex-shrink`}>
<MyText
weight="bold"
style={tw`text-sm text-brand500`}
numberOfLines={1}
ellipsizeMode="tail"
>
{region.name}
</MyText>
</View>
) : (
<MyText style={tw`text-sm text-gray-500`} numberOfLines={1} ellipsizeMode="tail">
Choose your address
</MyText>
)}
</View>
{activeAddress ? (
<MyText
style={tw`text-xs text-gray-500 mt-0.5`}
style={tw`text-xs text-gray-500 mt-1`}
numberOfLines={2}
ellipsizeMode="tail"
>

View file

@ -5,6 +5,7 @@ import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import { MyText, MyTouchableOpacity, tw, theme } from 'common-ui'
import { trpc } from '@/src/trpc-client'
import { useAuthOptional } from '@/src/contexts/AuthContext'
import { useAddressStore } from '@/src/store/addressStore'
import { confirmRegionSwitch } from '@/src/lib/region-switch'
import AddressForm from '@/src/components/AddressForm'
import Login from '@/app/(auth)/login'
@ -52,6 +53,8 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({ onClose, no
const utils = trpc.useUtils()
const auth = useAuthOptional()
const isAuthenticated = auth?.isAuthenticated ?? false
const setSelectedAddressId = useAddressStore((state) => state.setSelectedAddressId)
const selectedAddressId = useAddressStore((state) => state.selectedAddressId)
const [mode, setMode] = useState<'choose' | 'add' | 'login'>('choose')
const [busy, setBusy] = useState(false)
@ -72,17 +75,25 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({ onClose, no
const addresses = (addressesQuery.data?.data ?? []) as unknown as ChooserAddress[]
// The address the app treats as active: an explicit pick (bar / cart / this
// sheet) wins, otherwise the default. Same precedence as LocationBar,
// CheckoutAddressSelector and CheckoutAddressDisplay, so the sheet cannot
// disagree with the bar it was opened from.
const activeAddressId =
selectedAddressId ?? addresses.find((address) => address.isDefault)?.id ?? null
const activate = useCallback(
async (regionId: number, boundId: number | null) => {
async (regionId: number, boundId: number | null): Promise<boolean> => {
setBusy(true)
try {
const regions = await utils.common.listRegions.fetch()
const region = regions.find((candidate) => candidate.id === regionId)
if (!region) {
setMessage('This location is no longer serviceable.')
return
return false
}
await confirmRegionSwitch(region, queryClient, boundId)
return true
} finally {
setBusy(false)
}
@ -110,10 +121,15 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({ onClose, no
}
}
await activate(address.regionId, boundId)
const switched = await activate(address.regionId, boundId)
// Record the pick AFTER the switch: confirmRegionSwitch clears the
// selection, so setting it before would be wiped.
if (switched) {
setSelectedAddressId(address.id)
}
onClose?.()
},
[activate, onClose, utils]
[activate, onClose, setSelectedAddressId, utils]
)
const handleSetDefault = useCallback(
@ -148,13 +164,19 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({ onClose, no
[updateAddress, utils]
)
const handleFormSuccess = useCallback(async () => {
const resolved = resolvedRef.current
if (resolved) {
await activate(resolved.regionId, resolved.boundId)
}
onClose?.()
}, [activate, onClose])
const handleFormSuccess = useCallback(
async (addressId?: number) => {
const resolved = resolvedRef.current
const switched = resolved ? await activate(resolved.regionId, resolved.boundId) : true
// Same ordering rule as handleSelect. No id while signed out (the draft is
// posted later by PendingAddressSync), so only select when we have one.
if (switched && addressId != null) {
setSelectedAddressId(addressId)
}
onClose?.()
},
[activate, onClose, setSelectedAddressId]
)
if (mode === 'login') {
return (
@ -245,37 +267,46 @@ const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({ onClose, no
)}
{isAuthenticated &&
addresses.map((address) => (
<View
key={address.id}
style={tw`bg-white border border-gray-100 rounded-2xl p-4 mb-3 shadow-sm`}
>
<MyTouchableOpacity disabled={busy} onPress={() => handleSelect(address)}>
<View style={tw`flex-row items-center mb-1`}>
<MyText style={tw`text-base font-bold text-gray-900 mr-2`}>{address.name}</MyText>
{address.isDefault && (
<View style={tw`bg-green-100 px-2 py-0.5 rounded-full`}>
<MyText style={tw`text-green-700 text-[10px] font-semibold`}>Default</MyText>
</View>
)}
</View>
<MyText style={tw`text-gray-600 text-sm`}>
{address.addressLine1}
{address.addressLine2 ? `, ${address.addressLine2}` : ''}, {address.city}
</MyText>
</MyTouchableOpacity>
{!address.isDefault && (
<MyTouchableOpacity
onPress={() => handleSetDefault(address)}
disabled={busy || updateAddress.isPending}
style={tw`mt-2 self-start`}
>
<MyText style={tw`text-blue-500 text-xs font-medium`}>Set as default</MyText>
addresses.map((address) => {
const isActive = address.id === activeAddressId
return (
<View
key={address.id}
style={tw`border rounded-2xl p-4 mb-3 shadow-sm ${isActive ? 'bg-brand50 border-brand500' : 'bg-white border-gray-100'
}`}
>
<MyTouchableOpacity disabled={busy} onPress={() => handleSelect(address)}>
<View style={tw`flex-row items-center mb-1`}>
<MyText style={tw`text-base font-bold text-gray-900 mr-2`}>{address.name}</MyText>
{address.isDefault && (
<View style={tw`bg-green-100 px-2 py-0.5 rounded-full`}>
<MyText style={tw`text-green-700 text-[10px] font-semibold`}>Default</MyText>
</View>
)}
{isActive && (
<View style={tw`ml-auto bg-brand500 w-5 h-5 rounded-full items-center justify-center`}>
<MaterialIcons name="check" size={14} color="white" />
</View>
)}
</View>
<MyText style={tw`text-gray-600 text-sm`}>
{address.addressLine1}
{address.addressLine2 ? `, ${address.addressLine2}` : ''}, {address.city}
</MyText>
</MyTouchableOpacity>
)}
</View>
))}
{!address.isDefault && (
<MyTouchableOpacity
onPress={() => handleSetDefault(address)}
disabled={busy || updateAddress.isPending}
style={tw`mt-2 self-start`}
>
<MyText style={tw`text-blue-500 text-xs font-medium`}>Set as default</MyText>
</MyTouchableOpacity>
)}
</View>
)
})}
{isAuthenticated && !addressesQuery.isLoading && addresses.length === 0 && (
<MyText style={tw`text-gray-500 mb-3`}>No saved addresses yet.</MyText>

View file

@ -39,11 +39,14 @@ export async function confirmRegionSwitch(
// 1b. Clear the persisted local carts (regular + flash).
await Promise.all([clearLocalCart('regular'), clearLocalCart('flash')])
// 1c. Drop the chosen address: it belongs to the region we are leaving.
// A same-region switch (e.g. just picking another saved address) keeps it.
useAddressStore.getState().setSelectedAddressId(null)
}
// 2. Drop in-memory checkout / quick-delivery selections.
useQuickDeliveryStore.getState().setSelectedSlotId(null)
useAddressStore.getState().setSelectedAddressId(null)
useSlotStore.getState().setSlotId(undefined)
useSlotStore.getState().setStoreId(undefined)
useCartStore.getState().clearAddedToCartProduct()

View file

@ -1,8 +1,5 @@
import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router'
import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'
import { TanStackDevtools } from '@tanstack/react-devtools'
import { QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import { trpc, getTrpcClient } from '../lib/trpc-client'
import { getQueryClient } from '../lib/query-client'
import { AuthProvider } from '../lib/auth-context'
@ -43,19 +40,9 @@ function RootDocument({ children }: { children: React.ReactNode }) {
<RegionGate>
<div id="app">{children}</div>
</RegionGate>
<ReactQueryDevtools />
</AuthProvider>
</trpc.Provider>
</QueryClientProvider>
<TanStackDevtools
config={{ position: 'bottom-right' }}
plugins={[
{
name: 'Tanstack Router',
render: <TanStackRouterDevtoolsPanel />,
},
]}
/>
<Scripts />
</body>
</html>

View file

@ -8,7 +8,13 @@ export const Route = createFileRoute('/location-selector')({
// Optional centre override (?lat=&lng=&zoom=) so the map can be opened for a
// specific region; defaults to the Mahabubnagar town centre.
validateSearch: (search: Record<string, unknown>) => {
// TanStack's default search parser is parseSearchWith(JSON.parse), so
// `?lat=16.3570899` arrives here as a NUMBER, not a string. Accept both:
// requiring a string made every param validate to undefined, which dropped
// the query string from the URL entirely and left the map on its default
// centre for every region.
const num = (value: unknown): number | undefined => {
if (typeof value === 'number') return Number.isFinite(value) ? value : undefined
if (typeof value !== 'string' || value.trim() === '') return undefined
const parsed = Number(value)
return Number.isFinite(parsed) ? parsed : undefined
@ -65,7 +71,7 @@ type GoogleWindow = Window & {
// Mahabubnagar (Mahbubnagar), Telangana, India — default map center.
const MAHABUBNAGAR_CENTER: LatLngLiteral = { lat: 16.7488, lng: 77.9851 }
const DEFAULT_ZOOM = 12
const DEFAULT_ZOOM = 15
// Google Maps JS API key. Provide it via a Vite env var, e.g. in
// apps/web-ui/.env:

View file

@ -4791,3 +4791,233 @@ user-ui
the first region's bound and opens the map in the same step, skipping the dialog; the two
location triggers still ask first.
No other file changed. No tests run.
2026-10-15 22:21:05 Map trigger: the dialog is now a REGION PICKER, not a confirmation.
apps/user-ui/src/components/AddressForm.tsx
- replaced the "Open the map for <region>?" confirmation with a BottomDialog listing every
region (`address-map-region-<id>`, current one marked). Picking a region opens the map
focused on that region's bound centre (its `center`), in one step.
- state: `mapDialog {regionName}` -> `mapRegionPickerOpen`; + openMapAtRegion(region) and
closeMapRegionPicker(); the now-unused `mapRegion` selector was removed. "Select in Map"
still opens straight away on the first region's bound.
No other file changed. No tests run.
2026-10-15 22:27:30 Region picker: + "Select in Map" row after the region list.
apps/user-ui/src/components/AddressForm.tsx
- the map-trigger region picker now ends with a "Select in Map" row
(`address-map-region-select-in-map`) below the listed regions, which opens the map
straight away on the FIRST region's bound - same behaviour as the City selector's row.
- openMapForFirstRegion() also closes the picker, so it serves both entry points.
No other file changed. No tests run.
2026-10-15 22:31:10 "Select in Map" is no longer highlighted - it reads as a normal list option.
apps/user-ui/src/components/AddressForm.tsx
- dropped the blue icon + blue label from both "Select in Map" rows (region picker and City
selector) so they read as plain options, matching the region rows (text-gray-800, same
row padding/border). MaterialIcons is still used elsewhere in the file.
No other file changed. No tests run.
2026-10-15 22:52:40 FIX: the map page ignored ?lat/?lng, so every region opened on the default
centre (Mahabubnagar) - i.e. "all regions show the first region's area".
apps/web-ui/src/routes/location-selector.tsx
- validateSearch's num() required a STRING, but TanStack Router's default parser is
parseSearchWith(JSON.parse): `?lat=16.3570899` arrives already as a NUMBER. Every param
therefore validated to undefined and the router rewrote the URL with no search at all
(verified in a browser: location.search === '' after loading with params), leaving the map
on MAHABUBNAGAR_CENTER.
- num() now accepts a number as well as a numeric string.
Pre-existing bug (the ?lat=&lng=&zoom= support was there but never actually worked); the
region-centre work is what surfaced it. No other file changed. No tests run.
2026-10-15 22:40:15 Map page: a little more zoom by default.
apps/web-ui/src/routes/location-selector.tsx
- DEFAULT_ZOOM 12 -> 13 (used when no ?zoom= is supplied; user-ui never sends one, so this
is what every region open uses). handleZoom's fallback follows automatically.
No other file changed. No tests run.
2026-10-15 22:44:20 Map page: default zoom 13 -> 18 (requested).
apps/web-ui/src/routes/location-selector.tsx - DEFAULT_ZOOM = 18.
No other file changed. No tests run.
2026-10-15 22:47:05 Map page: default zoom 18 -> 15 (requested).
apps/web-ui/src/routes/location-selector.tsx - DEFAULT_ZOOM = 15.
No other file changed. No tests run.
2026-10-15 22:56:10 Superadmin "Add a region": optional Region Center.
packages/shared/types/region.types.ts
- CreateRegionWithBoundsInput + `center?: RegionCenter | null` (optional explicit region centre).
packages/db_helper_sqlite/src/superadmin-apis/regions.ts
- createRegionWithBounds: an explicit `center` is stored on the region's FIRST-PRIORITY bound
(the numerically-lowest priority among the submitted bounds, which is what RegionSummary
.center reads); every other bound still computes its own bounding-box centre. Without it,
nothing changes - it computes as before.
apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts
- superadmin.regions.create input + optional `center { lat, lng }` (range-validated).
apps/superadmin-ui/src/routes/regions.tsx
- CreateRegionForm: two optional inputs "Region Center - Latitude/Longitude" with a hint that
leaving them empty uses the first-priority bound's centre; both-or-neither, numeric.
Verification: first-priority selection checked numerically (10 vs 2, ties, decimals) - no live
region created (there is no delete-region procedure, and creation also seeds market rows and
writes cache files). No tests run.
2026-10-16 09:12:40 web-ui: removed the TanStack Devtools floating button (bottom right).
apps/web-ui/src/routes/__root.tsx
- dropped the <TanStackDevtools config={{position:'bottom-right'}} plugins=[TanStack Router]>
block and its two imports (TanStackDevtools, TanStackRouterDevtoolsPanel).
- left the `devtools()` Vite plugin alone: it is the source-injection plugin (it is what adds
the data-tsd-source attributes) and does not render any UI. ReactQueryDevtools is untouched
(separate tool, not the bottom-right symbol).
No other file changed. No tests run.
2026-10-16 10:55:10 web-ui: the bottom-right symbol was actually the React Query devtools toggle.
apps/web-ui/src/routes/__root.tsx
- also removed <ReactQueryDevtools /> and its import. Measured in a browser at 420x880 it sat
at left 364 / top 824 (bottom-right corner) with aria-label "Open Tanstack query devtools" -
that is the floating symbol, not the TanStackDevtools block removed just above.
- __root.tsx now renders no devtools UI at all.
No other file changed. No tests run.
2026-10-16 11:05:30 superadmin-ui: same devtools removal as web-ui (not tested, per request).
apps/superadmin-ui/src/routes/__root.tsx
- removed <ReactQueryDevtools /> (the bottom-right TanStack logo toggle - the actual floating
symbol in web-ui) and the <TanStackDevtools config={{position:'bottom-right'}}> block, plus
their three imports (TanStackDevtools, TanStackRouterDevtoolsPanel, ReactQueryDevtools).
- left the `devtools()` Vite plugin: it only augments the <TanStackDevtools> JSX element
(confirmed in @tanstack/devtools-vite's inject-plugin.js), so with the component gone it
renders nothing.
No other file changed. Nothing run/verified, per instruction.
2026-10-16 18:34:20 admin-ui: nav drawer header now shows who is logged in + their region.
Problem: the drawer header read `staff` from StaffAuthContext, but the context only set `staff`
inside the login mutation's onSuccess - `checkAuth` restored just the JWT - so after any reload
`staff` was null and the header block vanished (and it showed a hardcoded "Staff Member", never
the region). The login response carries only `regionId`, not a region name.
apps/admin-ui/hooks/useJWT.ts
+ export const STAFF_KEY = 'staff_session'
+ export interface StoredStaff { id: number; name: string; regionId?: number | null }
+ saveStaff(staff) / getStaff(): Promise<StoredStaff | null> / deleteStaff()
(JSON in SecureStore via common-ui StorageService, same mechanism as the JWT).
apps/admin-ui/components/context/staff-auth-context.tsx
- import saveStaff/getStaff/deleteStaff.
- checkAuth: when a token exists, `setStaff(await getStaff())` so the identity survives reloads.
- login onSuccess: `await saveStaff(data.staff)` before setStaff.
- logout: `await deleteStaff()` alongside deleteJWT.
apps/admin-ui/app/(drawer)/_layout.tsx
- CustomDrawerContent now also reads isLoggedIn + regionId from useStaffAuth and calls
`trpc.admin.region.current.useQuery(undefined, { enabled: isLoggedIn && regionId != null })`
(region name is not in the login payload).
- header: avatar icon + staff.name, and below it a place icon + region name
(falls back to `Region #<regionId>` then "No region" while the query loads/fails);
replaces the hardcoded "Staff Member" subtitle. Header no longer hidden when staff is null.
apps/admin-ui/tests/mocks/api.ts
- resetStorage() also clears 'staff_session' so the real-provider tests stay isolated.
apps/admin-ui/tests/mocks/staff-auth.ts
- StaffAuthMockState/context mock expose `regionId` (default null) so suites can enable the
region query without changing the default `staff` shape (keeps VendorSnippetForm tests as-is).
apps/admin-ui/tests/screens/drawer-layout.test.tsx
- beforeEach seeds regionId=1 + an 'admin.region.current' procedure; the header test asserts the
region name instead of "Staff Member".
No migrations. No other file changed.
2026-10-16 18:52:10 admin-ui + backend: drawer header reads a new `me` endpoint (server truth).
Why the extra endpoint: sessions that are already signed in when this update ships have a JWT but
no cached staff row, so they would render "Unknown user / No region" until a fresh login. The
tRPC context already resolves the staff row (id, name, regionId) on every request, so exposing it
is cheap and fixes existing sessions too.
apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts
+ import staffProcedure, getRegionById.
+ me: staffProcedure.query -> { id, name, regionId, regionName } (regionName from getRegionById,
null when the staff has no region). Placed right after `login`.
No DB/schema/migration changes; superadmin + user routers untouched.
apps/admin-ui/app/(drawer)/_layout.tsx
~ swapped the region.current query for `trpc.admin.staffUser.me.useQuery(undefined,
{ enabled: isLoggedIn })`.
- staffName = me.name ?? cached staff.name ?? "Unknown user"
- regionLabel = me.regionName ?? `Region #<id>` ?? "No region"
~ header shows the staff name (was hardcoded "Staff Member" subtitle before) + region row.
apps/admin-ui/tests/screens/drawer-layout.test.tsx
~ the mocked procedure is now 'admin.staffUser.me' (id/name/regionId/regionName: 'Hyderabad').
2026-10-16 18:58:40 dev DB (local D1, freshyo-dev): created a user via apps/backend scripts/create-user.ts.
cd apps/backend
bun run create-user -- --mobile 9000000001 --password "meatfarmer@123"
Local target (no --remote): wrangler.dev.toml -> freshyo-dev, `wrangler d1 execute --local`.
Writes `users` (name/email/mobile) + `user_creds` (bcrypt, 12 rounds). No repo file changed.
2026-10-16 19:24:05 user-ui: home-page address pick never reached the cart (it showed the default).
Root cause (two parts):
1. The LocationBar -> AddressSwitcherSheet -> LocationFallbackFlow path only called activate()
(= confirmRegionSwitch, i.e. region/bound only) and never wrote the chosen address to the
shared useAddressStore. Only QuickDeliveryAddressSelector's list tap and the cart page's
CheckoutAddressSelector ever set it.
2. confirmRegionSwitch unconditionally reset setSelectedAddressId(null) (step 2), even for a
same-region switch, so a selection could not survive the switch either.
Result: selectedAddressId stayed null -> CheckoutAddressSelector's "auto-select default" effect,
LocationBar's and CheckoutAddressDisplay's `?? isDefault` fallbacks all showed the default.
apps/user-ui/src/components/location/LocationFallbackFlow.tsx
+ import useAddressStore; read setSelectedAddressId from the store.
~ handleSelect: after `await activate(...)` (which clears it), set the picked address id.
~ handleFormSuccess(addressId?): after activate, set the new address id when AddressForm
returns one (the signed-out draft posts later via PendingAddressSync, so no id there).
Ordering is deliberate: set AFTER the switch, because the switch clears the selection.
apps/user-ui/src/lib/region-switch.ts
~ moved `useAddressStore.getState().setSelectedAddressId(null)` out of step 2 into the
`if (!isSameRegion)` block (new step 1c): a same-region switch keeps the address the user
just picked; a real region change still drops it (it may not exist in the new region).
No other file changed. Callers that switch region on a cross-region address tap (cart page,
QuickDeliveryAddressSelector) still do not re-record it - left as-is on purpose.
2026-10-16 19:58:20 user-ui: top address bar now highlights the active region as a coloured chip.
apps/user-ui/src/components/LocationBar.tsx (only file)
- before: one grey line "Deliver to: <region>" (region inline, bold, text-gray-900).
- after: a thin grey "Deliver to" label + the region as a brand-tinted pill
(bg-brand50 #EFF8FF / text-brand500 #2E90FA, rounded-full, py-0.5 px-2), bold, single
line with ellipsis; the pill is flex-shrink so a long region truncates instead of pushing
the chevron off. Address line unchanged (moved to mt-1, still up to 2 lines, grey).
- the null-region fallback ("Choose your address") stays plain grey, not pill-highlighted.
- read-only styling: still the same tap target (testID="location-bar") opening the sheet;
region still comes from useRegion(), no store/API changes.
Shared component, so the chip also shows on Me, Stores, Order-again and the 1 Hr Delivery
section (SlotSpecificView -> QuickDeliveryAddressSelector). No test referenced 'Deliver to' or
'location-bar'. No backend/schema changes.
2026-10-16 20:12:40 user-ui: the address switcher now highlights the active address.
apps/user-ui/src/components/location/LocationFallbackFlow.tsx
~ reads selectedAddressId from useAddressStore (it previously only wrote it) and derives
activeAddressId = selectedAddressId ?? the isDefault address id - the same precedence the
location bar, cart CheckoutAddressSelector and checkout CheckoutAddressDisplay already use,
so the sheet can no longer disagree with the bar it was opened from.
~ the active card: bg-brand50 + border-brand500 (was bg-white + border-gray-100) plus a
brand500 check circle at the right of the name row (mirrors the selected card in
CheckoutAddressSelector). The green "Default" badge and the "Set as default" link are
unchanged - a default is not necessarily the active address.
No store/API/backend changes; the sheet still selects via handleSelect.

View file

@ -215,17 +215,32 @@ export async function createRegionWithBounds(
.returning()
try {
// The region's centre is its first-priority bound's centre, so an explicit
// `center` overrides that bound's computed one. Every other bound keeps its
// own bounding-box centre.
const firstPriorityIndex = input.bounds.reduce(
(best, bound, index) =>
Number(bound.priority) < Number(input.bounds[best].priority) ? index : best,
0
)
const inserted = await tx
.insert(regionBounds)
.values(
input.bounds.map((bound) => ({
regionId: region.id,
description: bound.description ?? null,
geojson: bound.geojson,
priority: String(bound.priority),
centerLat: boundCenter(bound.geojson)?.lat ?? null,
centerLng: boundCenter(bound.geojson)?.lng ?? null,
}))
input.bounds.map((bound, index) => {
const center =
index === firstPriorityIndex && input.center != null
? input.center
: boundCenter(bound.geojson)
return {
regionId: region.id,
description: bound.description ?? null,
geojson: bound.geojson,
priority: String(bound.priority),
centerLat: center?.lat ?? null,
centerLng: center?.lng ?? null,
}
})
)
.returning()

View file

@ -92,6 +92,12 @@ export interface RegionBoundSeedInput {
/** Every region must be created with at least one bound. */
export interface CreateRegionWithBoundsInput extends CreateRegionInput {
bounds: RegionBoundSeedInput[]
/**
* Optional explicit centre for the region. It is stored on the region's
* first-priority bound (the one whose centre the region reports); every other
* bound computes its own from its geometry. Omit to compute it too.
*/
center?: RegionCenter | null
}
export interface UpdateRegionInput {