From e30fdae2ead2604ab143b276d8b729217c332f27 Mon Sep 17 00:00:00 2001 From: mihir Date: Thu, 8 Oct 2026 02:32:35 +0530 Subject: [PATCH] feat(forecasts): add transparent capture-rate planning baseline --- README.md | 2 + docs/capture-forecasts-api.md | 23 +++ docs/roadmap.md | 1 + prisma/migration-checksums.json | 3 +- .../migration.sql | 2 + src/analytics/analytics-query.ts | 10 +- src/analytics/analytics.module.ts | 6 +- src/analytics/forecast-policy.ts | 18 ++ src/analytics/forecast-query.ts | 21 +++ src/analytics/forecast.schemas.ts | 16 ++ src/analytics/forecast.store.ts | 65 +++++++ src/analytics/forecasts.controller.ts | 24 +++ src/identity/permissions.ts | 1 + test/capture-forecasts.spec.ts | 168 ++++++++++++++++++ test/forecast-policy.spec.ts | 36 ++++ 15 files changed, 390 insertions(+), 6 deletions(-) create mode 100644 docs/capture-forecasts-api.md create mode 100644 prisma/migrations/20261008100000_capture_forecasts/migration.sql create mode 100644 src/analytics/forecast-policy.ts create mode 100644 src/analytics/forecast-query.ts create mode 100644 src/analytics/forecast.schemas.ts create mode 100644 src/analytics/forecast.store.ts create mode 100644 src/analytics/forecasts.controller.ts create mode 100644 test/capture-forecasts.spec.ts create mode 100644 test/forecast-policy.spec.ts diff --git a/README.md b/README.md index 3d33153..f932a52 100644 --- a/README.md +++ b/README.md @@ -90,3 +90,5 @@ Live customer segments and consent-aware audience checks: see [Phase 4H API guid Moderated community discussions: see [Phase 5A API guide](docs/forum-api.md). Commerce activity analytics: see [Phase 5B API guide](docs/commerce-analytics-api.md). + +Captured-request forecast baseline: see [Phase 5C API guide](docs/capture-forecasts-api.md). diff --git a/docs/capture-forecasts-api.md b/docs/capture-forecasts-api.md new file mode 100644 index 0000000..79cc77d --- /dev/null +++ b/docs/capture-forecasts-api.md @@ -0,0 +1,23 @@ +# Captured-request forecasting baseline (Phase 5C) + +Staff can project a historical daily checkout-capture rate over a bounded future horizon. This provides an explicit planning baseline from currently non-cancelled checkout captures, including expired pending-payment orders. It does not imply completed sales, paid demand, revenue, stock requirements, or statistical confidence. The response names its method and evidence basis; no stock or production operation is triggered. + +`GET /api/v1/forecasts/captures` requires `forecasts.read`, rechecked with the live session inside the existing read transaction. `analytics.read` alone does not grant forecasting access. Existing system Owners receive the new permission through the additive migration; custom roles remain explicit. + +Required `from` and `to` reuse analytics ISO-offset datetime validation, normalize to UTC, and must be UTC midnight boundaries covering 7–366 complete past UTC days. Start is inclusive, end exclusive; the end cannot exceed today's UTC midnight. An offset such as `05:30:00+05:30` is valid when it normalizes to midnight UTC. Partial days, future history, excessive precision, unsupported normalized years, invalid/oversized windows, and extra fields return 400. + +Optional `horizonDays` is an integer 1–90, default 30. Optional `currency` is a three-uppercase-letter historical cohort filter; currency groups remain separate. `limit` defaults to 25 (maximum 100) and `offset` to zero (maximum 10,000), using existing pagination. Queries are scoped to the caller's organization and accept no organization/account override. Missing sessions return 401 and missing permission 403. + +The response includes `asOf`, `method: "MEAN_DAILY_CAPTURE_RATE"`, `basis: "NON_CANCELLED_CHECKOUT_CAPTURES"`, normalized `history`, `lookbackDays`, `horizonDays`, `historyAgeDays`, and `projection`. Projection starts at the next UTC midnight and ends exclusively after the requested whole-day horizon. History age measures days between the selected historical end and today's UTC midnight, making an old source window visible instead of silently presenting it as recent. + +Each variant/currency row includes current catalog ID/SKU/product/variant labels, `currentlySellable`, historical `orderCount`, `activityDays`, exact-string `observedQuantity`, and exact-string `projectedCaptureQuantity`. Historical quantities come from immutable order lines; current labels can change without rewriting those quantities. Older descriptor versions of the same variant/currency are combined. Currently inactive/unpublished variants are retained with `currentlySellable: false`; this flag is current catalog activity/publication, not a stock reservation or historical-currency price promise. + +The baseline is `ceil(observedQuantity × horizonDays / lookbackDays)`, calculated with integer arithmetic. The divisor includes every calendar day in the window, including days without captures. `activityDays` separately counts distinct UTC days with qualifying records. Currently cancelled orders are excluded, and later cancellation affects the next read. Empty cohorts return empty rows rather than invented observations; an empty paginated page is not a claim that no qualifying history exists elsewhere. + +Rows rank by observed quantity descending, then stable variant ID/currency. Each response is a live evaluation; no persistent cohort, total-count cursor, or backtest snapshot is implied. Historical status is evaluated as currently stored, so this is not a reconstruction of what staff knew at a past date. Monetary values, customer/order identifiers, contacts, addresses, coupon information, keys, and hashes are absent. + +The SQL reuses the same scoped, parameterized creation-time cohort as Phase 5B and the existing order date index. One aggregate statement provides a database snapshot; reads do not take the organization write lock. Inputs and pagination are bounded. No model-training dependency, new forecast table, scheduler, cache, confidence interval, seasonal adjustment, automatic purchasing, or production planning rule is introduced. Replace the simple daily mean with a validated model when suitable completed-sale/fulfillment history and forecasting requirements are available. + +Deploy the additive Owner-permission migration before the application. Existing tables, timestamps, order snapshots, and historical migrations remain unchanged. Older code ignores the permission on rollback. Native PostgreSQL concurrency verification remains subject to the existing CI database setup. + +Verification covers zero-activity days, cancellation exclusion and live re-evaluation, exclusive end dates, exact ceiling arithmetic beyond JavaScript safe integers, current labels/inactive flags, currency separation, deterministic pagination, empty cohorts, independent permissions, organization scope, past/full-day/horizon limits, inherited analytics bounds, and migration drift. diff --git a/docs/roadmap.md b/docs/roadmap.md index 9059847..a438c07 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -69,6 +69,7 @@ Moderated forums, advanced analytics, forecasts, accounting adapters, profitabil - 5A (backend implemented): immutable discussion threads and flat replies, independent append-only approval/rejection/hiding, private author history, public alias-only discovery, parent visibility gates, and pending-submission quotas. Forum UI, editing/appeals, media, realtime features and notifications remain separate milestones. - 5B (implemented): bounded UTC daily checkout activity and frozen variant-demand analytics, current-state/currency separation, exact snapshot values, scoped reporting permissions, and UTC application sessions. Paid/fulfilled revenue, financial recognition, forecasts, cross-channel analytics and dashboard UI remain separate milestones. +- 5C (baseline implemented): bounded historical daily capture-rate projections with exact unit arithmetic, zero-day inclusion, cancellation exclusion, visible evidence/staleness and current catalog flags. Validated sales/seasonal forecasts, confidence intervals, stock actions and automated production planning remain separate milestones. ## Definition of done for every feature diff --git a/prisma/migration-checksums.json b/prisma/migration-checksums.json index 674cc20..3888d56 100644 --- a/prisma/migration-checksums.json +++ b/prisma/migration-checksums.json @@ -52,5 +52,6 @@ "20261007140000_blog_publishing": "92e8d98a8e89f3eda28b6cf5c3b45125a325e5d8e852f1e5a0a3cf5d7eff65a4", "20261007150000_customer_segments": "bcafd50bc12dc44b7ee532ba4ca23da0b12eb3f0e89ad4b168789a22e110969a", "20261007160000_moderated_forums": "3a7dce2115e06acd0f4b02d366721db5ebcf8b5f31106b5d85093c1374a2b6a5", - "20261007170000_commerce_analytics": "800e392f788e176e3fb27c04f956a18e5f1505b820af6bb2364fc990aa8d26ea" + "20261007170000_commerce_analytics": "800e392f788e176e3fb27c04f956a18e5f1505b820af6bb2364fc990aa8d26ea", + "20261008100000_capture_forecasts": "69b94ac61b9f1c3f47268d5586d7f73c4c392cabdd3049d01f34e5e033cac043" } diff --git a/prisma/migrations/20261008100000_capture_forecasts/migration.sql b/prisma/migrations/20261008100000_capture_forecasts/migration.sql new file mode 100644 index 0000000..68fca53 --- /dev/null +++ b/prisma/migrations/20261008100000_capture_forecasts/migration.sql @@ -0,0 +1,2 @@ +UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['forecasts.read'])) + WHERE is_system = true AND name = 'Owner'; diff --git a/src/analytics/analytics-query.ts b/src/analytics/analytics-query.ts index d985e2a..53efbaf 100644 --- a/src/analytics/analytics-query.ts +++ b/src/analytics/analytics-query.ts @@ -1,7 +1,11 @@ import { Prisma } from '../generated/prisma/client'; import type { AnalyticsWindow, AnalyticsVariants } from './analytics.schemas'; -function cohort(organizationId: string, input: AnalyticsWindow, now: Date) { +export function commerceCohort( + organizationId: string, + input: AnalyticsWindow, + now: Date, +) { const currency = input.currency ? Prisma.sql`AND o.currency = ${input.currency}` : Prisma.empty; @@ -17,7 +21,7 @@ export function dailyQuery( input: AnalyticsWindow, now: Date, ) { - return Prisma.sql`WITH cohort AS (${cohort(organizationId, input, now)}) + return Prisma.sql`WITH cohort AS (${commerceCohort(organizationId, input, now)}) SELECT to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS day, currency, COUNT(*)::int AS "orderCount", COUNT(*) FILTER (WHERE is_open)::int AS "openOrderCount", @@ -35,7 +39,7 @@ export function variantsQuery( input: AnalyticsVariants, now: Date, ) { - return Prisma.sql`WITH cohort AS (${cohort(organizationId, input, now)}) + return Prisma.sql`WITH cohort AS (${commerceCohort(organizationId, input, now)}) SELECT c.currency, l.variant_id AS "variantId", l.sku, l.product_name AS "productName", l.variant_name AS "variantName", COUNT(*)::int AS "orderCount", SUM(l.quantity)::text AS "capturedQuantity", COALESCE(SUM(l.quantity) FILTER (WHERE c.is_open), 0)::text AS "openQuantity", diff --git a/src/analytics/analytics.module.ts b/src/analytics/analytics.module.ts index 306e1e2..dbf87ac 100644 --- a/src/analytics/analytics.module.ts +++ b/src/analytics/analytics.module.ts @@ -2,9 +2,11 @@ import { Module } from '@nestjs/common'; import { IdentityModule } from '../identity/identity.module'; import { AnalyticsController } from './analytics.controller'; import { AnalyticsStore } from './analytics.store'; +import { ForecastsController } from './forecasts.controller'; +import { ForecastStore } from './forecast.store'; @Module({ imports: [IdentityModule], - controllers: [AnalyticsController], - providers: [AnalyticsStore], + controllers: [AnalyticsController, ForecastsController], + providers: [AnalyticsStore, ForecastStore], }) export class AnalyticsModule {} diff --git a/src/analytics/forecast-policy.ts b/src/analytics/forecast-policy.ts new file mode 100644 index 0000000..e0f590f --- /dev/null +++ b/src/analytics/forecast-policy.ts @@ -0,0 +1,18 @@ +export const DAY_MS = 86400000; +export function utcDayStart(now: Date) { + const day = new Date(now); + day.setUTCHours(0, 0, 0, 0); + return day; +} +export function projectedCaptures( + quantity: string, + lookbackDays: number, + horizonDays: number, +) { + // ponytail: historical daily mean; use a validated seasonal model when completed-sales history exists. + const days = BigInt(lookbackDays); + return ( + (BigInt(quantity) * BigInt(horizonDays) + days - 1n) / + days + ).toString(); +} diff --git a/src/analytics/forecast-query.ts b/src/analytics/forecast-query.ts new file mode 100644 index 0000000..6174363 --- /dev/null +++ b/src/analytics/forecast-query.ts @@ -0,0 +1,21 @@ +import { Prisma } from '../generated/prisma/client'; +import { commerceCohort } from './analytics-query'; +import type { CaptureForecastInput } from './forecast.schemas'; +export function captureForecastQuery( + organizationId: string, + input: CaptureForecastInput, + now: Date, +) { + return Prisma.sql`WITH cohort AS (${commerceCohort(organizationId, input, now)}) + SELECT v.id AS "variantId", c.currency, v.sku, p.name AS "productName", v.name AS "variantName", + (v.active AND p.status = 'PUBLISHED') AS "currentlySellable", + COUNT(*)::int AS "orderCount", COUNT(DISTINCT (c.created_at AT TIME ZONE 'UTC')::date)::int AS "activityDays", + SUM(l.quantity)::text AS "observedQuantity" + FROM cohort c JOIN order_lines l ON l.order_id = c.id AND l.organization_id = c.organization_id + JOIN product_variants v ON v.id = l.variant_id AND v.organization_id = l.organization_id + JOIN products p ON p.id = v.product_id AND p.organization_id = v.organization_id + WHERE NOT c.is_cancelled + GROUP BY v.id, c.currency, v.sku, p.name, v.name, v.active, p.status + ORDER BY SUM(l.quantity) DESC, v.id ASC, c.currency ASC + LIMIT ${input.limit} OFFSET ${input.offset}`; +} diff --git a/src/analytics/forecast.schemas.ts b/src/analytics/forecast.schemas.ts new file mode 100644 index 0000000..1024142 --- /dev/null +++ b/src/analytics/forecast.schemas.ts @@ -0,0 +1,16 @@ +import { z } from 'zod'; +import { analyticsVariantsSchema } from './analytics.schemas'; +import { DAY_MS, utcDayStart } from './forecast-policy'; +export const captureForecastSchema = analyticsVariantsSchema + .safeExtend({ + horizonDays: z.coerce.number().int().min(1).max(90).default(30), + }) + .refine( + (input) => + input.from.getTime() === utcDayStart(input.from).getTime() && + input.to.getTime() === utcDayStart(input.to).getTime() && + input.to.getTime() - input.from.getTime() >= 7 * DAY_MS && + input.to <= utcDayStart(new Date()), + { message: 'Use 7–366 complete past UTC days', path: ['to'] }, + ); +export type CaptureForecastInput = z.infer; diff --git a/src/analytics/forecast.store.ts b/src/analytics/forecast.store.ts new file mode 100644 index 0000000..b2e5127 --- /dev/null +++ b/src/analytics/forecast.store.ts @@ -0,0 +1,65 @@ +import { Injectable } from '@nestjs/common'; +import { AccessStore } from '../identity/access.store'; +import type { Principal } from '../identity/identity.types'; +import { captureForecastQuery } from './forecast-query'; +import { DAY_MS, projectedCaptures, utcDayStart } from './forecast-policy'; +import type { CaptureForecastInput } from './forecast.schemas'; +type CaptureRow = { + variantId: string; + currency: string; + sku: string; + productName: string; + variantName: string; + currentlySellable: boolean; + orderCount: number; + activityDays: number; + observedQuantity: string; +}; +@Injectable() +export class ForecastStore { + constructor(private readonly access: AccessStore) {} + captures(actor: Principal, input: CaptureForecastInput) { + return this.access.mutate( + actor, + 'forecasts.read', + async (tx) => { + const now = new Date(); + const today = utcDayStart(now); + const lookbackDays = + (input.to.getTime() - input.from.getTime()) / DAY_MS; + const projectionStart = new Date(today.getTime() + DAY_MS); + const rows = await tx.$queryRaw( + captureForecastQuery(actor.organizationId, input, now), + ); + return { + asOf: now.toISOString(), + method: 'MEAN_DAILY_CAPTURE_RATE', + basis: 'NON_CANCELLED_CHECKOUT_CAPTURES', + history: { + from: input.from.toISOString(), + to: input.to.toISOString(), + currency: input.currency ?? null, + }, + historyAgeDays: (today.getTime() - input.to.getTime()) / DAY_MS, + lookbackDays, + horizonDays: input.horizonDays, + projection: { + from: projectionStart.toISOString(), + to: new Date( + projectionStart.getTime() + input.horizonDays * DAY_MS, + ).toISOString(), + }, + variants: rows.map((row) => ({ + ...row, + projectedCaptureQuantity: projectedCaptures( + row.observedQuantity, + lookbackDays, + input.horizonDays, + ), + })), + }; + }, + false, + ); + } +} diff --git a/src/analytics/forecasts.controller.ts b/src/analytics/forecasts.controller.ts new file mode 100644 index 0000000..84a12a4 --- /dev/null +++ b/src/analytics/forecasts.controller.ts @@ -0,0 +1,24 @@ +import { Controller, Get, Query } from '@nestjs/common'; +import { + CurrentPrincipal, + RequirePermission, +} from '../identity/access.decorator'; +import type { Principal } from '../identity/identity.types'; +import { SchemaPipe } from '../common/validation.pipe'; +import { + captureForecastSchema, + type CaptureForecastInput, +} from './forecast.schemas'; +import { ForecastStore } from './forecast.store'; +@Controller('forecasts') +@RequirePermission('forecasts.read') +export class ForecastsController { + constructor(private readonly forecasts: ForecastStore) {} + @Get('captures') + captures( + @CurrentPrincipal() actor: Principal, + @Query(new SchemaPipe(captureForecastSchema)) input: CaptureForecastInput, + ) { + return this.forecasts.captures(actor, input); + } +} diff --git a/src/identity/permissions.ts b/src/identity/permissions.ts index 9f540ad..1436dd2 100644 --- a/src/identity/permissions.ts +++ b/src/identity/permissions.ts @@ -1,4 +1,5 @@ export const PERMISSIONS = [ + 'forecasts.read', 'analytics.read', 'forum.read', 'forum.moderate', diff --git a/test/capture-forecasts.spec.ts b/test/capture-forecasts.spec.ts new file mode 100644 index 0000000..0e321a8 --- /dev/null +++ b/test/capture-forecasts.spec.ts @@ -0,0 +1,168 @@ +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); + }); +}); diff --git a/test/forecast-policy.spec.ts b/test/forecast-policy.spec.ts new file mode 100644 index 0000000..9cf8410 --- /dev/null +++ b/test/forecast-policy.spec.ts @@ -0,0 +1,36 @@ +import { + projectedCaptures, + utcDayStart, +} from '../src/analytics/forecast-policy'; +import { captureForecastSchema } from '../src/analytics/forecast.schemas'; + +it('projects exact integer quantities over all history days with ceiling rounding', () => { + expect(projectedCaptures('13', 14, 30)).toBe('28'); + expect(projectedCaptures('14', 14, 30)).toBe('30'); + expect(projectedCaptures('0', 14, 30)).toBe('0'); + expect(projectedCaptures('9007199254740993', 7, 7)).toBe('9007199254740993'); + expect(utcDayStart(new Date('2026-10-08T12:34:00Z')).toISOString()).toBe( + '2026-10-08T00:00:00.000Z', + ); +}); +it('requires complete historical days, preserves analytics bounds and limits horizons', () => { + const input = { from: '2026-01-01T00:00:00Z', to: '2026-01-15T00:00:00Z' }; + expect(captureForecastSchema.parse(input)).toMatchObject({ + horizonDays: 30, + limit: 25, + offset: 0, + }); + for (const change of [ + { from: '2026-01-01T01:00:00Z' }, + { to: '2026-01-02T00:00:00Z' }, + { to: '2027-01-03T00:00:00Z' }, + { from: '2024-01-01T00:00:00Z' }, + { horizonDays: 91 }, + { horizonDays: 0 }, + { limit: 101 }, + { currency: 'inr' }, + ]) + expect( + captureForecastSchema.safeParse({ ...input, ...change }).success, + ).toBe(false); +});