/** * 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]) }) })