This commit is contained in:
shafi54 2026-10-15 22:02:24 +05:30
parent bd09d84822
commit 38401bc2ec
9 changed files with 258 additions and 16 deletions

View file

@ -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]')
);

View file

@ -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,

View file

@ -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<AddressFormProps> = ({
const [isSubmitting, setIsSubmitting] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null);
const [mapOpen, setMapOpen] = useState(false);
const [mapConfirmOpen, setMapConfirmOpen] = useState(false);
const [currentLocation, setCurrentLocation] = useState<Coords | null>(
initialValues?.latitude != null && initialValues?.longitude != null
? { latitude: initialValues.latitude, longitude: initialValues.longitude }
@ -51,6 +52,17 @@ 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. 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<AddressFormProps> = ({
</MyText>
<MyTouchableOpacity
testID="address-choose-location"
onPress={() => setMapOpen(true)}
onPress={() => setMapConfirmOpen(true)}
style={tw`flex-row items-center mt-2`}
>
<MaterialIcons name="map" size={18} color="#3B82F6" />
@ -376,7 +388,7 @@ const AddressForm: React.FC<AddressFormProps> = ({
) : (
<MyTouchableOpacity
testID="address-attach-location"
onPress={() => setMapOpen(true)}
onPress={() => setMapConfirmOpen(true)}
style={tw`flex-row items-center`}
>
<MaterialIcons name="place" size={18} color="#3B82F6" />
@ -425,9 +437,49 @@ 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. */}
<BottomDialog open={mapConfirmOpen} onClose={() => setMapConfirmOpen(false)}>
<View style={tw`p-6`}>
<View style={tw`flex-row items-center mb-3`}>
<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`}>
{mapRegion ? `Open the map for ${mapRegion.name}?` : 'Open the map?'}
</MyText>
</View>
<MyText style={tw`text-gray-600 text-sm`}>
{mapRegion
? `The map will open on ${mapRegion.name}. Pick a point inside this region.`
: 'Pick a point on the map.'}
</MyText>
<View style={tw`flex-row gap-3 mt-6`}>
<MyTouchableOpacity
testID="address-map-confirm-cancel"
onPress={() => setMapConfirmOpen(false)}
style={tw`flex-1 border border-gray-200 py-3.5 rounded-xl items-center`}
>
<MyText style={tw`text-gray-700 font-bold`}>Cancel</MyText>
</MyTouchableOpacity>
<MyTouchableOpacity
testID="address-map-confirm-open"
onPress={openMap}
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>
</View>
</BottomDialog>
{/* Full-screen map picker. */}
<Modal visible={mapOpen} animationType="slide" onRequestClose={() => setMapOpen(false)}>
<LocationMapStep
lat={mapRegion?.center?.lat}
lng={mapRegion?.center?.lng}
onSelect={(coords) => {
setMapOpen(false);
void resolveLocation(coords, 'map');

View file

@ -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) => {

View file

@ -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.

View file

@ -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',

View file

@ -462,6 +462,11 @@ export const regionBounds = sqliteTable('region_bounds', {
description: text(),
geojson: jsonText<RegionGeoJson>('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),
}))

View file

@ -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<RegionSummary[]> {
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<number, number>()
// First (lowest-priority) bound per region is the effective one — it also
// provides the region's centre.
const effective = new Map<number, { id: number; center: RegionCenter | null }>()
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<RegionSummary | null> {
@ -87,7 +147,13 @@ export async function getRegionWithBounds(id: number): Promise<RegionWithBounds
.from(regionBounds)
.where(eq(regionBounds.regionId, id))
.orderBy(priorityOrder)
return { ...toSummary(region), bounds: bounds.map(toBoundDto) }
// bounds is priority-ascending, so [0] is the effective (first-priority) bound.
return {
...toSummary(region),
effectiveBoundId: bounds[0]?.id ?? null,
center: bounds[0] ? centerFromRow(bounds[0]) : null,
bounds: bounds.map(toBoundDto),
}
}
/**
@ -157,6 +223,8 @@ export async function createRegionWithBounds(
description: bound.description ?? null,
geojson: bound.geojson,
priority: String(bound.priority),
centerLat: boundCenter(bound.geojson)?.lat ?? null,
centerLng: boundCenter(bound.geojson)?.lng ?? null,
}))
)
.returning()
@ -313,6 +381,7 @@ export async function getBoundById(id: number): Promise<RegionBoundDto | null> {
export async function createRegionBound(input: CreateRegionBoundInput): Promise<RegionBoundDto> {
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<RegionBoundDto | null> {
// 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))

View file

@ -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 {