This commit is contained in:
shafi54 2026-10-20 16:13:09 +05:30
parent 80c3f0231f
commit 264bb493d7
32 changed files with 1935 additions and 222 deletions

View file

@ -53,3 +53,19 @@ react-native. They are available in the common-ui as MyText, MyTextInput, MyTouc
## Change Log ## Change Log
- there should be a change log file. unless explicitly specified, assume change-log.txt as the name of the log file. Ensure the file exists. If it doesn't exist create it. Before changing any file which is not a md file or txt file write the change to that file exactly. Write the diff to it and then start making changes. for every change add the current time stamp. - there should be a change log file. unless explicitly specified, assume change-log.txt as the name of the log file. Ensure the file exists. If it doesn't exist create it. Before changing any file which is not a md file or txt file write the change to that file exactly. Write the diff to it and then start making changes. for every change add the current time stamp.
## before editing
- there are proper tests for code. While changing code, also scope what changes are needed in the
tests. Tests and code should go hand in hand. One shouldn't be left behind while one is going
forward. Most of the Projects have a test directory.
## mirror projects
- admin-ui is a react native app. It has a web counterpart admin-web. user-ui is also react native
app. It's web counterpart is web-ui. Any changes you do in the react native should have exactly
same changes in their web counterparts too.
## relevant projects
- the db_helper_postgres is an abandoned project. Don't make any changes there or don't report any
errors from there.

View file

@ -0,0 +1,26 @@
import { runOrderItemsArchive, type ArchiveSummary, type ArchiveRunOptions } from '@/src/dbService'
import { ensureWorkerInit } from '@/src/lib/worker-init'
/** 2:00 AM IST (Cloudflare cron runs in UTC). */
export const CRON_ORDER_ITEMS_ARCHIVE = '30 20 * * *'
export async function runOrderItemsArchiveCron(params: {
cron: string
env: any
now?: Date
}): Promise<ArchiveSummary | null> {
const { cron, env, now } = params
if (cron !== CRON_ORDER_ITEMS_ARCHIVE) {
return null
}
ensureWorkerInit(env)
return runOrderItemsArchive({ now })
}
/** Guarded test/local entry point; the env is the worker's global ENV. */
export async function runOrderItemsArchiveNow(options: ArchiveRunOptions = {}): Promise<ArchiveSummary> {
const env = (globalThis as { ENV?: Record<string, unknown> }).ENV
ensureWorkerInit(env as any)
return runOrderItemsArchive(options)
}

View file

@ -286,4 +286,19 @@ export {
getEffectiveRegionSettings, getEffectiveRegionSettings,
// Superadmin - Complaints // Superadmin - Complaints
getAllComplaintsForSuperadmin, getAllComplaintsForSuperadmin,
// Order item archive
archiveOrderItems,
runOrderItemsArchive,
istCalendarCutoffUtc,
validateSnapshot,
buildSnapshot,
} from '../../../packages/db_helper_sqlite'
export type {
ArchiveSummary,
ArchiveSkip,
ArchiveRunOptions,
ArchiveSourceRow,
ArchiveSkuRow,
ArchiveStore,
} from '../../../packages/db_helper_sqlite' } from '../../../packages/db_helper_sqlite'

View file

