import { randomUUID } from 'node:crypto'; import { identityApp, type IdentityApp } from './helpers/identity-app'; import { secondActor, seedProduct } from './helpers/commerce'; describe('transparent captured-request forecasting baseline', () => { let ctx: IdentityApp; beforeAll(async () => { ctx = await identityApp(); }); afterAll(async () => { await ctx.close(); }); beforeEach(async () => { await ctx.clearLimits(); }); const window = { from: '2026-01-01T00:00:00Z', to: '2026-01-15T00:00:00Z', horizonDays: 30, }; const report = (input: object = window, token = ctx.token) => ctx .api() .get('/api/v1/forecasts/captures') .auth(token, { type: 'bearer' }) .query(input); async function seed( variantId: string, quantity: number, when: string, cancelled = false, currency = 'INR', ) { return ctx.db.order.create({ data: { userId: ctx.owner.userId, organizationId: ctx.owner.organizationId, currency, status: cancelled ? 'CANCELLED' : 'PENDING_PAYMENT', subtotal: quantity.toString(), discount: '0', merchandiseTotal: quantity.toString(), createdAt: new Date(when), expiresAt: new Date(new Date(when).getTime() + 900000), addressSnapshot: { recipient: 'Private recipient' }, idempotencyKey: randomUUID(), requestHash: 'a'.repeat(64), lines: { create: [ { variantId, sku: 'OLD-SKU', productName: 'Old product', variantName: 'Old variant', quantity, unitPrice: '1.00', lineTotal: quantity.toString(), }, ], }, }, }); } it('includes zero-activity days in the divisor, excludes cancellations and rounds projected units upward', async () => { const item = await seedProduct(ctx, true); await seed(item.variant.id, 10, '2026-01-01T12:00:00Z'); await seed(item.variant.id, 3, '2026-01-03T12:00:00Z'); await seed(item.variant.id, 99, '2026-01-04T12:00:00Z', true); await seed(item.variant.id, 50, '2026-01-15T00:00:00Z'); const result = await report().expect(200); expect(result.body).toMatchObject({ method: 'MEAN_DAILY_CAPTURE_RATE', basis: 'NON_CANCELLED_CHECKOUT_CAPTURES', lookbackDays: 14, horizonDays: 30, }); expect(result.body.variants).toHaveLength(1); expect(result.body.variants[0]).toMatchObject({ variantId: item.variant.id, currency: 'INR', orderCount: 2, activityDays: 2, observedQuantity: '13', projectedCaptureQuantity: '28', currentlySellable: true, }); expect( Date.parse(result.body.projection.to) - Date.parse(result.body.projection.from), ).toBe(30 * 86400000); expect(Date.parse(result.body.projection.from)).toBeGreaterThan( Date.parse(result.body.asOf), ); expect(JSON.stringify(result.body)).not.toMatch( /recipient|address|userId|requestHash|idempotencyKey|revenue|stockAdjustment/, ); }); it('uses current labels without rewriting historical quantities and keeps currency groups distinct', async () => { const item = await seedProduct(ctx, true); const input = { ...window, from: '2026-02-01T00:00:00Z', to: '2026-02-15T00:00:00Z', }; await seed(item.variant.id, 14, '2026-02-01T12:00:00Z'); await seed(item.variant.id, 7, '2026-02-02T12:00:00Z', false, 'USD'); await ctx.db.productVariant.update({ where: { id: item.variant.id }, data: { name: 'New label', active: false }, }); const first = await report({ ...input, limit: 1 }).expect(200); expect(first.body.variants[0]).toMatchObject({ currency: 'INR', variantName: 'New label', observedQuantity: '14', projectedCaptureQuantity: '30', currentlySellable: false, }); const second = await report({ ...input, limit: 1, offset: 1 }).expect(200); expect(second.body.variants[0]).toMatchObject({ currency: 'USD', observedQuantity: '7', projectedCaptureQuantity: '15', }); const filtered = await report({ ...input, currency: 'USD' }).expect(200); expect(filtered.body.variants).toHaveLength(1); expect(filtered.body.variants[0].currency).toBe('USD'); }); it('re-evaluates cancellation and returns empty cohorts without invented quantities', async () => { const item = await seedProduct(ctx, true); const input = { ...window, from: '2026-03-01T00:00:00Z', to: '2026-03-15T00:00:00Z', }; const order = await seed(item.variant.id, 14, '2026-03-01T12:00:00Z'); expect((await report(input).expect(200)).body.variants).toHaveLength(1); await ctx .api() .post('/api/v1/admin/orders/' + order.id + '/cancel') .auth(ctx.token, { type: 'bearer' }) .expect(201); expect((await report(input).expect(200)).body.variants).toEqual([]); }); it('enforces forecast permission, tenant scope and completed-day/horizon limits', async () => { const customer = await secondActor(ctx); await report(window, customer.token).expect(403); const analyst = await secondActor(ctx, true, ['analytics.read']); await report(window, analyst.token).expect(403); const foreign = await secondActor(ctx, false, ['forecasts.read']); expect( (await report(window, foreign.token).expect(200)).body.variants, ).toEqual([]); const staff = await secondActor(ctx, true, ['forecasts.read']); await report(window, staff.token).expect(200); for (const query of [ { ...window, to: '2026-01-02T00:00:00Z' }, { ...window, from: '2026-01-01T01:00:00Z' }, { ...window, horizonDays: 0 }, { ...window, horizonDays: 91 }, { ...window, limit: 101 }, { ...window, organizationId: foreign.organizationId }, { ...window, from: '9999-01-01T00:00:00Z', to: '9999-01-15T00:00:00Z' }, ]) await report(query).expect(400); await ctx.api().get('/api/v1/forecasts/captures').query(window).expect(401); }); });