freshyo/packages/db_helper_sqlite/src/user-apis/address.ts
2026-10-26 21:57:05 +05:30

231 lines
7.1 KiB
TypeScript

import { db } from '../db/db_index'
import { addresses, deliverySlotInfo, orders, orderStatus } from '../db/schema'
import { and, eq, gte, inArray, isNotNull } from 'drizzle-orm'
import type { InferSelectModel } from 'drizzle-orm'
import type { UserAddress } from '@packages/shared'
type AddressRow = InferSelectModel<typeof addresses>
const mapUserAddress = (address: AddressRow): UserAddress => ({
id: address.id,
userId: address.userId,
regionId: address.regionId ?? null,
boundId: address.boundId ?? null,
name: address.name,
phone: address.phone,
addressLine1: address.addressLine1,
addressLine2: address.addressLine2 ?? null,
city: address.city,
state: address.state,
isDefault: address.isDefault,
latitude: address.latitude ?? null,
longitude: address.longitude ?? null,
googleMapsUrl: address.googleMapsUrl ?? null,
vagueBackfilledCoords: address.vagueBackfilledCoords ?? false,
adminLatitude: address.adminLatitude ?? null,
adminLongitude: address.adminLongitude ?? null,
zoneId: address.zoneId ?? null,
createdAt: address.createdAt,
})
export async function getDefaultAddress(userId: number): Promise<UserAddress | null> {
const [defaultAddress] = await db
.select()
.from(addresses)
.where(and(eq(addresses.userId, userId), eq(addresses.isDefault, true)))
.limit(1)
return defaultAddress ? mapUserAddress(defaultAddress) : null
}
export async function getUserAddresses(userId: number): Promise<UserAddress[]> {
const userAddresses = await db.select().from(addresses).where(eq(addresses.userId, userId))
return userAddresses.map(mapUserAddress)
}
export async function getUserAddressById(userId: number, addressId: number): Promise<UserAddress | null> {
const [address] = await db
.select()
.from(addresses)
.where(and(eq(addresses.id, addressId), eq(addresses.userId, userId)))
.limit(1)
return address ? mapUserAddress(address) : null
}
export async function clearDefaultAddress(userId: number): Promise<void> {
await db.update(addresses).set({ isDefault: false }).where(eq(addresses.userId, userId))
}
export async function createUserAddress(input: {
userId: number
regionId: number
boundId?: number | null
name: string
phone: string
addressLine1: string
addressLine2?: string
city: string
state: string
isDefault: boolean
latitude?: number
longitude?: number
googleMapsUrl?: string
}): Promise<UserAddress> {
const [newAddress] = await db.insert(addresses).values({
userId: input.userId,
regionId: input.regionId,
boundId: input.boundId ?? null,
name: input.name,
phone: input.phone,
addressLine1: input.addressLine1,
addressLine2: input.addressLine2,
city: input.city,
state: input.state,
isDefault: input.isDefault,
latitude: input.latitude,
longitude: input.longitude,
googleMapsUrl: input.googleMapsUrl,
}).returning()
return mapUserAddress(newAddress)
}
export async function updateUserAddress(input: {
userId: number
addressId: number
regionId: number
boundId?: number | null
name: string
phone: string
addressLine1: string
addressLine2?: string
city: string
state: string
isDefault: boolean
latitude?: number
longitude?: number
googleMapsUrl?: string
vagueBackfilledCoords?: boolean
}): Promise<UserAddress | null> {
const [updatedAddress] = await db.update(addresses)
.set({
regionId: input.regionId,
...(input.boundId !== undefined ? { boundId: input.boundId } : {}),
name: input.name,
phone: input.phone,
addressLine1: input.addressLine1,
addressLine2: input.addressLine2,
city: input.city,
state: input.state,
isDefault: input.isDefault,
googleMapsUrl: input.googleMapsUrl,
latitude: input.latitude,
longitude: input.longitude,
...(input.vagueBackfilledCoords !== undefined
? { vagueBackfilledCoords: input.vagueBackfilledCoords }
: {}),
})
.where(and(eq(addresses.id, input.addressId), eq(addresses.userId, input.userId)))
.returning()
return updatedAddress ? mapUserAddress(updatedAddress) : null
}
export async function deleteUserAddress(userId: number, addressId: number): Promise<boolean> {
const [deleted] = await db.delete(addresses)
.where(and(eq(addresses.id, addressId), eq(addresses.userId, userId)))
.returning({ id: addresses.id })
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> {
const ongoingOrders = await db.select({
orderId: orders.id,
})
.from(orders)
.innerJoin(orderStatus, eq(orders.id, orderStatus.orderId))
.innerJoin(deliverySlotInfo, eq(orders.slotId, deliverySlotInfo.id))
.where(and(
eq(orders.addressId, addressId),
eq(orderStatus.isCancelled, false),
gte(deliverySlotInfo.deliveryTime, new Date())
))
.limit(1)
return ongoingOrders.length > 0
}