Compare commits
No commits in common. "0d56f3fea3059cfbf45a18b564326b5fe14818e2" and "8305c3bcf44a5da86ad75b37bc9d3a75f6a674f9" have entirely different histories.
0d56f3fea3
...
8305c3bcf4
9 changed files with 137 additions and 246 deletions
|
|
@ -50,8 +50,6 @@ export {
|
||||||
updateOrderItemPackaging,
|
updateOrderItemPackaging,
|
||||||
removeDeliveryCharge,
|
removeDeliveryCharge,
|
||||||
getSlotOrders,
|
getSlotOrders,
|
||||||
getOrderItems,
|
|
||||||
getArchivedOrderItems,
|
|
||||||
updateAddressCoords,
|
updateAddressCoords,
|
||||||
getAllOrders,
|
getAllOrders,
|
||||||
orderCoords,
|
orderCoords,
|
||||||
|
|
|
||||||
|
|
@ -16,8 +16,6 @@ import {
|
||||||
updateOrderItemPackaging as updateOrderItemPackagingInDb,
|
updateOrderItemPackaging as updateOrderItemPackagingInDb,
|
||||||
removeDeliveryCharge as removeDeliveryChargeInDb,
|
removeDeliveryCharge as removeDeliveryChargeInDb,
|
||||||
getSlotOrders as getSlotOrdersInDb,
|
getSlotOrders as getSlotOrdersInDb,
|
||||||
getOrderItems as getOrderItemsInDb,
|
|
||||||
getArchivedOrderItems as getArchivedOrderItemsInDb,
|
|
||||||
updateAddressCoords as updateAddressCoordsInDb,
|
updateAddressCoords as updateAddressCoordsInDb,
|
||||||
getAllOrders as getAllOrdersInDb,
|
getAllOrders as getAllOrdersInDb,
|
||||||
rebalanceSlots as rebalanceSlotsInDb,
|
rebalanceSlots as rebalanceSlotsInDb,
|
||||||
|
|
@ -31,7 +29,6 @@ import type {
|
||||||
AdminOrderBasicResult,
|
AdminOrderBasicResult,
|
||||||
AdminOrderDetails,
|
AdminOrderDetails,
|
||||||
AdminOrderItemPackagingResult,
|
AdminOrderItemPackagingResult,
|
||||||
AdminOrderItemsResult,
|
|
||||||
AdminOrderMessageResult,
|
AdminOrderMessageResult,
|
||||||
AdminOrderRow,
|
AdminOrderRow,
|
||||||
AdminOrderUpdateResult,
|
AdminOrderUpdateResult,
|
||||||
|
|
@ -201,25 +198,6 @@ export const orderRouter = router({
|
||||||
return { ...result, data }
|
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
|
updateAddressCoords: protectedProcedure
|
||||||
.input(
|
.input(
|
||||||
z.object({
|
z.object({
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
import { createFileRoute } from '@tanstack/react-router'
|
import { createFileRoute } from '@tanstack/react-router'
|
||||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||||
import { AlertCircle, Loader2, Minus, Plus } from 'lucide-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')({
|
export const Route = createFileRoute('/location-selector')({
|
||||||
// Optional centre override (?lat=&lng=&zoom=) so the map can be opened for a
|
// Optional centre override (?lat=&lng=&zoom=) so the map can be opened for a
|
||||||
|
|
@ -41,8 +43,6 @@ interface GoogleMap {
|
||||||
interface GoogleMarker {
|
interface GoogleMarker {
|
||||||
setMap: (map: GoogleMap | null) => void
|
setMap: (map: GoogleMap | null) => void
|
||||||
setPosition: (position: LatLngLiteral) => void
|
setPosition: (position: LatLngLiteral) => void
|
||||||
getPosition: () => { lat: () => number; lng: () => number } | null | undefined
|
|
||||||
addListener: (event: string, handler: () => void) => void
|
|
||||||
}
|
}
|
||||||
interface GoogleMapConstructor {
|
interface GoogleMapConstructor {
|
||||||
new (element: HTMLElement, options: Record<string, unknown>): GoogleMap
|
new (element: HTMLElement, options: Record<string, unknown>): GoogleMap
|
||||||
|
|
@ -177,17 +177,34 @@ 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() {
|
function LocationSelectorPage() {
|
||||||
const mapContainerRef = useRef<HTMLDivElement | null>(null)
|
const mapContainerRef = useRef<HTMLDivElement | null>(null)
|
||||||
const mapRef = useRef<GoogleMap | null>(null)
|
const mapRef = useRef<GoogleMap | null>(null)
|
||||||
|
const markerRef = useRef<GoogleMarker | null>(null)
|
||||||
|
|
||||||
const [isLoading, setIsLoading] = useState(true)
|
const [isLoading, setIsLoading] = useState(true)
|
||||||
const [loadError, setLoadError] = useState<string | null>(null)
|
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 [pendingCoords, setPendingCoords] = useState<LatLngLiteral | null>(null)
|
||||||
|
|
||||||
const search = Route.useSearch()
|
const search = Route.useSearch()
|
||||||
|
const isMobile = useIsMobile()
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!GOOGLE_MAPS_API_KEY) {
|
if (!GOOGLE_MAPS_API_KEY) {
|
||||||
|
|
@ -224,33 +241,20 @@ function LocationSelectorPage() {
|
||||||
})
|
})
|
||||||
mapRef.current = map
|
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) => {
|
map.addListener('click', (event) => {
|
||||||
const latLng = event.latLng
|
const latLng = event.latLng
|
||||||
if (!latLng) return
|
if (!latLng) return
|
||||||
|
|
||||||
const coords = { lat: latLng.lat(), lng: latLng.lng() }
|
const coords = { lat: latLng.lat(), lng: latLng.lng() }
|
||||||
marker.setPosition(coords)
|
|
||||||
|
// 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 })
|
||||||
|
}
|
||||||
|
|
||||||
setPendingCoords(coords)
|
setPendingCoords(coords)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -278,8 +282,16 @@ function LocationSelectorPage() {
|
||||||
|
|
||||||
// Hand the coordinates back to the native host when embedded.
|
// Hand the coordinates back to the native host when embedded.
|
||||||
sendCoordsToHost(pendingCoords)
|
sendCoordsToHost(pendingCoords)
|
||||||
|
|
||||||
|
setPendingCoords(null)
|
||||||
}, [pendingCoords])
|
}, [pendingCoords])
|
||||||
|
|
||||||
|
const handleCancel = useCallback(() => {
|
||||||
|
// Remove the highlight if the selection is rejected.
|
||||||
|
markerRef.current?.setMap(null)
|
||||||
|
setPendingCoords(null)
|
||||||
|
}, [])
|
||||||
|
|
||||||
const handleZoom = useCallback((delta: number) => {
|
const handleZoom = useCallback((delta: number) => {
|
||||||
const map = mapRef.current
|
const map = mapRef.current
|
||||||
if (!map) return
|
if (!map) return
|
||||||
|
|
@ -327,23 +339,53 @@ function LocationSelectorPage() {
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!isLoading && !loadError && (
|
{isMobile ? (
|
||||||
<div
|
<BottomDialog open={pendingCoords !== null} onClose={handleCancel}>
|
||||||
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)]"
|
<div className="pb-2">
|
||||||
style={{ paddingBottom: 'max(1rem, env(safe-area-inset-bottom))' }}
|
<p className="mb-5 text-center text-base font-semibold text-gray-900">
|
||||||
>
|
Use the selected point as address location
|
||||||
<p className="mb-2 text-center text-xs text-gray-500">
|
|
||||||
Drag the pin or tap the map to choose your exact location
|
|
||||||
</p>
|
</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
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={handleConfirm}
|
onClick={handleConfirm}
|
||||||
disabled={pendingCoords === null}
|
className="flex-1 rounded-lg bg-brand-600 px-5 py-3 text-sm font-bold text-white transition-colors hover:bg-brand-700"
|
||||||
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
|
Confirm location
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</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>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -10354,48 +10354,3 @@ Added LOC-57: the address text uses numberOfLines=1 + ellipsizeMode="tail".
|
||||||
|
|
||||||
--- apps/user-ui/JEST-TEST-CASES.md
|
--- apps/user-ui/JEST-TEST-CASES.md
|
||||||
LOC-57 row.
|
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.
|
|
||||||
|
|
|
||||||
|
|
@ -61,8 +61,6 @@ export {
|
||||||
updateOrderItemPackaging,
|
updateOrderItemPackaging,
|
||||||
removeDeliveryCharge,
|
removeDeliveryCharge,
|
||||||
getSlotOrders,
|
getSlotOrders,
|
||||||
getOrderItems,
|
|
||||||
getArchivedOrderItems,
|
|
||||||
updateAddressCoords,
|
updateAddressCoords,
|
||||||
getAllOrders,
|
getAllOrders,
|
||||||
orderCoords,
|
orderCoords,
|
||||||
|
|
|
||||||
|
|
@ -8,14 +8,9 @@ import {
|
||||||
orders,
|
orders,
|
||||||
orderStatus,
|
orderStatus,
|
||||||
} from '../db/schema'
|
} from '../db/schema'
|
||||||
import { and, desc, eq, inArray, isNull, lt, SQL } from 'drizzle-orm'
|
import { and, desc, eq, inArray, isNull, lt, sql, SQL } from 'drizzle-orm'
|
||||||
import { releaseCouponUsageIfGroupFullyCancelled } from '../user-apis/order'
|
import { releaseCouponUsageIfGroupFullyCancelled } from '../user-apis/order'
|
||||||
import {
|
import { attachOrderItems } from '../lib/order-items'
|
||||||
attachOrderItems,
|
|
||||||
loadArchivedOrderItems,
|
|
||||||
loadTableOrderItems,
|
|
||||||
type OrderItemRowCompat,
|
|
||||||
} from '../lib/order-items'
|
|
||||||
import type {
|
import type {
|
||||||
AdminOrderDetails,
|
AdminOrderDetails,
|
||||||
AdminOrderRow,
|
AdminOrderRow,
|
||||||
|
|
@ -26,7 +21,6 @@ import type {
|
||||||
AdminOrderBasicResult,
|
AdminOrderBasicResult,
|
||||||
AdminGetSlotOrdersResult,
|
AdminGetSlotOrdersResult,
|
||||||
AdminGetAllOrdersResultWithUserId,
|
AdminGetAllOrdersResultWithUserId,
|
||||||
AdminOrderListItemProduct,
|
|
||||||
AdminRebalanceSlotsResult,
|
AdminRebalanceSlotsResult,
|
||||||
AdminCancelOrderResult,
|
AdminCancelOrderResult,
|
||||||
GetAllOrdersInput,
|
GetAllOrdersInput,
|
||||||
|
|
@ -429,65 +423,6 @@ export async function updateAddressCoords(
|
||||||
return { success: result.length > 0 }
|
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> {
|
export async function getAllOrders(regionId: number, input: GetAllOrdersInput): Promise<AdminGetAllOrdersResultWithUserId> {
|
||||||
const {
|
const {
|
||||||
cursor,
|
cursor,
|
||||||
|
|
@ -501,8 +436,11 @@ export async function getAllOrders(regionId: number, input: GetAllOrdersInput):
|
||||||
|
|
||||||
let whereCondition: SQL<unknown> | undefined = eq(orders.regionId, regionId)
|
let whereCondition: SQL<unknown> | undefined = eq(orders.regionId, regionId)
|
||||||
|
|
||||||
// No date window: the admin list walks every order in the region, newest
|
// Admin manage-orders only shows the IST calendar window: today + previous 2 days.
|
||||||
// first, so older (archived) orders stay reachable through pagination.
|
whereCondition = and(
|
||||||
|
whereCondition,
|
||||||
|
sql`date(datetime(${orders.createdAt}), '+5 hours', '+30 minutes') >= date(datetime('now'), '+5 hours', '+30 minutes', '-2 days')`
|
||||||
|
)
|
||||||
|
|
||||||
// Keyset pagination over the region's own rows: the cursor is the id of the last
|
// 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
|
// order returned, so each page is just the next `limit + 1` rows below it. A page
|
||||||
|
|
@ -560,7 +498,24 @@ export async function getAllOrders(regionId: number, input: GetAllOrdersInput):
|
||||||
status = 'delivered'
|
status = 'delivered'
|
||||||
}
|
}
|
||||||
|
|
||||||
const items = toAdminOrderListItems(order.orderItems)
|
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)
|
||||||
|
|
||||||
order.address = order.address || {}
|
order.address = order.address || {}
|
||||||
const coords = orderCoords(order.address)
|
const coords = orderCoords(order.address)
|
||||||
|
|
|
||||||
|
|
@ -66,48 +66,48 @@ function chunks<T>(values: T[], size: number): T[][] {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reads ONLY the archived snapshots (`orders.items_json`). Table-backed orders
|
* Loads order items for the given orders, once.
|
||||||
* are absent from the returned map.
|
*
|
||||||
|
* - `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 (...)`.
|
||||||
*/
|
*/
|
||||||
export async function loadArchivedOrderItems(
|
export async function loadOrderItems(orderIds: number[]): Promise<Map<number, OrderItemRowCompat[]>> {
|
||||||
orderIds: number[]
|
|
||||||
): Promise<Map<number, OrderItemRowCompat[]>> {
|
|
||||||
const ids = [...new Set(orderIds.filter((id) => Number.isFinite(id)))]
|
const ids = [...new Set(orderIds.filter((id) => Number.isFinite(id)))]
|
||||||
const result = new Map<number, OrderItemRowCompat[]>()
|
const result = new Map<number, OrderItemRowCompat[]>()
|
||||||
if (ids.length === 0) return result
|
if (ids.length === 0) return result
|
||||||
|
|
||||||
|
const orderRows: { id: number; itemsJson: OrderItemSnapshot[] | null }[] = []
|
||||||
for (const chunk of chunks(ids, 50)) {
|
for (const chunk of chunks(ids, 50)) {
|
||||||
const rows = await db
|
const rows = await db
|
||||||
.select({ id: orders.id, itemsJson: orders.itemsJson })
|
.select({ id: orders.id, itemsJson: orders.itemsJson })
|
||||||
.from(orders)
|
.from(orders)
|
||||||
.where(inArray(orders.id, chunk))
|
.where(inArray(orders.id, chunk))
|
||||||
|
orderRows.push(...rows)
|
||||||
|
}
|
||||||
|
|
||||||
for (const order of rows) {
|
const tableBackedIds: number[] = []
|
||||||
|
for (const order of orderRows) {
|
||||||
if (order.itemsJson != null) {
|
if (order.itemsJson != null) {
|
||||||
result.set(
|
result.set(
|
||||||
order.id,
|
order.id,
|
||||||
order.itemsJson.map((snapshot) => snapshotToRow(order.id, snapshot))
|
order.itemsJson.map((snapshot) => snapshotToRow(order.id, snapshot))
|
||||||
)
|
)
|
||||||
}
|
} else {
|
||||||
|
tableBackedIds.push(order.id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
// 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, [])
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
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({
|
const rows = await db.query.orderItems.findMany({
|
||||||
where: inArray(orderItems.orderId, chunk),
|
where: inArray(orderItems.orderId, chunk),
|
||||||
with: {
|
with: {
|
||||||
|
|
@ -146,33 +146,6 @@ export async function loadTableOrderItems(
|
||||||
return result
|
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. */
|
/** Attaches `orderItems` to a batch of order rows without an eager relation. */
|
||||||
export async function attachOrderItems<T extends { id: number }>(
|
export async function attachOrderItems<T extends { id: number }>(
|
||||||
rows: T[]
|
rows: T[]
|
||||||
|
|
|
||||||
|
|
@ -210,14 +210,6 @@ export interface AdminGetAllOrdersResult {
|
||||||
nextCursor?: number;
|
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 {
|
export interface AdminGetAllOrdersResultWithUserId {
|
||||||
orders: AdminOrderListItemWithUserId[];
|
orders: AdminOrderListItemWithUserId[];
|
||||||
nextCursor?: number;
|
nextCursor?: number;
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue