diff --git a/apps/admin-ui/app/(drawer)/_layout.tsx b/apps/admin-ui/app/(drawer)/_layout.tsx index a559e81..684b053 100644 --- a/apps/admin-ui/app/(drawer)/_layout.tsx +++ b/apps/admin-ui/app/(drawer)/_layout.tsx @@ -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 = { @@ -33,21 +34,45 @@ const SCREEN_TITLES: Record = { 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 ( - {staff && ( - + + - - - {staff.name} + + + {staffName} - Staff Member + + + + {regionLabel} + + - )} + router.dismissTo("/(drawer)/dashboard" as any)} diff --git a/apps/admin-ui/components/context/staff-auth-context.tsx b/apps/admin-ui/components/context/staff-auth-context.tsx index 6dd5858..6ea7dfc 100644 --- a/apps/admin-ui/components/context/staff-auth-context.tsx +++ b/apps/admin-ui/components/context/staff-auth-context.tsx @@ -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(); diff --git a/apps/admin-ui/hooks/useJWT.ts b/apps/admin-ui/hooks/useJWT.ts index 8576f18..580fe18 100755 --- a/apps/admin-ui/hooks/useJWT.ts +++ b/apps/admin-ui/hooks/useJWT.ts @@ -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 { + 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) +} diff --git a/apps/admin-ui/tests/mocks/api.ts b/apps/admin-ui/tests/mocks/api.ts index f830e2f..d686a6d 100644 --- a/apps/admin-ui/tests/mocks/api.ts +++ b/apps/admin-ui/tests/mocks/api.ts @@ -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([]) } diff --git a/apps/admin-ui/tests/mocks/staff-auth.ts b/apps/admin-ui/tests/mocks/staff-auth.ts index 4f3cf42..ce8f828 100644 --- a/apps/admin-ui/tests/mocks/staff-auth.ts +++ b/apps/admin-ui/tests/mocks/staff-auth.ts @@ -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, diff --git a/apps/admin-ui/tests/screens/drawer-layout.test.tsx b/apps/admin-ui/tests/screens/drawer-layout.test.tsx index 45a5f07..a72b256 100644 --- a/apps/admin-ui/tests/screens/drawer-layout.test.tsx +++ b/apps/admin-ui/tests/screens/drawer-layout.test.tsx @@ -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() 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() diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts b/apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts index 4b36ab9..0e167cf 100644 --- a/apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts +++ b/apps/backend/src/trpc/apis/admin-apis/apis/staff-user.ts @@ -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(); diff --git a/apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts b/apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts index 7760aac..25210a1 100644 --- a/apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts +++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts @@ -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, diff --git a/apps/superadmin-ui/src/routes/__root.tsx b/apps/superadmin-ui/src/routes/__root.tsx index 317b7d7..7e3fecc 100644 --- a/apps/superadmin-ui/src/routes/__root.tsx +++ b/apps/superadmin-ui/src/routes/__root.tsx @@ -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 }) {
{children}
{/* Imperative alert()/confirm()/prompt() dialogs (shadcn AlertDialog). */} - - , - }, - ]} - /> diff --git a/apps/superadmin-ui/src/routes/regions.tsx b/apps/superadmin-ui/src/routes/regions.tsx index 2424ad2..a2af682 100644 --- a/apps/superadmin-ui/src/routes/regions.tsx +++ b/apps/superadmin-ui/src/routes/regions.tsx @@ -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([emptyBound()]) const [error, setError] = useState(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 /> +
+ setCenterLat(e.target.value)} + placeholder="e.g. 16.7488" + /> + setCenterLng(e.target.value)} + placeholder="e.g. 77.9851" + /> +
+ + Leave both empty to use the centre of the first-priority bound. Used to focus a map on the + region. + +
diff --git a/apps/user-ui/src/components/LocationBar.tsx b/apps/user-ui/src/components/LocationBar.tsx index 97b5c2c..599778b 100644 --- a/apps/user-ui/src/components/LocationBar.tsx +++ b/apps/user-ui/src/components/LocationBar.tsx @@ -53,15 +53,31 @@ const LocationBar: React.FC = () => { - - Deliver to:{' '} - - {region?.name ?? 'Choose your address'} - - + + Deliver to + {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. + + + {region.name} + + + ) : ( + + Choose your address + + )} + {activeAddress ? ( diff --git a/apps/user-ui/src/components/location/LocationFallbackFlow.tsx b/apps/user-ui/src/components/location/LocationFallbackFlow.tsx index 376dffb..7893013 100644 --- a/apps/user-ui/src/components/location/LocationFallbackFlow.tsx +++ b/apps/user-ui/src/components/location/LocationFallbackFlow.tsx @@ -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 = ({ 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 = ({ 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 => { 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 = ({ 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 = ({ 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 = ({ onClose, no )} {isAuthenticated && - addresses.map((address) => ( - - handleSelect(address)}> - - {address.name} - {address.isDefault && ( - - Default - - )} - - - {address.addressLine1} - {address.addressLine2 ? `, ${address.addressLine2}` : ''}, {address.city} - - - - {!address.isDefault && ( - handleSetDefault(address)} - disabled={busy || updateAddress.isPending} - style={tw`mt-2 self-start`} - > - Set as default + addresses.map((address) => { + const isActive = address.id === activeAddressId + return ( + + handleSelect(address)}> + + {address.name} + {address.isDefault && ( + + Default + + )} + {isActive && ( + + + + )} + + + {address.addressLine1} + {address.addressLine2 ? `, ${address.addressLine2}` : ''}, {address.city} + - )} - - ))} + + {!address.isDefault && ( + handleSetDefault(address)} + disabled={busy || updateAddress.isPending} + style={tw`mt-2 self-start`} + > + Set as default + + )} + + ) + })} {isAuthenticated && !addressesQuery.isLoading && addresses.length === 0 && ( No saved addresses yet. diff --git a/apps/user-ui/src/lib/region-switch.ts b/apps/user-ui/src/lib/region-switch.ts index ad27a53..e9aa79c 100644 --- a/apps/user-ui/src/lib/region-switch.ts +++ b/apps/user-ui/src/lib/region-switch.ts @@ -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() diff --git a/apps/web-ui/src/routes/__root.tsx b/apps/web-ui/src/routes/__root.tsx index f7eee99..e601b86 100644 --- a/apps/web-ui/src/routes/__root.tsx +++ b/apps/web-ui/src/routes/__root.tsx @@ -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 }) {
{children}
- - , - }, - ]} - /> diff --git a/apps/web-ui/src/routes/location-selector.tsx b/apps/web-ui/src/routes/location-selector.tsx index 5121f79..0da3c84 100644 --- a/apps/web-ui/src/routes/location-selector.tsx +++ b/apps/web-ui/src/routes/location-selector.tsx @@ -71,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: diff --git a/change-log.txt b/change-log.txt index d08a79c..10fa6f8 100644 --- a/change-log.txt +++ b/change-log.txt @@ -4832,3 +4832,192 @@ user-ui - 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 + 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 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 (the bottom-right TanStack logo toggle - the actual floating + symbol in web-ui) and the block, plus + their three imports (TanStackDevtools, TanStackRouterDevtoolsPanel, ReactQueryDevtools). + - left the `devtools()` Vite plugin: it only augments the 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 / 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 #` 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 #` ?? "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 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. diff --git a/packages/db_helper_sqlite/src/superadmin-apis/regions.ts b/packages/db_helper_sqlite/src/superadmin-apis/regions.ts index f688c5e..f3f4945b 100644 --- a/packages/db_helper_sqlite/src/superadmin-apis/regions.ts +++ b/packages/db_helper_sqlite/src/superadmin-apis/regions.ts @@ -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() diff --git a/packages/shared/types/region.types.ts b/packages/shared/types/region.types.ts index bebc05f..c1f7e0f 100644 --- a/packages/shared/types/region.types.ts +++ b/packages/shared/types/region.types.ts @@ -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 {