27 lines
5.9 KiB
Markdown
27 lines
5.9 KiB
Markdown
# 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.
|