freshyo/packages/db_helper_sqlite/src/lib/order-items.ts
2026-10-26 15:05:08 +05:30

186 lines
5.6 KiB
TypeScript

import { inArray } from 'drizzle-orm'
import { db } from '../db/db_index'
import { orderItems, orders, type OrderItemSnapshot } from '../db/schema'
/**
* Compatibility row shape: identical to what Drizzle returns for an `order_items`
* row with its `sku` relation. The API mappers and every client depend on this
* shape (nested `sku.product.name`, `sku.features`, raw `quantity`/`price`
* strings, snake_case packaging flags), so archived JSON is expanded back into it.
*/
export interface OrderItemRowCompat {
id: number
orderId: number
skuId: number
quantity: string
price: string
discountedPrice: string | null
is_packaged: boolean
is_package_verified: boolean
packagedAt: Date | null
sku: {
id: number
name: string | null
images: string[] | null
features: { featureName: string | null; featureValue: string }[]
product: { name: string } | null
} | null
}
function coercePackagedAt(value: string | null): Date | null {
if (!value) return null
const date = new Date(value)
return Number.isNaN(date.getTime()) ? null : date
}
function snapshotToRow(orderId: number, snapshot: OrderItemSnapshot): OrderItemRowCompat {
return {
id: snapshot.id,
orderId,
skuId: snapshot.skuId,
quantity: snapshot.quantity,
price: snapshot.price,
discountedPrice: snapshot.discountedPrice,
is_packaged: snapshot.isPackaged,
is_package_verified: snapshot.isPackageVerified,
packagedAt: coercePackagedAt(snapshot.packagedAt),
sku: {
id: snapshot.skuId,
name: snapshot.skuName,
images: snapshot.image ? [snapshot.image] : null,
features: snapshot.features.map((feature) => ({
featureName: feature.featureName,
featureValue: feature.featureValue,
})),
product: { name: snapshot.productName },
},
}
}
function chunks<T>(values: T[], size: number): T[][] {
const out: T[][] = []
for (let index = 0; index < values.length; index += size) {
out.push(values.slice(index, index + size))
}
return out
}
/**
* Reads ONLY the archived snapshots (`orders.items_json`). Table-backed orders
* are absent from the returned map.
*/
export async function loadArchivedOrderItems(
orderIds: number[]
): Promise<Map<number, OrderItemRowCompat[]>> {
const ids = [...new Set(orderIds.filter((id) => Number.isFinite(id)))]
const result = new Map<number, OrderItemRowCompat[]>()
if (ids.length === 0) return result
for (const chunk of chunks(ids, 50)) {
const rows = await db
.select({ id: orders.id, itemsJson: orders.itemsJson })
.from(orders)
.where(inArray(orders.id, chunk))
for (const order of rows) {
if (order.itemsJson != null) {
result.set(
order.id,
order.itemsJson.map((snapshot) => snapshotToRow(order.id, snapshot))
)
}
}
}
return result
}
/**
* Reads ONLY the live `order_items` rows (with sku/product/features). Archived
* orders keep no rows there, so they are absent from the returned map.
*/
export async function loadTableOrderItems(
orderIds: number[]
): Promise<Map<number, OrderItemRowCompat[]>> {
const ids = [...new Set(orderIds.filter((id) => Number.isFinite(id)))]
const result = new Map<number, OrderItemRowCompat[]>()
if (ids.length === 0) return result
// Queries are chunked: D1 allows at most 100 bound parameters per statement.
for (const chunk of chunks(ids, 50)) {
const rows = await db.query.orderItems.findMany({
where: inArray(orderItems.orderId, chunk),
with: {
sku: {
columns: {
id: true,
name: true,
images: true,
},
with: {
product: {
columns: { name: true },
},
features: {
columns: {
featureName: true,
featureValue: true,
},
},
},
},
},
})
for (const row of rows) {
const list = result.get(row.orderId) ?? []
list.push(row as unknown as OrderItemRowCompat)
result.set(row.orderId, list)
}
}
for (const list of result.values()) {
list.sort((first, second) => first.id - second.id)
}
return result
}
/**
* Loads order items for the given orders, once.
*
* - `orders.items_json IS NOT NULL` → parse the snapshot; `order_items` is never
* queried for that order.
* - otherwise → the existing relational query, only for the remaining ids.
*
* The two sources are also exported separately for callers that need to know
* which one answered (`loadArchivedOrderItems` / `loadTableOrderItems`).
*/
export async function loadOrderItems(orderIds: number[]): Promise<Map<number, OrderItemRowCompat[]>> {
const ids = [...new Set(orderIds.filter((id) => Number.isFinite(id)))]
const result = new Map<number, OrderItemRowCompat[]>()
if (ids.length === 0) return result
const archived = await loadArchivedOrderItems(ids)
const tableBackedIds = ids.filter((id) => !archived.has(id))
const tableBacked = await loadTableOrderItems(tableBackedIds)
// Orders that do not exist (or are outside the caller's scope) get an empty list.
for (const id of ids) {
result.set(id, archived.get(id) ?? tableBacked.get(id) ?? [])
}
return result
}
/** Attaches `orderItems` to a batch of order rows without an eager relation. */
export async function attachOrderItems<T extends { id: number }>(
rows: T[]
): Promise<Array<T & { orderItems: OrderItemRowCompat[] }>> {
if (rows.length === 0) return []
const itemsByOrder = await loadOrderItems(rows.map((row) => row.id))
return rows.map((row) => ({
...row,
orderItems: itemsByOrder.get(row.id) ?? [],
}))
}