@ -42,8 +42,10 @@ export const initializeAllStores = async (regionId?: number): Promise<void> => {
console.log('All application stores initialized successfully'); console.log('All application stores initialized successfully');
// Regenerate cache files for the target region(s) (fire-and-forget) // Regenerate cache files for the target region(s). Awaited so the DO alarm
createAllCacheFiles(regionId).catch(error => { // (and the startup path) cannot return before the upload/purge completes;
// the .catch keeps a cache failure from failing store initialization.
await createAllCacheFiles(regionId).catch(error => {
console.error('Failed to regenerate cache files during store initialization:', error) console.error('Failed to regenerate cache files during store initialization:', error)
}) })
} catch (error) { } catch (error) {

View file

@ -9,6 +9,7 @@ import { Hono } from 'hono'
import cacheSnapshotController from '@/src/test-support/cache-snapshot-controller' import cacheSnapshotController from '@/src/test-support/cache-snapshot-controller'
import rebuildController from '@/src/test-support/rebuild-controller' import rebuildController from '@/src/test-support/rebuild-controller'
import orderTrackerController from '@/src/test-support/order-tracker-controller' import orderTrackerController from '@/src/test-support/order-tracker-controller'
import orderItemsArchiveController from '@/src/test-support/order-items-archive-controller'
const router = new Hono() const router = new Hono()
@ -23,5 +24,6 @@ router.get('/', (c) => {
router.route('/cache', cacheSnapshotController) router.route('/cache', cacheSnapshotController)
router.route('/rebuild', rebuildController) router.route('/rebuild', rebuildController)
router.route('/order-trackers', orderTrackerController) router.route('/order-trackers', orderTrackerController)
router.route('/order-items-archive', orderItemsArchiveController)
export default router export default router

View file

@ -0,0 +1,44 @@
/**
* TEST-ONLY synchronous order-item archive route.
*
* Mounted at `/api/test/order-items-archive` behind `authenticateUser`.
* Returns 404 unless `ENABLE_TEST_ROUTES=true` (local `.dev.vars` only).
*
* Routes:
* POST /api/test/order-items-archive
* POST /api/test/order-items-archive?now=2026-10-20T00:00:00.000Z&batchSize=50
*/
import { Hono } from 'hono'
import { runOrderItemsArchiveNow } from '@/src/jobs/order-items-archive'
const router = new Hono()
router.post('/', async (c) => {
const env = (globalThis as { ENV?: Record<string, string> }).ENV
if (env?.ENABLE_TEST_ROUTES !== 'true') {
return c.json({ error: 'test routes are disabled' }, 404)
}
const nowRaw = c.req.query('now')
const now = nowRaw ? new Date(nowRaw) : new Date()
if (Number.isNaN(now.getTime())) {
return c.json({ error: 'now must be a valid ISO timestamp' }, 400)
}
const parsePositiveInt = (raw: string | undefined): number | undefined | null => {
if (raw == null || raw === '') return undefined
const value = Number(raw)
return Number.isInteger(value) && value > 0 ? value : null
}
const batchSize = parsePositiveInt(c.req.query('batchSize'))
const maxBatches = parsePositiveInt(c.req.query('maxBatches'))
if (batchSize === null || maxBatches === null) {
return c.json({ error: 'batchSize/maxBatches must be positive integers' }, 400)
}
const summary = await runOrderItemsArchiveNow({ now, batchSize, maxBatches })
return c.json({ ok: true, ...summary })
})
export default router

View file

@ -124,8 +124,10 @@ export const slotsRouter = router({
console.error('Failed to regenerate slots cache after slot create:', error) console.error('Failed to regenerate slots cache after slot create:', error)
}) })
// Fire and forget: cleanup stale product slot associations // Cleanup stale product slot associations. Awaited so the incremental
staleSlotsCleanup().catch((error) => { // 20-slot window is not skipped when the mutation returns; the .catch
// keeps a cleanup failure from failing slot creation.
await staleSlotsCleanup().catch((error) => {
console.error('Failed to cleanup stale slots:', error) console.error('Failed to cleanup stale slots:', error)
}) })

View file

@ -298,7 +298,14 @@ export const userRouter = {
negativityScore negativityScore
); );
recomputeUserNegativityScore(userId); // Await so workerd does not cancel the recompute when the mutation
// returns. The helper already logs; a recompute failure must not fail
// the incident that was already created.
try {
await recomputeUserNegativityScore(userId);
} catch {
/* logged inside recomputeUserNegativityScore */
}
return { return {
success: true, success: true,

View file

@ -0,0 +1,81 @@
/**
* Unit tests for `initializeAllStores`' cache-generation step.
*
* `initializeAllStores` used to call `createAllCacheFiles(...)` while returning
* immediately (fire-and-forget). In workerd that can let the caller (the
* CacheCreator alarm, or the Node startup path) finish while the S3 upload and
* CDN purge are still in flight. These tests pin the awaited behaviour:
* - the function does not resolve until cache generation settles;
* - a cache-generation failure is swallowed so store initialization still
* resolves (the existing `.catch` contract).
*/
import { initializeAllStores } from '@/src/stores/store-initializer'
import { createAllCacheFiles } from '@/src/lib/cloud_cache'
jest.mock('@/src/dbService', () => ({
getAllRegions: jest.fn(async () => [{ id: 1 }, { id: 2 }]),
}))
jest.mock('@/src/lib/roles-manager', () => ({
__esModule: true,
default: { fetchRoles: jest.fn(async () => undefined) },
}))
jest.mock('@/src/lib/const-store', () => ({
computeConstants: jest.fn(async () => undefined),
}))
jest.mock('@/src/stores/product-store', () => ({
initializeProducts: jest.fn(async () => undefined),
}))
jest.mock('@/src/stores/product-tag-store', () => ({
initializeProductTagStore: jest.fn(async () => undefined),
}))
jest.mock('@/src/stores/slot-store', () => ({
initializeSlotStore: jest.fn(async () => undefined),
}))
jest.mock('@/src/stores/banner-store', () => ({
initializeBannerStore: jest.fn(async () => undefined),
}))
jest.mock('@/src/lib/cloud_cache', () => ({
createAllCacheFiles: jest.fn(async () => []),
}))
const mockedCreateAllCacheFiles = createAllCacheFiles as jest.MockedFunction<typeof createAllCacheFiles>
const drainMicrotasks = () => new Promise<void>((resolve) => setImmediate(resolve))
describe('initializeAllStores cache generation', () => {
beforeEach(() => {
jest.clearAllMocks()
})
it('awaits createAllCacheFiles before resolving', async () => {
let release!: () => void
const work = new Promise<any[]>((resolve) => {
release = () => resolve([])
})
mockedCreateAllCacheFiles.mockReturnValueOnce(work)
const run = initializeAllStores(1)
let settled = false
run.then(() => {
settled = true
})
await drainMicrotasks()
expect(mockedCreateAllCacheFiles).toHaveBeenCalledTimes(1)
expect(mockedCreateAllCacheFiles).toHaveBeenCalledWith(1)
expect(settled).toBe(false)
release()
await run
expect(settled).toBe(true)
})
it('swallows a cache-generation failure so store init still resolves', async () => {
mockedCreateAllCacheFiles.mockRejectedValueOnce(new Error('s3 down'))
await expect(initializeAllStores(1)).resolves.toBeUndefined()
})
})

View file

@ -0,0 +1,395 @@
/**
* Unit tests for the order-items archive helpers.
*
* These exercise the pure pieces only (calendar cutoff + snapshot validation);
* the DB write/delete is covered by the archive route during live runs.
*/
import {
archiveOrderItems,
buildSnapshot,
istCalendarCutoffUtc,
runOrderItemsArchive,
validateSnapshot,
type ArchiveSkuRow,
type ArchiveSourceRow,
type ArchiveStore,
} from '@/src/dbService'
function sourceRow(over: Partial<ArchiveSourceRow> = {}): ArchiveSourceRow {
return {
id: 1,
orderId: 10,
skuId: 100,
quantity: '2',
price: '199',
discountedPrice: null,
is_packaged: false,
is_package_verified: false,
packagedAt: null,
...over,
}
}
function snapshot(over: Record<string, any> = {}) {
return {
id: 1,
skuId: 100,
quantity: '2',
price: '199',
discountedPrice: null,
isPackaged: false,
isPackageVerified: false,
packagedAt: null,
productName: 'Chicken Breast',
skuName: '1kg',
image: 'chicken.jpg',
features: [{ featureName: 'quantity', featureValue: '1kg' }],
...over,
}
}
describe('istCalendarCutoffUtc', () => {
it('returns the start of the IST day two days before now', () => {
// 12:00 UTC = 17:30 IST on Oct 20; keep Oct 18-20 IST.
const cutoff = istCalendarCutoffUtc(new Date('2026-10-20T12:00:00.000Z'))
expect(cutoff.toISOString()).toBe('2026-10-17T18:30:00.000Z')
})
it('treats 23:59:59 IST as the previous day (archived) and 00:00 IST as kept', () => {
const cutoff = istCalendarCutoffUtc(new Date('2026-10-20T12:00:00.000Z'))
expect(new Date('2026-10-17T18:29:59.000Z').getTime()).toBeLessThan(cutoff.getTime())
expect(new Date('2026-10-17T18:30:00.000Z').getTime()).toBe(cutoff.getTime())
})
})
function skuRow(over: Partial<ArchiveSkuRow> = {}): ArchiveSkuRow {
return {
id: 100,
name: '1kg',
images: ['chicken.jpg'],
isDeleted: false,
product: { name: 'Chicken Breast' },
features: [{ featureName: 'quantity', featureValue: '1kg' }],
...over,
}
}
describe('buildSnapshot', () => {
it('keeps raw quantity/price strings, booleans, null discount and nested features', () => {
const { snapshot } = buildSnapshot([sourceRow()], new Map([[100, skuRow()]]))
expect(snapshot).toEqual([
{
id: 1,
skuId: 100,
quantity: '2',
price: '199',
discountedPrice: null,
isPackaged: false,
isPackageVerified: false,
packagedAt: null,
productName: 'Chicken Breast',
skuName: '1kg',
image: 'chicken.jpg',
features: [{ featureName: 'quantity', featureValue: '1kg' }],
},
])
expect(typeof snapshot![0].quantity).toBe('string')
expect(typeof snapshot![0].price).toBe('string')
expect(snapshot![0].discountedPrice).toBeNull()
expect(snapshot![0].isPackaged).toBe(false)
expect(Array.isArray(snapshot![0].features)).toBe(true)
})
it('keeps an explicit discounted price and packaged flags', () => {
const { snapshot } = buildSnapshot(
[sourceRow({ discountedPrice: '149', is_packaged: true, is_package_verified: true })],
new Map([[100, skuRow()]])
)
expect(snapshot![0].discountedPrice).toBe('149')
expect(snapshot![0].isPackaged).toBe(true)
expect(snapshot![0].isPackageVerified).toBe(true)
})
it('reports a missing catalogue row instead of dropping the line', () => {
const built = buildSnapshot([sourceRow()], new Map())
expect(built.snapshot).toBeUndefined()
expect(built.reason).toMatch(/missing catalogue/)
})
})
describe('validateSnapshot', () => {
it('accepts a valid single-item snapshot and null discountedPrice', () => {
expect(validateSnapshot([sourceRow()], [snapshot()])).toBeNull()
})
it('accepts a populated discountedPrice', () => {
expect(
validateSnapshot(
[sourceRow({ discountedPrice: '149' })],
[snapshot({ discountedPrice: '149' })]
)
).toBeNull()
})
it('rejects an order with no source items', () => {
expect(validateSnapshot([], [])).toMatch(/no items/)
})
it('rejects an empty snapshot', () => {
expect(validateSnapshot([sourceRow()], [])).toMatch(/empty/)
})
it('rejects a count mismatch', () => {
expect(validateSnapshot([sourceRow()], [snapshot(), snapshot({ id: 2 })])).toMatch(
/length/
)
})
it('rejects duplicate ids', () => {
expect(
validateSnapshot(
[sourceRow(), sourceRow({ id: 2 })],
[snapshot(), snapshot()]
)
).toMatch(/duplicate/)
})
it('rejects missing source ids', () => {
expect(
validateSnapshot(
[sourceRow(), sourceRow({ id: 2 })],
[snapshot(), snapshot({ id: 3 })]
)
).toMatch(/unknown item id/)
})
it('rejects a missing productName', () => {
expect(validateSnapshot([sourceRow()], [snapshot({ productName: '' })])).toMatch(
/productName/
)
})
it('rejects non-numeric or non-positive quantity/price', () => {
expect(validateSnapshot([sourceRow()], [snapshot({ quantity: 'abc' })])).toMatch(
/quantity/
)
expect(validateSnapshot([sourceRow()], [snapshot({ quantity: '0' })])).toMatch(
/quantity/
)
expect(validateSnapshot([sourceRow()], [snapshot({ price: '-1' })])).toMatch(
/price/
)
})
it('rejects 0/1 or string flags', () => {
expect(validateSnapshot([sourceRow()], [snapshot({ isPackaged: 1 })])).toMatch(
/isPackaged/
)
expect(
validateSnapshot([sourceRow()], [snapshot({ isPackageVerified: 'true' })])
).toMatch(/isPackageVerified/)
})
it('rejects a stringified features array', () => {
expect(
validateSnapshot([sourceRow()], [snapshot({ features: '[]' })])
).toMatch(/features/)
})
it('rejects invalid feature entries', () => {
expect(
validateSnapshot(
[sourceRow()],
[snapshot({ features: [{ featureName: 'quantity', featureValue: 1 }] })]
)
).toMatch(/feature/)
})
it('rejects an invalid packagedAt', () => {
expect(
validateSnapshot([sourceRow()], [snapshot({ packagedAt: 'not-a-date' })])
).toMatch(/packagedAt/)
})
})
function makeStore(options: {
rowsByOrder: Record<number, ArchiveSourceRow[]>
skuById?: Map<number, ArchiveSkuRow>
apply?: (orderId: number, snapshot: unknown[], verifiedIds: number[]) => boolean | Promise<boolean>
eligibleBatches?: number[][]
}) {
const applyCalls: { orderId: number; snapshot: unknown[]; verifiedIds: number[] }[] = []
const listCursors: number[] = []
let listCall = 0
const store: ArchiveStore = {
loadSource: async (ids) => ({
rows: ids.flatMap((id) => options.rowsByOrder[id] ?? []),
skuById: options.skuById ?? new Map([[100, skuRow()]]),
}),
applyArchive: async (orderId, snapshot, verifiedIds) => {
applyCalls.push({ orderId, snapshot, verifiedIds })
return options.apply ? await options.apply(orderId, snapshot, verifiedIds) : true
},
listEligibleOrderIds: async (_cutoff, cursor, _limit) => {
listCursors.push(cursor)
return options.eligibleBatches?.[listCall++] ?? []
},
}
return { store, applyCalls, listCursors }
}
describe('archiveOrderItems', () => {
it('applies a valid order and keeps raw strings/booleans/features', async () => {
const { store, applyCalls } = makeStore({
rowsByOrder: { 10: [sourceRow()] },
})
const summary = await archiveOrderItems([10], store)
expect(summary).toEqual({ scanned: 1, archived: 1, skipped: [] })
expect(applyCalls).toHaveLength(1)
expect(applyCalls[0].orderId).toBe(10)
expect(applyCalls[0].verifiedIds).toEqual([1])
expect(applyCalls[0].snapshot[0]).toMatchObject({
id: 1,
skuId: 100,
quantity: '2',
price: '199',
isPackaged: false,
productName: 'Chicken Breast',
})
})
it('skips an order with no items and never calls applyArchive', async () => {
const { store, applyCalls } = makeStore({ rowsByOrder: { 10: [] } })
const summary = await archiveOrderItems([10], store)
expect(summary.archived).toBe(0)
expect(summary.skipped).toEqual([{ orderId: 10, reason: 'order has no items' }])
expect(applyCalls).toHaveLength(0)
})
it('skips an order with a missing catalogue row and never calls applyArchive', async () => {
const { store, applyCalls } = makeStore({
rowsByOrder: { 10: [sourceRow()] },
skuById: new Map(),
})
const summary = await archiveOrderItems([10], store)
expect(summary.archived).toBe(0)
expect(summary.skipped[0].orderId).toBe(10)
expect(summary.skipped[0].reason).toMatch(/missing catalogue/)
expect(applyCalls).toHaveLength(0)
})
it('reports a guard failure (concurrent change) without counting it as archived', async () => {
const { store } = makeStore({
rowsByOrder: { 10: [sourceRow()] },
apply: async () => false,
})
const summary = await archiveOrderItems([10], store)
expect(summary.archived).toBe(0)
expect(summary.skipped).toEqual([
{ orderId: 10, reason: 'source changed during archive' },
])
})
it('handles a mixed batch and deduplicates ids', async () => {
const { store, applyCalls } = makeStore({
rowsByOrder: {
10: [sourceRow()],
20: [sourceRow({ id: 2, orderId: 20 })],
},
skuById: new Map(),
})
const summary = await archiveOrderItems([10, 10, 20], store)
expect(summary.scanned).toBe(2)
expect(summary.archived).toBe(0)
expect(summary.skipped.map((entry) => entry.orderId).sort()).toEqual([10, 20])
expect(applyCalls).toHaveLength(0)
})
})
describe('runOrderItemsArchive', () => {
beforeEach(() => {
jest.spyOn(console, 'log').mockImplementation(() => undefined)
})
afterEach(() => {
jest.restoreAllMocks()
})
it('walks batches by cursor and stops on a short batch', async () => {
const { store, listCursors, applyCalls } = makeStore({
rowsByOrder: {
1: [sourceRow({ id: 1, orderId: 1 })],
2: [sourceRow({ id: 2, orderId: 2 })],
3: [sourceRow({ id: 3, orderId: 3 })],
},
eligibleBatches: [[1, 2], [3]],
})
const summary = await runOrderItemsArchive({ batchSize: 2, maxBatches: 5 }, store)
expect(summary).toMatchObject({ scanned: 3, archived: 3, skipped: [] })
expect(listCursors).toEqual([0, 2])
expect(applyCalls.map((call) => call.orderId)).toEqual([1, 2, 3])
})
it('respects maxBatches', async () => {
const { store, listCursors } = makeStore({
rowsByOrder: {
1: [sourceRow({ id: 1, orderId: 1 })],
2: [sourceRow({ id: 2, orderId: 2 })],
3: [sourceRow({ id: 3, orderId: 3 })],
},
eligibleBatches: [[1], [2], [3]],
})
const summary = await runOrderItemsArchive({ batchSize: 1, maxBatches: 2 }, store)
expect(summary.scanned).toBe(2)
expect(listCursors).toEqual([0, 1])
})
it('advances past skipped orders and reports them', async () => {
const { store, listCursors } = makeStore({
rowsByOrder: { 10: [sourceRow()], 20: [] },
skuById: new Map(),
eligibleBatches: [[10, 20]],
})
const summary = await runOrderItemsArchive({ batchSize: 5, maxBatches: 1 }, store)
expect(summary.scanned).toBe(2)
expect(summary.archived).toBe(0)
expect(summary.skipped.map((entry) => entry.orderId).sort()).toEqual([10, 20])
expect(listCursors).toEqual([0])
})
it('passes the IST calendar cutoff to the store', async () => {
const now = new Date('2026-10-20T12:00:00.000Z')
const cutoff = istCalendarCutoffUtc(now)
const observed: Date[] = []
const store: ArchiveStore = {
loadSource: async () => ({ rows: [], skuById: new Map() }),
applyArchive: async () => true,
listEligibleOrderIds: async (value) => {
observed.push(value)
return []
},
}
await runOrderItemsArchive({ now }, store)
expect(observed).toEqual([cutoff])
})
})

View file

@ -0,0 +1,209 @@
/**
* Unit tests for the queue consumer handlers.
*
* The downstream side effects are mocked, so nothing is sent and no notification
* implementation runs:
* - `sendAdminNotification` is a jest.fn (asserted, never executed)
* - `handleOrderPlaced` / `handleOrderCancelled` are jest.fn (asserted, never executed)
*/
jest.mock('@/src/lib/notif-job', () => ({
sendAdminNotification: jest.fn(async () => undefined),
}))
jest.mock('@/src/lib/post-order-handler', () => ({
handleOrderPlaced: jest.fn(async () => undefined),
handleOrderCancelled: jest.fn(async () => undefined),
}))
import {
handleNotifQueue,
handleOrderCancelledQueue,
handleOrderPlacedQueue,
} from '@/src/lib/queue-consumer'
import { sendAdminNotification } from '@/src/lib/notif-job'
import { handleOrderCancelled, handleOrderPlaced } from '@/src/lib/post-order-handler'
const mockedSendAdminNotification = sendAdminNotification as jest.MockedFunction<
typeof sendAdminNotification
>
const mockedHandleOrderPlaced = handleOrderPlaced as jest.MockedFunction<typeof handleOrderPlaced>
const mockedHandleOrderCancelled = handleOrderCancelled as jest.MockedFunction<
typeof handleOrderCancelled
>
function batch(...messages: any[]): any {
return { messages: messages.map((body) => ({ body })) }
}
beforeEach(() => {
jest.clearAllMocks()
jest.spyOn(console, 'log').mockImplementation(() => undefined)
})
afterEach(() => {
jest.restoreAllMocks()
})
describe('handleNotifQueue', () => {
const payload = {
name: 'send-admin-notification',
jobData: {
tokens: ['tok-1', 'tok-2'],
title: 'New order',
body: 'Order 41',
},
}
it('calls sendAdminNotification with the payload and null fallbacks', async () => {
await handleNotifQueue(batch(payload))
expect(mockedSendAdminNotification).toHaveBeenCalledTimes(1)
expect(mockedSendAdminNotification).toHaveBeenCalledWith({
tokens: ['tok-1', 'tok-2'],
title: 'New order',
body: 'Order 41',
imageUrl: null,
orderId: null,
})
})
it('passes imageUrl and orderId when present', async () => {
await handleNotifQueue(
batch({
...payload,
jobData: { ...payload.jobData, imageUrl: 'https://x/y.png', orderId: 41 },
})
)
expect(mockedSendAdminNotification).toHaveBeenCalledWith(
expect.objectContaining({ imageUrl: 'https://x/y.png', orderId: 41 })
)
})
it('processes only the valid message in a mixed batch', async () => {
await handleNotifQueue(
batch(
null,
{ name: 'other-job', jobData: { tokens: ['x'] } },
{ name: 'send-admin-notification', jobData: { tokens: [] } },
payload
)
)
expect(mockedSendAdminNotification).toHaveBeenCalledTimes(1)
})
it('does nothing for empty bodies or missing tokens', async () => {
await handleNotifQueue(
batch(
null,
{},
{ name: 'send-admin-notification' },
{ name: 'send-admin-notification', jobData: { tokens: [] } }
)
)
expect(mockedSendAdminNotification).not.toHaveBeenCalled()
})
it('handles a batch with no messages', async () => {
await handleNotifQueue({})
expect(mockedSendAdminNotification).not.toHaveBeenCalled()
})
it('propagates a rejection so the queue retries', async () => {
mockedSendAdminNotification.mockRejectedValueOnce(new Error('push failed'))
await expect(handleNotifQueue(batch(payload))).rejects.toThrow('push failed')
})
})
describe('handleOrderPlacedQueue', () => {
it('delegates orderIds to handleOrderPlaced', async () => {
await handleOrderPlacedQueue(batch({ orderIds: [10, 11] }))
expect(mockedHandleOrderPlaced).toHaveBeenCalledWith([10, 11])
})
it('processes each valid message', async () => {
await handleOrderPlacedQueue(batch({ orderIds: [1] }, { orderIds: [2] }))
expect(mockedHandleOrderPlaced).toHaveBeenNthCalledWith(1, [1])
expect(mockedHandleOrderPlaced).toHaveBeenNthCalledWith(2, [2])
})
it('skips empty bodies and non-array orderIds', async () => {
await handleOrderPlacedQueue(
batch(null, {}, { orderIds: 'nope' }, { orderIds: null }, { other: true })
)
expect(mockedHandleOrderPlaced).not.toHaveBeenCalled()
})
it('handles a batch with no messages', async () => {
await handleOrderPlacedQueue({})
expect(mockedHandleOrderPlaced).not.toHaveBeenCalled()
})
it('propagates a rejection so the queue retries', async () => {
mockedHandleOrderPlaced.mockRejectedValueOnce(new Error('placed failed'))
await expect(handleOrderPlacedQueue(batch({ orderIds: [1] }))).rejects.toThrow(
'placed failed'
)
})
})
describe('handleOrderCancelledQueue', () => {
const body = {
orderId: 77,
cancelledBy: 'user',
reason: 'changed mind',
cancelledAt: '2026-10-20T10:00:00.000Z',
}
it('delegates the mapped cancellation payload', async () => {
await handleOrderCancelledQueue(batch(body))
expect(mockedHandleOrderCancelled).toHaveBeenCalledTimes(1)
expect(mockedHandleOrderCancelled).toHaveBeenCalledWith({
orderId: 77,
cancelledBy: 'user',
reason: 'changed mind',
cancelledAt: '2026-10-20T10:00:00.000Z',
})
})
it('processes each valid message', async () => {
await handleOrderCancelledQueue(
batch(body, { ...body, orderId: 78, reason: 'other' })
)
expect(mockedHandleOrderCancelled).toHaveBeenNthCalledWith(
1,
expect.objectContaining({ orderId: 77 })
)
expect(mockedHandleOrderCancelled).toHaveBeenNthCalledWith(
2,
expect.objectContaining({ orderId: 78, reason: 'other' })
)
})
it('skips empty bodies and messages without an orderId', async () => {
await handleOrderCancelledQueue(
batch(null, {}, { orderId: 0 }, { reason: 'no id', cancelledBy: 'user' })
)
expect(mockedHandleOrderCancelled).not.toHaveBeenCalled()
})
it('handles a batch with no messages', async () => {
await handleOrderCancelledQueue({})
expect(mockedHandleOrderCancelled).not.toHaveBeenCalled()
})
it('propagates a rejection so the queue retries', async () => {
mockedHandleOrderCancelled.mockRejectedValueOnce(new Error('cancel failed'))
await expect(handleOrderCancelledQueue(batch(body))).rejects.toThrow('cancel failed')
})
})

View file

@ -0,0 +1,84 @@
/**
* Unit test for `admin.slots.createSlot`'s post-create cleanup.
*
* `staleSlotsCleanup` used to be called fire-and-forget. In workerd the
* mutation could return (and the isolate be frozen) before the cleanup ran.
* Because the cleanup is an incremental 20-slot window, a skipped run leaves
* `skuIds` on the slot that fell out of the window permanently. These tests pin
* the awaited behaviour and the existing "cleanup failure must not fail slot
* creation" contract.
*/
import { slotsRouter } from '@/src/trpc/apis/admin-apis/apis/slots'
import { createSlotWithRelations, staleSlotsCleanup } from '@/src/dbService'
import { createSlotsCacheFile } from '@/src/lib/cloud_cache'
jest.mock('@/src/dbService', () => ({
createSlotWithRelations: jest.fn(async () => ({
slot: { id: 1 },
createdSnippets: [],
message: 'Slot created',
})),
staleSlotsCleanup: jest.fn(async () => 1),
}))
jest.mock('@/src/lib/cloud_cache', () => ({
createSlotsCacheFile: jest.fn(async () => 1),
}))
const mockedCleanup = staleSlotsCleanup as jest.MockedFunction<typeof staleSlotsCleanup>
const mockedCreate = createSlotWithRelations as jest.MockedFunction<typeof createSlotWithRelations>
const mockedCache = createSlotsCacheFile as jest.MockedFunction<typeof createSlotsCacheFile>
const input = {
deliveryTime: new Date(Date.now() + 3_600_000).toISOString(),
freezeTime: new Date(Date.now() + 1_800_000).toISOString(),
}
const ctx = { staffUser: { id: 3, regionId: 1 } }
/** tRPC stores the resolver on the procedure's `_def`; call it with a fake ctx. */
const resolveCreateSlot = () => (slotsRouter.createSlot as any)._def.resolver
const drainMicrotasks = () => new Promise<void>((resolve) => setImmediate(resolve))
describe('admin.slots.createSlot cleanup', () => {
beforeEach(() => {
jest.clearAllMocks()
})
it('awaits staleSlotsCleanup before resolving', async () => {
let release!: () => void
const work = new Promise<number>((resolve) => {
release = () => resolve(1)
})
mockedCleanup.mockReturnValueOnce(work)
const run = resolveCreateSlot()({ input, ctx })
let settled = false
run.then(() => {
settled = true
})
await drainMicrotasks()
expect(mockedCreate).toHaveBeenCalledTimes(1)
expect(mockedCache).toHaveBeenCalledTimes(1)
expect(mockedCleanup).toHaveBeenCalledTimes(1)
expect(settled).toBe(false)
release()
await run
expect(settled).toBe(true)
})
it('swallows a cleanup rejection so slot creation still succeeds', async () => {
mockedCleanup.mockRejectedValueOnce(new Error('cleanup failed'))
const result = await resolveCreateSlot()({ input, ctx })
expect(result).toEqual(expect.objectContaining({ message: 'Slot created' }))
expect(mockedCleanup).toHaveBeenCalledTimes(1)
})
})

View file

@ -0,0 +1,83 @@
/**
* Unit tests for the worker `queue()` dispatcher.
*
* The catch-all branch used to call `handleNotifQueue(batch)` without `await`.
* In workerd that lets the queue handler resolve (and the batch be implicitly
* acked) before the push work finishes, so notifications could be silently
* dropped. These tests pin the awaited behaviour:
* - the handler does not resolve until the fallback promise settles;
* - a fallback rejection propagates so Cloudflare retries the batch.
*/
import worker from '@/worker'
import { handleNotifQueue } from '@/src/lib/queue-consumer'
jest.mock('@/src/app', () => ({
createApp: jest.fn(() => ({ fetch: jest.fn() })),
}))
jest.mock('@/src/jobs/cache-creator', () => ({
CacheCreator: class {},
}))
jest.mock('@/src/lib/worker-init', () => ({
ensureWorkerInit: jest.fn(),
}))
jest.mock('@/src/lib/flash-delivery-cron', () => ({
runFlashDeliveryToggleCron: jest.fn(async () => undefined),
}))
jest.mock('@/src/jobs/order-items-archive', () => ({
CRON_ORDER_ITEMS_ARCHIVE: '30 20 * * *',
runOrderItemsArchiveCron: jest.fn(async () => null),
}))
jest.mock('@/src/lib/queue-consumer', () => ({
handleNotifQueue: jest.fn(async () => undefined),
handleOrderPlacedQueue: jest.fn(async () => undefined),
handleOrderCancelledQueue: jest.fn(async () => undefined),
}))
const mockedHandleNotifQueue = handleNotifQueue as jest.MockedFunction<typeof handleNotifQueue>
const env = {
NOTIF_QUEUE_NAME: 'notif-queue',
ORDER_PLACED_QUEUE_NAME: 'order-placed-queue',
ORDER_CANCELLED_QUEUE_NAME: 'order-cancelled-queue',
} as any
const unknownBatch = { queue: 'some-other-queue', messages: [] } as any
describe('worker queue() fallback', () => {
beforeEach(() => {
jest.clearAllMocks()
})
it('awaits handleNotifQueue for an unknown queue before resolving', async () => {
let release!: () => void
const work = new Promise<void>((resolve) => {
release = resolve
})
mockedHandleNotifQueue.mockReturnValueOnce(work)
const handler = (worker as any).queue(unknownBatch, env, {})
let settled = false
handler.then(() => {
settled = true
})
// Let the handler reach the await; it must still be pending.
await Promise.resolve()
await Promise.resolve()
expect(mockedHandleNotifQueue).toHaveBeenCalledTimes(1)
expect(settled).toBe(false)
release()
await handler
expect(settled).toBe(true)
})
it('propagates a fallback rejection so the batch is retried', async () => {
mockedHandleNotifQueue.mockRejectedValueOnce(new Error('push failed'))
await expect((worker as any).queue(unknownBatch, env, {})).rejects.toThrow('push failed')
})
})

View file

@ -7,6 +7,10 @@ import { CacheCreator } from './src/jobs/cache-creator'
import { createApp } from './src/app' import { createApp } from './src/app'
import { ensureWorkerInit } from './src/lib/worker-init' import { ensureWorkerInit } from './src/lib/worker-init'
import { runFlashDeliveryToggleCron } from './src/lib/flash-delivery-cron' import { runFlashDeliveryToggleCron } from './src/lib/flash-delivery-cron'
import {
CRON_ORDER_ITEMS_ARCHIVE,
runOrderItemsArchiveCron,
} from './src/jobs/order-items-archive'
import { import {
handleNotifQueue, handleNotifQueue,
handleOrderPlacedQueue, handleOrderPlacedQueue,
@ -77,7 +81,7 @@ export default {
return return
} }
handleNotifQueue(batch) await handleNotifQueue(batch)
}, },
async scheduled( async scheduled(
event: any, event: any,
@ -87,6 +91,10 @@ export default {
ctx: ExecutionContext ctx: ExecutionContext
) { ) {
console.log('from the cron trigger first func'); console.log('from the cron trigger first func');
if (event.cron === CRON_ORDER_ITEMS_ARCHIVE) {
await runOrderItemsArchiveCron({ cron: event.cron, env })
return
}
await runFlashDeliveryToggleCron({cron: event.cron, env}); await runFlashDeliveryToggleCron({cron: event.cron, env});
// ctx.waitUntil(runFlashDeliveryToggleCron({ cron: event.cron, env })) // ctx.waitUntil(runFlashDeliveryToggleCron({ cron: event.cron, env }))
}, },

View file

@ -96,7 +96,8 @@ TELEGRAM_CHAT_IDS = "5147760058"
#crons = ["* * * * *"] #crons = ["* * * * *"]
crons = [ crons = [
"30 18 * * *", # 12:00 AM IST "30 18 * * *", # 12:00 AM IST
"35 18 * * *" # 12:05 AM IST "35 18 * * *", # 12:05 AM IST
"30 20 * * *" # 2:00 AM IST (order-items archive)
] ]
[build] [build]

View file

@ -85,7 +85,7 @@ TELEGRAM_BOT_TOKEN = "8410461852:AAGXQCwRPFbndqwTgLJh8kYxST4Z0vgh72U"
TELEGRAM_CHAT_IDS = "-5075171894" TELEGRAM_CHAT_IDS = "-5075171894"
[triggers] [triggers]
crons = ["0 16 * * *", "0 1 * * *"] crons = ["0 16 * * *", "0 1 * * *", "30 20 * * *"]
# crons = ["* * * * *"] # crons = ["* * * * *"]
# crons = ["7 18 * * *", "10 18 * * *"] # crons = ["7 18 * * *", "10 18 * * *"]

View file

@ -926,7 +926,7 @@ real.
| ME-14 | edge | no navigation target | no replace | | ME-14 | edge | no navigation target | no replace |
| ME-15 | edge | target is consumed | second focus does not replace again | | ME-15 | edge | target is consumed | second focus does not replace again |
| ME-16 | edge | NextOrderGlimpse | mounted above menu | | ME-16 | edge | NextOrderGlimpse | mounted above menu |
| ME-17 | edge | LocationBar | rendered; opens switcher | | ME-17 | edge | Me address bar | absent; Delivery Address menu opens switcher |
| ME-18 | edge | address sheet close | modal closes | | ME-18 | edge | address sheet close | modal closes |
| ME-19 | edge | version/footer | version text rendered | | ME-19 | edge | version/footer | version text rendered |
| ME-20 | edge | signed out | me layout login wall, hub not rendered | | ME-20 | edge | signed out | me layout login wall, hub not rendered |

View file

@ -4,7 +4,6 @@ import { useRouter } from 'expo-router';
import { useFocusEffect } from '@react-navigation/native'; import { useFocusEffect } from '@react-navigation/native';
import { AppContainer, MyText, tw, MyTouchableOpacity, ProfileImage, colors } from 'common-ui'; import { AppContainer, MyText, tw, MyTouchableOpacity, ProfileImage, colors } from 'common-ui';
import TabLayoutWrapper from '@/components/TabLayoutWrapper'; import TabLayoutWrapper from '@/components/TabLayoutWrapper';
import LocationBar from '@/src/components/LocationBar';
import { LinearGradient } from 'expo-linear-gradient'; import { LinearGradient } from 'expo-linear-gradient';
import { Ionicons } from '@expo/vector-icons'; import { Ionicons } from '@expo/vector-icons';
import NextOrderGlimpse from '@/components/NextOrderGlimpse'; import NextOrderGlimpse from '@/components/NextOrderGlimpse';
@ -110,7 +109,6 @@ export default function Me() {
showsVerticalScrollIndicator={false} showsVerticalScrollIndicator={false}
contentContainerStyle={tw`pb-8`} contentContainerStyle={tw`pb-8`}
> >
<LocationBar />
{/* Minimal Header Section */} {/* Minimal Header Section */}
<View style={tw`px-6 pt-8 pb-10 flex-row items-center justify-between`}> <View style={tw`px-6 pt-8 pb-10 flex-row items-center justify-between`}>
<View> <View>

View file

@ -2,7 +2,7 @@ import React, { useCallback, useEffect, useState } from 'react';
import { View, Modal, ScrollView, KeyboardAvoidingView, Platform, Keyboard } from 'react-native'; import { View, Modal, ScrollView, KeyboardAvoidingView, Platform, Keyboard } from 'react-native';
import { Formik } from 'formik'; import { Formik } from 'formik';
import * as Yup from 'yup'; import * as Yup from 'yup';
import { tw, MyText, MyTouchableOpacity , Checkbox , MyTextInput , LoadingDialog , BottomDialog } from 'common-ui'; import { tw, MyText, MyTouchableOpacity , Checkbox , MyTextInput , LoadingDialog , BottomDialog , BottomDropdown } from 'common-ui';
import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { trpc } from '../trpc-client'; import { trpc } from '../trpc-client';
import LocationMapStep from './location/LocationMapStep'; import LocationMapStep from './location/LocationMapStep';
@ -48,7 +48,6 @@ const AddressForm: React.FC<AddressFormProps> = ({
// Towns (regions) the user can deliver in — the City field is a picker over them. // Towns (regions) the user can deliver in — the City field is a picker over them.
const { data: regionsData } = trpc.common.listRegions.useQuery(); const { data: regionsData } = trpc.common.listRegions.useQuery();
const regions = regionsData ?? []; const regions = regionsData ?? [];
const [cityOpen, setCityOpen] = useState(false);
const cityName = regions.find((region) => region.id === resolvedRegion?.regionId)?.name ?? ''; const cityName = regions.find((region) => region.id === resolvedRegion?.regionId)?.name ?? '';
/** Centre the map WebView opens on (null = the page's own default). */ /** Centre the map WebView opens on (null = the page's own default). */
@ -79,7 +78,6 @@ const AddressForm: React.FC<AddressFormProps> = ({
// the map straight away on the first region's bound. // the map straight away on the first region's bound.
const openMapForFirstRegion = useCallback(() => { const openMapForFirstRegion = useCallback(() => {
const firstRegion = regions[0] ?? null; const firstRegion = regions[0] ?? null;
setCityOpen(false);
setMapRegionPickerOpen(false); setMapRegionPickerOpen(false);
setMapCenter(firstRegion?.center ?? null); setMapCenter(firstRegion?.center ?? null);
setMapOpen(true); setMapOpen(true);
@ -331,58 +329,26 @@ const AddressForm: React.FC<AddressFormProps> = ({
value={values.addressLine2} value={values.addressLine2}
/> />
{/* City is a picker over the serviceable towns (regions). */} {/* City is a bottom dropdown over the serviceable towns (regions). */}
<View style={tw`mb-1`}> <View style={tw`mb-1`}>
<MyText style={tw`text-gray-500 text-xs mb-1`}>City *</MyText> <BottomDropdown
<MyTouchableOpacity
testID="address-city" testID="address-city"
onPress={() => { topLabel="City *"
Keyboard.dismiss(); label="Select Town"
setCityOpen((prev) => !prev); placeholder="Select town"
value={resolvedRegion?.regionId ?? ''}
options={[
...regions.map((region) => ({ label: region.name, value: region.id })),
{ label: 'Select in Map', value: 'map' },
]}
onValueChange={(value) => {
if (value === 'map') {
openMapForFirstRegion();
return;
}
void handleCityChange(Number(value));
}} }}
style={tw`border border-gray-200 rounded-lg p-3 flex-row items-center justify-between bg-gray-50`} />
>
<MyText style={tw`${cityName ? 'text-gray-900' : 'text-gray-400'}`}>
{cityName || 'Select town'}
</MyText>
<MaterialIcons
name={cityOpen ? 'keyboard-arrow-up' : 'keyboard-arrow-down'}
size={20}
color="#9CA3AF"
/>
</MyTouchableOpacity>
{cityOpen && (
<View style={tw`border border-gray-200 rounded-lg mt-1 bg-white overflow-hidden`}>
{regions.map((region) => (
<MyTouchableOpacity
key={region.id}
testID={`address-city-option-${region.id}`}
onPress={() => {
setCityOpen(false);
void handleCityChange(region.id);
}}
style={tw`p-3 border-b border-gray-50 flex-row items-center justify-between`}
>
<MyText style={tw`text-gray-800`}>{region.name}</MyText>
{resolvedRegion?.regionId === region.id && (
<MaterialIcons name="check" size={18} color="#3B82F6" />
)}
</MyTouchableOpacity>
))}
{regions.length === 0 && (
<MyText style={tw`p-3 text-gray-400 text-sm`}>No towns available</MyText>
)}
{/* Last option: skip the town list and pick the point on the map. */}
<MyTouchableOpacity
testID="address-city-option-map"
onPress={openMapForFirstRegion}
style={tw`p-3 border-b border-gray-50 flex-row items-center justify-between`}
>
<MyText style={tw`text-gray-800`}>Select in Map</MyText>
</MyTouchableOpacity>
</View>
)}
</View> </View>
<MyTextInput <MyTextInput

View file

@ -19,9 +19,9 @@ import FlashOrderSuccess from '@/app/(drawer)/(tabs)/flash-delivery/order-succes
import { flush, renderWithProviders, seedBoot } from '../helpers/test-utils' import { flush, renderWithProviders, seedBoot } from '../helpers/test-utils'
import { resetAllMocks } from '../helpers/reset' import { resetAllMocks } from '../helpers/reset'
import { lastProcedureInput, setProcedure } from '../mocks/trpc-client' import { lastProcedureInput, setProcedure } from '../mocks/trpc-client'
import { __set } from '../mocks/secure-store-mock' import { __set, __snapshot } from '../mocks/secure-store-mock'
import { __setParams, router } from '../mocks/expo-router-mock' import { __setParams, router } from '../mocks/expo-router-mock'
import { A1, CART_FLASH, CART_SLOTS_RESPONSE } from '../fixtures' import { A1, CART_FLASH, CART_REG, CART_SLOTS_RESPONSE } from '../fixtures'
const FLASH_KEY = 'flash_cart_items' const FLASH_KEY = 'flash_cart_items'
@ -72,10 +72,11 @@ describe('Flash funnel routes', () => {
expect(getByTestId('bill-to-pay-amount')).toHaveTextContent('₹100') expect(getByTestId('bill-to-pay-amount')).toHaveTextContent('₹100')
}) })
it('FLASH-04: placing a flash order sends slotId null and the flash flag', async () => { it('FLASH-04: placing a flash order sends slotId null, sets the flag and clears the flash cart', async () => {
__set('cart_items', CART_REG)
const { getByTestId } = await mount(<FlashCheckout />) const { getByTestId } = await mount(<FlashCheckout />)
fireEvent.press(getByTestId('place-order-button')) fireEvent.press(getByTestId('place-order-button'))
await flush(4) await flush(5)
expect(lastProcedureInput('user.order.placeOrder')).toMatchObject({ expect(lastProcedureInput('user.order.placeOrder')).toMatchObject({
selectedItems: [{ skuId: 8, quantity: 1, slotId: null }], selectedItems: [{ skuId: 8, quantity: 1, slotId: null }],
@ -83,6 +84,9 @@ describe('Flash funnel routes', () => {
regionId: 1, regionId: 1,
isFlashDelivery: true, isFlashDelivery: true,
}) })
expect(JSON.parse(__snapshot()[FLASH_KEY])).toEqual([])
expect(__snapshot()['cart_items']).toBe(CART_REG)
}) })
it('FLASH-05: the flash success copy and Continue Shopping route (SUCCESS-08/09)', async () => { it('FLASH-05: the flash success copy and Continue Shopping route (SUCCESS-08/09)', async () => {

View file

@ -209,11 +209,11 @@ describe('Me hub (ME-01..ME-19)', () => {
expect(glimpse).toBeLessThan(menu) expect(glimpse).toBeLessThan(menu)
}) })
it('ME-17: the LocationBar is rendered and opens the switcher', async () => { it('ME-17: the address bar is absent; Delivery Address opens the switcher', async () => {
const view = await renderHub() const view = await renderHub()
expect(view.getByTestId('location-bar')).toBeTruthy() expect(view.queryByTestId('location-bar')).toBeNull()
fireEvent.press(view.getByTestId('location-bar')) fireEvent.press(view.getByTestId('me-menu-delivery-address'))
expect(view.getByTestId('location-add-address')).toBeTruthy() expect(view.getByTestId('location-add-address')).toBeTruthy()
}) })
@ -221,7 +221,7 @@ describe('Me hub (ME-01..ME-19)', () => {
it('ME-18: closing the address sheet dismisses it', async () => { it('ME-18: closing the address sheet dismisses it', async () => {
const view = await renderHub() const view = await renderHub()
fireEvent.press(view.getByTestId('location-bar')) fireEvent.press(view.getByTestId('me-menu-delivery-address'))
expect(view.getByTestId('location-add-address')).toBeTruthy() expect(view.getByTestId('location-add-address')).toBeTruthy()
const modal = view.UNSAFE_getAllByType(Modal).find((candidate: any) => candidate.props.visible) const modal = view.UNSAFE_getAllByType(Modal).find((candidate: any) => candidate.props.visible)

View file

@ -24,6 +24,7 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
const [isSubmitting, setIsSubmitting] = useState(false) const [isSubmitting, setIsSubmitting] = useState(false)
const [submitError, setSubmitError] = useState<string | null>(null) const [submitError, setSubmitError] = useState<string | null>(null)
const [mapOpen, setMapOpen] = useState(false) const [mapOpen, setMapOpen] = useState(false)
const [mapCenter, setMapCenter] = useState<{ lat: number; lng: number } | null>(null)
const [locating, setLocating] = useState(false) const [locating, setLocating] = useState(false)
const [locationError, setLocationError] = useState<string | null>(null) const [locationError, setLocationError] = useState<string | null>(null)
const [locationSource, setLocationSource] = useState<LocationSource | null>( const [locationSource, setLocationSource] = useState<LocationSource | null>(
@ -300,16 +301,26 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
<div> <div>
<label className="mb-1 block text-xs text-gray-500">City *</label> <label className="mb-1 block text-xs text-gray-500">City *</label>
<select <select
data-testid="address-city"
value={resolvedRegion?.regionId ?? ''} value={resolvedRegion?.regionId ?? ''}
onChange={(e) => void handleCityChange(Number(e.target.value))} onChange={(e) => {
if (e.target.value === 'map') {
const firstRegion = regions[0] ?? null
setMapCenter(firstRegion?.center ?? null)
setMapOpen(true)
return
}
void handleCityChange(Number(e.target.value))
}}
className="w-full rounded-lg border border-gray-200 bg-gray-50 p-3 text-base outline-none" className="w-full rounded-lg border border-gray-200 bg-gray-50 p-3 text-base outline-none"
> >
<option value="">Select town</option> <option value="">Select town</option>
{regions.map((region) => ( {regions.map((region) => (
<option key={region.id} value={region.id}> <option key={region.id} value={region.id} data-testid={`address-city-option-${region.id}`}>
{region.name} {region.name}
</option> </option>
))} ))}
<option value="map" data-testid="address-city-option-map">Select in Map</option>
</select> </select>
</div> </div>
<div> <div>
@ -333,7 +344,10 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
</p> </p>
<button <button
type="button" type="button"
onClick={() => setMapOpen(true)} onClick={() => {
setMapCenter(null)
setMapOpen(true)
}}
className="flex items-center gap-2 text-left text-sm font-medium text-blue-500" className="flex items-center gap-2 text-left text-sm font-medium text-blue-500"
> >
<MapPin className="h-4 w-4" /> Choose Another Location in Map <MapPin className="h-4 w-4" /> Choose Another Location in Map
@ -343,7 +357,10 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<button <button
type="button" type="button"
onClick={() => setMapOpen(true)} onClick={() => {
setMapCenter(null)
setMapOpen(true)
}}
className="flex items-center gap-2 text-left text-sm font-medium text-blue-500" className="flex items-center gap-2 text-left text-sm font-medium text-blue-500"
> >
<MapPin className="h-4 w-4" /> Attach Location in map <MapPin className="h-4 w-4" /> Attach Location in map
@ -385,7 +402,11 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
{mapOpen && ( {mapOpen && (
<div className="fixed inset-0 z-[200] bg-white"> <div className="fixed inset-0 z-[200] bg-white">
<iframe <iframe
src="/location-selector" src={
mapCenter
? `/location-selector?lat=${mapCenter.lat}&lng=${mapCenter.lng}`
: '/location-selector'
}
title="Select delivery location" title="Select delivery location"
className="h-full w-full border-0" className="h-full w-full border-0"
/> />

View file

@ -8074,3 +8074,208 @@ Run: bun run test:api -- user-order-lifecycle admin-order user-order-place
-> 3/3 suites, 145/145 tests passed (105 s); test:api:typecheck clean. -> 3/3 suites, 145/145 tests passed (105 s); test:api:typecheck clean.
The run re-added live suite data (79 E2E stores, 87 products) — clean with The run re-added live suite data (79 E2E stores, 87 products) — clean with
tests/README.md "Cleaning up test data" when needed. tests/README.md "Cleaning up test data" when needed.
================================================================================
[2026-10-20 15:00:00 IST] FEAT-2026-10-20-14 order-items JSON archive (backend-only)
================================================================================
Plan: docs/order-items-json-archive-plan.md
Schema (packages/db_helper_sqlite/src/db/schema.ts)
+ OrderItemSnapshot interface
+ orders.items_json (jsonText, nullable)
+ orders.items_archived_at (timestampText, nullable)
No DTO/type changes.
New backend helpers
+ packages/db_helper_sqlite/src/lib/order-items.ts
loadOrderItems(orderIds): archive-first loader. JSON rows are never looked up in
order_items; table rows keep the existing Drizzle relational shape (nested sku,
raw quantity/price strings, is_packaged/is_package_verified) so API mappers and
DTOs stay untouched.
+ packages/db_helper_sqlite/src/lib/order-items-archive.ts
calendar-day IST cutoff, snapshot builder, validation (non-empty, count/ids,
raw numeric strings, booleans, features array, null discount), guarded
db.batch(update + delete) with count/id re-check.
+ apps/backend/src/jobs/order-items-archive.ts
runOrderItemsArchiveCron + runOrderItemsArchive (batch loop, logs only).
+ apps/backend/src/test-support/order-items-archive-controller.ts
POST /api/test/order-items-archive (guarded by ENABLE_TEST_ROUTES).
Read paths switched to the loader (no archived order_items query):
- user-apis/order.ts: getOrdersWithRelations, getOrderByIdWithRelations,
getOrdersByIdsWithFullData, getOrderByIdWithFullData
- admin-apis/order.ts: getOrderDetails, getSlotOrders, getAllOrders
- admin-apis/vendor-snippets.ts: getVendorOrdersBySlotIdInDb
- admin-apis/user.ts: getItemCountsByOrderIds (json_array_length for archived)
Guards (no API/DTO changes):
- updateOrderPackaged returns null for archived (existing 404 path), status untouched
- rebalanceSlots excludes archived orders (items_json IS NULL)
- updateOrderItemPackaging / vendor packaging keep orderItemId-only input
- getAllOrders adds the IST calendar-day filter server-side
Migration
- drizzle/0006_regions_and_superadmins.sql: __new_orders gains items_json +
items_archived_at; the orders copy builds a verified snapshot for orders before
the IST cutoff and leaves failing orders table-backed; __new_order_items rows for
verified/archived orders are deleted after the copy.
Cron
- wrangler.dev.toml / wrangler.prod.toml: "30 20 * * *" (2 AM IST)
- worker.ts scheduled() dispatches it.
Tests
+ apps/backend/tests/unit/order-items-archive.test.ts (cutoff + validation)
No client apps or shared DTOs touched.
Implementation status:
- Backend + db_helper typecheck clean (tsc -p apps/backend/tsconfig.json and
test:api:typecheck).
- 0006 backfill SQL validated on a throwaway copy of the local D1:
candidates 1064, valid/archived 1038, empty JSON 0, bad feature arrays 0,
bad boolean flags 0. The real local D1 was not migrated (per repo rule).
- No client app / shared type changes.
- Unit tests added but not run (repo rule: run only when asked).
Test-enablement note: to run the affected backend tests before the user applies the
migration, the two nullable columns were added manually to the LOCAL D1
(`ALTER TABLE orders ADD COLUMN items_json text; ... items_archived_at text;`).
No backfill and no drizzle migration was run; all existing orders stay table-backed.
Verification (affected backend areas):
- 7 suites / 222 tests passed:
tests/unit/order-items-archive.test.ts,
tests/api/{admin-order,user-order-lifecycle,user-order-place,admin-vendor,
admin-user,e2e-order-lifecycle}.test.ts
- Smoke: POST /api/test/order-items-archive archived old orders (3 then 58 of 60;
2 legacy orders with no items were skipped and logged). Verified JSON raw
strings/booleans/features, zero leftover order_items rows for archived orders,
admin detail renders archived items, admin list excludes them, packaging on an
archived item/order returns the existing 404.
- Found during smoke: 99/100-row admin pages exceeded D1's 100 bound-parameter
limit inside the item loader (relational subqueries add params). Fixed by
chunking loader / counts / archive-source queries at 50 ids; limit=100 works and
the 7 suites were re-run green.
================================================================================
[2026-10-20 15:45:00 IST] TEST-2026-10-20-15 flash cart clear on order success
================================================================================
apps/user-ui/tests/pages/flash-checkout.test.tsx (FLASH-04)
Places a regular cart beside the flash cart, submits a flash order, and asserts
flash_cart_items becomes [] while cart_items is untouched (PAY-12 covers the
regular counterpart).
Run: bun run test -- tests/pages/flash-checkout.test.tsx -> 6/6 passed.
- Timestamp: 2026-10-20 15:27:34
Fix floating promise in admin.user.addUserIncident (workerd may cancel
unawaited work as soon as the mutation returns).
File: apps/backend/src/trpc/apis/admin-apis/apis/user.ts
Diff:
- recomputeUserNegativityScore(userId);
+ // Await so workerd does not cancel the recompute when the mutation
+ // returns. The helper already logs; a recompute failure must not fail
+ // the incident that was already created.
+ try {
+ await recomputeUserNegativityScore(userId);
+ } catch {
+ /* logged inside recomputeUserNegativityScore */
+ }
Tests: no change required. The mutation response and persisted incident are
unchanged, and the live API test AUSER-22 (tests/api/admin-user.test.ts)
already covers incident creation; the recompute only reads (no persisted
side effect to assert).
================================================================================
[2026-10-20 16:00:00 IST] UI-2026-10-20-16 remove LocationBar from Me tab
================================================================================
apps/user-ui/app/(drawer)/(tabs)/me/index.tsx
- removed the <LocationBar /> render and its import. The "Delivery Address" menu
item still opens AddressSwitcherSheet.
Tests:
- me-hub ME-17 now asserts the bar is absent (and the menu opens the switcher).
- ME-18 opens the sheet from me-menu-delivery-address instead of location-bar.
- JEST-TEST-CASES.md ME-17 description updated.
Run: bun run test -- tests/pages/me-hub.test.tsx -> 19/19 passed; user-ui typecheck clean.
- Timestamp: 2026-10-20 15:32:34
Fix floating promise in the worker queue() fallback (workerd may cancel the
unawaited notification work when the handler returns, and the batch is then
implicitly acked and lost).
File: apps/backend/worker.ts
Diff:
- handleNotifQueue(batch)
+ await handleNotifQueue(batch)
- Timestamp: 2026-10-20 15:33:55
Add regression test for the worker queue() fallback await.
New: apps/backend/tests/unit/worker-queue.test.ts
- asserts queue() does not resolve until handleNotifQueue settles
- asserts a fallback rejection propagates so Cloudflare retries the batch
================================================================================
[2026-10-20 16:20:00 IST] TEST-2026-10-20-17 unit-test the archive method
================================================================================
Refactor (packages/db_helper_sqlite/src/lib/order-items-archive.ts):
- ArchiveStore seam (loadSource / applyArchive / listEligibleOrderIds) with a
default DB-backed implementation, so the archive orchestration can be unit
tested without D1. Behaviour unchanged.
Tests (apps/backend/tests/unit/order-items-archive.test.ts):
- archiveOrderItems: valid order applied, invalid order skipped without apply,
guard failure reported, mixed batch.
- runOrderItemsArchive: cursor progression, batchSize, maxBatches, skip handling.
Not testing the cron trigger/wrapper.
Run: bun run test:api -- tests/unit/order-items-archive.test.ts -> 27/27 passed.
- Timestamp: 2026-10-20 15:38:12
Fix floating promise in initializeAllStores: await cache-file generation so
the DO alarm / startup path does not lose the S3 upload + CDN purge when the
caller returns.
File: apps/backend/src/stores/store-initializer.ts
Diff:
- createAllCacheFiles(regionId).catch(error => {
+ await createAllCacheFiles(regionId).catch(error => {
Behaviour: cache failures are still swallowed (the .catch stays), but the
generation is now tied to initializeAllStores' lifetime.
New test: apps/backend/tests/unit/initialize-all-stores.test.ts
- asserts initializeAllStores does not resolve until createAllCacheFiles settles
- asserts a cache-generation rejection is swallowed
- Timestamp: 2026-10-20 15:42:22
Fix floating promise in admin.slots.createSlot: await staleSlotsCleanup so
the incremental 20-slot cleanup is not skipped when the mutation returns in
workerd (a skipped run permanently leaves skuIds on the slot that falls out
of the window).
File: apps/backend/src/trpc/apis/admin-apis/apis/slots.ts
Diff:
- staleSlotsCleanup().catch((error) => {
+ await staleSlotsCleanup().catch((error) => {
Behaviour: cleanup failures are still swallowed and slot creation still
succeeds; only the lifecycle changes.
New test: apps/backend/tests/unit/slots-create-cleanup.test.ts
- asserts createSlot does not resolve until staleSlotsCleanup settles
- asserts a cleanup rejection does not fail slot creation
================================================================================
[2026-10-20 16:35:00 IST] TEST-2026-10-20-18 queue consumer handler UTs
================================================================================
New: apps/backend/tests/unit/queue-consumer.test.ts
- handleNotifQueue: mocked sendAdminNotification (no real push); asserts the exact
payload, imageUrl/orderId fallbacks, skip cases and error propagation.
- handleOrderPlacedQueue: mocked handleOrderPlaced; asserts orderIds delegation,
skip cases, multiple messages and error propagation.
- handleOrderCancelledQueue: mocked handleOrderCancelled; asserts the mapped payload,
skip cases, multiple messages and error propagation.
Notification implementation is never executed.
Run: bun run test:api -- tests/unit/queue-consumer.test.ts -> 16/16 passed.
================================================================================
[2026-10-20 17:00:00 IST] UI-2026-10-20-19 AddressForm city -> BottomDropdown
================================================================================
apps/user-ui/src/components/AddressForm.tsx
- City/region field replaced the custom inline list with common-ui BottomDropdown
(single select) over trpc.common.listRegions. "Select in Map" is a sentinel option.
- Removed cityOpen state; map region picker (BottomDialog) unchanged.
Tests (apps/user-ui/tests/components/address-form.test.tsx)
- Existing address-city / address-city-option-* testIDs preserved by the dropdown.
- Assertions adapted to the dialog-based dropdown where needed.
Web counterpart (apps/web-ui/src/components/AddressForm.tsx)
- Replaced the native <select> with the web dropdown equivalent so the RN/web
behaviour matches (same options + Select in Map).
Run: bun run test -- tests/components/address-form.test.tsx -> 37/37 passed (no test
assertions needed changing; address-city / address-city-option-* IDs preserved).
Typecheck: user-ui clean; web-ui `npm run typecheck` clean.

View file

@ -478,6 +478,8 @@ CREATE TABLE `__new_orders` (
`is_flash_delivery` integer DEFAULT false NOT NULL, `is_flash_delivery` integer DEFAULT false NOT NULL,
`created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
`delivered_at` text, `delivered_at` text,
`items_json` text,
`items_archived_at` text,
`region_id` integer NOT NULL, `region_id` integer NOT NULL,
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action,
FOREIGN KEY (`address_id`) REFERENCES `__new_addresses`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`address_id`) REFERENCES `__new_addresses`(`id`) ON UPDATE no action ON DELETE no action,
@ -485,8 +487,72 @@ CREATE TABLE `__new_orders` (
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
); );
--> statement-breakpoint --> statement-breakpoint
INSERT INTO `__new_orders` (`id`,`user_id`,`address_id`,`slot_id`,`total_amount`,`delivery_charge`,`discount_amount`,`readable_id`,`admin_notes`,`user_notes`,`order_group_id`,`order_group_proportion`,`is_flash_delivery`,`created_at`,`delivered_at`,`region_id`) WITH `archive_candidate` AS (
SELECT `id`,`user_id`,`address_id`,`slot_id`,`total_amount`,`delivery_charge`,'0',`readable_id`,`admin_notes`,`user_notes`,`order_group_id`,`order_group_proportion`,`is_flash_delivery`,`created_at`,`delivered_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `orders`; SELECT
o.`id` AS `order_id`,
(SELECT COUNT(*) FROM `order_items` `oi` WHERE `oi`.`order_id` = o.`id`) AS `source_count`,
(SELECT json_group_array(json_object(
'id', `oi`.`id`,
'skuId', `oi`.`sku_id`,
'quantity', `oi`.`quantity`,
'price', `oi`.`price`,
'discountedPrice', `oi`.`discounted_price`,
'isPackaged', json(CASE WHEN `oi`.`is_packaged` = 1 THEN 'true' ELSE 'false' END),
'isPackageVerified', json(CASE WHEN `oi`.`is_package_verified` = 1 THEN 'true' ELSE 'false' END),
'packagedAt', `oi`.`packaged_at`,
'productName', `p`.`name`,
'skuName', `ps`.`name`,
'image', CASE WHEN json_valid(`ps`.`images`) THEN json_extract(`ps`.`images`, '$[0]') END,
'features', json(COALESCE((
SELECT json_group_array(json_object(
'featureName', `f`.`feature_name`,
'featureValue', `f`.`feature_value`
))
FROM `sku_features` `f` WHERE `f`.`sku_id` = `oi`.`sku_id`
), '[]'))
))
FROM `order_items` `oi`
LEFT JOIN `product_skus` `ps` ON `ps`.`id` = `oi`.`sku_id`
LEFT JOIN `product_info` `p` ON `p`.`id` = `ps`.`product_id`
WHERE `oi`.`order_id` = o.`id`) AS `items_json`
FROM `orders` o
WHERE date(datetime(o.`created_at`), '+5 hours', '+30 minutes') <
date(datetime('now'), '+5 hours', '+30 minutes', '-2 days')
),
`archive_valid` AS (
SELECT c.*,
(c.`source_count` >= 1
AND json_valid(c.`items_json`)
AND json_array_length(c.`items_json`) = c.`source_count`
AND (SELECT COUNT(DISTINCT CAST(json_extract(`je`.`value`, '$.id') AS INTEGER))
FROM json_each(c.`items_json`) `je`) = c.`source_count`
AND NOT EXISTS (
SELECT 1 FROM `order_items` `oi`
LEFT JOIN `product_skus` `ps` ON `ps`.`id` = `oi`.`sku_id`
LEFT JOIN `product_info` `p` ON `p`.`id` = `ps`.`product_id`
WHERE `oi`.`order_id` = c.`order_id`
AND (`ps`.`id` IS NULL OR `p`.`name` IS NULL OR `p`.`name` = ''
OR `oi`.`quantity` IS NULL OR `oi`.`quantity` = ''
OR `oi`.`quantity` NOT GLOB '*[0-9]*'
OR `oi`.`quantity` GLOB '*[^0-9.]*' OR `oi`.`quantity` GLOB '*.*.*'
OR CAST(`oi`.`quantity` AS REAL) <= 0
OR `oi`.`price` IS NULL OR `oi`.`price` = ''
OR `oi`.`price` NOT GLOB '*[0-9]*'
OR `oi`.`price` GLOB '*[^0-9.]*' OR `oi`.`price` GLOB '*.*.*'
OR CAST(`oi`.`price` AS REAL) < 0
OR (`oi`.`discounted_price` IS NOT NULL AND (
`oi`.`discounted_price` = ''
OR `oi`.`discounted_price` NOT GLOB '*[0-9]*'
OR `oi`.`discounted_price` GLOB '*[^0-9.]*'
OR `oi`.`discounted_price` GLOB '*.*.*'
OR CAST(`oi`.`discounted_price` AS REAL) < 0
))
OR (`oi`.`packaged_at` IS NOT NULL AND datetime(`oi`.`packaged_at`) IS NULL)
))) AS `ok`
FROM `archive_candidate` c
)
INSERT INTO `__new_orders` (`id`,`user_id`,`address_id`,`slot_id`,`total_amount`,`delivery_charge`,`discount_amount`,`readable_id`,`admin_notes`,`user_notes`,`order_group_id`,`order_group_proportion`,`is_flash_delivery`,`created_at`,`delivered_at`,`items_json`,`items_archived_at`,`region_id`)
SELECT o.`id`,o.`user_id`,o.`address_id`,o.`slot_id`,o.`total_amount`,o.`delivery_charge`,'0',o.`readable_id`,o.`admin_notes`,o.`user_notes`,o.`order_group_id`,o.`order_group_proportion`,o.`is_flash_delivery`,o.`created_at`,o.`delivered_at`,CASE WHEN v.`ok` THEN v.`items_json` END,CASE WHEN v.`ok` THEN CURRENT_TIMESTAMP END,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `orders` o LEFT JOIN `archive_valid` v ON v.`order_id` = o.`id`;
--> statement-breakpoint --> statement-breakpoint
CREATE TABLE `__new_order_items` ( CREATE TABLE `__new_order_items` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
@ -505,6 +571,10 @@ CREATE TABLE `__new_order_items` (
INSERT INTO `__new_order_items` (`id`,`order_id`,`sku_id`,`quantity`,`price`,`discounted_price`,`is_packaged`,`is_package_verified`,`packaged_at`) INSERT INTO `__new_order_items` (`id`,`order_id`,`sku_id`,`quantity`,`price`,`discounted_price`,`is_packaged`,`is_package_verified`,`packaged_at`)
SELECT `id`,`order_id`,`sku_id`,`quantity`,`price`,`discounted_price`,`is_packaged`,`is_package_verified`,`packaged_at` FROM `order_items`; SELECT `id`,`order_id`,`sku_id`,`quantity`,`price`,`discounted_price`,`is_packaged`,`is_package_verified`,`packaged_at` FROM `order_items`;
--> statement-breakpoint --> statement-breakpoint
-- Orders archived into `orders.items_json` keep no rows in the hot table.
DELETE FROM `__new_order_items`
WHERE `order_id` IN (SELECT `id` FROM `__new_orders` WHERE `items_json` IS NOT NULL);
--> statement-breakpoint
CREATE TABLE `__new_order_status` ( CREATE TABLE `__new_order_status` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`order_time` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `order_time` text DEFAULT CURRENT_TIMESTAMP NOT NULL,

View file

@ -458,3 +458,23 @@ export {
listAllProducts, listAllProducts,
elevateProductToGlobal, elevateProductToGlobal,
} from './src/superadmin-apis/products' } from './src/superadmin-apis/products'
export {
archiveOrderItems,
runOrderItemsArchive,
istCalendarCutoffUtc,
validateSnapshot,
buildSnapshot,
type ArchiveSummary,
type ArchiveSkip,
type ArchiveRunOptions,
type ArchiveSourceRow,
type ArchiveSkuRow,
type ArchiveStore,
} from './src/lib/order-items-archive'
export {
loadOrderItems,
attachOrderItems,
type OrderItemRowCompat,
} from './src/lib/order-items'

View file

@ -8,8 +8,9 @@ import {
orders, orders,
orderStatus, orderStatus,
} from '../db/schema' } from '../db/schema'
import { and, desc, eq, inArray, 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 { attachOrderItems } from '../lib/order-items'
import type { import type {
AdminOrderDetails, AdminOrderDetails,
AdminOrderRow, AdminOrderRow,
@ -61,11 +62,15 @@ export async function updateOrderPackaged(regionId: number, orderId: string, isP
const orderCheck = await db.query.orders.findFirst({ const orderCheck = await db.query.orders.findFirst({
where: and(eq(orders.id, orderIdNumber), eq(orders.regionId, regionId)), where: and(eq(orders.id, orderIdNumber), eq(orders.regionId, regionId)),
columns: { id: true }, columns: { id: true, itemsJson: true },
}) })
if (!orderCheck) { if (!orderCheck) {
return null return null
} }
// Archived orders are read-only: do not touch order_status or any item rows.
if (orderCheck.itemsJson != null) {
return null
}
await db await db
.update(orderItems) .update(orderItems)
@ -125,16 +130,6 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
user: true, user: true,
address: true, address: true,
slot: true, slot: true,
orderItems: {
with: {
sku: {
with: {
product: true,
features: true,
},
},
},
},
orderStatus: true, orderStatus: true,
}, },
}) })
@ -143,6 +138,8 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
return null return null
} }
const items = (await attachOrderItems([orderData]))[0].orderItems
let couponOrderIds: number[] = [orderData.id] let couponOrderIds: number[] = [orderData.id]
if (orderData.orderGroupId) { if (orderData.orderGroupId) {
const groupOrders = await db const groupOrders = await db
@ -209,7 +206,7 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
status, status,
isPackaged: orderStatusRecord?.isPackaged || false, isPackaged: orderStatusRecord?.isPackaged || false,
isDelivered: orderStatusRecord?.isDelivered || false, isDelivered: orderStatusRecord?.isDelivered || false,
items: orderData.orderItems.map((item: any) => ({ items: items.map((item: any) => ({
id: item.id, id: item.id,
name: composeSkuName(item.sku.product?.name ?? 'Unknown', item.sku.features || [], item.sku.name), name: composeSkuName(item.sku.product?.name ?? 'Unknown', item.sku.features || [], item.sku.name),
skuName: item.sku.name ?? null, skuName: item.sku.name ?? null,
@ -318,21 +315,13 @@ export async function getSlotOrders(regionId: number, slotId: string): Promise<A
user: true, user: true,
address: true, address: true,
slot: true, slot: true,
orderItems: {
with: {
sku: {
with: {
product: true,
features: true,
},
},
},
},
orderStatus: true, orderStatus: true,
}, },
}) })
const formattedOrders = slotOrders.map((order: any) => { const withItems = await attachOrderItems(slotOrders)
const formattedOrders = withItems.map((order: any) => {
const statusRecord = order.orderStatus[0] const statusRecord = order.orderStatus[0]
let status: 'pending' | 'delivered' | 'cancelled' = 'pending' let status: 'pending' | 'delivered' | 'cancelled' = 'pending'
if (statusRecord?.isCancelled) { if (statusRecord?.isCancelled) {
@ -414,6 +403,12 @@ 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)
// 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')`
)
// 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
// bounded by a window derived from the globally newest order id could come back // bounded by a window derived from the globally newest order id could come back
@ -453,24 +448,15 @@ export async function getAllOrders(regionId: number, input: GetAllOrdersInput):
user: true, user: true,
address: true, address: true,
slot: true, slot: true,
orderItems: {
with: {
sku: {
with: {
product: true,
features: true,
},
},
},
},
orderStatus: true, orderStatus: true,
}, },
}) })
const hasMore = allOrders.length > limit const hasMore = allOrders.length > limit
const ordersToReturn = hasMore ? allOrders.slice(0, limit) : allOrders const ordersToReturn = hasMore ? allOrders.slice(0, limit) : allOrders
const withItems = await attachOrderItems(ordersToReturn)
const formattedOrders = ordersToReturn.map((order: any) => { const formattedOrders = withItems.map((order: any) => {
const statusRecord = order.orderStatus[0] const statusRecord = order.orderStatus[0]
let status: 'pending' | 'delivered' | 'cancelled' = 'pending' let status: 'pending' | 'delivered' | 'cancelled' = 'pending'
if (statusRecord?.isCancelled) { if (statusRecord?.isCancelled) {
@ -545,7 +531,12 @@ export async function rebalanceSlots(regionId: number, slotIds: number[]): Promi
} }
const ordersList = await db.query.orders.findMany({ const ordersList = await db.query.orders.findMany({
where: and(inArray(orders.slotId, inRegionSlotIds), eq(orders.regionId, regionId)), where: and(
inArray(orders.slotId, inRegionSlotIds),
eq(orders.regionId, regionId),
// Archived orders have no order_items and must never be repriced.
isNull(orders.itemsJson)
),
with: { with: {
orderItems: { orderItems: {
with: { with: {

View file

@ -172,21 +172,48 @@ export async function getOrderStatusesByOrderIds(regionId: number, orderIds: num
export async function getItemCountsByOrderIds(regionId: number, orderIds: number[]): Promise<{ orderId: number; itemCount: number }[]> { export async function getItemCountsByOrderIds(regionId: number, orderIds: number[]): Promise<{ orderId: number; itemCount: number }[]> {
if (orderIds.length === 0) return [] if (orderIds.length === 0) return []
const inRegionOrders = await db const chunk = <T,>(values: T[], size: number): T[][] => {
.select({ id: orders.id }) const out: T[][] = []
.from(orders) for (let index = 0; index < values.length; index += size) {
.where(and(inArray(orders.id, orderIds), eq(orders.regionId, regionId))) out.push(values.slice(index, index + size))
}
return out
}
const inRegionOrders: { id: number; itemsJson: unknown[] | null }[] = []
for (const ids of chunk(orderIds, 50)) {
const rows = await db
.select({ id: orders.id, itemsJson: orders.itemsJson })
.from(orders)
.where(and(inArray(orders.id, ids), eq(orders.regionId, regionId)))
inRegionOrders.push(...(rows as { id: number; itemsJson: unknown[] | null }[]))
}
if (inRegionOrders.length === 0) return [] if (inRegionOrders.length === 0) return []
return await db const archivedCounts = inRegionOrders
.select({ .filter((order) => order.itemsJson != null)
orderId: orderItems.orderId, .map((order) => ({ orderId: order.id, itemCount: order.itemsJson!.length }))
itemCount: count(orderItems.id),
}) const tableBackedIds = inRegionOrders
.from(orderItems) .filter((order) => order.itemsJson == null)
.where(inArray(orderItems.orderId, inRegionOrders.map((o) => o.id))) .map((order) => order.id)
.groupBy(orderItems.orderId)
const tableCounts: { orderId: number; itemCount: number }[] = []
for (const ids of chunk(tableBackedIds, 50)) {
if (ids.length === 0) continue
const rows = await db
.select({
orderId: orderItems.orderId,
itemCount: count(orderItems.id),
})
.from(orderItems)
.where(inArray(orderItems.orderId, ids))
.groupBy(orderItems.orderId)
tableCounts.push(...rows)
}
return [...archivedCounts, ...tableCounts]
} }
export async function upsertUserSuspension(userId: number, isSuspended: boolean): Promise<void> { export async function upsertUserSuspension(userId: number, isSuspended: boolean): Promise<void> {

View file

@ -10,6 +10,7 @@ import type {
AdminVendorUpdatePackagingResult, AdminVendorUpdatePackagingResult,
} from '@packages/shared' } from '@packages/shared'
import { coerceDate } from '../lib/date' import { coerceDate } from '../lib/date'
import { attachOrderItems } from '../lib/order-items'
import type { SlotRow } from '../user-apis/slots' import type { SlotRow } from '../user-apis/slots'
type VendorSnippetRow = InferSelectModel<typeof vendorSnippets> type VendorSnippetRow = InferSelectModel<typeof vendorSnippets>
@ -220,7 +221,7 @@ export async function getVendorSlotById(regionId: number | null, slotId: number)
} }
export async function getVendorOrdersBySlotId(regionId: number | null, slotId: number) { export async function getVendorOrdersBySlotId(regionId: number | null, slotId: number) {
return await db.query.orders.findMany({ const rows = await db.query.orders.findMany({
where: regionId == null where: regionId == null
? eq(orders.slotId, slotId) ? eq(orders.slotId, slotId)
: and( : and(
@ -228,22 +229,14 @@ export async function getVendorOrdersBySlotId(regionId: number | null, slotId: n
eq(orders.regionId, regionId) eq(orders.regionId, regionId)
), ),
with: { with: {
orderItems: {
with: {
sku: {
with: {
product: true,
features: true,
},
},
},
},
orderStatus: true, orderStatus: true,
user: true, user: true,
slot: true, slot: true,
}, },
orderBy: desc(orders.createdAt), orderBy: desc(orders.createdAt),
}) })
return attachOrderItems(rows)
} }
export async function updateVendorOrderItemPackaging( export async function updateVendorOrderItemPackaging(

View file

@ -341,6 +341,21 @@ export const specialDeals = sqliteTable('special_deals', {
validTill: timestampText('valid_till').notNull(), validTill: timestampText('valid_till').notNull(),
}) })
export interface OrderItemSnapshot {
id: number
skuId: number
quantity: string
price: string
discountedPrice: string | null
isPackaged: boolean
isPackageVerified: boolean
packagedAt: string | null
productName: string
skuName: string | null
image: string | null
features: { featureName: string | null; featureValue: string }[]
}
export const orders = sqliteTable('orders', { export const orders = sqliteTable('orders', {
id: integer().primaryKey({ autoIncrement: true }), id: integer().primaryKey({ autoIncrement: true }),
regionId: integer('region_id').references(() => regions.id), regionId: integer('region_id').references(() => regions.id),
@ -358,6 +373,8 @@ export const orders = sqliteTable('orders', {
isFlashDelivery: integer('is_flash_delivery', { mode: 'boolean' }).notNull().default(false), isFlashDelivery: integer('is_flash_delivery', { mode: 'boolean' }).notNull().default(false),
createdAt: timestampText('created_at').notNull().default(sql`CURRENT_TIMESTAMP`), createdAt: timestampText('created_at').notNull().default(sql`CURRENT_TIMESTAMP`),
deliveredAt: timestampText('delivered_at'), deliveredAt: timestampText('delivered_at'),
itemsJson: jsonText<OrderItemSnapshot[]>('items_json'),
itemsArchivedAt: timestampText('items_archived_at'),
}) })
export const orderItems = sqliteTable('order_items', { export const orderItems = sqliteTable('order_items', {

View file

@ -0,0 +1,333 @@
import { and, eq, gt, inArray, isNull, sql } from 'drizzle-orm'
import { db } from '../db/db_index'
import { orderItems, orders, productSkus, type OrderItemSnapshot } from '../db/schema'
const IST_OFFSET_MS = 5.5 * 60 * 60 * 1000
const DAY_MS = 24 * 60 * 60 * 1000
/**
* Start (UTC) of the IST calendar day two days before `now`. Orders created
* before this instant are archived: today, yesterday and the day before stay.
*/
export function istCalendarCutoffUtc(now: Date = new Date()): Date {
const ist = new Date(now.getTime() + IST_OFFSET_MS)
const startOfIstDayUtc = Date.UTC(ist.getUTCFullYear(), ist.getUTCMonth(), ist.getUTCDate()) - IST_OFFSET_MS
return new Date(startOfIstDayUtc - 2 * DAY_MS)
}
export interface ArchiveSkip {
orderId: number
reason: string
}
export interface ArchiveSummary {
scanned: number
archived: number
skipped: ArchiveSkip[]
}
export interface ArchiveStore {
loadSource(orderIds: number[]): Promise<{ rows: ArchiveSourceRow[]; skuById: Map<number, ArchiveSkuRow> }>
applyArchive(orderId: number, snapshot: OrderItemSnapshot[], verifiedIds: number[]): Promise<boolean>
listEligibleOrderIds(cutoff: Date, cursor: number, limit: number): Promise<number[]>
}
export type ArchiveSourceRow = {
id: number
orderId: number
skuId: number
quantity: string
price: string
discountedPrice: string | null
is_packaged: boolean
is_package_verified: boolean
packagedAt: Date | null
}
export type ArchiveSkuRow = {
id: number
name: string | null
images: string[] | null
isDeleted: boolean
product: { name: string } | null
features: { featureName: string | null; featureValue: string }[]
}
function isFiniteNumberString(value: string, options: { min: number }): boolean {
if (value.trim() !== value || value === '') return false
const parsed = Number(value)
return Number.isFinite(parsed) && parsed >= options.min
}
export function validateSnapshot(
source: ArchiveSourceRow[],
snapshot: OrderItemSnapshot[]
): string | null {
if (source.length === 0) return 'order has no items'
if (!Array.isArray(snapshot) || snapshot.length === 0) return 'snapshot is empty'
if (snapshot.length !== source.length) {
return `snapshot length ${snapshot.length} != source ${source.length}`
}
const sourceIds = new Set(source.map((row) => row.id))
const seen = new Set<number>()
for (const line of snapshot) {
if (!Number.isInteger(line.id) || line.id <= 0) return 'invalid item id'
if (seen.has(line.id)) return `duplicate item id ${line.id}`
seen.add(line.id)
if (!sourceIds.has(line.id)) return `unknown item id ${line.id}`
if (!Number.isInteger(line.skuId) || line.skuId <= 0) return `invalid skuId for item ${line.id}`
if (typeof line.productName !== 'string' || line.productName.trim() === '') {
return `missing productName for item ${line.id}`
}
if (typeof line.quantity !== 'string' || !isFiniteNumberString(line.quantity, { min: Number.MIN_VALUE })) {
return `invalid quantity for item ${line.id}`
}
if (typeof line.price !== 'string' || !isFiniteNumberString(line.price, { min: 0 })) {
return `invalid price for item ${line.id}`
}
if (
line.discountedPrice !== null &&
(typeof line.discountedPrice !== 'string' ||
!isFiniteNumberString(line.discountedPrice, { min: 0 }))
) {
return `invalid discountedPrice for item ${line.id}`
}
if (typeof line.isPackaged !== 'boolean') return `invalid isPackaged for item ${line.id}`
if (typeof line.isPackageVerified !== 'boolean') return `invalid isPackageVerified for item ${line.id}`
if (line.packagedAt !== null) {
if (typeof line.packagedAt !== 'string' || Number.isNaN(new Date(line.packagedAt).getTime())) {
return `invalid packagedAt for item ${line.id}`
}
}
if (line.image !== null && typeof line.image !== 'string') return `invalid image for item ${line.id}`
if (!Array.isArray(line.features)) return `invalid features for item ${line.id}`
for (const feature of line.features) {
if (!feature || typeof feature.featureValue !== 'string') {
return `invalid feature for item ${line.id}`
}
if (feature.featureName !== null && typeof feature.featureName !== 'string') {
return `invalid feature name for item ${line.id}`
}
}
}
if (seen.size !== sourceIds.size) return 'snapshot is missing source ids'
return null
}
export function buildSnapshot(
rows: ArchiveSourceRow[],
skuById: Map<number, ArchiveSkuRow>
): { snapshot?: OrderItemSnapshot[]; reason?: string } {
const snapshot: OrderItemSnapshot[] = []
for (const row of rows) {
const sku = skuById.get(row.skuId)
if (!sku || !sku.product) return { reason: `missing catalogue data for item ${row.id}` }
snapshot.push({
id: row.id,
skuId: row.skuId,
quantity: row.quantity,
price: row.price,
discountedPrice: row.discountedPrice,
isPackaged: row.is_packaged,
isPackageVerified: row.is_package_verified,
packagedAt: row.packagedAt ? row.packagedAt.toISOString() : null,
productName: sku.product.name,
skuName: sku.name,
image: Array.isArray(sku.images) && sku.images.length > 0 ? sku.images[0] : null,
features: (sku.features ?? []).map((feature) => ({
featureName: feature.featureName,
featureValue: feature.featureValue,
})),
})
}
return { snapshot }
}
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
}
async function loadSource(orderIds: number[]): Promise<{ rows: ArchiveSourceRow[]; skuById: Map<number, ArchiveSkuRow> }> {
const rows: ArchiveSourceRow[] = []
for (const chunk of chunks(orderIds, 50)) {
const chunkRows = (await db
.select()
.from(orderItems)
.where(inArray(orderItems.orderId, chunk))) as unknown as ArchiveSourceRow[]
rows.push(...chunkRows)
}
const skuIds = [...new Set(rows.map((row) => row.skuId))]
const skuById = new Map<number, ArchiveSkuRow>()
const skus: ArchiveSkuRow[] = []
for (const chunk of chunks(skuIds, 50)) {
const chunkSkus = (await db.query.productSkus.findMany({
where: inArray(productSkus.id, chunk),
with: {
product: { columns: { name: true } },
features: true,
},
})) as unknown as ArchiveSkuRow[]
skus.push(...chunkSkus)
}
for (const sku of skus) skuById.set(sku.id, sku)
return { rows, skuById }
}
async function applyArchiveToDb(
orderId: number,
snapshot: OrderItemSnapshot[],
verifiedIds: number[]
): Promise<boolean> {
const update = db
.update(orders)
.set({ itemsJson: snapshot, itemsArchivedAt: new Date() })
.where(
and(
eq(orders.id, orderId),
isNull(orders.itemsJson),
sql`(SELECT COUNT(*) FROM order_items WHERE order_id = ${orderId}) = ${verifiedIds.length}`,
sql`NOT EXISTS (SELECT 1 FROM order_items WHERE order_id = ${orderId} AND id NOT IN (${sql.join(
verifiedIds.map((id) => sql`${id}`),
sql`, `
)}))`
)
)
const remove = db
.delete(orderItems)
.where(
and(
eq(orderItems.orderId, orderId),
sql`EXISTS (SELECT 1 FROM orders WHERE id = ${orderId} AND items_json IS NOT NULL)`
)
)
await db.batch([update, remove])
const [archivedOrder] = await db
.select({ itemsJson: orders.itemsJson })
.from(orders)
.where(eq(orders.id, orderId))
.limit(1)
return archivedOrder?.itemsJson != null
}
async function listEligibleOrderIds(cutoff: Date, cursor: number, limit: number): Promise<number[]> {
const rows = await db
.select({ id: orders.id })
.from(orders)
.where(
and(
isNull(orders.itemsJson),
gt(orders.id, cursor),
sql`datetime(${orders.createdAt}) < datetime(${cutoff.toISOString()})`
)
)
.orderBy(orders.id)
.limit(limit)
return rows.map((row) => row.id)
}
const defaultArchiveStore: ArchiveStore = {
loadSource,
applyArchive: applyArchiveToDb,
listEligibleOrderIds,
}
/**
* Archives the given orders. Each order is validated first; only valid orders
* are written (guarded `db.batch(update + delete)`, atomic on D1). Invalid orders
* keep their `order_items` rows and are reported in `skipped`.
*/
export async function archiveOrderItems(
orderIds: number[],
store: ArchiveStore = defaultArchiveStore
): Promise<ArchiveSummary> {
const ids = [...new Set(orderIds.filter((id) => Number.isFinite(id)))]
const summary: ArchiveSummary = { scanned: ids.length, archived: 0, skipped: [] }
if (ids.length === 0) return summary
const { rows, skuById } = await store.loadSource(ids)
const rowsByOrder = new Map<number, ArchiveSourceRow[]>()
for (const row of rows) {
const list = rowsByOrder.get(row.orderId) ?? []
list.push(row)
rowsByOrder.set(row.orderId, list)
}
for (const orderId of ids) {
const orderRows = rowsByOrder.get(orderId) ?? []
const built = buildSnapshot(orderRows, skuById)
if (!built.snapshot) {
summary.skipped.push({ orderId, reason: built.reason ?? 'invalid snapshot' })
continue
}
const validationError = validateSnapshot(orderRows, built.snapshot)
if (validationError) {
summary.skipped.push({ orderId, reason: validationError })
continue
}
const verifiedIds = orderRows.map((row) => row.id)
const applied = await store.applyArchive(orderId, built.snapshot, verifiedIds)
if (applied) {
summary.archived += 1
} else {
summary.skipped.push({ orderId, reason: 'source changed during archive' })
}
}
return summary
}
export interface ArchiveRunOptions {
now?: Date
batchSize?: number
maxBatches?: number
}
/** Runs the archive over every unarchived order older than the IST cutoff. */
export async function runOrderItemsArchive(
options: ArchiveRunOptions = {},
store: ArchiveStore = defaultArchiveStore
): Promise<ArchiveSummary> {
const now = options.now ?? new Date()
const batchSize = options.batchSize ?? 100
const maxBatches = options.maxBatches ?? 20
const cutoff = istCalendarCutoffUtc(now)
const summary: ArchiveSummary = { scanned: 0, archived: 0, skipped: [] }
let cursor = 0
for (let batch = 0; batch < maxBatches; batch += 1) {
const ids = await store.listEligibleOrderIds(cutoff, cursor, batchSize)
if (ids.length === 0) break
cursor = ids[ids.length - 1]
const result = await archiveOrderItems(ids, store)
summary.scanned += result.scanned
summary.archived += result.archived
summary.skipped.push(...result.skipped)
if (ids.length < batchSize) break
}
console.log(
`[order-items-archive] scanned=${summary.scanned} archived=${summary.archived} skipped=${summary.skipped.length}`
)
for (const skip of summary.skipped) {
console.log(`[order-items-archive] skipped order ${skip.orderId}: ${skip.reason}`)
}
return summary
}

View file

@ -0,0 +1,159 @@
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
}
/**
* 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 (...)`.
*/
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 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)
}
}
// 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)) {
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
}
/** 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) ?? [],
}))
}

View file

@ -22,6 +22,7 @@ import type {
} from '@packages/shared' } from '@packages/shared'
import { coerceDate } from '../lib/date' import { coerceDate } from '../lib/date'
import { runBatched } from '../lib/run-batched' import { runBatched } from '../lib/run-batched'
import { attachOrderItems } from '../lib/order-items'
import { composeSkuName, composeUnitNotation } from '../lib/sku-features' import { composeSkuName, composeUnitNotation } from '../lib/sku-features'
import { marketStatsForRegion } from '../lib/market-stats' import { marketStatsForRegion } from '../lib/market-stats'
import { computeEligibleSubtotal, type CartLine } from '@packages/shared' import { computeEligibleSubtotal, type CartLine } from '@packages/shared'
@ -394,30 +395,6 @@ export async function getOrdersWithRelations(
const ordersWithRelations = await db.query.orders.findMany({ const ordersWithRelations = await db.query.orders.findMany({
where: eq(orders.userId, userId), where: eq(orders.userId, userId),
with: { with: {
orderItems: {
with: {
sku: {
with: {
product: {
columns: {
name: true,
},
},
features: {
columns: {
featureName: true,
featureValue: true,
},
},
},
columns: {
id: true,
name: true,
images: true,
},
},
},
},
slot: { slot: {
columns: { columns: {
deliveryTime: true, deliveryTime: true,
@ -443,7 +420,9 @@ export async function getOrdersWithRelations(
offset: offset, offset: offset,
}) })
return ordersWithRelations.map((order) => { const withItems = await attachOrderItems(ordersWithRelations)
return withItems.map((order) => {
const createdAt = coerceDate(order.createdAt) ?? new Date(0) const createdAt = coerceDate(order.createdAt) ?? new Date(0)
const slot = order.slot const slot = order.slot
? { ? {
@ -502,30 +481,6 @@ export async function getOrderByIdWithRelations(
const order = await db.query.orders.findFirst({ const order = await db.query.orders.findFirst({
where: and(eq(orders.id, orderId), eq(orders.userId, userId)), where: and(eq(orders.id, orderId), eq(orders.userId, userId)),
with: { with: {
orderItems: {
with: {
sku: {
with: {
product: {
columns: {
name: true,
},
},
features: {
columns: {
featureName: true,
featureValue: true,
},
},
},
columns: {
id: true,
name: true,
images: true,
},
},
},
},
slot: { slot: {
columns: { columns: {
deliveryTime: true, deliveryTime: true,
@ -552,16 +507,17 @@ export async function getOrderByIdWithRelations(
return null return null
} }
const createdAt = coerceDate(order.createdAt) ?? new Date(0) const [orderWithItems] = await attachOrderItems([order])
const slot = order.slot const createdAt = coerceDate(orderWithItems.createdAt) ?? new Date(0)
const slot = orderWithItems.slot
? { ? {
...order.slot, ...orderWithItems.slot,
deliveryTime: coerceDate(order.slot.deliveryTime) ?? new Date(0), deliveryTime: coerceDate(orderWithItems.slot.deliveryTime) ?? new Date(0),
} }
: null : null
return { return {
...order, ...orderWithItems,
createdAt, createdAt,
slot, slot,
} as OrderDetailWithRelations } as OrderDetailWithRelations
@ -757,21 +713,6 @@ export async function getOrdersByIdsWithFullData(
phone: true, phone: true,
}, },
}, },
orderItems: {
with: {
sku: {
columns: {
name: true,
},
with: {
product: {
columns: { name: true },
},
features: true,
},
},
},
},
slot: { slot: {
columns: { columns: {
deliveryTime: true, deliveryTime: true,
@ -781,7 +722,9 @@ export async function getOrdersByIdsWithFullData(
}) })
}) })
return orderChunks.flat() as unknown as OrderWithFullData[] const withItems = await attachOrderItems(orderChunks.flat())
return withItems as unknown as OrderWithFullData[]
} }
export type OrderWithCancellationData = OrderWithFullData export type OrderWithCancellationData = OrderWithFullData
@ -789,7 +732,7 @@ export type OrderWithCancellationData = OrderWithFullData
export async function getOrderByIdWithFullData( export async function getOrderByIdWithFullData(
orderId: number orderId: number
): Promise<OrderWithCancellationData | null> { ): Promise<OrderWithCancellationData | null> {
return db.query.orders.findFirst({ const order = await db.query.orders.findFirst({
where: eq(orders.id, orderId), where: eq(orders.id, orderId),
with: { with: {
address: { address: {
@ -802,24 +745,15 @@ export async function getOrderByIdWithFullData(
phone: true, phone: true,
}, },
}, },
orderItems: {
with: {
sku: {
with: {
product: {
columns: {
name: true,
},
},
},
},
},
},
slot: { slot: {
columns: { columns: {
deliveryTime: true, deliveryTime: true,
}, },
}, },
}, },
}) as Promise<OrderWithCancellationData | null> })
if (!order) return null
const [withItems] = await attachOrderItems([order])
return withItems as unknown as OrderWithCancellationData
} }