From d9917b9ee18472a0822ee925c927fa13ee4430c1 Mon Sep 17 00:00:00 2001 From: mihir Date: Wed, 7 Oct 2026 18:31:17 +0530 Subject: [PATCH 1/2] fix(database): enforce UTC for pooled connections --- src/database/database.service.ts | 14 ++++++++++++- test/database.spec.ts | 34 +++++++++++++++++++++++++++++++- test/helpers/test-database.ts | 2 ++ 3 files changed, 48 insertions(+), 2 deletions(-) diff --git a/src/database/database.service.ts b/src/database/database.service.ts index 0cf9fad..82c7196 100644 --- a/src/database/database.service.ts +++ b/src/database/database.service.ts @@ -9,15 +9,27 @@ import { PrismaClient } from '../generated/prisma/client'; import { ENVIRONMENT } from '../config/environment.module'; import type { Environment } from '../config/environment'; +export function utcDatabaseUrl(value: string, fallbackOptions = '') { + const url = new URL(value); + const options = url.searchParams.get('options') || fallbackOptions; + url.searchParams.set('options', `${options} -c timezone=UTC`.trim()); + return url.toString(); +} + @Injectable() export class DatabaseService extends PrismaClient implements OnModuleInit, OnModuleDestroy { constructor(@Inject(ENVIRONMENT) environment: Environment) { + // The installed adapter serializes UTC wall-clock values without offsets. + // Enforce UTC on every pooled connection, preserving other startup options. super({ adapter: new PrismaPg({ - connectionString: environment.DATABASE_URL, + connectionString: utcDatabaseUrl( + environment.DATABASE_URL, + process.env.PGOPTIONS ?? '', + ), connectionTimeoutMillis: 3000, query_timeout: 3000, max: environment.DATABASE_POOL_SIZE, diff --git a/test/database.spec.ts b/test/database.spec.ts index f715407..85c8a6a 100644 --- a/test/database.spec.ts +++ b/test/database.spec.ts @@ -1,8 +1,40 @@ import 'reflect-metadata'; -import { DatabaseService } from '../src/database/database.service'; +import { + DatabaseService, + utcDatabaseUrl, +} from '../src/database/database.service'; import { parseEnvironment } from '../src/config/environment'; describe('database lifecycle', () => { + it('preserves credentials and other startup options while enforcing UTC last', () => { + const source = new URL( + 'postgresql://user:p%40ss@localhost/mani?sslmode=require', + ); + source.searchParams.set( + 'options', + '-c application_name=mani -c timezone=Asia/Kolkata', + ); + const result = new URL(utcDatabaseUrl(source.toString())); + expect(result.username).toBe(source.username); + expect(result.password).toBe(source.password); + expect(result.searchParams.get('sslmode')).toBe('require'); + expect(result.searchParams.get('options')).toBe( + '-c application_name=mani -c timezone=Asia/Kolkata -c timezone=UTC', + ); + expect( + new URL(utcDatabaseUrl('postgresql://localhost/mani')).searchParams.get( + 'options', + ), + ).toBe('-c timezone=UTC'); + expect( + new URL( + utcDatabaseUrl( + 'postgresql://localhost/mani', + '-c application_name=env', + ), + ).searchParams.get('options'), + ).toBe('-c application_name=env -c timezone=UTC'); + }); let database: DatabaseService; beforeEach(() => { database = new DatabaseService( diff --git a/test/helpers/test-database.ts b/test/helpers/test-database.ts index b6f5d28..c7c39dc 100644 --- a/test/helpers/test-database.ts +++ b/test/helpers/test-database.ts @@ -31,6 +31,8 @@ export async function testDatabase() { }; } else { const pg = await PGlite.create(); + // The socket emulator ignores startup options; match application UTC sessions. + await pg.exec("SET TIME ZONE 'UTC'"); const server = new PGLiteSocketServer({ db: pg, port: 0, -- 2.40.1 From 490c3a01552a0eeddcf0a35acc42ded4d4641ad5 Mon Sep 17 00:00:00 2001 From: mihir Date: Wed, 7 Oct 2026 18:31:18 +0530 Subject: [PATCH 2/2] feat(analytics): add bounded commerce activity reports --- README.md | 2 + docs/commerce-analytics-api.md | 26 ++ docs/roadmap.md | 1 + prisma/checkout.prisma | 1 + prisma/migration-checksums.json | 3 +- .../migration.sql | 3 + src/analytics/analytics-query.ts | 49 +++ src/analytics/analytics.controller.ts | 33 ++ src/analytics/analytics.module.ts | 10 + src/analytics/analytics.schemas.ts | 40 +++ src/analytics/analytics.store.ts | 91 ++++++ src/app.module.ts | 2 + src/identity/permissions.ts | 1 + test/analytics-policy.spec.ts | 39 +++ test/commerce-analytics.spec.ts | 290 ++++++++++++++++++ 15 files changed, 590 insertions(+), 1 deletion(-) create mode 100644 docs/commerce-analytics-api.md create mode 100644 prisma/migrations/20261007170000_commerce_analytics/migration.sql create mode 100644 src/analytics/analytics-query.ts create mode 100644 src/analytics/analytics.controller.ts create mode 100644 src/analytics/analytics.module.ts create mode 100644 src/analytics/analytics.schemas.ts create mode 100644 src/analytics/analytics.store.ts create mode 100644 test/analytics-policy.spec.ts create mode 100644 test/commerce-analytics.spec.ts diff --git a/README.md b/README.md index ea5d68e..3d33153 100644 --- a/README.md +++ b/README.md @@ -88,3 +88,5 @@ Blog drafts, publication and SEO metadata: see [Phase 4G API guide](docs/blog-pu Live customer segments and consent-aware audience checks: see [Phase 4H API guide](docs/customer-segments-api.md). 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). diff --git a/docs/commerce-analytics-api.md b/docs/commerce-analytics-api.md new file mode 100644 index 0000000..7b0cdb4 --- /dev/null +++ b/docs/commerce-analytics-api.md @@ -0,0 +1,26 @@ +# Commerce activity analytics (Phase 5B) + +Staff can inspect UTC daily checkout activity and frozen variant demand for a bounded creation-time cohort. Both endpoints require `analytics.read`; live session, user/organization scope, and permission are rechecked within the read transaction. Existing system Owners gain the permission through the additive migration; custom roles remain explicit. + +| Method | Route | Result | +| ------ | ------------------------------------- | ------------------------------------------------------------- | +| GET | `/api/v1/analytics/commerce/daily` | `window`, `asOf`, and daily/currency aggregate `days`. | +| GET | `/api/v1/analytics/commerce/variants` | `window`, `asOf`, and paginated frozen-descriptor `variants`. | + +Required query fields `from` and `to` are ISO datetimes with explicit UTC/offsets, up to millisecond precision, and normalized UTC years 0001–9999. The start is inclusive, end exclusive, and the window must increase by at most 366 elapsed days. Responses normalize both to UTC. Optional `currency` is three uppercase letters and filters rather than converts values. Variants support the existing `limit` (default 25, maximum 100) and `offset` (default 0, maximum 10,000). Extra fields, missing endpoints, reversed/oversized windows, and invalid filters return 400. Missing sessions return 401 and insufficient permission 403. Organization overrides are rejected. + +Daily rows group the cohort by UTC creation date and currency, sorted ascending. Each contains `orderCount`, `openOrderCount`, `expiredOrderCount`, and `cancelledOrderCount`. Open means `PENDING_PAYMENT` with expiry strictly after the response's `asOf`; expired means pending with expiry at/before it. Cancelled uses current stored status. These are current states of orders **created in the window**, not a reconstruction of state at the window end or a count of cancellations occurring during that period. + +Money fields are exact two-decimal strings: `capturedSubtotal`, `capturedDiscount`, `capturedMerchandiseValue`, `openMerchandiseValue`, `expiredMerchandiseValue`, and `cancelledMerchandiseValue`. Values come from immutable order snapshots; daily queries do not join lines and therefore cannot multiply order totals for multi-line orders. Captured values include all supported states. Days/currencies with no activity are omitted; empty windows return an empty array. Currencies remain separate, with no FX conversion or combined total. + +Variant rows group by currency, variant ID, frozen SKU, product name and variant name. Renaming or repricing the current catalog does not rewrite those descriptors or values. A variant whose snapshot descriptors changed can appear in several rows. `orderCount` counts orders represented in that descriptor group, `capturedQuantity`/`openQuantity`/`expiredQuantity`/`cancelledQuantity` are exact integer strings, and `capturedLineValue` is the frozen line-total sum **before order-level coupon discounts**. Discounts are not allocated arbitrarily across variants. Rows rank by captured quantity descending, then stable variant/currency/descriptors; pages are independent live evaluations and no total-count/cursor snapshot is implied. + +These reports cover retail checkout captures and current demand activity. Payment remains deferred; captured merchandise value is not recognized revenue, fulfilled sales, profit, tax liability, or cash receipts. Existing partner receipt/account reports retain their separate contracts. Paid/fulfilled analytics, financial recognition, margin attribution, forecasts, cross-channel data, BI exports, caching, and dashboard UI remain later milestones. + +Each aggregate is one parameterized SQL statement using a single database snapshot. The permission wrapper runs without the organization write lock, so reads do not serialize commerce mutations. One server `asOf` is used for expiry classification. Only aggregate order counts/values and frozen catalog descriptors leave the store; customer IDs, order IDs, addresses, contacts, coupon details, keys, and hashes are omitted. SQL values are bound, windows/pagination bounded, and the new `(organization_id, created_at, id)` order index supports date scans. + +The UTC boundary check exposed the installed `adapter-pg` timestamp codec's dependence on UTC sessions. Application connection URLs now append the UTC startup option after preserving existing URL options; each real PostgreSQL pool connection receives it. The embedded socket test emulator ignores startup options, so its database is explicitly initialized to UTC. This follows the [PostgreSQL connection startup options](https://www.postgresql.org/docs/17/libpq-connect.html) and addresses the behavior documented in the [Prisma adapter timezone issue](https://github.com/prisma/prisma/issues/26786), also confirmed against the installed adapter source. No stored timestamps are rewritten. Deployments previously using non-UTC sessions should review historical timestamp interpretation before adopting corrected serialization. + +Deploy the additive date-index/Owner-permission migration before the application. No new reporting table or provider is introduced, and historical migrations/order snapshots stay unchanged. Index creation uses the project's normal migration runner; schedule it appropriately for a large existing order table. Older code ignores the index/new permission on rollback. Removing the UTC application setting would reintroduce the non-UTC codec behavior on affected connections. + +Verification covers exact decimals, separate currencies/current states, UTC midnight and offset normalization, inclusive/exclusive boundaries, empty periods, multi-line fanout prevention, coupon/replay/cancellation behavior, frozen descriptors, stable pagination, scoped permissions, strict window limits, preserved connection options, migration drift and existing recovery/campaign regressions. Native multi-connection PostgreSQL CI remains dependent on the existing test setup. diff --git a/docs/roadmap.md b/docs/roadmap.md index 785eea8..9059847 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -68,6 +68,7 @@ Wishlist, verified reviews/moderation, seasonal campaigns, discounts, cart recov Moderated forums, advanced analytics, forecasts, accounting adapters, profitability and workflow automation. SaaS tenancy/billing requires a separate architecture decision before implementation; an organization table alone does not provide tenant isolation. - 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. ## Definition of done for every feature diff --git a/prisma/checkout.prisma b/prisma/checkout.prisma index 1d29477..0364766 100644 --- a/prisma/checkout.prisma +++ b/prisma/checkout.prisma @@ -77,6 +77,7 @@ model Order { @@unique([userId, organizationId, idempotencyKey]) @@unique([id, organizationId]) @@index([organizationId, userId, createdAt, id]) + @@index([organizationId, createdAt, id]) @@unique([id, userId, organizationId]) @@index([couponId, status, expiresAt]) @@map("orders") diff --git a/prisma/migration-checksums.json b/prisma/migration-checksums.json index ab21745..674cc20 100644 --- a/prisma/migration-checksums.json +++ b/prisma/migration-checksums.json @@ -51,5 +51,6 @@ "20261007130000_messaging_consent": "b4fd5b1cf6a7cd17083a4b5fbef815ec1ebc25ba7538c6de18c05e16212155dd", "20261007140000_blog_publishing": "92e8d98a8e89f3eda28b6cf5c3b45125a325e5d8e852f1e5a0a3cf5d7eff65a4", "20261007150000_customer_segments": "bcafd50bc12dc44b7ee532ba4ca23da0b12eb3f0e89ad4b168789a22e110969a", - "20261007160000_moderated_forums": "3a7dce2115e06acd0f4b02d366721db5ebcf8b5f31106b5d85093c1374a2b6a5" + "20261007160000_moderated_forums": "3a7dce2115e06acd0f4b02d366721db5ebcf8b5f31106b5d85093c1374a2b6a5", + "20261007170000_commerce_analytics": "800e392f788e176e3fb27c04f956a18e5f1505b820af6bb2364fc990aa8d26ea" } diff --git a/prisma/migrations/20261007170000_commerce_analytics/migration.sql b/prisma/migrations/20261007170000_commerce_analytics/migration.sql new file mode 100644 index 0000000..e4ee429 --- /dev/null +++ b/prisma/migrations/20261007170000_commerce_analytics/migration.sql @@ -0,0 +1,3 @@ +CREATE INDEX "orders_organization_id_created_at_id_idx" ON "orders"("organization_id", "created_at", "id"); +UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['analytics.read'])) + WHERE is_system = true AND name = 'Owner'; diff --git a/src/analytics/analytics-query.ts b/src/analytics/analytics-query.ts new file mode 100644 index 0000000..d985e2a --- /dev/null +++ b/src/analytics/analytics-query.ts @@ -0,0 +1,49 @@ +import { Prisma } from '../generated/prisma/client'; +import type { AnalyticsWindow, AnalyticsVariants } from './analytics.schemas'; + +function cohort(organizationId: string, input: AnalyticsWindow, now: Date) { + const currency = input.currency + ? Prisma.sql`AND o.currency = ${input.currency}` + : Prisma.empty; + return Prisma.sql`SELECT o.id, o.organization_id, o.currency, o.created_at, o.subtotal, o.discount, o.merchandise_total, + (o.status = 'PENDING_PAYMENT' AND o.expires_at > ${now}) AS is_open, + (o.status = 'PENDING_PAYMENT' AND o.expires_at <= ${now}) AS is_expired, + (o.status = 'CANCELLED') AS is_cancelled + FROM orders o WHERE o.organization_id = ${organizationId}::uuid + AND o.created_at >= ${input.from} AND o.created_at < ${input.to} ${currency}`; +} +export function dailyQuery( + organizationId: string, + input: AnalyticsWindow, + now: Date, +) { + return Prisma.sql`WITH cohort AS (${cohort(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", + COUNT(*) FILTER (WHERE is_expired)::int AS "expiredOrderCount", + COUNT(*) FILTER (WHERE is_cancelled)::int AS "cancelledOrderCount", + SUM(subtotal)::text AS "capturedSubtotal", SUM(discount)::text AS "capturedDiscount", + SUM(merchandise_total)::text AS "capturedMerchandiseValue", + COALESCE(SUM(merchandise_total) FILTER (WHERE is_open), 0)::text AS "openMerchandiseValue", + COALESCE(SUM(merchandise_total) FILTER (WHERE is_expired), 0)::text AS "expiredMerchandiseValue", + COALESCE(SUM(merchandise_total) FILTER (WHERE is_cancelled), 0)::text AS "cancelledMerchandiseValue" + FROM cohort GROUP BY day, currency ORDER BY day, currency`; +} +export function variantsQuery( + organizationId: string, + input: AnalyticsVariants, + now: Date, +) { + return Prisma.sql`WITH cohort AS (${cohort(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", + COALESCE(SUM(l.quantity) FILTER (WHERE c.is_expired), 0)::text AS "expiredQuantity", + COALESCE(SUM(l.quantity) FILTER (WHERE c.is_cancelled), 0)::text AS "cancelledQuantity", + SUM(l.line_total)::text AS "capturedLineValue" + FROM cohort c JOIN order_lines l ON l.order_id = c.id AND l.organization_id = c.organization_id + GROUP BY c.currency, l.variant_id, l.sku, l.product_name, l.variant_name + ORDER BY SUM(l.quantity) DESC, l.variant_id ASC, c.currency ASC, l.sku ASC, l.product_name ASC, l.variant_name ASC + LIMIT ${input.limit} OFFSET ${input.offset}`; +} diff --git a/src/analytics/analytics.controller.ts b/src/analytics/analytics.controller.ts new file mode 100644 index 0000000..9ff8433 --- /dev/null +++ b/src/analytics/analytics.controller.ts @@ -0,0 +1,33 @@ +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 { + analyticsWindowSchema, + analyticsVariantsSchema, + type AnalyticsWindow, + type AnalyticsVariants, +} from './analytics.schemas'; +import { AnalyticsStore } from './analytics.store'; +@Controller('analytics/commerce') +@RequirePermission('analytics.read') +export class AnalyticsController { + constructor(private readonly analytics: AnalyticsStore) {} + @Get('daily') + daily( + @CurrentPrincipal() actor: Principal, + @Query(new SchemaPipe(analyticsWindowSchema)) input: AnalyticsWindow, + ) { + return this.analytics.daily(actor, input); + } + @Get('variants') + variants( + @CurrentPrincipal() actor: Principal, + @Query(new SchemaPipe(analyticsVariantsSchema)) input: AnalyticsVariants, + ) { + return this.analytics.variants(actor, input); + } +} diff --git a/src/analytics/analytics.module.ts b/src/analytics/analytics.module.ts new file mode 100644 index 0000000..306e1e2 --- /dev/null +++ b/src/analytics/analytics.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { IdentityModule } from '../identity/identity.module'; +import { AnalyticsController } from './analytics.controller'; +import { AnalyticsStore } from './analytics.store'; +@Module({ + imports: [IdentityModule], + controllers: [AnalyticsController], + providers: [AnalyticsStore], +}) +export class AnalyticsModule {} diff --git a/src/analytics/analytics.schemas.ts b/src/analytics/analytics.schemas.ts new file mode 100644 index 0000000..60c3bd8 --- /dev/null +++ b/src/analytics/analytics.schemas.ts @@ -0,0 +1,40 @@ +import { z } from 'zod'; +import { pageSchema } from '../identity/identity.schemas'; +const timestamp = z.iso + .datetime({ offset: true }) + .refine( + (value) => (value.match(/\.(\d+)/)?.[1].length ?? 0) <= 3, + 'Use at most millisecond precision', + ) + .transform((value) => new Date(value)) + .refine( + (value) => value.getUTCFullYear() >= 1 && value.getUTCFullYear() <= 9999, + 'Use UTC years 0001 through 9999', + ); +const fields = { + from: timestamp, + to: timestamp, + currency: z + .string() + .regex(/^[A-Z]{3}$/) + .optional(), +}; +const bounded = (input: { from: Date; to: Date }) => + input.to > input.from && + input.to.getTime() - input.from.getTime() <= 366 * 86400000; +export const analyticsWindowSchema = z + .object(fields) + .strict() + .refine(bounded, { + message: 'Use an increasing window of at most 366 days', + path: ['to'], + }); +export const analyticsVariantsSchema = pageSchema + .extend(fields) + .strict() + .refine(bounded, { + message: 'Use an increasing window of at most 366 days', + path: ['to'], + }); +export type AnalyticsWindow = z.infer; +export type AnalyticsVariants = z.infer; diff --git a/src/analytics/analytics.store.ts b/src/analytics/analytics.store.ts new file mode 100644 index 0000000..a44fd89 --- /dev/null +++ b/src/analytics/analytics.store.ts @@ -0,0 +1,91 @@ +import { Injectable } from '@nestjs/common'; +import { AccessStore } from '../identity/access.store'; +import type { Principal } from '../identity/identity.types'; +import { Prisma } from '../generated/prisma/client'; +import { dailyQuery, variantsQuery } from './analytics-query'; +import type { AnalyticsWindow, AnalyticsVariants } from './analytics.schemas'; + +type DailyRow = { + day: string; + currency: string; + orderCount: number; + openOrderCount: number; + expiredOrderCount: number; + cancelledOrderCount: number; + capturedSubtotal: string; + capturedDiscount: string; + capturedMerchandiseValue: string; + openMerchandiseValue: string; + expiredMerchandiseValue: string; + cancelledMerchandiseValue: string; +}; +type VariantRow = { + currency: string; + variantId: string; + sku: string; + productName: string; + variantName: string; + orderCount: number; + capturedQuantity: string; + openQuantity: string; + expiredQuantity: string; + cancelledQuantity: string; + capturedLineValue: string; +}; +const fixed = (value: string) => new Prisma.Decimal(value).toFixed(2); +const windowView = (input: AnalyticsWindow) => ({ + from: input.from.toISOString(), + to: input.to.toISOString(), + currency: input.currency ?? null, +}); +@Injectable() +export class AnalyticsStore { + constructor(private readonly access: AccessStore) {} + daily(actor: Principal, input: AnalyticsWindow) { + return this.access.mutate( + actor, + 'analytics.read', + async (tx) => { + const now = new Date(); + const rows = await tx.$queryRaw( + dailyQuery(actor.organizationId, input, now), + ); + return { + window: windowView(input), + asOf: now.toISOString(), + days: rows.map((row) => ({ + ...row, + capturedSubtotal: fixed(row.capturedSubtotal), + capturedDiscount: fixed(row.capturedDiscount), + capturedMerchandiseValue: fixed(row.capturedMerchandiseValue), + openMerchandiseValue: fixed(row.openMerchandiseValue), + expiredMerchandiseValue: fixed(row.expiredMerchandiseValue), + cancelledMerchandiseValue: fixed(row.cancelledMerchandiseValue), + })), + }; + }, + false, + ); // Each report is one SQL snapshot; analytics reads need no organization write lock. + } + variants(actor: Principal, input: AnalyticsVariants) { + return this.access.mutate( + actor, + 'analytics.read', + async (tx) => { + const now = new Date(); + const rows = await tx.$queryRaw( + variantsQuery(actor.organizationId, input, now), + ); + return { + window: windowView(input), + asOf: now.toISOString(), + variants: rows.map((row) => ({ + ...row, + capturedLineValue: fixed(row.capturedLineValue), + })), + }; + }, + false, + ); + } +} diff --git a/src/app.module.ts b/src/app.module.ts index 49a01c3..e738d63 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -18,9 +18,11 @@ import { MessagingModule } from './messaging/messaging.module'; import { BlogModule } from './blog/blog.module'; import { SegmentsModule } from './segments/segments.module'; import { ForumModule } from './forum/forum.module'; +import { AnalyticsModule } from './analytics/analytics.module'; @Module({ imports: [ + AnalyticsModule, ForumModule, SegmentsModule, BlogModule, diff --git a/src/identity/permissions.ts b/src/identity/permissions.ts index 526e957..9f540ad 100644 --- a/src/identity/permissions.ts +++ b/src/identity/permissions.ts @@ -1,4 +1,5 @@ export const PERMISSIONS = [ + 'analytics.read', 'forum.read', 'forum.moderate', 'segments.read', diff --git a/test/analytics-policy.spec.ts b/test/analytics-policy.spec.ts new file mode 100644 index 0000000..039d71f --- /dev/null +++ b/test/analytics-policy.spec.ts @@ -0,0 +1,39 @@ +import { + analyticsWindowSchema, + analyticsVariantsSchema, +} from '../src/analytics/analytics.schemas'; + +it('normalizes offsets, bounds windows and validates paginated currency filters', () => { + const input = { + from: '2026-01-01T05:30:00+05:30', + to: '2027-01-01T00:00:00Z', + }; + expect(analyticsWindowSchema.parse(input).from.toISOString()).toBe( + '2026-01-01T00:00:00.000Z', + ); + expect( + analyticsWindowSchema.safeParse({ + from: '2024-01-01T00:00:00Z', + to: '2025-01-01T00:00:00Z', + }).success, + ).toBe(true); + for (const values of [ + { to: input.from }, + { to: '2027-01-03T00:00:00Z' }, + { from: '2026-01-01' }, + { from: '2026-01-01T00:00:00.0001Z' }, + { from: '0000-01-01T00:00:00Z', to: '0000-01-02T00:00:00Z' }, + { currency: 'inr' }, + { organizationId: 'foreign' }, + ]) + expect( + analyticsWindowSchema.safeParse({ ...input, ...values }).success, + ).toBe(false); + expect(analyticsVariantsSchema.parse(input)).toMatchObject({ + limit: 25, + offset: 0, + }); + expect( + analyticsVariantsSchema.safeParse({ ...input, limit: 101 }).success, + ).toBe(false); +}); diff --git a/test/commerce-analytics.spec.ts b/test/commerce-analytics.spec.ts new file mode 100644 index 0000000..abd0a48 --- /dev/null +++ b/test/commerce-analytics.spec.ts @@ -0,0 +1,290 @@ +import { randomUUID } from 'node:crypto'; +import { identityApp, type IdentityApp } from './helpers/identity-app'; +import { secondActor, seedProduct } from './helpers/commerce'; +import { checkoutFixture, couponInput } from './helpers/checkout'; + +describe('date-bounded commerce activity analytics', () => { + let ctx: IdentityApp; + beforeAll(async () => { + ctx = await identityApp(); + }); + afterAll(async () => { + await ctx.close(); + }); + beforeEach(async () => { + await ctx.clearLimits(); + }); + const range = { from: '2026-01-01T00:00:00Z', to: '2026-01-02T00:00:00Z' }; + const report = (kind = 'daily', query: object = range, token = ctx.token) => + ctx + .api() + .get('/api/v1/analytics/commerce/' + kind) + .auth(token, { type: 'bearer' }) + .query(query); + async function seed( + variantId: string, + quantity: number, + status: 'PENDING_PAYMENT' | 'CANCELLED', + expiresAt: Date, + createdAt = new Date('2026-01-01T12:00:00Z'), + currency = 'INR', + extraVariantId?: string, + ) { + const value = (quantity / 10).toFixed(2); + const subtotal = ((quantity / 10) * (extraVariantId ? 2 : 1)).toFixed(2); + return ctx.db.order.create({ + data: { + userId: ctx.owner.userId, + organizationId: ctx.owner.organizationId, + currency, + status, + subtotal, + discount: '0.00', + merchandiseTotal: subtotal, + addressSnapshot: { recipient: 'Private recipient' }, + idempotencyKey: randomUUID(), + requestHash: 'a'.repeat(64), + createdAt, + expiresAt, + lines: { + create: [variantId, ...(extraVariantId ? [extraVariantId] : [])].map( + (id) => ({ + variantId: id, + sku: 'FROZEN-SKU', + productName: 'Frozen product', + variantName: 'Frozen variant', + quantity, + unitPrice: '0.10', + lineTotal: value, + }), + ), + }, + }, + }); + } + it('aggregates exact currency totals and separates open, expired and cancelled states', async () => { + const item = await seedProduct(ctx, true); + const future = new Date(Date.now() + 3600000); + await seed(item.variant.id, 1, 'PENDING_PAYMENT', future); + await seed( + item.variant.id, + 2, + 'PENDING_PAYMENT', + new Date('2026-01-01T13:00:00Z'), + ); + await seed(item.variant.id, 3, 'CANCELLED', future); + await seed( + item.variant.id, + 4, + 'PENDING_PAYMENT', + future, + new Date('2026-01-01T12:00:00Z'), + 'USD', + ); + const result = await report().expect(200); + expect(result.body.days).toEqual([ + { + day: '2026-01-01', + currency: 'INR', + orderCount: 3, + openOrderCount: 1, + expiredOrderCount: 1, + cancelledOrderCount: 1, + capturedSubtotal: '0.60', + capturedDiscount: '0.00', + capturedMerchandiseValue: '0.60', + openMerchandiseValue: '0.10', + expiredMerchandiseValue: '0.20', + cancelledMerchandiseValue: '0.30', + }, + { + day: '2026-01-01', + currency: 'USD', + orderCount: 1, + openOrderCount: 1, + expiredOrderCount: 0, + cancelledOrderCount: 0, + capturedSubtotal: '0.40', + capturedDiscount: '0.00', + capturedMerchandiseValue: '0.40', + openMerchandiseValue: '0.40', + expiredMerchandiseValue: '0.00', + cancelledMerchandiseValue: '0.00', + }, + ]); + expect(JSON.stringify(result.body)).not.toMatch( + /recipient|address|userId|requestHash|idempotencyKey|revenue/, + ); + const usd = await report('daily', { ...range, currency: 'USD' }).expect( + 200, + ); + expect(usd.body.days).toHaveLength(1); + expect(usd.body.days[0].currency).toBe('USD'); + }); + it('uses UTC buckets and an inclusive start/exclusive end without joining line fanout', async () => { + const item = await seedProduct(ctx, true); + const extra = await seedProduct(ctx, true); + await seed( + item.variant.id, + 1, + 'PENDING_PAYMENT', + new Date(Date.now() + 3600000), + new Date('2026-02-01T00:00:00Z'), + 'INR', + extra.variant.id, + ); + await seed( + item.variant.id, + 1, + 'PENDING_PAYMENT', + new Date(Date.now() + 3600000), + new Date('2026-02-02T00:00:00Z'), + ); + const input = { + from: '2026-02-01T05:30:00+05:30', + to: '2026-02-02T05:30:00+05:30', + }; + const result = await report('daily', input).expect(200); + expect(result.body.window).toMatchObject({ + from: '2026-02-01T00:00:00.000Z', + to: '2026-02-02T00:00:00.000Z', + }); + expect(result.body.days).toHaveLength(1); + expect(result.body.days[0]).toMatchObject({ + day: '2026-02-01', + orderCount: 1, + capturedMerchandiseValue: '0.20', + }); + await report('daily', { + from: '2026-02-03T00:00:00Z', + to: '2026-02-04T00:00:00Z', + }) + .expect(200) + .then((r) => expect(r.body.days).toEqual([])); + }); + it('preserves frozen variant descriptors and paginates captured demand without calling it sales', async () => { + const item = await seedProduct(ctx, true); + const when = new Date('2026-03-01T12:00:00Z'); + const future = new Date(Date.now() + 3600000); + await seed(item.variant.id, 1, 'PENDING_PAYMENT', future, when); + await seed( + item.variant.id, + 2, + 'PENDING_PAYMENT', + new Date('2026-03-01T13:00:00Z'), + when, + ); + await seed(item.variant.id, 3, 'CANCELLED', future, when); + await seed(item.variant.id, 4, 'PENDING_PAYMENT', future, when, 'USD'); + const variantRange = { + from: '2026-03-01T00:00:00Z', + to: '2026-03-02T00:00:00Z', + }; + const result = await report('variants', { + ...variantRange, + limit: 1, + }).expect(200); + expect(result.body.variants).toHaveLength(1); + expect(result.body.variants[0]).toMatchObject({ + currency: 'INR', + sku: 'FROZEN-SKU', + productName: 'Frozen product', + variantName: 'Frozen variant', + orderCount: 3, + capturedQuantity: '6', + openQuantity: '1', + expiredQuantity: '2', + cancelledQuantity: '3', + capturedLineValue: '0.60', + }); + const id = result.body.variants[0].variantId; + await ctx.db.productVariant.update({ + where: { id }, + data: { name: 'Renamed variant', price: '9.99' }, + }); + const updated = await report('variants', { + ...variantRange, + limit: 1, + }).expect(200); + expect(updated.body.variants).toEqual(result.body.variants); + const second = await report('variants', { + ...variantRange, + limit: 1, + offset: 1, + }).expect(200); + expect(second.body.variants[0].currency).toBe('USD'); + }); + it('reports real checkout discounts once and reflects later cancellation', async () => { + const f = await checkoutFixture(ctx); + const coupon = couponInput(); + await ctx + .api() + .post('/api/v1/coupons') + .auth(ctx.token, { type: 'bearer' }) + .send(coupon) + .expect(201); + const checkoutInput = { ...f.input, couponCode: coupon.code }; + const created = await ctx + .api() + .post('/api/v1/checkout') + .auth(f.actor.token, { type: 'bearer' }) + .send(checkoutInput) + .expect(201); + await ctx + .api() + .post('/api/v1/checkout') + .auth(f.actor.token, { type: 'bearer' }) + .send(checkoutInput) + .expect(201); + const when = new Date(created.body.createdAt); + const input = { + from: when.toISOString(), + to: new Date(when.getTime() + 1).toISOString(), + }; + const first = await report('daily', input).expect(200); + expect(first.body.days[0]).toMatchObject({ + orderCount: 1, + capturedSubtotal: '998.00', + capturedDiscount: '99.80', + capturedMerchandiseValue: '898.20', + }); + await ctx + .api() + .post('/api/v1/orders/' + created.body.id + '/cancel') + .auth(f.actor.token, { type: 'bearer' }) + .expect(201); + expect( + (await report('daily', input).expect(200)).body.days[0], + ).toMatchObject({ + orderCount: 1, + cancelledOrderCount: 1, + cancelledMerchandiseValue: '898.20', + openOrderCount: 0, + }); + }); + it('enforces analytics permission, scope, date limits and strict query input', async () => { + const customer = await secondActor(ctx); + await report('daily', range, customer.token).expect(403); + const foreign = await secondActor(ctx, false, ['analytics.read']); + expect( + (await report('daily', range, foreign.token).expect(200)).body.days, + ).toEqual([]); + const staff = await secondActor(ctx, true, ['analytics.read']); + await report('daily', range, staff.token).expect(200); + await ctx + .api() + .get('/api/v1/analytics/commerce/daily') + .query(range) + .expect(401); + for (const query of [ + { from: range.from }, + { ...range, to: range.from }, + { ...range, to: '2027-01-03T00:00:00Z' }, + { ...range, currency: 'inr' }, + { ...range, organizationId: foreign.organizationId }, + ]) + await report('daily', query).expect(400); + await report('variants', { ...range, limit: 101 }).expect(400); + await report('variants', { ...range, offset: -1 }).expect(400); + }); +}); -- 2.40.1