diff --git a/apps/backend/src/sqliteImporter.ts b/apps/backend/src/sqliteImporter.ts index 82063aa..16e583f 100644 --- a/apps/backend/src/sqliteImporter.ts +++ b/apps/backend/src/sqliteImporter.ts @@ -50,6 +50,8 @@ export { updateOrderItemPackaging, removeDeliveryCharge, getSlotOrders, + getOrderItems, + getArchivedOrderItems, updateAddressCoords, getAllOrders, orderCoords, diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/order.ts b/apps/backend/src/trpc/apis/admin-apis/apis/order.ts index 94460f3..f036e97 100644 --- a/apps/backend/src/trpc/apis/admin-apis/apis/order.ts +++ b/apps/backend/src/trpc/apis/admin-apis/apis/order.ts @@ -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 => { + 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 => { + const items = await getArchivedOrderItemsInDb(ctx.staffUser!.regionId, input.orderId) + return { items, source: 'archive' } + }), + updateAddressCoords: protectedProcedure .input( z.object({ diff --git a/apps/web-ui/src/routes/location-selector.tsx b/apps/web-ui/src/routes/location-selector.tsx index 0da3c84..347a26d 100644 --- a/apps/web-ui/src/routes/location-selector.tsx +++ b/apps/web-ui/src/routes/location-selector.tsx @@ -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): 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(null) const mapRef = useRef(null) - const markerRef = useRef(null) const [isLoading, setIsLoading] = useState(true) const [loadError, setLoadError] = useState(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(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() { )} - {isMobile ? ( - -
-

- Use the selected point as address location -

-
- - -
-
-
- ) : ( - -
-

Use the selected point as address location

- -
- - -
-
-
+ {!isLoading && !loadError && ( +
+

+ Drag the pin or tap the map to choose your exact location +

+ +
)} ) diff --git a/change-log.txt b/change-log.txt index e22f00c..d83a032 100644 --- a/change-log.txt +++ b/change-log.txt @@ -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. diff --git a/packages/db_helper_sqlite/index.ts b/packages/db_helper_sqlite/index.ts index d86e444..55fc3e0 100644 --- a/packages/db_helper_sqlite/index.ts +++ b/packages/db_helper_sqlite/index.ts @@ -61,6 +61,8 @@ export { updateOrderItemPackaging, removeDeliveryCharge, getSlotOrders, + getOrderItems, + getArchivedOrderItems, updateAddressCoords, getAllOrders, orderCoords, diff --git a/packages/db_helper_sqlite/src/admin-apis/order.ts b/packages/db_helper_sqlite/src/admin-apis/order.ts index 411b749..e7b8f79 100644 --- a/packages/db_helper_sqlite/src/admin-apis/order.ts +++ b/packages/db_helper_sqlite/src/admin-apis/order.ts @@ -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 { + 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 { + 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 { + 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 { const { cursor, @@ -436,11 +501,8 @@ export async function getAllOrders(regionId: number, input: GetAllOrdersInput): let whereCondition: SQL | 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) diff --git a/packages/db_helper_sqlite/src/lib/order-items.ts b/packages/db_helper_sqlite/src/lib/order-items.ts index 265862e..d7dd98b 100644 --- a/packages/db_helper_sqlite/src/lib/order-items.ts +++ b/packages/db_helper_sqlite/src/lib/order-items.ts @@ -66,48 +66,48 @@ function chunks(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> { +export async function loadArchivedOrderItems( + orderIds: number[] +): Promise> { const ids = [...new Set(orderIds.filter((id) => Number.isFinite(id)))] const result = new Map() 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> { + const ids = [...new Set(orderIds.filter((id) => Number.isFinite(id)))] + const result = new Map() + 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> { + const ids = [...new Set(orderIds.filter((id) => Number.isFinite(id)))] + const result = new Map() + 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( rows: T[] diff --git a/packages/shared/types/admin.ts b/packages/shared/types/admin.ts index fcff0fd..a0f5f11 100644 --- a/packages/shared/types/admin.ts +++ b/packages/shared/types/admin.ts @@ -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;