Compare commits
47 Commits
feat/moder
...
main
| Author | SHA1 | Date |
|---|---|---|
|
|
b4f61ff65e | |
|
|
58d3f55b35 | |
|
|
b81e8ddad2 | |
|
|
38f58ee3b1 | |
|
|
1b7d7362de | |
|
|
74c129ba6c | |
|
|
a229d6a657 | |
|
|
29f0a2b7b8 | |
|
|
b610ef71f2 | |
|
|
a83a0c0742 | |
|
|
04e7f1f9b6 | |
|
|
6c72f8ce96 | |
|
|
e3ee5ef019 | |
|
|
07966121fa | |
|
|
4c1af3262b | |
|
|
549f87f078 | |
|
|
5f729571cb | |
|
|
83f2584133 | |
|
|
6da3aaad19 | |
|
|
2e605262a9 | |
|
|
727968729c | |
|
|
28af830548 | |
|
|
0ec26dc532 | |
|
|
fa0073e109 | |
|
|
779496cc15 | |
|
|
0f4e73f06e | |
|
|
7bcce6fe4d | |
|
|
9f12fc686e | |
|
|
ceb881e30a | |
|
|
8431fbca4b | |
|
|
c8cf3515ba | |
|
|
fae73b38b0 | |
|
|
d60d5d79d0 | |
|
|
600bed2ada | |
|
|
5a8087b51a | |
|
|
eb02a059b8 | |
|
|
16296e5e22 | |
|
|
93db8564a7 | |
|
|
eb37578e1d | |
|
|
7f1937dc54 | |
|
|
5ac4e20ccf | |
|
|
fa38e1f491 | |
|
|
e30fdae2ea | |
|
|
26225c4b9e | |
|
|
490c3a0155 | |
|
|
d9917b9ee1 | |
|
|
0d3e219fd1 |
|
|
@ -23,15 +23,16 @@ steps:
|
||||||
- name: Deploy
|
- name: Deploy
|
||||||
image: appleboy/drone-ssh
|
image: appleboy/drone-ssh
|
||||||
settings:
|
settings:
|
||||||
host: api.midastix.com
|
host: manicandles-backend.midastix.com
|
||||||
username: manicandle-backend
|
username: manicandle-backend
|
||||||
key:
|
key:
|
||||||
from_secret: server_ssh_pkey
|
from_secret: server_ssh_pkey
|
||||||
port: 22
|
port: 22
|
||||||
command_timeout: 3m
|
command_timeout: 3m
|
||||||
script:
|
script:
|
||||||
|
- set -e
|
||||||
- echo "Deploying manicandle-backend"
|
- echo "Deploying manicandle-backend"
|
||||||
- sudo /opt/deployable/manicandle-backend/docker/deploy.sh
|
- sudo -n /opt/deployable/manicandle-backend/docker/deploy.sh
|
||||||
- echo "Deployment completed"
|
- echo "Deployment completed"
|
||||||
when:
|
when:
|
||||||
branch:
|
branch:
|
||||||
|
|
|
||||||
|
|
@ -14,5 +14,10 @@ RECOVERY_TTL_MINUTES=15
|
||||||
# RECOVERY_URL=https://shop.example.com/reset
|
# RECOVERY_URL=https://shop.example.com/reset
|
||||||
DATABASE_POOL_SIZE=10
|
DATABASE_POOL_SIZE=10
|
||||||
|
|
||||||
|
# Reverse proxies whose X-Forwarded-For is trusted for client IPs (rate limits).
|
||||||
|
# Comma-separated IPs, CIDRs, or loopback/linklocal/uniquelocal. Empty = trust none.
|
||||||
|
# Behind the local Nginx plus the frontend server's Nginx, list both hops, e.g.:
|
||||||
|
# TRUST_PROXY=loopback,172.17.0.0/16,<frontend server IP>
|
||||||
|
|
||||||
# Optional; defaults to true only in development.
|
# Optional; defaults to true only in development.
|
||||||
# SWAGGER_ENABLED=true
|
# SWAGGER_ENABLED=true
|
||||||
|
|
|
||||||
|
|
@ -7,27 +7,47 @@ on:
|
||||||
jobs:
|
jobs:
|
||||||
quality:
|
quality:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
container: node:24.15-bookworm
|
||||||
|
timeout-minutes: 30
|
||||||
|
env:
|
||||||
|
DATABASE_URL: postgresql://postgres:postgres@127.0.0.1:5432/postgres
|
||||||
|
TEST_DATABASE_URL: ''
|
||||||
|
steps:
|
||||||
|
- uses: https://github.com/actions/checkout@v4
|
||||||
|
- name: Install locked dependencies
|
||||||
|
run: npm install --global pnpm@11.19.0 && pnpm install --frozen-lockfile
|
||||||
|
- name: Audit production dependencies
|
||||||
|
run: pnpm security:audit
|
||||||
|
- name: Generate Prisma client
|
||||||
|
run: pnpm db:generate
|
||||||
|
- name: Validate embedded migration upgrade and schema drift
|
||||||
|
run: pnpm db:test
|
||||||
|
- name: Formatting, types, tooling, coverage and build
|
||||||
|
run: pnpm check
|
||||||
|
native-postgres:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container: node:24.15-bookworm
|
||||||
|
timeout-minutes: 15
|
||||||
services:
|
services:
|
||||||
postgres:
|
postgres:
|
||||||
image: postgres:17
|
image: postgres:17
|
||||||
env:
|
env:
|
||||||
POSTGRES_USER: mani
|
POSTGRES_USER: mani
|
||||||
POSTGRES_PASSWORD: ci_only_password
|
POSTGRES_PASSWORD: ${{ secrets.CI_POSTGRES_PASSWORD }}
|
||||||
POSTGRES_DB: mani_ci
|
POSTGRES_DB: mani_ci
|
||||||
options: >-
|
options: >-
|
||||||
--health-cmd "pg_isready -U mani -d mani_ci"
|
--health-cmd "pg_isready -U mani -d mani_ci"
|
||||||
--health-interval 5s --health-timeout 5s --health-retries 10
|
--health-interval 5s --health-timeout 5s --health-retries 10
|
||||||
env:
|
env:
|
||||||
DATABASE_URL: postgresql://mani:ci_only_password@postgres:5432/mani_ci
|
DATABASE_URL: postgresql://mani:${{ secrets.CI_POSTGRES_PASSWORD }}@postgres:5432/mani_ci
|
||||||
TEST_DATABASE_URL: postgresql://mani:ci_only_password@postgres:5432/mani_ci
|
TEST_DATABASE_URL: postgresql://mani:${{ secrets.CI_POSTGRES_PASSWORD }}@postgres:5432/mani_ci
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: https://github.com/actions/checkout@v4
|
||||||
- uses: actions/setup-node@v4
|
- name: Install locked dependencies
|
||||||
with:
|
run: npm install --global pnpm@11.19.0 && pnpm install --frozen-lockfile
|
||||||
node-version: '24'
|
- name: Generate Prisma client
|
||||||
- run: npm install --global pnpm@11.19.0
|
run: pnpm db:generate
|
||||||
- run: pnpm install --frozen-lockfile
|
- name: Validate native migration upgrade and schema drift
|
||||||
- run: pnpm security:audit
|
run: node scripts/verify-migrations.mjs
|
||||||
- run: pnpm db:generate
|
- name: Require native concurrency tests without skips
|
||||||
- run: node scripts/verify-migrations.mjs
|
run: pnpm test:native
|
||||||
- run: pnpm check
|
|
||||||
|
|
|
||||||
12
README.md
12
README.md
|
|
@ -88,3 +88,15 @@ 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).
|
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).
|
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).
|
||||||
|
|
||||||
|
Accounting source events: see [Phase 5D API guide](docs/accounting-source-feed-api.md).
|
||||||
|
|
||||||
|
Indicative batch material contribution: see [Phase 5E API guide](docs/batch-contribution-api.md).
|
||||||
|
|
||||||
|
Bounded order expiry automation: see [Phase 5F API guide](docs/order-expiry-workflow-api.md).
|
||||||
|
|
||||||
|
Production verification gates and launch procedure: see [Phase 6A runbook](docs/production-readiness.md).
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,30 @@
|
||||||
|
# Accounting source feed (Phase 5D)
|
||||||
|
|
||||||
|
This provider-independent contract exposes recorded supplier invoices, supplier payments and corrections, plus external partner receipts and corrections. It supplies immutable source facts for future reconciliation/adapters. It does not assign a chart of accounts, generate journal debits/credits, post to an external system, or infer retail paid sales. Source records, source approvals, and their existing audit trail remain unchanged.
|
||||||
|
|
||||||
|
`GET /api/v1/accounting/source-events` requires `accounting.read`, rechecked against the live session and caller's organization in the read transaction. Existing system Owners gain the permission; custom roles must grant it explicitly. Other finance/analytics permissions do not implicitly grant access to this feed.
|
||||||
|
|
||||||
|
Required `from` and `to` reuse the bounded analytics datetime contract: explicit UTC/offsets, at most millisecond precision, supported normalized years, increasing by at most 366 elapsed days. Start is inclusive and end exclusive. Selection uses each source record's **recorded timestamp**, not its invoice/payment business date. Optional `currency` is a three-uppercase-letter filter, `kind` one of the six types below, and `limit` an integer 1–100 (default 25). Extra fields, offset pagination, invalid windows/types, and malformed/incompatible cursors return 400; absent sessions return 401 and insufficient permission 403.
|
||||||
|
|
||||||
|
| Event type | Operation | Amount and relationship |
|
||||||
|
| --------------------------- | --------- | -------------------------------------------------------------------------------------- |
|
||||||
|
| `SUPPLIER_INVOICE` | `RECORD` | Captured payable total, merchandise/tax/shipping components; invoice and supplier IDs. |
|
||||||
|
| `SUPPLIER_INVOICE_VOID` | `VOID` | Original captured invoice amounts; links to its original invoice event. |
|
||||||
|
| `SUPPLIER_PAYMENT` | `RECORD` | Captured external payment amount; related invoice and supplier IDs. |
|
||||||
|
| `SUPPLIER_PAYMENT_REVERSAL` | `REVERSE` | Original payment amount; links to that payment event. |
|
||||||
|
| `PARTNER_RECEIPT` | `RECORD` | Captured external partner receipt; related partner order and business-account IDs. |
|
||||||
|
| `PARTNER_RECEIPT_REVERSAL` | `REVERSE` | Original receipt amount; links to that receipt event. |
|
||||||
|
|
||||||
|
The response is `{ schemaVersion: 1, window, events, nextCursor }`. Each event contains `eventType`, `operation`, `sourceId`, `eventKey`, `occurredAt`, nullable `businessDate`, `currency`, positive two-decimal `amount`, nullable component amounts, `relatedId`/`relatedType`, `counterpartyId`/`counterpartyType`, and nullable `reversesEventKey`. `eventKey` is `<eventType>:<sourceId>`, unique within the organization. A correction can use the same source UUID under a different event type. Every original remains present after later void/reversal, so a consumer can process both original and correcting facts rather than silently losing history.
|
||||||
|
|
||||||
|
Invoice/payment/receipt business dates are copied from their source. Corrections have no separately recorded business date and return null; their recording timestamp and original-event link remain available. All amounts remain positive; `operation` expresses the source correction without assuming a provider's signed-value/debit/credit convention. Invoice tax/shipping are captured charges, not a tax treatment decision. Payment reversal records invalidate an external payment entry and are not proof of a bank refund. Currencies are retained separately, with no conversion or combined amount.
|
||||||
|
|
||||||
|
Results are ordered by recorded timestamp, event type using deterministic C collation, then UUID. Fetch the next page by sending the returned opaque `cursor` with the same organization/window/currency/type; page size may change. The token validates a timestamp/type/UUID position and a filter/scope fingerprint. It is a pagination hint, not an authorization credential; every query independently enforces caller scope. `limit + 1` lookahead determines whether another cursor is needed. Missing/empty pages return `nextCursor: null`, and tied timestamps remain traversable by type/UUID.
|
||||||
|
|
||||||
|
**Synchronization limit:** pages are independent live database snapshots, not a durable change-data-capture stream or exactly-once export. A transaction committed later can have an earlier recording timestamp and arrive behind a consumed cursor. Consumers must repeatedly scan overlapping closed windows and deduplicate by `(organization, eventKey)`, including correction events, before advancing their own reconciliation checkpoint. Do not treat the last page as certification that a period can never gain a late record. Persistent export batches/acknowledgements can follow when a concrete accounting provider and delivery guarantees are selected.
|
||||||
|
|
||||||
|
The feed omits invoice numbers, bank/payment references, methods, contact/profile/address data, staff reasons/IDs, evidence files, hashes, and request keys. Stable technical document/counterparty IDs allow explicit external mappings later. Only recorded supplier liabilities and external receipt/payment facts are included; retail pending orders, quotes, production estimates and unfinalized tax/shipping are not invented as accounting entries.
|
||||||
|
|
||||||
|
One parameterized UNION query supplies each page's snapshot without taking the organization write lock. Scoped joins protect every correction/original relationship. Six additive source timestamp indexes support bounded scans; no export table, queue, provider credential, CSV conversion, or new dependency is introduced. Deploy the indexes/Owner-permission migration before the application, scheduling index builds appropriately for large source tables. Older code ignores them on rollback. Preserve financial records, corrections and audit evidence; historical migrations are not edited.
|
||||||
|
|
||||||
|
Verification covers all six source types, original/correction coexistence, exact positive amounts/components, original-event links, recording-time boundaries versus business dates, deterministic tie pagination, filter/scope-bound cursors, malformed tokens, private-field omission, permission/organization isolation, strict limits, and migration drift. External ledger posting, chart-of-account/tax mapping, durable synchronization and native multi-connection PostgreSQL CI remain outside this milestone.
|
||||||
|
|
@ -0,0 +1,30 @@
|
||||||
|
# Indicative batch contribution (Phase 5E)
|
||||||
|
|
||||||
|
Staff can compare a completed batch's sealed standard material/packaging cost with an explicit net unit-price assumption. The report reuses immutable actual-consumption/wastage and packaging cost evidence from Phase 2M, including frozen standard rate revisions. It does not infer costs from current catalog prices, pending orders, or unrelated batches.
|
||||||
|
|
||||||
|
`GET /api/v1/profitability/batches/:batchId?currency=INR&unitNetPrice=5.00` requires `profitability.read`. The active session, user/organization scope, and permission are rechecked inside the read transaction. `cost.read` alone does not grant access, and a profitability-only reader can see this summary without receiving detailed material/rate evidence. Existing system Owners gain the new permission; custom roles remain explicit.
|
||||||
|
|
||||||
|
Both query fields are required. Currency uses the existing supported currency set and must match the sealed snapshot; there is no FX conversion. `unitNetPrice` is a nonnegative two-decimal string up to `9999999999.99`, interpreted as a staff-selected selling-price assumption after discounts and excluding selling taxes/freight charges. No price is taken automatically from the catalog or an order. Negative, imprecise, oversized, missing, or extra fields return 400. Missing sessions return 401, insufficient permission 403, and currency mismatch `PROFITABILITY_CURRENCY` (409).
|
||||||
|
|
||||||
|
Only a sealed cost snapshot attached to a completed batch in the caller's organization is eligible. Missing, unsealed, unknown and foreign-scope evidence returns `BATCH_COST_NOT_FOUND` (404). Snapshot creation stays in the existing cost workflow; this read does not seal, recost, or rewrite any batch. The scoped response includes batch/variant/snapshot IDs, seal date, currency, good output quantity, explicit price, production/packaging subtotals, and `basis: "SEALED_BATCH_STANDARD_MATERIAL_COST"`.
|
||||||
|
|
||||||
|
The returned calculations are:
|
||||||
|
|
||||||
|
| Field | Definition |
|
||||||
|
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
|
||||||
|
| `comparisonNetValue` | Price assumption multiplied by all good units. |
|
||||||
|
| `standardMaterialCost` | Sealed production plus packaging material total, including recorded wastage. |
|
||||||
|
| `materialContribution` | Comparison value minus sealed material cost; negative amounts are retained. |
|
||||||
|
| `contributionRateBps` | Contribution/value × 10,000, nearest integer with half away from zero; signed integer string, or null when comparison value is zero. |
|
||||||
|
| `breakEvenUnitNetPrice` | Sealed cost divided by good units, rounded **up** to a whole cent; null when no good units exist. |
|
||||||
|
| `comparisonState` | `ABOVE_MATERIAL_BREAK_EVEN`, `AT_MATERIAL_BREAK_EVEN`, `BELOW_MATERIAL_BREAK_EVEN`, or `NO_GOOD_OUTPUT`. |
|
||||||
|
|
||||||
|
Money uses exact integer cents and two-decimal strings. Scenario totals can exceed the per-order money limit without floating-point loss. Basis-point rates use strings so large negative values remain exact. A zero-price scenario returns the signed material shortfall and null rate. A batch with zero good output returns zero comparison value, negative captured material cost, null break-even/rate, and `NO_GOOD_OUTPUT`, avoiding division by zero. Break-even is calculated from the full batch cost; rounding a display unit cost down must not understate it.
|
||||||
|
|
||||||
|
The summary lists excluded categories: labour, overhead, fulfillment, channel fees, marketing and finance. These costs are not recorded here and are not silently estimated or treated as zero in a net-profit claim. The report is an indicative **material contribution scenario**, not realized revenue, recognized net profit, a complete margin statement, cost-of-goods-sold allocation, or evidence that all good units were sold. No sale-to-batch attribution, tax treatment, inventory valuation policy, or external ledger posting is invented.
|
||||||
|
|
||||||
|
Sealed rate changes and later catalog repricing do not change cost evidence or the chosen price assumption. Staff must supply a new price to evaluate another scenario. No customer data, supplier contact/evidence, creator identities, hashes or keys are returned. No audit event or report table is created for this read. Full cost lines remain behind their existing permission.
|
||||||
|
|
||||||
|
Deploy the additive Owner-permission migration before the application. No schema table, dependency, pricing policy, source amount or historical migration changes. Older code ignores the permission on rollback. This branch is stacked on the pushed Phase 5D accounting source branch; merge that prerequisite first or review the stacked diff accordingly.
|
||||||
|
|
||||||
|
Verification covers positive/negative/zero contribution, exact large values, upward break-even rounding, signed basis-point rounding, zero price/output, sealed evidence, frozen rates and ignored catalog changes, explicit currency matching, independent permission, organization isolation, strict price input and migration drift. Realized profitability, complete expense/COGS attribution, margin dashboards and native multi-connection PostgreSQL checks remain separate work.
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -25,3 +25,13 @@ Stock quantities are integers. Opening stock is an adjustment. Adjustments requi
|
||||||
Availability equals on-hand stock minus unexpired active reservations. Stock row locks serialize changes. Expired holds stop consuming availability and cannot be committed. Release and commit are idempotent. Commit decrements stock and appends one ledger entry in the same transaction. A database trigger rejects ledger updates/deletes.
|
Availability equals on-hand stock minus unexpired active reservations. Stock row locks serialize changes. Expired holds stop consuming availability and cannot be committed. Release and commit are idempotent. Commit decrements stock and appends one ledger entry in the same transaction. A database trigger rejects ledger updates/deletes.
|
||||||
|
|
||||||
Existing system roles receive permissions through migration; custom roles require explicit grants. This phase covers finished goods. Checkout/orders and pricing snapshots follow in Phase 1D; procurement and production in Phase 2.
|
Existing system roles receive permissions through migration; custom roles require explicit grants. This phase covers finished goods. Checkout/orders and pricing snapshots follow in Phase 1D; procurement and production in Phase 2.
|
||||||
|
|
||||||
|
## Product photos
|
||||||
|
|
||||||
|
| Method | Path | Permission | Request / result |
|
||||||
|
| ------ | -------------------------------------------------------- | ----------------- | -------------------------------------------------------------------- |
|
||||||
|
| POST | /products/:id/images | catalog.manage | multipart `file`: JPEG, PNG or WebP up to 2 MiB → id, mimeType, size |
|
||||||
|
| DELETE | /products/:id/images/:imageId | catalog.manage | 204; 404 if missing or out of scope |
|
||||||
|
| GET | /storefront/:organizationId/products/:id/images/:imageId | Public; throttled | Image bytes for published products only; cached publicly for one day |
|
||||||
|
|
||||||
|
The file signature must match the declared type, so renamed scripts or SVGs are rejected. A product holds at most 8 photos, ordered by upload; the first is the main photo. Storefront lists include `images` with the main photo ID; storefront and admin product details include all photos. Images are immutable rows; replace one by deleting and uploading again. Archived products cannot change photos.
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,13 @@
|
||||||
# Phase 1B: identity and access API
|
# Phase 1B: identity and access API
|
||||||
|
|
||||||
All paths below start with `/api/v1`. Protected endpoints require `Authorization: Bearer <accessToken>`. There are no public account-creation or owner-creation endpoints. Staff account provisioning is available to authorized administrators; storefront self-registration and verified email onboarding can be added with the customer milestone.
|
All paths below start with `/api/v1`. Protected endpoints require `Authorization: Bearer <accessToken>`. Customers create their own accounts with `/auth/register`; there is no public owner-creation endpoint. Staff accounts are provisioned by authorized administrators. Email verification is not yet implemented.
|
||||||
|
|
||||||
## Endpoints
|
## Endpoints
|
||||||
|
|
||||||
| Method | Path | Permission | Request / result |
|
| Method | Path | Permission | Request / result |
|
||||||
| ------ | ---------------------- | ------------------ | ------------------------------------------------------------------- |
|
| ------ | ---------------------- | ------------------ | ------------------------------------------------------------------------------------------------ |
|
||||||
| POST | /auth/login | Public; throttled | organizationId, email, password → accessToken, tokenType, expiresAt |
|
| POST | /auth/login | Public; throttled | organizationId, email, password → accessToken, tokenType, expiresAt |
|
||||||
|
| POST | /auth/register | Public; throttled | organizationId, email, name, password → active customer + session; 409 duplicate; 10/hour per IP |
|
||||||
| GET | /auth/me | Authenticated | userId, organizationId, sessionId, effective permissions |
|
| GET | /auth/me | Authenticated | userId, organizationId, sessionId, effective permissions |
|
||||||
| POST | /auth/logout | Authenticated | Revoke current session; 204 |
|
| POST | /auth/logout | Authenticated | Revoke current session; 204 |
|
||||||
| POST | /auth/logout-all | Authenticated | Revoke all current user sessions; 204 |
|
| POST | /auth/logout-all | Authenticated | Revoke all current user sessions; 204 |
|
||||||
|
|
@ -36,7 +37,7 @@ Example login:
|
||||||
|
|
||||||
## Access rules
|
## Access rules
|
||||||
|
|
||||||
Organization scope comes from the persisted session, never from an administration request body. Email uniqueness is per organization and normalized to lowercase. New accounts have no roles and cannot sign in until approved. Multiple roles combine their permissions. Permissions are reloaded on every request and rechecked inside administration transactions.
|
Organization scope comes from the persisted session, never from an administration request body. Email uniqueness is per organization and normalized to lowercase. Staff-created accounts have no roles and cannot sign in until approved. Self-registered customers are active immediately with no roles: they can use their own cart, checkout, addresses, orders and wishlist, and nothing that requires a permission. Multiple roles combine their permissions. Permissions are reloaded on every request and rechecked inside administration transactions.
|
||||||
|
|
||||||
Administrators cannot grant permissions they do not hold, modify a more privileged role, change their own role assignments, assign the system Owner role, or change the owner's approval state. A single installation owner is created by the CLI; API-supplied owner flags are rejected. Suspending a user revokes sessions and recovery tokens; reactivation does not restore them.
|
Administrators cannot grant permissions they do not hold, modify a more privileged role, change their own role assignments, assign the system Owner role, or change the owner's approval state. A single installation owner is created by the CLI; API-supplied owner flags are rejected. Suspending a user revokes sessions and recovery tokens; reactivation does not restore them.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,28 @@
|
||||||
|
# Bounded order expiry workflow (Phase 5F)
|
||||||
|
|
||||||
|
An authenticated operator/service account can run a bounded expiry sweep through HTTP or the scheduler-friendly one-shot command. The workflow selects only the caller's organization, `PENDING_PAYMENT` orders whose expiry is at/before one captured server time, then uses the same cancellation routine as the existing customer/staff order endpoints. Live payments remain deferred; future paid states are not selected.
|
||||||
|
|
||||||
|
| Method | Route | Access |
|
||||||
|
| ------ | ------------------------------------- | ------------------------------------------------------------------- |
|
||||||
|
| POST | `/api/v1/workflows/order-expiry/runs` | Both `workflows.run` and `orders.manage`; execute one atomic sweep. |
|
||||||
|
| GET | `/api/v1/workflows/order-expiry/runs` | `workflows.read`; paginated immutable run history. |
|
||||||
|
|
||||||
|
POST body is `{ "limit": 10, "idempotencyKey": "<uuid>" }`. Limit defaults to 10, ranges 1–25, and bounds orders per transaction. Invalid/extra fields and organization overrides return 400; missing sessions return 401; missing either execution permission returns 403. Both execution permissions and active session are checked again inside the organization-locked transaction. Existing system Owners receive `workflows.read`/`workflows.run`; custom roles remain explicit.
|
||||||
|
|
||||||
|
Orders are considered in expiry/UUID order. The workflow locks all affected stock IDs in deterministic order before shared cancellation logic releases active order-bound holds, stores `CANCELLED`, and enqueues the existing `order.cancelled` event. Physical on-hand stock is unchanged. Already cancelled orders, future pending orders, foreign organizations, and standalone reservations are not selected. Existing reads already exclude expired holds from availability; this sweep finalizes their stored status and audit evidence.
|
||||||
|
|
||||||
|
Audit action `order.expired` distinguishes workflow expiry from manual `order.cancelled`. A successful sweep appends `workflow.order_expiry_completed` and one immutable run record with operator ID, limit, evaluation/completion times and processed order IDs/count. Customer-visible expired orders become stored cancellations; detailed cause remains in the run/audit trail. No money, order prices, addresses, coupons or stock ledger quantities are rewritten. Existing cancellation retry behavior remains unchanged.
|
||||||
|
|
||||||
|
Run keys are organization-scoped. Exact retries return the original result and do not reselect newer expired orders or duplicate holds/events/audits. Changing the limit with the same key returns `IDEMPOTENCY_CONFLICT` (409). New invocations use fresh keys, including empty successful runs. A failure anywhere before commit rolls back every cancellation/release/event and the run record; there is no partial-success report. Failed attempts are not persisted as successful history and can be retried with the same key.
|
||||||
|
|
||||||
|
History contains technical IDs, operator ID, parameters and result counts; tokens, customer profiles, addresses, request hashes and idempotency keys are absent. Existing pagination defaults/maxima apply. Native guards freeze run history, validate limits/hash/time order and ensure listed IDs are distinct, scoped cancelled orders with expired evidence.
|
||||||
|
|
||||||
|
After `pnpm build`, `pnpm workflows:expire` opens an application context, authenticates `WORKFLOW_TOKEN`, and invokes the same permission-checked workflow. Supply a normal active session token for a dedicated account with execution permissions. Optional `WORKFLOW_LIMIT` defaults to 10; optional UUID `WORKFLOW_RUN_KEY` fixes retry identity, otherwise a new UUID is generated. Result JSON contains only the safe run view; errors omit credentials and exit nonzero. Connections close on success/failure. Session expiry, account suspension and permission revocation apply to the command normally.
|
||||||
|
|
||||||
|
Configure the chosen deployment's scheduler to invoke the one-shot command periodically using a secret-managed token and non-overlapping job policy. Keep the same run key when retrying an uncertain attempt and rotate it for the next scheduled invocation. Drain larger backlogs with repeated bounded invocations; timeout/failure remains atomic, so reduce the batch size if needed. This repository does not install or enable a live scheduler, store a bypass/service password, refresh credentials, or create recurring Codex tasks.
|
||||||
|
|
||||||
|
The existing organization lock serializes sweeps and cancellation/catalog work; stock locks also coordinate independent inventory transactions. The batch limit bounds work but a busy organization can still experience lock latency; use a lower limit/cadence, then dedicated job workers if measured load requires it. No generic rule engine, configurable financial posting, stock reorder, production planning, standalone reservation cleanup, message delivery or ledger integration is enabled.
|
||||||
|
|
||||||
|
Deploy the additive run-table, pending-expiry scan index and Owner-permission migration before the application. Source order snapshots, previous migrations and historical financial records remain unchanged. Older code ignores run history, but cannot reopen orders already cancelled by a successful sweep. This branch is stacked on the pushed accounting and contribution branches; merge prerequisites first. Native multi-connection CI and deployment scheduler operation remain pending.
|
||||||
|
|
||||||
|
Verification covers eligible selection, untouched future/foreign orders, hold release/on-hand preservation, exact/conflicting retries, competing sweeps, run-history immutability, transaction rollback, dual permissions/live account status, strict limits, authenticated CLI/resource closure, schema drift and existing manual checkout/cancellation regressions.
|
||||||
|
|
@ -0,0 +1,42 @@
|
||||||
|
# Phase 6A: release gates and production readiness
|
||||||
|
|
||||||
|
This milestone prepares repeatable verification and the launch procedure. It does not deploy the service or establish that the production environment is ready.
|
||||||
|
|
||||||
|
## Required merge checks
|
||||||
|
|
||||||
|
The `Backend quality` workflow runs on feature/fix pushes, main pushes and pull requests targeting main. Two independent jobs must pass:
|
||||||
|
|
||||||
|
| Job | Evidence |
|
||||||
|
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||||
|
| `quality` | Frozen dependency installation, production dependency audit, embedded migration deployment/status/drift, immutable migration hashes, formatting, Prisma validation, TypeScript, tooling tests, coverage and compilation. |
|
||||||
|
| `native-postgres` | PostgreSQL 17 migration deployment/status/drift and the existing checkout, inventory, recovery and outbox concurrency tests. The gate fails on missing configuration, failures, empty results or any skipped/todo test. |
|
||||||
|
|
||||||
|
Configure a Docker-capable Gitea runner with the existing `ubuntu-latest` label, able to pull Node/PostgreSQL images, GitHub checkout and npm packages. Both jobs explicitly run in `node:24.15-bookworm`; the native job reaches its database by the `postgres` service hostname. Absolute action URLs avoid dependence on the instance's default action host; see [Gitea action compatibility](https://docs.gitea.com/usage/actions/comparison/).
|
||||||
|
|
||||||
|
Enable Actions for the repository and instance if it is disabled. An unavailable Actions page does not establish whether execution is disabled or the viewer lacks permission; inspect the authenticated settings and runner status before claiming the gates are active.
|
||||||
|
|
||||||
|
Add repository Actions secret `CI_POSTGRES_PASSWORD`: a random alphanumeric password used only for the disposable CI PostgreSQL service. Alphanumeric characters keep the connection URL valid without URL encoding. CI tests create and drop isolated databases, so the CI role needs `CREATEDB`. Never supply a production database URL or credentials. No service port is published to the runner host.
|
||||||
|
|
||||||
|
Express's transitive `proxy-addr` is pinned to 2.0.8 through the existing workspace override mechanism to address [GHSA-jqcg-44mw-7w3h](https://github.com/advisories/GHSA-jqcg-44mw-7w3h). Keep the production audit gate enabled; remove the override when the upstream dependency graph resolves a patched version itself.
|
||||||
|
|
||||||
|
In Gitea branch protection for `main`, require both job statuses using their exact names from the first successful run, require review, and disable force pushes. These repository settings are operational prerequisites; committing YAML does not enable branch protection or register a runner.
|
||||||
|
|
||||||
|
The existing `.drone.yml` is a separate build/deploy pipeline: a push to `main` publishes `git.midastix.com/ci-docker-repo-user/manicandle-backend:latest` and then invokes the server deployment script. It does not wait for the new Gitea jobs. Require the reviewed commit's checks before merging and avoid direct main pushes; otherwise deployment can run before validation completes. Its registry secrets are Drone repository secrets `docker_username` and `docker_password`, not `CI_POSTGRES_PASSWORD`. For `unauthorized: reqPackageAccess`, verify that the credentials belong to the target package owner or an authorized publisher, and use a Gitea token with package write access. Retrying a successful main build also runs deployment; server credentials and settings are managed manually by the operator.
|
||||||
|
|
||||||
|
Locally, run `pnpm check` and `pnpm db:test`. To exercise all six native-only tests and the surrounding regression cases, provide `TEST_DATABASE_URL` for a disposable native PostgreSQL administrator connection, then run `pnpm test:native`. The native command uses the normal test helper to create separate randomly named databases and remove them afterward. Embedded PostgreSQL is useful for ordinary tests but does not prove multi-connection locking behavior.
|
||||||
|
|
||||||
|
## Staging and launch procedure
|
||||||
|
|
||||||
|
1. Select a reviewed commit whose two CI jobs pass. Record its SHA, the previous release SHA and migration manifest. Agree on the launch feature cut: payments, carriers, live marketing and automated scheduler invocation remain deferred.
|
||||||
|
2. Provision the deployment target, TLS boundary and PostgreSQL 17 service. Store secrets outside Git and logs; separate migration, application and CI database roles. Verify connection limits against `DATABASE_POOL_SIZE` and replica count. Configure explicit HTTPS `CORS_ORIGINS`, `NODE_ENV=production` and `SWAGGER_ENABLED=false`. Configure recovery SMTP and the HTTPS recovery URL together before promising password recovery. Validate network-boundary rate limiting and proxy behavior against [VAPT readiness](vapt-readiness.md). Rate limits key on the client IP: set `TRUST_PROXY` to exactly the proxy hops in front of the service (for example the backend host's Nginx or Docker bridge, plus the frontend server whose Nginx forwards `/api`), and make every hop append `X-Forwarded-For $proxy_add_x_forwarded_for`. Without it, all visitors share one proxy IP and one rate-limit bucket. Never trust all addresses; a direct caller could then spoof its IP.
|
||||||
|
3. Build the existing image or compiled application from that exact commit. For a source installation: `pnpm install --frozen-lockfile`, `pnpm db:generate`, `pnpm build`. The current Dockerfile is a development-derived build; non-root runtime, graceful shutdown verification, image scanning and a tested deployment definition remain launch work, not proven by this CI milestone.
|
||||||
|
4. Take a database backup and restore it into isolated staging. Verify representative immutable audit, order, supplier-payment and inventory records after restore. Keep production secrets and outbound provider access out of the staging restore.
|
||||||
|
5. Run `pnpm migrations:check`, then `pnpm db:deploy` and `pnpm db:status` against staging with migration credentials. Start the built service with restricted application credentials. Verify `/api/v1/health/live` and `/api/v1/health/ready`; readiness must fail when PostgreSQL is unavailable.
|
||||||
|
6. Smoke-test login, denied/foreign-organization access, checkout and cancellation/hold release, procurement and stock reads, and expiry replay using staging identities. Confirm errors/logs omit credentials, tokens, addresses and document bodies. Exercise the deployment's shutdown/restart behavior before enabling traffic.
|
||||||
|
7. After the restore drill and staging checks pass, take a fresh production backup, apply reviewed additive migrations, deploy the same artifact and verify readiness before routing traffic. Keep a named operator monitoring health, errors, latency, database connections and integrity-sensitive flows during the first hour. Define alert destinations and acceptable baselines for the actual environment before launch.
|
||||||
|
|
||||||
|
## Rollback and remaining decisions
|
||||||
|
|
||||||
|
Stop scheduler invocation and route traffic back to the previous compatible application artifact if readiness, authentication, stock integrity or error/latency checks regress. Preserve additive tables, audit history, completed expiry runs and released holds; an application rollback cannot reopen cancelled orders. Never edit committed migration SQL or reverse financial/stock history with database deletes. A destructive schema rollback or database restore requires a separate incident decision, an assessed data-loss window and reconciliation.
|
||||||
|
|
||||||
|
Before public launch, the operator still needs to select the host/database/secret store, enable and observe both CI jobs, configure branch protection, validate backup restoration, complete monitoring and incident ownership, verify the runtime container/process lifecycle, settle tax/shipping/retention policy and perform deployed-environment security testing. Live providers and SaaS tenancy/billing remain separate decisions.
|
||||||
|
|
@ -68,6 +68,15 @@ 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.
|
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.
|
- 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.
|
||||||
|
- 5D (source contract implemented): scoped, bounded accounting source-event pages for supplier invoices/payments and partner receipts, with original/correction links, exact captured amounts and deterministic cursor traversal. Provider posting, ledger/tax mapping and durable export acknowledgements remain separate milestones.
|
||||||
|
- 5E (material-contribution baseline implemented): explicit net-price scenarios against sealed batch material/packaging cost, signed exact contribution, upward break-even prices and zero-output handling. Realized net profit, complete expense/COGS attribution, sales-to-batch linkage and dashboards remain separate milestones.
|
||||||
|
- 5F (expiry workflow implemented): bounded, idempotent expired-order sweeps with shared cancellation/hold-release logic, immutable run history, atomic rollback and an authenticated scheduler-ready command. Deployment scheduling, broader workflow rules, live providers and complete production launch work remain separate milestones.
|
||||||
|
|
||||||
|
## Phase 6: Production readiness
|
||||||
|
|
||||||
|
- 6A (release gates implemented; operational activation pending): separate embedded quality and native PostgreSQL concurrency jobs, fail-closed native test evidence, and a staging/backup/rollback runbook. Runner/secret setup, required branch checks, observed remote CI, hardened runtime, deployment infrastructure, restore drills, monitoring and live launch remain operational or later milestones.
|
||||||
|
|
||||||
## Definition of done for every feature
|
## Definition of done for every feature
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -19,10 +19,13 @@
|
||||||
"db:validate": "prisma validate",
|
"db:validate": "prisma validate",
|
||||||
"db:migrate": "prisma migrate dev",
|
"db:migrate": "prisma migrate dev",
|
||||||
"db:deploy": "prisma migrate deploy",
|
"db:deploy": "prisma migrate deploy",
|
||||||
"check": "pnpm migrations:check && pnpm format:check && pnpm db:validate && pnpm typecheck && pnpm test:coverage && pnpm build",
|
"check": "pnpm migrations:check && pnpm format:check && pnpm db:validate && pnpm typecheck && pnpm test:tooling && pnpm test:coverage && pnpm build",
|
||||||
|
"test:tooling": "node --test scripts/test/*.test.mjs",
|
||||||
|
"test:native": "node scripts/test-native.mjs",
|
||||||
"start:watch": "node --watch dist/main.js",
|
"start:watch": "node --watch dist/main.js",
|
||||||
"db:status": "prisma migrate status",
|
"db:status": "prisma migrate status",
|
||||||
"bootstrap:owner": "node dist/cli/bootstrap-owner.js",
|
"bootstrap:owner": "node dist/cli/bootstrap-owner.js",
|
||||||
|
"workflows:expire": "node dist/cli/workflow-expiry.js",
|
||||||
"admin:prepare-local": "node dist/cli/local-admin.js prepare",
|
"admin:prepare-local": "node dist/cli/local-admin.js prepare",
|
||||||
"admin:seed-local": "node dist/cli/local-admin.js seed",
|
"admin:seed-local": "node dist/cli/local-admin.js seed",
|
||||||
"db:test": "node scripts/test-migrations.mjs",
|
"db:test": "node scripts/test-migrations.mjs",
|
||||||
|
|
@ -38,10 +41,10 @@
|
||||||
"@prisma/client": "^7.0.0",
|
"@prisma/client": "^7.0.0",
|
||||||
"dotenv": "^17.0.0",
|
"dotenv": "^17.0.0",
|
||||||
"helmet": "^8.0.0",
|
"helmet": "^8.0.0",
|
||||||
"nodemailer": "^10.0.2",
|
"nodemailer": "^10.6.1",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
"rxjs": "^7.8.2",
|
"rxjs": "^7.8.2",
|
||||||
"zod": "^4.0.0"
|
"zod": "^4.6.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@electric-sql/pglite": "^0.5.8",
|
"@electric-sql/pglite": "^0.5.8",
|
||||||
|
|
|
||||||
|
|
@ -6,10 +6,12 @@ settings:
|
||||||
|
|
||||||
overrides:
|
overrides:
|
||||||
'@prisma/config>deepmerge-ts': 8.0.0
|
'@prisma/config>deepmerge-ts': 8.0.0
|
||||||
|
'@prisma/config>effect': 3.22.5
|
||||||
prisma>mysql2: 3.23.1
|
prisma>mysql2: 3.23.1
|
||||||
'@nestjs/platform-express>multer': 2.4.0
|
'@nestjs/platform-express>multer': 2.5.0
|
||||||
'@nestjs/swagger>js-yaml': 5.4.1
|
'@nestjs/swagger>js-yaml': 5.4.1
|
||||||
ajv>fast-uri: 3.1.8
|
ajv>fast-uri: 3.1.9
|
||||||
|
express>proxy-addr: 2.0.8
|
||||||
|
|
||||||
importers:
|
importers:
|
||||||
|
|
||||||
|
|
@ -40,8 +42,8 @@ importers:
|
||||||
specifier: ^8.0.0
|
specifier: ^8.0.0
|
||||||
version: 8.3.0
|
version: 8.3.0
|
||||||
nodemailer:
|
nodemailer:
|
||||||
specifier: ^10.0.2
|
specifier: ^10.6.1
|
||||||
version: 10.0.11
|
version: 10.6.1
|
||||||
reflect-metadata:
|
reflect-metadata:
|
||||||
specifier: ^0.2.2
|
specifier: ^0.2.2
|
||||||
version: 0.2.2
|
version: 0.2.2
|
||||||
|
|
@ -49,8 +51,8 @@ importers:
|
||||||
specifier: ^7.8.2
|
specifier: ^7.8.2
|
||||||
version: 7.8.2
|
version: 7.8.2
|
||||||
zod:
|
zod:
|
||||||
specifier: ^4.0.0
|
specifier: ^4.6.7
|
||||||
version: 4.5.4
|
version: 4.6.7
|
||||||
devDependencies:
|
devDependencies:
|
||||||
'@electric-sql/pglite':
|
'@electric-sql/pglite':
|
||||||
specifier: ^0.5.8
|
specifier: ^0.5.8
|
||||||
|
|
@ -1339,8 +1341,8 @@ packages:
|
||||||
better-result@2.10.0:
|
better-result@2.10.0:
|
||||||
resolution: {integrity: sha512-oQhh0y1qo2/ZKdAAEvHZAqKKiHOFU5k/bW96fE2ScgQOVkJRiHwB+nOS1SgFsYqRlxMDWvefXi9Q3px7QvgNDw==}
|
resolution: {integrity: sha512-oQhh0y1qo2/ZKdAAEvHZAqKKiHOFU5k/bW96fE2ScgQOVkJRiHwB+nOS1SgFsYqRlxMDWvefXi9Q3px7QvgNDw==}
|
||||||
|
|
||||||
body-parser@2.3.0:
|
body-parser@2.4.0:
|
||||||
resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==}
|
resolution: {integrity: sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
brace-expansion@2.1.4:
|
brace-expansion@2.1.4:
|
||||||
|
|
@ -1610,8 +1612,8 @@ packages:
|
||||||
ee-first@1.1.1:
|
ee-first@1.1.1:
|
||||||
resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}
|
resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}
|
||||||
|
|
||||||
effect@3.20.0:
|
effect@3.22.5:
|
||||||
resolution: {integrity: sha512-qMLfDJscrNG8p/aw+IkT9W7fgj50Z4wG5bLBy0Txsxz8iUHjDIkOgO3SV0WZfnQbNG2VJYb0b+rDLMrhM4+Krw==}
|
resolution: {integrity: sha512-AdIU4llI19BzhJ4xUBZix7kS8oiYSlCsJ61j3UM3UyJw9ecDrsrrweDFm/Ku1nHbJWMLoynK+1Me4it3Zkmjpw==}
|
||||||
|
|
||||||
electron-to-chromium@1.5.422:
|
electron-to-chromium@1.5.422:
|
||||||
resolution: {integrity: sha512-UvA/32XqrLDdZSn7Jllo1AYNcWji/G0d5M0GTViE7KoGBiMunw3a34Sb2KO4ZZyrSEhqsxFoVhWWJshdyfKqJA==}
|
resolution: {integrity: sha512-UvA/32XqrLDdZSn7Jllo1AYNcWji/G0d5M0GTViE7KoGBiMunw3a34Sb2KO4ZZyrSEhqsxFoVhWWJshdyfKqJA==}
|
||||||
|
|
@ -1726,8 +1728,8 @@ packages:
|
||||||
fast-safe-stringify@2.1.1:
|
fast-safe-stringify@2.1.1:
|
||||||
resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==}
|
resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==}
|
||||||
|
|
||||||
fast-uri@3.1.8:
|
fast-uri@3.1.9:
|
||||||
resolution: {integrity: sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==}
|
resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==}
|
||||||
|
|
||||||
fb-watchman@2.0.2:
|
fb-watchman@2.0.2:
|
||||||
resolution: {integrity: sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==}
|
resolution: {integrity: sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==}
|
||||||
|
|
@ -2219,8 +2221,8 @@ packages:
|
||||||
ms@2.1.3:
|
ms@2.1.3:
|
||||||
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
|
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
|
||||||
|
|
||||||
multer@2.4.0:
|
multer@2.5.0:
|
||||||
resolution: {integrity: sha512-7dqa0ZcFfzbefdTuIkzOSMvZWC0J7FLqBOjJUZvDCXShIURWKxAyTT1wHhnE5q19c7jOJf43IYYKjBmZVZmvhg==}
|
resolution: {integrity: sha512-BsqOzYGVq49JcW2IzoSAxeKYRevb+dGGPPWleOR8Lrlk4igwxu1/9pwSXlByhCb7MVZDrNJFC0IBP5/O5nLYRw==}
|
||||||
engines: {node: '>= 10.16.0'}
|
engines: {node: '>= 10.16.0'}
|
||||||
|
|
||||||
mysql2@3.23.1:
|
mysql2@3.23.1:
|
||||||
|
|
@ -2258,8 +2260,8 @@ packages:
|
||||||
resolution: {integrity: sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ==}
|
resolution: {integrity: sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
nodemailer@10.0.11:
|
nodemailer@10.6.1:
|
||||||
resolution: {integrity: sha512-/c4P7U7aGpiNu2Rl08q525q2zECkUpSaf2zQPgIStCcAjHAkkQQKwD4sTyi3l91mGcLQrKzL1syXPHymo+Ogtw==}
|
resolution: {integrity: sha512-d7kfFfS/tR4Aca+SBvRaQ+MXKNv7d2JiRe5TxaRcFT/kYMh4GGPnW9aKksTIEvyEbA7d/7HYWE4YPDEHxzJj/g==}
|
||||||
engines: {node: '>=20.0.0'}
|
engines: {node: '>=20.0.0'}
|
||||||
|
|
||||||
normalize-path@3.0.0:
|
normalize-path@3.0.0:
|
||||||
|
|
@ -2449,8 +2451,8 @@ packages:
|
||||||
proper-lockfile@4.1.2:
|
proper-lockfile@4.1.2:
|
||||||
resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==}
|
resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==}
|
||||||
|
|
||||||
proxy-addr@2.0.7:
|
proxy-addr@2.0.8:
|
||||||
resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==}
|
resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==}
|
||||||
engines: {node: '>= 0.10'}
|
engines: {node: '>= 0.10'}
|
||||||
|
|
||||||
pure-rand@6.1.0:
|
pure-rand@6.1.0:
|
||||||
|
|
@ -2459,8 +2461,8 @@ packages:
|
||||||
pure-rand@7.0.1:
|
pure-rand@7.0.1:
|
||||||
resolution: {integrity: sha512-oTUZM/NAZS8p7ANR3SHh30kXB+zK2r2BPcEn/awJIbOvq82WoMN4p62AWWp3Hhw50G0xMsw1mhIBLqHw64EcNQ==}
|
resolution: {integrity: sha512-oTUZM/NAZS8p7ANR3SHh30kXB+zK2r2BPcEn/awJIbOvq82WoMN4p62AWWp3Hhw50G0xMsw1mhIBLqHw64EcNQ==}
|
||||||
|
|
||||||
qs@6.16.0:
|
qs@6.17.1:
|
||||||
resolution: {integrity: sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==}
|
resolution: {integrity: sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==}
|
||||||
engines: {node: '>=0.6'}
|
engines: {node: '>=0.6'}
|
||||||
|
|
||||||
range-parser@1.3.0:
|
range-parser@1.3.0:
|
||||||
|
|
@ -2848,8 +2850,8 @@ packages:
|
||||||
zeptomatch@2.1.0:
|
zeptomatch@2.1.0:
|
||||||
resolution: {integrity: sha512-KiGErG2J0G82LSpniV0CtIzjlJ10E04j02VOudJsPyPwNZgGnRKQy7I1R7GMyg/QswnE4l7ohSGrQbQbjXPPDA==}
|
resolution: {integrity: sha512-KiGErG2J0G82LSpniV0CtIzjlJ10E04j02VOudJsPyPwNZgGnRKQy7I1R7GMyg/QswnE4l7ohSGrQbQbjXPPDA==}
|
||||||
|
|
||||||
zod@4.5.4:
|
zod@4.6.7:
|
||||||
resolution: {integrity: sha512-sC95tT5iHHH9gtpj6A81kh+NEaRAUFN+qlUPDUbRfOMvNf5QCBqsb3WgvnpVtK5Y+4UfA6KqufotuTvMGiTlsA==}
|
resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==}
|
||||||
|
|
||||||
snapshots:
|
snapshots:
|
||||||
|
|
||||||
|
|
@ -3453,7 +3455,7 @@ snapshots:
|
||||||
'@nestjs/core': 11.2.3(@nestjs/common@11.2.3(reflect-metadata@0.2.2)(rxjs@7.8.2)(supports-color@8.1.1))(@nestjs/platform-express@11.2.3)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
'@nestjs/core': 11.2.3(@nestjs/common@11.2.3(reflect-metadata@0.2.2)(rxjs@7.8.2)(supports-color@8.1.1))(@nestjs/platform-express@11.2.3)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||||
cors: 2.8.6
|
cors: 2.8.6
|
||||||
express: 5.2.1(supports-color@8.1.1)
|
express: 5.2.1(supports-color@8.1.1)
|
||||||
multer: 2.4.0
|
multer: 2.5.0
|
||||||
path-to-regexp: 8.4.2
|
path-to-regexp: 8.4.2
|
||||||
tslib: 2.8.1
|
tslib: 2.8.1
|
||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
|
|
@ -3568,7 +3570,7 @@ snapshots:
|
||||||
dependencies:
|
dependencies:
|
||||||
c12: 3.3.4
|
c12: 3.3.4
|
||||||
deepmerge-ts: 8.0.0
|
deepmerge-ts: 8.0.0
|
||||||
effect: 3.20.0
|
effect: 3.22.5
|
||||||
empathic: 2.0.0
|
empathic: 2.0.0
|
||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- magicast
|
- magicast
|
||||||
|
|
@ -4040,7 +4042,7 @@ snapshots:
|
||||||
ajv@8.20.0:
|
ajv@8.20.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
fast-deep-equal: 3.1.3
|
fast-deep-equal: 3.1.3
|
||||||
fast-uri: 3.1.8
|
fast-uri: 3.1.9
|
||||||
json-schema-traverse: 1.0.0
|
json-schema-traverse: 1.0.0
|
||||||
require-from-string: 2.0.2
|
require-from-string: 2.0.2
|
||||||
|
|
||||||
|
|
@ -4139,7 +4141,7 @@ snapshots:
|
||||||
|
|
||||||
better-result@2.10.0: {}
|
better-result@2.10.0: {}
|
||||||
|
|
||||||
body-parser@2.3.0(supports-color@8.1.1):
|
body-parser@2.4.0(supports-color@8.1.1):
|
||||||
dependencies:
|
dependencies:
|
||||||
bytes: 3.1.2
|
bytes: 3.1.2
|
||||||
content-type: 2.1.0
|
content-type: 2.1.0
|
||||||
|
|
@ -4147,7 +4149,7 @@ snapshots:
|
||||||
http-errors: 2.0.1
|
http-errors: 2.0.1
|
||||||
iconv-lite: 0.7.3
|
iconv-lite: 0.7.3
|
||||||
on-finished: 2.4.1
|
on-finished: 2.4.1
|
||||||
qs: 6.16.0
|
qs: 6.17.1
|
||||||
raw-body: 3.0.2
|
raw-body: 3.0.2
|
||||||
type-is: 2.1.0
|
type-is: 2.1.0
|
||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
|
|
@ -4379,7 +4381,7 @@ snapshots:
|
||||||
|
|
||||||
ee-first@1.1.1: {}
|
ee-first@1.1.1: {}
|
||||||
|
|
||||||
effect@3.20.0:
|
effect@3.22.5:
|
||||||
dependencies:
|
dependencies:
|
||||||
'@standard-schema/spec': 1.1.0
|
'@standard-schema/spec': 1.1.0
|
||||||
fast-check: 3.23.2
|
fast-check: 3.23.2
|
||||||
|
|
@ -4487,7 +4489,7 @@ snapshots:
|
||||||
express@5.2.1(supports-color@8.1.1):
|
express@5.2.1(supports-color@8.1.1):
|
||||||
dependencies:
|
dependencies:
|
||||||
accepts: 2.0.0
|
accepts: 2.0.0
|
||||||
body-parser: 2.3.0(supports-color@8.1.1)
|
body-parser: 2.4.0(supports-color@8.1.1)
|
||||||
content-disposition: 1.1.0
|
content-disposition: 1.1.0
|
||||||
content-type: 1.0.5
|
content-type: 1.0.5
|
||||||
cookie: 0.7.2
|
cookie: 0.7.2
|
||||||
|
|
@ -4505,8 +4507,8 @@ snapshots:
|
||||||
on-finished: 2.4.1
|
on-finished: 2.4.1
|
||||||
once: 1.4.0
|
once: 1.4.0
|
||||||
parseurl: 1.3.3
|
parseurl: 1.3.3
|
||||||
proxy-addr: 2.0.7
|
proxy-addr: 2.0.8
|
||||||
qs: 6.16.0
|
qs: 6.17.1
|
||||||
range-parser: 1.3.0
|
range-parser: 1.3.0
|
||||||
router: 2.2.0(supports-color@8.1.1)
|
router: 2.2.0(supports-color@8.1.1)
|
||||||
send: 1.2.1(supports-color@8.1.1)
|
send: 1.2.1(supports-color@8.1.1)
|
||||||
|
|
@ -4535,7 +4537,7 @@ snapshots:
|
||||||
|
|
||||||
fast-safe-stringify@2.1.1: {}
|
fast-safe-stringify@2.1.1: {}
|
||||||
|
|
||||||
fast-uri@3.1.8: {}
|
fast-uri@3.1.9: {}
|
||||||
|
|
||||||
fb-watchman@2.0.2:
|
fb-watchman@2.0.2:
|
||||||
dependencies:
|
dependencies:
|
||||||
|
|
@ -5173,7 +5175,7 @@ snapshots:
|
||||||
|
|
||||||
ms@2.1.3: {}
|
ms@2.1.3: {}
|
||||||
|
|
||||||
multer@2.4.0:
|
multer@2.5.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
append-field: 1.0.0
|
append-field: 1.0.0
|
||||||
busboy: 1.6.0
|
busboy: 1.6.0
|
||||||
|
|
@ -5211,7 +5213,7 @@ snapshots:
|
||||||
|
|
||||||
node-releases@2.0.54: {}
|
node-releases@2.0.54: {}
|
||||||
|
|
||||||
nodemailer@10.0.11: {}
|
nodemailer@10.6.1: {}
|
||||||
|
|
||||||
normalize-path@3.0.0: {}
|
normalize-path@3.0.0: {}
|
||||||
|
|
||||||
|
|
@ -5382,7 +5384,7 @@ snapshots:
|
||||||
retry: 0.12.0
|
retry: 0.12.0
|
||||||
signal-exit: 3.0.7
|
signal-exit: 3.0.7
|
||||||
|
|
||||||
proxy-addr@2.0.7:
|
proxy-addr@2.0.8:
|
||||||
dependencies:
|
dependencies:
|
||||||
forwarded: 0.2.0
|
forwarded: 0.2.0
|
||||||
ipaddr.js: 1.9.1
|
ipaddr.js: 1.9.1
|
||||||
|
|
@ -5391,7 +5393,7 @@ snapshots:
|
||||||
|
|
||||||
pure-rand@7.0.1: {}
|
pure-rand@7.0.1: {}
|
||||||
|
|
||||||
qs@6.16.0:
|
qs@6.17.1:
|
||||||
dependencies:
|
dependencies:
|
||||||
es-define-property: 1.0.1
|
es-define-property: 1.0.1
|
||||||
side-channel: 1.1.1
|
side-channel: 1.1.1
|
||||||
|
|
@ -5599,7 +5601,7 @@ snapshots:
|
||||||
formidable: 3.5.4
|
formidable: 3.5.4
|
||||||
methods: 1.1.2
|
methods: 1.1.2
|
||||||
mime: 2.6.0
|
mime: 2.6.0
|
||||||
qs: 6.16.0
|
qs: 6.17.1
|
||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- supports-color
|
- supports-color
|
||||||
|
|
||||||
|
|
@ -5791,4 +5793,4 @@ snapshots:
|
||||||
grammex: 3.1.13
|
grammex: 3.1.13
|
||||||
graphmatch: 1.1.1
|
graphmatch: 1.1.1
|
||||||
|
|
||||||
zod@4.5.4: {}
|
zod@4.6.7: {}
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,9 @@ allowBuilds:
|
||||||
unrs-resolver: true
|
unrs-resolver: true
|
||||||
overrides:
|
overrides:
|
||||||
'@prisma/config>deepmerge-ts': 8.0.0
|
'@prisma/config>deepmerge-ts': 8.0.0
|
||||||
|
'@prisma/config>effect': 3.22.5
|
||||||
'prisma>mysql2': 3.23.1
|
'prisma>mysql2': 3.23.1
|
||||||
'@nestjs/platform-express>multer': 2.4.0
|
'@nestjs/platform-express>multer': 2.5.0
|
||||||
'@nestjs/swagger>js-yaml': 5.4.1
|
'@nestjs/swagger>js-yaml': 5.4.1
|
||||||
'ajv>fast-uri': 3.1.8
|
'ajv>fast-uri': 3.1.9
|
||||||
|
'express>proxy-addr': 2.0.8
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,7 @@ model Product {
|
||||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
|
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
|
||||||
variants ProductVariant[]
|
variants ProductVariant[]
|
||||||
groups ProductGroup[]
|
groups ProductGroup[]
|
||||||
|
images ProductImage[]
|
||||||
@@unique([organizationId, slug])
|
@@unique([organizationId, slug])
|
||||||
@@unique([id, organizationId])
|
@@unique([id, organizationId])
|
||||||
@@index([organizationId, status, createdAt, id])
|
@@index([organizationId, status, createdAt, id])
|
||||||
|
|
|
||||||
|
|
@ -77,6 +77,8 @@ model Order {
|
||||||
@@unique([userId, organizationId, idempotencyKey])
|
@@unique([userId, organizationId, idempotencyKey])
|
||||||
@@unique([id, organizationId])
|
@@unique([id, organizationId])
|
||||||
@@index([organizationId, userId, createdAt, id])
|
@@index([organizationId, userId, createdAt, id])
|
||||||
|
@@index([organizationId, createdAt, id])
|
||||||
|
@@index([organizationId, status, expiresAt, id])
|
||||||
@@unique([id, userId, organizationId])
|
@@unique([id, userId, organizationId])
|
||||||
@@index([couponId, status, expiresAt])
|
@@index([couponId, status, expiresAt])
|
||||||
@@map("orders")
|
@@map("orders")
|
||||||
|
|
|
||||||
|
|
@ -51,5 +51,11 @@
|
||||||
"20261007130000_messaging_consent": "b4fd5b1cf6a7cd17083a4b5fbef815ec1ebc25ba7538c6de18c05e16212155dd",
|
"20261007130000_messaging_consent": "b4fd5b1cf6a7cd17083a4b5fbef815ec1ebc25ba7538c6de18c05e16212155dd",
|
||||||
"20261007140000_blog_publishing": "92e8d98a8e89f3eda28b6cf5c3b45125a325e5d8e852f1e5a0a3cf5d7eff65a4",
|
"20261007140000_blog_publishing": "92e8d98a8e89f3eda28b6cf5c3b45125a325e5d8e852f1e5a0a3cf5d7eff65a4",
|
||||||
"20261007150000_customer_segments": "bcafd50bc12dc44b7ee532ba4ca23da0b12eb3f0e89ad4b168789a22e110969a",
|
"20261007150000_customer_segments": "bcafd50bc12dc44b7ee532ba4ca23da0b12eb3f0e89ad4b168789a22e110969a",
|
||||||
"20261007160000_moderated_forums": "3a7dce2115e06acd0f4b02d366721db5ebcf8b5f31106b5d85093c1374a2b6a5"
|
"20261007160000_moderated_forums": "3a7dce2115e06acd0f4b02d366721db5ebcf8b5f31106b5d85093c1374a2b6a5",
|
||||||
|
"20261007170000_commerce_analytics": "800e392f788e176e3fb27c04f956a18e5f1505b820af6bb2364fc990aa8d26ea",
|
||||||
|
"20261008100000_capture_forecasts": "69b94ac61b9f1c3f47268d5586d7f73c4c392cabdd3049d01f34e5e033cac043",
|
||||||
|
"20261008110000_accounting_sources": "47b89e83291dbdf7b9fc7f1f25e7260a9f06bde0291ae2f7db01200e75eed396",
|
||||||
|
"20261008120000_batch_contribution": "4d6c577e6d59e9163c41253b828ed19729b76d881f21197f6b863c2f79233471",
|
||||||
|
"20261008130000_order_expiry_workflow": "e9ff103b0870e6998e2a906924a4f0394ac8ccbbe811b323d8485c3ee0dd92ff",
|
||||||
|
"20261126080000_product_images": "ce59729946f37d8958bb9f42974859b76cdaaa67e85491dc5a7eb3fa9e07d9eb"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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';
|
||||||
|
|
@ -0,0 +1,2 @@
|
||||||
|
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['forecasts.read']))
|
||||||
|
WHERE is_system = true AND name = 'Owner';
|
||||||
|
|
@ -0,0 +1,8 @@
|
||||||
|
CREATE INDEX supplier_invoices_accounting_idx ON supplier_invoices (organization_id, created_at, id);
|
||||||
|
CREATE INDEX supplier_invoice_voids_accounting_idx ON supplier_invoice_voids (organization_id, created_at, invoice_id);
|
||||||
|
CREATE INDEX supplier_payments_accounting_idx ON supplier_payments (organization_id, created_at, id);
|
||||||
|
CREATE INDEX supplier_payment_reversals_accounting_idx ON supplier_payment_reversals (organization_id, created_at, payment_id);
|
||||||
|
CREATE INDEX partner_payments_accounting_idx ON b2b_partner_payments (organization_id, created_at, id);
|
||||||
|
CREATE INDEX partner_payment_reversals_accounting_idx ON b2b_partner_payment_reversals (organization_id, created_at, payment_id);
|
||||||
|
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['accounting.read']))
|
||||||
|
WHERE is_system = true AND name = 'Owner';
|
||||||
|
|
@ -0,0 +1,2 @@
|
||||||
|
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['profitability.read']))
|
||||||
|
WHERE is_system = true AND name = 'Owner';
|
||||||
|
|
@ -0,0 +1,24 @@
|
||||||
|
CREATE TABLE order_expiry_runs (
|
||||||
|
id UUID NOT NULL, organization_id UUID NOT NULL, actor_id UUID NOT NULL,
|
||||||
|
idempotency_key UUID NOT NULL, request_hash CHAR(64) NOT NULL, "limit" INTEGER NOT NULL,
|
||||||
|
as_of TIMESTAMPTZ(3) NOT NULL, completed_at TIMESTAMPTZ(3) NOT NULL, processed_order_ids UUID[] NOT NULL,
|
||||||
|
CONSTRAINT order_expiry_runs_pkey PRIMARY KEY (id),
|
||||||
|
CONSTRAINT order_expiry_runs_actor_id_organization_id_fkey FOREIGN KEY (actor_id, organization_id) REFERENCES users(id, organization_id) ON DELETE RESTRICT ON UPDATE CASCADE,
|
||||||
|
CONSTRAINT expiry_run_valid CHECK ("limit" BETWEEN 1 AND 25 AND cardinality(processed_order_ids) <= "limit" AND completed_at >= as_of AND request_hash ~ '^[a-f0-9]{64}$')
|
||||||
|
);
|
||||||
|
CREATE INDEX orders_organization_id_status_expires_at_id_idx ON orders (organization_id, status, expires_at, id);
|
||||||
|
CREATE UNIQUE INDEX order_expiry_runs_organization_id_idempotency_key_key ON order_expiry_runs (organization_id, idempotency_key);
|
||||||
|
CREATE INDEX order_expiry_runs_organization_id_completed_at_id_idx ON order_expiry_runs (organization_id, completed_at, id);
|
||||||
|
CREATE FUNCTION guard_order_expiry_run() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Order expiry run history is immutable'; END IF;
|
||||||
|
IF (SELECT COUNT(DISTINCT id) FROM unnest(NEW.processed_order_ids) AS ids(id)) <> cardinality(NEW.processed_order_ids)
|
||||||
|
OR EXISTS (SELECT 1 FROM unnest(NEW.processed_order_ids) AS ids(id) LEFT JOIN orders o ON o.id = ids.id AND o.organization_id = NEW.organization_id
|
||||||
|
WHERE o.id IS NULL OR o.status <> 'CANCELLED' OR o.expires_at > NEW.as_of)
|
||||||
|
THEN RAISE EXCEPTION 'Expiry run contains invalid order evidence'; END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
CREATE TRIGGER order_expiry_run_guard BEFORE INSERT OR UPDATE OR DELETE ON order_expiry_runs FOR EACH ROW EXECUTE FUNCTION guard_order_expiry_run();
|
||||||
|
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['workflows.read', 'workflows.run']))
|
||||||
|
WHERE is_system = true AND name = 'Owner';
|
||||||
|
|
@ -0,0 +1,9 @@
|
||||||
|
CREATE TABLE product_images (
|
||||||
|
id UUID NOT NULL, product_id UUID NOT NULL, organization_id UUID NOT NULL,
|
||||||
|
mime_type VARCHAR(32) NOT NULL, sha256 CHAR(64) NOT NULL, size INTEGER NOT NULL,
|
||||||
|
content BYTEA NOT NULL, created_at TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
CONSTRAINT product_images_pkey PRIMARY KEY (id),
|
||||||
|
CONSTRAINT product_images_product_id_organization_id_fkey FOREIGN KEY (product_id, organization_id) REFERENCES products(id, organization_id) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||||
|
CONSTRAINT product_image_valid CHECK (mime_type IN ('image/jpeg', 'image/png', 'image/webp') AND size BETWEEN 1 AND 2097152 AND octet_length(content) = size AND sha256 ~ '^[a-f0-9]{64}$')
|
||||||
|
);
|
||||||
|
CREATE INDEX product_images_product_id_created_at_id_idx ON product_images (product_id, created_at, id);
|
||||||
|
|
@ -86,6 +86,7 @@ model B2bPartnerPayment {
|
||||||
@@unique([organizationId, reference])
|
@@unique([organizationId, reference])
|
||||||
@@index([organizationId, orderId, createdAt, id])
|
@@index([organizationId, orderId, createdAt, id])
|
||||||
@@map("b2b_partner_payments")
|
@@map("b2b_partner_payments")
|
||||||
|
@@index([organizationId, createdAt, id], map: "partner_payments_accounting_idx")
|
||||||
}
|
}
|
||||||
|
|
||||||
model B2bPartnerPaymentReversal {
|
model B2bPartnerPaymentReversal {
|
||||||
|
|
@ -102,4 +103,5 @@ model B2bPartnerPaymentReversal {
|
||||||
@@unique([paymentId, organizationId])
|
@@unique([paymentId, organizationId])
|
||||||
@@unique([organizationId, idempotencyKey])
|
@@unique([organizationId, idempotencyKey])
|
||||||
@@map("b2b_partner_payment_reversals")
|
@@map("b2b_partner_payment_reversals")
|
||||||
|
@@index([organizationId, createdAt, paymentId], map: "partner_payment_reversals_accounting_idx")
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -224,6 +224,7 @@ model SupplierInvoice {
|
||||||
@@unique([id, organizationId])
|
@@unique([id, organizationId])
|
||||||
@@index([organizationId, purchaseOrderId, createdAt, id], map: "supplier_invoices_order_created_idx")
|
@@index([organizationId, purchaseOrderId, createdAt, id], map: "supplier_invoices_order_created_idx")
|
||||||
@@map("supplier_invoices")
|
@@map("supplier_invoices")
|
||||||
|
@@index([organizationId, createdAt, id], map: "supplier_invoices_accounting_idx")
|
||||||
}
|
}
|
||||||
|
|
||||||
model SupplierInvoiceLine {
|
model SupplierInvoiceLine {
|
||||||
|
|
@ -253,6 +254,7 @@ model SupplierInvoiceVoid {
|
||||||
voidedBy User @relation(fields: [voidedById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
voidedBy User @relation(fields: [voidedById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
@@unique([invoiceId, organizationId])
|
@@unique([invoiceId, organizationId])
|
||||||
@@map("supplier_invoice_voids")
|
@@map("supplier_invoice_voids")
|
||||||
|
@@index([organizationId, createdAt, invoiceId], map: "supplier_invoice_voids_accounting_idx")
|
||||||
}
|
}
|
||||||
|
|
||||||
model SupplierPayment {
|
model SupplierPayment {
|
||||||
|
|
@ -277,6 +279,7 @@ model SupplierPayment {
|
||||||
@@unique([id, organizationId])
|
@@unique([id, organizationId])
|
||||||
@@index([organizationId, invoiceId, createdAt, id], map: "supplier_payments_invoice_created_idx")
|
@@index([organizationId, invoiceId, createdAt, id], map: "supplier_payments_invoice_created_idx")
|
||||||
@@map("supplier_payments")
|
@@map("supplier_payments")
|
||||||
|
@@index([organizationId, createdAt, id], map: "supplier_payments_accounting_idx")
|
||||||
}
|
}
|
||||||
|
|
||||||
model SupplierPaymentReversal {
|
model SupplierPaymentReversal {
|
||||||
|
|
@ -290,4 +293,5 @@ model SupplierPaymentReversal {
|
||||||
reversedBy User @relation(fields: [reversedById, organizationId], references: [id, organizationId], onDelete: Restrict, map: "supplier_payment_reversal_actor_scope_fkey")
|
reversedBy User @relation(fields: [reversedById, organizationId], references: [id, organizationId], onDelete: Restrict, map: "supplier_payment_reversal_actor_scope_fkey")
|
||||||
@@unique([paymentId, organizationId])
|
@@unique([paymentId, organizationId])
|
||||||
@@map("supplier_payment_reversals")
|
@@map("supplier_payment_reversals")
|
||||||
|
@@index([organizationId, createdAt, paymentId], map: "supplier_payment_reversals_accounting_idx")
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,13 @@
|
||||||
|
model ProductImage {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
productId String @map("product_id") @db.Uuid
|
||||||
|
organizationId String @map("organization_id") @db.Uuid
|
||||||
|
mimeType String @map("mime_type") @db.VarChar(32)
|
||||||
|
sha256 String @db.Char(64)
|
||||||
|
size Int
|
||||||
|
content Bytes @db.ByteA
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||||
|
product Product @relation(fields: [productId, organizationId], references: [id, organizationId], onDelete: Cascade)
|
||||||
|
@@index([productId, createdAt, id])
|
||||||
|
@@map("product_images")
|
||||||
|
}
|
||||||
|
|
@ -96,6 +96,7 @@ model User {
|
||||||
blogsWithdrawn BlogArticle[] @relation("BlogWithdrawer")
|
blogsWithdrawn BlogArticle[] @relation("BlogWithdrawer")
|
||||||
forumPosts ForumPost[]
|
forumPosts ForumPost[]
|
||||||
forumDecisions ForumModeration[]
|
forumDecisions ForumModeration[]
|
||||||
|
expiryRuns OrderExpiryRun[]
|
||||||
reviewPurchases ReviewPurchaseVerification[] @relation("ReviewBuyer")
|
reviewPurchases ReviewPurchaseVerification[] @relation("ReviewBuyer")
|
||||||
reviewVerifications ReviewPurchaseVerification[] @relation("ReviewVerifier")
|
reviewVerifications ReviewPurchaseVerification[] @relation("ReviewVerifier")
|
||||||
reviewRevocations ReviewPurchaseRevocation[]
|
reviewRevocations ReviewPurchaseRevocation[]
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,15 @@
|
||||||
|
model OrderExpiryRun {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
organizationId String @map("organization_id") @db.Uuid
|
||||||
|
actorId String @map("actor_id") @db.Uuid
|
||||||
|
idempotencyKey String @map("idempotency_key") @db.Uuid
|
||||||
|
requestHash String @map("request_hash") @db.Char(64)
|
||||||
|
limit Int
|
||||||
|
asOf DateTime @map("as_of") @db.Timestamptz(3)
|
||||||
|
completedAt DateTime @map("completed_at") @db.Timestamptz(3)
|
||||||
|
processedOrderIds String[] @map("processed_order_ids") @db.Uuid
|
||||||
|
actor User @relation(fields: [actorId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||||
|
@@unique([organizationId, idempotencyKey])
|
||||||
|
@@index([organizationId, completedAt, id])
|
||||||
|
@@map("order_expiry_runs")
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,83 @@
|
||||||
|
import { spawnSync } from 'node:child_process';
|
||||||
|
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join, resolve } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
export function assertNativeReport(report) {
|
||||||
|
const nativeTests = (report.testResults ?? []).flatMap((suite) =>
|
||||||
|
(suite.assertionResults ?? []).filter((test) =>
|
||||||
|
test.fullName.includes('native PostgreSQL'),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
report.success !== true ||
|
||||||
|
nativeTests.length < 6 ||
|
||||||
|
!(report.numTotalTests > 0) ||
|
||||||
|
report.numPassedTests !== report.numTotalTests ||
|
||||||
|
report.numPendingTests !== 0 ||
|
||||||
|
report.numTodoTests !== 0 ||
|
||||||
|
report.numRuntimeErrorTestSuites !== 0
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
'Native PostgreSQL gate requires all six concurrency checks and no skipped tests',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function run() {
|
||||||
|
const value = process.env.TEST_DATABASE_URL;
|
||||||
|
if (
|
||||||
|
!value ||
|
||||||
|
!URL.canParse(value) ||
|
||||||
|
!['postgres:', 'postgresql:'].includes(new URL(value).protocol)
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
'TEST_DATABASE_URL must identify a disposable native PostgreSQL database',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const directory = mkdtempSync(join(tmpdir(), 'mani-native-'));
|
||||||
|
try {
|
||||||
|
const reportPath = join(directory, 'report.json');
|
||||||
|
const child = spawnSync(
|
||||||
|
process.execPath,
|
||||||
|
[
|
||||||
|
'--experimental-vm-modules',
|
||||||
|
'node_modules/jest/bin/jest.js',
|
||||||
|
'--runInBand',
|
||||||
|
'--runTestsByPath',
|
||||||
|
'test/checkout-concurrency.spec.ts',
|
||||||
|
'test/events-concurrency.spec.ts',
|
||||||
|
'test/inventory.spec.ts',
|
||||||
|
'test/migration-integrity.spec.ts',
|
||||||
|
'--json',
|
||||||
|
'--outputFile',
|
||||||
|
reportPath,
|
||||||
|
],
|
||||||
|
{ stdio: 'inherit', env: process.env },
|
||||||
|
);
|
||||||
|
if (child.error) throw new Error('Could not start native PostgreSQL tests');
|
||||||
|
if (child.status !== 0) throw new Error('Native PostgreSQL tests failed');
|
||||||
|
assertNativeReport(JSON.parse(readFileSync(reportPath, 'utf8')));
|
||||||
|
console.log('Native PostgreSQL gate passed: no selected tests skipped');
|
||||||
|
} finally {
|
||||||
|
rmSync(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
process.argv[1] &&
|
||||||
|
resolve(process.argv[1]) === fileURLToPath(import.meta.url)
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
run();
|
||||||
|
} catch (error) {
|
||||||
|
// Database credentials and provider errors must not appear in gate diagnostics.
|
||||||
|
console.error(
|
||||||
|
error instanceof Error && error.message.startsWith('Native PostgreSQL')
|
||||||
|
? error.message
|
||||||
|
: 'Native gate failed; check TEST_DATABASE_URL and test output',
|
||||||
|
);
|
||||||
|
process.exitCode = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,55 @@
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { spawnSync } from 'node:child_process';
|
||||||
|
import { assertNativeReport } from '../test-native.mjs';
|
||||||
|
|
||||||
|
const passing = {
|
||||||
|
success: true,
|
||||||
|
numTotalTests: 6,
|
||||||
|
numPassedTests: 6,
|
||||||
|
numPendingTests: 0,
|
||||||
|
numTodoTests: 0,
|
||||||
|
numRuntimeErrorTestSuites: 0,
|
||||||
|
testResults: [
|
||||||
|
{
|
||||||
|
assertionResults: Array.from({ length: 6 }, () => ({
|
||||||
|
fullName: 'native PostgreSQL concurrency check',
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
test('requires complete passing evidence, including zero skipped tests', () => {
|
||||||
|
assert.doesNotThrow(() => assertNativeReport(passing));
|
||||||
|
for (const changed of [
|
||||||
|
{ success: false },
|
||||||
|
{ numTotalTests: 0, numPassedTests: 0 },
|
||||||
|
{ numPassedTests: 5 },
|
||||||
|
{ numPendingTests: 1 },
|
||||||
|
{ numTodoTests: 1 },
|
||||||
|
{ numRuntimeErrorTestSuites: 1 },
|
||||||
|
{ testResults: [] },
|
||||||
|
{
|
||||||
|
testResults: [
|
||||||
|
{ assertionResults: [{ fullName: 'ordinary embedded test' }] },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
])
|
||||||
|
assert.throws(() => assertNativeReport({ ...passing, ...changed }));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects absent or invalid database configuration without leaking it', () => {
|
||||||
|
for (const value of [
|
||||||
|
'',
|
||||||
|
'https://user:private-password@localhost/db',
|
||||||
|
'invalid',
|
||||||
|
]) {
|
||||||
|
const child = spawnSync(process.execPath, ['scripts/test-native.mjs'], {
|
||||||
|
env: { ...process.env, TEST_DATABASE_URL: value },
|
||||||
|
encoding: 'utf8',
|
||||||
|
});
|
||||||
|
assert.equal(child.status, 1);
|
||||||
|
assert.match(child.stderr, /Native gate failed/);
|
||||||
|
assert.doesNotMatch(child.stderr, /private-password/);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,16 @@
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
|
||||||
|
test('Express rejects IPv4 peers outside the configured trust subnet', () => {
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const platformRequire = createRequire(
|
||||||
|
require.resolve('@nestjs/platform-express'),
|
||||||
|
);
|
||||||
|
const expressRequire = createRequire(platformRequire.resolve('express'));
|
||||||
|
const proxyaddr = expressRequire('proxy-addr');
|
||||||
|
assert.equal(proxyaddr.compile('::ffff:10.0.0.0/8')('203.0.113.10'), false);
|
||||||
|
const trust = proxyaddr.compile('10.0.0.0/8');
|
||||||
|
assert.equal(trust('10.1.2.3'), true);
|
||||||
|
assert.equal(trust('203.0.113.10'), false);
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,21 @@
|
||||||
|
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 { sourceQuerySchema, type SourceQuery } from './source.schemas';
|
||||||
|
import { AccountingSourceStore } from './source.store';
|
||||||
|
@Controller('accounting')
|
||||||
|
@RequirePermission('accounting.read')
|
||||||
|
export class AccountingController {
|
||||||
|
constructor(private readonly sources: AccountingSourceStore) {}
|
||||||
|
@Get('source-events')
|
||||||
|
events(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Query(new SchemaPipe(sourceQuerySchema)) query: SourceQuery,
|
||||||
|
) {
|
||||||
|
return this.sources.events(actor, query);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,10 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { IdentityModule } from '../identity/identity.module';
|
||||||
|
import { AccountingController } from './accounting.controller';
|
||||||
|
import { AccountingSourceStore } from './source.store';
|
||||||
|
@Module({
|
||||||
|
imports: [IdentityModule],
|
||||||
|
controllers: [AccountingController],
|
||||||
|
providers: [AccountingSourceStore],
|
||||||
|
})
|
||||||
|
export class AccountingModule {}
|
||||||
|
|
@ -0,0 +1,53 @@
|
||||||
|
import { AppError } from '../common/errors/app-error';
|
||||||
|
import { commandHash } from '../common/idempotency';
|
||||||
|
import {
|
||||||
|
sourceCursorSchema,
|
||||||
|
type SourceQuery,
|
||||||
|
type SourceCursor,
|
||||||
|
} from './source.schemas';
|
||||||
|
export function sourceScope(organizationId: string, query: SourceQuery) {
|
||||||
|
return commandHash(
|
||||||
|
organizationId,
|
||||||
|
query.from.toISOString(),
|
||||||
|
query.to.toISOString(),
|
||||||
|
query.currency ?? '',
|
||||||
|
query.kind ?? '',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
export function decodeSourceCursor(
|
||||||
|
value: string | undefined,
|
||||||
|
scope: string,
|
||||||
|
query: SourceQuery,
|
||||||
|
): SourceCursor | null {
|
||||||
|
if (!value) return null;
|
||||||
|
try {
|
||||||
|
const parsed = sourceCursorSchema.safeParse(
|
||||||
|
JSON.parse(Buffer.from(value, 'base64url').toString('utf8')),
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
parsed.success &&
|
||||||
|
parsed.data.scope === scope &&
|
||||||
|
parsed.data.at >= query.from &&
|
||||||
|
parsed.data.at < query.to
|
||||||
|
)
|
||||||
|
return parsed.data;
|
||||||
|
} catch {
|
||||||
|
/* Invalid bytes/JSON become the same public validation error. */
|
||||||
|
}
|
||||||
|
throw new AppError('REQUEST_INVALID', 'Invalid accounting source cursor', [
|
||||||
|
'cursor',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
export function encodeSourceCursor(
|
||||||
|
row: { occurredAt: Date; eventType: string; sourceId: string },
|
||||||
|
scope: string,
|
||||||
|
) {
|
||||||
|
return Buffer.from(
|
||||||
|
JSON.stringify({
|
||||||
|
at: row.occurredAt.toISOString(),
|
||||||
|
type: row.eventType,
|
||||||
|
id: row.sourceId,
|
||||||
|
scope,
|
||||||
|
}),
|
||||||
|
).toString('base64url');
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,57 @@
|
||||||
|
import { Prisma } from '../generated/prisma/client';
|
||||||
|
import type { SourceQuery, SourceCursor } from './source.schemas';
|
||||||
|
export function accountingSourceQuery(
|
||||||
|
organizationId: string,
|
||||||
|
query: SourceQuery,
|
||||||
|
cursor: SourceCursor | null,
|
||||||
|
) {
|
||||||
|
const currency = query.currency
|
||||||
|
? Prisma.sql`AND e.currency = ${query.currency}`
|
||||||
|
: Prisma.empty;
|
||||||
|
const kind = query.kind
|
||||||
|
? Prisma.sql`AND e.event_type = ${query.kind}`
|
||||||
|
: Prisma.empty;
|
||||||
|
const after = cursor
|
||||||
|
? Prisma.sql`AND (e.occurred_at, e.event_type COLLATE "C", e.source_id) > (${cursor.at}, ${cursor.type}::text COLLATE "C", ${cursor.id}::uuid)`
|
||||||
|
: Prisma.empty;
|
||||||
|
return Prisma.sql`WITH events AS (
|
||||||
|
SELECT 'SUPPLIER_INVOICE'::text event_type, 'RECORD'::text operation, i.id source_id, i.created_at occurred_at,
|
||||||
|
i.invoice_date::text business_date, i.currency, i.payable_total::text amount,
|
||||||
|
i.merchandise_total::text merchandise_amount, i.tax_amount::text tax_amount, i.shipping_amount::text shipping_amount,
|
||||||
|
i.id related_id, 'SUPPLIER_INVOICE'::text related_type, i.supplier_id counterparty_id, 'SUPPLIER'::text counterparty_type,
|
||||||
|
NULL::text reverses_event_key
|
||||||
|
FROM supplier_invoices i WHERE i.organization_id = ${organizationId}::uuid
|
||||||
|
UNION ALL
|
||||||
|
SELECT 'SUPPLIER_INVOICE_VOID', 'VOID', v.invoice_id, v.created_at, NULL::text, i.currency, i.payable_total::text,
|
||||||
|
i.merchandise_total::text, i.tax_amount::text, i.shipping_amount::text, i.id, 'SUPPLIER_INVOICE', i.supplier_id, 'SUPPLIER', 'SUPPLIER_INVOICE:' || i.id::text
|
||||||
|
FROM supplier_invoice_voids v JOIN supplier_invoices i ON i.id = v.invoice_id AND i.organization_id = v.organization_id
|
||||||
|
WHERE v.organization_id = ${organizationId}::uuid
|
||||||
|
UNION ALL
|
||||||
|
SELECT 'SUPPLIER_PAYMENT', 'RECORD', p.id, p.created_at, p.paid_at::text, p.currency, p.amount::text,
|
||||||
|
NULL::text, NULL::text, NULL::text, p.invoice_id, 'SUPPLIER_INVOICE', i.supplier_id, 'SUPPLIER', NULL::text
|
||||||
|
FROM supplier_payments p JOIN supplier_invoices i ON i.id = p.invoice_id AND i.organization_id = p.organization_id
|
||||||
|
WHERE p.organization_id = ${organizationId}::uuid
|
||||||
|
UNION ALL
|
||||||
|
SELECT 'SUPPLIER_PAYMENT_REVERSAL', 'REVERSE', r.payment_id, r.created_at, NULL::text, p.currency, p.amount::text,
|
||||||
|
NULL::text, NULL::text, NULL::text, p.invoice_id, 'SUPPLIER_INVOICE', i.supplier_id, 'SUPPLIER', 'SUPPLIER_PAYMENT:' || p.id::text
|
||||||
|
FROM supplier_payment_reversals r JOIN supplier_payments p ON p.id = r.payment_id AND p.organization_id = r.organization_id
|
||||||
|
JOIN supplier_invoices i ON i.id = p.invoice_id AND i.organization_id = p.organization_id
|
||||||
|
WHERE r.organization_id = ${organizationId}::uuid
|
||||||
|
UNION ALL
|
||||||
|
SELECT 'PARTNER_RECEIPT', 'RECORD', p.id, p.created_at, p.received_on::text, p.currency, p.amount::text,
|
||||||
|
NULL::text, NULL::text, NULL::text, p.order_id, 'PARTNER_ORDER', o.account_id, 'B2B_ACCOUNT', NULL::text
|
||||||
|
FROM b2b_partner_payments p JOIN b2b_partner_orders o ON o.id = p.order_id AND o.organization_id = p.organization_id
|
||||||
|
WHERE p.organization_id = ${organizationId}::uuid
|
||||||
|
UNION ALL
|
||||||
|
SELECT 'PARTNER_RECEIPT_REVERSAL', 'REVERSE', r.payment_id, r.created_at, NULL::text, p.currency, p.amount::text,
|
||||||
|
NULL::text, NULL::text, NULL::text, p.order_id, 'PARTNER_ORDER', o.account_id, 'B2B_ACCOUNT', 'PARTNER_RECEIPT:' || p.id::text
|
||||||
|
FROM b2b_partner_payment_reversals r JOIN b2b_partner_payments p ON p.id = r.payment_id AND p.organization_id = r.organization_id
|
||||||
|
JOIN b2b_partner_orders o ON o.id = p.order_id AND o.organization_id = p.organization_id
|
||||||
|
WHERE r.organization_id = ${organizationId}::uuid
|
||||||
|
) SELECT e.event_type AS "eventType", e.operation, e.source_id AS "sourceId", e.occurred_at AS "occurredAt",
|
||||||
|
e.business_date AS "businessDate", e.currency, e.amount, e.merchandise_amount AS "merchandiseAmount",
|
||||||
|
e.tax_amount AS "taxAmount", e.shipping_amount AS "shippingAmount", e.related_id AS "relatedId", e.related_type AS "relatedType",
|
||||||
|
e.counterparty_id AS "counterpartyId", e.counterparty_type AS "counterpartyType", e.reverses_event_key AS "reversesEventKey"
|
||||||
|
FROM events e WHERE e.occurred_at >= ${query.from} AND e.occurred_at < ${query.to} ${currency} ${kind} ${after}
|
||||||
|
ORDER BY e.occurred_at, e.event_type COLLATE "C", e.source_id LIMIT ${query.limit + 1}`;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,30 @@
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { analyticsWindowSchema } from '../analytics/analytics.schemas';
|
||||||
|
export const SOURCE_KINDS = [
|
||||||
|
'SUPPLIER_INVOICE',
|
||||||
|
'SUPPLIER_INVOICE_VOID',
|
||||||
|
'SUPPLIER_PAYMENT',
|
||||||
|
'SUPPLIER_PAYMENT_REVERSAL',
|
||||||
|
'PARTNER_RECEIPT',
|
||||||
|
'PARTNER_RECEIPT_REVERSAL',
|
||||||
|
] as const;
|
||||||
|
export const sourceQuerySchema = analyticsWindowSchema.safeExtend({
|
||||||
|
kind: z.enum(SOURCE_KINDS).optional(),
|
||||||
|
limit: z.coerce.number().int().min(1).max(100).default(25),
|
||||||
|
cursor: z
|
||||||
|
.string()
|
||||||
|
.min(1)
|
||||||
|
.max(900)
|
||||||
|
.regex(/^[A-Za-z0-9_-]+$/)
|
||||||
|
.optional(),
|
||||||
|
});
|
||||||
|
export const sourceCursorSchema = z
|
||||||
|
.object({
|
||||||
|
at: analyticsWindowSchema.shape.from,
|
||||||
|
type: z.enum(SOURCE_KINDS),
|
||||||
|
id: z.uuid(),
|
||||||
|
scope: z.string().regex(/^[a-f0-9]{64}$/),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
export type SourceQuery = z.infer<typeof sourceQuerySchema>;
|
||||||
|
export type SourceCursor = z.infer<typeof sourceCursorSchema>;
|
||||||
|
|
@ -0,0 +1,73 @@
|
||||||
|
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 { accountingSourceQuery } from './source-query';
|
||||||
|
import {
|
||||||
|
sourceScope,
|
||||||
|
decodeSourceCursor,
|
||||||
|
encodeSourceCursor,
|
||||||
|
} from './source-cursor';
|
||||||
|
import type { SourceQuery } from './source.schemas';
|
||||||
|
type SourceRow = {
|
||||||
|
eventType: string;
|
||||||
|
operation: string;
|
||||||
|
sourceId: string;
|
||||||
|
occurredAt: Date;
|
||||||
|
businessDate: string | null;
|
||||||
|
currency: string;
|
||||||
|
amount: string;
|
||||||
|
merchandiseAmount: string | null;
|
||||||
|
taxAmount: string | null;
|
||||||
|
shippingAmount: string | null;
|
||||||
|
relatedId: string;
|
||||||
|
relatedType: string;
|
||||||
|
counterpartyId: string;
|
||||||
|
counterpartyType: string;
|
||||||
|
reversesEventKey: string | null;
|
||||||
|
};
|
||||||
|
const fixed = (amount: string) => new Prisma.Decimal(amount).toFixed(2);
|
||||||
|
@Injectable()
|
||||||
|
export class AccountingSourceStore {
|
||||||
|
constructor(private readonly access: AccessStore) {}
|
||||||
|
events(actor: Principal, query: SourceQuery) {
|
||||||
|
return this.access.mutate(
|
||||||
|
actor,
|
||||||
|
'accounting.read',
|
||||||
|
async (tx) => {
|
||||||
|
const scope = sourceScope(actor.organizationId, query);
|
||||||
|
const cursor = decodeSourceCursor(query.cursor, scope, query);
|
||||||
|
const rows = await tx.$queryRaw<SourceRow[]>(
|
||||||
|
accountingSourceQuery(actor.organizationId, query, cursor),
|
||||||
|
);
|
||||||
|
const page = rows.slice(0, query.limit);
|
||||||
|
return {
|
||||||
|
schemaVersion: 1,
|
||||||
|
window: {
|
||||||
|
from: query.from.toISOString(),
|
||||||
|
to: query.to.toISOString(),
|
||||||
|
currency: query.currency ?? null,
|
||||||
|
kind: query.kind ?? null,
|
||||||
|
},
|
||||||
|
events: page.map((row) => ({
|
||||||
|
...row,
|
||||||
|
eventKey: row.eventType + ':' + row.sourceId,
|
||||||
|
amount: fixed(row.amount),
|
||||||
|
merchandiseAmount:
|
||||||
|
row.merchandiseAmount === null
|
||||||
|
? null
|
||||||
|
: fixed(row.merchandiseAmount),
|
||||||
|
taxAmount: row.taxAmount === null ? null : fixed(row.taxAmount),
|
||||||
|
shippingAmount:
|
||||||
|
row.shippingAmount === null ? null : fixed(row.shippingAmount),
|
||||||
|
})),
|
||||||
|
nextCursor:
|
||||||
|
rows.length > query.limit
|
||||||
|
? encodeSourceCursor(page[page.length - 1], scope)
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,53 @@
|
||||||
|
import { Prisma } from '../generated/prisma/client';
|
||||||
|
import type { AnalyticsWindow, AnalyticsVariants } from './analytics.schemas';
|
||||||
|
|
||||||
|
export function commerceCohort(
|
||||||
|
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 (${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",
|
||||||
|
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 (${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",
|
||||||
|
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}`;
|
||||||
|
}
|
||||||
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
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, ForecastsController],
|
||||||
|
providers: [AnalyticsStore, ForecastStore],
|
||||||
|
})
|
||||||
|
export class AnalyticsModule {}
|
||||||
|
|
@ -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<typeof analyticsWindowSchema>;
|
||||||
|
export type AnalyticsVariants = z.infer<typeof analyticsVariantsSchema>;
|
||||||
|
|
@ -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<DailyRow[]>(
|
||||||
|
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<VariantRow[]>(
|
||||||
|
variantsQuery(actor.organizationId, input, now),
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
window: windowView(input),
|
||||||
|
asOf: now.toISOString(),
|
||||||
|
variants: rows.map((row) => ({
|
||||||
|
...row,
|
||||||
|
capturedLineValue: fixed(row.capturedLineValue),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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();
|
||||||
|
}
|
||||||
|
|
@ -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}`;
|
||||||
|
}
|
||||||
|
|
@ -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<typeof captureForecastSchema>;
|
||||||
|
|
@ -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<CaptureRow[]>(
|
||||||
|
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,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -18,9 +18,15 @@ import { MessagingModule } from './messaging/messaging.module';
|
||||||
import { BlogModule } from './blog/blog.module';
|
import { BlogModule } from './blog/blog.module';
|
||||||
import { SegmentsModule } from './segments/segments.module';
|
import { SegmentsModule } from './segments/segments.module';
|
||||||
import { ForumModule } from './forum/forum.module';
|
import { ForumModule } from './forum/forum.module';
|
||||||
|
import { AnalyticsModule } from './analytics/analytics.module';
|
||||||
|
import { AccountingModule } from './accounting/accounting.module';
|
||||||
|
import { WorkflowsModule } from './workflows/workflows.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
|
WorkflowsModule,
|
||||||
|
AccountingModule,
|
||||||
|
AnalyticsModule,
|
||||||
ForumModule,
|
ForumModule,
|
||||||
SegmentsModule,
|
SegmentsModule,
|
||||||
BlogModule,
|
BlogModule,
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,11 @@ import { ProductsController } from './products.controller';
|
||||||
import { GroupsController } from './groups.controller';
|
import { GroupsController } from './groups.controller';
|
||||||
import { StorefrontController } from './storefront.controller';
|
import { StorefrontController } from './storefront.controller';
|
||||||
import { StorefrontGuard } from './storefront.guard';
|
import { StorefrontGuard } from './storefront.guard';
|
||||||
|
import { ProductImageStore } from './product-image.store';
|
||||||
|
import {
|
||||||
|
ProductImagesController,
|
||||||
|
StorefrontImagesController,
|
||||||
|
} from './product-images.controller';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [DatabaseModule, IdentityModule],
|
imports: [DatabaseModule, IdentityModule],
|
||||||
|
|
@ -18,7 +23,14 @@ import { StorefrontGuard } from './storefront.guard';
|
||||||
GroupStore,
|
GroupStore,
|
||||||
StorefrontStore,
|
StorefrontStore,
|
||||||
StorefrontGuard,
|
StorefrontGuard,
|
||||||
|
ProductImageStore,
|
||||||
|
],
|
||||||
|
controllers: [
|
||||||
|
ProductsController,
|
||||||
|
GroupsController,
|
||||||
|
StorefrontController,
|
||||||
|
ProductImagesController,
|
||||||
|
StorefrontImagesController,
|
||||||
],
|
],
|
||||||
controllers: [ProductsController, GroupsController, StorefrontController],
|
|
||||||
})
|
})
|
||||||
export class CatalogModule {}
|
export class CatalogModule {}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,38 @@
|
||||||
|
import { AppError } from '../common/errors/app-error';
|
||||||
|
import { fileDigest } from '../common/file-digest';
|
||||||
|
import type { UploadedDocument } from '../procurement/supplier-document-file';
|
||||||
|
|
||||||
|
export const MAX_PRODUCT_IMAGE_BYTES = 2 * 1024 * 1024;
|
||||||
|
export const MAX_PRODUCT_IMAGES = 8;
|
||||||
|
|
||||||
|
// The declared type must match the file's own signature, so a renamed script or SVG is rejected.
|
||||||
|
function signature(bytes: Buffer) {
|
||||||
|
if (bytes.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')))
|
||||||
|
return 'image/png';
|
||||||
|
if (bytes.subarray(0, 3).equals(Buffer.from('ffd8ff', 'hex')))
|
||||||
|
return 'image/jpeg';
|
||||||
|
if (
|
||||||
|
bytes.subarray(0, 4).toString('latin1') === 'RIFF' &&
|
||||||
|
bytes.subarray(8, 12).toString('latin1') === 'WEBP'
|
||||||
|
)
|
||||||
|
return 'image/webp';
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function inspectProductImage(file?: UploadedDocument) {
|
||||||
|
const bytes = file?.buffer;
|
||||||
|
if (
|
||||||
|
!file ||
|
||||||
|
!bytes?.length ||
|
||||||
|
bytes.length > MAX_PRODUCT_IMAGE_BYTES ||
|
||||||
|
file.size !== bytes.length ||
|
||||||
|
signature(bytes) !== file.mimetype
|
||||||
|
)
|
||||||
|
throw new AppError('PRODUCT_IMAGE_INVALID');
|
||||||
|
return {
|
||||||
|
mimeType: file.mimetype,
|
||||||
|
sha256: fileDigest(bytes),
|
||||||
|
size: bytes.length,
|
||||||
|
content: Uint8Array.from(bytes),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,87 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { DatabaseService } from '../database/database.service';
|
||||||
|
import { AccessStore } from '../identity/access.store';
|
||||||
|
import { recordAudit } from '../identity/audit';
|
||||||
|
import type { Principal } from '../identity/identity.types';
|
||||||
|
import { AppError } from '../common/errors/app-error';
|
||||||
|
import type { UploadedDocument } from '../procurement/supplier-document-file';
|
||||||
|
import { editableProduct } from './catalog.helpers';
|
||||||
|
import { inspectProductImage, MAX_PRODUCT_IMAGES } from './product-image-file';
|
||||||
|
|
||||||
|
export const imageSummary = {
|
||||||
|
id: true,
|
||||||
|
mimeType: true,
|
||||||
|
size: true,
|
||||||
|
createdAt: true,
|
||||||
|
} as const;
|
||||||
|
export const imageOrder = [
|
||||||
|
{ createdAt: 'asc' as const },
|
||||||
|
{ id: 'asc' as const },
|
||||||
|
];
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ProductImageStore {
|
||||||
|
constructor(
|
||||||
|
private readonly db: DatabaseService,
|
||||||
|
private readonly access: AccessStore,
|
||||||
|
) {}
|
||||||
|
add(actor: Principal, productId: string, file?: UploadedDocument) {
|
||||||
|
const image = inspectProductImage(file);
|
||||||
|
return this.access.mutate(actor, 'catalog.manage', async (tx) => {
|
||||||
|
await editableProduct(tx, actor.organizationId, productId);
|
||||||
|
// The product row lock serializes concurrent uploads against the quota.
|
||||||
|
await tx.$queryRaw`SELECT id FROM products WHERE id = ${productId}::uuid FOR UPDATE`;
|
||||||
|
if (
|
||||||
|
(await tx.productImage.count({ where: { productId } })) >=
|
||||||
|
MAX_PRODUCT_IMAGES
|
||||||
|
)
|
||||||
|
throw new AppError('PRODUCT_IMAGE_LIMIT');
|
||||||
|
const saved = await tx.productImage.create({
|
||||||
|
data: { ...image, productId, organizationId: actor.organizationId },
|
||||||
|
select: imageSummary,
|
||||||
|
});
|
||||||
|
await recordAudit(
|
||||||
|
tx,
|
||||||
|
actor.organizationId,
|
||||||
|
actor.userId,
|
||||||
|
'product.image_added',
|
||||||
|
productId,
|
||||||
|
);
|
||||||
|
return saved;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
remove(actor: Principal, productId: string, imageId: string) {
|
||||||
|
return this.access.mutate(actor, 'catalog.manage', async (tx) => {
|
||||||
|
await editableProduct(tx, actor.organizationId, productId);
|
||||||
|
const { count } = await tx.productImage.deleteMany({
|
||||||
|
where: { id: imageId, productId, organizationId: actor.organizationId },
|
||||||
|
});
|
||||||
|
if (!count) throw new AppError('PRODUCT_IMAGE_NOT_FOUND');
|
||||||
|
await recordAudit(
|
||||||
|
tx,
|
||||||
|
actor.organizationId,
|
||||||
|
actor.userId,
|
||||||
|
'product.image_removed',
|
||||||
|
productId,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Public: only images of published products in the requested organization.
|
||||||
|
async publicImage(
|
||||||
|
organizationId: string,
|
||||||
|
productId: string,
|
||||||
|
imageId: string,
|
||||||
|
) {
|
||||||
|
const image = await this.db.productImage.findFirst({
|
||||||
|
where: {
|
||||||
|
id: imageId,
|
||||||
|
productId,
|
||||||
|
organizationId,
|
||||||
|
product: { status: 'PUBLISHED' },
|
||||||
|
},
|
||||||
|
select: { mimeType: true, content: true },
|
||||||
|
});
|
||||||
|
if (!image) throw new AppError('PRODUCT_IMAGE_NOT_FOUND');
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,86 @@
|
||||||
|
import {
|
||||||
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
HttpCode,
|
||||||
|
Param,
|
||||||
|
ParseUUIDPipe,
|
||||||
|
Post,
|
||||||
|
Res,
|
||||||
|
UploadedFile,
|
||||||
|
UseGuards,
|
||||||
|
UseInterceptors,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { FileInterceptor } from '@nestjs/platform-express';
|
||||||
|
import { ApiBody, ApiConsumes, ApiProduces } from '@nestjs/swagger';
|
||||||
|
import type { Response } from 'express';
|
||||||
|
import {
|
||||||
|
CurrentPrincipal,
|
||||||
|
Public,
|
||||||
|
RequirePermission,
|
||||||
|
} from '../identity/access.decorator';
|
||||||
|
import type { Principal } from '../identity/identity.types';
|
||||||
|
import type { UploadedDocument } from '../procurement/supplier-document-file';
|
||||||
|
import { MAX_PRODUCT_IMAGE_BYTES } from './product-image-file';
|
||||||
|
import { ProductImageStore } from './product-image.store';
|
||||||
|
import { StorefrontGuard } from './storefront.guard';
|
||||||
|
|
||||||
|
@Controller('products/:id/images')
|
||||||
|
export class ProductImagesController {
|
||||||
|
constructor(private readonly images: ProductImageStore) {}
|
||||||
|
@Post()
|
||||||
|
@RequirePermission('catalog.manage')
|
||||||
|
@ApiConsumes('multipart/form-data')
|
||||||
|
@ApiBody({
|
||||||
|
schema: {
|
||||||
|
type: 'object',
|
||||||
|
required: ['file'],
|
||||||
|
properties: { file: { type: 'string', format: 'binary' } },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
@UseInterceptors(
|
||||||
|
FileInterceptor('file', {
|
||||||
|
limits: { fileSize: MAX_PRODUCT_IMAGE_BYTES + 1, files: 1, fields: 0 },
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
add(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
@UploadedFile() file?: UploadedDocument,
|
||||||
|
) {
|
||||||
|
return this.images.add(actor, id, file);
|
||||||
|
}
|
||||||
|
@Delete(':imageId')
|
||||||
|
@RequirePermission('catalog.manage')
|
||||||
|
@HttpCode(204)
|
||||||
|
remove(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
@Param('imageId', ParseUUIDPipe) imageId: string,
|
||||||
|
) {
|
||||||
|
return this.images.remove(actor, id, imageId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@UseGuards(StorefrontGuard)
|
||||||
|
@Controller('storefront/:organizationId/products/:id/images')
|
||||||
|
export class StorefrontImagesController {
|
||||||
|
constructor(private readonly images: ProductImageStore) {}
|
||||||
|
@Get(':imageId')
|
||||||
|
@ApiProduces('image/jpeg', 'image/png', 'image/webp')
|
||||||
|
async get(
|
||||||
|
@Param('organizationId', ParseUUIDPipe) organizationId: string,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
@Param('imageId', ParseUUIDPipe) imageId: string,
|
||||||
|
@Res() response: Response,
|
||||||
|
) {
|
||||||
|
const image = await this.images.publicImage(organizationId, id, imageId);
|
||||||
|
response.setHeader('Content-Type', image.mimeType);
|
||||||
|
response.setHeader('X-Content-Type-Options', 'nosniff');
|
||||||
|
response.setHeader('Content-Security-Policy', 'sandbox');
|
||||||
|
// Image rows are never edited, so an ID always names the same bytes.
|
||||||
|
response.setHeader('Cache-Control', 'public, max-age=86400, immutable');
|
||||||
|
response.send(Buffer.from(image.content));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -11,6 +11,7 @@ import {
|
||||||
validateGroups,
|
validateGroups,
|
||||||
} from './catalog.helpers';
|
} from './catalog.helpers';
|
||||||
import type { CatalogQuery, ProductInput } from './catalog.schemas';
|
import type { CatalogQuery, ProductInput } from './catalog.schemas';
|
||||||
|
import { imageOrder, imageSummary } from './product-image.store';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ProductStore {
|
export class ProductStore {
|
||||||
|
|
@ -34,6 +35,7 @@ export class ProductStore {
|
||||||
include: {
|
include: {
|
||||||
variants: { orderBy: { id: 'asc' } },
|
variants: { orderBy: { id: 'asc' } },
|
||||||
groups: { include: { group: true } },
|
groups: { include: { group: true } },
|
||||||
|
images: { orderBy: imageOrder, select: imageSummary },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ import { Injectable } from '@nestjs/common';
|
||||||
import { DatabaseService } from '../database/database.service';
|
import { DatabaseService } from '../database/database.service';
|
||||||
import { AppError } from '../common/errors/app-error';
|
import { AppError } from '../common/errors/app-error';
|
||||||
import type { CatalogQuery } from './catalog.schemas';
|
import type { CatalogQuery } from './catalog.schemas';
|
||||||
|
import { imageOrder } from './product-image.store';
|
||||||
|
|
||||||
const storefrontView = {
|
const storefrontView = {
|
||||||
id: true,
|
id: true,
|
||||||
|
|
@ -21,6 +22,7 @@ const storefrontView = {
|
||||||
attributes: true,
|
attributes: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
images: { orderBy: imageOrder, select: { id: true } },
|
||||||
groups: {
|
groups: {
|
||||||
select: {
|
select: {
|
||||||
group: { select: { id: true, name: true, slug: true, kind: true } },
|
group: { select: { id: true, name: true, slug: true, kind: true } },
|
||||||
|
|
@ -33,7 +35,12 @@ export class StorefrontStore {
|
||||||
list(organizationId: string, query: CatalogQuery) {
|
list(organizationId: string, query: CatalogQuery) {
|
||||||
return this.db.product.findMany({
|
return this.db.product.findMany({
|
||||||
where: catalogWhere(organizationId, query, true),
|
where: catalogWhere(organizationId, query, true),
|
||||||
select: { id: true, name: true, slug: true },
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
slug: true,
|
||||||
|
images: { orderBy: imageOrder, take: 1, select: { id: true } },
|
||||||
|
},
|
||||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||||
take: query.limit,
|
take: query.limit,
|
||||||
skip: query.offset,
|
skip: query.offset,
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,40 @@
|
||||||
|
import type { Prisma } from '../generated/prisma/client';
|
||||||
|
import type { Principal } from '../identity/identity.types';
|
||||||
|
import { lockStock } from '../inventory/stock-lock';
|
||||||
|
import { enqueueEvent } from '../events/enqueue-event';
|
||||||
|
import { recordAudit } from '../identity/audit';
|
||||||
|
import { orderView } from './order-view';
|
||||||
|
export const cancellationInclude = {
|
||||||
|
lines: true,
|
||||||
|
pricing: true,
|
||||||
|
reservations: { orderBy: { stockItemId: 'asc' as const } },
|
||||||
|
};
|
||||||
|
type CancellableOrder = Prisma.OrderGetPayload<{
|
||||||
|
include: typeof cancellationInclude;
|
||||||
|
}>;
|
||||||
|
export async function cancelOrderRecord(
|
||||||
|
tx: Prisma.TransactionClient,
|
||||||
|
actor: Principal,
|
||||||
|
order: CancellableOrder,
|
||||||
|
action: 'order.cancelled' | 'order.expired' = 'order.cancelled',
|
||||||
|
) {
|
||||||
|
if (order.status === 'CANCELLED') return orderView(order);
|
||||||
|
for (const reservation of order.reservations)
|
||||||
|
await lockStock(tx, actor.organizationId, reservation.stockItemId);
|
||||||
|
await tx.stockReservation.updateMany({
|
||||||
|
where: {
|
||||||
|
orderId: order.id,
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
status: 'ACTIVE',
|
||||||
|
},
|
||||||
|
data: { status: 'RELEASED' },
|
||||||
|
});
|
||||||
|
const updated = await tx.order.update({
|
||||||
|
where: { id: order.id },
|
||||||
|
data: { status: 'CANCELLED' },
|
||||||
|
include: { lines: true, pricing: true },
|
||||||
|
});
|
||||||
|
await enqueueEvent(tx, actor.organizationId, order.id, 'order.cancelled');
|
||||||
|
await recordAudit(tx, actor.organizationId, actor.userId, action, order.id);
|
||||||
|
return orderView(updated);
|
||||||
|
}
|
||||||
|
|
@ -2,11 +2,9 @@ import { Injectable } from '@nestjs/common';
|
||||||
import { DatabaseService } from '../database/database.service';
|
import { DatabaseService } from '../database/database.service';
|
||||||
import { AccessStore } from '../identity/access.store';
|
import { AccessStore } from '../identity/access.store';
|
||||||
import type { Principal } from '../identity/identity.types';
|
import type { Principal } from '../identity/identity.types';
|
||||||
import { recordAudit } from '../identity/audit';
|
|
||||||
import { AppError } from '../common/errors/app-error';
|
import { AppError } from '../common/errors/app-error';
|
||||||
import { lockStock } from '../inventory/stock-lock';
|
|
||||||
import { orderView, orderStatus } from './order-view';
|
import { orderView, orderStatus } from './order-view';
|
||||||
import { enqueueEvent } from '../events/enqueue-event';
|
import { cancellationInclude, cancelOrderRecord } from './cancel-order';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class OrderStore {
|
export class OrderStore {
|
||||||
|
|
@ -67,34 +65,10 @@ export class OrderStore {
|
||||||
organizationId: actor.organizationId,
|
organizationId: actor.organizationId,
|
||||||
...(!staff ? { userId: actor.userId } : {}),
|
...(!staff ? { userId: actor.userId } : {}),
|
||||||
},
|
},
|
||||||
include: {
|
include: cancellationInclude,
|
||||||
lines: true,
|
|
||||||
pricing: true,
|
|
||||||
reservations: { orderBy: { stockItemId: 'asc' } },
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
if (!order) throw new AppError('ORDER_NOT_FOUND');
|
if (!order) throw new AppError('ORDER_NOT_FOUND');
|
||||||
if (order.status === 'CANCELLED') return orderView(order);
|
return cancelOrderRecord(tx, actor, order);
|
||||||
for (const reservation of order.reservations)
|
|
||||||
await lockStock(tx, actor.organizationId, reservation.stockItemId);
|
|
||||||
await tx.stockReservation.updateMany({
|
|
||||||
where: { orderId: id, status: 'ACTIVE' },
|
|
||||||
data: { status: 'RELEASED' },
|
|
||||||
});
|
|
||||||
const updated = await tx.order.update({
|
|
||||||
where: { id },
|
|
||||||
data: { status: 'CANCELLED' },
|
|
||||||
include: { lines: true, pricing: true },
|
|
||||||
});
|
|
||||||
await enqueueEvent(tx, actor.organizationId, id, 'order.cancelled');
|
|
||||||
await recordAudit(
|
|
||||||
tx,
|
|
||||||
actor.organizationId,
|
|
||||||
actor.userId,
|
|
||||||
'order.cancelled',
|
|
||||||
id,
|
|
||||||
);
|
|
||||||
return orderView(updated);
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,37 @@
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import 'dotenv/config';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { AppModule } from '../app.module';
|
||||||
|
import { SessionStore } from '../identity/session.store';
|
||||||
|
import { OrderExpiryStore } from '../workflows/order-expiry.store';
|
||||||
|
import { expiryRunSchema } from '../workflows/workflow.schemas';
|
||||||
|
export async function runExpiryCommand(environment = process.env) {
|
||||||
|
const token = z
|
||||||
|
.string()
|
||||||
|
.regex(/^[A-Za-z0-9_-]{43}$/)
|
||||||
|
.parse(environment.WORKFLOW_TOKEN);
|
||||||
|
const input = expiryRunSchema.parse({
|
||||||
|
limit: Number(environment.WORKFLOW_LIMIT ?? 10),
|
||||||
|
idempotencyKey: environment.WORKFLOW_RUN_KEY ?? randomUUID(),
|
||||||
|
});
|
||||||
|
const app = await NestFactory.createApplicationContext(AppModule, {
|
||||||
|
logger: false,
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const actor = await app.get(SessionStore).authenticate(token);
|
||||||
|
return await app.get(OrderExpiryStore).run(actor, input);
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (require.main === module)
|
||||||
|
void runExpiryCommand()
|
||||||
|
.then((result) => console.log(JSON.stringify(result)))
|
||||||
|
.catch(() => {
|
||||||
|
console.error(
|
||||||
|
'Order expiry workflow failed. Check authentication, permissions and database availability.',
|
||||||
|
);
|
||||||
|
process.exitCode = 1;
|
||||||
|
});
|
||||||
|
|
@ -10,6 +10,21 @@ export const COMMERCE_ERRORS = {
|
||||||
'Archived products cannot be edited',
|
'Archived products cannot be edited',
|
||||||
'Archived product mutation rejected',
|
'Archived product mutation rejected',
|
||||||
],
|
],
|
||||||
|
PRODUCT_IMAGE_NOT_FOUND: [
|
||||||
|
404,
|
||||||
|
'Product image not found',
|
||||||
|
'Scoped product image lookup failed',
|
||||||
|
],
|
||||||
|
PRODUCT_IMAGE_LIMIT: [
|
||||||
|
409,
|
||||||
|
'Product image limit reached',
|
||||||
|
'Product image quota exceeded',
|
||||||
|
],
|
||||||
|
PRODUCT_IMAGE_INVALID: [
|
||||||
|
400,
|
||||||
|
'Image must be a JPEG, PNG or WebP file up to 2 MiB',
|
||||||
|
'Product image upload bytes, size or type rejected',
|
||||||
|
],
|
||||||
VARIANT_NOT_FOUND: [
|
VARIANT_NOT_FOUND: [
|
||||||
404,
|
404,
|
||||||
'Product variant not found',
|
'Product variant not found',
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ import { CAMPAIGN_ERRORS } from './campaign-errors';
|
||||||
import { MESSAGING_ERRORS } from './messaging-errors';
|
import { MESSAGING_ERRORS } from './messaging-errors';
|
||||||
import { BLOG_ERRORS } from './blog-errors';
|
import { BLOG_ERRORS } from './blog-errors';
|
||||||
import { FORUM_ERRORS } from './forum-errors';
|
import { FORUM_ERRORS } from './forum-errors';
|
||||||
|
import { PROFITABILITY_ERRORS } from './profitability-errors';
|
||||||
import { CHECKOUT_ERRORS } from './checkout-errors';
|
import { CHECKOUT_ERRORS } from './checkout-errors';
|
||||||
import { OPERATIONS_ERRORS } from './operations-errors';
|
import { OPERATIONS_ERRORS } from './operations-errors';
|
||||||
import { PLATFORM_ERRORS } from './platform-errors';
|
import { PLATFORM_ERRORS } from './platform-errors';
|
||||||
|
|
@ -18,6 +19,7 @@ import { B2B_ARTWORK_ERRORS } from './b2b-artwork-errors';
|
||||||
import { B2B_ORDER_ERRORS } from './b2b-order-errors';
|
import { B2B_ORDER_ERRORS } from './b2b-order-errors';
|
||||||
import { B2B_PAYMENT_ERRORS } from './b2b-payment-errors';
|
import { B2B_PAYMENT_ERRORS } from './b2b-payment-errors';
|
||||||
export const ERRORS = {
|
export const ERRORS = {
|
||||||
|
...PROFITABILITY_ERRORS,
|
||||||
...FORUM_ERRORS,
|
...FORUM_ERRORS,
|
||||||
...BLOG_ERRORS,
|
...BLOG_ERRORS,
|
||||||
...MESSAGING_ERRORS,
|
...MESSAGING_ERRORS,
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
export const PROFITABILITY_ERRORS = {
|
||||||
|
PROFITABILITY_CURRENCY: [
|
||||||
|
409,
|
||||||
|
'Comparison currency must match the cost snapshot',
|
||||||
|
'Profitability currency mismatch',
|
||||||
|
],
|
||||||
|
PROFITABILITY_QUANTITY: [
|
||||||
|
409,
|
||||||
|
'Batch output quantity is invalid',
|
||||||
|
'Invalid batch contribution quantity',
|
||||||
|
],
|
||||||
|
} as const;
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import { identityEnvironmentShape, validateSmtp } from './identity-environment';
|
import { identityEnvironmentShape, validateSmtp } from './identity-environment';
|
||||||
|
import { isIP } from 'node:net';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
const schema = z
|
const schema = z
|
||||||
|
|
@ -12,6 +13,17 @@ const schema = z
|
||||||
.enum(['true', 'false'])
|
.enum(['true', 'false'])
|
||||||
.transform((value) => value === 'true')
|
.transform((value) => value === 'true')
|
||||||
.optional(),
|
.optional(),
|
||||||
|
// Proxies whose X-Forwarded-For is believed. Never "true": any client could spoof its IP.
|
||||||
|
TRUST_PROXY: z
|
||||||
|
.string()
|
||||||
|
.default('')
|
||||||
|
.transform((value) =>
|
||||||
|
value
|
||||||
|
.split(',')
|
||||||
|
.map((entry) => entry.trim())
|
||||||
|
.filter(Boolean),
|
||||||
|
)
|
||||||
|
.pipe(z.array(z.string().refine(isTrustedProxy))),
|
||||||
DATABASE_POOL_SIZE: z.coerce.number().int().min(1).max(50).default(10),
|
DATABASE_POOL_SIZE: z.coerce.number().int().min(1).max(50).default(10),
|
||||||
DATABASE_URL: z.url().refine((value) => /^postgres(ql)?:/.test(value)),
|
DATABASE_URL: z.url().refine((value) => /^postgres(ql)?:/.test(value)),
|
||||||
CORS_ORIGINS: z
|
CORS_ORIGINS: z
|
||||||
|
|
@ -39,6 +51,18 @@ const schema = z
|
||||||
|
|
||||||
export type Environment = z.infer<typeof schema>;
|
export type Environment = z.infer<typeof schema>;
|
||||||
|
|
||||||
|
const PROXY_NAMES = ['loopback', 'linklocal', 'uniquelocal'];
|
||||||
|
function isTrustedProxy(entry: string): boolean {
|
||||||
|
if (PROXY_NAMES.includes(entry)) return true;
|
||||||
|
const [address, prefix, extra] = entry.split('/');
|
||||||
|
const family = isIP(address);
|
||||||
|
if (!family || extra !== undefined) return false;
|
||||||
|
if (prefix === undefined) return true;
|
||||||
|
return (
|
||||||
|
/^\d{1,3}$/.test(prefix) && Number(prefix) <= (family === 4 ? 32 : 128)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function parseEnvironment(input: NodeJS.ProcessEnv): Environment {
|
export function parseEnvironment(input: NodeJS.ProcessEnv): Environment {
|
||||||
const result = schema.safeParse(input);
|
const result = schema.safeParse(input);
|
||||||
if (!result.success) {
|
if (!result.success) {
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,8 @@ export function configureApp(
|
||||||
app: INestApplication,
|
app: INestApplication,
|
||||||
environment: Environment,
|
environment: Environment,
|
||||||
): void {
|
): void {
|
||||||
|
if (environment.TRUST_PROXY.length)
|
||||||
|
(app as NestExpressApplication).set('trust proxy', environment.TRUST_PROXY);
|
||||||
app.setGlobalPrefix('api/v1');
|
app.setGlobalPrefix('api/v1');
|
||||||
app.use(helmet());
|
app.use(helmet());
|
||||||
app.use((_request: Request, response: Response, next: NextFunction) => {
|
app.use((_request: Request, response: Response, next: NextFunction) => {
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,42 @@
|
||||||
|
import { minor } from '../checkout/money';
|
||||||
|
import { AppError } from '../common/errors/app-error';
|
||||||
|
|
||||||
|
function signedMoney(value: bigint) {
|
||||||
|
const magnitude = value < 0n ? -value : value;
|
||||||
|
return `${value < 0n ? '-' : ''}${magnitude / 100n}.${(magnitude % 100n).toString().padStart(2, '0')}`;
|
||||||
|
}
|
||||||
|
export function materialContribution(
|
||||||
|
totalCost: string,
|
||||||
|
goodQuantity: number,
|
||||||
|
unitNetPrice: string,
|
||||||
|
) {
|
||||||
|
if (!Number.isInteger(goodQuantity) || goodQuantity < 0)
|
||||||
|
throw new AppError('PROFITABILITY_QUANTITY');
|
||||||
|
const cost = minor(totalCost);
|
||||||
|
const quantity = BigInt(goodQuantity);
|
||||||
|
const comparison = minor(unitNetPrice) * quantity;
|
||||||
|
const contribution = comparison - cost;
|
||||||
|
const magnitude = contribution < 0n ? -contribution : contribution;
|
||||||
|
const roundedRate =
|
||||||
|
comparison === 0n
|
||||||
|
? null
|
||||||
|
: (magnitude * 10000n + comparison / 2n) / comparison;
|
||||||
|
return {
|
||||||
|
comparisonNetValue: signedMoney(comparison),
|
||||||
|
materialContribution: signedMoney(contribution),
|
||||||
|
contributionRateBps:
|
||||||
|
roundedRate === null
|
||||||
|
? null
|
||||||
|
: (contribution < 0n ? -roundedRate : roundedRate).toString(),
|
||||||
|
breakEvenUnitNetPrice:
|
||||||
|
quantity === 0n ? null : signedMoney((cost + quantity - 1n) / quantity),
|
||||||
|
comparisonState:
|
||||||
|
quantity === 0n
|
||||||
|
? 'NO_GOOD_OUTPUT'
|
||||||
|
: contribution > 0n
|
||||||
|
? 'ABOVE_MATERIAL_BREAK_EVEN'
|
||||||
|
: contribution < 0n
|
||||||
|
? 'BELOW_MATERIAL_BREAK_EVEN'
|
||||||
|
: 'AT_MATERIAL_BREAK_EVEN',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
@ -4,6 +4,8 @@ import { IdentityModule } from '../identity/identity.module';
|
||||||
import { CostingStore } from './costing.store';
|
import { CostingStore } from './costing.store';
|
||||||
import { BatchCostController } from './batch-cost.controller';
|
import { BatchCostController } from './batch-cost.controller';
|
||||||
import { BatchCostStore } from './batch-cost.store';
|
import { BatchCostStore } from './batch-cost.store';
|
||||||
|
import { ProfitabilityStore } from './profitability.store';
|
||||||
|
import { ProfitabilityController } from './profitability.controller';
|
||||||
import {
|
import {
|
||||||
MaterialCostRatesController,
|
MaterialCostRatesController,
|
||||||
PackagingCostController,
|
PackagingCostController,
|
||||||
|
|
@ -12,8 +14,9 @@ import {
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [DatabaseModule, IdentityModule],
|
imports: [DatabaseModule, IdentityModule],
|
||||||
providers: [CostingStore, BatchCostStore],
|
providers: [CostingStore, BatchCostStore, ProfitabilityStore],
|
||||||
controllers: [
|
controllers: [
|
||||||
|
ProfitabilityController,
|
||||||
MaterialCostRatesController,
|
MaterialCostRatesController,
|
||||||
ProductionCostController,
|
ProductionCostController,
|
||||||
PackagingCostController,
|
PackagingCostController,
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
import { Controller, Get, Param, ParseUUIDPipe, 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 {
|
||||||
|
contributionQuerySchema,
|
||||||
|
type ContributionQuery,
|
||||||
|
} from './profitability.schemas';
|
||||||
|
import { ProfitabilityStore } from './profitability.store';
|
||||||
|
@Controller('profitability/batches')
|
||||||
|
@RequirePermission('profitability.read')
|
||||||
|
export class ProfitabilityController {
|
||||||
|
constructor(private readonly profitability: ProfitabilityStore) {}
|
||||||
|
@Get(':batchId')
|
||||||
|
batch(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Param('batchId', ParseUUIDPipe) batchId: string,
|
||||||
|
@Query(new SchemaPipe(contributionQuerySchema)) query: ContributionQuery,
|
||||||
|
) {
|
||||||
|
return this.profitability.batch(actor, batchId, query);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,8 @@
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { costQuerySchema } from './costing.schemas';
|
||||||
|
export const contributionQuerySchema = costQuerySchema
|
||||||
|
.extend({
|
||||||
|
unitNetPrice: z.string().regex(/^(0|[1-9]\d{0,9})\.\d{2}$/),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
export type ContributionQuery = z.infer<typeof contributionQuerySchema>;
|
||||||
|
|
@ -0,0 +1,67 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { AccessStore } from '../identity/access.store';
|
||||||
|
import type { Principal } from '../identity/identity.types';
|
||||||
|
import { AppError } from '../common/errors/app-error';
|
||||||
|
import { materialContribution } from './contribution-math';
|
||||||
|
import type { ContributionQuery } from './profitability.schemas';
|
||||||
|
@Injectable()
|
||||||
|
export class ProfitabilityStore {
|
||||||
|
constructor(private readonly access: AccessStore) {}
|
||||||
|
batch(actor: Principal, batchId: string, query: ContributionQuery) {
|
||||||
|
return this.access.mutate(
|
||||||
|
actor,
|
||||||
|
'profitability.read',
|
||||||
|
async (tx) => {
|
||||||
|
const snapshot = await tx.batchCostSnapshot.findFirst({
|
||||||
|
where: {
|
||||||
|
batchId,
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
sealedAt: { not: null },
|
||||||
|
batch: { status: 'COMPLETED' },
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
batchId: true,
|
||||||
|
currency: true,
|
||||||
|
goodQuantity: true,
|
||||||
|
productionTotal: true,
|
||||||
|
packagingTotal: true,
|
||||||
|
total: true,
|
||||||
|
sealedAt: true,
|
||||||
|
batch: { select: { bom: { select: { variantId: true } } } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!snapshot) throw new AppError('BATCH_COST_NOT_FOUND');
|
||||||
|
if (snapshot.currency !== query.currency)
|
||||||
|
throw new AppError('PROFITABILITY_CURRENCY');
|
||||||
|
return {
|
||||||
|
batchId,
|
||||||
|
variantId: snapshot.batch.bom.variantId,
|
||||||
|
costSnapshotId: snapshot.id,
|
||||||
|
sealedAt: snapshot.sealedAt,
|
||||||
|
basis: 'SEALED_BATCH_STANDARD_MATERIAL_COST',
|
||||||
|
currency: snapshot.currency,
|
||||||
|
goodQuantity: snapshot.goodQuantity,
|
||||||
|
unitNetPrice: query.unitNetPrice,
|
||||||
|
productionCost: snapshot.productionTotal.toFixed(2),
|
||||||
|
packagingCost: snapshot.packagingTotal.toFixed(2),
|
||||||
|
standardMaterialCost: snapshot.total.toFixed(2),
|
||||||
|
...materialContribution(
|
||||||
|
snapshot.total.toFixed(2),
|
||||||
|
snapshot.goodQuantity,
|
||||||
|
query.unitNetPrice,
|
||||||
|
),
|
||||||
|
excludedCostCategories: [
|
||||||
|
'LABOUR',
|
||||||
|
'OVERHEAD',
|
||||||
|
'FULFILLMENT',
|
||||||
|
'CHANNEL_FEES',
|
||||||
|
'MARKETING',
|
||||||
|
'FINANCE',
|
||||||
|
],
|
||||||
|
};
|
||||||
|
},
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -9,15 +9,27 @@ import { PrismaClient } from '../generated/prisma/client';
|
||||||
import { ENVIRONMENT } from '../config/environment.module';
|
import { ENVIRONMENT } from '../config/environment.module';
|
||||||
import type { Environment } from '../config/environment';
|
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()
|
@Injectable()
|
||||||
export class DatabaseService
|
export class DatabaseService
|
||||||
extends PrismaClient
|
extends PrismaClient
|
||||||
implements OnModuleInit, OnModuleDestroy
|
implements OnModuleInit, OnModuleDestroy
|
||||||
{
|
{
|
||||||
constructor(@Inject(ENVIRONMENT) environment: Environment) {
|
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({
|
super({
|
||||||
adapter: new PrismaPg({
|
adapter: new PrismaPg({
|
||||||
connectionString: environment.DATABASE_URL,
|
connectionString: utcDatabaseUrl(
|
||||||
|
environment.DATABASE_URL,
|
||||||
|
process.env.PGOPTIONS ?? '',
|
||||||
|
),
|
||||||
connectionTimeoutMillis: 3000,
|
connectionTimeoutMillis: 3000,
|
||||||
query_timeout: 3000,
|
query_timeout: 3000,
|
||||||
max: environment.DATABASE_POOL_SIZE,
|
max: environment.DATABASE_POOL_SIZE,
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ export class AuthRateGuard implements CanActivate {
|
||||||
constructor(private readonly limits: RateLimitService) {}
|
constructor(private readonly limits: RateLimitService) {}
|
||||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||||
const request = context.switchToHttp().getRequest<Request>();
|
const request = context.switchToHttp().getRequest<Request>();
|
||||||
// Express proxy trust remains disabled; never trust arbitrary forwarded IP headers.
|
// request.ip honours X-Forwarded-For only from TRUST_PROXY hops; never arbitrary clients.
|
||||||
await this.limits.consume(`auth-ip:${request.ip}`, 30, 60);
|
await this.limits.consume(`auth-ip:${request.ip}`, 30, 60);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ import {
|
||||||
Get,
|
Get,
|
||||||
Header,
|
Header,
|
||||||
HttpCode,
|
HttpCode,
|
||||||
|
Ip,
|
||||||
Post,
|
Post,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
|
|
@ -12,7 +13,12 @@ import { AuthService } from './auth.service';
|
||||||
import { AuthStore } from './auth.store';
|
import { AuthStore } from './auth.store';
|
||||||
import { AuthRateGuard } from './auth-rate.guard';
|
import { AuthRateGuard } from './auth-rate.guard';
|
||||||
import { CurrentPrincipal, Public } from './access.decorator';
|
import { CurrentPrincipal, Public } from './access.decorator';
|
||||||
import { loginSchema, type LoginInput } from './identity.schemas';
|
import {
|
||||||
|
loginSchema,
|
||||||
|
registerSchema,
|
||||||
|
type LoginInput,
|
||||||
|
type RegisterInput,
|
||||||
|
} from './identity.schemas';
|
||||||
import type { Principal } from './identity.types';
|
import type { Principal } from './identity.types';
|
||||||
|
|
||||||
@Controller('auth')
|
@Controller('auth')
|
||||||
|
|
@ -30,6 +36,17 @@ export class AuthController {
|
||||||
return this.auth.login(input);
|
return this.auth.login(input);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@Post('register')
|
||||||
|
@HttpCode(201)
|
||||||
|
@Header('Cache-Control', 'no-store')
|
||||||
|
register(
|
||||||
|
@Body(new SchemaPipe(registerSchema)) input: RegisterInput,
|
||||||
|
@Ip() ip: string,
|
||||||
|
) {
|
||||||
|
return this.auth.register(input, ip);
|
||||||
|
}
|
||||||
|
|
||||||
@Get('me')
|
@Get('me')
|
||||||
@Header('Cache-Control', 'no-store')
|
@Header('Cache-Control', 'no-store')
|
||||||
me(@CurrentPrincipal() principal: Principal) {
|
me(@CurrentPrincipal() principal: Principal) {
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ import { AuthStore } from './auth.store';
|
||||||
import { PasswordService } from './password.service';
|
import { PasswordService } from './password.service';
|
||||||
import { RateLimitService } from './rate-limit.service';
|
import { RateLimitService } from './rate-limit.service';
|
||||||
import { issueToken } from './tokens';
|
import { issueToken } from './tokens';
|
||||||
import type { LoginInput } from './identity.schemas';
|
import type { LoginInput, RegisterInput } from './identity.schemas';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AuthService {
|
export class AuthService {
|
||||||
|
|
@ -36,6 +36,19 @@ export class AuthService {
|
||||||
: 'ACCOUNT_INACTIVE';
|
: 'ACCOUNT_INACTIVE';
|
||||||
throw new AppError('AUTH_INVALID_CREDENTIALS', reason);
|
throw new AppError('AUTH_INVALID_CREDENTIALS', reason);
|
||||||
}
|
}
|
||||||
|
return this.startSession(user);
|
||||||
|
}
|
||||||
|
// Customers get an active account with no roles: cart, checkout, addresses and orders need only a session.
|
||||||
|
async register(input: RegisterInput, ip: string) {
|
||||||
|
await this.limits.consume(`register-ip:${ip}`, 10, 3600);
|
||||||
|
const { password, ...profile } = input;
|
||||||
|
const user = await this.store.createCustomer({
|
||||||
|
...profile,
|
||||||
|
passwordHash: await this.passwords.hash(password),
|
||||||
|
});
|
||||||
|
return this.startSession(user);
|
||||||
|
}
|
||||||
|
private async startSession(user: { id: string; passwordHash: string }) {
|
||||||
const { token, tokenHash } = issueToken();
|
const { token, tokenHash } = issueToken();
|
||||||
const expiresAt = new Date(
|
const expiresAt = new Date(
|
||||||
Date.now() + this.env.SESSION_TTL_MINUTES * 60_000,
|
Date.now() + this.env.SESSION_TTL_MINUTES * 60_000,
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,26 @@ export class AuthStore {
|
||||||
where: { organizationId_email: { organizationId, email } },
|
where: { organizationId_email: { organizationId, email } },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
createCustomer(input: {
|
||||||
|
organizationId: string;
|
||||||
|
email: string;
|
||||||
|
name: string;
|
||||||
|
passwordHash: string;
|
||||||
|
}) {
|
||||||
|
return this.db.$transaction(async (tx) => {
|
||||||
|
const user = await tx.user.create({
|
||||||
|
data: { ...input, status: 'ACTIVE' },
|
||||||
|
});
|
||||||
|
await recordAudit(
|
||||||
|
tx,
|
||||||
|
user.organizationId,
|
||||||
|
user.id,
|
||||||
|
'user.registered',
|
||||||
|
user.id,
|
||||||
|
);
|
||||||
|
return user;
|
||||||
|
});
|
||||||
|
}
|
||||||
async createSession(
|
async createSession(
|
||||||
userId: string,
|
userId: string,
|
||||||
expectedHash: string,
|
expectedHash: string,
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,9 @@ export const loginSchema = z
|
||||||
password: z.string().min(1).max(128),
|
password: z.string().min(1).max(128),
|
||||||
})
|
})
|
||||||
.strict();
|
.strict();
|
||||||
|
export const registerSchema = z
|
||||||
|
.object({ organizationId: z.uuid(), email, name, password })
|
||||||
|
.strict();
|
||||||
export const recoveryRequestSchema = loginSchema.omit({ password: true });
|
export const recoveryRequestSchema = loginSchema.omit({ password: true });
|
||||||
export const recoveryResetSchema = z
|
export const recoveryResetSchema = z
|
||||||
.object({
|
.object({
|
||||||
|
|
@ -49,6 +52,7 @@ export const pageSchema = z
|
||||||
})
|
})
|
||||||
.strict();
|
.strict();
|
||||||
export type LoginInput = z.infer<typeof loginSchema>;
|
export type LoginInput = z.infer<typeof loginSchema>;
|
||||||
|
export type RegisterInput = z.infer<typeof registerSchema>;
|
||||||
export type RecoveryInput = z.infer<typeof recoveryRequestSchema>;
|
export type RecoveryInput = z.infer<typeof recoveryRequestSchema>;
|
||||||
export type CreateUserInput = z.infer<typeof createUserSchema>;
|
export type CreateUserInput = z.infer<typeof createUserSchema>;
|
||||||
export type RoleInput = z.infer<typeof roleSchema>;
|
export type RoleInput = z.infer<typeof roleSchema>;
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,10 @@
|
||||||
export const PERMISSIONS = [
|
export const PERMISSIONS = [
|
||||||
|
'workflows.read',
|
||||||
|
'workflows.run',
|
||||||
|
'profitability.read',
|
||||||
|
'accounting.read',
|
||||||
|
'forecasts.read',
|
||||||
|
'analytics.read',
|
||||||
'forum.read',
|
'forum.read',
|
||||||
'forum.moderate',
|
'forum.moderate',
|
||||||
'segments.read',
|
'segments.read',
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,10 @@ export class RateLimitService {
|
||||||
THEN NOW() + ${seconds} * INTERVAL '1 second' ELSE rate_limits.expires_at END
|
THEN NOW() + ${seconds} * INTERVAL '1 second' ELSE rate_limits.expires_at END
|
||||||
RETURNING hits, expires_at AS "expiresAt"
|
RETURNING hits, expires_at AS "expiresAt"
|
||||||
`;
|
`;
|
||||||
|
// shortcut: ~1% of calls sweep expired windows; move to the scheduler once one runs in production.
|
||||||
|
if (Math.random() < 0.01)
|
||||||
|
await this.db
|
||||||
|
.$executeRaw`DELETE FROM rate_limits WHERE expires_at < NOW() - INTERVAL '1 hour'`;
|
||||||
if (row.hits > limit)
|
if (row.hits > limit)
|
||||||
throw new AppError(
|
throw new AppError(
|
||||||
'RATE_LIMITED',
|
'RATE_LIMITED',
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,104 @@
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { AccessStore } from '../identity/access.store';
|
||||||
|
import type { Principal } from '../identity/identity.types';
|
||||||
|
import type { PageInput } from '../identity/identity.schemas';
|
||||||
|
import { assertReplay, commandHash } from '../common/idempotency';
|
||||||
|
import { AppError } from '../common/errors/app-error';
|
||||||
|
import { recordAudit } from '../identity/audit';
|
||||||
|
import {
|
||||||
|
cancellationInclude,
|
||||||
|
cancelOrderRecord,
|
||||||
|
} from '../checkout/cancel-order';
|
||||||
|
import { lockStock } from '../inventory/stock-lock';
|
||||||
|
import type { ExpiryRunInput } from './workflow.schemas';
|
||||||
|
const runSelect = {
|
||||||
|
id: true,
|
||||||
|
actorId: true,
|
||||||
|
limit: true,
|
||||||
|
asOf: true,
|
||||||
|
completedAt: true,
|
||||||
|
processedOrderIds: true,
|
||||||
|
};
|
||||||
|
const view = <T extends { processedOrderIds: string[] }>(run: T) => ({
|
||||||
|
...run,
|
||||||
|
processedCount: run.processedOrderIds.length,
|
||||||
|
});
|
||||||
|
@Injectable()
|
||||||
|
export class OrderExpiryStore {
|
||||||
|
constructor(private readonly access: AccessStore) {}
|
||||||
|
run(actor: Principal, input: ExpiryRunInput) {
|
||||||
|
const requestHash = commandHash(input.limit);
|
||||||
|
return this.access.mutate(actor, 'workflows.run', async (tx, current) => {
|
||||||
|
if (!current.permissions.includes('orders.manage'))
|
||||||
|
throw new AppError('ACCESS_DENIED');
|
||||||
|
const where = {
|
||||||
|
organizationId_idempotencyKey: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
idempotencyKey: input.idempotencyKey,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const previous = await tx.orderExpiryRun.findUnique({
|
||||||
|
where,
|
||||||
|
select: { ...runSelect, requestHash: true },
|
||||||
|
});
|
||||||
|
if (previous) {
|
||||||
|
const { requestHash: priorHash, ...run } = previous;
|
||||||
|
assertReplay(priorHash, requestHash);
|
||||||
|
return view(run);
|
||||||
|
}
|
||||||
|
const asOf = new Date();
|
||||||
|
const orders = await tx.order.findMany({
|
||||||
|
where: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
status: 'PENDING_PAYMENT',
|
||||||
|
expiresAt: { lte: asOf },
|
||||||
|
},
|
||||||
|
include: cancellationInclude,
|
||||||
|
orderBy: [{ expiresAt: 'asc' }, { id: 'asc' }],
|
||||||
|
take: input.limit,
|
||||||
|
});
|
||||||
|
const stockIds = [
|
||||||
|
...new Set(
|
||||||
|
orders.flatMap((o) => o.reservations.map((r) => r.stockItemId)),
|
||||||
|
),
|
||||||
|
].sort();
|
||||||
|
for (const id of stockIds) await lockStock(tx, actor.organizationId, id);
|
||||||
|
for (const order of orders)
|
||||||
|
await cancelOrderRecord(tx, actor, order, 'order.expired');
|
||||||
|
const run = await tx.orderExpiryRun.create({
|
||||||
|
data: {
|
||||||
|
organizationId: actor.organizationId,
|
||||||
|
actorId: actor.userId,
|
||||||
|
idempotencyKey: input.idempotencyKey,
|
||||||
|
requestHash,
|
||||||
|
limit: input.limit,
|
||||||
|
asOf,
|
||||||
|
completedAt: new Date(),
|
||||||
|
processedOrderIds: orders.map((o) => o.id),
|
||||||
|
},
|
||||||
|
select: runSelect,
|
||||||
|
});
|
||||||
|
await recordAudit(
|
||||||
|
tx,
|
||||||
|
actor.organizationId,
|
||||||
|
actor.userId,
|
||||||
|
'workflow.order_expiry_completed',
|
||||||
|
run.id,
|
||||||
|
);
|
||||||
|
return view(run);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
history(actor: Principal, page: PageInput) {
|
||||||
|
return this.access.mutate(actor, 'workflows.read', async (tx) =>
|
||||||
|
(
|
||||||
|
await tx.orderExpiryRun.findMany({
|
||||||
|
where: { organizationId: actor.organizationId },
|
||||||
|
orderBy: [{ completedAt: 'desc' }, { id: 'desc' }],
|
||||||
|
skip: page.offset,
|
||||||
|
take: page.limit,
|
||||||
|
select: runSelect,
|
||||||
|
})
|
||||||
|
).map(view),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,8 @@
|
||||||
|
import { z } from 'zod';
|
||||||
|
export const expiryRunSchema = z
|
||||||
|
.object({
|
||||||
|
limit: z.number().int().min(1).max(25).default(10),
|
||||||
|
idempotencyKey: z.uuid(),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
export type ExpiryRunInput = z.infer<typeof expiryRunSchema>;
|
||||||
|
|
@ -0,0 +1,30 @@
|
||||||
|
import { Body, Controller, Get, Post, Query } from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
CurrentPrincipal,
|
||||||
|
RequirePermission,
|
||||||
|
} from '../identity/access.decorator';
|
||||||
|
import type { Principal } from '../identity/identity.types';
|
||||||
|
import { pageSchema, type PageInput } from '../identity/identity.schemas';
|
||||||
|
import { SchemaPipe } from '../common/validation.pipe';
|
||||||
|
import { expiryRunSchema, type ExpiryRunInput } from './workflow.schemas';
|
||||||
|
import { OrderExpiryStore } from './order-expiry.store';
|
||||||
|
@Controller('workflows/order-expiry/runs')
|
||||||
|
export class WorkflowsController {
|
||||||
|
constructor(private readonly expiry: OrderExpiryStore) {}
|
||||||
|
@Post()
|
||||||
|
@RequirePermission('workflows.run')
|
||||||
|
run(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Body(new SchemaPipe(expiryRunSchema)) input: ExpiryRunInput,
|
||||||
|
) {
|
||||||
|
return this.expiry.run(actor, input);
|
||||||
|
}
|
||||||
|
@Get()
|
||||||
|
@RequirePermission('workflows.read')
|
||||||
|
history(
|
||||||
|
@CurrentPrincipal() actor: Principal,
|
||||||
|
@Query(new SchemaPipe(pageSchema)) page: PageInput,
|
||||||
|
) {
|
||||||
|
return this.expiry.history(actor, page);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,10 @@
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { IdentityModule } from '../identity/identity.module';
|
||||||
|
import { WorkflowsController } from './workflows.controller';
|
||||||
|
import { OrderExpiryStore } from './order-expiry.store';
|
||||||
|
@Module({
|
||||||
|
imports: [IdentityModule],
|
||||||
|
controllers: [WorkflowsController],
|
||||||
|
providers: [OrderExpiryStore],
|
||||||
|
})
|
||||||
|
export class WorkflowsModule {}
|
||||||
|
|
@ -0,0 +1,56 @@
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { sourceQuerySchema } from '../src/accounting/source.schemas';
|
||||||
|
import {
|
||||||
|
sourceScope,
|
||||||
|
encodeSourceCursor,
|
||||||
|
decodeSourceCursor,
|
||||||
|
} from '../src/accounting/source-cursor';
|
||||||
|
|
||||||
|
it('round-trips validated positions and binds them to scope, window and filters', () => {
|
||||||
|
const query = sourceQuerySchema.parse({
|
||||||
|
from: '2026-01-01T00:00:00Z',
|
||||||
|
to: '2026-01-02T00:00:00Z',
|
||||||
|
});
|
||||||
|
const scope = sourceScope(randomUUID(), query);
|
||||||
|
const row = {
|
||||||
|
occurredAt: query.from,
|
||||||
|
eventType: 'SUPPLIER_INVOICE',
|
||||||
|
sourceId: randomUUID(),
|
||||||
|
};
|
||||||
|
const token = encodeSourceCursor(row, scope);
|
||||||
|
expect(decodeSourceCursor(token, scope, query)).toMatchObject({
|
||||||
|
at: query.from,
|
||||||
|
type: row.eventType,
|
||||||
|
id: row.sourceId,
|
||||||
|
scope,
|
||||||
|
});
|
||||||
|
expect(decodeSourceCursor(undefined, scope, query)).toBeNull();
|
||||||
|
expect(() =>
|
||||||
|
decodeSourceCursor(token, sourceScope(randomUUID(), query), query),
|
||||||
|
).toThrow();
|
||||||
|
expect(() => decodeSourceCursor('not-json', scope, query)).toThrow();
|
||||||
|
expect(() =>
|
||||||
|
decodeSourceCursor(
|
||||||
|
encodeSourceCursor({ ...row, occurredAt: query.to }, scope),
|
||||||
|
scope,
|
||||||
|
query,
|
||||||
|
),
|
||||||
|
).toThrow();
|
||||||
|
const extra = Buffer.from(
|
||||||
|
JSON.stringify({
|
||||||
|
at: query.from,
|
||||||
|
type: row.eventType,
|
||||||
|
id: row.sourceId,
|
||||||
|
scope,
|
||||||
|
organizationId: randomUUID(),
|
||||||
|
}),
|
||||||
|
).toString('base64url');
|
||||||
|
expect(() => decodeSourceCursor(extra, scope, query)).toThrow();
|
||||||
|
expect(
|
||||||
|
sourceQuerySchema.safeParse({
|
||||||
|
from: query.from.toISOString(),
|
||||||
|
to: query.to.toISOString(),
|
||||||
|
kind: 'UNKNOWN',
|
||||||
|
}).success,
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,258 @@
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
||||||
|
import {
|
||||||
|
seedPurchaseOrder,
|
||||||
|
receiveAccepted,
|
||||||
|
seedSupplierInvoice,
|
||||||
|
} from './helpers/procurement';
|
||||||
|
import { seedPartnerOrder } from './helpers/b2b-partner-order';
|
||||||
|
import { secondActor } from './helpers/commerce';
|
||||||
|
|
||||||
|
describe('provider-independent accounting source events', () => {
|
||||||
|
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-12-31T00:00:00Z' };
|
||||||
|
const auth = { type: 'bearer' as const };
|
||||||
|
const feed = (query: object = window, token = ctx.token) =>
|
||||||
|
ctx
|
||||||
|
.api()
|
||||||
|
.get('/api/v1/accounting/source-events')
|
||||||
|
.auth(token, auth)
|
||||||
|
.query(query);
|
||||||
|
async function evidence() {
|
||||||
|
const order = await seedPurchaseOrder(ctx);
|
||||||
|
await receiveAccepted(ctx, order, '1.000');
|
||||||
|
const invoice = await ctx
|
||||||
|
.api()
|
||||||
|
.post('/api/v1/purchase-orders/' + order.id + '/invoices')
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({
|
||||||
|
invoiceNumber: randomUUID(),
|
||||||
|
invoiceDate: '2026-09-28',
|
||||||
|
taxAmount: '18.05',
|
||||||
|
shippingAmount: '1.20',
|
||||||
|
lines: [{ purchaseOrderLineId: order.lineId, quantity: '1.000' }],
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
const payment = await ctx
|
||||||
|
.api()
|
||||||
|
.post('/api/v1/supplier-invoices/' + invoice.body.id + '/payments')
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({
|
||||||
|
reference: randomUUID(),
|
||||||
|
method: 'BANK_TRANSFER',
|
||||||
|
amount: '50.01',
|
||||||
|
paidDate: '2026-09-28',
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post('/api/v1/supplier-payments/' + payment.body.id + '/reverse')
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({ reason: 'Entered in error' })
|
||||||
|
.expect(201);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post('/api/v1/supplier-invoices/' + invoice.body.id + '/void')
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({ reason: 'Invoice superseded' })
|
||||||
|
.expect(201);
|
||||||
|
const partner = await seedPartnerOrder(ctx);
|
||||||
|
const receipt = await ctx
|
||||||
|
.api()
|
||||||
|
.post('/api/v1/b2b/partner-orders/' + partner.order.id + '/payments')
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({
|
||||||
|
reference: randomUUID(),
|
||||||
|
method: 'BANK_TRANSFER',
|
||||||
|
amount: '0.10',
|
||||||
|
receivedOn: '2026-10-03',
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post(
|
||||||
|
'/api/v1/b2b/partner-orders/' +
|
||||||
|
partner.order.id +
|
||||||
|
'/payments/' +
|
||||||
|
receipt.body.id +
|
||||||
|
'/reverse',
|
||||||
|
)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({ reason: 'Entered in error', idempotencyKey: randomUUID() })
|
||||||
|
.expect(201);
|
||||||
|
return {
|
||||||
|
invoice: invoice.body,
|
||||||
|
payment: payment.body,
|
||||||
|
receipt: receipt.body,
|
||||||
|
partner,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
it('retains originals and correction events with exact amounts and source links', async () => {
|
||||||
|
const f = await evidence();
|
||||||
|
const result = await feed().expect(200);
|
||||||
|
expect(result.body.schemaVersion).toBe(1);
|
||||||
|
expect(result.body.events).toHaveLength(6);
|
||||||
|
const by = (type: string) =>
|
||||||
|
result.body.events.find((e: any) => e.eventType === type);
|
||||||
|
expect(by('SUPPLIER_INVOICE')).toMatchObject({
|
||||||
|
sourceId: f.invoice.id,
|
||||||
|
amount: '139.25',
|
||||||
|
merchandiseAmount: '120.00',
|
||||||
|
taxAmount: '18.05',
|
||||||
|
shippingAmount: '1.20',
|
||||||
|
businessDate: '2026-09-28',
|
||||||
|
operation: 'RECORD',
|
||||||
|
});
|
||||||
|
expect(by('SUPPLIER_INVOICE_VOID')).toMatchObject({
|
||||||
|
sourceId: f.invoice.id,
|
||||||
|
amount: '139.25',
|
||||||
|
operation: 'VOID',
|
||||||
|
reversesEventKey: 'SUPPLIER_INVOICE:' + f.invoice.id,
|
||||||
|
});
|
||||||
|
expect(by('SUPPLIER_PAYMENT')).toMatchObject({
|
||||||
|
sourceId: f.payment.id,
|
||||||
|
amount: '50.01',
|
||||||
|
relatedId: f.invoice.id,
|
||||||
|
operation: 'RECORD',
|
||||||
|
});
|
||||||
|
expect(by('SUPPLIER_PAYMENT_REVERSAL')).toMatchObject({
|
||||||
|
sourceId: f.payment.id,
|
||||||
|
amount: '50.01',
|
||||||
|
operation: 'REVERSE',
|
||||||
|
reversesEventKey: 'SUPPLIER_PAYMENT:' + f.payment.id,
|
||||||
|
});
|
||||||
|
expect(by('PARTNER_RECEIPT')).toMatchObject({
|
||||||
|
sourceId: f.receipt.id,
|
||||||
|
amount: '0.10',
|
||||||
|
counterpartyId: f.partner.accountId,
|
||||||
|
relatedId: f.partner.order.id,
|
||||||
|
});
|
||||||
|
expect(by('PARTNER_RECEIPT_REVERSAL')).toMatchObject({
|
||||||
|
sourceId: f.receipt.id,
|
||||||
|
amount: '0.10',
|
||||||
|
reversesEventKey: 'PARTNER_RECEIPT:' + f.receipt.id,
|
||||||
|
});
|
||||||
|
expect(new Set(result.body.events.map((e: any) => e.eventKey)).size).toBe(
|
||||||
|
6,
|
||||||
|
);
|
||||||
|
expect(JSON.stringify(result.body)).not.toMatch(
|
||||||
|
/contactEmail|contactPhone|reference|reason|requestHash|idempotencyKey|invoiceNumber|recordedById/,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
(await feed({ ...window, currency: 'USD' }).expect(200)).body.events,
|
||||||
|
).toEqual([]);
|
||||||
|
});
|
||||||
|
it('pages without duplicate keys and rejects reuse with changed window or filters', async () => {
|
||||||
|
await evidence();
|
||||||
|
const initial = await feed({ ...window, limit: 1 }).expect(200);
|
||||||
|
expect(initial.body.nextCursor).toEqual(expect.any(String));
|
||||||
|
const keys = [initial.body.events[0].eventKey];
|
||||||
|
let cursor = initial.body.nextCursor;
|
||||||
|
for (let i = 0; cursor && i < 20; i++) {
|
||||||
|
const page = await feed({ ...window, limit: 1, cursor }).expect(200);
|
||||||
|
keys.push(...page.body.events.map((e: any) => e.eventKey));
|
||||||
|
cursor = page.body.nextCursor;
|
||||||
|
}
|
||||||
|
expect(cursor).toBeNull();
|
||||||
|
expect(new Set(keys).size).toBe(keys.length);
|
||||||
|
expect(keys.length).toBeGreaterThanOrEqual(6);
|
||||||
|
await feed({
|
||||||
|
...window,
|
||||||
|
cursor: initial.body.nextCursor,
|
||||||
|
currency: 'INR',
|
||||||
|
}).expect(400);
|
||||||
|
await feed({
|
||||||
|
...window,
|
||||||
|
cursor: initial.body.nextCursor,
|
||||||
|
to: '2026-12-30T00:00:00Z',
|
||||||
|
}).expect(400);
|
||||||
|
await feed({ ...window, cursor: 'not-json' }).expect(400);
|
||||||
|
});
|
||||||
|
it('bounds recorded timestamps independently of business dates and preserves scoped permissions', async () => {
|
||||||
|
const f = await evidence();
|
||||||
|
const event = await ctx.db.supplierInvoice.findUniqueOrThrow({
|
||||||
|
where: { id: f.invoice.id },
|
||||||
|
});
|
||||||
|
const from = event.createdAt.toISOString();
|
||||||
|
const to = new Date(event.createdAt.getTime() + 1).toISOString();
|
||||||
|
const result = await feed({ from, to, kind: 'SUPPLIER_INVOICE' }).expect(
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
expect(result.body.events).toHaveLength(1);
|
||||||
|
expect(result.body.events[0].businessDate).toBe('2026-09-28');
|
||||||
|
const customer = await secondActor(ctx);
|
||||||
|
await feed(window, customer.token).expect(403);
|
||||||
|
const foreign = await secondActor(ctx, false, ['accounting.read']);
|
||||||
|
expect((await feed(window, foreign.token).expect(200)).body.events).toEqual(
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
const accountant = await secondActor(ctx, true, ['accounting.read']);
|
||||||
|
await feed(window, accountant.token).expect(200);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.get('/api/v1/accounting/source-events')
|
||||||
|
.query(window)
|
||||||
|
.expect(401);
|
||||||
|
for (const query of [
|
||||||
|
{ ...window, limit: 101 },
|
||||||
|
{ ...window, kind: 'PAID_RETAIL_SALE' },
|
||||||
|
{ ...window, organizationId: foreign.organizationId },
|
||||||
|
{ ...window, to: '2028-01-01T00:00:00Z' },
|
||||||
|
{ ...window, offset: 1 },
|
||||||
|
])
|
||||||
|
await feed(query).expect(400);
|
||||||
|
});
|
||||||
|
it('uses source IDs to traverse events sharing a recorded timestamp', async () => {
|
||||||
|
const { invoice } = await seedSupplierInvoice(ctx);
|
||||||
|
const recordedAt = new Date();
|
||||||
|
const payments = await ctx.db.$transaction(async (tx) => {
|
||||||
|
const rows = [];
|
||||||
|
for (const amount of ['25.01', '25.02'])
|
||||||
|
rows.push(
|
||||||
|
await tx.supplierPayment.create({
|
||||||
|
data: {
|
||||||
|
organizationId: ctx.owner.organizationId,
|
||||||
|
invoiceId: invoice.id,
|
||||||
|
createdById: ctx.owner.userId,
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
requestHash: 'a'.repeat(64),
|
||||||
|
reference: randomUUID().toUpperCase(),
|
||||||
|
method: 'BANK_TRANSFER',
|
||||||
|
currency: 'INR',
|
||||||
|
createdAt: recordedAt,
|
||||||
|
amount,
|
||||||
|
paidAt: new Date('2026-09-28T00:00:00Z'),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return rows;
|
||||||
|
});
|
||||||
|
expect(payments[0].createdAt).toEqual(payments[1].createdAt);
|
||||||
|
const query = {
|
||||||
|
from: payments[0].createdAt.toISOString(),
|
||||||
|
to: new Date(payments[0].createdAt.getTime() + 1).toISOString(),
|
||||||
|
kind: 'SUPPLIER_PAYMENT',
|
||||||
|
limit: 1,
|
||||||
|
};
|
||||||
|
const first = await feed(query).expect(200);
|
||||||
|
const next = await feed({ ...query, cursor: first.body.nextCursor }).expect(
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
expect([
|
||||||
|
first.body.events[0].sourceId,
|
||||||
|
next.body.events[0].sourceId,
|
||||||
|
]).toEqual(payments.map((p) => p.id).sort());
|
||||||
|
expect(next.body.nextCursor).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -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);
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,164 @@
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
||||||
|
import { secondActor } from './helpers/commerce';
|
||||||
|
import {
|
||||||
|
prepareCostBatch,
|
||||||
|
startCostBatch,
|
||||||
|
recordCostUsage,
|
||||||
|
completeCostBatch,
|
||||||
|
packageCostBatch,
|
||||||
|
setCostRate,
|
||||||
|
} from './helpers/batch-cost';
|
||||||
|
|
||||||
|
describe('indicative batch material contribution', () => {
|
||||||
|
let ctx: IdentityApp;
|
||||||
|
beforeAll(async () => {
|
||||||
|
ctx = await identityApp();
|
||||||
|
});
|
||||||
|
afterAll(async () => {
|
||||||
|
await ctx.close();
|
||||||
|
});
|
||||||
|
beforeEach(async () => {
|
||||||
|
await ctx.clearLimits();
|
||||||
|
});
|
||||||
|
const report = (
|
||||||
|
id: string,
|
||||||
|
unitNetPrice = '5.00',
|
||||||
|
currency = 'INR',
|
||||||
|
token = ctx.token,
|
||||||
|
) =>
|
||||||
|
ctx
|
||||||
|
.api()
|
||||||
|
.get('/api/v1/profitability/batches/' + id)
|
||||||
|
.auth(token, { type: 'bearer' })
|
||||||
|
.query({ unitNetPrice, currency });
|
||||||
|
async function ready(good = 20) {
|
||||||
|
const batch = await prepareCostBatch(ctx);
|
||||||
|
await startCostBatch(ctx, batch.batchId);
|
||||||
|
await recordCostUsage(
|
||||||
|
ctx,
|
||||||
|
batch.batchId,
|
||||||
|
batch.productionLineId,
|
||||||
|
'CONSUMED',
|
||||||
|
'200.000',
|
||||||
|
);
|
||||||
|
await recordCostUsage(
|
||||||
|
ctx,
|
||||||
|
batch.batchId,
|
||||||
|
batch.productionLineId,
|
||||||
|
'WASTED',
|
||||||
|
'10.000',
|
||||||
|
);
|
||||||
|
await completeCostBatch(ctx, batch.batchId, good);
|
||||||
|
if (good)
|
||||||
|
await packageCostBatch(
|
||||||
|
ctx,
|
||||||
|
batch.batchId,
|
||||||
|
batch.packagingBomId,
|
||||||
|
batch.packagingLineId,
|
||||||
|
);
|
||||||
|
await setCostRate(ctx, batch.productionMaterialId, '0.1000');
|
||||||
|
await setCostRate(ctx, batch.packagingMaterialId, '2.0000');
|
||||||
|
const snapshot = await ctx
|
||||||
|
.api()
|
||||||
|
.post('/api/v1/production-batches/' + batch.batchId + '/cost-snapshot')
|
||||||
|
.auth(ctx.token, { type: 'bearer' })
|
||||||
|
.send({ currency: 'INR', idempotencyKey: randomUUID() })
|
||||||
|
.expect(201);
|
||||||
|
return { ...batch, snapshot: snapshot.body };
|
||||||
|
}
|
||||||
|
it('compares an explicit price with sealed costs and preserves frozen rates', async () => {
|
||||||
|
const f = await ready();
|
||||||
|
const result = await report(f.batchId).expect(200);
|
||||||
|
expect(result.body).toMatchObject({
|
||||||
|
batchId: f.batchId,
|
||||||
|
variantId: f.variantId,
|
||||||
|
costSnapshotId: f.snapshot.id,
|
||||||
|
basis: 'SEALED_BATCH_STANDARD_MATERIAL_COST',
|
||||||
|
currency: 'INR',
|
||||||
|
goodQuantity: 20,
|
||||||
|
unitNetPrice: '5.00',
|
||||||
|
productionCost: '21.00',
|
||||||
|
packagingCost: '40.00',
|
||||||
|
standardMaterialCost: '61.00',
|
||||||
|
comparisonNetValue: '100.00',
|
||||||
|
materialContribution: '39.00',
|
||||||
|
contributionRateBps: '3900',
|
||||||
|
breakEvenUnitNetPrice: '3.05',
|
||||||
|
comparisonState: 'ABOVE_MATERIAL_BREAK_EVEN',
|
||||||
|
});
|
||||||
|
expect(JSON.stringify(result.body)).not.toMatch(
|
||||||
|
/createdById|idempotencyKey|requestHash|revenue|netProfit/,
|
||||||
|
);
|
||||||
|
await setCostRate(ctx, f.productionMaterialId, '9.0000');
|
||||||
|
await ctx.db.productVariant.update({
|
||||||
|
where: { id: f.variantId },
|
||||||
|
data: { price: '999.00' },
|
||||||
|
});
|
||||||
|
const after = await report(f.batchId).expect(200);
|
||||||
|
expect(after.body.standardMaterialCost).toBe('61.00');
|
||||||
|
expect(after.body.materialContribution).toBe('39.00');
|
||||||
|
expect((await report(f.batchId, '1.00').expect(200)).body).toMatchObject({
|
||||||
|
comparisonNetValue: '20.00',
|
||||||
|
materialContribution: '-41.00',
|
||||||
|
contributionRateBps: '-20500',
|
||||||
|
comparisonState: 'BELOW_MATERIAL_BREAK_EVEN',
|
||||||
|
});
|
||||||
|
expect((await report(f.batchId, '3.05').expect(200)).body).toMatchObject({
|
||||||
|
materialContribution: '0.00',
|
||||||
|
contributionRateBps: '0',
|
||||||
|
comparisonState: 'AT_MATERIAL_BREAK_EVEN',
|
||||||
|
});
|
||||||
|
expect((await report(f.batchId, '0.00').expect(200)).body).toMatchObject({
|
||||||
|
materialContribution: '-61.00',
|
||||||
|
contributionRateBps: null,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it('reports zero good output without dividing by zero', async () => {
|
||||||
|
const f = await ready(0);
|
||||||
|
const result = await report(f.batchId).expect(200);
|
||||||
|
expect(result.body).toMatchObject({
|
||||||
|
goodQuantity: 0,
|
||||||
|
comparisonNetValue: '0.00',
|
||||||
|
standardMaterialCost: '21.00',
|
||||||
|
materialContribution: '-21.00',
|
||||||
|
breakEvenUnitNetPrice: null,
|
||||||
|
contributionRateBps: null,
|
||||||
|
comparisonState: 'NO_GOOD_OUTPUT',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it('requires sealed evidence, matching currency and scoped profitability permission', async () => {
|
||||||
|
const f = await prepareCostBatch(ctx);
|
||||||
|
await report(f.batchId).expect(404);
|
||||||
|
await report(randomUUID()).expect(404);
|
||||||
|
const readyBatch = await ready();
|
||||||
|
expect(
|
||||||
|
(await report(readyBatch.batchId, '5.00', 'USD').expect(409)).body.code,
|
||||||
|
).toBe('PROFITABILITY_CURRENCY');
|
||||||
|
const reader = await secondActor(ctx, true, ['profitability.read']);
|
||||||
|
await report(readyBatch.batchId, '5.00', 'INR', reader.token).expect(200);
|
||||||
|
const costReader = await secondActor(ctx, true, ['cost.read']);
|
||||||
|
await report(readyBatch.batchId, '5.00', 'INR', costReader.token).expect(
|
||||||
|
403,
|
||||||
|
);
|
||||||
|
const foreign = await secondActor(ctx, false, ['profitability.read']);
|
||||||
|
await report(readyBatch.batchId, '5.00', 'INR', foreign.token).expect(404);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.get('/api/v1/profitability/batches/' + readyBatch.batchId)
|
||||||
|
.query({ currency: 'INR', unitNetPrice: '5.00' })
|
||||||
|
.expect(401);
|
||||||
|
for (const price of ['-1.00', '1.001', '1', '10000000000.00', 'NaN'])
|
||||||
|
await report(readyBatch.batchId, price).expect(400);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.get('/api/v1/profitability/batches/' + readyBatch.batchId)
|
||||||
|
.auth(ctx.token, { type: 'bearer' })
|
||||||
|
.query({
|
||||||
|
currency: 'INR',
|
||||||
|
unitNetPrice: '5.00',
|
||||||
|
organizationId: foreign.organizationId,
|
||||||
|
})
|
||||||
|
.expect(400);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,42 @@
|
||||||
|
import { materialContribution } from '../src/costing/contribution-math';
|
||||||
|
import { contributionQuerySchema } from '../src/costing/profitability.schemas';
|
||||||
|
|
||||||
|
it('uses exact signed money, ceiling break-even and zero-denominator handling', () => {
|
||||||
|
expect(materialContribution('0.19', 2, '0.09')).toMatchObject({
|
||||||
|
materialContribution: '-0.01',
|
||||||
|
breakEvenUnitNetPrice: '0.10',
|
||||||
|
contributionRateBps: '-556',
|
||||||
|
});
|
||||||
|
expect(materialContribution('0.19', 2, '0.10')).toMatchObject({
|
||||||
|
materialContribution: '0.01',
|
||||||
|
contributionRateBps: '500',
|
||||||
|
});
|
||||||
|
expect(materialContribution('61.00', 20, '0.00')).toMatchObject({
|
||||||
|
comparisonNetValue: '0.00',
|
||||||
|
materialContribution: '-61.00',
|
||||||
|
contributionRateBps: null,
|
||||||
|
});
|
||||||
|
expect(materialContribution('21.00', 0, '5.00')).toMatchObject({
|
||||||
|
comparisonState: 'NO_GOOD_OUTPUT',
|
||||||
|
breakEvenUnitNetPrice: null,
|
||||||
|
contributionRateBps: null,
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
materialContribution('0.01', 1000000, '9999999999.99').comparisonNetValue,
|
||||||
|
).toBe('9999999999990000.00');
|
||||||
|
expect(() => materialContribution('1.00', -1, '1.00')).toThrow();
|
||||||
|
expect(() => materialContribution('1.00', 1.5, '1.00')).toThrow();
|
||||||
|
});
|
||||||
|
it('validates supported currencies and explicit bounded net-price strings', () => {
|
||||||
|
expect(
|
||||||
|
contributionQuerySchema.safeParse({ currency: 'INR', unitNetPrice: '0.00' })
|
||||||
|
.success,
|
||||||
|
).toBe(true);
|
||||||
|
for (const price of ['-1.00', '1', '01.00', '0.001', '10000000000.00'])
|
||||||
|
expect(
|
||||||
|
contributionQuerySchema.safeParse({
|
||||||
|
currency: 'INR',
|
||||||
|
unitNetPrice: price,
|
||||||
|
}).success,
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,95 @@
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
||||||
|
|
||||||
|
describe('customer self-registration', () => {
|
||||||
|
let ctx: IdentityApp;
|
||||||
|
const customer = {
|
||||||
|
email: 'Buyer@Example.com',
|
||||||
|
name: 'Asha Buyer',
|
||||||
|
password: 'a long enough customer password',
|
||||||
|
};
|
||||||
|
const register = (body: object) =>
|
||||||
|
ctx.api().post('/api/v1/auth/register').send(body);
|
||||||
|
beforeAll(async () => {
|
||||||
|
ctx = await identityApp();
|
||||||
|
}, 60000);
|
||||||
|
afterAll(async () => {
|
||||||
|
await ctx?.close();
|
||||||
|
});
|
||||||
|
beforeEach(async () => {
|
||||||
|
await ctx.clearLimits();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates an active role-less customer with a working session', async () => {
|
||||||
|
const response = await register({
|
||||||
|
organizationId: ctx.owner.organizationId,
|
||||||
|
...customer,
|
||||||
|
}).expect(201);
|
||||||
|
expect(response.body).toMatchObject({ tokenType: 'Bearer' });
|
||||||
|
expect(JSON.stringify(response.body)).not.toContain(customer.password);
|
||||||
|
const me = await ctx
|
||||||
|
.api()
|
||||||
|
.get('/api/v1/auth/me')
|
||||||
|
.auth(response.body.accessToken, { type: 'bearer' })
|
||||||
|
.expect(200);
|
||||||
|
expect(me.body.permissions).toEqual([]);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.get('/api/v1/cart')
|
||||||
|
.auth(response.body.accessToken, { type: 'bearer' })
|
||||||
|
.expect(200);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.get('/api/v1/users')
|
||||||
|
.auth(response.body.accessToken, { type: 'bearer' })
|
||||||
|
.expect(403);
|
||||||
|
const user = await ctx.db.user.findFirstOrThrow({
|
||||||
|
where: { email: 'buyer@example.com' },
|
||||||
|
include: { roles: true },
|
||||||
|
});
|
||||||
|
expect(user).toMatchObject({ status: 'ACTIVE', isOwner: false, roles: [] });
|
||||||
|
expect(
|
||||||
|
await ctx.db.auditEvent.count({
|
||||||
|
where: { action: 'user.registered', targetId: user.id },
|
||||||
|
}),
|
||||||
|
).toBe(1);
|
||||||
|
expect(
|
||||||
|
(await ctx.login('buyer@example.com', customer.password)).status,
|
||||||
|
).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects duplicates, weak passwords, unknown organizations and extra fields', async () => {
|
||||||
|
const organizationId = ctx.owner.organizationId;
|
||||||
|
await register({ organizationId, ...customer, email: 'dup@example.com' });
|
||||||
|
await register({
|
||||||
|
organizationId,
|
||||||
|
...customer,
|
||||||
|
email: 'DUP@example.com',
|
||||||
|
}).expect(409);
|
||||||
|
await register({ organizationId, ...customer, password: 'short' }).expect(
|
||||||
|
400,
|
||||||
|
);
|
||||||
|
await register({ ...customer, organizationId: randomUUID() }).expect(
|
||||||
|
(response) => expect(response.status).toBeGreaterThanOrEqual(400),
|
||||||
|
);
|
||||||
|
await register({ organizationId, ...customer, isOwner: true }).expect(400);
|
||||||
|
expect(
|
||||||
|
await ctx.db.user.count({ where: { email: 'dup@example.com' } }),
|
||||||
|
).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('limits registrations per client address', async () => {
|
||||||
|
const organizationId = ctx.owner.organizationId;
|
||||||
|
for (let index = 0; index < 10; index++)
|
||||||
|
await register({
|
||||||
|
organizationId,
|
||||||
|
...customer,
|
||||||
|
email: `bulk${index}@example.com`,
|
||||||
|
}).expect(201);
|
||||||
|
await register({
|
||||||
|
organizationId,
|
||||||
|
...customer,
|
||||||
|
email: 'bulk-over@example.com',
|
||||||
|
}).expect(429);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -1,8 +1,40 @@
|
||||||
import 'reflect-metadata';
|
import 'reflect-metadata';
|
||||||
import { DatabaseService } from '../src/database/database.service';
|
import {
|
||||||
|
DatabaseService,
|
||||||
|
utcDatabaseUrl,
|
||||||
|
} from '../src/database/database.service';
|
||||||
import { parseEnvironment } from '../src/config/environment';
|
import { parseEnvironment } from '../src/config/environment';
|
||||||
|
|
||||||
describe('database lifecycle', () => {
|
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;
|
let database: DatabaseService;
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
database = new DatabaseService(
|
database = new DatabaseService(
|
||||||
|
|
|
||||||
|
|
@ -27,12 +27,28 @@ describe('environment configuration', () => {
|
||||||
{ NODE_ENV: 'staging' },
|
{ NODE_ENV: 'staging' },
|
||||||
{ CORS_ORIGINS: '*' },
|
{ CORS_ORIGINS: '*' },
|
||||||
{ CORS_ORIGINS: 'https://shop.example.com/path' },
|
{ CORS_ORIGINS: 'https://shop.example.com/path' },
|
||||||
|
{ TRUST_PROXY: 'true' },
|
||||||
|
{ TRUST_PROXY: '*' },
|
||||||
|
{ TRUST_PROXY: '2' },
|
||||||
|
{ TRUST_PROXY: '10.0.0.0/33' },
|
||||||
|
{ TRUST_PROXY: '10.0.0.1/8/1' },
|
||||||
|
{ TRUST_PROXY: 'proxy.example.com' },
|
||||||
])('rejects invalid configuration %j', (override) => {
|
])('rejects invalid configuration %j', (override) => {
|
||||||
expect(() => parseEnvironment({ ...valid, ...override })).toThrow(
|
expect(() => parseEnvironment({ ...valid, ...override })).toThrow(
|
||||||
'Invalid environment',
|
'Invalid environment',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('parses trusted proxy addresses, subnets and named ranges', () => {
|
||||||
|
expect(parseEnvironment(valid).TRUST_PROXY).toEqual([]);
|
||||||
|
expect(
|
||||||
|
parseEnvironment({
|
||||||
|
...valid,
|
||||||
|
TRUST_PROXY: ' loopback, 172.17.0.0/16 ,203.0.113.7,::1/128',
|
||||||
|
}).TRUST_PROXY,
|
||||||
|
).toEqual(['loopback', '172.17.0.0/16', '203.0.113.7', '::1/128']);
|
||||||
|
});
|
||||||
|
|
||||||
it('does not leak credentials in validation errors', () => {
|
it('does not leak credentials in validation errors', () => {
|
||||||
expect(() => parseEnvironment({ DATABASE_URL: 'secret-password' })).toThrow(
|
expect(() => parseEnvironment({ DATABASE_URL: 'secret-password' })).toThrow(
|
||||||
'DATABASE_URL',
|
'DATABASE_URL',
|
||||||
|
|
|
||||||
|
|
@ -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);
|
||||||
|
});
|
||||||
|
|
@ -31,6 +31,8 @@ export async function testDatabase() {
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
const pg = await PGlite.create();
|
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({
|
const server = new PGLiteSocketServer({
|
||||||
db: pg,
|
db: pg,
|
||||||
port: 0,
|
port: 0,
|
||||||
|
|
|
||||||
|
|
@ -90,6 +90,23 @@ describe('identity transactional failure paths', () => {
|
||||||
});
|
});
|
||||||
await expect(limits.consume('test-bucket', 1, 60)).resolves.toBeUndefined();
|
await expect(limits.consume('test-bucket', 1, 60)).resolves.toBeUndefined();
|
||||||
});
|
});
|
||||||
|
it('sweeps long-expired rate-limit windows', async () => {
|
||||||
|
const limits = ctx.app.get(RateLimitService);
|
||||||
|
await ctx.db.rateLimit.create({
|
||||||
|
data: { key: hashToken('stale-bucket'), hits: 1, expiresAt: new Date(0) },
|
||||||
|
});
|
||||||
|
const random = jest.spyOn(Math, 'random').mockReturnValue(0);
|
||||||
|
try {
|
||||||
|
await limits.consume('sweep-trigger', 100, 60);
|
||||||
|
} finally {
|
||||||
|
random.mockRestore();
|
||||||
|
}
|
||||||
|
expect(
|
||||||
|
await ctx.db.rateLimit.findUnique({
|
||||||
|
where: { key: hashToken('stale-bucket') },
|
||||||
|
}),
|
||||||
|
).toBeNull();
|
||||||
|
});
|
||||||
it('rechecks current permissions inside administration transactions', async () => {
|
it('rechecks current permissions inside administration transactions', async () => {
|
||||||
const actor = await ctx.app.get(SessionStore).authenticate(ctx.token);
|
const actor = await ctx.app.get(SessionStore).authenticate(ctx.token);
|
||||||
const ownerRole = await ctx.db.role.findFirstOrThrow({
|
const ownerRole = await ctx.db.role.findFirstOrThrow({
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,223 @@
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
||||||
|
import { checkoutFixture } from './helpers/checkout';
|
||||||
|
import { secondActor } from './helpers/commerce';
|
||||||
|
|
||||||
|
describe('bounded auditable order expiry workflow', () => {
|
||||||
|
let ctx: IdentityApp;
|
||||||
|
beforeAll(async () => {
|
||||||
|
ctx = await identityApp();
|
||||||
|
});
|
||||||
|
afterAll(async () => {
|
||||||
|
await ctx.close();
|
||||||
|
});
|
||||||
|
beforeEach(async () => {
|
||||||
|
await ctx.clearLimits();
|
||||||
|
});
|
||||||
|
const run = (body: object, token = ctx.token) =>
|
||||||
|
ctx
|
||||||
|
.api()
|
||||||
|
.post('/api/v1/workflows/order-expiry/runs')
|
||||||
|
.auth(token, { type: 'bearer' })
|
||||||
|
.send(body);
|
||||||
|
async function expired() {
|
||||||
|
const f = await checkoutFixture(ctx);
|
||||||
|
const createdAt = new Date(Date.now() - 3600000);
|
||||||
|
const expiresAt = new Date(createdAt.getTime() + 900000);
|
||||||
|
const order = await ctx.db.order.create({
|
||||||
|
data: {
|
||||||
|
userId: f.actor.userId,
|
||||||
|
organizationId: f.actor.organizationId,
|
||||||
|
currency: 'INR',
|
||||||
|
subtotal: '998.00',
|
||||||
|
discount: '0.00',
|
||||||
|
merchandiseTotal: '998.00',
|
||||||
|
addressSnapshot: { recipient: 'Private recipient' },
|
||||||
|
createdAt,
|
||||||
|
expiresAt,
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
requestHash: 'a'.repeat(64),
|
||||||
|
lines: {
|
||||||
|
create: [
|
||||||
|
{
|
||||||
|
variantId: f.variant.id,
|
||||||
|
sku: f.variant.sku,
|
||||||
|
productName: f.product.name,
|
||||||
|
variantName: f.variant.name,
|
||||||
|
quantity: 2,
|
||||||
|
unitPrice: '499.00',
|
||||||
|
lineTotal: '998.00',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const reservation = await ctx.db.stockReservation.create({
|
||||||
|
data: {
|
||||||
|
stockItemId: f.stock.id,
|
||||||
|
organizationId: f.actor.organizationId,
|
||||||
|
userId: f.actor.userId,
|
||||||
|
orderId: order.id,
|
||||||
|
quantity: 2,
|
||||||
|
expiresAt,
|
||||||
|
idempotencyKey: randomUUID(),
|
||||||
|
requestHash: 'b'.repeat(64),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return { ...f, order, reservation };
|
||||||
|
}
|
||||||
|
it('expires only eligible orders, releases holds, preserves stock and replays a run once', async () => {
|
||||||
|
const f = await expired();
|
||||||
|
const active = await ctx
|
||||||
|
.api()
|
||||||
|
.post('/api/v1/checkout')
|
||||||
|
.auth(f.actor.token, { type: 'bearer' })
|
||||||
|
.send(f.input)
|
||||||
|
.expect(201);
|
||||||
|
const input = { limit: 1, idempotencyKey: randomUUID() };
|
||||||
|
const result = await run(input).expect(201);
|
||||||
|
expect(result.body).toMatchObject({
|
||||||
|
processedCount: 1,
|
||||||
|
processedOrderIds: [f.order.id],
|
||||||
|
limit: 1,
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
(await ctx.db.order.findUniqueOrThrow({ where: { id: f.order.id } }))
|
||||||
|
.status,
|
||||||
|
).toBe('CANCELLED');
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx.db.stockReservation.findUniqueOrThrow({
|
||||||
|
where: { id: f.reservation.id },
|
||||||
|
})
|
||||||
|
).status,
|
||||||
|
).toBe('RELEASED');
|
||||||
|
expect(
|
||||||
|
(await ctx.db.stockItem.findUniqueOrThrow({ where: { id: f.stock.id } }))
|
||||||
|
.onHand,
|
||||||
|
).toBe(10);
|
||||||
|
expect(
|
||||||
|
(await ctx.db.order.findUniqueOrThrow({ where: { id: active.body.id } }))
|
||||||
|
.status,
|
||||||
|
).toBe('PENDING_PAYMENT');
|
||||||
|
expect((await run(input).expect(201)).body).toEqual(result.body);
|
||||||
|
expect((await run({ ...input, limit: 2 }).expect(409)).body.code).toBe(
|
||||||
|
'IDEMPOTENCY_CONFLICT',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
await ctx.db.commerceEvent.count({
|
||||||
|
where: { orderId: f.order.id, kind: 'order.cancelled' },
|
||||||
|
}),
|
||||||
|
).toBe(1);
|
||||||
|
expect(
|
||||||
|
await ctx.db.auditEvent.count({
|
||||||
|
where: { targetId: f.order.id, action: 'order.expired' },
|
||||||
|
}),
|
||||||
|
).toBe(1);
|
||||||
|
expect(
|
||||||
|
(await run({ limit: 1, idempotencyKey: randomUUID() }).expect(201)).body
|
||||||
|
.processedCount,
|
||||||
|
).toBe(0);
|
||||||
|
expect(JSON.stringify(result.body)).not.toMatch(
|
||||||
|
/address|recipient|token|requestHash|idempotencyKey/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
it('bounds batches, serializes competing sweeps and preserves immutable history', async () => {
|
||||||
|
const a = await expired();
|
||||||
|
const b = await expired();
|
||||||
|
const results = await Promise.all([
|
||||||
|
run({ limit: 1, idempotencyKey: randomUUID() }),
|
||||||
|
run({ limit: 1, idempotencyKey: randomUUID() }),
|
||||||
|
]);
|
||||||
|
expect(results.map((r) => r.status)).toEqual([201, 201]);
|
||||||
|
expect(new Set(results.flatMap((r) => r.body.processedOrderIds))).toEqual(
|
||||||
|
new Set([a.order.id, b.order.id]),
|
||||||
|
);
|
||||||
|
const history = await ctx
|
||||||
|
.api()
|
||||||
|
.get('/api/v1/workflows/order-expiry/runs')
|
||||||
|
.auth(ctx.token, { type: 'bearer' })
|
||||||
|
.query({ limit: 2 })
|
||||||
|
.expect(200);
|
||||||
|
expect(history.body).toHaveLength(2);
|
||||||
|
await expect(
|
||||||
|
ctx.executeSql(
|
||||||
|
`DELETE FROM order_expiry_runs WHERE id = '${results[0].body.id}'`,
|
||||||
|
),
|
||||||
|
).rejects.toThrow(/immutable/);
|
||||||
|
});
|
||||||
|
it('requires both workflow and order-management permissions and scopes runs', async () => {
|
||||||
|
const f = await expired();
|
||||||
|
const operator = await secondActor(ctx, true, ['workflows.run']);
|
||||||
|
await run({ idempotencyKey: randomUUID() }, operator.token).expect(403);
|
||||||
|
const orderManager = await secondActor(ctx, true, ['orders.manage']);
|
||||||
|
await run({ idempotencyKey: randomUUID() }, orderManager.token).expect(403);
|
||||||
|
const foreign = await secondActor(ctx, false, [
|
||||||
|
'workflows.run',
|
||||||
|
'orders.manage',
|
||||||
|
'workflows.read',
|
||||||
|
]);
|
||||||
|
expect(
|
||||||
|
(await run({ idempotencyKey: randomUUID() }, foreign.token).expect(201))
|
||||||
|
.body.processedCount,
|
||||||
|
).toBe(0);
|
||||||
|
expect(
|
||||||
|
(await ctx.db.order.findUniqueOrThrow({ where: { id: f.order.id } }))
|
||||||
|
.status,
|
||||||
|
).toBe('PENDING_PAYMENT');
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.get('/api/v1/workflows/order-expiry/runs')
|
||||||
|
.auth(operator.token, { type: 'bearer' })
|
||||||
|
.expect(403);
|
||||||
|
for (const body of [
|
||||||
|
{ idempotencyKey: randomUUID(), limit: 26 },
|
||||||
|
{ idempotencyKey: randomUUID(), limit: 0 },
|
||||||
|
{ idempotencyKey: randomUUID(), organizationId: foreign.organizationId },
|
||||||
|
])
|
||||||
|
await run(body).expect(400);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.post('/api/v1/workflows/order-expiry/runs')
|
||||||
|
.send({ idempotencyKey: randomUUID() })
|
||||||
|
.expect(401);
|
||||||
|
await ctx.db.user.update({
|
||||||
|
where: { id: foreign.userId },
|
||||||
|
data: { status: 'SUSPENDED' },
|
||||||
|
});
|
||||||
|
await run({ idempotencyKey: randomUUID() }, foreign.token).expect(401);
|
||||||
|
});
|
||||||
|
it('rolls back cancellations, releases and outbox events if run persistence fails', async () => {
|
||||||
|
const f = await expired();
|
||||||
|
await ctx.executeSql(`CREATE FUNCTION fail_expiry_run_test() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'Injected run persistence failure'; END; $$;
|
||||||
|
CREATE TRIGGER fail_expiry_run_test BEFORE INSERT ON order_expiry_runs FOR EACH ROW EXECUTE FUNCTION fail_expiry_run_test();`);
|
||||||
|
try {
|
||||||
|
await run({ limit: 25, idempotencyKey: randomUUID() }).expect(500);
|
||||||
|
} finally {
|
||||||
|
await ctx.executeSql(
|
||||||
|
'DROP TRIGGER fail_expiry_run_test ON order_expiry_runs; DROP FUNCTION fail_expiry_run_test();',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
expect(
|
||||||
|
(await ctx.db.order.findUniqueOrThrow({ where: { id: f.order.id } }))
|
||||||
|
.status,
|
||||||
|
).toBe('PENDING_PAYMENT');
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await ctx.db.stockReservation.findUniqueOrThrow({
|
||||||
|
where: { id: f.reservation.id },
|
||||||
|
})
|
||||||
|
).status,
|
||||||
|
).toBe('ACTIVE');
|
||||||
|
expect(
|
||||||
|
await ctx.db.commerceEvent.count({
|
||||||
|
where: { orderId: f.order.id, kind: 'order.cancelled' },
|
||||||
|
}),
|
||||||
|
).toBe(0);
|
||||||
|
expect(
|
||||||
|
await ctx.db.auditEvent.count({
|
||||||
|
where: { targetId: f.order.id, action: 'order.expired' },
|
||||||
|
}),
|
||||||
|
).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,132 @@
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
||||||
|
import { secondActor, seedProduct } from './helpers/commerce';
|
||||||
|
|
||||||
|
const png = Buffer.concat([
|
||||||
|
Buffer.from('89504e470d0a1a0a', 'hex'),
|
||||||
|
Buffer.from('fake image body'),
|
||||||
|
]);
|
||||||
|
const webp = Buffer.concat([
|
||||||
|
Buffer.from('RIFF'),
|
||||||
|
Buffer.alloc(4),
|
||||||
|
Buffer.from('WEBPVP8 body'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
describe('product images', () => {
|
||||||
|
let ctx: IdentityApp;
|
||||||
|
const auth = { type: 'bearer' as const };
|
||||||
|
const upload = (
|
||||||
|
productId: string,
|
||||||
|
bytes = png,
|
||||||
|
contentType = 'image/png',
|
||||||
|
token = ctx.token,
|
||||||
|
) =>
|
||||||
|
ctx
|
||||||
|
.api()
|
||||||
|
.post(`/api/v1/products/${productId}/images`)
|
||||||
|
.auth(token, auth)
|
||||||
|
.attach('file', bytes, { filename: 'photo', contentType });
|
||||||
|
const storefront = (path: string) =>
|
||||||
|
ctx
|
||||||
|
.api()
|
||||||
|
.get(`/api/v1/storefront/${ctx.owner.organizationId}/products${path}`);
|
||||||
|
beforeAll(async () => {
|
||||||
|
ctx = await identityApp();
|
||||||
|
}, 60000);
|
||||||
|
afterAll(async () => {
|
||||||
|
await ctx?.close();
|
||||||
|
});
|
||||||
|
beforeEach(async () => {
|
||||||
|
await ctx.clearLimits();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stores images and serves them publicly only for published products', async () => {
|
||||||
|
const { product } = await seedProduct(ctx);
|
||||||
|
const first = await upload(product.id).expect(201);
|
||||||
|
expect(first.body).toMatchObject({
|
||||||
|
mimeType: 'image/png',
|
||||||
|
size: png.length,
|
||||||
|
});
|
||||||
|
expect(first.body).not.toHaveProperty('content');
|
||||||
|
await upload(product.id, webp, 'image/webp').expect(201);
|
||||||
|
const path = `/${product.id}/images/${first.body.id}`;
|
||||||
|
await storefront(path).expect(404);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.patch(`/api/v1/products/${product.id}/status`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.send({ status: 'PUBLISHED' })
|
||||||
|
.expect(200);
|
||||||
|
const served = await storefront(path)
|
||||||
|
.buffer(true)
|
||||||
|
.parse((response, done) => {
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
response.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||||
|
response.on('end', () => done(null, Buffer.concat(chunks)));
|
||||||
|
})
|
||||||
|
.expect(200);
|
||||||
|
expect(served.headers['content-type']).toBe('image/png');
|
||||||
|
expect(served.headers['cache-control']).toContain('public');
|
||||||
|
expect(Buffer.compare(served.body as Buffer, png)).toBe(0);
|
||||||
|
const detail = await storefront(`/${product.id}`).expect(200);
|
||||||
|
expect(detail.body.images).toHaveLength(2);
|
||||||
|
expect(detail.body.images[0]).toEqual({ id: first.body.id });
|
||||||
|
const list = await storefront('?limit=100').expect(200);
|
||||||
|
expect(
|
||||||
|
list.body.find((item: { id: string }) => item.id === product.id).images,
|
||||||
|
).toEqual([{ id: first.body.id }]);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.get(`/api/v1/storefront/${randomUUID()}/products${path}`)
|
||||||
|
.expect(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects disguised, oversized and over-quota uploads', async () => {
|
||||||
|
const { product } = await seedProduct(ctx);
|
||||||
|
for (const [bytes, type] of [
|
||||||
|
[Buffer.from('<svg onload=alert(1)>'), 'image/png'],
|
||||||
|
[png, 'image/jpeg'],
|
||||||
|
[Buffer.from('<svg/>'), 'image/svg+xml'],
|
||||||
|
] as const)
|
||||||
|
expect(
|
||||||
|
(await upload(product.id, bytes, type).expect(400)).body.code,
|
||||||
|
).toBe('PRODUCT_IMAGE_INVALID');
|
||||||
|
const big = Buffer.concat([png, Buffer.alloc(2 * 1024 * 1024)]);
|
||||||
|
expect((await upload(product.id, big)).status).toBeGreaterThanOrEqual(400);
|
||||||
|
for (let index = 0; index < 8; index++)
|
||||||
|
await upload(product.id).expect(201);
|
||||||
|
expect((await upload(product.id).expect(409)).body.code).toBe(
|
||||||
|
'PRODUCT_IMAGE_LIMIT',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires catalog.manage and organization scope to add or remove', async () => {
|
||||||
|
const { product } = await seedProduct(ctx);
|
||||||
|
const image = await upload(product.id).expect(201);
|
||||||
|
const customer = await secondActor(ctx);
|
||||||
|
await upload(product.id, png, 'image/png', customer.token).expect(403);
|
||||||
|
const foreign = await secondActor(ctx, false, ['catalog.manage']);
|
||||||
|
await upload(product.id, png, 'image/png', foreign.token).expect(404);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.delete(`/api/v1/products/${product.id}/images/${image.body.id}`)
|
||||||
|
.auth(foreign.token, auth)
|
||||||
|
.expect(404);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.delete(`/api/v1/products/${product.id}/images/${image.body.id}`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.expect(204);
|
||||||
|
await ctx
|
||||||
|
.api()
|
||||||
|
.delete(`/api/v1/products/${product.id}/images/${image.body.id}`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.expect(404);
|
||||||
|
const admin = await ctx
|
||||||
|
.api()
|
||||||
|
.get(`/api/v1/products/${product.id}`)
|
||||||
|
.auth(ctx.token, auth)
|
||||||
|
.expect(200);
|
||||||
|
expect(admin.body.images).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,58 @@
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import { Controller, Get, Module, Req } from '@nestjs/common';
|
||||||
|
import { Test } from '@nestjs/testing';
|
||||||
|
import type { INestApplication } from '@nestjs/common';
|
||||||
|
import type { Request } from 'express';
|
||||||
|
import request from 'supertest';
|
||||||
|
import { configureApp } from '../src/configure-app';
|
||||||
|
import { parseEnvironment } from '../src/config/environment';
|
||||||
|
|
||||||
|
@Controller('ip')
|
||||||
|
class IpController {
|
||||||
|
@Get()
|
||||||
|
ip(@Req() req: Request) {
|
||||||
|
return { ip: req.ip };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ controllers: [IpController] })
|
||||||
|
class IpModule {}
|
||||||
|
|
||||||
|
async function appWith(TRUST_PROXY?: string): Promise<INestApplication> {
|
||||||
|
const module = await Test.createTestingModule({
|
||||||
|
imports: [IpModule],
|
||||||
|
}).compile();
|
||||||
|
const app = module.createNestApplication();
|
||||||
|
configureApp(
|
||||||
|
app,
|
||||||
|
parseEnvironment({
|
||||||
|
DATABASE_URL: 'postgresql://localhost/mani',
|
||||||
|
TRUST_PROXY,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await app.init();
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
const ipOf = async (app: INestApplication, forwarded: string) =>
|
||||||
|
(
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get('/api/v1/ip')
|
||||||
|
.set('X-Forwarded-For', forwarded)
|
||||||
|
.expect(200)
|
||||||
|
).body.ip as string;
|
||||||
|
|
||||||
|
describe('client IP behind reverse proxies', () => {
|
||||||
|
it('ignores forwarded headers when no proxy is trusted', async () => {
|
||||||
|
const app = await appWith();
|
||||||
|
expect(await ipOf(app, '198.51.100.4')).not.toBe('198.51.100.4');
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses the forwarded client address from trusted hops only', async () => {
|
||||||
|
// supertest connects over loopback, standing in for the local Nginx.
|
||||||
|
const app = await appWith('loopback,203.0.113.7');
|
||||||
|
expect(await ipOf(app, '198.51.100.4, 203.0.113.7')).toBe('198.51.100.4');
|
||||||
|
// A client that skips the trusted frontend proxy cannot spoof an address.
|
||||||
|
expect(await ipOf(app, '198.51.100.4, 192.0.2.66')).toBe('192.0.2.66');
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,69 @@
|
||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import type { INestApplicationContext } from '@nestjs/common';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { SessionStore } from '../src/identity/session.store';
|
||||||
|
import { runExpiryCommand } from '../src/cli/workflow-expiry';
|
||||||
|
|
||||||
|
describe('authenticated expiry command', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
jest.restoreAllMocks();
|
||||||
|
});
|
||||||
|
function fixture(fail = false) {
|
||||||
|
const actor = {
|
||||||
|
userId: randomUUID(),
|
||||||
|
organizationId: randomUUID(),
|
||||||
|
sessionId: randomUUID(),
|
||||||
|
permissions: ['workflows.run', 'orders.manage'],
|
||||||
|
};
|
||||||
|
const authenticate = jest.fn().mockResolvedValue(actor);
|
||||||
|
const run = fail
|
||||||
|
? jest.fn().mockRejectedValue(new Error('Failure'))
|
||||||
|
: jest.fn().mockResolvedValue({ id: 'run-id', processedCount: 0 });
|
||||||
|
const close = jest.fn().mockResolvedValue(undefined);
|
||||||
|
const app = {
|
||||||
|
get: (type: unknown) =>
|
||||||
|
type === SessionStore ? { authenticate } : { run },
|
||||||
|
close,
|
||||||
|
} as unknown as INestApplicationContext;
|
||||||
|
const create = jest
|
||||||
|
.spyOn(NestFactory, 'createApplicationContext')
|
||||||
|
.mockResolvedValue(app);
|
||||||
|
return { actor, authenticate, run, close, create };
|
||||||
|
}
|
||||||
|
it('authenticates and runs with a stable supplied key, then closes resources', async () => {
|
||||||
|
const f = fixture();
|
||||||
|
const key = randomUUID();
|
||||||
|
const token = 'a'.repeat(43);
|
||||||
|
expect(
|
||||||
|
await runExpiryCommand({
|
||||||
|
WORKFLOW_TOKEN: token,
|
||||||
|
WORKFLOW_LIMIT: '5',
|
||||||
|
WORKFLOW_RUN_KEY: key,
|
||||||
|
}),
|
||||||
|
).toMatchObject({ processedCount: 0 });
|
||||||
|
expect(f.authenticate).toHaveBeenCalledWith(token);
|
||||||
|
expect(f.run).toHaveBeenCalledWith(f.actor, {
|
||||||
|
limit: 5,
|
||||||
|
idempotencyKey: key,
|
||||||
|
});
|
||||||
|
expect(f.close).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
it('closes resources after a failed workflow', async () => {
|
||||||
|
const f = fixture(true);
|
||||||
|
await expect(
|
||||||
|
runExpiryCommand({ WORKFLOW_TOKEN: 'a'.repeat(43) }),
|
||||||
|
).rejects.toThrow('Failure');
|
||||||
|
expect(f.close).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
it('rejects missing credentials and oversized limits before application startup', async () => {
|
||||||
|
const f = fixture();
|
||||||
|
await expect(runExpiryCommand({})).rejects.toThrow();
|
||||||
|
await expect(
|
||||||
|
runExpiryCommand({
|
||||||
|
WORKFLOW_TOKEN: 'a'.repeat(43),
|
||||||
|
WORKFLOW_LIMIT: '26',
|
||||||
|
}),
|
||||||
|
).rejects.toThrow();
|
||||||
|
expect(f.create).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue