freshyo/packages/db_helper_sqlite/src/superadmin-apis/regions.ts
2026-10-07 13:36:48 +05:30

174 lines
5.6 KiB
TypeScript

import { db } from '../db/db_index'
import { regions, regionBounds, regionBoundSettings } from '../db/schema'
import { and, eq, sql } from 'drizzle-orm'
import type {
RegionSummary,
RegionWithBounds,
RegionBoundDto,
CreateRegionInput,
UpdateRegionInput,
CreateRegionBoundInput,
UpdateRegionBoundInput,
EffectiveRegionSettings,
} from '@packages/shared'
// Bounds are ordered by numeric priority ascending (lower number = higher precedence).
const priorityOrder = sql`CAST(${regionBounds.priority} AS REAL) ASC`
function toSummary(region: typeof regions.$inferSelect): RegionSummary {
return { id: region.id, name: region.name, description: region.description }
}
function toBoundDto(bound: typeof regionBounds.$inferSelect): RegionBoundDto {
return {
id: bound.id,
regionId: bound.regionId,
description: bound.description,
geojson: bound.geojson as RegionBoundDto['geojson'],
priority: bound.priority ?? '',
}
}
export async function getAllRegions(): Promise<RegionSummary[]> {
const rows = await db.select().from(regions).orderBy(regions.name)
return rows.map(toSummary)
}
export async function getRegionById(id: number): Promise<RegionSummary | null> {
const row = await db.query.regions.findFirst({ where: eq(regions.id, id) })
return row ? toSummary(row) : null
}
export async function getRegionWithBounds(id: number): Promise<RegionWithBounds | null> {
const region = await db.query.regions.findFirst({ where: eq(regions.id, id) })
if (!region) return null
const bounds = await db
.select()
.from(regionBounds)
.where(eq(regionBounds.regionId, id))
.orderBy(priorityOrder)
return { ...toSummary(region), bounds: bounds.map(toBoundDto) }
}
export async function createRegion(input: CreateRegionInput): Promise<RegionSummary> {
const [row] = await db
.insert(regions)
.values({ name: input.name, description: input.description ?? null })
.returning()
return toSummary(row)
}
export async function updateRegion(input: UpdateRegionInput): Promise<RegionSummary | null> {
const [row] = await db
.update(regions)
.set({
...(input.name !== undefined ? { name: input.name } : {}),
...(input.description !== undefined ? { description: input.description } : {}),
})
.where(eq(regions.id, input.id))
.returning()
return row ? toSummary(row) : null
}
export async function getBoundsForRegion(regionId: number): Promise<RegionBoundDto[]> {
const rows = await db
.select()
.from(regionBounds)
.where(eq(regionBounds.regionId, regionId))
.orderBy(priorityOrder)
return rows.map(toBoundDto)
}
export async function getBoundById(id: number): Promise<RegionBoundDto | null> {
const row = await db.query.regionBounds.findFirst({ where: eq(regionBounds.id, id) })
return row ? toBoundDto(row) : null
}
export async function createRegionBound(input: CreateRegionBoundInput): Promise<RegionBoundDto> {
const [row] = await db
.insert(regionBounds)
.values({
regionId: input.regionId,
description: input.description ?? null,
geojson: input.geojson,
priority: String(input.priority),
})
.returning()
return toBoundDto(row)
}
export async function updateRegionBound(input: UpdateRegionBoundInput): Promise<RegionBoundDto | null> {
const [row] = await db
.update(regionBounds)
.set({
...(input.description !== undefined ? { description: input.description } : {}),
...(input.geojson !== undefined ? { geojson: input.geojson } : {}),
...(input.priority !== undefined ? { priority: String(input.priority) } : {}),
})
.where(eq(regionBounds.id, input.id))
.returning()
return row ? toBoundDto(row) : null
}
export async function getBoundSettings(boundId: number): Promise<Record<string, string | null>> {
const rows = await db
.select()
.from(regionBoundSettings)
.where(eq(regionBoundSettings.boundId, boundId))
const result: Record<string, string | null> = {}
for (const row of rows) result[row.key] = row.value
return result
}
export async function upsertBoundSettings(
boundId: number,
settings: Array<{ key: string; value: string | null }>
): Promise<void> {
const bound = await db.query.regionBounds.findFirst({
where: eq(regionBounds.id, boundId),
columns: { id: true, regionId: true },
})
if (!bound) throw new Error(`Region bound ${boundId} not found`)
await db.transaction(async (tx) => {
for (const { key, value } of settings) {
const existing = await tx.query.regionBoundSettings.findFirst({
where: and(
eq(regionBoundSettings.boundId, boundId),
eq(regionBoundSettings.key, key)
),
columns: { id: true },
})
if (existing) {
await tx
.update(regionBoundSettings)
.set({ value: value === null ? null : String(value) })
.where(eq(regionBoundSettings.id, existing.id))
} else {
await tx.insert(regionBoundSettings).values({
regionId: bound.regionId,
boundId,
key,
value: value === null ? null : String(value),
})
}
}
})
}
/** Effective region settings = settings of the region's lowest-numbered-priority bound. */
export async function getEffectiveRegionSettings(regionId: number): Promise<EffectiveRegionSettings | null> {
const bound = await db.query.regionBounds.findFirst({
where: eq(regionBounds.regionId, regionId),
orderBy: priorityOrder,
})
if (!bound) return null
const settings = await getBoundSettings(bound.id)
return {
regionId,
boundId: bound.id,
priority: bound.priority ?? '',
settings,
}
}