diff --git a/AGENTS.md b/AGENTS.md index 83daecb..c13d8db 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,3 +53,19 @@ react-native. They are available in the common-ui as MyText, MyTextInput, MyTouc ## 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. + + +## 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. + diff --git a/apps/backend/src/jobs/order-items-archive.ts b/apps/backend/src/jobs/order-items-archive.ts new file mode 100644 index 0000000..8589735 --- /dev/null +++ b/apps/backend/src/jobs/order-items-archive.ts @@ -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 { + 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 { + const env = (globalThis as { ENV?: Record }).ENV + ensureWorkerInit(env as any) + return runOrderItemsArchive(options) +} diff --git a/apps/backend/src/sqliteImporter.ts b/apps/backend/src/sqliteImporter.ts index 57a8b09..41d962c 100644 --- a/apps/backend/src/sqliteImporter.ts +++ b/apps/backend/src/sqliteImporter.ts @@ -286,4 +286,19 @@ export { getEffectiveRegionSettings, // Superadmin - Complaints 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' diff --git a/apps/backend/src/stores/store-initializer.ts b/apps/backend/src/stores/store-initializer.ts index c123371..585fcc0 100644 --- a/apps/backend/src/stores/store-initializer.ts +++ b/apps/backend/src/stores/store-initializer.ts @@ -42,8 +42,10 @@ export const initializeAllStores = async (regionId?: number): Promise => { console.log('All application stores initialized successfully'); - // Regenerate cache files for the target region(s) (fire-and-forget) - createAllCacheFiles(regionId).catch(error => { + // Regenerate cache files for the target region(s). Awaited so the DO alarm + // (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) }) } catch (error) { diff --git a/apps/backend/src/test-controller.ts b/apps/backend/src/test-controller.ts index e46260c..9eb9c79 100644 --- a/apps/backend/src/test-controller.ts +++ b/apps/backend/src/test-controller.ts @@ -9,6 +9,7 @@ import { Hono } from 'hono' import cacheSnapshotController from '@/src/test-support/cache-snapshot-controller' import rebuildController from '@/src/test-support/rebuild-controller' import orderTrackerController from '@/src/test-support/order-tracker-controller' +import orderItemsArchiveController from '@/src/test-support/order-items-archive-controller' const router = new Hono() @@ -23,5 +24,6 @@ router.get('/', (c) => { router.route('/cache', cacheSnapshotController) router.route('/rebuild', rebuildController) router.route('/order-trackers', orderTrackerController) +router.route('/order-items-archive', orderItemsArchiveController) export default router diff --git a/apps/backend/src/test-support/order-items-archive-controller.ts b/apps/backend/src/test-support/order-items-archive-controller.ts new file mode 100644 index 0000000..96a8051 --- /dev/null +++ b/apps/backend/src/test-support/order-items-archive-controller.ts @@ -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 }).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 diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/slots.ts b/apps/backend/src/trpc/apis/admin-apis/apis/slots.ts index aca1cb4..158909e 100644 --- a/apps/backend/src/trpc/apis/admin-apis/apis/slots.ts +++ b/apps/backend/src/trpc/apis/admin-apis/apis/slots.ts @@ -124,8 +124,10 @@ export const slotsRouter = router({ console.error('Failed to regenerate slots cache after slot create:', error) }) - // Fire and forget: cleanup stale product slot associations - staleSlotsCleanup().catch((error) => { + // Cleanup stale product slot associations. Awaited so the incremental + // 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) }) diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/user.ts b/apps/backend/src/trpc/apis/admin-apis/apis/user.ts index 5961c79..3c377f1 100644 --- a/apps/backend/src/trpc/apis/admin-apis/apis/user.ts +++ b/apps/backend/src/trpc/apis/admin-apis/apis/user.ts @@ -298,7 +298,14 @@ export const userRouter = { 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 { success: true, diff --git a/apps/backend/tests/unit/initialize-all-stores.test.ts b/apps/backend/tests/unit/initialize-all-stores.test.ts new file mode 100644 index 0000000..6ad70a0 --- /dev/null +++ b/apps/backend/tests/unit/initialize-all-stores.test.ts @@ -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 + +const drainMicrotasks = () => new Promise((resolve) => setImmediate(resolve)) + +describe('initializeAllStores cache generation', () => { + beforeEach(() => { + jest.clearAllMocks() + }) + + it('awaits createAllCacheFiles before resolving', async () => { + let release!: () => void + const work = new Promise((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() + }) +}) diff --git a/apps/backend/tests/unit/order-items-archive.test.ts b/apps/backend/tests/unit/order-items-archive.test.ts new file mode 100644 index 0000000..5dac1f3 --- /dev/null +++ b/apps/backend/tests/unit/order-items-archive.test.ts @@ -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 { + 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 = {}) { + 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 { + 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 + skuById?: Map + apply?: (orderId: number, snapshot: unknown[], verifiedIds: number[]) => boolean | Promise + 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]) + }) +}) diff --git a/apps/backend/tests/unit/queue-consumer.test.ts b/apps/backend/tests/unit/queue-consumer.test.ts new file mode 100644 index 0000000..8b08ed5 --- /dev/null +++ b/apps/backend/tests/unit/queue-consumer.test.ts @@ -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 +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') + }) +}) diff --git a/apps/backend/tests/unit/slots-create-cleanup.test.ts b/apps/backend/tests/unit/slots-create-cleanup.test.ts new file mode 100644 index 0000000..832de2c --- /dev/null +++ b/apps/backend/tests/unit/slots-create-cleanup.test.ts @@ -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 +const mockedCreate = createSlotWithRelations as jest.MockedFunction +const mockedCache = createSlotsCacheFile as jest.MockedFunction + +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((resolve) => setImmediate(resolve)) + +describe('admin.slots.createSlot cleanup', () => { + beforeEach(() => { + jest.clearAllMocks() + }) + + it('awaits staleSlotsCleanup before resolving', async () => { + let release!: () => void + const work = new Promise((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) + }) +}) diff --git a/apps/backend/tests/unit/worker-queue.test.ts b/apps/backend/tests/unit/worker-queue.test.ts new file mode 100644 index 0000000..de7bfe3 --- /dev/null +++ b/apps/backend/tests/unit/worker-queue.test.ts @@ -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 + +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((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') + }) +}) diff --git a/apps/backend/worker.ts b/apps/backend/worker.ts index 773485c..2405387 100644 --- a/apps/backend/worker.ts +++ b/apps/backend/worker.ts @@ -7,6 +7,10 @@ import { CacheCreator } from './src/jobs/cache-creator' import { createApp } from './src/app' import { ensureWorkerInit } from './src/lib/worker-init' import { runFlashDeliveryToggleCron } from './src/lib/flash-delivery-cron' +import { + CRON_ORDER_ITEMS_ARCHIVE, + runOrderItemsArchiveCron, +} from './src/jobs/order-items-archive' import { handleNotifQueue, handleOrderPlacedQueue, @@ -77,7 +81,7 @@ export default { return } - handleNotifQueue(batch) + await handleNotifQueue(batch) }, async scheduled( event: any, @@ -87,6 +91,10 @@ export default { ctx: ExecutionContext ) { 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}); // ctx.waitUntil(runFlashDeliveryToggleCron({ cron: event.cron, env })) }, diff --git a/apps/backend/wrangler.dev.toml b/apps/backend/wrangler.dev.toml index 48bc97a..1021bf6 100644 --- a/apps/backend/wrangler.dev.toml +++ b/apps/backend/wrangler.dev.toml @@ -96,7 +96,8 @@ TELEGRAM_CHAT_IDS = "5147760058" #crons = ["* * * * *"] crons = [ "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] diff --git a/apps/backend/wrangler.prod.toml b/apps/backend/wrangler.prod.toml index dec3c51..acf81fd 100644 --- a/apps/backend/wrangler.prod.toml +++ b/apps/backend/wrangler.prod.toml @@ -85,7 +85,7 @@ TELEGRAM_BOT_TOKEN = "8410461852:AAGXQCwRPFbndqwTgLJh8kYxST4Z0vgh72U" TELEGRAM_CHAT_IDS = "-5075171894" [triggers] -crons = ["0 16 * * *", "0 1 * * *"] +crons = ["0 16 * * *", "0 1 * * *", "30 20 * * *"] # crons = ["* * * * *"] # crons = ["7 18 * * *", "10 18 * * *"] diff --git a/apps/user-ui/JEST-TEST-CASES.md b/apps/user-ui/JEST-TEST-CASES.md index a05c0a1..68c5d79 100644 --- a/apps/user-ui/JEST-TEST-CASES.md +++ b/apps/user-ui/JEST-TEST-CASES.md @@ -926,7 +926,7 @@ real. | ME-14 | edge | no navigation target | no replace | | ME-15 | edge | target is consumed | second focus does not replace again | | 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-19 | edge | version/footer | version text rendered | | ME-20 | edge | signed out | me layout login wall, hub not rendered | diff --git a/apps/user-ui/app/(drawer)/(tabs)/me/index.tsx b/apps/user-ui/app/(drawer)/(tabs)/me/index.tsx index b2a6541..8223d71 100644 --- a/apps/user-ui/app/(drawer)/(tabs)/me/index.tsx +++ b/apps/user-ui/app/(drawer)/(tabs)/me/index.tsx @@ -4,7 +4,6 @@ import { useRouter } from 'expo-router'; import { useFocusEffect } from '@react-navigation/native'; import { AppContainer, MyText, tw, MyTouchableOpacity, ProfileImage, colors } from 'common-ui'; import TabLayoutWrapper from '@/components/TabLayoutWrapper'; -import LocationBar from '@/src/components/LocationBar'; import { LinearGradient } from 'expo-linear-gradient'; import { Ionicons } from '@expo/vector-icons'; import NextOrderGlimpse from '@/components/NextOrderGlimpse'; @@ -110,7 +109,6 @@ export default function Me() { showsVerticalScrollIndicator={false} contentContainerStyle={tw`pb-8`} > - {/* Minimal Header Section */} diff --git a/apps/user-ui/src/components/AddressForm.tsx b/apps/user-ui/src/components/AddressForm.tsx index 96dcf63..aeb2c0c 100644 --- a/apps/user-ui/src/components/AddressForm.tsx +++ b/apps/user-ui/src/components/AddressForm.tsx @@ -2,7 +2,7 @@ import React, { useCallback, useEffect, useState } from 'react'; import { View, Modal, ScrollView, KeyboardAvoidingView, Platform, Keyboard } from 'react-native'; import { Formik } from 'formik'; 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 { trpc } from '../trpc-client'; import LocationMapStep from './location/LocationMapStep'; @@ -48,7 +48,6 @@ const AddressForm: React.FC = ({ // Towns (regions) the user can deliver in — the City field is a picker over them. const { data: regionsData } = trpc.common.listRegions.useQuery(); const regions = regionsData ?? []; - const [cityOpen, setCityOpen] = useState(false); const cityName = regions.find((region) => region.id === resolvedRegion?.regionId)?.name ?? ''; /** Centre the map WebView opens on (null = the page's own default). */ @@ -79,7 +78,6 @@ const AddressForm: React.FC = ({ // the map straight away on the first region's bound. const openMapForFirstRegion = useCallback(() => { const firstRegion = regions[0] ?? null; - setCityOpen(false); setMapRegionPickerOpen(false); setMapCenter(firstRegion?.center ?? null); setMapOpen(true); @@ -331,58 +329,26 @@ const AddressForm: React.FC = ({ value={values.addressLine2} /> - {/* City is a picker over the serviceable towns (regions). */} + {/* City is a bottom dropdown over the serviceable towns (regions). */} - City * - { - Keyboard.dismiss(); - setCityOpen((prev) => !prev); + topLabel="City *" + label="Select Town" + 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`} - > - - {cityName || 'Select town'} - - - - {cityOpen && ( - - {regions.map((region) => ( - { - setCityOpen(false); - void handleCityChange(region.id); - }} - style={tw`p-3 border-b border-gray-50 flex-row items-center justify-between`} - > - {region.name} - {resolvedRegion?.regionId === region.id && ( - - )} - - ))} - {regions.length === 0 && ( - No towns available - )} - - {/* Last option: skip the town list and pick the point on the map. */} - - Select in Map - - - )} + /> { 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() fireEvent.press(getByTestId('place-order-button')) - await flush(4) + await flush(5) expect(lastProcedureInput('user.order.placeOrder')).toMatchObject({ selectedItems: [{ skuId: 8, quantity: 1, slotId: null }], @@ -83,6 +84,9 @@ describe('Flash funnel routes', () => { regionId: 1, 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 () => { diff --git a/apps/user-ui/tests/pages/me-hub.test.tsx b/apps/user-ui/tests/pages/me-hub.test.tsx index c4d5392..1d7f19b 100644 --- a/apps/user-ui/tests/pages/me-hub.test.tsx +++ b/apps/user-ui/tests/pages/me-hub.test.tsx @@ -209,11 +209,11 @@ describe('Me hub (ME-01..ME-19)', () => { 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() - expect(view.getByTestId('location-bar')).toBeTruthy() - fireEvent.press(view.getByTestId('location-bar')) + expect(view.queryByTestId('location-bar')).toBeNull() + fireEvent.press(view.getByTestId('me-menu-delivery-address')) 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 () => { 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() const modal = view.UNSAFE_getAllByType(Modal).find((candidate: any) => candidate.props.visible) diff --git a/apps/web-ui/src/components/AddressForm.tsx b/apps/web-ui/src/components/AddressForm.tsx index dec8ec9..5a67db4 100644 --- a/apps/web-ui/src/components/AddressForm.tsx +++ b/apps/web-ui/src/components/AddressForm.tsx @@ -24,6 +24,7 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv const [isSubmitting, setIsSubmitting] = useState(false) const [submitError, setSubmitError] = useState(null) const [mapOpen, setMapOpen] = useState(false) + const [mapCenter, setMapCenter] = useState<{ lat: number; lng: number } | null>(null) const [locating, setLocating] = useState(false) const [locationError, setLocationError] = useState(null) const [locationSource, setLocationSource] = useState( @@ -300,16 +301,26 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv
@@ -333,7 +344,10 @@ export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolv