Compare commits
2 commits
8305c3bcf4
...
0d56f3fea3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d56f3fea3 | ||
|
|
7c74dfaf09 |
9 changed files with 246 additions and 137 deletions
|
|
@ -50,6 +50,8 @@ export {
|
|||
updateOrderItemPackaging,
|
||||
removeDeliveryCharge,
|
||||
getSlotOrders,
|
||||
getOrderItems,
|
||||
getArchivedOrderItems,
|
||||
updateAddressCoords,
|
||||
getAllOrders,
|
||||
orderCoords,
|
||||
|
|
|
|||
|
|
@ -16,6 +16,8 @@ import {
|
|||
updateOrderItemPackaging as updateOrderItemPackagingInDb,
|
||||
removeDeliveryCharge as removeDeliveryChargeInDb,
|
||||
getSlotOrders as getSlotOrdersInDb,
|
||||
getOrderItems as getOrderItemsInDb,
|
||||
getArchivedOrderItems as getArchivedOrderItemsInDb,
|
||||
updateAddressCoords as updateAddressCoordsInDb,
|
||||
getAllOrders as getAllOrdersInDb,
|
||||
rebalanceSlots as rebalanceSlotsInDb,
|
||||
|
|
@ -29,6 +31,7 @@ import type {
|
|||
AdminOrderBasicResult,
|
||||
AdminOrderDetails,
|
||||
AdminOrderItemPackagingResult,
|
||||
AdminOrderItemsResult,
|
||||
AdminOrderMessageResult,
|
||||
AdminOrderRow,
|
||||
AdminOrderUpdateResult,
|
||||
|
|
@ -198,6 +201,25 @@ export const orderRouter = router({
|
|||
return { ...result, data }
|
||||
}),
|
||||
|
||||
// Live `order_items` rows for one order. Older orders keep no rows there
|
||||
// (their items live in orders.items_json) and return an empty list.
|
||||
getOrderItems: protectedProcedure
|
||||
.input(z.object({ orderId: z.number() }))
|
||||
.query(async ({ input, ctx }): Promise<AdminOrderItemsResult> => {
|
||||
const items = await getOrderItemsInDb(ctx.staffUser!.regionId, input.orderId)
|
||||
return { items, source: 'table' }
|
||||
}),
|
||||
|
||||
// Archived items (`orders.items_json`) for one order. Live orders return an
|
||||
// empty list. Kept separate from the table query on purpose: callers can pick
|
||||
// the source without the backend guessing.
|
||||
getArchivedOrderItems: protectedProcedure
|
||||
.input(z.object({ orderId: z.number() }))
|
||||
.query(async ({ input, ctx }): Promise<AdminOrderItemsResult> => {
|
||||
const items = await getArchivedOrderItemsInDb(ctx.staffUser!.regionId, input.orderId)
|
||||
return { items, source: 'archive' }
|
||||
}),
|
||||
|
||||
updateAddressCoords: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
|
|
|
|||
|
|
@ -1,8 +1,6 @@
|
|||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { AlertCircle, Loader2, Minus, Plus } from 'lucide-react'
|
||||
import { BottomDialog } from 'web-components'
|
||||
import { Dialog } from '../components/Dialog'
|
||||
|
||||
export const Route = createFileRoute('/location-selector')({
|
||||
// Optional centre override (?lat=&lng=&zoom=) so the map can be opened for a
|
||||
|
|
@ -43,6 +41,8 @@ interface GoogleMap {
|
|||
interface GoogleMarker {
|
||||
setMap: (map: GoogleMap | null) => void
|
||||
setPosition: (position: LatLngLiteral) => void
|
||||
getPosition: () => { lat: () => number; lng: () => number } | null | undefined
|
||||
addListener: (event: string, handler: () => void) => void
|
||||
}
|
||||
interface GoogleMapConstructor {
|
||||
new (element: HTMLElement, options: Record<string, unknown>): GoogleMap
|
||||
|
|
@ -177,34 +177,17 @@ function sendCoordsToHost(coords: LatLngLiteral) {
|
|||
}
|
||||
}
|
||||
|
||||
// Tailwind's `md` breakpoint is 768px, so "mobile" is anything below it.
|
||||
const MOBILE_QUERY = '(max-width: 767px)'
|
||||
|
||||
function useIsMobile(): boolean {
|
||||
const [isMobile, setIsMobile] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const mql = window.matchMedia(MOBILE_QUERY)
|
||||
const update = () => setIsMobile(mql.matches)
|
||||
update()
|
||||
mql.addEventListener('change', update)
|
||||
return () => mql.removeEventListener('change', update)
|
||||
}, [])
|
||||
|
||||
return isMobile
|
||||
}
|
||||
|
||||
function LocationSelectorPage() {
|
||||
const mapContainerRef = useRef<HTMLDivElement | null>(null)
|
||||
const mapRef = useRef<GoogleMap | null>(null)
|
||||
const markerRef = useRef<GoogleMarker | null>(null)
|
||||
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [loadError, setLoadError] = useState<string | null>(null)
|
||||
// The chosen point. `null` = untouched: the pin is on the map, but the user
|
||||
// has not tapped/dragged it yet, so Continue stays disabled.
|
||||
const [pendingCoords, setPendingCoords] = useState<LatLngLiteral | null>(null)
|
||||
|
||||
const search = Route.useSearch()
|
||||
const isMobile = useIsMobile()
|
||||
|
||||
useEffect(() => {
|
||||
if (!GOOGLE_MAPS_API_KEY) {
|
||||
|
|
@ -241,20 +224,33 @@ function LocationSelectorPage() {
|
|||
})
|
||||
mapRef.current = map
|
||||
|
||||
// The pin is on the map from the start, at the map centre. Continue is
|
||||
// disabled until the user touches it (tap anywhere on the map, tap the
|
||||
// pin, or drag the pin), which is what writes `pendingCoords`.
|
||||
const marker = new maps.Marker({
|
||||
map,
|
||||
position: center,
|
||||
draggable: true,
|
||||
})
|
||||
|
||||
const chooseMarkerPosition = () => {
|
||||
const position = marker.getPosition()
|
||||
if (!position) return
|
||||
setPendingCoords({ lat: position.lat(), lng: position.lng() })
|
||||
}
|
||||
|
||||
// `dragstart` enables Continue as soon as the pin is grabbed; `dragend`
|
||||
// stores the final position. A plain tap on the pin also selects it.
|
||||
marker.addListener('dragstart', chooseMarkerPosition)
|
||||
marker.addListener('dragend', chooseMarkerPosition)
|
||||
marker.addListener('click', chooseMarkerPosition)
|
||||
|
||||
map.addListener('click', (event) => {
|
||||
const latLng = event.latLng
|
||||
if (!latLng) return
|
||||
|
||||
const coords = { lat: latLng.lat(), lng: latLng.lng() }
|
||||
|
||||
// Highlight the selected point right away.
|
||||
if (markerRef.current) {
|
||||
markerRef.current.setPosition(coords)
|
||||
markerRef.current.setMap(map)
|
||||
} else {
|
||||
markerRef.current = new maps.Marker({ map, position: coords })
|
||||
}
|
||||
|
||||
marker.setPosition(coords)
|
||||
setPendingCoords(coords)
|
||||
})
|
||||
|
||||
|
|
@ -282,16 +278,8 @@ function LocationSelectorPage() {
|
|||
|
||||
// Hand the coordinates back to the native host when embedded.
|
||||
sendCoordsToHost(pendingCoords)
|
||||
|
||||
setPendingCoords(null)
|
||||
}, [pendingCoords])
|
||||
|
||||
const handleCancel = useCallback(() => {
|
||||
// Remove the highlight if the selection is rejected.
|
||||
markerRef.current?.setMap(null)
|
||||
setPendingCoords(null)
|
||||
}, [])
|
||||
|
||||
const handleZoom = useCallback((delta: number) => {
|
||||
const map = mapRef.current
|
||||
if (!map) return
|
||||
|
|
@ -339,53 +327,23 @@ function LocationSelectorPage() {
|
|||
</div>
|
||||
)}
|
||||
|
||||
{isMobile ? (
|
||||
<BottomDialog open={pendingCoords !== null} onClose={handleCancel}>
|
||||
<div className="pb-2">
|
||||
<p className="mb-5 text-center text-base font-semibold text-gray-900">
|
||||
Use the selected point as address location
|
||||
</p>
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCancel}
|
||||
className="flex-1 rounded-lg border border-gray-200 bg-white px-5 py-3 text-sm font-bold text-gray-700 transition-colors hover:bg-gray-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleConfirm}
|
||||
className="flex-1 rounded-lg bg-brand-600 px-5 py-3 text-sm font-bold text-white transition-colors hover:bg-brand-700"
|
||||
>
|
||||
Confirm location
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</BottomDialog>
|
||||
) : (
|
||||
<Dialog open={pendingCoords !== null} onClose={handleCancel} title="Confirm this location?">
|
||||
<div className="px-6 py-5">
|
||||
<p className="text-sm text-gray-600">Use the selected point as address location</p>
|
||||
|
||||
<div className="mt-5 flex justify-end gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCancel}
|
||||
className="rounded-lg border border-gray-200 bg-white px-5 py-2.5 text-sm font-bold text-gray-700 transition-colors hover:bg-gray-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleConfirm}
|
||||
className="rounded-lg bg-brand-600 px-5 py-2.5 text-sm font-bold text-white transition-colors hover:bg-brand-700"
|
||||
>
|
||||
Confirm location
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
{!isLoading && !loadError && (
|
||||
<div
|
||||
className="absolute inset-x-0 bottom-0 z-10 border-t border-gray-100 bg-white px-4 pt-3 shadow-[0_-2px_10px_rgba(0,0,0,0.06)]"
|
||||
style={{ paddingBottom: 'max(1rem, env(safe-area-inset-bottom))' }}
|
||||
>
|
||||
<p className="mb-2 text-center text-xs text-gray-500">
|
||||
Drag the pin or tap the map to choose your exact location
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleConfirm}
|
||||
disabled={pendingCoords === null}
|
||||
className="w-full rounded-lg bg-brand-600 px-5 py-3 text-sm font-bold text-white transition-colors hover:bg-brand-700 disabled:cursor-not-allowed disabled:bg-gray-300 disabled:hover:bg-gray-300"
|
||||
>
|
||||
Continue
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -10354,3 +10354,48 @@ Added LOC-57: the address text uses numberOfLines=1 + ellipsizeMode="tail".
|
|||
|
||||
--- apps/user-ui/JEST-TEST-CASES.md
|
||||
LOC-57 row.
|
||||
|
||||
[2026-10-26 00:51 IST] Location selector (web-ui `/location-selector`): legacy draggable pin is now on
|
||||
the map from the start, and a persistent "Continue" button replaces the post-tap confirm
|
||||
dialog/sheet. Continue stays disabled until the pin is touched (map tap, pin tap, or pin drag).
|
||||
|
||||
--- apps/web-ui/src/routes/location-selector.tsx
|
||||
- Removed `BottomDialog` / `Dialog` imports, `MOBILE_QUERY`, `useIsMobile`, `isMobile`.
|
||||
+ GoogleMarker gains `addListener`, `getPosition`; the marker is created at the initial centre
|
||||
with `draggable: true`.
|
||||
+ `dragstart` / `dragend` / marker `click` / map `click` all write `pendingCoords`; null means
|
||||
"untouched", so the Continue button is disabled.
|
||||
+ Bottom action bar with the hint "Drag the pin or tap the map ..." and a disabled-until-touched
|
||||
Continue button (same on mobile/desktop; the hosts already render their own Cancel).
|
||||
- Removed `handleCancel` (the parent/WebView closes the map).
|
||||
Bottom bar uses `padding-bottom: max(1rem, env(safe-area-inset-bottom))` for the WebView/home indicator.
|
||||
Typecheck: `apps/web-ui` clean. No user-ui change needed (it embeds this page and keeps its own Cancel).
|
||||
|
||||
[2026-10-26 15:02 IST] Admin manage-orders: older orders are now listed, and item loading is split
|
||||
into a live `order_items` query and an `orders.items_json` (archived) query.
|
||||
|
||||
--- packages/db_helper_sqlite/src/lib/order-items.ts
|
||||
+ loadArchivedOrderItems(orderIds): reads only `orders.items_json`.
|
||||
+ loadTableOrderItems(orderIds): reads only `order_items` (+ sku/product/features).
|
||||
~ loadOrderItems() now uses archived-first, table-fallback via those two; the compat row shape
|
||||
and callers (`attachOrderItems`) are unchanged.
|
||||
|
||||
--- packages/db_helper_sqlite/src/admin-apis/order.ts
|
||||
- removed the "today + previous 2 days (IST)" window from getAllOrders, so pagination walks every
|
||||
order in the region (archived ones included).
|
||||
+ toAdminOrderListItems() shared mapper (same numbers as before).
|
||||
+ getOrderItems(regionId, orderId) -> live table rows only.
|
||||
+ getArchivedOrderItems(regionId, orderId) -> items_json rows only.
|
||||
|
||||
--- apps/backend/src/trpc/apis/admin-apis/apis/order.ts
|
||||
+ admin.order.getOrderItems({ orderId }) -> { items, source: 'table' }
|
||||
+ admin.order.getArchivedOrderItems({ orderId }) -> { items, source: 'archive' }
|
||||
|
||||
--- packages/shared/types/admin.ts
|
||||
+ AdminOrderItemsResult / AdminOrderItemsSource.
|
||||
Also re-exported the two new DB helpers through `packages/db_helper_sqlite/index.ts` and
|
||||
`apps/backend/src/sqliteImporter.ts`.
|
||||
Typecheck: backend, admin-ui, admin-web all clean.
|
||||
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
|
||||
client change was needed. The 3-day window was the only thing hiding them.
|
||||
|
|
|
|||
0
change-logs/change-log-pre-multiregion.txt
Normal file
0
change-logs/change-log-pre-multiregion.txt
Normal file
|
|
@ -61,6 +61,8 @@ export {
|
|||
updateOrderItemPackaging,
|
||||
removeDeliveryCharge,
|
||||
getSlotOrders,
|
||||
getOrderItems,
|
||||
getArchivedOrderItems,
|
||||
updateAddressCoords,
|
||||
getAllOrders,
|
||||
orderCoords,
|
||||
|
|
|
|||
|
|
@ -8,9 +8,14 @@ import {
|
|||
orders,
|
||||
orderStatus,
|
||||
} from '../db/schema'
|
||||
import { and, desc, eq, inArray, isNull, lt, sql, SQL } from 'drizzle-orm'
|
||||
import { and, desc, eq, inArray, isNull, lt, SQL } from 'drizzle-orm'
|
||||
import { releaseCouponUsageIfGroupFullyCancelled } from '../user-apis/order'
|
||||
import { attachOrderItems } from '../lib/order-items'
|
||||
import {
|
||||
attachOrderItems,
|
||||
loadArchivedOrderItems,
|
||||
loadTableOrderItems,
|
||||
type OrderItemRowCompat,
|
||||
} from '../lib/order-items'
|
||||
import type {
|
||||
AdminOrderDetails,
|
||||
AdminOrderRow,
|
||||
|
|
@ -21,6 +26,7 @@ import type {
|
|||
AdminOrderBasicResult,
|
||||
AdminGetSlotOrdersResult,
|
||||
AdminGetAllOrdersResultWithUserId,
|
||||
AdminOrderListItemProduct,
|
||||
AdminRebalanceSlotsResult,
|
||||
AdminCancelOrderResult,
|
||||
GetAllOrdersInput,
|
||||
|
|
@ -423,6 +429,65 @@ export async function updateAddressCoords(
|
|||
return { success: result.length > 0 }
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared admin-list item shape for both sources (`order_items` rows and rows
|
||||
* expanded from `orders.items_json`). Keeps the per-line numbers the list and
|
||||
* its items dialog already show.
|
||||
*/
|
||||
function toAdminOrderListItems(items: OrderItemRowCompat[]): AdminOrderListItemProduct[] {
|
||||
return items
|
||||
.map((item) => ({
|
||||
id: item.id,
|
||||
name: composeSkuName(
|
||||
item.sku?.product?.name ?? 'Unknown',
|
||||
item.sku?.features || [],
|
||||
item.sku?.name ?? null
|
||||
),
|
||||
skuName: item.sku?.name ?? null,
|
||||
quantity: parseFloat(item.quantity),
|
||||
price: parseFloat(item.price.toString()),
|
||||
amount: parseFloat(item.quantity) * parseFloat(item.price.toString()),
|
||||
unit: composeUnitNotation(item.sku?.features || []),
|
||||
productSize: 1,
|
||||
isPackaged: item.is_packaged,
|
||||
isPackageVerified: item.is_package_verified,
|
||||
features: (item.sku?.features || []).map((feature) => ({
|
||||
featureName: feature.featureName,
|
||||
featureValue: feature.featureValue,
|
||||
})),
|
||||
}))
|
||||
.sort((first, second) => first.id - second.id)
|
||||
}
|
||||
|
||||
/** Region guard shared by the two item-source queries. */
|
||||
async function orderExistsInRegion(regionId: number, orderId: number): Promise<boolean> {
|
||||
const row = await db.query.orders.findFirst({
|
||||
where: and(eq(orders.id, orderId), eq(orders.regionId, regionId)),
|
||||
columns: { id: true },
|
||||
})
|
||||
return row != null
|
||||
}
|
||||
|
||||
/** Live items only: `order_items` rows for one order (empty for archived orders). */
|
||||
export async function getOrderItems(
|
||||
regionId: number,
|
||||
orderId: number
|
||||
): Promise<AdminOrderListItemProduct[]> {
|
||||
if (!(await orderExistsInRegion(regionId, orderId))) return []
|
||||
const itemsByOrder = await loadTableOrderItems([orderId])
|
||||
return toAdminOrderListItems(itemsByOrder.get(orderId) ?? [])
|
||||
}
|
||||
|
||||
/** Archived items only: `orders.items_json` for one order (empty for live orders). */
|
||||
export async function getArchivedOrderItems(
|
||||
regionId: number,
|
||||
orderId: number
|
||||
): Promise<AdminOrderListItemProduct[]> {
|
||||
if (!(await orderExistsInRegion(regionId, orderId))) return []
|
||||
const itemsByOrder = await loadArchivedOrderItems([orderId])
|
||||
return toAdminOrderListItems(itemsByOrder.get(orderId) ?? [])
|
||||
}
|
||||
|
||||
export async function getAllOrders(regionId: number, input: GetAllOrdersInput): Promise<AdminGetAllOrdersResultWithUserId> {
|
||||
const {
|
||||
cursor,
|
||||
|
|
@ -436,11 +501,8 @@ export async function getAllOrders(regionId: number, input: GetAllOrdersInput):
|
|||
|
||||
let whereCondition: SQL<unknown> | undefined = eq(orders.regionId, regionId)
|
||||
|
||||
// Admin manage-orders only shows the IST calendar window: today + previous 2 days.
|
||||
whereCondition = and(
|
||||
whereCondition,
|
||||
sql`date(datetime(${orders.createdAt}), '+5 hours', '+30 minutes') >= date(datetime('now'), '+5 hours', '+30 minutes', '-2 days')`
|
||||
)
|
||||
// No date window: the admin list walks every order in the region, newest
|
||||
// first, so older (archived) orders stay reachable through pagination.
|
||||
|
||||
// Keyset pagination over the region's own rows: the cursor is the id of the last
|
||||
// order returned, so each page is just the next `limit + 1` rows below it. A page
|
||||
|
|
@ -498,24 +560,7 @@ export async function getAllOrders(regionId: number, input: GetAllOrdersInput):
|
|||
status = 'delivered'
|
||||
}
|
||||
|
||||
const items = order.orderItems
|
||||
.map((item: any) => ({
|
||||
id: item.id,
|
||||
name: composeSkuName(item.sku.product?.name ?? 'Unknown', item.sku.features || [], item.sku.name),
|
||||
skuName: item.sku.name ?? null,
|
||||
quantity: parseFloat(item.quantity),
|
||||
price: parseFloat(item.price.toString()),
|
||||
amount: parseFloat(item.quantity) * parseFloat(item.price.toString()),
|
||||
unit: composeUnitNotation(item.sku.features || []),
|
||||
productSize: 1,
|
||||
isPackaged: item.is_packaged,
|
||||
isPackageVerified: item.is_package_verified,
|
||||
features: (item.sku.features || []).map((f: any) => ({
|
||||
featureName: f.featureName,
|
||||
featureValue: f.featureValue,
|
||||
})),
|
||||
}))
|
||||
.sort((first: any, second: any) => first.id - second.id)
|
||||
const items = toAdminOrderListItems(order.orderItems)
|
||||
|
||||
order.address = order.address || {}
|
||||
const coords = orderCoords(order.address)
|
||||
|
|
|
|||
|
|
@ -66,48 +66,48 @@ function chunks<T>(values: T[], size: number): T[][] {
|
|||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* Queries are chunked: D1 allows at most 100 bound parameters per statement and
|
||||
* the relational `with` subqueries consume one each, so large admin pages (up to
|
||||
* 100 rows) must not be sent in one `IN (...)`.
|
||||
* Reads ONLY the archived snapshots (`orders.items_json`). Table-backed orders
|
||||
* are absent from the returned map.
|
||||
*/
|
||||
export async function loadOrderItems(orderIds: number[]): Promise<Map<number, OrderItemRowCompat[]>> {
|
||||
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
|
||||
|
||||
const orderRows: { id: number; itemsJson: OrderItemSnapshot[] | null }[] = []
|
||||
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))
|
||||
orderRows.push(...rows)
|
||||
}
|
||||
|
||||
const tableBackedIds: number[] = []
|
||||
for (const order of orderRows) {
|
||||
if (order.itemsJson != null) {
|
||||
result.set(
|
||||
order.id,
|
||||
order.itemsJson.map((snapshot) => snapshotToRow(order.id, snapshot))
|
||||
)
|
||||
} else {
|
||||
tableBackedIds.push(order.id)
|
||||
for (const order of rows) {
|
||||
if (order.itemsJson != null) {
|
||||
result.set(
|
||||
order.id,
|
||||
order.itemsJson.map((snapshot) => snapshotToRow(order.id, snapshot))
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Orders that do not exist (or are outside the caller's scope) get an empty list.
|
||||
for (const id of ids) {
|
||||
if (!result.has(id)) result.set(id, [])
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
for (const chunk of chunks(tableBackedIds, 50)) {
|
||||
/**
|
||||
* 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: {
|
||||
|
|
@ -146,6 +146,33 @@ export async function loadOrderItems(orderIds: number[]): Promise<Map<number, Or
|
|||
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[]
|
||||
|
|
|
|||
|
|
@ -210,6 +210,14 @@ export interface AdminGetAllOrdersResult {
|
|||
nextCursor?: number;
|
||||
}
|
||||
|
||||
/** Where an order's items came from: the live table or the archived JSON. */
|
||||
export type AdminOrderItemsSource = 'table' | 'archive';
|
||||
|
||||
export interface AdminOrderItemsResult {
|
||||
items: AdminOrderListItemProduct[];
|
||||
source: AdminOrderItemsSource;
|
||||
}
|
||||
|
||||
export interface AdminGetAllOrdersResultWithUserId {
|
||||
orders: AdminOrderListItemWithUserId[];
|
||||
nextCursor?: number;
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue