339 lines
11 KiB
TypeScript
339 lines
11 KiB
TypeScript
import { db } from '../db/db_index'
|
|
import { regions, regionBounds, regionConsts, regionBoundConsts } from '../db/schema'
|
|
import { eq, sql, and } from 'drizzle-orm'
|
|
import { BOUND_CONST_KEYS, CONST_DEFAULTS, REGION_CONST_KEYS } from '../lib/const-keys'
|
|
import type {
|
|
RegionSummary,
|
|
RegionWithBounds,
|
|
RegionBoundDto,
|
|
CreateRegionInput,
|
|
CreateRegionWithBoundsInput,
|
|
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`
|
|
|
|
const serializeDefault = (value: unknown): string | null => {
|
|
if (value === null || value === undefined) return null
|
|
return typeof value === 'string' ? value : String(value)
|
|
}
|
|
|
|
const isVersionKey = (key: string) => key.includes('version')
|
|
|
|
function defaultRegionRows(regionId: number) {
|
|
return REGION_CONST_KEYS.map((key) => ({
|
|
regionId,
|
|
key,
|
|
value: isVersionKey(key) ? '1' : serializeDefault(CONST_DEFAULTS[key as keyof typeof CONST_DEFAULTS]),
|
|
}))
|
|
}
|
|
|
|
function defaultBoundRows(regionId: number, boundId: number) {
|
|
return BOUND_CONST_KEYS.map((key) => ({
|
|
regionId,
|
|
boundId,
|
|
key,
|
|
value: serializeDefault(CONST_DEFAULTS[key as keyof typeof CONST_DEFAULTS]),
|
|
}))
|
|
}
|
|
|
|
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)
|
|
const boundRows = await db
|
|
.select({ id: regionBounds.id, regionId: regionBounds.regionId })
|
|
.from(regionBounds)
|
|
.orderBy(regionBounds.regionId, priorityOrder)
|
|
|
|
// First (lowest-priority) bound per region is the effective one.
|
|
const effective = new Map<number, number>()
|
|
for (const bound of boundRows) {
|
|
if (!effective.has(bound.regionId)) effective.set(bound.regionId, bound.id)
|
|
}
|
|
|
|
return rows.map((region) => ({
|
|
...toSummary(region),
|
|
effectiveBoundId: effective.get(region.id) ?? null,
|
|
}))
|
|
}
|
|
|
|
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) }
|
|
}
|
|
|
|
/**
|
|
* Every region with its bounds, for coordinate-based region resolution.
|
|
* Regions are ordered by id; each region's bounds by ascending numeric priority
|
|
* (lowest number = highest precedence).
|
|
*/
|
|
export async function getAllRegionsWithBounds(): Promise<RegionWithBounds[]> {
|
|
const regionRows = await db.select().from(regions).orderBy(regions.id)
|
|
const boundRows = await db
|
|
.select()
|
|
.from(regionBounds)
|
|
.orderBy(regionBounds.regionId, priorityOrder)
|
|
|
|
const byRegion = new Map<number, RegionBoundDto[]>()
|
|
for (const bound of boundRows) {
|
|
const list = byRegion.get(bound.regionId) ?? []
|
|
list.push(toBoundDto(bound))
|
|
byRegion.set(bound.regionId, list)
|
|
}
|
|
|
|
return regionRows.map((region) => ({
|
|
...toSummary(region),
|
|
bounds: byRegion.get(region.id) ?? [],
|
|
}))
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
/**
|
|
* Create a region together with at least one delivery bound, atomically.
|
|
* Regions are unusable without bounds, so creation and seeding are one step.
|
|
* Seeds default region_consts rows and per-bound region_bound_consts rows.
|
|
*/
|
|
export async function createRegionWithBounds(
|
|
input: CreateRegionWithBoundsInput
|
|
): Promise<{ region: RegionSummary; bounds: RegionBoundDto[] }> {
|
|
return db.transaction(async (tx) => {
|
|
const [region] = await tx
|
|
.insert(regions)
|
|
.values({ name: input.name, description: input.description ?? null })
|
|
.returning()
|
|
|
|
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),
|
|
}))
|
|
)
|
|
.returning()
|
|
|
|
await tx.insert(regionConsts).values(defaultRegionRows(region.id)).onConflictDoNothing()
|
|
|
|
const boundRows = inserted.flatMap((bound) => defaultBoundRows(region.id, bound.id))
|
|
if (boundRows.length > 0) {
|
|
await tx.insert(regionBoundConsts).values(boundRows).onConflictDoNothing()
|
|
}
|
|
|
|
return { region: toSummary(region), bounds: inserted.map(toBoundDto) }
|
|
})
|
|
}
|
|
|
|
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> {
|
|
return db.transaction(async (tx) => {
|
|
const [row] = await tx
|
|
.insert(regionBounds)
|
|
.values({
|
|
regionId: input.regionId,
|
|
description: input.description ?? null,
|
|
geojson: input.geojson,
|
|
priority: String(input.priority),
|
|
})
|
|
.returning()
|
|
|
|
await tx
|
|
.insert(regionBoundConsts)
|
|
.values(defaultBoundRows(input.regionId, row.id))
|
|
.onConflictDoNothing()
|
|
|
|
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
|
|
}
|
|
|
|
/** Bound-scoped consts (region_bound_consts) for one bound. */
|
|
export async function getBoundSettings(boundId: number): Promise<Record<string, string | null>> {
|
|
const rows = await db
|
|
.select()
|
|
.from(regionBoundConsts)
|
|
.where(eq(regionBoundConsts.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 nextValue = value === null ? null : String(value)
|
|
await tx
|
|
.insert(regionBoundConsts)
|
|
.values({ regionId: bound.regionId, boundId, key, value: nextValue })
|
|
.onConflictDoUpdate({
|
|
target: [regionBoundConsts.boundId, regionBoundConsts.key],
|
|
set: { value: nextValue, regionId: bound.regionId },
|
|
})
|
|
}
|
|
})
|
|
}
|
|
|
|
/** Region-scoped consts (region_consts) for one region. */
|
|
export async function getRegionConstants(regionId: number): Promise<Record<string, string | null>> {
|
|
const rows = await db.select().from(regionConsts).where(eq(regionConsts.regionId, regionId))
|
|
const result: Record<string, string | null> = {}
|
|
for (const row of rows) result[row.key] = row.value
|
|
return result
|
|
}
|
|
|
|
export async function upsertRegionConstants(
|
|
regionId: number,
|
|
settings: Array<{ key: string; value: string | null }>
|
|
): Promise<void> {
|
|
await db.transaction(async (tx) => {
|
|
for (const { key, value } of settings) {
|
|
const nextValue = value === null ? null : String(value)
|
|
await tx
|
|
.insert(regionConsts)
|
|
.values({ regionId, key, value: nextValue })
|
|
.onConflictDoUpdate({
|
|
target: [regionConsts.regionId, regionConsts.key],
|
|
set: { value: nextValue },
|
|
})
|
|
}
|
|
})
|
|
}
|
|
|
|
/** The region's lowest-numbered-priority bound id, if any. */
|
|
export async function getEffectiveBoundId(regionId: number): Promise<number | null> {
|
|
const bound = await db.query.regionBounds.findFirst({
|
|
where: eq(regionBounds.regionId, regionId),
|
|
orderBy: priorityOrder,
|
|
columns: { id: true },
|
|
})
|
|
return bound?.id ?? null
|
|
}
|
|
|
|
/**
|
|
* Effective region settings = the region's region_consts merged with the
|
|
* region_bound_consts of its lowest-numbered-priority bound (bound wins).
|
|
*/
|
|
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 [regionValues, boundValues] = await Promise.all([
|
|
getRegionConstants(regionId),
|
|
getBoundSettings(bound.id),
|
|
])
|
|
return {
|
|
regionId,
|
|
boundId: bound.id,
|
|
priority: bound.priority ?? '',
|
|
settings: { ...regionValues, ...boundValues },
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Region + a SPECIFIC bound's settings (bound wins over region). Used at checkout
|
|
* to apply the delivery address's bound instead of the region's effective bound.
|
|
* Returns null when the bound does not belong to the region.
|
|
*/
|
|
export async function getRegionSettingsForBound(
|
|
regionId: number,
|
|
boundId: number
|
|
): Promise<EffectiveRegionSettings | null> {
|
|
const bound = await db.query.regionBounds.findFirst({
|
|
where: and(eq(regionBounds.id, boundId), eq(regionBounds.regionId, regionId)),
|
|
})
|
|
if (!bound) return null
|
|
const [regionValues, boundValues] = await Promise.all([
|
|
getRegionConstants(regionId),
|
|
getBoundSettings(boundId),
|
|
])
|
|
return {
|
|
regionId,
|
|
boundId,
|
|
priority: bound.priority ?? '',
|
|
settings: { ...regionValues, ...boundValues },
|
|
}
|
|
}
|