diff --git a/apps/backend/dev-migration-region-bound-centers.sql b/apps/backend/dev-migration-region-bound-centers.sql new file mode 100644 index 0000000..4cb60e1 --- /dev/null +++ b/apps/backend/dev-migration-region-bound-centers.sql @@ -0,0 +1,27 @@ +-- DEV ONLY — the local dev DB has already run 0006, so this applies just the +-- region-bound centre addition that 0006 now carries for a fresh database. +-- +-- Run once, against the dev database: +-- bunx wrangler d1 execute freshyo-dev \ +-- --file=apps/backend/dev-migration-region-bound-centers.sql \ +-- --config wrangler.dev.toml +-- +-- Afterwards the app keeps these fresh: every bound create/update recomputes the +-- centre (boundCenter in superadmin-apis/regions.ts). + +ALTER TABLE `region_bounds` ADD COLUMN `center_lat` real; +--> statement-breakpoint +ALTER TABLE `region_bounds` ADD COLUMN `center_lng` real; +--> statement-breakpoint + +-- Bounding-box centre of each bound's GeoJSON. Reads the first feature's outer +-- ring (the shape every seeded bound currently uses). +UPDATE `region_bounds` SET + `center_lat` = ( + SELECT (MIN(CAST(json_extract(value, '$[1]') AS REAL)) + MAX(CAST(json_extract(value, '$[1]') AS REAL))) / 2 + FROM json_each(`region_bounds`.`geojson`, '$.features[0].geometry.coordinates[0]') + ), + `center_lng` = ( + SELECT (MIN(CAST(json_extract(value, '$[0]') AS REAL)) + MAX(CAST(json_extract(value, '$[0]') AS REAL))) / 2 + FROM json_each(`region_bounds`.`geojson`, '$.features[0].geometry.coordinates[0]') + ); diff --git a/apps/backend/src/lib/region-geo.ts b/apps/backend/src/lib/region-geo.ts index 5132265..b94ffde 100644 --- a/apps/backend/src/lib/region-geo.ts +++ b/apps/backend/src/lib/region-geo.ts @@ -66,7 +66,10 @@ export async function resolveRegionAndBound( const polygons = boundToPolygons(bound.geojson) if (polygons.length > 0 && polygons.some((poly) => booleanPointInPolygon(point, poly))) { return { - region: { id: region.id, name: region.name, description: region.description }, + // The centre always describes the region's first-priority bound (the + // one that supplies its effective values), not necessarily the matched + // one — bounds are priority-ascending, so [0] is it. + region: { ...region, center: region.bounds[0]?.center ?? null }, bound: { id: bound.id, regionId: bound.regionId, diff --git a/apps/user-ui/src/components/AddressForm.tsx b/apps/user-ui/src/components/AddressForm.tsx index 1eb9d93..d34fda6 100644 --- a/apps/user-ui/src/components/AddressForm.tsx +++ b/apps/user-ui/src/components/AddressForm.tsx @@ -2,7 +2,7 @@ import React, { useCallback, useEffect, useState } from 'react'; import { View, Modal, ScrollView, KeyboardAvoidingView, Platform, Keyboard } from 'react-native'; import { Formik } from 'formik'; import * as Yup from 'yup'; -import { tw, MyText, MyTouchableOpacity , Checkbox , MyTextInput , LoadingDialog } from 'common-ui'; +import { tw, MyText, MyTouchableOpacity , Checkbox , MyTextInput , LoadingDialog , BottomDialog } from 'common-ui'; import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import { trpc } from '../trpc-client'; import LocationMapStep from './location/LocationMapStep'; @@ -28,6 +28,7 @@ const AddressForm: React.FC = ({ const [isSubmitting, setIsSubmitting] = useState(false); const [submitError, setSubmitError] = useState(null); const [mapOpen, setMapOpen] = useState(false); + const [mapConfirmOpen, setMapConfirmOpen] = useState(false); const [currentLocation, setCurrentLocation] = useState( initialValues?.latitude != null && initialValues?.longitude != null ? { latitude: initialValues.latitude, longitude: initialValues.longitude } @@ -51,6 +52,17 @@ const AddressForm: React.FC = ({ 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. Confirmed before opening, and + // its stored centre (first-priority bound) becomes the map's centre. + const mapRegion = + regions.find((region) => region.id === (resolvedRegion?.regionId ?? browsingRegionId)) ?? null; + + const openMap = useCallback(() => { + setMapConfirmOpen(false); + setMapOpen(true); + }, []); + // 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( @@ -364,7 +376,7 @@ const AddressForm: React.FC = ({ setMapOpen(true)} + onPress={() => setMapConfirmOpen(true)} style={tw`flex-row items-center mt-2`} > @@ -376,7 +388,7 @@ const AddressForm: React.FC = ({ ) : ( setMapOpen(true)} + onPress={() => setMapConfirmOpen(true)} style={tw`flex-row items-center`} > @@ -425,9 +437,49 @@ const AddressForm: React.FC = ({ message={isEdit ? "Updating address..." : "Adding address..."} /> + {/* Confirm the region before handing over to the map WebView, which opens + focused on that region's centre. */} + setMapConfirmOpen(false)}> + + + + + + + {mapRegion ? `Open the map for ${mapRegion.name}?` : 'Open the map?'} + + + + + {mapRegion + ? `The map will open on ${mapRegion.name}. Pick a point inside this region.` + : 'Pick a point on the map.'} + + + + setMapConfirmOpen(false)} + style={tw`flex-1 border border-gray-200 py-3.5 rounded-xl items-center`} + > + Cancel + + + Open map + + + + + {/* Full-screen map picker. */} setMapOpen(false)}> { setMapOpen(false); void resolveLocation(coords, 'map'); diff --git a/apps/user-ui/src/components/location/LocationMapStep.tsx b/apps/user-ui/src/components/location/LocationMapStep.tsx index 7700f1d..71b8cc0 100644 --- a/apps/user-ui/src/components/location/LocationMapStep.tsx +++ b/apps/user-ui/src/components/location/LocationMapStep.tsx @@ -16,16 +16,28 @@ interface LocationMapStepProps { onCancel: () => void /** Shown when a previously picked point was rejected (outside the region). */ error?: string + /** Map centre override — the selected region's centre, so the map opens there. */ + lat?: number | null + lng?: number | null } /** * Full-screen WebView wrapping the web-ui `/location-selector` page. The page * posts `{ type: 'location-selected', latitude, longitude }` back through * `window.ReactNativeWebView.postMessage` when the user confirms a point. + * + * `lat`/`lng` open the map focused on that point; the page keeps its own default + * zoom. Without them it opens on its default centre. */ -export default function LocationMapStep({ onSelect, onCancel, error }: LocationMapStepProps) { +export default function LocationMapStep({ onSelect, onCancel, error, lat, lng }: LocationMapStepProps) { const [isLoading, setIsLoading] = useState(true) - const url = `${constants.WEB_UI_BASE_URL}/location-selector` + + const url = (() => { + const base = `${constants.WEB_UI_BASE_URL}/location-selector` + if (lat == null || lng == null) return base + const params = new URLSearchParams({ lat: String(lat), lng: String(lng) }) + return `${base}?${params.toString()}` + })() const handleMessage = useCallback( (event: WebViewMessageEvent) => { diff --git a/change-log.txt b/change-log.txt index 5177cfa..e8addea 100644 --- a/change-log.txt +++ b/change-log.txt @@ -4734,3 +4734,37 @@ user-ui - the Login footer is now rendered whenever the user is not signed in (dropped the `&& !isAuthLoading` guard), so the button is present while auth settles too. No other file changed. No tests run. + +2026-10-15 21:22:30 Persist a bound's centre so the map can open focused on a region. + + A region's centre = its FIRST-PRIORITY bound's centre, stored per bound (no cascade to + recompute, and it cannot drift when bounds are reprioritised). + + packages/shared/types/region.types.ts + - + RegionCenter { lat, lng }. + - RegionSummary.center?: RegionCenter | null (the region store still persists the whole + summary, so the centre is saved with the region). + - RegionBoundDto.center?: RegionCenter | null. + packages/db_helper_sqlite/src/db/schema.ts + - regionBounds: + center_lat / center_lng (real, nullable). + packages/db_helper_sqlite/src/superadmin-apis/regions.ts + - + boundCenter(geojson): bbox centre over every coordinate (all features, Polygon and + MultiPolygon), null when unusable. No new dependency. + - toBoundDto exposes `center` from the stored columns. + - getAllRegions / getRegionWithBounds fill RegionSummary.center from the region's + first-priority bound. + - createRegionWithBounds / createRegionBound store the computed centre; + updateRegionBound recomputes it when the geojson changes. + apps/backend/src/lib/region-geo.ts + - resolveRegionAndBound returns the region's first-priority-bound centre too. + packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql (not applied to prod yet) + - region_bounds CREATE gains center_lat/center_lng, plus a bbox backfill after the seeds. + apps/backend/dev-migration-region-bound-centers.sql (NEW, dev only) + - ALTER + the same backfill for the already-migrated dev DB. + apps/user-ui/src/components/location/LocationMapStep.tsx + - + optional lat/lng props appended as ?lat=&lng= (no zoom: the page keeps its default). + apps/user-ui/src/components/AddressForm.tsx + - both map triggers go through a shared handler that first shows a BottomDialog naming the + selected region; on confirm the map opens focused on that region's stored centre. + apps/web-ui: unchanged (option A - the page already centres from ?lat=&lng). + No tests run. diff --git a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql index 0eb0010..209bf6d 100644 --- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql +++ b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql @@ -47,6 +47,8 @@ CREATE TABLE IF NOT EXISTS `region_bounds` ( `description` text, `geojson` text NOT NULL, `priority` text NOT NULL, + `center_lat` real, + `center_lng` real, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint @@ -939,6 +941,19 @@ SELECT b.`id`, b.`region_id`, 'isFlashDeliveryEnabled', IN ('1', 'true', '1.0') THEN 'true' ELSE 'false' END FROM `regions` r JOIN `region_bounds` b ON b.`region_id` = r.`id` WHERE r.`name` = 'Mahabubnagar'; --> statement-breakpoint +-- Bounding-box centre of each seeded bound, persisted so clients can focus a map +-- on a region without loading its geometry. (The app recomputes this on every +-- bound create/update; this covers the rows that exist before it runs.) +UPDATE `region_bounds` SET + `center_lat` = ( + SELECT (MIN(CAST(json_extract(value, '$[1]') AS REAL)) + MAX(CAST(json_extract(value, '$[1]') AS REAL))) / 2 + FROM json_each(`region_bounds`.`geojson`, '$.features[0].geometry.coordinates[0]') + ), + `center_lng` = ( + SELECT (MIN(CAST(json_extract(value, '$[0]') AS REAL)) + MAX(CAST(json_extract(value, '$[0]') AS REAL))) / 2 + FROM json_each(`region_bounds`.`geojson`, '$.features[0].geometry.coordinates[0]') + ); +--> statement-breakpoint -- Keep only the leftover keys in key_val_store (same set 0009 keeps). DELETE FROM `key_val_store` WHERE `key` IN ( 'versionNum','playStoreUrl','appStoreUrl','internalAppVersion', diff --git a/packages/db_helper_sqlite/src/db/schema.ts b/packages/db_helper_sqlite/src/db/schema.ts index a625323..91e799d 100644 --- a/packages/db_helper_sqlite/src/db/schema.ts +++ b/packages/db_helper_sqlite/src/db/schema.ts @@ -462,6 +462,11 @@ export const regionBounds = sqliteTable('region_bounds', { description: text(), geojson: jsonText('geojson').notNull(), priority: numericText('priority').notNull(), + // Bounding-box centre of `geojson`, persisted (see boundCenter in + // superadmin-apis/regions.ts) so clients can focus a map on the region + // without downloading the geometry. + centerLat: real('center_lat'), + centerLng: real('center_lng'), }, (t) => ({ unq_region_priority: uniqueIndex('unique_region_bound_priority').on(t.regionId, t.priority), })) diff --git a/packages/db_helper_sqlite/src/superadmin-apis/regions.ts b/packages/db_helper_sqlite/src/superadmin-apis/regions.ts index 8c3f7cf..f688c5e 100644 --- a/packages/db_helper_sqlite/src/superadmin-apis/regions.ts +++ b/packages/db_helper_sqlite/src/superadmin-apis/regions.ts @@ -6,6 +6,8 @@ import type { RegionSummary, RegionWithBounds, RegionBoundDto, + RegionCenter, + RegionGeoJson, CreateRegionInput, CreateRegionWithBoundsInput, UpdateRegionInput, @@ -17,6 +19,51 @@ import type { // Bounds are ordered by numeric priority ascending (lower number = higher precedence). const priorityOrder = sql`CAST(${regionBounds.priority} AS REAL) ASC` +/** + * Bounding-box centre of a bound's GeoJSON: every coordinate of every feature is + * visited, so a Polygon and a MultiPolygon are both handled (the client never + * parses geometry — this is what gets persisted in center_lat/center_lng). + * Returns null when there is no usable coordinate. + */ +export function boundCenter(geojson: RegionGeoJson | null | undefined): RegionCenter | null { + let minLat = Infinity + let maxLat = -Infinity + let minLng = Infinity + let maxLng = -Infinity + + const visit = (coords: unknown): void => { + if (!Array.isArray(coords)) return + + // A position is [lng, lat]; anything deeper is a ring / polygon / multipolygon list. + if (typeof coords[0] === 'number' && typeof coords[1] === 'number') { + const lng = Number(coords[0]) + const lat = Number(coords[1]) + if (!Number.isFinite(lng) || !Number.isFinite(lat)) return + if (lat < minLat) minLat = lat + if (lat > maxLat) maxLat = lat + if (lng < minLng) minLng = lng + if (lng > maxLng) maxLng = lng + return + } + + for (const child of coords) visit(child) + } + + for (const feature of geojson?.features ?? []) visit(feature?.geometry?.coordinates) + + if (!Number.isFinite(minLat) || !Number.isFinite(minLng)) return null + return { lat: (minLat + maxLat) / 2, lng: (minLng + maxLng) / 2 } +} + +/** The persisted centre of a bound row, when it has one. */ +function centerFromRow(bound: { + centerLat: number | null + centerLng: number | null +}): RegionCenter | null { + if (bound.centerLat == null || bound.centerLng == null) return null + return { lat: bound.centerLat, lng: bound.centerLng } +} + const serializeDefault = (value: unknown): string | null => { if (value === null || value === undefined) return null return typeof value === 'string' ? value : String(value) @@ -52,26 +99,39 @@ function toBoundDto(bound: typeof regionBounds.$inferSelect): RegionBoundDto { description: bound.description, geojson: bound.geojson as RegionBoundDto['geojson'], priority: bound.priority ?? '', + center: centerFromRow(bound), } } export async function getAllRegions(): Promise { const rows = await db.select().from(regions).orderBy(regions.name) const boundRows = await db - .select({ id: regionBounds.id, regionId: regionBounds.regionId }) + .select({ + id: regionBounds.id, + regionId: regionBounds.regionId, + centerLat: regionBounds.centerLat, + centerLng: regionBounds.centerLng, + }) .from(regionBounds) .orderBy(regionBounds.regionId, priorityOrder) - // First (lowest-priority) bound per region is the effective one. - const effective = new Map() + // First (lowest-priority) bound per region is the effective one — it also + // provides the region's centre. + const effective = new Map() for (const bound of boundRows) { - if (!effective.has(bound.regionId)) effective.set(bound.regionId, bound.id) + if (!effective.has(bound.regionId)) { + effective.set(bound.regionId, { id: bound.id, center: centerFromRow(bound) }) + } } - return rows.map((region) => ({ - ...toSummary(region), - effectiveBoundId: effective.get(region.id) ?? null, - })) + return rows.map((region) => { + const firstBound = effective.get(region.id) + return { + ...toSummary(region), + effectiveBoundId: firstBound?.id ?? null, + center: firstBound?.center ?? null, + } + }) } export async function getRegionById(id: number): Promise { @@ -87,7 +147,13 @@ export async function getRegionWithBounds(id: number): Promise { export async function createRegionBound(input: CreateRegionBoundInput): Promise { return db.transaction(async (tx) => { + const center = boundCenter(input.geojson) const [row] = await tx .insert(regionBounds) .values({ @@ -320,6 +389,8 @@ export async function createRegionBound(input: CreateRegionBoundInput): Promise< description: input.description ?? null, geojson: input.geojson, priority: String(input.priority), + centerLat: center?.lat ?? null, + centerLng: center?.lng ?? null, }) .returning() @@ -333,11 +404,20 @@ export async function createRegionBound(input: CreateRegionBoundInput): Promise< } export async function updateRegionBound(input: UpdateRegionBoundInput): Promise { + // Moving a boundary moves its centre; leave it untouched when the geometry + // is not part of this update. + const nextCenter = input.geojson !== undefined ? boundCenter(input.geojson) : undefined const [row] = await db .update(regionBounds) .set({ ...(input.description !== undefined ? { description: input.description } : {}), - ...(input.geojson !== undefined ? { geojson: input.geojson } : {}), + ...(input.geojson !== undefined + ? { + geojson: input.geojson, + centerLat: nextCenter?.lat ?? null, + centerLng: nextCenter?.lng ?? null, + } + : {}), ...(input.priority !== undefined ? { priority: String(input.priority) } : {}), }) .where(eq(regionBounds.id, input.id)) diff --git a/packages/shared/types/region.types.ts b/packages/shared/types/region.types.ts index 3ed6e26..bebc05f 100644 --- a/packages/shared/types/region.types.ts +++ b/packages/shared/types/region.types.ts @@ -14,6 +14,12 @@ export interface RegionGeoJson { features: RegionGeoJsonFeature[] } +/** A representative point for a bound (and therefore for its region). */ +export interface RegionCenter { + lat: number + lng: number +} + export interface RegionSummary { id: number name: string @@ -24,6 +30,12 @@ export interface RegionSummary { * consts. `null` when the region has no bounds. */ effectiveBoundId?: number | null + /** + * Centre of the region's lowest-numbered-priority bound, so clients can focus + * a map on the region without requesting its geometry. Persisted per bound. + * `null` when the region has no bounds (or none with usable geometry). + */ + center?: RegionCenter | null } export interface RegionBoundDto { @@ -32,6 +44,8 @@ export interface RegionBoundDto { description: string | null geojson: RegionGeoJson priority: string + /** Bounding-box centre of `geojson`, persisted alongside it. */ + center?: RegionCenter | null } export interface RegionWithBounds extends RegionSummary {