enh
This commit is contained in:
parent
0d56f3fea3
commit
0ed9ffdae8
10 changed files with 371 additions and 14 deletions
|
|
@ -1,5 +1,5 @@
|
||||||
import React, { useState, useCallback, useMemo, useEffect } from 'react'
|
import React, { useState, useCallback, useMemo, useEffect } from 'react'
|
||||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
import { createFileRoute, Outlet, useLocation, useNavigate } from '@tanstack/react-router'
|
||||||
import { ShoppingBag, CircleAlert, Users } from 'lucide-react'
|
import { ShoppingBag, CircleAlert, Users } from 'lucide-react'
|
||||||
import { AppContainer, p as MyText, SearchBar, MyFlatList, MyButton } from 'web-components'
|
import { AppContainer, p as MyText, SearchBar, MyFlatList, MyButton } from 'web-components'
|
||||||
import { trpc } from '@/lib/trpc-client'
|
import { trpc } from '@/lib/trpc-client'
|
||||||
|
|
@ -139,6 +139,7 @@ const ListFooter: React.FC<{ isFetching: boolean, hasNextPage: boolean, onLoadMo
|
||||||
}
|
}
|
||||||
|
|
||||||
function UserManagement() {
|
function UserManagement() {
|
||||||
|
const location = useLocation()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const [searchTerm, setSearchTerm] = useState('')
|
const [searchTerm, setSearchTerm] = useState('')
|
||||||
const [refreshing, setRefreshing] = useState(false)
|
const [refreshing, setRefreshing] = useState(false)
|
||||||
|
|
@ -197,6 +198,12 @@ function UserManagement() {
|
||||||
return <UserItem user={item} index={index} onClick={() => handleUserPress(item.id)} />
|
return <UserItem user={item} index={index} onClick={() => handleUserPress(item.id)} />
|
||||||
}, [handleUserPress])
|
}, [handleUserPress])
|
||||||
|
|
||||||
|
// Render the user-detail child route. Placed after all hooks so hook order
|
||||||
|
// stays stable between the list and detail screens.
|
||||||
|
if (location.pathname !== '/dashboard/users') {
|
||||||
|
return <Outlet />
|
||||||
|
}
|
||||||
|
|
||||||
if (isLoading && !hasLoadedOnce) {
|
if (isLoading && !hasLoadedOnce) {
|
||||||
return (
|
return (
|
||||||
<AppContainer>
|
<AppContainer>
|
||||||
|
|
|
||||||
|
|
@ -1454,6 +1454,7 @@ Covered by UCOMP-01..11. Add admin-side cases in section 7.
|
||||||
| SREG-16 | error | duplicate priority | 409 |
|
| SREG-16 | error | duplicate priority | 409 |
|
||||||
| SREG-17 | error | unknown region | 409/404 |
|
| SREG-17 | error | unknown region | 409/404 |
|
||||||
| SREG-18 | happy | updateBound | description/geojson/priority |
|
| SREG-18 | happy | updateBound | description/geojson/priority |
|
||||||
|
| SREG-18b | happy | updateBound geojson | region addresses rebalanced from coords; outside → null; backfill flag unchanged |
|
||||||
| SREG-19 | error | duplicate priority | 409 |
|
| SREG-19 | error | duplicate priority | 409 |
|
||||||
| SREG-20 | error | unknown | 404 |
|
| SREG-20 | error | unknown | 404 |
|
||||||
| SREG-21 | happy | deleteBound | success/remaining bounds |
|
| SREG-21 | happy | deleteBound | success/remaining bounds |
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,35 @@
|
||||||
import { polygon as turfPolygon, point as turfPoint } from '@turf/helpers'
|
import { polygon as turfPolygon, point as turfPoint } from '@turf/helpers'
|
||||||
import { booleanPointInPolygon } from '@turf/boolean-point-in-polygon'
|
import { booleanPointInPolygon } from '@turf/boolean-point-in-polygon'
|
||||||
import type { RegionGeoJson, ResolvedRegion } from '@packages/shared'
|
import type { RegionBoundDto, RegionGeoJson, ResolvedRegion } from '@packages/shared'
|
||||||
import { getAllRegionsWithBounds, getRegionWithBounds } from '@/src/dbService'
|
import {
|
||||||
|
getAllRegionsWithBounds,
|
||||||
|
getRegionAddressCoords,
|
||||||
|
getRegionWithBounds,
|
||||||
|
updateAddressBounds,
|
||||||
|
} from '@/src/dbService'
|
||||||
|
|
||||||
export type BoundPolygon = ReturnType<typeof turfPolygon>
|
export type BoundPolygon = ReturnType<typeof turfPolygon>
|
||||||
|
|
||||||
|
export interface AddressCoords {
|
||||||
|
id: number
|
||||||
|
latitude: number
|
||||||
|
longitude: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AddressBoundAssignment {
|
||||||
|
id: number
|
||||||
|
boundId: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RegionAddressRebalanceResult {
|
||||||
|
/** Addresses in the region that have coordinates (and were therefore checked). */
|
||||||
|
scanned: number
|
||||||
|
/** Rows whose `bound_id` was written. */
|
||||||
|
updated: number
|
||||||
|
/** Addresses left with no containing bound after the edit. */
|
||||||
|
unassigned: number
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A bound's GeoJSON is a FeatureCollection; each feature geometry may be a
|
* A bound's GeoJSON is a FeatureCollection; each feature geometry may be a
|
||||||
* Polygon or MultiPolygon. Flatten them into turf polygons for containment tests.
|
* Polygon or MultiPolygon. Flatten them into turf polygons for containment tests.
|
||||||
|
|
@ -48,6 +73,62 @@ export async function resolveBoundInRegion(
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Assign each address to the first bound (priority-ascending) whose polygons
|
||||||
|
* contain its coordinates. Points outside every bound get `boundId: null`.
|
||||||
|
*
|
||||||
|
* Pure so bound-edit rebalancing is unit-testable; `rebalanceRegionAddresses`
|
||||||
|
* persists only the returned ids/bound ids.
|
||||||
|
*/
|
||||||
|
export function assignAddressesToBounds(
|
||||||
|
bounds: Array<Pick<RegionBoundDto, 'id' | 'geojson'>>,
|
||||||
|
addressesToAssign: AddressCoords[]
|
||||||
|
): AddressBoundAssignment[] {
|
||||||
|
const prepared = bounds.map((bound) => ({
|
||||||
|
id: bound.id,
|
||||||
|
polygons: boundToPolygons(bound.geojson),
|
||||||
|
}))
|
||||||
|
|
||||||
|
return addressesToAssign.map((address) => {
|
||||||
|
const point = turfPoint([address.longitude, address.latitude]) // GeoJSON: [lng, lat]
|
||||||
|
const match = prepared.find(
|
||||||
|
(bound) =>
|
||||||
|
bound.polygons.length > 0 &&
|
||||||
|
bound.polygons.some((poly) => booleanPointInPolygon(point, poly))
|
||||||
|
)
|
||||||
|
return { id: address.id, boundId: match?.id ?? null }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recompute `addresses.bound_id` for every address in a region that has
|
||||||
|
* coordinates, after that region's bounds were edited.
|
||||||
|
*
|
||||||
|
* Only the bound id is written; coordinates and `vague_backfilled_coords` are
|
||||||
|
* preserved. Addresses without coordinates keep their current bound because
|
||||||
|
* there is no geometry to resolve them against.
|
||||||
|
*/
|
||||||
|
export async function rebalanceRegionAddresses(
|
||||||
|
regionId: number
|
||||||
|
): Promise<RegionAddressRebalanceResult> {
|
||||||
|
const region = await getRegionWithBounds(regionId)
|
||||||
|
if (!region) throw new Error(`Region ${regionId} not found`)
|
||||||
|
|
||||||
|
const regionAddresses = await getRegionAddressCoords(regionId)
|
||||||
|
if (regionAddresses.length === 0) {
|
||||||
|
return { scanned: 0, updated: 0, unassigned: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
const assignments = assignAddressesToBounds(region.bounds, regionAddresses)
|
||||||
|
const updated = await updateAddressBounds(regionId, assignments)
|
||||||
|
|
||||||
|
return {
|
||||||
|
scanned: regionAddresses.length,
|
||||||
|
updated,
|
||||||
|
unassigned: assignments.filter((assignment) => assignment.boundId == null).length,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve a point to the region + bound that contains it, scanning every region
|
* Resolve a point to the region + bound that contains it, scanning every region
|
||||||
* (regions by id, bounds least-priority first). Returns `null` when the point
|
* (regions by id, bounds least-priority first). Returns `null` when the point
|
||||||
|
|
|
||||||
|
|
@ -151,6 +151,8 @@ export {
|
||||||
clearUserDefaultAddress,
|
clearUserDefaultAddress,
|
||||||
createUserAddress,
|
createUserAddress,
|
||||||
updateUserAddress,
|
updateUserAddress,
|
||||||
|
getRegionAddressCoords,
|
||||||
|
updateAddressBounds,
|
||||||
deleteUserAddress,
|
deleteUserAddress,
|
||||||
hasOngoingOrdersForAddress,
|
hasOngoingOrdersForAddress,
|
||||||
// User - Banners
|
// User - Banners
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ import { TRPCError } from '@trpc/server'
|
||||||
import { ApiError } from '@/src/lib/api-error'
|
import { ApiError } from '@/src/lib/api-error'
|
||||||
import { assertConstantKeysInScope } from '@/src/lib/const-keys'
|
import { assertConstantKeysInScope } from '@/src/lib/const-keys'
|
||||||
import { refreshGenKvForRegion, deleteGenKvForBound } from '@/src/lib/gen-store'
|
import { refreshGenKvForRegion, deleteGenKvForBound } from '@/src/lib/gen-store'
|
||||||
|
import { rebalanceRegionAddresses } from '@/src/lib/region-geo'
|
||||||
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
|
import { scheduleStoreInitialization } from '@/src/stores/store-initializer'
|
||||||
import {
|
import {
|
||||||
getAllRegions,
|
getAllRegions,
|
||||||
|
|
@ -130,22 +131,29 @@ export const superadminRegionsRouter = router({
|
||||||
priority: z.string().regex(/^-?\d+(\.\d+)?$/, 'Priority must be numeric'),
|
priority: z.string().regex(/^-?\d+(\.\d+)?$/, 'Priority must be numeric'),
|
||||||
}))
|
}))
|
||||||
.mutation(async ({ input }) => {
|
.mutation(async ({ input }) => {
|
||||||
|
let bound: Awaited<ReturnType<typeof createRegionBound>> | null = null
|
||||||
try {
|
try {
|
||||||
const bound = await createRegionBound({
|
bound = await createRegionBound({
|
||||||
regionId: input.regionId,
|
regionId: input.regionId,
|
||||||
description: input.description ?? null,
|
description: input.description ?? null,
|
||||||
geojson: input.geojson,
|
geojson: input.geojson,
|
||||||
priority: input.priority,
|
priority: input.priority,
|
||||||
})
|
})
|
||||||
// A new bound can become the effective (lowest-priority) one.
|
|
||||||
await refreshGenKvForRegion(bound.regionId)
|
|
||||||
return bound
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new ApiError(
|
throw new ApiError(
|
||||||
'Could not create bound. Priority may already exist for this region.',
|
'Could not create bound. Priority may already exist for this region.',
|
||||||
409
|
409
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
if (!bound) {
|
||||||
|
throw new ApiError('Could not create bound.', 500)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A new bound can become the effective (lowest-priority) one and can
|
||||||
|
// capture addresses that previously fell outside every bound.
|
||||||
|
await refreshGenKvForRegion(bound.regionId)
|
||||||
|
await rebalanceRegionAddresses(bound.regionId)
|
||||||
|
return bound
|
||||||
}),
|
}),
|
||||||
|
|
||||||
updateBound: superadminProcedure
|
updateBound: superadminProcedure
|
||||||
|
|
@ -156,19 +164,28 @@ export const superadminRegionsRouter = router({
|
||||||
priority: z.string().regex(/^-?\d+(\.\d+)?$/, 'Priority must be numeric').optional(),
|
priority: z.string().regex(/^-?\d+(\.\d+)?$/, 'Priority must be numeric').optional(),
|
||||||
}))
|
}))
|
||||||
.mutation(async ({ input }) => {
|
.mutation(async ({ input }) => {
|
||||||
|
let bound: Awaited<ReturnType<typeof updateRegionBound>> = null
|
||||||
try {
|
try {
|
||||||
const bound = await updateRegionBound(input)
|
bound = await updateRegionBound(input)
|
||||||
if (!bound) throw new TRPCError({ code: 'NOT_FOUND' })
|
|
||||||
// Priority/geojson changes can change which bound is effective.
|
|
||||||
await refreshGenKvForRegion(bound.regionId)
|
|
||||||
return bound
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof TRPCError) throw error
|
|
||||||
throw new ApiError(
|
throw new ApiError(
|
||||||
'Could not update bound. Priority may already exist for this region.',
|
'Could not update bound. Priority may already exist for this region.',
|
||||||
409
|
409
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
if (!bound) throw new TRPCError({ code: 'NOT_FOUND' })
|
||||||
|
|
||||||
|
// Priority/geojson changes can change which bound is effective.
|
||||||
|
await refreshGenKvForRegion(bound.regionId)
|
||||||
|
|
||||||
|
// A geometry or precedence change can move existing addresses into a
|
||||||
|
// different bound (or outside every bound). Recompute from coordinates;
|
||||||
|
// this writes only bound_id, never vague_backfilled_coords.
|
||||||
|
if (input.geojson !== undefined || input.priority !== undefined) {
|
||||||
|
await rebalanceRegionAddresses(bound.regionId)
|
||||||
|
}
|
||||||
|
|
||||||
|
return bound
|
||||||
}),
|
}),
|
||||||
|
|
||||||
deleteBound: superadminProcedure
|
deleteBound: superadminProcedure
|
||||||
|
|
|
||||||
|
|
@ -443,6 +443,47 @@ describe('superadmin.regions.updateBound (SREG-18..20)', () => {
|
||||||
expect(bound.priority).toBe('5')
|
expect(bound.priority).toBe('5')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('SREG-18b: editing a bound rebalances the region addresses without touching the backfill flag', async () => {
|
||||||
|
const lat = 16.25
|
||||||
|
const lng = 77.75
|
||||||
|
const region = await createRegionRaw({
|
||||||
|
bounds: [{ lat, lng, priority: '1' }],
|
||||||
|
})
|
||||||
|
const user = await registerThrowawayUser()
|
||||||
|
const address: any = await createAddress(user.token, {
|
||||||
|
regionId: region.regionId,
|
||||||
|
latitude: lat,
|
||||||
|
longitude: lng,
|
||||||
|
})
|
||||||
|
expect(address.boundId).toBe(region.boundIds[0])
|
||||||
|
|
||||||
|
const superadmin = await superadminClient()
|
||||||
|
const readStoredAddress = async () => {
|
||||||
|
const res: any = await apiClient(user.token).user.address.getUserAddresses.query()
|
||||||
|
return res.data.find((row: any) => row.id === address.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move the only bound away from the address's coordinates.
|
||||||
|
await superadmin.superadmin.regions.updateBound.mutate({
|
||||||
|
id: region.boundIds[0],
|
||||||
|
geojson: squareGeojson(lat + 2, lng),
|
||||||
|
})
|
||||||
|
|
||||||
|
const outside = await readStoredAddress()
|
||||||
|
expect(outside.boundId).toBeNull()
|
||||||
|
expect(outside.vagueBackfilledCoords).toBe(address.vagueBackfilledCoords)
|
||||||
|
|
||||||
|
// Moving it back re-assigns the same address from the same coordinates.
|
||||||
|
await superadmin.superadmin.regions.updateBound.mutate({
|
||||||
|
id: region.boundIds[0],
|
||||||
|
geojson: squareGeojson(lat, lng),
|
||||||
|
})
|
||||||
|
|
||||||
|
const restored = await readStoredAddress()
|
||||||
|
expect(restored.boundId).toBe(address.boundId)
|
||||||
|
expect(restored.vagueBackfilledCoords).toBe(address.vagueBackfilledCoords)
|
||||||
|
})
|
||||||
|
|
||||||
it('SREG-19: updateBound to a duplicate priority is 409', async () => {
|
it('SREG-19: updateBound to a duplicate priority is 409', async () => {
|
||||||
const region = await createRegionRaw({
|
const region = await createRegionRaw({
|
||||||
bounds: [
|
bounds: [
|
||||||
|
|
|
||||||
85
apps/backend/tests/unit/region-address-rebalance.test.ts
Normal file
85
apps/backend/tests/unit/region-address-rebalance.test.ts
Normal file
|
|
@ -0,0 +1,85 @@
|
||||||
|
/**
|
||||||
|
* Unit tests for the pure coordinate -> bound assignment used after a
|
||||||
|
* superadmin edits a bound. Persisting the result writes only `bound_id`; the
|
||||||
|
* integration test SREG-18b covers the end-to-end API behaviour, including
|
||||||
|
* preserving `vague_backfilled_coords`.
|
||||||
|
*/
|
||||||
|
import { assignAddressesToBounds } from '@/src/lib/region-geo'
|
||||||
|
|
||||||
|
function square(lat: number, lng: number, delta = 0.01) {
|
||||||
|
return {
|
||||||
|
type: 'FeatureCollection' as const,
|
||||||
|
features: [
|
||||||
|
{
|
||||||
|
type: 'Feature' as const,
|
||||||
|
properties: {},
|
||||||
|
geometry: {
|
||||||
|
type: 'Polygon' as const,
|
||||||
|
coordinates: [
|
||||||
|
[
|
||||||
|
[lng - delta, lat - delta],
|
||||||
|
[lng + delta, lat - delta],
|
||||||
|
[lng + delta, lat + delta],
|
||||||
|
[lng - delta, lat + delta],
|
||||||
|
[lng - delta, lat - delta],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('assignAddressesToBounds', () => {
|
||||||
|
it('assigns points to the first priority-ordered bound that contains them', () => {
|
||||||
|
const assignments = assignAddressesToBounds(
|
||||||
|
[
|
||||||
|
{ id: 10, geojson: square(16.75, 78.0, 0.05) },
|
||||||
|
{ id: 20, geojson: square(16.75, 78.0, 0.01) },
|
||||||
|
],
|
||||||
|
[
|
||||||
|
// Inside both: the earlier (lowest-numbered priority) bound wins.
|
||||||
|
{ id: 1, latitude: 16.75, longitude: 78.0 },
|
||||||
|
// Inside only the outer bound.
|
||||||
|
{ id: 2, latitude: 16.79, longitude: 78.0 },
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(assignments).toEqual([
|
||||||
|
{ id: 1, boundId: 10 },
|
||||||
|
{ id: 2, boundId: 10 },
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('leaves a point unassigned when it is outside every bound', () => {
|
||||||
|
expect(
|
||||||
|
assignAddressesToBounds(
|
||||||
|
[{ id: 7, geojson: square(16.75, 78.0) }],
|
||||||
|
[{ id: 99, latitude: 10.0, longitude: 70.0 }]
|
||||||
|
)
|
||||||
|
).toEqual([{ id: 99, boundId: null }])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps assignment order and ignores bounds with no usable polygons', () => {
|
||||||
|
const empty = {
|
||||||
|
type: 'FeatureCollection' as const,
|
||||||
|
features: [],
|
||||||
|
}
|
||||||
|
|
||||||
|
const assignments = assignAddressesToBounds(
|
||||||
|
[
|
||||||
|
{ id: 1, geojson: empty },
|
||||||
|
{ id: 2, geojson: square(12.0, 79.0) },
|
||||||
|
],
|
||||||
|
[
|
||||||
|
{ id: 5, latitude: 12.0, longitude: 79.0 },
|
||||||
|
{ id: 6, latitude: 11.0, longitude: 79.0 },
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(assignments).toEqual([
|
||||||
|
{ id: 5, boundId: 2 },
|
||||||
|
{ id: 6, boundId: null },
|
||||||
|
])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -10399,3 +10399,51 @@ Typecheck: backend, admin-ui, admin-web all clean.
|
||||||
Notes: the list/detail already expand archived items via `loadOrderItems` (archived-first,
|
Notes: the list/detail already expand archived items via `loadOrderItems` (archived-first,
|
||||||
table-fallback), so older orders now render their items in both admin apps; no admin-UI/admin-web
|
table-fallback), so older orders now render their items in both admin apps; no admin-UI/admin-web
|
||||||
client change was needed. The 3-day window was the only thing hiding them.
|
client change was needed. The 3-day window was the only thing hiding them.
|
||||||
|
|
||||||
|
[2026-10-26 17:09:21 IST] Documentation-only mobile-friendliness review.
|
||||||
|
+ docs/web-ui-mobile-friendliness-audit.md: source-backed findings comparing
|
||||||
|
apps/web-ui with apps/user-ui and their shared UI primitives; priorities,
|
||||||
|
route-reachability caveats, mobile browser risks, and follow-up validation scope.
|
||||||
|
No application or test files changed. No tests, builds, deployments, migrations,
|
||||||
|
or git commands run for this review. Findings are from static source inspection.
|
||||||
|
|
||||||
|
[2026-10-26 19:50:55 IST] Rebalance region addresses after a superadmin bound edit.
|
||||||
|
|
||||||
|
--- packages/db_helper_sqlite/src/user-apis/address.ts
|
||||||
|
+ getRegionAddressCoords(regionId): address id + non-null lat/lng for the region.
|
||||||
|
+ updateAddressBounds(regionId, assignments): groups assignments by bound and
|
||||||
|
updates ONLY addresses.bound_id (chunked under D1's parameter cap). Coordinates
|
||||||
|
and vague_backfilled_coords are not written.
|
||||||
|
--- packages/db_helper_sqlite/index.ts + apps/backend/src/sqliteImporter.ts
|
||||||
|
+ re-export both helpers.
|
||||||
|
--- apps/backend/src/lib/region-geo.ts
|
||||||
|
+ assignAddressesToBounds(bounds, addresses): pure, priority-ordered point-in-polygon
|
||||||
|
assignment; null when the point is outside every bound.
|
||||||
|
+ rebalanceRegionAddresses(regionId): scans the region's addresses with coordinates,
|
||||||
|
recomputes their bound and applies the assignments.
|
||||||
|
--- apps/backend/src/trpc/apis/superadmin-apis/apis/regions.ts
|
||||||
|
~ updateBound rebalances after the bound + KV refresh when geojson or priority changed.
|
||||||
|
Description-only edits do not rebalance. Rebalance errors are no longer mislabeled
|
||||||
|
as duplicate-priority 409s.
|
||||||
|
~ createBound also rebalances: a new bound can capture previously-unassigned addresses
|
||||||
|
or outrank an existing containing bound.
|
||||||
|
--- apps/backend/tests/unit/region-address-rebalance.test.ts (new)
|
||||||
|
+ pure assignment coverage: lowest-priority overlap, outside-all, order.
|
||||||
|
--- apps/backend/tests/api/superadmin-regions.test.ts
|
||||||
|
+ SREG-18b: moving a bound off an address clears its bound_id, moving it back restores
|
||||||
|
it, and vagueBackfilledCoords stays unchanged.
|
||||||
|
--- apps/backend/API-TEST-CASES.md
|
||||||
|
+ SREG-18b catalogue row.
|
||||||
|
Scope note: addresses with NULL coordinates cannot be re-derived and are left unchanged.
|
||||||
|
Tests/typechecks were not run (repo rule).
|
||||||
|
|
||||||
|
[2026-10-26 21:55:50 IST] Fix admin-web complaint → user detail navigation.
|
||||||
|
|
||||||
|
--- apps/admin-web/src/routes/dashboard.users.tsx
|
||||||
|
+ import Outlet + useLocation.
|
||||||
|
+ when pathname !== '/dashboard/users', render <Outlet /> (placed after all hooks),
|
||||||
|
matching dashboard.stores/orders/products/coupons.
|
||||||
|
Before: /dashboard/users/:id rendered the parent list (no Outlet), so clicking a
|
||||||
|
complaint's user showed the users list instead of User Details.
|
||||||
|
No test file exists under apps/admin-web. Typecheck to be run manually.
|
||||||
|
Typecheck: apps/admin-web clean.
|
||||||
|
|
|
||||||
|
|
@ -188,6 +188,8 @@ export {
|
||||||
updateUserAddress,
|
updateUserAddress,
|
||||||
deleteUserAddress,
|
deleteUserAddress,
|
||||||
hasOngoingOrdersForAddress,
|
hasOngoingOrdersForAddress,
|
||||||
|
getRegionAddressCoords,
|
||||||
|
updateAddressBounds,
|
||||||
} from './src/user-apis/address'
|
} from './src/user-apis/address'
|
||||||
|
|
||||||
export {
|
export {
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import { db } from '../db/db_index'
|
import { db } from '../db/db_index'
|
||||||
import { addresses, deliverySlotInfo, orders, orderStatus } from '../db/schema'
|
import { addresses, deliverySlotInfo, orders, orderStatus } from '../db/schema'
|
||||||
import { and, eq, gte } from 'drizzle-orm'
|
import { and, eq, gte, inArray, isNotNull } from 'drizzle-orm'
|
||||||
import type { InferSelectModel } from 'drizzle-orm'
|
import type { InferSelectModel } from 'drizzle-orm'
|
||||||
import type { UserAddress } from '@packages/shared'
|
import type { UserAddress } from '@packages/shared'
|
||||||
|
|
||||||
|
|
@ -140,6 +140,79 @@ export async function deleteUserAddress(userId: number, addressId: number): Prom
|
||||||
return !!deleted
|
return !!deleted
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Coordinates of a region's addresses that can be re-resolved against new bounds. */
|
||||||
|
export async function getRegionAddressCoords(
|
||||||
|
regionId: number
|
||||||
|
): Promise<Array<{ id: number; latitude: number; longitude: number }>> {
|
||||||
|
const rows = await db
|
||||||
|
.select({
|
||||||
|
id: addresses.id,
|
||||||
|
latitude: addresses.latitude,
|
||||||
|
longitude: addresses.longitude,
|
||||||
|
})
|
||||||
|
.from(addresses)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(addresses.regionId, regionId),
|
||||||
|
isNotNull(addresses.latitude),
|
||||||
|
isNotNull(addresses.longitude)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Drizzle's nullability narrowing does not survive the where() clause, so
|
||||||
|
// narrow once here for callers. Addresses without coordinates are deliberately
|
||||||
|
// skipped: their bound cannot be re-derived from geometry.
|
||||||
|
return rows.flatMap((row) =>
|
||||||
|
row.latitude != null && row.longitude != null
|
||||||
|
? [{ id: row.id, latitude: row.latitude, longitude: row.longitude }]
|
||||||
|
: []
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// id + region_id + bound_id = 3 parameters/statement; keep the IN list well under
|
||||||
|
// D1's 100-parameter ceiling.
|
||||||
|
const ADDRESS_BOUND_UPDATE_CHUNK_SIZE = 90
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Applies recomputed bound assignments for a region. Only `bound_id` is written:
|
||||||
|
* coordinates and `vague_backfilled_coords` are intentionally left untouched.
|
||||||
|
* Returns the number of address rows actually updated.
|
||||||
|
*/
|
||||||
|
export async function updateAddressBounds(
|
||||||
|
regionId: number,
|
||||||
|
assignments: Array<{ id: number; boundId: number | null }>
|
||||||
|
): Promise<number> {
|
||||||
|
if (assignments.length === 0) return 0
|
||||||
|
|
||||||
|
const idsByBound = new Map<number | null, number[]>()
|
||||||
|
for (const assignment of assignments) {
|
||||||
|
const ids = idsByBound.get(assignment.boundId) ?? []
|
||||||
|
ids.push(assignment.id)
|
||||||
|
idsByBound.set(assignment.boundId, ids)
|
||||||
|
}
|
||||||
|
|
||||||
|
let updated = 0
|
||||||
|
await db.transaction(async (tx) => {
|
||||||
|
for (const [boundId, ids] of idsByBound) {
|
||||||
|
for (let i = 0; i < ids.length; i += ADDRESS_BOUND_UPDATE_CHUNK_SIZE) {
|
||||||
|
const rows = await tx
|
||||||
|
.update(addresses)
|
||||||
|
.set({ boundId })
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(addresses.regionId, regionId),
|
||||||
|
inArray(addresses.id, ids.slice(i, i + ADDRESS_BOUND_UPDATE_CHUNK_SIZE))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.returning({ id: addresses.id })
|
||||||
|
updated += rows.length
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return updated
|
||||||
|
}
|
||||||
|
|
||||||
export async function hasOngoingOrdersForAddress(addressId: number): Promise<boolean> {
|
export async function hasOngoingOrdersForAddress(addressId: number): Promise<boolean> {
|
||||||
const ongoingOrders = await db.select({
|
const ongoingOrders = await db.select({
|
||||||
orderId: orders.id,
|
orderId: orders.id,
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue